问:
Populating table with textbox value from previous HTML page
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

```<code><div class="selecttier">
  <h1>5. Number of Clicks</h1>
  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
</code>```

JS on page 1:

```<code>$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });
</code>```

JS on page 2:

```<code>// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("<tr></tr>");
            let recordName = $("<td></td>").text(data_from_page_1[i].name);
            let recordValue = $("<td></td>").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();
</code>```

Output HTML table (page 2):

```<code><table id="output_table">
        <tr>
            <th>Name</th>
            <th>Value</th>
            <th>Number of Clicks</th>
        </tr>
        <tfoot>
            <tr>
                <th id="total" colspan="1">Total CPC:</th>
                <td id="sum1"></td>
            </tr>
    </tfoot>
    </table>
</code>```

答:
ANSWER:

What would be the best way to approach this?

window.localStorage - stores data with no expiration date

window.sessionStorage - stores data for one session

Body:
I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.

This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?

I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).

Here's what I have so far:

HTML for textbox (page 1):

5. Number of Clicks

  <input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />

JS on page 1:

$('#sales_order_form_button').click(function() {
        let table_info = [];
        $('input[type=checkbox]').each(
            function(index, value) {
            if($(this).is(':checked')) {
                table_info.push(
                    {
                        name: $(this).attr('name'),
                        value: $(this).attr('value'),
                    }
                );
            }
        });
        let base64str=btoa(JSON.stringify(table_info));

        window.location = "page2.html?table_data=" + base64str;
        });

JS on page 2:

// Helper function
        function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.href);
            return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, '    '));
        };

        // actual code
        let table_data = getUrlParameter('table_data');
        let data_from_page_1 = JSON.parse(atob(table_data));

        for(let i = 0; i < data_from_page_1.length; i++){
            let row = $("

");
            let recordName = $("	").text(data_from_page_1[i].name);
            let recordValue = $("	").text(data_from_page_1[i].value);
            row.append(recordName, recordValue);
            $('#output_table').append(row);
        }

        // code to sum CPC column
        var sum1 = 0;

        $("#output_table tr > td:nth-child(2)").each(
        (_,el) => sum1 += Number($(el).text()) || 0
        );

        $("#sum1").text(sum1);

        //datetime stamp
        var dt = new Date();
        document.getElementById("datetime").innerHTML = dt.toLocaleString();

Output HTML table (page 2):

            Name
            Value
            Number of Clicks

                Total CPC:


来源: stackexchange

问:
How to use etags for caching?
Can anyone tell me how to pass etag correctly for this url?

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,id&playlistId=UUwpy_3CqtfwM7tg2JgQQQyA&maxResults=50&key={API_KEY}.

I was passing like this, but didn't work.

https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,id&playlistId=UUwpy_3CqtfwM7tg2JgQQQyA&maxResults=50&key={API_KEY}&If-None-Match="p4VTdlkQv3HQeTEaXgvLePAydmU/vKZr9jiSytaO7UdTbhKbIrwbX20"

答: If-None-Match is request header, and not query param. Need set this header in headers of request. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

ContentLicense: CC BY-SA 4.0

Title: How to use etags for caching?


问:
Howto use external plugins via config file (runtime configuration) with Unity Container 5
I'm trying to setup a simple .NET Core 3.1 project that uses Unity Container 5 (https://github.com/unitycontainer/unity).

I've added a reference to latest Unity Configuration 5.11.1 package (https://www.nuget.org/packages/Unity.Configuration/).

Then I've created interface, implementation and test app with a simpliest config file:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration" />
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <container>
      <register
        type="Interfaces.InterfaceN, Interfaces"
        mapTo="Implementations.ImplementationN, Implementations">
      </register>
    </container>
  </unity>
</configuration>
</code>```

But i'm getting System.InvalidOperationException:

{"The type name or alias Implementations.ImplementationN,
  Implementations could not be resolved. Please check your configuration
  file and verify this type name."}

I've uploaded my code to GitHub. Any help is appreciated.

P.S. Visual Studio 2019 16.4.4 Enterprise, Windows 10 1909 x64 Professional

P.P.S. Same code compiled for .NET Framework 4.8 works fine - GitHub

UPDATE: To clarify more - I need an upproach without ANY project referencing Implementations.dll, I should be able to change specific implementation (via changing config.json) without recompilation.

答:
I've found out this more a ".NET Core assembly loading" problem than an IoC container problem.

To cut a long story short, if the assembly isn't specifically referenced by your app, you need to tell .NET Core assembly loader where to get it EVEN IF IT'S IN YOUR BIN FOLDER.

So if you (like me) don't want to have a bootstrap library that references all implementation libraries that you need but you want to have runtime configuration via config file - you should do the following.

From Autofac IoC examples repository:

```<code>// THIS IS THE MAGIC!
// .NET Core assembly loading is confusing. Things that happen to be in your bin folder don't just suddenly
// qualify with the assembly loader. If the assembly isn't specifically referenced by your app, you need to
// tell .NET Core where to get it EVEN IF IT'S IN YOUR BIN FOLDER.
// https://stackoverflow.com/questions/43918837/net-core-1-1-type-gettype-from-external-assembly-returns-null
//
// The documentation says that any .dll in the application base folder should work, but that doesn't seem
// to be entirely true. You always have to set up additional handlers if you AREN'T referencing the plugin assembly.
// https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/corehost.md
//
// To verify, try commenting this out and you'll see that the config system can't load the external plugin type.
var executionFolder = Path.GetDirectoryName(typeof(Program).Assembly.Location);
AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext context, AssemblyName assembly) =>
{
     // DISCLAIMER: NO PROMISES THIS IS SECURE. You may or may not want this strategy. It's up to
     // you to determine if allowing any assembly in the directory to be loaded is acceptable. This
     // is for demo purposes only.
     return context.LoadFromAssemblyPath(Path.Combine(executionFolder, $"{assembly.Name}.dll"));
 };
</code>```

And after that the following code

```<code>var container = new UnityContainer().LoadConfiguration();

var type = container.Resolve<InterfaceN>();
</code>```

is working like a charm.

P.S. Some more info from Microsoft

Body:
I'm trying to setup a simple .NET Core 3.1 project that uses Unity Container 5 (https://github.com/unitycontainer/unity).

I've added a reference to latest Unity Configuration 5.11.1 package (https://www.nuget.org/packages/Unity.Configuration/).

Then I've created interface, implementation and test app with a simpliest config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <container>
      <register
        type="Interfaces.InterfaceN, Interfaces"
        mapTo="Implementations.ImplementationN, Implementations">
      </register>
    </container>
  </unity>
</configuration>

But i'm getting System.InvalidOperationException:

{"The type name or alias Implementations.ImplementationN,
  Implementations could not be resolved. Please check your configuration
  file and verify this type name."}

I've uploaded my code to GitHub. Any help is appreciated.

P.S. Visual Studio 2019 16.4.4 Enterprise, Windows 10 1909 x64 Professional

P.P.S. Same code compiled for .NET Framework 4.8 works fine - GitHub

UPDATE: To clarify more - I need an upproach without ANY project referencing Implementations.dll, I should be able to change specific implementation (via changing config.json) without recompilation.

Body:
I've found out this more a ".NET Core assembly loading" problem than an IoC container problem.

To cut a long story short, if the assembly isn't specifically referenced by your app, you need to tell .NET Core assembly loader where to get it EVEN IF IT'S IN YOUR BIN FOLDER.

So if you (like me) don't want to have a bootstrap library that references all implementation libraries that you need but you want to have runtime configuration via config file - you should do the following.

From Autofac IoC examples repository:

// THIS IS THE MAGIC!
// .NET Core assembly loading is confusing. Things that happen to be in your bin folder don't just suddenly
// qualify with the assembly loader. If the assembly isn't specifically referenced by your app, you need to
// tell .NET Core where to get it EVEN IF IT'S IN YOUR BIN FOLDER.
// https://stackoverflow.com/questions/43918837/net-core-1-1-type-gettype-from-external-assembly-returns-null
//
// The documentation says that any .dll in the application base folder should work, but that doesn't seem
// to be entirely true. You always have to set up additional handlers if you AREN'T referencing the plugin assembly.
// https://github.com/dotnet/core-setup/blob/master/Documentation/design-docs/corehost.md
//
// To verify, try commenting this out and you'll see that the config system can't load the external plugin type.
var executionFolder = Path.GetDirectoryName(typeof(Program).Assembly.Location);
AssemblyLoadContext.Default.Resolving += (AssemblyLoadContext context, AssemblyName assembly) =>
{
     // DISCLAIMER: NO PROMISES THIS IS SECURE. You may or may not want this strategy. It's up to
     // you to determine if allowing any assembly in the directory to be loaded is acceptable. This
     // is for demo purposes only.
     return context.LoadFromAssemblyPath(Path.Combine(executionFolder, $"{assembly.Name}.dll"));
 };

And after that the following code

var container = new UnityContainer().LoadConfiguration();

var type = container.Resolve<InterfaceN>();

is working like a charm.

P.S. Some more info from Microsoft


问:
Approach for associated model searching with Elasticsearch [Ruby, ActiveRecord, elasticsearch-model]
I have a question about choosing the best approach in case of searching in Elasticsearch.

I have Ruby off Rails API, with ActiveRecord, together with Elasticsearch ( elasticsearch-model gem).

It's a simple API which returns projects (Project AR model), where I set up indexes:

```<code>mapping dynamic: false do
indexes :created_at, type: 'date'
end
</code>```

Then I simply make a search on Elasticsearch and return AR relations directly from the controller. It's working perfectly.

Now I am trying to add categories to projects, as categories has_many projects, and projects belongs_to categories. I am wondering about two things:

How now should I make a query to get projects from specific categories, should I reimplement it to return result = Category.search(...) and return result.jobs, or still seeking by projects, but searching by category_id?

How to combine Category and Project in Elasticsearch to make possible to search for projects from a specific category, and from various multiple categories? Merge mappings?

Thanks in advance!

答:
// mapping (nested categories)

```<code> mapping dynamic: false do
  indexes :created_at, type: 'date'
  indexes :categories, type: 'nested' do
    indexes :name, type: :text, analyzer: :english
  end
 end
</code>```

// json

```<code>  def as_indexed_json(_options = nil)
  {
   created_at: created_at,
   # in case project belong_to category
   # categories: [category.name, Category::DEFAULT].map do ...
   categories: categories.map do |category|
     {
       name: category.name
     }
   end
  }
 end
</code>```

// search function(elasticsearch DSL) as you want to search projects by categories

```<code>def by_categories(categories)
  filters = []
  categories.each { |category|
    filters.push term: {"categories.name":category.name}
  }
  Project.__elasticsearch__.search(
     query: {
        nested: {
           path: "categories",
           query: {
              bool: {
                 filter:{
                    bool:{
                        should:filters
                    }
                  }
               }
            }
        }
     }
  )
end
</code>```

Body:
I have a question about choosing the best approach in case of searching in Elasticsearch.

I have Ruby off Rails API, with ActiveRecord, together with Elasticsearch ( elasticsearch-model gem).

It's a simple API which returns projects (Project AR model), where I set up indexes:

mapping dynamic: false do
indexes :created_at, type: 'date'
end

Then I simply make a search on Elasticsearch and return AR relations directly from the controller. It's working perfectly.

Now I am trying to add categories to projects, as categories has_many projects, and projects belongs_to categories. I am wondering about two things:

How now should I make a query to get projects from specific categories, should I reimplement it to return result = Category.search(...) and return result.jobs, or still seeking by projects, but searching by category_id?

How to combine Category and Project in Elasticsearch to make possible to search for projects from a specific category, and from various multiple categories? Merge mappings?

Thanks in advance!

Body:
// mapping (nested categories)

 mapping dynamic: false do
  indexes :created_at, type: 'date'
  indexes :categories, type: 'nested' do
    indexes :name, type: :text, analyzer: :english
  end
 end

// json

  def as_indexed_json(_options = nil)
  {
   created_at: created_at,
   # in case project belong_to category
   # categories: [category.name, Category::DEFAULT].map do ...
   categories: categories.map do |category|
     {
       name: category.name
     }
   end
  }
 end

// search function(elasticsearch DSL) as you want to search projects by categories

def by_categories(categories)
  filters = []
  categories.each { |category|
    filters.push term: {"categories.name":category.name}
  }
  Project.__elasticsearch__.search(
     query: {
        nested: {
           path: "categories",
           query: {
              bool: {
                 filter:{
                    bool:{
                        should:filters
                    }
                  }
               }
            }
        }
     }
  )
end


问:
Can you use both styles and styleUrls in an Angular component?
In my Angular 2 component, I'm using styleUrls to import a common stylesheet, but dont want to create a whole new stylesheet for a single rule that I want to add specific to this component.

Can I also define styles? So in my component I'm declaring both styles and styleUrls but it doesn't appear to work.

Just wanted to verify if this is possible or not.

答:
Although this was not supported on earlier versions, starting from Angular 9 it is possible:

You can specify more than one styles file or even a combination of
  styles and styleUrls.

Here's a link to the latest doc (if you look at older versions docs that remark is omitted).

ContentLicense: CC BY-SA 3.0


问:
How to detect changes in MSSQL table in java?
Is there a way to detect changes in MSSQL table in Java. If new record insert into specific table want to detect in Java. Searched in Goolge can't get any solution most of results are like schedule the Job or runnable thread to detect the changes.
Is any specific way to detect the changes in Java. Suggest the Best way to detect the changes.

答:
just some ideas

a trigger, from database

a code to check before you save,update,delete and then dispatch some event

maybe can use a listener, interceptor, auditing(jpa/hibernate), Observer Pattern(not sure)


问:
how to change class of a element multiple times in VueJS
Function in vanilla js, which I want to implement in Vue.js

example: https://codesandbox.io/s/xjk3xqnprw
This is what I want to implement in Vue js

Below is my vue component, it is loading perfectly but it is not having animation

My Vue component:

```<code><template>
    <div class="container">
        <div class="row justify-content-center">

            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">Dice Game <h5 class="blink" style="color: red">* live</h5></div>
                    <div class="card-body" style="background-color: #3f0d12;background-image: linear-gradient(315deg, #3f0d12 0%, #a71d31 74%);
">
                        <div class="dice">
                            <ol class="die-list even-roll" data-roll="1" id="die-1">
                                <li class="die-item" data-side="1">
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="2">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="3">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="4">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="5">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="6">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                            </ol>
                            <ol class="die-list odd-roll" data-roll="1" id="die-2">
                                <li class="die-item" data-side="1">
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="2">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="3">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="4">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="5">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                                <li class="die-item" data-side="6">
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                    <span class="dot"></span>
                                </li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "Home",
        methods: {
            rollDice() {
                const array1= [5,6];
                const dice = [...document.querySelectorAll(".die-list")];
                console.log(dice);
                let count = 0;
                dice.forEach(die => {
                    toggleClasses(die);
                    die.dataset.roll = array1[count];
                    count++
                });
            },
            toggleClasses(die) {
                die.classList.toggle("odd-roll");
                die.classList.toggle("even-roll");
            },
            getRandomNumber(min, max) {
                min = Math.ceil(min);
                max = Math.floor(max);
                return Math.floor(Math.random() * (max - min + 1)) + min;
            },
        },
        beforeMount() {
            this.rollDice();
        },
    }
</script>

<style scoped>

</style>
</code>```

I want the toggle style class(in a loop) so that the animation of dice roll can be achieved

Thanks for the help in advance

答:
You are now toggling your rollDice function beforeMount, if you change this to created the changes will be toggled correctly, also note that you will need to change toggleClasses to this.toggleClasses since it is defined in the methods section of your component and is therefore bound to the component and not a global function anymore.

I hope this helps you!

P.S. See my codepen for a working sample, note that I used a settimeout here for demo purposes, but you can adjust this to a @click="rollDice" on a button within your component and leave out the mounted alltogether

Body:
Function in vanilla js, which I want to implement in Vue.js

example: https://codesandbox.io/s/xjk3xqnprw
This is what I want to implement in Vue js

Below is my vue component, it is loading perfectly but it is not having animation

My Vue component:

<template>

Dice Game
* live

</template>

I want the toggle style class(in a loop) so that the animation of dice roll can be achieved

Thanks for the help in advance


问:
How to check which user logged into ADFS
I want to know which user is logged in currently into the ADFS.
I am using Claims Provider for ADFS and through that, I am logging into ADFS. Now I want to see in ADFS that this particular user is currently logged in. Basically I want to see the user details of logged in user in ADFS</p>

答:
There is no as such session monitoring console on ADFS, instead there are events generated for every successfull authentication that contains claims.
Also, if you want to check the entire header based interaction, please enable security logs.
Also, enabling security logs is not recommended for production environment as it creates enormously large count of events for every authentication request ADFS receives.</p>


问:
R-value references and std::make_unique
Say I have an initialised object Foo_obj of a class Foo and wish to create a unique smart pointer to a copy of this object. The code auto pointer = make_unique<Foo>(Foo_obj) executes and does exactly this. However when looking at the reference for std::make_unique, this only accepts R-value references as arguments and calls the constructor of the respective class with these arguments.

My understanding is that an object such as Foo_obj is an l-value and thus the above code should not compile. What am I missing?

答:
When you have something like template <typename T> void foo (T&& rt) {...} something called reference collapsing happens and that's what Meyers calls "A universal reference". In a nutshell, if you pass an rvalue, this becomes an rvalue reference, if you pass an lvalue, this becomes an lvalue reference. This way, the function perfectly forwards all the parameters to the constructor of the unique_ptr.

Learn more about the universal references in this blog post by the man himself.

Title: R-value references and std::make_unique


问:
aws batch: get overview over past submitted jobs
Is there an easy way to list past jobs for a certain queue, ideally on the console?

I lack a view in the web console where I see the past jobs regardless of status

答:
the aws cli also offers to only view one status at a time. Looping over the relevant statuses and making the output pretty using jq results in this kind of script:

```<code>for STATUS in RUNNABLE STARTING RUNNING SUCCEEDED FAILED; do
  echo $STATUS;
  aws batch list-jobs --job-queue cheap-lane --job-status $STATUS |
    jq -r 'def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
           .jobSummaryList[] | [(.createdAt / 1000 | strftime("%Y-%m-%d %H:%M")), (.jobName[:25] | lpad(25;" ")), .jobId]|@tsv' |
    sort -r
done
</code>```

The ouptut of the command above is something like:

```<code>RUNNABLE
STARTING
RUNNING
SUCCEEDED
2020-02-19 11:00                   tutti-loremips       0fc36af9[…]f22
2020-02-19 08:00                   tutti-loremips       7628d413[…]306
2020-02-19 07:38               tutti-loremips-cli       a2c40a72[…]b4a
2020-02-19 05:17        megajob-lister-id-asdfghi       eb5bd15e[…]d5f
2020-02-19 04:14                check-harker-test       b30d0c54[…]c47
2020-02-18 15:22               tutti-loremips-cli       a27b0742[…]096
2020-02-18 14:06               tutti-loremips-cli       86e6a89c[…]eb7
2020-02-18 07:01           tutti-loremips-manual3       8c81afe3[…]2ec
2020-02-18 05:17        megajob-lister-id-asdfghi       1a55d717[…]fbd
FAILED
2020-02-19 07:35               tutti-loremips-cli       76291571[…]5f8
2020-02-19 07:30               tutti-loremips-cli       83563bb6[…]fb3
2020-02-19 07:28               tutti-loremips-cli       dc35b9bb[…]05c
2020-02-18 06:30        tutti-loremips-manual-sub       955a1d0b[…]685
</code>```

btw: there's currently a PR open for jq which would make lpad available in jq natively.

Body:
the aws cli also offers to only view one status at a time. Looping over the relevant statuses and making the output pretty using jq results in this kind of script:

for STATUS in RUNNABLE STARTING RUNNING SUCCEEDED FAILED; do
  echo $STATUS;
  aws batch list-jobs --job-queue cheap-lane --job-status $STATUS |
    jq -r 'def lpad($len; $fill): tostring | ($len - length) as $l | ($fill * $l)[:$l] + .;
           .jobSummaryList[] | [(.createdAt / 1000 | strftime("%Y-%m-%d %H:%M")), (.jobName[:25] | lpad(25;" ")), .jobId]|@tsv' |
    sort -r
done

The ouptut of the command above is something like:

RUNNABLE
STARTING
RUNNING
SUCCEEDED
2020-02-19 11:00                   tutti-loremips       0fc36af9[…]f22
2020-02-19 08:00                   tutti-loremips       7628d413[…]306
2020-02-19 07:38               tutti-loremips-cli       a2c40a72[…]b4a
2020-02-19 05:17        megajob-lister-id-asdfghi       eb5bd15e[…]d5f
2020-02-19 04:14                check-harker-test       b30d0c54[…]c47
2020-02-18 15:22               tutti-loremips-cli       a27b0742[…]096
2020-02-18 14:06               tutti-loremips-cli       86e6a89c[…]eb7
2020-02-18 07:01           tutti-loremips-manual3       8c81afe3[…]2ec
2020-02-18 05:17        megajob-lister-id-asdfghi       1a55d717[…]fbd
FAILED
2020-02-19 07:35               tutti-loremips-cli       76291571[…]5f8
2020-02-19 07:30               tutti-loremips-cli       83563bb6[…]fb3
2020-02-19 07:28               tutti-loremips-cli       dc35b9bb[…]05c
2020-02-18 06:30        tutti-loremips-manual-sub       955a1d0b[…]685

btw: there's currently a PR open for jq which would make lpad available in jq natively.


问:
fbprophet library error while installing: name 'HolidayBase' is not defined
When I tried to install the fbprophet library for Python, I faced the following error:

name 'HolidayBase' is not defined

and it took me a while to get the solution. That's why I'm answering my own question, in case it helps someone.

答:
The solution I found is to downgrade my Python version from 3.7.3 to 3.6.7.

I did not do an extensive analysis on to which other versions work - maybe all 3.6 do.


问:
Adding values with condition in google bigquery
I need to add some values with a condition in GoogleBigQuery

NOTICE: I edited the original question since  it was not accurate enough.

Thanks to the two participants who have tried to help me.
I tried to apply the solutions  kindly suggested by you but I got the same result from the pct column as a result.

Something like this:
results

Here is the more detailed definition:

TABLE

Columns:

Shop: Shop location

brand: Brands of cars sold at shoplocation

sales: sales of each brand sold at each shop_location
rank: Rank of each brand per shop location (the biggest the greater)

total_sales_shop: SUM of all brand sales per shop location

pct: percentage of sales by brand in relationship with shop location
pct_acc:

What i need to calc is pct_acc which is the cumulative sum of the shops by rank (while it has no relation with brand)

PCT_ACC

My need is to reach something like PCT_ACC, and  then save the results in another one like this:endtable

答:
If you want only the final sum for the rows with that condition you can try:

```<code>SELECT
   SUM (IF(Rank < 2, Values, 0) AS condition1
FROM table
</code>```

If you want to get the rank and the sum only for the rows with that condition you can try doing

```<code>SELECT
   Rank,
   SUM (IF(Rank < 2, Values, 0) AS condition1
FROM table
WHERE
   RANK < 2
GROUP BY
   Rank
</code>```

Finally, if you want to get the rank and the sum considering all the rows you can try doing:

```<code>SELECT
   Rank,
   SUM (IF(Rank < 2, Values, 0) AS condition1
FROM table
GROUP BY
   Rank
</code>```

I hope it helps

Body:
If you want only the final sum for the rows with that condition you can try:

SELECT
   SUM (IF(Rank < 2, Values, 0) AS condition1
FROM table

If you want to get the rank and the sum only for the rows with that condition you can try doing

SELECT
   Rank,
   SUM (IF(Rank < 2, Values, 0) AS condition1
FROM table
WHERE
   RANK < 2
GROUP BY
   Rank

Finally, if you want to get the rank and the sum considering all the rows you can try doing:

SELECT
   Rank,
   SUM (IF(Rank < 2, Values, 0) AS condition1
FROM table
GROUP BY
   Rank

I hope it helps


问:
GKE cluster - can I direct traffic from global http load balancer to nginx ingress controller
I'm using GKE and I installed nginx ingress controller on the cluster. GCP created automatically a TCP load balancer to redirect the request from the external ephemeral IP to my cluster nodes (nginx).

I have another a web application deployed on a VM, and I'd like to balance the incoming requests by subdomain between VM and gke cluster. In order to do that I created a global load balancer with 2 backends and the host and path rules.

I configured DNS record A to point the Global load balancer.

I can reach the VM from my domain but I cannot reach the ingresses installed on GKE.

I tried to configure the gke-backend as instance group (node pool) and as Internet network endpoint group pointing to TCP load balancer. But without success :-(

How can I balance between a VM and GKE cluster in GCP?

答:
This is not normally done. To begin with, you can't have an HTTP(S) Load balancer target a network load balancer. The LB must point to a backend service that is comprised of either a network endpoint group or an instance group.

The only way for this to work is to use an unmanaged instance group that contains all the current nodes. You can then add the unmanaged instance group as a backend service to your HTTP(S) LB, specifying the Nginx Ingress nodePort as the backend port.

The problem with the above is that when any of the cluster nodes change (scale up, down, or get replaced due to an upgrade), the unmanaged instance group will not update with the new nodes automatically. You will need to manually keep the group up to date.


问:
Android Studio. Calling Static method from other Activity
```<code>public class MainActivity extends AppCompatActivity {

    private static  final int REQUEST_LOCATION=1;

    public static Context gb;

    static LocationManager locationManager;
    public static String latitude,longitude;
    public MainActivity(Context context){
        this.gb = context;
    }

    Button getlocationBtn;
    static TextView showLocationTxt;

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

        //Add permission

        ActivityCompat.requestPermissions(this,new String[]
                {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        showLocationTxt=findViewById(R.id.show_location);
        getlocationBtn=findViewById(R.id.getLocation);

        getlocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //place the following line on all operations e.g click
                locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);

                //Check gps is enable or not

                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                {
                    //Write Function To enable gps

                    OnGPS();
                }
                else
                {
                    //GPS is already On then

                    getLocation();
                }
            }
        });

    }

    public static void getLocation() {

        //Check Permissions again

        if (ActivityCompat.checkSelfPermission(gb,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(gb, Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions((Activity)gb,new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        }
        else
        {
            Location LocationGps= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location LocationNetwork=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Location LocationPassive=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

            if (LocationGps !=null)
            {
                double lat=LocationGps.getLatitude();
                double longi=LocationGps.getLongitude();

                latitude=String.valueOf(lat);
                longitude=String.valueOf(longi);

                showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
            }
            else if (LocationNetwork !=null)
            {
                double lat=LocationNetwork.getLatitude();
                double longi=LocationNetwork.getLongitude();

                latitude=String.valueOf(lat);
                longitude=String.valueOf(longi);

                showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
            }
            else if (LocationPassive !=null)
            {
                double lat=LocationPassive.getLatitude();
                double longi=LocationPassive.getLongitude();

                latitude=String.valueOf(lat);
                longitude=String.valueOf(longi);

                showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
            }
            else
            {
                Toast.makeText(gb, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void OnGPS() {

        final AlertDialog.Builder builder= new AlertDialog.Builder(this);

        builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();
            }
        });
        final AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }
}
</code>```

==================== Calling Activity==============================

```<code>package com.example.currentlocation;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class calling extends AppCompatActivity {
    Button btnLoc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calling);
        btnLoc = (Button) findViewById(R.id.getLocation);
        btnLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getLocation();
            }
        });
    }
}
</code>```

===============================Question================================

Greetings! I am trying to write a code in java. I want to declare all of the methods in a single class with static modifier. So that whenever required I could call that method and perform function associated with that. in the given example I am trying to toast the current location which is working perfectly fine on button click. but when I try to call this static getLocation from another activity the app crashes.

答:
There are a couple of things wrong with this, UI elements like the TextView, shouldn’t be static. If you want to modularise functions, you are better off writing Utils classes. Don’t try to access methods from other activities, even though it is possible to access non static methods, if you instantiate that particular Activity class. Static methods are almost useless in an Activity.

The Android system instantiates the Activities and calls the life cycle methods, to display and store info for that screen. Activities are not meant to be used as conventional classes. I would suggest studying the MVC architecture and Android activity life cycle.

Body:
public class MainActivity extends AppCompatActivity {

    private static  final int REQUEST_LOCATION=1;

    public static Context gb;

    static LocationManager locationManager;
    public static String latitude,longitude;
    public MainActivity(Context context){
        this.gb = context;
    }

    Button getlocationBtn;
    static TextView showLocationTxt;

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

        //Add permission

        ActivityCompat.requestPermissions(this,new String[]
                {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

        showLocationTxt=findViewById(R.id.show_location);
        getlocationBtn=findViewById(R.id.getLocation);

        getlocationBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //place the following line on all operations e.g click
                locationManager=(LocationManager) getSystemService(Context.LOCATION_SERVICE);

                //Check gps is enable or not

                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                {
                    //Write Function To enable gps

                    OnGPS();
                }
                else
                {
                    //GPS is already On then

                    getLocation();
                }
            }
        });

    }

    public static void getLocation() {

        //Check Permissions again

        if (ActivityCompat.checkSelfPermission(gb,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(gb, Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions((Activity)gb,new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        }
        else
        {
            Location LocationGps= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Location LocationNetwork=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Location LocationPassive=locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

            if (LocationGps !=null)
            {
                double lat=LocationGps.getLatitude();
                double longi=LocationGps.getLongitude();

                latitude=String.valueOf(lat);
                longitude=String.valueOf(longi);

                showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
            }
            else if (LocationNetwork !=null)
            {
                double lat=LocationNetwork.getLatitude();
                double longi=LocationNetwork.getLongitude();

                latitude=String.valueOf(lat);
                longitude=String.valueOf(longi);

                showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
            }
            else if (LocationPassive !=null)
            {
                double lat=LocationPassive.getLatitude();
                double longi=LocationPassive.getLongitude();

                latitude=String.valueOf(lat);
                longitude=String.valueOf(longi);

                showLocationTxt.setText("Your Location:"+"\n"+"Latitude= "+latitude+"\n"+"Longitude= "+longitude);
            }
            else
            {
                Toast.makeText(gb, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
            }
        }

    }

    private void OnGPS() {

        final AlertDialog.Builder builder= new AlertDialog.Builder(this);

        builder.setMessage("Enable GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
            }
        }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.cancel();
            }
        });
        final AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }
}

==================== Calling Activity==============================

package com.example.currentlocation;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class calling extends AppCompatActivity {
    Button btnLoc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calling);
        btnLoc = (Button) findViewById(R.id.getLocation);
        btnLoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.getLocation();
            }
        });
    }
}

===============================Question================================

Greetings! I am trying to write a code in java. I want to declare all of the methods in a single class with static modifier. So that whenever required I could call that method and perform function associated with that. in the given example I am trying to toast the current location which is working perfectly fine on button click. but when I try to call this static getLocation from another activity the app crashes.


问:
How can i get non repeated date values grails with <g:select >tag
I have an option for selecting a date from a drop-down with <g:select>.  How can I get non-repeated date values through this?  This is the code to get date in the specified format from the domain class.

dob is of type Date.

```<code><g:set var="dateFormat" value="MM/dd/yyyy"/>
<g:select id="dob" name="dob" from="${Person.list().dob*.format(dateFormat)}"
    value="${personInstance?.dob?.format(dateFormat)}" />
</code>```

答:
Call unique() on the list of items?

ie:

```<code>def colonies = [ 'a', 'a', 'b', 'c', 'c' ]
println colonies.unique()
</code>```

prints

```<code>[ 'a', 'b', 'c' ]
</code>```

Be aware however that unique() mutates the original collection, so

```<code>println colonies
</code>```

after calling unique() also prints

```<code>[ 'a', 'b', 'c' ]
</code>```

Body:
I have an option for selecting a date from a drop-down with <g:select>.  How can I get non-repeated date values through this?  This is the code to get date in the specified format from the domain class.

dob is of type Date.

<g:set var="dateFormat" value="MM/dd/yyyy"/>
<g:select id="dob" name="dob" from="${Person.list().dob*.format(dateFormat)}"
    value="${personInstance?.dob?.format(dateFormat)}" />

Body:
Call unique() on the list of items?

ie:

def colonies = [ 'a', 'a', 'b', 'c', 'c' ]
println colonies.unique()

prints

[ 'a', 'b', 'c' ]

Be aware however that unique() mutates the original collection, so

println colonies

after calling unique() also prints

[ 'a', 'b', 'c' ]


问:
Access a Groovy variable from within shell step in Jenkins pipeline
Using the Pipeline plugin in Jenkins 2.x, how can I access a Groovy variable that is defined somewhere at stage- or node-level from within a sh step?

Simple example:

```<code>node {
    stage('Test Stage') {
        some_var = 'Hello World' // this is Groovy
        echo some_var // printing via Groovy works
        sh 'echo $some_var' // printing in shell does not work
    }
}
</code>```

gives the following on the Jenkins output page:

```<code>[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test Stage)
[Pipeline] echo
Hello World
[Pipeline] sh
[test] Running shell script
+ echo

[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

As one can see, echo in the sh step prints an empty string.

A work-around would be to define the variable in the environment scope via

```<code>env.some_var = 'Hello World'
</code>```

and print it via

```<code>sh 'echo ${env.some_var}'
</code>```

However, this kind of abuses the environmental scope for this task.

答:
I would like to add another scenario to this discussion.
I was using shell environment  variables and groovy variables in the same script.

```<code> format='html'
    for file in *.txt;
        do mv  -- "\$file" "\${file%.txt}.$format";
    done
</code>```

So here, What I have done is use \$ only for shell environment variables and use $ for groovy variables.

Body:
Using the Pipeline plugin in Jenkins 2.x, how can I access a Groovy variable that is defined somewhere at stage- or node-level from within a sh step?

Simple example:

node {
    stage('Test Stage') {
        some_var = 'Hello World' // this is Groovy
        echo some_var // printing via Groovy works
        sh 'echo $some_var' // printing in shell does not work
    }
}

gives the following on the Jenkins output page:

[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test Stage)
[Pipeline] echo
Hello World
[Pipeline] sh
[test] Running shell script
+ echo

[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

As one can see, echo in the sh step prints an empty string.

A work-around would be to define the variable in the environment scope via

env.some_var = 'Hello World'

and print it via

sh 'echo ${env.some_var}'

However, this kind of abuses the environmental scope for this task.

Body:
I would like to add another scenario to this discussion.
I was using shell environment  variables and groovy variables in the same script.

 format='html'
    for file in *.txt;
        do mv  -- "\$file" "\${file%.txt}.$format";
    done

So here, What I have done is use \$ only for shell environment variables and use $ for groovy variables.


问:
How to make a RESTful call using Basic Authentication in apache camel?
I have an apache camel application that requires sending log files to an endpoint and this requires Basic Authentication. I was able to pass the authMethod, authusername and authPassword to the url as specified in the camel documentation but the challange I'm having is that I keep getting null response from the endpoint after starting the application.
However, the same endpoint returns response code and response body using postman.

Below is my code:

```<code>from("{{routes.feeds.working.directory}}?idempotent=true")
                .process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
                    File file = exchange.getIn().getBody(File.class);
                    multipartEntityBuilder.addPart("file",
                            new FileBody(file, ContentType.MULTIPART_FORM_DATA, fileName));
                    exchange.getOut().setBody(multipartEntityBuilder.build());
                    Message out = exchange.getOut();
                    int responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
                    log.info("response code "+responseCode);

            }
        })
                .setHeader(Exchange.HTTP_QUERY,
            constant("authMethod=Basic&authUsername="+username+"&authPassword="+password+""))
                .to(TARGET_WITH_AUTH +"/"+uuid+"/files")
                .log(LoggingLevel.DEBUG, "response code >>>>"+Exchange.HTTP_RESPONSE_CODE)
                .log(LoggingLevel.INFO, "RESPONSE BODY ${body}")
                .end();
</code>```

Kindly help review and advise further

答:
For HTTP basic authentication I use this before sending a request

```<code><setHeader headerName="Authorization">
    <constant>Basic cm9vdDpyb290</constant>
</setHeader>
</code>```

cm9vdDpyb290 - Encoded Base64 root:root(username and password) string

Body:
I have an apache camel application that requires sending log files to an endpoint and this requires Basic Authentication. I was able to pass the authMethod, authusername and authPassword to the url as specified in the camel documentation but the challange I'm having is that I keep getting null response from the endpoint after starting the application.
However, the same endpoint returns response code and response body using postman.

Below is my code:

from("{{routes.feeds.working.directory}}?idempotent=true")
                .process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                    multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    String fileName = exchange.getIn().getHeader(Exchange.FILE_NAME, String.class);
                    File file = exchange.getIn().getBody(File.class);
                    multipartEntityBuilder.addPart("file",
                            new FileBody(file, ContentType.MULTIPART_FORM_DATA, fileName));
                    exchange.getOut().setBody(multipartEntityBuilder.build());
                    Message out = exchange.getOut();
                    int responseCode = out.getHeader(Exchange.HTTP_RESPONSE_CODE, Integer.class);
                    log.info("response code "+responseCode);

            }
        })
                .setHeader(Exchange.HTTP_QUERY,
            constant("authMethod=Basic&authUsername="+username+"&authPassword="+password+""))
                .to(TARGET_WITH_AUTH +"/"+uuid+"/files")
                .log(LoggingLevel.DEBUG, "response code >>>>"+Exchange.HTTP_RESPONSE_CODE)
                .log(LoggingLevel.INFO, "RESPONSE BODY ${body}")
                .end();

Kindly help review and advise further

Body:
For HTTP basic authentication I use this before sending a request

<setHeader headerName="Authorization">
    <constant>Basic cm9vdDpyb290</constant>
</setHeader>

cm9vdDpyb290 - Encoded Base64 root:root(username and password) string


问:
Using Ghost as a Headless CMS
I am interested in using Ghost as a headless CMS for a Gatsby site.  What I am wondering, though, how flexible Ghost is as a headless cms.  For instance, for the site that I am building now - I have different pages with different content structures, a news section and more.

In Wordpress, I would simply use different content types for the different page types.  I am wondering, though, is something like this possible in Ghost?

If so, how?

Thanks.

答:
With Ghost you can add tags to define different post types and use the Content API filter option to retrieve them:
https://ghost.org/docs/api/v3/content/#parameters</p>

Title: Using Ghost as a Headless CMS


问:
Validation of multiple models in one, using Nested Atrributes
So i tried to build a form consisted of fields from two models.
Unfortunately, validation only works for one of them, despite they are the same.

If there is a white sign in first field, console shows red "rollback" and view shows the error.

If there is a white sign in second field, everything goes as normal, the next page is rendered, no error is shown, YET the value is not saved.

So to sum up: validation works on both, but throws errors and rollbacks only in case of first. On addition, I am using the wicked form wizard gem.

My models are:

candidate.rb

```<code>class Candidate < ApplicationRecord
  belongs_to :user
  has_one :candidate_form
  has_one :employee_form
  accepts_nested_attributes_for :candidate_form
  accepts_nested_attributes_for :employee_form
end
</code>```

candidate_form.rb

```<code>class CandidateForm < ApplicationRecord
  belongs_to :candidate
  validates_format_of :name, without: /\W/, allow_blank: true
end
</code>```

employee_form.rb (as you can see, its the same as candidate_form.rb)

```<code>class EmployeeForm < ApplicationRecord
  belongs_to :candidate
  validates_format_of :pesel, without: /\W/, allow_blank: true
end
</code>```

controller:

```<code>def show
    @candidate = current_user.candidate
    render_wizard
  end

  def update
    @candidate = current_user.candidate
    @candidate.attributes = candidate_params
    render_wizard @candidate
  end

private

  def candidate_params
    params.require(:candidate).permit(candidate_form_attributes: [:id, :name],
                                      employee_form_attributes: [:id, :pesel])
  end
</code>```

my form structure

```<code><%= form_for @candidate, url: wizard_path, method: "put" do |f| %>
    <%= f.fields_for :candidate_form do |cand| %>
        <%= cand.text_field :name %>
    <% end %>
    <%= f.fields_for :employee_form do |emp| %>
        <%= emp.text_field :pesel %>
    <% end %>
    <%= f.submit "NEXT" %>
<% end %>
</code>```

One last clarification what doesn't works:

"Name with a space" - string like this in field :name prevents the form from being saved, throws an error, provides a rollback

"Pesel witha a space" - string like this in field :pesel DOES NOT prevent the form from being saved (only this field is not saved) and the rollback doesn't occur

答: Oh, nevermind. The :pesel was of type integer in database. Changing it to string makes everything works perfectly.</p>

Body:
So i tried to build a form consisted of fields from two models.
Unfortunately, validation only works for one of them, despite they are the same.

If there is a white sign in first field, console shows red "rollback" and view shows the error.

If there is a white sign in second field, everything goes as normal, the next page is rendered, no error is shown, YET the value is not saved.

So to sum up: validation works on both, but throws errors and rollbacks only in case of first. On addition, I am using the wicked form wizard gem.

My models are:

candidate.rb

class Candidate < ApplicationRecord
  belongs_to :user
  has_one :candidate_form
  has_one :employee_form
  accepts_nested_attributes_for :candidate_form
  accepts_nested_attributes_for :employee_form
end

candidate_form.rb

class CandidateForm < ApplicationRecord
  belongs_to :candidate
  validates_format_of :name, without: /\W/, allow_blank: true
end

employee_form.rb (as you can see, its the same as candidate_form.rb)

class EmployeeForm < ApplicationRecord
  belongs_to :candidate
  validates_format_of :pesel, without: /\W/, allow_blank: true
end

controller:

def show
    @candidate = current_user.candidate
    render_wizard
  end

  def update
    @candidate = current_user.candidate
    @candidate.attributes = candidate_params
    render_wizard @candidate
  end

private

  def candidate_params
    params.require(:candidate).permit(candidate_form_attributes: [:id, :name],
                                      employee_form_attributes: [:id, :pesel])
  end

my form structure

<%= form_for @candidate, url: wizard_path, method: "put" do |f| %>
    <%= f.fields_for :candidate_form do |cand| %>
        <%= cand.text_field :name %>
    <% end %>
    <%= f.fields_for :employee_form do |emp| %>
        <%= emp.text_field :pesel %>
    <% end %>
    <%= f.submit "NEXT" %>
<% end %>

One last clarification what doesn't works:

"Name with a space" - string like this in field :name prevents the form from being saved, throws an error, provides a rollback

"Pesel witha a space" - string like this in field :pesel DOES NOT prevent the form from being saved (only this field is not saved) and the rollback doesn't occur


问:
isearch across line breaks
Is it possible to make isearch disregard line breaks, i.e. a search for foo bar will find

```<code>.......... foo
bar .....
</code>```

I get bitten by isearch failing on such queries regularly when navigating long documents, and it's rather annoying.  I am aware that word-search-forward finds matches across lines, but it has certain shortcomings (e.g. it forces you to use complete words, so a search for "foo b" will fail; it doesn't highlight search results), and, more importantly, it's a little silly to use a different command depending on whether you are searching for one word or two.

答: Use C-M-s - isearch-forward-regexp.  This will interpret space characters as a marker for any white space character.

Title: isearch across line breaks

Body:
Is it possible to make isearch disregard line breaks, i.e. a search for foo bar will find

.......... foo
bar .....

I get bitten by isearch failing on such queries regularly when navigating long documents, and it's rather annoying.  I am aware that word-search-forward finds matches across lines, but it has certain shortcomings (e.g. it forces you to use complete words, so a search for "foo b" will fail; it doesn't highlight search results), and, more importantly, it's a little silly to use a different command depending on whether you are searching for one word or two.


问:
Python Script to get multi table counts
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.

Expected Output:

```<code>('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])
</code>```

Script:

```<code>import psycopg2

# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()

sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    result = cursor.fetchall()
    print('Counts:',result)

conn.close()
</code>```

Current output:

```<code>[root@pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])
</code>```

Any help is appreciated.

Thanks!

答:
I believe something as below, Unable to test code because of certificate issue.</p>

```<code>sql = """SELECT 'oltptransactions', COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases', COUNT(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    for name, count in cursor:
        print ("")

Or

sql = """SELECT 'oltptransactions :'||COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases :'||COUNT(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    result = cursor.fetchall()
    print(result)
</code>```

Title: Python Script to get multi table counts

Body:
I'm trying to write a python script to get a count of some tables for monitoring which looks a bit like the code below. I'm trying to get an output such as below and have tried using python multi-dimensional arrays but not having any luck.

Expected Output:

('oltptransactions:', [(12L,)])
('oltpcases:', [(24L,)])

Script:

import psycopg2

# Connection with the DataBase
conn = psycopg2.connect(user = "appuser", database = "onedb", host = "192.168.1.1", port = "5432")
cursor = conn.cursor()

sql = """SELECT COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT count(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    result = cursor.fetchall()
    print('Counts:',result)

conn.close()

Current output:

[root@pgenc python_scripts]# python multi_getrcount.py
('Counts:', [(12L,)])
('Counts:', [(24L,)])

Any help is appreciated.

Thanks!

Body:
I believe something as below, Unable to test code because of certificate issue.

sql = """SELECT 'oltptransactions', COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases', COUNT(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    for name, count in cursor:
        print ("")

Or

sql = """SELECT 'oltptransactions :'||COUNT(id) FROM appuser.oltptransactions"""
sql2 = """SELECT 'oltpcases :'||COUNT(id) FROM appuser.oltpcases"""

sqls = [sql,sql2]
for i in sqls:
    cursor.execute(i)
    result = cursor.fetchall()
    print(result)


问:
Why is the output for my datediff expression to return a number of days bracketed?
I have written the following expression to give me the number of days between a date and today.

```<code>=IIF(Fields!First_Check_Start_Date.Value = nothing,nothing,datediff("d",Today,Fields!First_Check_Start_Date.Value))
</code>```

The output is correct but is bracketing the number

ie.  (292) instead of 292

Any help as to why this is

答:
So it appears that whilst viewing in SSRS Report builder the numbers are bracketed (292), however once export to either csv or excel the bracket disappears and is replaced bi a minus -292 which is correct

Thanks

Body:
I have written the following expression to give me the number of days between a date and today.

=IIF(Fields!First_Check_Start_Date.Value = nothing,nothing,datediff("d",Today,Fields!First_Check_Start_Date.Value))

The output is correct but is bracketing the number

ie.  (292) instead of 292

Any help as to why this is


问:
Achieve 3D model using 2D horizontal polygons sorted by z-axis
Please advise me.

I want to construct a 3D model in C++ using 2D horizontal polygons (actually a set of 2D points which form a closed contour) sorted by z-axis (Using frameworks like OpenGL).

How could I do that ?

Thanks.

答:
A 3D model usually consists of a vertice array and a triangles array. The vertices are your points where the order is irrelevant.
The triangles array then contains only indices from the vertice-array and describes the triangles that way.
For example if your points are pA, pB, pC and stored in that order in the vertices array, then your triangles array contains 0, 1, 2.

However the actual details depend a lot on your implementation environment. Look up some examples in your desired engine.

By the way, if this is for a research project or stuff like that, I'd recomend a higher level engine than OpenGL. I did a thesis project about code-generated 3D models project by using Unity. That's C# instead of C++, but unless you need large models to be created in Realtime, the speed suffices easily and you will develop much more efficiently.


问:
NumberFormatException while parsing date with SimpleDateFormat.parse()
Have a function that creates a time-only Date object. (why this is required is a long story which is irrelevant in this context but I need to compare to some stuff in XML world where TIME (i.e. time-only) is a valid concept).

```<code>private static final SimpleDateFormat DF_TIMEONLY = new SimpleDateFormat("HH:mm:ss.SSSZ");

public static Date getCurrentTimeOnly() {

    String onlyTimeStr = DF_TIMEONLY.format(new Date());  // line #5
    Date  onlyTimeDt = null;
    try {
        onlyTimeDt = DF_TIMEONLY.parse(onlyTimeStr);  // line #8
    } catch (ParseException ex) {
        // can never happen (you would think!)
    }
    return onlyTimeDt;
}
</code>```

There are probably at least a couple other ways to create a time-only Date in Java (or more precisely one where the date part is 1970-01-01) but my question is really not about that.

My question is that this piece of code starts randomly throwing NumberFormatException on line #8 after having run in production for long time. Technically I would say that this should be impossible, right ?

Here's an extract of random NumberFormatExceptions that come from above piece of code:

```<code>java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: ".11331133EE22"
java.lang.NumberFormatException: For input string: "880044E.3880044"
java.lang.NumberFormatException: For input string: "880044E.3880044E3"
</code>```

First of all I hope we can agree that formally this should be impossible?  The code uses the same format (DF_TIMEONLY) as output and then input. Let me know if you disagree that it should be impossible.

I haven't been able to re-produce the problem in a standalone environment. The problem seems to come when the JVM has run for a long time (>1 week). I cannot find a pattern to the problem, i.e. summer time / winter time, AM/PM, etc.  The error is sporadic, meaning that one minute it will throw NumberFormatException and the next minute it will run fine.

I suspect that there's some kind of arithmetic malfunction somewhere in either the JVM or perhaps even in the CPU. The above exceptions suggests that there's floating point numbers involved but I fail to see where they would come from. As far as I know Java's Date object is a wrapper around a long which holds the number of millis since the epoch.

I'm guessing what is happening is that there's an unexpected string onlyTimeStr created in line #5 so the problem really lies here rather than in line #8.

Here's an example of a full stacktrace:

```<code>java.lang.NumberFormatException: For input string: "880044E.3880044E3"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at java.text.DigitList.getDouble(DigitList.java:168)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1321)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2086)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1455)
    at java.text.DateFormat.parse(DateFormat.java:355)
    at org.mannmann.zip.Tanker.getCurrentTimeOnly(Tanker.java:746)
</code>```

Environment:  Java 7

答:
SimpleDateFormat is not thread safe. the following program will reproduce NumberFormatException while parsing string represented date to date object.

public class MaintainEqualThreadsPatallel {
    static int parallelCount = 20;
    public static void main(String[] args) throws Exception {
        ExecutorService executorPool = Executors.newFixedThreadPool(parallelCount);

        int numberOfThreads = 150; // Total thread count = 150*2= 300.
        List<Future<Object>> futureReturns = new LinkedList<Future<Object>>();
        for (int i = 0; i < numberOfThreads; i++) {
            int uniqueRandomValues = uniqueRandomValues(1, 10);

            // Callable Thread - call()
            Future<Object> submit = executorPool.submit( new WorkerCallable(uniqueRandomValues) );
            futureReturns.add(submit);

            // Runnable Thread - run()
            executorPool.execute( new WorkerThread(uniqueRandomValues) );
        }

        // WorkerCallable: Blocking main thread until task completes.
        waitTillThreadsCompleteWork(futureReturns);
        // Terminate Pool threads in-order to terminate main thread
        executorPool.shutdown();
    }
    private static final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    public static Date numberFormatEx(Date date) throws ParseException { // synchronized
        String dateStr = sdf.format(date);
        Date dateParsed = sdf.parse(dateStr); // NumberFormatException: For input string: "186E.2186E2"
        System.out.println("Date :"+ dateParsed);
        return dateParsed;
    }

    protected void loopFunction(int repeatCount) {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName +":START");
        for (int i = 1; i <= repeatCount; i++) {
            try {
                System.out.println(threadName +":"+ i);
                sleepThread(100);

                numberFormatEx(new Date());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(threadName +":END");
    }

    public static void waitTillThreadsCompleteWork(List<Future<Object>> futureReturns) throws Exception {
        for (Future<Object> future : futureReturns) {
            int threadReturnVal = (int) future.get();
            System.out.println("Future Response : "+threadReturnVal);
        }
    }

    public static int uniqueRandomValues(int min, int max) {
        int nextInt = ThreadLocalRandom.current().nextInt(min, max);
        System.out.println("Random Vlaue : "+nextInt);
        return nextInt;
    }
    public void sleepThread(long mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class WorkerThread extends MaintainEqualThreadsPatallel implements Runnable {
    int randomValue = 0;
    public WorkerThread(int randomValue) {
        this.randomValue = randomValue;
    }

    @Override
    public void run() {
        // As separate stack run() function doesn't accepts parameters, pass to constructor.
        loopFunction(randomValue);
    }
}
class WorkerCallable extends MaintainEqualThreadsPatallel implements Callable<Object> {
    int randomValue = 0;
    public WorkerCallable(int randomValue) {
        this.randomValue = randomValue;
    }

    public Object call() {
        // As separate stack run() function doesn't accepts parameters, pass to constructor.
        loopFunction(randomValue);
        return randomValue;
    }
}
```

<p>NumberFormatException with different messages:</p>

```java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException: For input string: "186E.2"
java.lang.NumberFormatException: For input string: "186E.2186E2"
java.lang.NumberFormatException: For input string: "22200222E.222002224EE4"

java.lang.NumberFormatException: For input string: "22200222E.222002224EE44"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.text.DigitList.getDouble(DigitList.java:169)
    at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
    at java.text.DateFormat.parse(DateFormat.java:364)
```

<p>In <code>Multi-Threading</code>/<code>Web Application with Multi-Requests</code> concept parse function leads to <strong><code>NumberFormatException</code></strong> which can be handled using synchronized block.</p>

<hr>

<p>To overcome NumberFormatException on <code>parse()</code> function use any of the following scenarios.</p>

<ol>
<li><strong>Separate Object</strong>: Every request/thread works on its own object.</li>
</ol>

<pre class="lang-java prettyprint-override"><code>public static Date numberFormatEx(Date date) throws ParseException {
    SimpleDateFormat ObjInstance = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    String dateStr = ObjInstance.format(date);
    Date dateParsed = ObjInstance.parse(dateStr);
    System.out.println("Date :"+ dateParsed);
    return dateParsed;
}
</code>```

Unnecessary creating reusable object for each thread.

Static Object synchronized block: Every request/thread shares the common object to perform operation. As multiple threads share same object at same time then the object data gets clear/overrride ""/"186E.2186E2" at some point and leads to error.

static SimpleDateFormat objStatic = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
public static synchronized Date numberFormatEx(Date date) throws ParseException {
    String dateStr = objStatic.format(date);
    Date dateParsed = objStatic.parse(dateStr); // NumberFormatException: For input string: "186E.2186E2"
    System.out.println("Date :"+ dateParsed);
    return dateParsed;
}
```

NOTE: In case of Memory management it better to use synchronized block with static object which is reusable.

Body:
Have a function that creates a time-only Date object. (why this is required is a long story which is irrelevant in this context but I need to compare to some stuff in XML world where TIME (i.e. time-only) is a valid concept).

private static final SimpleDateFormat DF_TIMEONLY = new SimpleDateFormat("HH:mm:ss.SSSZ");

public static Date getCurrentTimeOnly() {

    String onlyTimeStr = DF_TIMEONLY.format(new Date());  // line #5
    Date  onlyTimeDt = null;
    try {
        onlyTimeDt = DF_TIMEONLY.parse(onlyTimeStr);  // line #8
    } catch (ParseException ex) {
        // can never happen (you would think!)
    }
    return onlyTimeDt;
}

There are probably at least a couple other ways to create a time-only Date in Java (or more precisely one where the date part is 1970-01-01) but my question is really not about that.

My question is that this piece of code starts randomly throwing NumberFormatException on line #8 after having run in production for long time. Technically I would say that this should be impossible, right ?

Here's an extract of random NumberFormatExceptions that come from above piece of code:

java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: ".11331133EE22"
java.lang.NumberFormatException: For input string: "880044E.3880044"
java.lang.NumberFormatException: For input string: "880044E.3880044E3"

First of all I hope we can agree that formally this should be impossible?  The code uses the same format (DF_TIMEONLY) as output and then input. Let me know if you disagree that it should be impossible.

I haven't been able to re-produce the problem in a standalone environment. The problem seems to come when the JVM has run for a long time (>1 week). I cannot find a pattern to the problem, i.e. summer time / winter time, AM/PM, etc.  The error is sporadic, meaning that one minute it will throw NumberFormatException and the next minute it will run fine.

I suspect that there's some kind of arithmetic malfunction somewhere in either the JVM or perhaps even in the CPU. The above exceptions suggests that there's floating point numbers involved but I fail to see where they would come from. As far as I know Java's Date object is a wrapper around a long which holds the number of millis since the epoch.

I'm guessing what is happening is that there's an unexpected string onlyTimeStr created in line #5 so the problem really lies here rather than in line #8.

Here's an example of a full stacktrace:

java.lang.NumberFormatException: For input string: "880044E.3880044E3"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1241)
    at java.lang.Double.parseDouble(Double.java:540)
    at java.text.DigitList.getDouble(DigitList.java:168)
    at java.text.DecimalFormat.parse(DecimalFormat.java:1321)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:2086)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1455)
    at java.text.DateFormat.parse(DateFormat.java:355)
    at org.mannmann.zip.Tanker.getCurrentTimeOnly(Tanker.java:746)

Environment:  Java 7

Body:
SimpleDateFormat is not thread safe. the following program will reproduce NumberFormatException while parsing string represented date to date object.

public class MaintainEqualThreadsPatallel {
    static int parallelCount = 20;
    public static void main(String[] args) throws Exception {
        ExecutorService executorPool = Executors.newFixedThreadPool(parallelCount);

        int numberOfThreads = 150; // Total thread count = 150*2= 300.
        List<Future<Object>> futureReturns = new LinkedList<Future<Object>>();
        for (int i = 0; i < numberOfThreads; i++) {
            int uniqueRandomValues = uniqueRandomValues(1, 10);

            // Callable Thread - call()
            Future<Object> submit = executorPool.submit( new WorkerCallable(uniqueRandomValues) );
            futureReturns.add(submit);

            // Runnable Thread - run()
            executorPool.execute( new WorkerThread(uniqueRandomValues) );
        }

        // WorkerCallable: Blocking main thread until task completes.
        waitTillThreadsCompleteWork(futureReturns);
        // Terminate Pool threads in-order to terminate main thread
        executorPool.shutdown();
    }
    private static final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    public static Date numberFormatEx(Date date) throws ParseException { // synchronized
        String dateStr = sdf.format(date);
        Date dateParsed = sdf.parse(dateStr); // NumberFormatException: For input string: "186E.2186E2"
        System.out.println("Date :"+ dateParsed);
        return dateParsed;
    }

    protected void loopFunction(int repeatCount) {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName +":START");
        for (int i = 1; i <= repeatCount; i++) {
            try {
                System.out.println(threadName +":"+ i);
                sleepThread(100);

                numberFormatEx(new Date());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(threadName +":END");
    }

    public static void waitTillThreadsCompleteWork(List<Future<Object>> futureReturns) throws Exception {
        for (Future<Object> future : futureReturns) {
            int threadReturnVal = (int) future.get();
            System.out.println("Future Response : "+threadReturnVal);
        }
    }

    public static int uniqueRandomValues(int min, int max) {
        int nextInt = ThreadLocalRandom.current().nextInt(min, max);
        System.out.println("Random Vlaue : "+nextInt);
        return nextInt;
    }
    public void sleepThread(long mills) {
        try {
            Thread.sleep(mills);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class WorkerThread extends MaintainEqualThreadsPatallel implements Runnable {
    int randomValue = 0;
    public WorkerThread(int randomValue) {
        this.randomValue = randomValue;
    }

    @Override
    public void run() {
        // As separate stack run() function doesn't accepts parameters, pass to constructor.
        loopFunction(randomValue);
    }
}
class WorkerCallable extends MaintainEqualThreadsPatallel implements Callable<Object> {
    int randomValue = 0;
    public WorkerCallable(int randomValue) {
        this.randomValue = randomValue;
    }

    public Object call() {
        // As separate stack run() function doesn't accepts parameters, pass to constructor.
        loopFunction(randomValue);
        return randomValue;
    }
}

NumberFormatException with different messages:

java.lang.NumberFormatException: multiple points
java.lang.NumberFormatException: For input string: ""
java.lang.NumberFormatException: For input string: "186E.2"
java.lang.NumberFormatException: For input string: "186E.2186E2"
java.lang.NumberFormatException: For input string: "22200222E.222002224EE4"

java.lang.NumberFormatException: For input string: "22200222E.222002224EE44"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.text.DigitList.getDouble(DigitList.java:169)
    at java.text.DecimalFormat.parse(DecimalFormat.java:2056)
    at java.text.SimpleDateFormat.subParse(SimpleDateFormat.java:1869)
    at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1514)
    at java.text.DateFormat.parse(DateFormat.java:364)

In Multi-Threading/Web Application with Multi-Requests concept parse function leads to NumberFormatException which can be handled using synchronized block.

To overcome NumberFormatException on parse() function use any of the following scenarios.

Separate Object: Every request/thread works on its own object.

public static Date numberFormatEx(Date date) throws ParseException {
    SimpleDateFormat ObjInstance = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
    String dateStr = ObjInstance.format(date);
    Date dateParsed = ObjInstance.parse(dateStr);
    System.out.println("Date :"+ dateParsed);
    return dateParsed;
}

Unnecessary creating reusable object for each thread.

Static Object synchronized block: Every request/thread shares the common object to perform operation. As multiple threads share same object at same time then the object data gets clear/overrride ""/"186E.2186E2" at some point and leads to error.

static SimpleDateFormat objStatic = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
public static synchronized Date numberFormatEx(Date date) throws ParseException {
    String dateStr = objStatic.format(date);
    Date dateParsed = objStatic.parse(dateStr); // NumberFormatException: For input string: "186E.2186E2"
    System.out.println("Date :"+ dateParsed);
    return dateParsed;
}

NOTE: In case of Memory management it better to use synchronized block with static object which is reusable.


问:
how to use join and like mysql in mongodb
```<code>var query = req.params.query;
const messages = await Message.aggregate([

      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },

      {'text': {'$regex': `.*${query}.*`}}
    ])
</code>```

Getting error "message": "Arguments must be aggregate pipeline operators",

I wanted to join first_name and last_name from users table and search ability based on either first_name, last_name and text how can i achieve this

答:
The error is occurring because 'text' is not an aggregation pipeline operator.

You can use $text inside of the $match stage.  See https://docs.mongodb.com/manual/tutorial/text-search-in-aggregation/ for more details.

I find it's helpful to build a pipeline in an aggregation pipeline builder inside of MongoDB Atlas (cloud.mongodb.com) or using MongoDB Compass (https://www.mongodb.com/products/compass) so that you can visually see what's happening at each stage of the pipeline.

Body:
var query = req.params.query;
const messages = await Message.aggregate([

      {
        $lookup: {
          from: 'users',
          localField: 'reference_id',
          foreignField: '_id',
          as: 'users'
        }
      },

      {'text': {'$regex': `.*${query}.*`}}
    ])

Getting error "message": "Arguments must be aggregate pipeline operators",

I wanted to join first_name and last_name from users table and search ability based on either first_name, last_name and text how can i achieve this


问:
Differentiate between audio start and audio play(after a pause) in HTML5 <audio>
How to add a listener on audio/video start?

I can do it like:

```<code>$audio.on("play", function() {
    console.log("audio played");
});
</code>```

where $audio is a jQuery object representing the single DOM audio element.

but it will also run when we resume the video. I want it to run on start only.

One way I can do it is:

```<code>$audio.on("play", function() {
  if(this.currentTime === 0) {
      console.log("audio started);
  }
});
</code>```

but this will run multiple times when we play/pause the audio on the start.

Is there any better way to do this? The listener should only work on audio start and audio replayed, not when the user manually drags the seek bar to the beginning of the source.

答:
Actually, it might be sounding confusing because I was under the impression that there could be a possibility that currentTime could still return 0 if we do it in a fraction of seconds. But after reading @freedomn-m, @roko-c-buljan, @rory-mccrossan comments, I got it that it will never be possible that currentTime returns 0 when we play-pause-play the video immediately.

Now, let's say I want to track how many times a user has watched the video. The requirements might sound weird but by watched I only meant started/replayed. It doesn't count if the user manually drags the seek bar to the beginning of the source.

Here is how I implemented it finally using all your points:

```<code>const $audio = $('.audio');
$audio.on("play", function() {

  if ($(this).data('once-played')) return; // Do nothing if data exists.

  // Your code here
  console.log("Audio started/replayed");

  // Finally, add a flag.
  $(this).data('once-played', true);
});

$audio.on("ended", function() {
  $(this).data('once-played', false);
});
</code>```

Body:
How to add a listener on audio/video start?

I can do it like:

$audio.on("play", function() {
    console.log("audio played");
});

where $audio is a jQuery object representing the single DOM audio element.

but it will also run when we resume the video. I want it to run on start only.

One way I can do it is:

$audio.on("play", function() {
  if(this.currentTime === 0) {
      console.log("audio started);
  }
});

but this will run multiple times when we play/pause the audio on the start.

Is there any better way to do this? The listener should only work on audio start and audio replayed, not when the user manually drags the seek bar to the beginning of the source.

Body:
Actually, it might be sounding confusing because I was under the impression that there could be a possibility that currentTime could still return 0 if we do it in a fraction of seconds. But after reading @freedomn-m, @roko-c-buljan, @rory-mccrossan comments, I got it that it will never be possible that currentTime returns 0 when we play-pause-play the video immediately.

Now, let's say I want to track how many times a user has watched the video. The requirements might sound weird but by watched I only meant started/replayed. It doesn't count if the user manually drags the seek bar to the beginning of the source.

Here is how I implemented it finally using all your points:

const $audio = $('.audio');
$audio.on("play", function() {

  if ($(this).data('once-played')) return; // Do nothing if data exists.

  // Your code here
  console.log("Audio started/replayed");

  // Finally, add a flag.
  $(this).data('once-played', true);
});

$audio.on("ended", function() {
  $(this).data('once-played', false);
});


问:
Adding NSMutableArray A to NSMutableArray B, and then doing "removeAllObjects" on A, clears B too?
```<code>A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];
</code>```

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

答:
Its because when you call addObject it adds the reference, not a copy of the object. And thus any change in the original object will be reflected in the reference stored in array. If you want to store a copy of the object then made a copy of it and store in array.

```<code>NSMutableArray *bookmarkCopy = [bookmarkArray mutableCopy];
[issueArray addObject:bookmarkCopy];
[bookmarkCopy release];
</code>```

Body:
A = bookmarkArray
B = issueArray
[issueArray addObject:bookmarkArray];
[bookmarkArray removeAllObjects];

Why does this leave issueArray empty, and what can I do to make sure I still have issueArray populated when bookmarkArray is cleared?

Body:
Its because when you call addObject it adds the reference, not a copy of the object. And thus any change in the original object will be reflected in the reference stored in array. If you want to store a copy of the object then made a copy of it and store in array.

NSMutableArray *bookmarkCopy = [bookmarkArray mutableCopy];
[issueArray addObject:bookmarkCopy];
[bookmarkCopy release];


问:
Is the Google SignIn framework available with mac catalyst support?
I am looking for the google signin sdk with mac catalyst support. Current version of 5.0.1 also don't support catalyst. Is there any planned release for the same?</p>

答:
Google Support has mentioned the following regarding Mac Catalyst:

We cannot provide technical assistance regarding your concern as the Mac Catalyst is not supported by the Mobile Ads SDK. To get future updates regarding this, please keep an eye on our blog.


问:
Most common value (mode) by group in R
I need to find the most common values for the unique names in column afor individual month. I know that the topic was already and I found a solution here: Is there a built-in function for finding the mode?, but I have a problem with multiple mode.

Solutions below:

```<code>Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

df<-data.frame(a=rep(c("a","b"),each=5),b=c(2,1,2,2,3,3,1,1,2,3),
               c = c("Feb","Feb","Jan","Jan","Mar","Mar","Jan","Jan","Feb","Feb"))
df %>% group_by(a,c) %>% summarise(d=Mode(b))

# A tibble: 6 x 3
# Groups:   a [2]
  a     c         d
  <fct> <fct> <dbl>
1 a     Feb       2
2 a     Jan       2
3 a     Mar       3
4 b     Feb       2
5 b     Jan       1
6 b     Mar       3

#When I want use:

Modes <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

df %>% group_by(a,c) %>% summarise(d=Modes(b))

#I get:
Error: Column `d` must be length 1 (a summary value), not 2

I expected:

1 a     Feb       2
2 a     Feb       1
3 a     Jan       2
4 a     Mar       3
5 b     Feb       2
6 b     Feb       3
7 b     Jan       1
8 b     Mar       3
</code>```

答:
You can do it like this:

```<code>library(dplyr)

df %>%
  count(a, b, c) %>%
  group_by(a, c) %>%
  filter(n == max(n)) %>%
  select(a, b, c)
</code>```

Solution:

```<code># A tibble: 8 x 3
# Groups:   a, c [6]
  a         b c
  <fct> <dbl> <fct>
1 a         2 Feb
2 a         1 Feb
3 a         2 Jan
4 a         3 Mar
5 b         3 Mar
6 b         1 Jan
7 b         2 Feb
8 b         3 Feb
</code>```

Title: Most common value (mode) by group in R

Body:
I need to find the most common values for the unique names in column afor individual month. I know that the topic was already and I found a solution here: Is there a built-in function for finding the mode?, but I have a problem with multiple mode.

Solutions below:

Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

df<-data.frame(a=rep(c("a","b"),each=5),b=c(2,1,2,2,3,3,1,1,2,3),
               c = c("Feb","Feb","Jan","Jan","Mar","Mar","Jan","Jan","Feb","Feb"))
df %>% group_by(a,c) %>% summarise(d=Mode(b))

# A tibble: 6 x 3
# Groups:   a [2]
  a     c         d
  <fct> <fct> <dbl>
1 a     Feb       2
2 a     Jan       2
3 a     Mar       3
4 b     Feb       2
5 b     Jan       1
6 b     Mar       3

#When I want use:

Modes <- function(x) {
  ux <- unique(x)
  tab <- tabulate(match(x, ux))
  ux[tab == max(tab)]
}

df %>% group_by(a,c) %>% summarise(d=Modes(b))

#I get:
Error: Column `d` must be length 1 (a summary value), not 2

I expected:

1 a     Feb       2
2 a     Feb       1
3 a     Jan       2
4 a     Mar       3
5 b     Feb       2
6 b     Feb       3
7 b     Jan       1
8 b     Mar       3

Body:
You can do it like this:

library(dplyr)

df %>%
  count(a, b, c) %>%
  group_by(a, c) %>%
  filter(n == max(n)) %>%
  select(a, b, c)

Solution:

# A tibble: 8 x 3
# Groups:   a, c [6]
  a         b c
  <fct> <dbl> <fct>
1 a         2 Feb
2 a         1 Feb
3 a         2 Jan
4 a         3 Mar
5 b         3 Mar
6 b         1 Jan
7 b         2 Feb
8 b         3 Feb


问:
Python - IndexError: list index out of range while running python code
Please I need assistance with this code. I keep getting the error message above on line 5 and 35 of the code shown below. What is wrong?</p>

```<code>output = sys.argv[1]
main()
</code>```

答:
sys.argv returns:

The list of command line arguments passed to a Python script. argv[0]
  is the script name

So, if you execute the script like this python script.py then sys.argv[0]  returns script.py which is the name of script.

As there is no other argument, hence calling sys.argv[1] will raises as IndexError

Now consider another scenario when you execute the script as python script.py tom:

In this case calling sys.argv[1] returns the first command line argument which is tom.

Hope, this helps clear your understanding.

Body:
Please I need assistance with this code. I keep getting the error message above on line 5 and 35 of the code shown below. What is wrong?

output = sys.argv[1]
main()