问:
c# refactoring with linq query
I am trying to improve my linq syntax coding and i was wondering if anyone could show me a better way of writing this code below.Question is taken from leetcode https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/.
Thanks

```<code>        public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
        {
           var kidCandle = candles.Select(x => x+ extraCandies);
           var con = new List<bool>();
            foreach(var kid in kidCandle)
            {
                if (kid >= candles.Max())
                    con.Add(true);
                else
                    con.Add(false);
            }

           return con;
        }
</code>```

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

答:
Linq also does looping but just a syntacitc sugar, but we can write a Select for the foreach. So the code :

```<code>var con = new List<bool>();
foreach(var kid in kidCandle)
{
    if (kid >= candles.Max())
        con.Add(true);
    else
        con.Add(false);
}
</code>```

can be replaced with:

```<code>public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var kidCandle = candles.Select(x => x+ extraCandies);
   var maxCandles = candles.Max();
   var con = kidCandle.Select(kid => (kid >= maxCandles)).ToList();
   return con;
}
</code>```

even the whole method could be written like:

```<code>public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
    var maxCandles = candles.Max();
    return candles.Select(x => x+ extraCandies)
                 .Select(kid => (kid >= maxCandles)).ToList();
}
</code>```

Now more simpler:

```<code>public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var maxCandles = candles.Max();
   var con = candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
   return con;
}
</code>```

we can even avoid var :

```<code> public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
 {
     var maxCandles = candles.Max();
     return candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
 }
</code>```

Title: c# refactoring with linq query

Body:
I am trying to improve my linq syntax coding and i was wondering if anyone could show me a better way of writing this code below.Question is taken from leetcode https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/.
Thanks

        public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
        {
           var kidCandle = candles.Select(x => x+ extraCandies);
           var con = new List<bool>();
            foreach(var kid in kidCandle)
            {
                if (kid >= candles.Max())
                    con.Add(true);
                else
                    con.Add(false);
            }

           return con;
        }

https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/

Body:
Linq also does looping but just a syntacitc sugar, but we can write a Select for the foreach. So the code :

var con = new List<bool>();
foreach(var kid in kidCandle)
{
    if (kid >= candles.Max())
        con.Add(true);
    else
        con.Add(false);
}

can be replaced with:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var kidCandle = candles.Select(x => x+ extraCandies);
   var maxCandles = candles.Max();
   var con = kidCandle.Select(kid => (kid >= maxCandles)).ToList();
   return con;
}

even the whole method could be written like:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
    var maxCandles = candles.Max();
    return candles.Select(x => x+ extraCandies)
                 .Select(kid => (kid >= maxCandles)).ToList();
}

Now more simpler:

public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
{
   var maxCandles = candles.Max();
   var con = candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
   return con;
}

we can even avoid var :

 public static IList<bool> KidsWithCandies(int[] candles, int extraCandies)
 {
     var maxCandles = candles.Max();
     return candles.Select(kid => (kid + extraCandies >= maxCandles)).ToList();
 }


来源: stackexchange

问:
form data not saving to chrome local storage
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

```<code>    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}
</code>```

HTML

```<code><form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                <label for="name">Name:</label><br />
                <input type="text" id="name" name="name"><br><br>
                <label for="email">Email:</label><br />
                <input type="email" id="email" name="email"><br><br>
                <label for="feedback">Feedback:</label><br />
                <textarea id="feedback" name="feedback"></textarea><br>
                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>
    </section>
    <script src="form.js" type="text/javascript"></script>
</code>```

答:
You have created a very pesky and hard to find bug there!

No it's not the event doubling in <input type="submit" value="Submit" onclick="submit()"> <input type="submit" value="Submit" onclick="submit()">
even though it can be considered a bad practice

Spot it?

it's submit()!

Try this and submit the form

<form action="form.html" method="get" onsubmit="alert(getAttributeNames()); submit()">
  <fieldset style="width: 80%; margin: auto;">
    <legend>Feedback:</legend>
    Name:

    <input type="text" id="name" name="name">

    Email:

    <input type="email" id="email" name="email">

    Feedback:

    <textarea id="feedback" name="feedback"></textarea>

    <input type="submit" value="Submit" onclick="submit()">
  </fieldset>
</form>

```
</div>
</div>
</p>

<p>Surprised eh? You haven't defined <code>getAttributeNames()</code> anywhere yet it works! How is that you ask??</p>

<p>This is because it is one of many inbuilt DOM method that every html element inherits. Now you get the idea what happened when you used <code>onsubmit="submit()"</code> <strong>It didn't call the submit() function you wrote instead it called the inbuilt submit (form's native) method  that submits it to server</strong> and once it submits obviously it won't do any localstorage business </p>

<p>The fix is simple just use names that won't collide with the built-in(s). Or you can also use addEventListener() because in that you can tell browser explicitly <em>"no, use this function that I've written not the inbuilt one, please"</em></p>

<blockquote>
  <p>Here is a fixed version I just changed the name of your function</p>
</blockquote>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="form.html" method="get" onsubmit="submit2()">
  <fieldset style="width: 80%; margin: auto;">
    <legend>Feedback:</legend>
    <label for="name">Name:</label><br />
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label><br />
    <input type="email" id="email" name="email"><br><br>
    <label for="feedback">Feedback:</label><br />
    <textarea id="feedback" name="feedback"></textarea><br>
    <input type="submit" value="Submit" onclick="submit()">
  </fieldset>
</form>
</section>

<script>
  function submit2() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
  }

  function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

    document.write("passed value = " + name);
    document.write("passed value = " + email);
    document.write("passed value = " + feedback);

  }
</script></code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm pretty new coder and only touched on JavaScript, but I'm trying to submit a form and get back the data as part of my school work, but according to google's DevTool its not saving into google's local storage, any help?

    function submit() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
}

function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

        document.write("passed value = " + name);
        document.write("passed value = " + email);
        document.write("passed value = " + feedback);

}

HTML

<form action="form.html" method="get" onsubmit="submit()">
            <fieldset style="width: 80%; margin: auto;">
                <legend>Feedback:</legend>
                Name:

                <input type="text" id="name" name="name">

                Email:

                <input type="email" id="email" name="email">

                Feedback:

                <textarea id="feedback" name="feedback"></textarea>

                <input type="submit" value="Submit" onclick="submit()">
            </fieldset>
        </form>

Body:
You have created a very pesky and hard to find bug there!

No it's not the event doubling in <input type="submit" value="Submit" onclick="submit()"> <input type="submit" value="Submit" onclick="submit()">
even though it can be considered a bad practice

Spot it?

it's submit()!

Try this and submit the form

<form action="form.html" method="get" onsubmit="alert(getAttributeNames()); submit()">
  <fieldset style="width: 80%; margin: auto;">
    <legend>Feedback:</legend>
    <label for="name">Name:</label><br />
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label><br />
    <input type="email" id="email" name="email"><br><br>
    <label for="feedback">Feedback:</label><br />
    <textarea id="feedback" name="feedback"></textarea><br>
    <input type="submit" value="Submit" onclick="submit()">
  </fieldset>
</form>
</section>

Surprised eh? You haven't defined getAttributeNames() anywhere yet it works! How is that you ask??

This is because it is one of many inbuilt DOM method that every html element inherits. Now you get the idea what happened when you used onsubmit="submit()" It didn't call the submit() function you wrote instead it called the inbuilt submit (form's native) method  that submits it to server and once it submits obviously it won't do any localstorage business

The fix is simple just use names that won't collide with the built-in(s). Or you can also use addEventListener() because in that you can tell browser explicitly "no, use this function that I've written not the inbuilt one, please"

Here is a fixed version I just changed the name of your function

<form action="form.html" method="get" onsubmit="submit2()">
  <fieldset style="width: 80%; margin: auto;">
    <legend>Feedback:</legend>
    <label for="name">Name:</label><br />
    <input type="text" id="name" name="name"><br><br>
    <label for="email">Email:</label><br />
    <input type="email" id="email" name="email"><br><br>
    <label for="feedback">Feedback:</label><br />
    <textarea id="feedback" name="feedback"></textarea><br>
    <input type="submit" value="Submit" onclick="submit()">
  </fieldset>
</form>
</section>

<script>
  function submit2() {
    var name = document.getElementById("name").value;
    var email = document.getElementById("email").value;
    var feedback = document.getElementById("feedback").value;

    localStorage.setItem("name", name);
    localStorage.setItem("email", email);
    localStorage.setItem("feedback", feedback);

    return true;
  }

  function init() {
    var name = localStorage.getItem("name");
    var email = localStorage.getItem("email");
    var feedback = localStorage.getItem("feedback");

    document.write("passed value = " + name);
    document.write("passed value = " + email);
    document.write("passed value = " + feedback);

  }
</script>


问:
How to make setState take effect immediately?
There is an input element in my code:

```<code><input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>
</code>```

And the onChange handler is:

```<code>    const changeQty = (e) => {
        setQty(e.target.value);
        console.log(qty);
    }
</code>```

So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.

For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:

Could anyone tell me how to remove the delay?

I read useState set method not reflecting change immediately, but still cannot solve it.

I tried the code below as the answer indicates,

```<code>useEffect(() => {
    setQty(document.getElementById("input").value)
}, [qty]);
</code>```

but an error ReferenceError: Cannot access 'qty' before initialization occurred.

Thanks!

答:
this.setState() has two forms that could help you here:

Functional Form

this.setState((prevState, props) => ({}))
```

<p><strong>Callback Form</strong></p>

<pre class="lang-js prettyprint-override"><code>this.setState(nextState, () => {
    // instructions for immediately-after the state update
})
</code>```

It sounds like you could use the callback form here to defer some calculations into the callback.

Also, you can chain those if it's a warzone out there:

this.setState(nextState, () => {
    this.setState(nextState, () => {
        this.setState(nextState, () => {
            // you can do this, but probably don't
        })
    })
})
```

But, notice the extreme indenting that is occurring; it's reminiscent of callback hell and Promise christmas-tree hell.

Body:
There is an input element in my code:

<input id="input" className="ml-2" type="number" name="Qty" min="1" max="999" value={qty} onChange={(e) => {changeQty(e)}}/>

And the onChange handler is:

    const changeQty = (e) => {
        setQty(e.target.value);
        console.log(qty);
    }

So I suppose that whatever I enter in the input field will be printed out in the console, but the fact is there is delay.

For example, the default value is 1, then I type 2, then 1 will be printed out. Then I type 3, then 2 will be printed out. The number printed out is the previous one I entered instead of the current one, as shown below:

Could anyone tell me how to remove the delay?

I read useState set method not reflecting change immediately, but still cannot solve it.

I tried the code below as the answer indicates,

useEffect(() => {
    setQty(document.getElementById("input").value)
}, [qty]);

but an error ReferenceError: Cannot access 'qty' before initialization occurred.

Thanks!

Body:
this.setState() has two forms that could help you here:

Functional Form

this.setState((prevState, props) => ({}))

Callback Form

this.setState(nextState, () => {
    // instructions for immediately-after the state update
})

It sounds like you could use the callback form here to defer some calculations into the callback.

Also, you can chain those if it's a warzone out there:

this.setState(nextState, () => {
    this.setState(nextState, () => {
        this.setState(nextState, () => {
            // you can do this, but probably don't
        })
    })
})

But, notice the extreme indenting that is occurring; it's reminiscent of callback hell and Promise christmas-tree hell.


问:
Difference between the Domain Model & Activity Diagram
So I'm currently studying UML and I have a question regarding the difference between a Domain Model how this is compared with an Activity Diagram. I a bit confused with the following terms:

Activity Diagram (AD)

Domain Model (DM)

OO Domain Model (OO DM)

Class Diagram (as a term)

Domain Class Diagram (CD)

Design Class Diagram (DCD)

In Visual Paradigm, you have two the option between Activity & Class Diagrams to draw out your designs. So far I have been using Class Diagrams for my Domain Model but a friend of mine told me you should not be using Class Diagrams for your Domain Model. So my question what's the difference and how does a program like Visual Paradigm differentials with the standards of the subject I'm trying to learn.

答:
Domain model and domain diagram do not exist in UML, so all depends on the definition you use.

If I look at the literature it seems the 'standard' diagram to show a domain model is a class diagram, may be associated with object diagram to show example of instances.

An activity is a behavior, to use common word an 'algorithm'. An activity can be used to model the body of an operation. The goal of an activity and a class are totally different, one cannot replace the other.

Even the definition in Wikipedia is a domain model is a conceptual model of the domain that incorporates both behaviour and data the associated diagram in the article is a class diagram. In the article the word behaviour visibly refer to the rules the business uses in relation to that data.

Anyway, whatever, all depends on what you have to model, there is no definitive rules saying in case 1 use only class diagram, in case 2 use only activity diagram, and so on. You use all the diagrams you want while they are adapted for to say something useful


问:
Parsing JSON Data Swift "Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > points. I can navigate to faces but getting points is the issue.

here is code

```<code>
let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any]

let media = dictionary!["media"] as? [String: Any]
print(media!["faces"]) // Works see the returned data below
let faces = media!["faces"] as? [String: Any]
print(faces!["points"]) // Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value

</code>```

API returned data for print(media!["faces"])

```<code>{
    angle = "1.2222";
    "appearance_id" = 0;
    "detection_score" = 1;
    duration = "00:00:00";
    "face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
    height = "74.31999999999999";
    "media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
    "person_id" = "";
    points =     (
                {
            name = "basic eye left";
            type = 512;
            x = "85.16";
            y = "86.62";
        },
                {
            name = "basic eye right";
            type = 768;
            x = "110.92";
            y = "86.66";
        }
</code>```

答:
The main problem here is that you are force unwrapping optionals that you can't guarantee have a value - and when they don't have one that's causing a fatal error.

A better approach is to unwrap the variables safely and throw an error if you need to handle it. I've tried to show a few different ways to do that below.

```<code>guard let data = data else { return }
do {
    let dictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
    guard let media = dictionary?["media"] as? [String: Any] else { throw MyError.mediaNotFoundError }

    if let faces = media["faces"] as? [String: Any] {
        print(faces)

        guard let points = faces["points"] else { throw MyError.pointsNotFound}
        print(points)
    } else {
        throw MyError.facesNotFound
    }
} catch {
    // Handle error here
}
</code>```

Note, I have used a custom error enum. I would also advise adding a localised description to it in order to add more details for debugging.

```<code>enum MyError: Error {
    case mediaNotFoundError
    case facesNotFound
    case pointsNotFound
}
</code>```

I would also recommend reading this answer here for a more in-depth explanation on optionals.

Body:
I am trying to parse some JSON data returned from an API call. The path I want to navigate is media > faces > points. I can navigate to faces but getting points is the issue.

here is code

let dictionary = try JSONSerialization.jsonObject(with: data!, options:.mutableContainers) as? [String:Any]

let media = dictionary!["media"] as? [String: Any]
print(media!["faces"]) // Works see the returned data below
let faces = media!["faces"] as? [String: Any]
print(faces!["points"]) // Thread 4: Fatal error: Unexpectedly found nil while unwrapping an Optional value

API returned data for print(media!["faces"])

{
    angle = "1.2222";
    "appearance_id" = 0;
    "detection_score" = 1;
    duration = "00:00:00";
    "face_uuid" = "78338d20-9ced-11ea-b153-0cc47a6c4dbd";
    height = "74.31999999999999";
    "media_uuid" = "fec83ac3-de00-44f0-ad5b-e1e990a29a8c";
    "person_id" = "";
    points =     (
                {
            name = "basic eye left";
            type = 512;
            x = "85.16";
            y = "86.62";
        },
                {
            name = "basic eye right";
            type = 768;
            x = "110.92";
            y = "86.66";
        }

Body:
The main problem here is that you are force unwrapping optionals that you can't guarantee have a value - and when they don't have one that's causing a fatal error.

A better approach is to unwrap the variables safely and throw an error if you need to handle it. I've tried to show a few different ways to do that below.

guard let data = data else { return }
do {
    let dictionary = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
    guard let media = dictionary?["media"] as? [String: Any] else { throw MyError.mediaNotFoundError }

    if let faces = media["faces"] as? [String: Any] {
        print(faces)

        guard let points = faces["points"] else { throw MyError.pointsNotFound}
        print(points)
    } else {
        throw MyError.facesNotFound
    }
} catch {
    // Handle error here
}

Note, I have used a custom error enum. I would also advise adding a localised description to it in order to add more details for debugging.

enum MyError: Error {
    case mediaNotFoundError
    case facesNotFound
    case pointsNotFound
}

I would also recommend reading this answer here for a more in-depth explanation on optionals.


问:
SSRS add event data and manually updating SSRS Parameter
I am not sure if this is the best way, but it work for me. THe only downside is I need to add a random seconds of delay in order to use the current parameter.
Please look at my code below.

In SQL JOB of SSRS I modify step 1 of the SQL JOB. Prior to do exec addevent I update parameter value.

```<code>    declare @xml as xml
    set quoted_identifier ON
    DECLARE db_cursor CURSOR FOR
    SELECT C.[City]
    FROM #FService C
    GROUP BY C.[City]
    ORDER BY C.[City]
    DECLARE @CityLoop VARCHAR(50);
    OPEN db_cursor;
    FETCH NEXT FROM db_cursor INTO @CityLoop;
    WHILE @@FETCH_STATUS = 0
BEGIN
    -- THIS IS TO UPDATE XML
    set @xml = (select  Parameters
    from ReportServer.dbo.Subscriptions sb
    where sb.SubscriptionID = 'GUID')
       set @xml.modify('    replace value of
       (/ParameterValues/ParameterValue[2]/Value/text())[1]    with
       sql:variable("@CityLoop")  ')

    -- HERE WE UPDATE PARAMETER TABLE
    update ReportServer.dbo.Subscriptions
    set parameters = convert(nvarchar(max), @xml)
    where SubscriptionID = 'GUID'

    -- HERE IS THE ORIGINAL EXEC
    exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='GUID'

    WAITFOR DELAY '00:00:30';

    --RAISERROR (@DealLoop, 0, 1) WITH NOWAIT

    FETCH NEXT FROM db_cursor INTO @CityLoop;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
</code>```

Notice we add a 30 seconds delay for the SSRS to pickup and execute the report.
is there a way to avoid random seconds and execute the report directly? or AddEvent is the only way to do this?

if I don't have a delay, the report will only run using the last @cityLoop parameter. that is why I add the delay then the job works properly by sending email every 30 seconds for each City that is available in the parameter query

I am using SSRS and SQL Server 2012

thank you for your help

答:
I adapted this in order to solve the risky random wait times.
SQL Server central article[https://www.sqlservercentral.com/articles/dynamically-name-reportfile-export-in-ssrs]

It basically uses a wait for execution

```<code>            -- WAIT for EXECUTION
        set @bool1 = ISNULL((select eventdata from event where eventdata = @SBidEventData), '')
        while  @bool1 <> ''
        begin
            set @bool1 = ISNULL((select eventdata from event where eventdata = @SBidEventData), '')
            if  @bool1 = ''
            begin
                -- SET PATH AND PARAMETER TO THE WAY IT WAS
                WAITFOR DELAY '000:00:07'
                update Catalog
                set Path = '/Report/Report1'
                where ItemID = @ItemID
                update Subscriptions
                set Parameters = '<ParameterValues><ParameterValue><Name>Year</Name><Value>2019</Value></ParameterValue><ParameterValue><Name>Category</Name><Value>HONDA</Value></ParameterValue><ParameterValue><Name>Month</Name><Value>12</Value></ParameterValue></ParameterValues>'
                where SubscriptionID = @SBidEventData
            end
</code>```

end

ContentLicense: CC BY-SA 3.0

Body:
I am not sure if this is the best way, but it work for me. THe only downside is I need to add a random seconds of delay in order to use the current parameter.
Please look at my code below.

In SQL JOB of SSRS I modify step 1 of the SQL JOB. Prior to do exec addevent I update parameter value.

    declare @xml as xml
    set quoted_identifier ON
    DECLARE db_cursor CURSOR FOR
    SELECT C.[City]
    FROM #FService C
    GROUP BY C.[City]
    ORDER BY C.[City]
    DECLARE @CityLoop VARCHAR(50);
    OPEN db_cursor;
    FETCH NEXT FROM db_cursor INTO @CityLoop;
    WHILE @@FETCH_STATUS = 0
BEGIN
    -- THIS IS TO UPDATE XML
    set @xml = (select  Parameters
    from ReportServer.dbo.Subscriptions sb
    where sb.SubscriptionID = 'GUID')
       set @xml.modify('    replace value of
       (/ParameterValues/ParameterValue[2]/Value/text())[1]    with
       sql:variable("@CityLoop")  ')

    -- HERE WE UPDATE PARAMETER TABLE
    update ReportServer.dbo.Subscriptions
    set parameters = convert(nvarchar(max), @xml)
    where SubscriptionID = 'GUID'

    -- HERE IS THE ORIGINAL EXEC
    exec [ReportServer].dbo.AddEvent @EventType='TimedSubscription', @EventData='GUID'

    WAITFOR DELAY '00:00:30';

    --RAISERROR (@DealLoop, 0, 1) WITH NOWAIT

    FETCH NEXT FROM db_cursor INTO @CityLoop;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Notice we add a 30 seconds delay for the SSRS to pickup and execute the report.
is there a way to avoid random seconds and execute the report directly? or AddEvent is the only way to do this?

if I don't have a delay, the report will only run using the last @cityLoop parameter. that is why I add the delay then the job works properly by sending email every 30 seconds for each City that is available in the parameter query

I am using SSRS and SQL Server 2012

thank you for your help

Body:
I adapted this in order to solve the risky random wait times.
SQL Server central article[https://www.sqlservercentral.com/articles/dynamically-name-reportfile-export-in-ssrs]

It basically uses a wait for execution

            -- WAIT for EXECUTION
        set @bool1 = ISNULL((select eventdata from event where eventdata = @SBidEventData), '')
        while  @bool1 <> ''
        begin
            set @bool1 = ISNULL((select eventdata from event where eventdata = @SBidEventData), '')
            if  @bool1 = ''
            begin
                -- SET PATH AND PARAMETER TO THE WAY IT WAS
                WAITFOR DELAY '000:00:07'
                update Catalog
                set Path = '/Report/Report1'
                where ItemID = @ItemID
                update Subscriptions
                set Parameters = '<ParameterValues><ParameterValue><Name>Year</Name><Value>2019</Value></ParameterValue><ParameterValue><Name>Category</Name><Value>HONDA</Value></ParameterValue><ParameterValue><Name>Month</Name><Value>12</Value></ParameterValue></ParameterValues>'
                where SubscriptionID = @SBidEventData
            end

end


问:
How to get the right cells closer to left celss in TableLayout?
I have the following code:

```<code>    <TableLayout
        android:id="@+id/table"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:shrinkColumns="*"
        android:stretchColumns="*"
        android:layout_marginTop="15dp">

        <TableRow
            android:id="@+id/table_row1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="text"/>

            <Spinner
                android:id="@+id/spinner_project2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:drawSelectorOnTop="true" />
        </TableRow>

        <TableRow
            android:id="@+id/table_row2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Very long test"/>

            <Spinner
                android:id="@+id/spinner_project2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:drawSelectorOnTop="true" />
        </TableRow>
    </TableLayout
</code>```

It basically creates the following table:

```<code>text                         [spinner]
very long text               [spinner]
</code>```

I want the spinner to be closer to the text so I don't want the row to be 50-50. Rather I want to take the longest string in the text and this will be the size of the cells in the first column. I will get:

```<code>text            [spinner]  <Nothing here>
very long text  [spinner]  <Nothing here>
</code>```

I tried to use marginLeft but it didn't help. I also tried use weights=3 with inserting empty text-view. It looks better but then I get empty textview in the middle of the code. I'm sure there is a way to do it. How can I do it?

答:
Use  android:shrinkColumns="1" for TableLayout currently you are using * and remove android:stretchColumns="*"

```<code><TableLayout
        android:id="@+id/table"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:shrinkColumns="1"
        android:layout_margin="15dp"
        >

        <TableRow
            android:id="@+id/table_row1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="text"/>

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawSelectorOnTop="true" />

        </TableRow>

        <TableRow
            android:id="@+id/table_row2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Very long test"/>

            <Spinner
                android:id="@+id/spinner_2"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:drawSelectorOnTop="true" />

        </TableRow>
    </TableLayout>
</code>```

Note : Indexing starts from 0 i.e if you want to shrink/stretch 1st
  column you have to use 0 not 1

Body:
I have the following code:

    <TableLayout
        android:id="@+id/table"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:shrinkColumns="*"
        android:stretchColumns="*"
        android:layout_marginTop="15dp">

        <TableRow
            android:id="@+id/table_row1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="text"/>

            <Spinner
                android:id="@+id/spinner_project2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:drawSelectorOnTop="true" />
        </TableRow>

        <TableRow
            android:id="@+id/table_row2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Very long test"/>

            <Spinner
                android:id="@+id/spinner_project2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:drawSelectorOnTop="true" />
        </TableRow>
    </TableLayout

It basically creates the following table:

text                         [spinner]
very long text               [spinner]

I want the spinner to be closer to the text so I don't want the row to be 50-50. Rather I want to take the longest string in the text and this will be the size of the cells in the first column. I will get:

text            [spinner]  <Nothing here>
very long text  [spinner]  <Nothing here>

I tried to use marginLeft but it didn't help. I also tried use weights=3 with inserting empty text-view. It looks better but then I get empty textview in the middle of the code. I'm sure there is a way to do it. How can I do it?

Body:
Use  android:shrinkColumns="1" for TableLayout currently you are using * and remove android:stretchColumns="*"

<TableLayout
        android:id="@+id/table"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:shrinkColumns="1"
        android:layout_margin="15dp"
        >

        <TableRow
            android:id="@+id/table_row1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="text"/>

            <Spinner
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawSelectorOnTop="true" />

        </TableRow>

        <TableRow
            android:id="@+id/table_row2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/text_project2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Very long test"/>

            <Spinner
                android:id="@+id/spinner_2"
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:drawSelectorOnTop="true" />

        </TableRow>
    </TableLayout>

Note : Indexing starts from 0 i.e if you want to shrink/stretch 1st
  column you have to use 0 not 1


问:
Typescript: Filter Object by Interface or Class
I would like to sync an object that is provided by an API to a table.
The table is defined in Sequelize and has an interface and a class:

declare interface SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}
```

<pre class="lang-js prettyprint-override"><code>class SampleClass implements SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}
</code>```

The response of the API is not always the same, but could look something like this:

const sampleResponse = {
  value2: "..."
  value3: 0
  value4: "..."
}
```

<p>Now, I would only like create a new object that can be passed to sequelize that has the matching contents, for example:</p>

<pre class="lang-js prettyprint-override"><code>const filteredResponse = {
  value2: "..."
  value3: 0
}
</code>```

How can I match the object properties keys to the interface or class?

Thanks!

答:
You can get fields of class programmatically if you set default values to them and instantiate the class</p>

```<code>class SampleClass {
    value1?= "";
    value2?= "";
    value3?= 0;

}
var keys = Object.keys(new SampleClass()) as (keyof SampleClass)[];

var ob = { value1: "asd", value2: "sdad", value4: "xxx" };

var result: SampleClass = {};
for (var k of keys) {
    if (k in ob) { // remove this line if you want set missing fields to undefined
        result[k] = (ob as any)[k];
    }
}

console.log(result);
</code>```

Body:
I would like to sync an object that is provided by an API to a table.
The table is defined in Sequelize and has an interface and a class:

declare interface SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}

class SampleClass implements SampleInterface {
  value1?: string;
  value2?: string;
  value3?: number;
}

The response of the API is not always the same, but could look something like this:

const sampleResponse = {
  value2: "..."
  value3: 0
  value4: "..."
}

Now, I would only like create a new object that can be passed to sequelize that has the matching contents, for example:

const filteredResponse = {
  value2: "..."
  value3: 0
}

How can I match the object properties keys to the interface or class?

Thanks!

Body:
You can get fields of class programmatically if you set default values to them and instantiate the class

class SampleClass {
    value1?= "";
    value2?= "";
    value3?= 0;

}
var keys = Object.keys(new SampleClass()) as (keyof SampleClass)[];

var ob = { value1: "asd", value2: "sdad", value4: "xxx" };

var result: SampleClass = {};
for (var k of keys) {
    if (k in ob) { // remove this line if you want set missing fields to undefined
        result[k] = (ob as any)[k];
    }
}

console.log(result);


问:
WCF "A call to SSPI failed, see inner exception"
We have an existing system that uses WCF and was working fine until yesterday, when suddenly it stopped working on both my machine and another developer machine.

I've setup system diagnostics in the client config to write a trace file and we see the following exception:

```<code>Throwing an exception

**Basic Information**

Activity Name           Receive bytes on connection 'net.tcp://localhost:8004/'.
Time                    2016-01-06 13:38:45.3958
Level                   Error
Source                  System.ServiceModel
Process                 NServiceBus.Host
Thread                  219
Computer                RL-ZORO-LPT
Trace Identifier/Code   http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx

**Exception**

System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    System.Security.Authentication.AuthenticationException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
         System.ComponentModel.Win32Exception, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Exception Type: System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Message: A call to SSPI failed, see inner exception.

Stack Trace:  System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorAsyncResult.CompleteAuthenticateAsServer(IAsyncResult result)
              System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorAsyncResult.OnAuthenticateAsServer(IAsyncResult result)
              System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
              System.Net.LazyAsyncResult.Complete(IntPtr userToken)
              System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
              System.Net.Security.SslState.FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
              System.Net.Security.SslState.ReadFrameCallback(AsyncProtocolRequest asyncRequest)
              System.Net.AsyncProtocolRequest.CompleteRequest(Int32 result)
              System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
              System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
              System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
              System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(Object state)
              System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
              System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs e)
              System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
              System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
              System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
</code>```

Our server configuration looks like this:

```<code><system.serviceModel>
    <services>
      <service name="ServerImpl.RACServiceImpl.RACService" behaviorConfiguration="BILLService.ServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.Tcp://localhost:8004" />
            <add baseAddress="http://localhost:8006" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <endpoint address="BILLService" binding="netTcpBinding" bindingConfiguration="netTcpBindingConf" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService">
          <identity>
            <dns value="RACServer" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <client>
      <endpoint address="net.Tcp://localhost:8001/RMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBindingConf" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior name="BILLService.ServiceBehavior">
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <serviceCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <clientCertificate>
              <certificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </clientCertificate>
          </serviceCredentials>
          <serviceThrottling maxConcurrentCalls="40" maxConcurrentInstances="40" maxConcurrentSessions="40" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <clientCredentials>
            <clientCertificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <defaultCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBindingConf" closeTimeout="00:11:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="100" openTimeout="00:20:00">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:15:00" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" algorithmSuite="Default" />
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
</system.serviceModel>
</code>```

This is our client configuration:

```<code><system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBinding_RACService" closeTimeout="00:10:00" openTimeout="00:40:00" receiveTimeout="00:32:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" algorithmSuite="Default" />
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
          </security>
        </binding>
      </netTcpBinding>
    <wsHttpBinding>
        <binding name="WSHttpBinding_IThirdPartyRACService" closeTimeout="00:59:00" openTimeout="00:59:00" receiveTimeout="00:59:00" sendTimeout="00:59:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
          <security mode="None">
            <message clientCredentialType="None" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"></message>
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="net.Tcp://localhost:8004/AMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
      <endpoint address="net.Tcp://localhost:8004/AMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService1">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
    <endpoint address="https://localhost/ThirdPartyWebService/ThirdPartyRACService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IThirdPartyRACService" contract="IThirdPartyRACService" name="WSHttpBinding_IThirdPartyRACService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <clientCredentials>
            <clientCertificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <defaultCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
</system.serviceModel>
</code>```

If we set the security mode to "None" on both the client and the server then it works.

What can be wrong here?

答:
I got an error while testing this on localhost on windows 10 and thought to share with you all.

In App.Config on the client side i removed/commented below line :

```<code>  <!--<identity>
                <userPrincipalName value="AD\7329688" />
            </identity>-->
</code>```

Now its working

Body:
We have an existing system that uses WCF and was working fine until yesterday, when suddenly it stopped working on both my machine and another developer machine.

I've setup system diagnostics in the client config to write a trace file and we see the following exception:

Throwing an exception

**Basic Information**

Activity Name           Receive bytes on connection 'net.tcp://localhost:8004/'.
Time                    2016-01-06 13:38:45.3958
Level                   Error
Source                  System.ServiceModel
Process                 NServiceBus.Host
Thread                  219
Computer                RL-ZORO-LPT
Trace Identifier/Code   http://msdn.microsoft.com/en-US/library/System.ServiceModel.Diagnostics.ThrowingException.aspx

**Exception**

System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
    System.Security.Authentication.AuthenticationException, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
         System.ComponentModel.Win32Exception, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Exception Type: System.ServiceModel.Security.SecurityNegotiationException, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

Message: A call to SSPI failed, see inner exception.

Stack Trace:  System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorAsyncResult.CompleteAuthenticateAsServer(IAsyncResult result)
              System.ServiceModel.Channels.StreamSecurityUpgradeAcceptorAsyncResult.OnAuthenticateAsServer(IAsyncResult result)
              System.Runtime.Fx.AsyncThunk.UnhandledExceptionFrame(IAsyncResult result)
              System.Net.LazyAsyncResult.Complete(IntPtr userToken)
              System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
              System.Net.Security.SslState.FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
              System.Net.Security.SslState.ReadFrameCallback(AsyncProtocolRequest asyncRequest)
              System.Net.AsyncProtocolRequest.CompleteRequest(Int32 result)
              System.Net.FixedSizeReader.CheckCompletionBeforeNextRead(Int32 bytes)
              System.Net.FixedSizeReader.ReadCallback(IAsyncResult transportResult)
              System.Runtime.AsyncResult.Complete(Boolean completedSynchronously)
              System.ServiceModel.Channels.ConnectionStream.IOAsyncResult.OnAsyncIOComplete(Object state)
              System.ServiceModel.Channels.TracingConnection.TracingConnectionState.ExecuteCallback()
              System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(SocketAsyncEventArgs e)
              System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(SocketError socketError, Int32 bytesTransferred, SocketFlags flags)
              System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
              System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

Our server configuration looks like this:

<system.serviceModel>
    <services>
      <service name="ServerImpl.RACServiceImpl.RACService" behaviorConfiguration="BILLService.ServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="net.Tcp://localhost:8004" />
            <add baseAddress="http://localhost:8006" />
          </baseAddresses>
        </host>

        <endpoint address="BILLService" binding="netTcpBinding" bindingConfiguration="netTcpBindingConf" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService">
          <identity>
            <dns value="RACServer" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <client>
      <endpoint address="net.Tcp://localhost:8001/RMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBindingConf" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <serviceBehaviors>
        <behavior name="BILLService.ServiceBehavior">

          <serviceMetadata httpGetEnabled="false" />

          <serviceDebug includeExceptionDetailInFaults="true" />
          <serviceCredentials>
            <serviceCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <clientCertificate>
              <certificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </clientCertificate>
          </serviceCredentials>
          <serviceThrottling maxConcurrentCalls="40" maxConcurrentInstances="40" maxConcurrentSessions="40" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <clientCredentials>
            <clientCertificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <defaultCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBindingConf" closeTimeout="00:11:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxReceivedMessageSize="2147483647" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxConnections="100" openTimeout="00:20:00">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:15:00" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" algorithmSuite="Default" />
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
          </security>
        </binding>
      </netTcpBinding>
    </bindings>
</system.serviceModel>

This is our client configuration:

<system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBinding_RACService" closeTimeout="00:10:00" openTimeout="00:40:00" receiveTimeout="00:32:00" sendTimeout="00:10:00" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" />
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" algorithmSuite="Default" />
            <transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
          </security>
        </binding>
      </netTcpBinding>
    <wsHttpBinding>
        <binding name="WSHttpBinding_IThirdPartyRACService" closeTimeout="00:59:00" openTimeout="00:59:00" receiveTimeout="00:59:00" sendTimeout="00:59:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
          <security mode="None">
            <message clientCredentialType="None" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"></message>
            <transport clientCredentialType="None" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <client>
      <endpoint address="net.Tcp://localhost:8004/AMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
      <endpoint address="net.Tcp://localhost:8004/AMACService" behaviorConfiguration="ClientBehavior" binding="netTcpBinding" bindingConfiguration="netTcpBinding_RACService" contract="ServerImpl.Rsp.ServiceInterfaces.IRACService" name="IRACService1">
        <identity>
          <dns value="RACServer" />
        </identity>
      </endpoint>
    <endpoint address="https://localhost/ThirdPartyWebService/ThirdPartyRACService.svc" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IThirdPartyRACService" contract="IThirdPartyRACService" name="WSHttpBinding_IThirdPartyRACService">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="ClientBehavior">
          <clientCredentials>
            <clientCertificate findValue="RACClient" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
            <serviceCertificate>
              <defaultCertificate findValue="RACServer" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" />
              <authentication certificateValidationMode="PeerOrChainTrust" revocationMode="NoCheck" />
            </serviceCertificate>
          </clientCredentials>
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
</system.serviceModel>

If we set the security mode to "None" on both the client and the server then it works.

What can be wrong here?

Body:
I got an error while testing this on localhost on windows 10 and thought to share with you all.

In App.Config on the client side i removed/commented below line :

  <!--<identity>
                <userPrincipalName value="AD\7329688" />
            </identity>-->

Now its working


问:
JUnit's @TestMethodOrder annotation not working
I'm having a problem with following integration test

```<code>import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;

@SpringBootTest
@ActiveProfiles("test")
@TestMethodOrder(OrderAnnotation.class)
public class FooServiceIT {
    @Test
    @Order(1)
    void testUploadSuccess() { ... }
    @Test
    @Order(2)
    void testDownloadSuccess() { ... }
    @Test
    @Order(3)
    void testDeleteSuccess() { ... }
}
</code>```

I'd expect when I run the test that the execution order would 1, 2, 3 but for some reason, the actual execution order is 2, 3, 1.

Tbh, I'm clueless why the annotation is not working. I'm using Spring Boot 2.1.3 with JUnit 5.4.

答:
I have faced the same issue. But, I found the problem where exactly is on my case. Wrongly import the "Order" class.

Wrong One

```<code>import org.springframework.core.annotation.Order;
</code>```

Right one

```<code>*import org.junit.jupiter.api.Order;*
</code>```

Also, please verify the following five classes with proper import

```<code>import org.junit.jupiter.api.Assertions;

import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;

import org.junit.jupiter.api.Order;

import org.junit.jupiter.api.Test;

import org.junit.jupiter.api.TestMethodOrder;
</code>```

Body:
I'm having a problem with following integration test

import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;

@SpringBootTest
@ActiveProfiles("test")
@TestMethodOrder(OrderAnnotation.class)
public class FooServiceIT {
    @Test
    @Order(1)
    void testUploadSuccess() { ... }
    @Test
    @Order(2)
    void testDownloadSuccess() { ... }
    @Test
    @Order(3)
    void testDeleteSuccess() { ... }
}

I'd expect when I run the test that the execution order would 1, 2, 3 but for some reason, the actual execution order is 2, 3, 1.

Tbh, I'm clueless why the annotation is not working. I'm using Spring Boot 2.1.3 with JUnit 5.4.

Body:
I have faced the same issue. But, I found the problem where exactly is on my case. Wrongly import the "Order" class.

Wrong One

import org.springframework.core.annotation.Order;

Right one

*import org.junit.jupiter.api.Order;*

Also, please verify the following five classes with proper import

import org.junit.jupiter.api.Assertions;

import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;

import org.junit.jupiter.api.Order;

import org.junit.jupiter.api.Test;

import org.junit.jupiter.api.TestMethodOrder;


问:
Is there more to enumerate() than just zip(range(len()))?
Everything in Python is there for a reason. All systems powered by Python depend on something like 50 built-in functions, most of which are extremely useful and unique, like format(), len(), list(), or range(). I can't understand why enumerate() exists.

It's been introduced in PEP 279 (2002) and was kept until now. I really don't understand why it exists because it can be done using other more important built-in functions in 2-3 characters more. From the Python Docs:

```<code>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
</code>```

```<code>for i in enumerate(seasons):
    print(i)
</code>```

An implementation using more important built-in functions is this:

```<code>for i in zip(range(len(seasons)), seasons):
    print(i)
</code>```

```<code>[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
</code>```

These two are the same, and we all know how critically important zip() and range() are. So why add a built-in function that would seemingly add no value beyond these two?

In the Python Docs, here is the equivalent of enumerate():

```<code>def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1
</code>```

The bottom line: I'm wondering if enumerate() has some unique capabilities that I'm not seeing.

答:
I feel using itertools.count would be more appropriate here as an alternative to enumerate as enumerate doesn't need to know the length it only supplies next number and next object in it's iterations.

```<code>from itertools import count
for i, o in zip(count(), iterable):
    ...
</code>```

V.S

```<code>for i, o in enumerate(iterable):
    ...
</code>```

Besides, using len is adding another unnecessary operation. Although the inclusion of enumerate eliminates the need to import from a library for such simple needs.

Body:
Everything in Python is there for a reason. All systems powered by Python depend on something like 50 built-in functions, most of which are extremely useful and unique, like format(), len(), list(), or range(). I can't understand why enumerate() exists.

It's been introduced in PEP 279 (2002) and was kept until now. I really don't understand why it exists because it can be done using other more important built-in functions in 2-3 characters more. From the Python Docs:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

for i in enumerate(seasons):
    print(i)

An implementation using more important built-in functions is this:

for i in zip(range(len(seasons)), seasons):
    print(i)

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

These two are the same, and we all know how critically important zip() and range() are. So why add a built-in function that would seemingly add no value beyond these two?

In the Python Docs, here is the equivalent of enumerate():

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

The bottom line: I'm wondering if enumerate() has some unique capabilities that I'm not seeing.

Body:
I feel using itertools.count would be more appropriate here as an alternative to enumerate as enumerate doesn't need to know the length it only supplies next number and next object in it's iterations.

from itertools import count
for i, o in zip(count(), iterable):
    ...

V.S

for i, o in enumerate(iterable):
    ...

Besides, using len is adding another unnecessary operation. Although the inclusion of enumerate eliminates the need to import from a library for such simple needs.


问:
getting rxjs value in sync, is this an anti pattern?
I often find myself having to just get a value from the store and do something like this which seems like an anti pattern (side effect of remembering r) and wonder if there is a better way.

```<code>    getAssetName(i_page: IPager): string {
        let r = '';
        if (i_page.Player[0].$.src) {
            this.storeSelector.getScene(i_page.Player[0].$.src)
                .take(1)
                .subscribe((v) => {
                    r = v.Player.$.label;
                });
        } else {
            this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .take(1)
                .subscribe((v) => {
                    r = v.resource_name;
                });
        }
        return r;
    }
</code>```

in other words, a better way of getting value 'r' without having to closure it?

now, I am using Angular and am aware I can use 'async' as in

```<code>{{ getAssetName$(element.pager) | async | truncate:[maxStringSize]}}

this.getAssetName$ = this.getAssetName;

 getAssetName(i_page: IPager): Observable<string> {
        if (i_page.Player[0].$.src) {
            return this.storeSelector.getScene(i_page.Player[0].$.src)
                .map((v) => {
                    return v.Player.$.label;
                });
        } else {
            return this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .map((v) => {
                    return v.resource_name;
                });
        }
    }

</code>```

but trying to see if there is a way to do without async template method.
If I use the async without onPush template performance degradation is visible

Thanks,

Sean

答:
A few ways to go about this - below are three possible solutions.

Since you're only getting one result you can use .toPromise() as a cleaner way to convert the stream to return an async result.

```<code>async getAssetName(i_page: IPager): string {
  const assetSrc = (i_page.Player[0].$.src)
    ? this.storeSelector.getScene(i_page.Player[0].$.src).pipe(map(x => x.Player.$.label))
    : this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
      .pipe(map(x => x.resource_name));
  return await assetSrc.pipe(take(1)).toPromise();
}
</code>```

If you want to avoid the async entirely, and you want to get the name as part of constructing a bigger object, then that construction can cleanly be done within the stream itself.

```<code>template: MyTemplate;

private getAssetName$(i_page: IPager): Observable<string> {
  const assetSrc = (i_page.Player[0].$.src)
    ? this.storeSelector.getScene(i_page.Player[0].$.src).pipe(map(x => x.Player.$.label))
    : this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
       .pipe(map(x => x.resource_name));
  return assetSrc.pipe(take(1));
}

createTemplate(i_page: IPager, /* other stuff */) {
  // you can skip the fork join if you're just using one observable.
  forkJoin(this.getAssetName(i_page), /* other observables if necessary*/).pipe(
    subscribe(([assetName, /* other results */]) => {
      this.template = { assetName, /* other stuff */ };
    })
  );
}
</code>```

I am not a huge fan of doing this this way.  If possible, I'd make the template itself an observable.

To build the template I combine all the latest changes from all Observables that are needed for construction.  When the pager is changed, a subject is fired.  That subject is linked to the retrieval of the assetName in the combineLatest using switchMap.  When the result is retrieved the template$ Observable is updated with the latest result.

```<code>private pageChangeSubject = new Subject<IPager>();
// like forkJoin the combineLatest is only needed if multiple observables.
// getAssetName is the same method from the previous example.
template$: Observable<MyTemplate> = this.combineLatest(
    this.pageChangeSubject.pipe(switchMap(x => this.getAssetName(x)))
  ).pipe(map(([assetName, /* ... */]) => ({ assetName, /* ... */ })));

pageChanged(page: IPager) { this.pageChangeSubject.next(page); }
</code>```

Body:
I often find myself having to just get a value from the store and do something like this which seems like an anti pattern (side effect of remembering r) and wonder if there is a better way.

    getAssetName(i_page: IPager): string {
        let r = '';
        if (i_page.Player[0].$.src) {
            this.storeSelector.getScene(i_page.Player[0].$.src)
                .take(1)
                .subscribe((v) => {
                    r = v.Player.$.label;
                });
        } else {
            this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .take(1)
                .subscribe((v) => {
                    r = v.resource_name;
                });
        }
        return r;
    }

in other words, a better way of getting value 'r' without having to closure it?

now, I am using Angular and am aware I can use 'async' as in

{{ getAssetName$(element.pager) | async | truncate:[maxStringSize]}}

this.getAssetName$ = this.getAssetName;

 getAssetName(i_page: IPager): Observable<string> {
        if (i_page.Player[0].$.src) {
            return this.storeSelector.getScene(i_page.Player[0].$.src)
                .map((v) => {
                    return v.Player.$.label;
                });
        } else {
            return this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
                .map((v) => {
                    return v.resource_name;
                });
        }
    }

but trying to see if there is a way to do without async template method.
If I use the async without onPush template performance degradation is visible

Thanks,

Sean

Body:
A few ways to go about this - below are three possible solutions.

Since you're only getting one result you can use .toPromise() as a cleaner way to convert the stream to return an async result.

async getAssetName(i_page: IPager): string {
  const assetSrc = (i_page.Player[0].$.src)
    ? this.storeSelector.getScene(i_page.Player[0].$.src).pipe(map(x => x.Player.$.label))
    : this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
      .pipe(map(x => x.resource_name));
  return await assetSrc.pipe(take(1)).toPromise();
}

If you want to avoid the async entirely, and you want to get the name as part of constructing a bigger object, then that construction can cleanly be done within the stream itself.

template: MyTemplate;

private getAssetName$(i_page: IPager): Observable<string> {
  const assetSrc = (i_page.Player[0].$.src)
    ? this.storeSelector.getScene(i_page.Player[0].$.src).pipe(map(x => x.Player.$.label))
    : this.storeSelector.getResource(i_page.Player[0].Data[0].Resource[0].$.resource)
       .pipe(map(x => x.resource_name));
  return assetSrc.pipe(take(1));
}

createTemplate(i_page: IPager, /* other stuff */) {
  // you can skip the fork join if you're just using one observable.
  forkJoin(this.getAssetName(i_page), /* other observables if necessary*/).pipe(
    subscribe(([assetName, /* other results */]) => {
      this.template = { assetName, /* other stuff */ };
    })
  );
}

I am not a huge fan of doing this this way.  If possible, I'd make the template itself an observable.

To build the template I combine all the latest changes from all Observables that are needed for construction.  When the pager is changed, a subject is fired.  That subject is linked to the retrieval of the assetName in the combineLatest using switchMap.  When the result is retrieved the template$ Observable is updated with the latest result.

private pageChangeSubject = new Subject<IPager>();
// like forkJoin the combineLatest is only needed if multiple observables.
// getAssetName is the same method from the previous example.
template$: Observable<MyTemplate> = this.combineLatest(
    this.pageChangeSubject.pipe(switchMap(x => this.getAssetName(x)))
  ).pipe(map(([assetName, /* ... */]) => ({ assetName, /* ... */ })));

pageChanged(page: IPager) { this.pageChangeSubject.next(page); }


问:
Passing state variable to child component via localStorage
I'm trying to pass the state variable 'atoken' which holds an access token, to the child component 'Home' via localStorage, but when I try, localStorage.getItem(this.props.atoken) in the 'Home' component, an undefined value will show in the console. How can I properly pass this state variable (atoken) from the 'App' component to the 'Home' component?

```<code>import React, { Component } from 'react';
import Playlist from './components/playlist';
import Home from './components/Home';
import {
    BrowserRouter as Router,
    Route,
} from 'react-router-dom';

var Spotify = require('spotify-web-api-js');
var spotifyApi = new Spotify();

class App extends Component {
  constructor(props){
    super(props);
    const params = this.getHashParams(); //tokens saved here
    const token = params.access_token;
    if (token) {
      spotifyApi.setAccessToken(token);
    }
    this.state = {
      loggedIn: token ? true : false,
      atoken: token, //access token
    };
    window.localStorage.setItem(this.state.atoken, spotifyApi.getAccessToken());
    console.log(window.localStorage.getItem(this.state.atoken));
  }

    getHashParams() { //uses authenticated users refresh and access token
      var hashParams = {};
      var e, r = /([^&;=]+)=?([^&;]*)/g,
          q = window.location.hash.substring(1);
      e = r.exec(q)
      while (e) {
         hashParams[e[1]] = decodeURIComponent(e[2]);
         e = r.exec(q);
      }
      return hashParams;
  }

  render() {
    return (
      <Router>
        <div className='App'>
          <Route exact path = '/'  component= {Home}/>
          <Route path= '/playlist' component = {Playlist}/>
        </div>
      </Router>

    );
  }
}
export default App;
</code>```

In the class 'Home', the state variable 'atoken' is not retrieving the access token from the parent component 'App'.

```<code>import React, { Component } from 'react';
import './App.css';

var Spotify = require('spotify-web-api-js');
var spotifyApi = new Spotify();

class Home extends Component {
  constructor(props){
    super(props);
    this.state = {
      year: ' ',
      atoken: window.localStorage.getItem(this.props.atoken), //access token
    };
    console.log(this.state.atoken);

    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateInput = this.updateInput.bind(this);
  }

  handleSubmit(event){
    alert("Year Submitted");
    this.props.history.push({
      pathname: '/playlist',
      state: {year: this.state.year, atoken: this.state.atoken},
    });
    event.preventDefault();
  }

  updateInput(event){
    this.setState({year : event.target.value})
  }

  render() {
    return (
        <div id="body" className="Home">
            <div>
              <form onSubmit={this.handleSubmit}>
                <input id = "yearInput" autoComplete="off" type="text" placeholder = "Enter Year" onChange={this.updateInput} />
              </form>
            </div>
            <div id ="logout">
              <a href='http://localhost:8888' >
                  <button id="logout_btn"> Logout </button>
              </a>
            </div>
        </div>

    );
  }
}
export default Home;
</code>```

答:
So the issue is how you are trying to use local storage. When setting local storage, it takes two variables. The first is the unique name of the item you want to store and the second is the value. So when you are calling setItem it should be localStorage.setItem('name',value). Right now you are trying to pass two seperate tokens to storage.  you would be doing.

```<code>  window.localStorage.setItem('mySpotifyToken', spotifyApi.getAccessToken())
  window.localStorage.setItem('otherTokenName', this.state.atoken)
</code>```

Then you can access them in your home class by calling:

```<code>  window.localStorage.getItem('mySpotifyToken')
  window.localStorage.getItem('otherTokenName')
</code>```

In your class Home, you are calling this.props.atoken, but you are not passing in anything via props so it will be undefined.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Body:
I'm trying to pass the state variable 'atoken' which holds an access token, to the child component 'Home' via localStorage, but when I try, localStorage.getItem(this.props.atoken) in the 'Home' component, an undefined value will show in the console. How can I properly pass this state variable (atoken) from the 'App' component to the 'Home' component?

import React, { Component } from 'react';
import Playlist from './components/playlist';
import Home from './components/Home';
import {
    BrowserRouter as Router,
    Route,
} from 'react-router-dom';

var Spotify = require('spotify-web-api-js');
var spotifyApi = new Spotify();

class App extends Component {
  constructor(props){
    super(props);
    const params = this.getHashParams(); //tokens saved here
    const token = params.access_token;
    if (token) {
      spotifyApi.setAccessToken(token);
    }
    this.state = {
      loggedIn: token ? true : false,
      atoken: token, //access token
    };
    window.localStorage.setItem(this.state.atoken, spotifyApi.getAccessToken());
    console.log(window.localStorage.getItem(this.state.atoken));
  }

    getHashParams() { //uses authenticated users refresh and access token
      var hashParams = {};
      var e, r = /([^&;=]+)=?([^&;]*)/g,
          q = window.location.hash.substring(1);
      e = r.exec(q)
      while (e) {
         hashParams[e[1]] = decodeURIComponent(e[2]);
         e = r.exec(q);
      }
      return hashParams;
  }

  render() {
    return (
      <Router>

          <Route exact path = '/'  component= {Home}/>
          <Route path= '/playlist' component = {Playlist}/>

      </Router>

    );
  }
}
export default App;

In the class 'Home', the state variable 'atoken' is not retrieving the access token from the parent component 'App'.

import React, { Component } from 'react';
import './App.css';

var Spotify = require('spotify-web-api-js');
var spotifyApi = new Spotify();

class Home extends Component {
  constructor(props){
    super(props);
    this.state = {
      year: ' ',
      atoken: window.localStorage.getItem(this.props.atoken), //access token
    };
    console.log(this.state.atoken);

    this.handleSubmit = this.handleSubmit.bind(this);
    this.updateInput = this.updateInput.bind(this);
  }

  handleSubmit(event){
    alert("Year Submitted");
    this.props.history.push({
      pathname: '/playlist',
      state: {year: this.state.year, atoken: this.state.atoken},
    });
    event.preventDefault();
  }

  updateInput(event){
    this.setState({year : event.target.value})
  }

  render() {
    return (

              <form onSubmit={this.handleSubmit}>
                <input id = "yearInput" autoComplete="off" type="text" placeholder = "Enter Year" onChange={this.updateInput} />
              </form>

                  <button id="logout_btn"> Logout </button>

    );
  }
}
export default Home;

Body:
So the issue is how you are trying to use local storage. When setting local storage, it takes two variables. The first is the unique name of the item you want to store and the second is the value. So when you are calling setItem it should be localStorage.setItem('name',value). Right now you are trying to pass two seperate tokens to storage.  you would be doing.

  window.localStorage.setItem('mySpotifyToken', spotifyApi.getAccessToken())
  window.localStorage.setItem('otherTokenName', this.state.atoken)

Then you can access them in your home class by calling:

  window.localStorage.getItem('mySpotifyToken')
  window.localStorage.getItem('otherTokenName')

In your class Home, you are calling this.props.atoken, but you are not passing in anything via props so it will be undefined.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage


问:
How do I make my pagination show in Django template?
Goodday everyone. I want to add pagination to my home page ('index.html'). I followed the documentation of Django for pagination but I added Bootstrap's pagination to it to give a beautiful outlook.

However, it does show on my home page.

Here is the index.html code

```<code><div class="row">
            <div class="col-md-12">
                {% if post.has_other_pages %}
                    <ul class="pagination">
                        {% if post.has_previous%}
                            <li class="page-item">
                                <a href="?page={{post.previous_page_number}}" class="page-link">«
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link">«</a>
                            </li>
                        {% endif %}
                        {% for i in post.paginator.page_range %}
                            {% if post.number == i %}
                                <li class="page-item active">
                                    <a class="page-link">{{i}}</a>
                                </li>
                            {% else %}
                                <li class="page-item">
                                    <a href="?page={{i}}"class="page-link">{{i}}</a>
                                </li>
                            {% endif %}
                        {% endfor %}
                        {% if post.has_next%}
                            <li class="page-item">
                                <a href="?page={{post.next_page_number}}" class="page-link">»
                                </a>
                            </li>
                        {% else %}
                            <li class="page-item disabled">
                                <a class="page-link">»</a>
                            </li>
                        {% endif %}
                    </ul>
                {% endif %}
            </div>

    </div>
</code>```

This is the protion that contains the pagination.
Here is my views.index

```<code>def index(request):
    post = Post.objects.all()
    paginator = Paginator(post, 3)
    page = request.GET.get('page')
    page_post = paginator.get_page(page)

    context = {
        'post': page_post
    }
    return render(request, 'blog/index.html', context)
</code>```

What am I doing wrong please?

答: I fixed this by posting about 6 articles from the backend instead of the three (I had initially) since I want to show just 3 articles per page. On saving this and running my server again, the pagination worked.</p>

Body:
Goodday everyone. I want to add pagination to my home page ('index.html'). I followed the documentation of Django for pagination but I added Bootstrap's pagination to it to give a beautiful outlook.

However, it does show on my home page.

Here is the index.html code

                {% if post.has_other_pages %}

                        {% if post.has_previous%}

                                «

                        {% else %}

                                «

                        {% endif %}
                        {% for i in post.paginator.page_range %}
                            {% if post.number == i %}

                                    {{i}}

                            {% else %}

                                    {{i}}

                            {% endif %}
                        {% endfor %}
                        {% if post.has_next%}

                                »

                        {% else %}

                                »

                        {% endif %}

                {% endif %}

This is the protion that contains the pagination.
Here is my views.index

def index(request):
    post = Post.objects.all()
    paginator = Paginator(post, 3)
    page = request.GET.get('page')
    page_post = paginator.get_page(page)

    context = {
        'post': page_post
    }
    return render(request, 'blog/index.html', context)

What am I doing wrong please?


问:
Python : Memory consumption accumulating in a while loop
A confession first - a noob programmer here doing occasional scripting. I've been trying to figure the memory consumption for this simple piece of code but unable to figure this out. I have tried searching in the answered questions, but couldn't figure it out. I'm fetching some json data using REST API, and the piece of code below ends up consuming a lot of RAM. I checked the Windows task manager and the memory consumption increases incrementally with each iteration of the loop. I'm overwriting the same variable for each API call, so I think the previous response variable should be overwritten.

```<code>while Flag == True:
        urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
        response = json.loads(obj1.get_request(urlpart))
        lstDataList = lstDataList + response['data']
        Flag = response['pageInfo']['hasMoreData']
        varScrollId = response['pageInfo']['scrollId']
        count += 1
        print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
        print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
    return lstDataList
</code>```

I tried to profile memory usage using memory_profiler...here's what it shows

```<code>    92  119.348 MiB    0.000 MiB       count = 0
    93  806.938 MiB    0.000 MiB       while Flag == True:
    94  806.938 MiB    0.000 MiB           urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
    95  807.559 MiB   30.293 MiB           response = json.loads(obj1.get_request(urlpart))
    96  806.859 MiB    0.000 MiB           print('Size of response within the loop  is {}'.format(sys.getsizeof(response)))
    97  806.938 MiB    1.070 MiB           lstDataList = lstDataList + response['data']
    98  806.938 MiB    0.000 MiB           Flag = response['pageInfo']['hasMoreData']
    99  806.938 MiB    0.000 MiB           varScrollId = response['pageInfo']['scrollId']
   100  806.938 MiB    0.000 MiB           count += 1
   101  806.938 MiB    0.000 MiB           print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
   102  806.938 MiB    0.000 MiB           print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
   103                                 return lstDataList

</code>```

obj1 is an object of Cisco's rest_api_lib class. Link to code here

In fact the program ends up consuming ~1.6 Gigs of RAM. The data I'm fetching has roughly 570K records. The API limits the records to 10K at a time, so the loop runs ~56 times. Line 95 of the code consumes ~30M of RAM as per the memory_profiler output. It's as if each iteration consumes 30M ending u with ~1.6G, so in the same ballpark. Unable to figure out why the memory consumption keeps on accumulating for the loop.
Thanks.

答:
I would suspect it is the line lstDataList = lstDataList + response['data']

This is accumulating response['data'] over time. Also, your indentation seems off, should it be:

```<code>while Flag == True:
    urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
    response = json.loads(obj1.get_request(urlpart))
    lstDataList = lstDataList + response['data']
    Flag = response['pageInfo']['hasMoreData']
    varScrollId = response['pageInfo']['scrollId']
    count += 1
    print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
    print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
return lstDataList
</code>```

As far as I can tell, lstDataList will keep growing with each request, leading to the memory increase. Hope that helps, Happy Friday!

Body:
A confession first - a noob programmer here doing occasional scripting. I've been trying to figure the memory consumption for this simple piece of code but unable to figure this out. I have tried searching in the answered questions, but couldn't figure it out. I'm fetching some json data using REST API, and the piece of code below ends up consuming a lot of RAM. I checked the Windows task manager and the memory consumption increases incrementally with each iteration of the loop. I'm overwriting the same variable for each API call, so I think the previous response variable should be overwritten.

while Flag == True:
        urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
        response = json.loads(obj1.get_request(urlpart))
        lstDataList = lstDataList + response['data']
        Flag = response['pageInfo']['hasMoreData']
        varScrollId = response['pageInfo']['scrollId']
        count += 1
        print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
        print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
    return lstDataList

I tried to profile memory usage using memory_profiler...here's what it shows

    92  119.348 MiB    0.000 MiB       count = 0
    93  806.938 MiB    0.000 MiB       while Flag == True:
    94  806.938 MiB    0.000 MiB           urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
    95  807.559 MiB   30.293 MiB           response = json.loads(obj1.get_request(urlpart))
    96  806.859 MiB    0.000 MiB           print('Size of response within the loop  is {}'.format(sys.getsizeof(response)))
    97  806.938 MiB    1.070 MiB           lstDataList = lstDataList + response['data']
    98  806.938 MiB    0.000 MiB           Flag = response['pageInfo']['hasMoreData']
    99  806.938 MiB    0.000 MiB           varScrollId = response['pageInfo']['scrollId']
   100  806.938 MiB    0.000 MiB           count += 1
   101  806.938 MiB    0.000 MiB           print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
   102  806.938 MiB    0.000 MiB           print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
   103                                 return lstDataList

obj1 is an object of Cisco's rest_api_lib class. Link to code here

In fact the program ends up consuming ~1.6 Gigs of RAM. The data I'm fetching has roughly 570K records. The API limits the records to 10K at a time, so the loop runs ~56 times. Line 95 of the code consumes ~30M of RAM as per the memory_profiler output. It's as if each iteration consumes 30M ending u with ~1.6G, so in the same ballpark. Unable to figure out why the memory consumption keeps on accumulating for the loop.
Thanks.

Body:
I would suspect it is the line lstDataList = lstDataList + response['data']

This is accumulating response['data'] over time. Also, your indentation seems off, should it be:

while Flag == True:
    urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
    response = json.loads(obj1.get_request(urlpart))
    lstDataList = lstDataList + response['data']
    Flag = response['pageInfo']['hasMoreData']
    varScrollId = response['pageInfo']['scrollId']
    count += 1
    print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
    print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
return lstDataList

As far as I can tell, lstDataList will keep growing with each request, leading to the memory increase. Hope that helps, Happy Friday!


问:
Java game development - Look and shoot at mouse coordinates
I'm going to make a game where you run around with a character, seen from above. But the problem is how do I make the character look at the mouse all the time? And how do I calculate the angle so that I can shoot towards the mouse(where I'm currently looking). I guess you have to play around with trigonometry and stuff like that to get angles, but I really don't know how.

I'm pretty good at math, so I might figure it out if you guys give me some help.

And sorry for my eventually bad english, I'm swedish :)

Thanks,
Alexandberg

答:
```<code>double angle = Math.atan2(yMouse-yChar, xMouse-xChar);
</code>```