问:
how do I connect my backend flask micro services with my frontend flask code?
I am working on someone else's code. I need to debug and resolve issue. I have pretty good experience with backend but zero knowledge on front-end. I believe his code is full stack code which includes front-end and backend micro-services implemented using flask. I need to connect his front end code with backend one. backend works fine. I have already verified. However, not sure what's wrong in his code which connects backend and reflects output in web browser. Below is his code :

#backend flask (works totally fine)-
from flask import Flask
import os, sys
from drivers.snapshot.snapshot_service import SnapshotService
from drivers.comparison.comparison_service import ComparisonService
import json

os.environ['JSNAPY_HOME'] = sys.path[0]

app = Flask(__name__)
@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

@app.route("/")
def hello():
    return "Initiate App!"

@app.route('/snapshot/<hostname>')
def snapshot(hostname):
    return SnapshotService().snapshot(hostname)

#frontend flask
from flask import Flask, render_template, redirect

app = Flask(__name__)

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

@app.route('/')
def index():
    return redirect('/snapshot/')

@app.route('/snapshot/')
def view_snap():
    return render_template('snap.html')```
<pre class="snippet-code-html lang-html prettyprint-override"><code>{% extends 'base.html' %}
{% block content %}
<div class="row">

    <div class="col-sm-6 col-sm-offset-3">
        <!-- general form elements -->
        <div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">Snapshot</h3>
            </div>
            <!-- /.box-header -->
            <!-- form start -->
            <form role="form">
                <div class="box-body">
                    <div class="form-group">
                        <input type="text" class="form-control" id="hostname" value="ASBNVAEG1CW" placeholder="Hostname/IP">
                    </div>

                    <button type="submit" id="submit_snap_button" class="btn btn-primary btn-block"><i class="fa fa-camera"></i> Snap</button>
                </div>
            </form>
            <div id="div_result" class="alert alert-success" style="display: none;">
                <div id="div_result_msg" class="text-center"></div>
            </div>
        </div>
        <!-- /.box -->
    </div>
</div>

{% endblock %}

{% block page_javascript %}
<script>
$(document).ready(function() {
    $('#submit_snap_button').click(function(e) {
        $('#submit_snap_button').html('<i class="fa fa-refresh fa-spin"></i>');
        $('#submit_snap_button').attr("disabled", true);
        $('#div_result').hide();
        $.getJSON("http://molab-backend:5000/snapshot/" + $('#hostname').val(), function(data) {
            $('#div_result_msg').html(data.message);
            if (data.success === 0) {
                $('#div_result').addClass('alert-danger').removeClass('alert-success')
            }
            else {
                $('#div_result').addClass('alert-success').removeClass('alert-danger')
            }

            $('#div_result').show();
            $('#submit_snap_button').attr("disabled", false);
            $('#submit_snap_button').html('<i class="fa fa-camera"></i> Snap');

        }, function() {

        }, 'json');
        e.preventDefault();
    });

})
</script>
{% endblock %}</code>```

答:
Whenever the HTML element with id '#submit_snap_button' is clicked, this jquery piece of code makes a request to your 'snapshot' route:

```<code>$.getJSON("http://molab-backend:5000/snapshot/" + $('#hostname').val(), function(data) {
        $('#div_result_msg').html(data.message);
        if (data.success === 0) {
            $('#div_result').addClass('alert-danger').removeClass('alert-success')
        }
        else {
            $('#div_result').addClass('alert-success').removeClass('alert-danger')
        }

        $('#div_result').show();
        $('#submit_snap_button').attr("disabled", false);
        $('#submit_snap_button').html('<i class="fa fa-camera"></i> Snap');
}
</code>```

If the request is successful, it adds the class 'alert-danger' and removes the class 'alert-success' from the element with id '#div_result'. If the request is not successful it does the opposite.

Then it makes the element with id '#div_result' visible.

It then changes the attribute 'disabled' of the element with id '#submit_snap_button' to false, and the HTML to ' Snap'

Your route should return a json file to be accessed by the front end.

```<code>@app.route('/snapshot/<hostname>')
def snapshot(hostname):
        return SnapshotService().snapshot(hostname)
</code>```

Body:
I am working on someone else's code. I need to debug and resolve issue. I have pretty good experience with backend but zero knowledge on front-end. I believe his code is full stack code which includes front-end and backend micro-services implemented using flask. I need to connect his front end code with backend one. backend works fine. I have already verified. However, not sure what's wrong in his code which connects backend and reflects output in web browser. Below is his code :

#backend flask (works totally fine)-
from flask import Flask
import os, sys
from drivers.snapshot.snapshot_service import SnapshotService
from drivers.comparison.comparison_service import ComparisonService
import json

os.environ['JSNAPY_HOME'] = sys.path[0]

app = Flask(__name__)
@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

@app.route("/")
def hello():
    return "Initiate App!"

@app.route('/snapshot/<hostname>')
def snapshot(hostname):
    return SnapshotService().snapshot(hostname)

#frontend flask
from flask import Flask, render_template, redirect

app = Flask(__name__)

@app.after_request
def after_request(response):
  response.headers.add('Access-Control-Allow-Origin', '*')
  response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
  response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
  return response

@app.route('/')
def index():
    return redirect('/snapshot/')

@app.route('/snapshot/')
def view_snap():
    return render_template('snap.html')

{% extends 'base.html' %}
{% block content %}

Snapshot

            <form role="form">

                        <input type="text" class="form-control" id="hostname" value="ASBNVAEG1CW" placeholder="Hostname/IP">

                    <button type="submit" id="submit_snap_button" class="btn btn-primary btn-block"> Snap</button>

            </form>

{% endblock %}

{% block page_javascript %}

{% endblock %}

Body:
Whenever the HTML element with id '#submit_snap_button' is clicked, this jquery piece of code makes a request to your 'snapshot' route:

$.getJSON("http://molab-backend:5000/snapshot/" + $('#hostname').val(), function(data) {
        $('#div_result_msg').html(data.message);
        if (data.success === 0) {
            $('#div_result').addClass('alert-danger').removeClass('alert-success')
        }
        else {
            $('#div_result').addClass('alert-success').removeClass('alert-danger')
        }

        $('#div_result').show();
        $('#submit_snap_button').attr("disabled", false);
        $('#submit_snap_button').html('<i class="fa fa-camera"></i> Snap');
}

If the request is successful, it adds the class 'alert-danger' and removes the class 'alert-success' from the element with id '#div_result'. If the request is not successful it does the opposite.

Then it makes the element with id '#div_result' visible.

It then changes the attribute 'disabled' of the element with id '#submit_snap_button' to false, and the HTML to '<i class="fa fa-camera"></i> Snap'

Your route should return a json file to be accessed by the front end.

@app.route('/snapshot/<hostname>')
def snapshot(hostname):
        return SnapshotService().snapshot(hostname)


来源: stackexchange

问:
HTTP 500 error launcing ASP.NET 3.0 application
I have just upgraded our ASP.NET Core 2.2 web application to 3.0. It builds and deploys fine. The problem is when I go to run it from our IIS server. This was running perfectly fine as a Core 2.2 web app, but now fails since upgrading to Core 3.0.

When I launch the web app from the commandline there are no reported errors.

When I launch the application from the browser the Windows logs indicate that the app started correctly.

The app then fails with an HTTP 500 error. Here are the IIS log entries.

We're using Windows Server 2012 R2 with IIS 8.5.9600.16384

The app appears to start correctly but then fails with an HTTP 500 error. Has anyone else seen this or something similar? Any ideas how to diagnose / fix the problem?

UPDATE

I've attached the VS 2019 debugger to the deployed app via the w3wp.exe process and it's not even hitting any of the middleware (I have a breakpoint at Startup() in Startup.cs).

I've tried changing the application pool settings e.g. identity, .NET version but to no avail.

When I launch the site from the web server I get the following error message which doesn't really tell me anything.

I can't see what's causing the problem.

答:
You will check web.config "aspNetCore"

```<code><aspNetCore processPath="dotnet" arguments=".\Api.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
</code>```

maybe proccessPath is wrong.

if it doesn't solve  problem , write to log step step startup.cs.
Maybe throw error in startup.cs

ContentLicense: CC BY-SA 4.0

Body:
You will check web.config "aspNetCore"

<aspNetCore processPath="dotnet" arguments=".\Api.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

maybe proccessPath is wrong.

if it doesn't solve  problem , write to log step step startup.cs.
Maybe throw error in startup.cs


问:
How can I add two Vector3's together in unity
I am making a 2d shooter game. I have a Gameobject that is "Gun" when the Player Gameobject touches the gun it goes to the position of the player. However, I then would like to move the gun from that position on the player sprite to the sprits hand. I thought that the easiest method to do this would be to add a Vector on to the starting vector, to change the coordinates of the gun. However I am not sure how to add the vectors, this is what I have tried but it comes up with the error: 'Vector3' cannot be used as a method.  </p>

```<code>Vector3 coords = GameObject.FindGameObjectWithTag("Gun").transform.position = GameObject.FindGameObjectWithTag("Player").transform.position;
Vector3 newcoords = coords + Vector3(1, 1, 0)
</code>```

答:
The easiest way to do it is (given that your player is properly defined as a tree structure, head, torso, hand etc), is to assign to the weapon's the local position of the hand, or even better to put the weapon as a child node of your hand. Therefore when you'll make any changes within hand, transformation, rotation etc your weapon will react accordingly. Just find "hand" within your player's structure and then assign to "weapon.parent = hand" (that's pseudocode of course, but you know the gist).
Of course if your weapon had a world's position already assigned, after making it child of player's hand you will have to set the weapon.position again, relative to position of the hand (you can set it up to Vector3.zero and see what you'll get as a result)

Body:
I am making a 2d shooter game. I have a Gameobject that is "Gun" when the Player Gameobject touches the gun it goes to the position of the player. However, I then would like to move the gun from that position on the player sprite to the sprits hand. I thought that the easiest method to do this would be to add a Vector on to the starting vector, to change the coordinates of the gun. However I am not sure how to add the vectors, this is what I have tried but it comes up with the error: 'Vector3' cannot be used as a method.

Vector3 coords = GameObject.FindGameObjectWithTag("Gun").transform.position = GameObject.FindGameObjectWithTag("Player").transform.position;
Vector3 newcoords = coords + Vector3(1, 1, 0)


问:
Save model as h5 / Save model as .ckpt
i have had big troubles today with saving formats while training a style-transfer neural network.

The task is already solved  i feel, i only need to save my model and load it again. But i can't find a proper way to do it.

I used the following code from github to train a style-transfer network:

https://github.com/nikhilagrawal2000/Neural-Style-Transfer-with-Eager-Execution/blob/master/Neural_Style_Transfer_with_Eager_Execution.ipynb

I already succesfully trained the network.

Now, i saved the model using the following line:

```<code>model.save("/tmp/nst/test.h5")
</code>```

For applying the saved neural network though, i need to use the network in a .ckpt format.

Can someone tell me how to switch the data formats between h5 and .ckpt ?

Or is there a specific save method for keras, so i can save it as .ckpt?
(--> pseudocode: model.save_cpkt("/tmp/nst/test.ckpt")

Would be extremely happy if someone could explain that to me, i tried it for several hours now without success.

答:
You can save the weights in checkpoint format using:

```<code>model.save_weights("modelcheckpoint",save_format="tf")
</code>```

You can read more about saving weights or models and chepoints here

Title: Save model as h5 / Save model as .ckpt

Body:
i have had big troubles today with saving formats while training a style-transfer neural network.

The task is already solved  i feel, i only need to save my model and load it again. But i can't find a proper way to do it.

I used the following code from github to train a style-transfer network:

https://github.com/nikhilagrawal2000/Neural-Style-Transfer-with-Eager-Execution/blob/master/Neural_Style_Transfer_with_Eager_Execution.ipynb

I already succesfully trained the network.

Now, i saved the model using the following line:

model.save("/tmp/nst/test.h5")

For applying the saved neural network though, i need to use the network in a .ckpt format.

Can someone tell me how to switch the data formats between h5 and .ckpt ?

Or is there a specific save method for keras, so i can save it as .ckpt?
(--> pseudocode: model.save_cpkt("/tmp/nst/test.ckpt")

Would be extremely happy if someone could explain that to me, i tried it for several hours now without success.

Body:
You can save the weights in checkpoint format using:

model.save_weights("modelcheckpoint",save_format="tf")

You can read more about saving weights or models and chepoints here


问:
In a recursive python function, how is the line of code reached, that comes after the line of code which calls itself
this is my code that I copied from the sudoku solver video computerphile made:

grid = [ [4, 0, 0, 0, 0, 5, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 9, 8],
[3, 0, 0, 0, 8, 2, 4, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 8, 0],
[9, 0, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 3, 0, 6, 7, 0],
[0, 5, 0, 0, 0, 9, 0, 0, 0],
[0, 0, 0, 2, 0, 0, 9, 0, 7],
[6, 4, 0, 3, 0, 0, 0, 0, 0], ]

def possible(x, y, n):
    for i in range(0, 9):
        if grid[i][x] == n and i != y:
            return False
    for i in range(0, 9):
        if grid[y][i] == n and i != x:
            return False
    x0 = (x // 3) * 3
    y0 = (y // 3) * 3
    for X in range(x0, x0 + 3):
        for Y in range(y0, y0 + 3):
            if grid[Y][X] == n:
                return False
    return True

def Print(matrix):
    for i in range(9):
        print(matrix[i])

def solve():
    global grid
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                for n in range(1, 10):
                    if possible(x, y, n):
                        grid[y][x] = n
                        solve()
                        grid[y][x] = 0
                return
    Print(grid)
    input("")

solve()
```

I want to know how the grid[y][x] = 0 located inside the solve() function ever gets reached? Wouldn't Python go back to the beginning of the solve() function every time it reaches the line above, which is solve()?

So how does the function solve() run?

答:
somewhere in solving the puzzle the answer to possible(x, y, n) will be false for every instance of the for-loop, in this case the code jumps to return statement for solve method. in this time, the program runs the grid[y][x] = 0 part!

you can see more example of recursive functions here.

Body:
this is my code that I copied from the sudoku solver video computerphile made:

grid = [ [4, 0, 0, 0, 0, 5, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 9, 8],
[3, 0, 0, 0, 8, 2, 4, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 8, 0],
[9, 0, 3, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 3, 0, 6, 7, 0],
[0, 5, 0, 0, 0, 9, 0, 0, 0],
[0, 0, 0, 2, 0, 0, 9, 0, 7],
[6, 4, 0, 3, 0, 0, 0, 0, 0], ]

def possible(x, y, n):
    for i in range(0, 9):
        if grid[i][x] == n and i != y:
            return False
    for i in range(0, 9):
        if grid[y][i] == n and i != x:
            return False
    x0 = (x // 3) * 3
    y0 = (y // 3) * 3
    for X in range(x0, x0 + 3):
        for Y in range(y0, y0 + 3):
            if grid[Y][X] == n:
                return False
    return True

def Print(matrix):
    for i in range(9):
        print(matrix[i])

def solve():
    global grid
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                for n in range(1, 10):
                    if possible(x, y, n):
                        grid[y][x] = n
                        solve()
                        grid[y][x] = 0
                return
    Print(grid)
    input("")

solve()

I want to know how the grid[y][x] = 0 located inside the solve() function ever gets reached? Wouldn't Python go back to the beginning of the solve() function every time it reaches the line above, which is solve()?

So how does the function solve() run?


问:
Changing formulas on the fly with VBA RegEx
i'm trying to change formulas in excel, i need to change the row number of the formulas.

I'm trying do use replace regex to do this. I use an loop to iterate through the rows of the excel and need to change the formula for the row that is iterating at the time. Here is an exemple of the code:

```<code>    For i = 2 To rows_aux
            DoEvents

            Formula_string= "=IFS(N19='Z001';'xxxxxx';N19='Z007';'xxxxxx';0=0;'xxxxxxx')"
            Formula_string_new = regEx.Replace(Formula_string, "$1" & i)
            wb.Cells(i, 33) = ""
            wb.Cells(i, 33).Formula = Formula_string_new
      .
      .
      .
   Next i
</code>```

I need to replace rows references but not the ones in quotes or double quotes. Example:
If i = 2 i want the new string to be this:

```<code>"=IFS(N2='Z001';'xxxxxx';N2='Z007';'xxxxxx';0=0;'xxxxxxx')"
</code>```

I'm trying to use this regex:

```<code>([a-zA-Z]+)(\d+)
</code>```

But its changing everything in quotes too. Like this:
If i = 2:

```<code>"=IFS(N2='Z2';'xxxxxx';N2='Z2';'xxxxxx';0=0;'xxxxxxx')"
</code>```

If anyone can help me i will be very grateful!
Thanks in advance.

答:
If you can identify some unique features like in the example preceding bracket ( or colon ; and trailing equal = then this might work</p>

```<code>Sub test()
    Dim s As String, sNew As String, i As Long

    Dim Regex As Object
    Set Regex = CreateObject("vbscript.regexp")
    With Regex
      .Global = True
      .MultiLine = False
      .IgnoreCase = True
      .Pattern = "([(;][a-zA-Z]{1,3})(\d+)="
    End With

    i = 1
    s = "=IFS(NANA19='Z001';'xxxxxx';NA19='Z007';'xxxxxx';0=0;'xxxxxxx')"
    sNew = Regex.Replace(s, "$1" & i & "=")

    Debug.Print s & vbCr & sNew

End Sub
</code>```

Body:
i'm trying to change formulas in excel, i need to change the row number of the formulas.

I'm trying do use replace regex to do this. I use an loop to iterate through the rows of the excel and need to change the formula for the row that is iterating at the time. Here is an exemple of the code:

    For i = 2 To rows_aux
            DoEvents

            Formula_string= "=IFS(N19='Z001';'xxxxxx';N19='Z007';'xxxxxx';0=0;'xxxxxxx')"
            Formula_string_new = regEx.Replace(Formula_string, "$1" & i)
            wb.Cells(i, 33) = ""
            wb.Cells(i, 33).Formula = Formula_string_new
      .
      .
      .
   Next i

I need to replace rows references but not the ones in quotes or double quotes. Example:
If i = 2 i want the new string to be this:

"=IFS(N2='Z001';'xxxxxx';N2='Z007';'xxxxxx';0=0;'xxxxxxx')"

I'm trying to use this regex:

([a-zA-Z]+)(\d+)

But its changing everything in quotes too. Like this:
If i = 2:

"=IFS(N2='Z2';'xxxxxx';N2='Z2';'xxxxxx';0=0;'xxxxxxx')"

If anyone can help me i will be very grateful!
Thanks in advance.

Body:
If you can identify some unique features like in the example preceding bracket ( or colon ; and trailing equal = then this might work

Sub test()
    Dim s As String, sNew As String, i As Long

    Dim Regex As Object
    Set Regex = CreateObject("vbscript.regexp")
    With Regex
      .Global = True
      .MultiLine = False
      .IgnoreCase = True
      .Pattern = "([(;][a-zA-Z]{1,3})(\d+)="
    End With

    i = 1
    s = "=IFS(NANA19='Z001';'xxxxxx';NA19='Z007';'xxxxxx';0=0;'xxxxxxx')"
    sNew = Regex.Replace(s, "$1" & i & "=")

    Debug.Print s & vbCr & sNew

End Sub


问:
Generate random 128 bit decimal in given range in go
Let's say that we have a random number generator that can generate random 32 or 64 bit integers (like rand.Rand in the standard library)

Generating a random int64 in a given range [a,b] is fairly easy:

```<code>rand.Seed(time.Now().UnixNano())
n := rand.Int63n(b-a) + a
</code>```

Is it possible to generate random 128 bit decimal (as defined in specification IEEE 754-2008) in a given range from a combination of 32 or 64 bit random integers?

答: This is definitely what you are looking for.</p>

Body:
Let's say that we have a random number generator that can generate random 32 or 64 bit integers (like rand.Rand in the standard library)

Generating a random int64 in a given range [a,b] is fairly easy:

rand.Seed(time.Now().UnixNano())
n := rand.Int63n(b-a) + a

Is it possible to generate random 128 bit decimal (as defined in specification IEEE 754-2008) in a given range from a combination of 32 or 64 bit random integers?


问:
jQuery.Popup is not a constructor & Query is not defined(anonymous function)
I've come to the tail end of a module I'm creating for Magento 2 but I'm having trouble getting it to render on the screen. This code has worked on other sites in the past but there seems to be an issue stopping this one from working. The issue seems to be with my code "var popup = new jQuery.Popup(poOptions);" note being recognized as a constructor.

I read through a few similar posts (like this one WOW is not a constructor) but I can't seem to figure out what the issue is still

The jquery plugin I'm utilizing originates from https://github.com/Toddish/Popup, on our website page here https://76a8q06e6vrsbggs.mojostratus.io/catalog/product/view/id/44/s/2018-official-joules-vest/category/5/

The idea is you add some custom text in the field labeled "personalize", click the preview button, and a window opens up showing the custom text you had on the item. The link the code constructs works fine, its the actual popup that renders the image that is the issue. I'm adding the code that seems relevant to the situation, hope someone can help me out here this has been a headscratcher especially since it works a lot of times, but if you refresh enough it breaks and I don't understand why.
Can anyone out there help me figure this out?

EDIT: I removed an additional jQuery Library call that seemed to be triggering some errors, having said that, it's still inconsistently working because sometimes I get the "(index):2025 Uncaught ReferenceError: jQuery is not defined" error.

```<code>
</code>```

```<code>        /*optionId = InputId Of Personalization field*/

        var personalizedField = document.getElementsByClassName('product-custom-option')[0].id;
        //!TODO: String/VAR TO ARRAY
        // console.log('personalizedField: ' + personalizedField);

        arguments = {optionId:personalizedField, argument:'<?= $liquifire_argument ?>'};
        // console.log("arguments: " + arguments);
        liquifireArguments.push(arguments);

        jQuery( document ).ready(function(){
            function lpiEncode(str) {
                var encoded = str;
                encoded = encoded.replace(/&/g, "U0026amp;");
                encoded = encoded.replace(/'/g, "U0027");
                encoded = encoded.replace(/\(/g, "U0026lp;");
                encoded = encoded.replace(/\)/g, "U0026rp;");
                encoded = encoded.replace(/\[/g, "U005B");
                encoded = encoded.replace(/\]/g, "U005D");
                encoded = encoded.replace(/\`/g, "U0060");
                encoded = encoded.replace(/\+/g, "%2b");
                return encoded;
            }
            jQuery('#product-options-wrapper').append('<div class="lp-box"><button type="button" title="Preview" class="button" id="liquifire-preview"><span><span>Preview</span></span></button></div>');
            jQuery('#liquifire-preview').click(function(){
                //jQuery('.mousetrap').addClass('liquidpixels');
                var liquifireUrl = 'https://urm.liquifire.com/urm';
                var liquifireChain = '<?= $image_chain ?>';
                var imageUrl = liquifireUrl + '?';
                // console.log("liquifireUrl: " + liquifireUrl);
                // console.log("liquifireChain: " + liquifireChain);
                // console.log("imageUrl: " + imageUrl);

                jQuery.each(liquifireArguments, function(){
                    optionValue = document.getElementById(this.optionId).value;
                    if( optionValue !== ''){
                        var argument = this.argument;

                        if(liquifireArguments.indexOf(this) === 0){
                            imageUrl += 'set=';
                        }else{
                            imageUrl += ',';
                        }
                        // Add variable and value
                        imageUrl += argument + '[' + lpiEncode(optionValue) + ']';
                    }
                });

                if(document.getElementById('select_label_color')) {
                    lpcolor = document.getElementById('select_label_color').textContent.toLowerCase();
                    if( lpcolor !== ''){
                        imageUrl += ',selColor[' + lpcolor + '.jpg]';
                    }
                }

                // Zoom Url
                zoomUrl = imageUrl + '&call=url[file:' + liquifireChain + ']&scale=size[1000]&sink';
                // console.log('zoomUrl: '+ zoomUrl);

                // Add image chain
                imageUrl += '&call=url[file:' + liquifireChain + ']&scale=size[900]&sink';
                // console.log('imageUrl: '+ imageUrl);

                var poOptions = { type : 'image' };
                var popup = new jQuery.Popup(poOptions);

                popup.open(zoomUrl);
            });

        });

    </script>
</code>```

答:
This seems to be a relatively common Magento 2 issue for custom modules. There are a number of solutions out there that may be better than this one, having said that, the one I found here https://www.offset101.com/magento-2-x-fix-uncaught-referenceerror-jquery-not-definedanonymous-function-javascript-message/ was the most straight forward.

Wrapping my code in the below require function did the trick.

```<code>require(['jquery'],function($){

    $(document).ready(function(){

       alert('YOUR JS HERE');

    });

});
</code>```

Body:
I've come to the tail end of a module I'm creating for Magento 2 but I'm having trouble getting it to render on the screen. This code has worked on other sites in the past but there seems to be an issue stopping this one from working. The issue seems to be with my code "var popup = new jQuery.Popup(poOptions);" note being recognized as a constructor.

I read through a few similar posts (like this one WOW is not a constructor) but I can't seem to figure out what the issue is still

The jquery plugin I'm utilizing originates from https://github.com/Toddish/Popup, on our website page here https://76a8q06e6vrsbggs.mojostratus.io/catalog/product/view/id/44/s/2018-official-joules-vest/category/5/

The idea is you add some custom text in the field labeled "personalize", click the preview button, and a window opens up showing the custom text you had on the item. The link the code constructs works fine, its the actual popup that renders the image that is the issue. I'm adding the code that seems relevant to the situation, hope someone can help me out here this has been a headscratcher especially since it works a lot of times, but if you refresh enough it breaks and I don't understand why.
Can anyone out there help me figure this out?

EDIT: I removed an additional jQuery Library call that seemed to be triggering some errors, having said that, it's still inconsistently working because sometimes I get the "(index):2025 Uncaught ReferenceError: jQuery is not defined" error.

        /*optionId = InputId Of Personalization field*/

        var personalizedField = document.getElementsByClassName('product-custom-option')[0].id;
        //!TODO: String/VAR TO ARRAY
        // console.log('personalizedField: ' + personalizedField);

        arguments = {optionId:personalizedField, argument:'<?= $liquifire_argument ?>'};
        // console.log("arguments: " + arguments);
        liquifireArguments.push(arguments);

        jQuery( document ).ready(function(){
            function lpiEncode(str) {
                var encoded = str;
                encoded = encoded.replace(/&/g, "U0026amp;");
                encoded = encoded.replace(/'/g, "U0027");
                encoded = encoded.replace(/\(/g, "U0026lp;");
                encoded = encoded.replace(/\)/g, "U0026rp;");
                encoded = encoded.replace(/\[/g, "U005B");
                encoded = encoded.replace(/\]/g, "U005D");
                encoded = encoded.replace(/\`/g, "U0060");
                encoded = encoded.replace(/\+/g, "%2b");
                return encoded;
            }
            jQuery('#product-options-wrapper').append('
<button type="button" title="Preview" class="button" id="liquifire-preview">Preview</button>
');
            jQuery('#liquifire-preview').click(function(){
                //jQuery('.mousetrap').addClass('liquidpixels');
                var liquifireUrl = 'https://urm.liquifire.com/urm';
                var liquifireChain = '<?= $image_chain ?>';
                var imageUrl = liquifireUrl + '?';
                // console.log("liquifireUrl: " + liquifireUrl);
                // console.log("liquifireChain: " + liquifireChain);
                // console.log("imageUrl: " + imageUrl);

                jQuery.each(liquifireArguments, function(){
                    optionValue = document.getElementById(this.optionId).value;
                    if( optionValue !== ''){
                        var argument = this.argument;

                        if(liquifireArguments.indexOf(this) === 0){
                            imageUrl += 'set=';
                        }else{
                            imageUrl += ',';
                        }
                        // Add variable and value
                        imageUrl += argument + '[' + lpiEncode(optionValue) + ']';
                    }
                });

                if(document.getElementById('select_label_color')) {
                    lpcolor = document.getElementById('select_label_color').textContent.toLowerCase();
                    if( lpcolor !== ''){
                        imageUrl += ',selColor[' + lpcolor + '.jpg]';
                    }
                }

                // Zoom Url
                zoomUrl = imageUrl + '&call=url[file:' + liquifireChain + ']&scale=size[1000]&sink';
                // console.log('zoomUrl: '+ zoomUrl);

                // Add image chain
                imageUrl += '&call=url[file:' + liquifireChain + ']&scale=size[900]&sink';
                // console.log('imageUrl: '+ imageUrl);

                var poOptions = { type : 'image' };
                var popup = new jQuery.Popup(poOptions);

                popup.open(zoomUrl);
            });

        });

    </script>

Body:
This seems to be a relatively common Magento 2 issue for custom modules. There are a number of solutions out there that may be better than this one, having said that, the one I found here https://www.offset101.com/magento-2-x-fix-uncaught-referenceerror-jquery-not-definedanonymous-function-javascript-message/ was the most straight forward.

Wrapping my code in the below require function did the trick.

require(['jquery'],function($){

    $(document).ready(function(){

       alert('YOUR JS HERE');

    });

});


问:
How to match a variable value against an array of values in Javascript?
I have an array of values with names:

```<code>names = ['Jim', 'Jack', 'Fred']
</code>```

I have also received a value from a function, which is a name in string form, such as:

```<code>returnedValue = 'Jim'
</code>```

How can I run the returnedValue string against the values of the names array and test for a match?

My feeling is that you would want to use the .filter method of the array prototype but I can't conceive of how to do it that way.

答:
Check out this link on dictionaries
https://www.w3schools.com/python/python_dictionaries.asp
If you have a variable whose value would match a string in the dictionary you can set a variable to equal that value. Here is a snip from some of my own code`</p>

```<code>global element1
element1 = 1
elementdict = {
"H": 1.008,
"He": 4.00,
"Li": 6.49,
"Be": 9.01,
"B": 10.81,
"C": 12.01,
"N": 14.01,
"O": 16.00,
"F": 19.00,
"Ne": 20.18,
"Na": 22.99,
"Mg": 24.30
}
element1 = input("Enter an element to recieve its mass")
element1 = elementdict[element1]
print(element1)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of values with names:

names = ['Jim', 'Jack', 'Fred']

I have also received a value from a function, which is a name in string form, such as:

returnedValue = 'Jim'

How can I run the returnedValue string against the values of the names array and test for a match?

My feeling is that you would want to use the .filter method of the array prototype but I can't conceive of how to do it that way.

Body:
Check out this link on dictionaries
https://www.w3schools.com/python/python_dictionaries.asp
If you have a variable whose value would match a string in the dictionary you can set a variable to equal that value. Here is a snip from some of my own code`

global element1
element1 = 1
elementdict = {
"H": 1.008,
"He": 4.00,
"Li": 6.49,
"Be": 9.01,
"B": 10.81,
"C": 12.01,
"N": 14.01,
"O": 16.00,
"F": 19.00,
"Ne": 20.18,
"Na": 22.99,
"Mg": 24.30
}
element1 = input("Enter an element to recieve its mass")
element1 = elementdict[element1]
print(element1)


问:
Android Canvas: drawing too large bitmap
I'm running Ubuntu 16.04. And on Android Studio when I try to run my application in the emulator I get the following error:

FATAL EXCEPTION: main
                    Process: project name here, PID: 2528
                    java.lang.RuntimeException: Canvas: trying to draw too large(216090000bytes) bitmap.
                        at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
                        at android.graphics.Canvas.drawBitmap(Canvas.java:1415)
                        at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:528)
                        at android.widget.ImageView.onDraw(ImageView.java:1316)
                        at android.view.View.draw(View.java:17185)
                        at android.view.View.updateDisplayListIfDirty(View.java:16167)
                        at android.view.View.draw(View.java:16951)
                        at android.view.ViewGroup.drawChild(ViewGroup.java:3727)
                        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3513)
                        at android.view.View.updateDisplayListIfDirty(View.java:16162)
                        at android.view.View.draw(View.java:16951)
                        at android.view.ViewGroup.drawChild(ViewGroup.java:3727)
                        at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3513) at

  etc...

I did have to run through some hoops to get my emulator working however, needed to create a sym-link so I can run the emulator on AMD. Not sure if this is part of the problem. And for the life of me I cannot figure why it continues to do this. In my group there are others who emulate the project just fine on the same emulated phone and SDK.

答: I also had this issue when i was trying to add a splash screen to the android app through the launch_backgrgound.xml . the issue was the resolution. it was too high so the images memory footprint exploded and caused the app to crash hence the reason for this error. so just resize your image using a site called nativescript image builder so i got the ldpi,mdpi and all the rest and it worked fine for me.</p>


问:
How to pass values to a function which is a list item in Python
I want to pass a value as argument in a function which is a list item.

For example:

```<code>def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3, foo('want values here as arguments')]

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])
</code>```

Thanks ahead.

答:
<pre class="lang-py prettyprint-override"><code> def foo(arg1, arg2):
    print("Something is happening here", arg1, arg2 )

l = [1,2,3, foo]

def foo_bar():
    x = 0
    y = 1
    print("want to pass x and y inside: " , l[3](x,y))

</code>```

Body:
I want to pass a value as argument in a function which is a list item.

For example:

def foo(arg1, arg2):
    print(“Something is happening here”, arg1, arg2 )

l = [1,2,3, foo('want values here as arguments')]

def foo_bar():
    x = 0, y = 1
    print(“want to pass x and y inside: “ , l[3])

Thanks ahead.


问:
Can you run PHPUnit tests from a script?
I have a PHP deployment script that I want to run PHPUnit tests first, and stop if the tests fail. I've been googling this a lot, and it's very hard to find documentation on running unit tests from php, rather than from the command line tool.

For the newest version of PHPUnit, can you do something like:

```<code>$unit_tests = new PHPUnit('my_tests_dir');
$passed = $unit_tests->run();
</code>```

Preferably a solution that doesn't require me to manually specify each test suite.

答:
Solution for PHP7 & phpunit ^7

use PHPUnit\TextUI\Command;

$command = new Command();
$command->run(['phpunit', 'tests']);
```

<p>Does the same effect as CLI command:</p>

<pre class="lang-sh prettyprint-override"><code>vendor/bin/phpunit --bootstrap vendor/autoload.php tests
</code>```

Body:
I have a PHP deployment script that I want to run PHPUnit tests first, and stop if the tests fail. I've been googling this a lot, and it's very hard to find documentation on running unit tests from php, rather than from the command line tool.

For the newest version of PHPUnit, can you do something like:

$unit_tests = new PHPUnit('my_tests_dir');
$passed = $unit_tests->run();

Preferably a solution that doesn't require me to manually specify each test suite.

Body:
Solution for PHP7 & phpunit ^7

use PHPUnit\TextUI\Command;

$command = new Command();
$command->run(['phpunit', 'tests']);

Does the same effect as CLI command:

vendor/bin/phpunit --bootstrap vendor/autoload.php tests


问:
Syntax error when using Delimiters with Aurora Serverless MySQL 5.6
I'm using Aurora Serverless MySQL 5.6 to create the following trigger which will update one table when data is inserted into another table but am receiving syntax errors, specifically around the Delimiter keyword.

```<code>DELIMITER $$
CREATE TRIGGER Create_Media_Like_Trigger AFTER INSERT ON MediaLike
FOR EACH ROW
BEGIN
    IF NEW.likeType = 'LIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes + 1
        WHERE Media.mediaId = NEW.mediaId;
    ELSEIF NEW.likeType = 'DISLIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes - 1
        WHERE Media.mediaId = NEW.mediaId;
    ENDIF;
END $$
DELIMITER ;
</code>```

Like I said above, I am receiving syntax errors near DELIMITER, is this issue AWS specific and how can I fix it?

UPDATE with error messages:

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'DELIMITER $$ CREATE TRIGGER Create_Media_Like_Trigger
AFTER INSERT ON MediaLike ' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'ELSEIF NEW.likeType = 'DISLIKE' THEN UPDATE Media SET
Media.numLikes = Media.num' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'END $$' at line 1
</code>```

答:
I spent a day trying to figure this out so hopefully this helps someone out there...

DELIMITER is a feature of the client, not the MySQL server. The RDS Query Editor is a client but it does not support changing the delimiter so attempting to run the script you've provided won't work since the first time it sees a semicolon it will interpret that as the end of the command and fail with a syntax error.

So, how do you create something like a stored procedure that has multiple statements and semicolons in it? You must create it as an .sql file and send it using the Data API from either a Lambda function or the CLI.

First, create your script in a .sql file without any DELIMITER commands or alternate delimiters.

For example: function.sql

CREATE PROCEDURE simpleproc (OUT param1 INT)
BEGIN
   SELECT COUNT(*) INTO param1 FROM t;
END
```

<p>Then, run the script using the CLI like this:</p>

<pre class="lang-sh prettyprint-override"><code>cat function.sql | xargs -0 aws rds-data execute-statement \
    --resource-arn arn:aws:rds:eu-west-1:xxx:cluster:cluster-name \
    --secret-arn arn:aws:secretsmanager:eu-west-1:xxx:secret:secret-name-xxx \
    --database "database_name" \
    --sql
</code>```

Alternatively, you can create a Lambda function that reads the file and uses rds_client.execute_statement() to send the script to the server via the Data API. But again, do NOT use the DELIMITER statement. The server sees the BEGIN and END lines and acts accordingly without the need to change the delimiter.

Body:
I'm using Aurora Serverless MySQL 5.6 to create the following trigger which will update one table when data is inserted into another table but am receiving syntax errors, specifically around the Delimiter keyword.

DELIMITER $$
CREATE TRIGGER Create_Media_Like_Trigger AFTER INSERT ON MediaLike
FOR EACH ROW
BEGIN
    IF NEW.likeType = 'LIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes + 1
        WHERE Media.mediaId = NEW.mediaId;
    ELSEIF NEW.likeType = 'DISLIKE' THEN
        UPDATE Media
        SET Media.numLikes = Media.numLikes - 1
        WHERE Media.mediaId = NEW.mediaId;
    ENDIF;
END $$
DELIMITER ;

Like I said above, I am receiving syntax errors near DELIMITER, is this issue AWS specific and how can I fix it?

UPDATE with error messages:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'DELIMITER $$ CREATE TRIGGER Create_Media_Like_Trigger
AFTER INSERT ON MediaLike ' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'ELSEIF NEW.likeType = 'DISLIKE' THEN UPDATE Media SET
Media.numLikes = Media.num' at line 1

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near 'END $$' at line 1

Body:
I spent a day trying to figure this out so hopefully this helps someone out there...

DELIMITER is a feature of the client, not the MySQL server. The RDS Query Editor is a client but it does not support changing the delimiter so attempting to run the script you've provided won't work since the first time it sees a semicolon it will interpret that as the end of the command and fail with a syntax error.

So, how do you create something like a stored procedure that has multiple statements and semicolons in it? You must create it as an .sql file and send it using the Data API from either a Lambda function or the CLI.

First, create your script in a .sql file without any DELIMITER commands or alternate delimiters.

For example: function.sql

CREATE PROCEDURE simpleproc (OUT param1 INT)
BEGIN
   SELECT COUNT(*) INTO param1 FROM t;
END

Then, run the script using the CLI like this:

cat function.sql | xargs -0 aws rds-data execute-statement \
    --resource-arn arn:aws:rds:eu-west-1:xxx:cluster:cluster-name \
    --secret-arn arn:aws:secretsmanager:eu-west-1:xxx:secret:secret-name-xxx \
    --database "database_name" \
    --sql

Alternatively, you can create a Lambda function that reads the file and uses rds_client.execute_statement() to send the script to the server via the Data API. But again, do NOT use the DELIMITER statement. The server sees the BEGIN and END lines and acts accordingly without the need to change the delimiter.


问:
Delete all branches that are more than X days/weeks old
I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?</p>

```<code>for k in $(git branch | sed /\*/d); do
  echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'
</code>```

答:
```<code>for k in $(git branch -r | sed /\*/d); do
  if [ -n "$(git log -1 --before='80 week ago' -s $k)" ]; then
    git push origin --delete "${k/origin\//}"
  fi
done
</code>```

Body:
I found the below script that lists the branches by date. How do I filter this to exclude newer branches and feed the results into the Git delete command?

for k in $(git branch | sed /\*/d); do
  echo "$(git log -1 --pretty=format:"%ct" $k) $k"
done | sort -r | awk '{print $2}'


问:
Pyspark: applying kmeans on different groups of a dataframe
Using Pyspark I would like to apply kmeans separately on groups of a dataframe and not to the whole dataframe at once. For the moment I use a for loop which iterates on each group, applies kmeans and appends the result to another table. But having a lot of groups makes it time consuming. Anyone could help me please??
Thanks a lot!</p>

```<code>for customer in customer_list:
    temp_df = togroup.filter(col("customer_id")==customer)
    df = assembler.transform(temp_df)
    k = 1
    while (k < 5 & mtrc < width):
        k += 1
        kmeans = KMeans(k=k,seed=5,maxIter=20,initSteps=5)
        model = kmeans.fit(df)
        mtric = 1 - model.computeCost(df)/ttvar
        a = model.transform(df)select(cols)
        allcustomers = allcustomers .union(a)
</code>```

答:
I came up with a solution using pandas_udf. A pure spark or scala solution is preferred and yet to be offered.
Assume my data is

```<code>import pandas as pd
df_pd = pd.DataFrame([['cat1',10.],['cat1',20.],['cat1',11.],['cat1',21.],['cat1',22.],['cat1',9.],['cat2',101.],['cat2',201.],['cat2',111.],['cat2',214.],['cat2',224.],['cat2',99.]],columns=['cat','val'])
df_sprk = spark.createDataFrame(df_pd)
</code>```

First solve the problem in pandas:

```<code>from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=2,random_state=0)

def skmean(kmeans,x):
    X = np.array(x)
    kmeans.fit(X)
    return(kmeans.predict(X))
</code>```

You can apply skmean() to a panda data frame (to make sure it works properly):

```<code>df_pd.groupby('cat').apply(lambda x:skmean(kmeans,x)).reset_index()
</code>```

To apply the function to pyspark data frame, we use pandas_udf. But first define a schema for the output data frame:

```<code>from pyspark.sql.types import *
schema = StructType(
       [StructField('cat',StringType(),True),
        StructField('clusters',ArrayType(IntegerType()))])
</code>```

Convert the function above to a pandas_udf:

```<code>from pyspark.sql.functions import pandas_udf
from pyspark.sql.functions import PandasUDFType

@pandas_udf(schema, functionType=PandasUDFType.GROUPED_MAP)
def skmean_udf(df):
    result = pd.DataFrame(
             df.groupby('cat').apply(lambda x: skmean(kmeans,x))
    result.reset_index(inplace=True, drop=False)
    return(result)
</code>```

You can use the function as follows:

```<code>df_spark.groupby('cat').apply(skmean_udf).show()
</code>```

Body:
Using Pyspark I would like to apply kmeans separately on groups of a dataframe and not to the whole dataframe at once. For the moment I use a for loop which iterates on each group, applies kmeans and appends the result to another table. But having a lot of groups makes it time consuming. Anyone could help me please??
Thanks a lot!

for customer in customer_list:
    temp_df = togroup.filter(col("customer_id")==customer)
    df = assembler.transform(temp_df)
    k = 1
    while (k < 5 & mtrc < width):
        k += 1
        kmeans = KMeans(k=k,seed=5,maxIter=20,initSteps=5)
        model = kmeans.fit(df)
        mtric = 1 - model.computeCost(df)/ttvar
        a = model.transform(df)select(cols)
        allcustomers = allcustomers .union(a)

Body:
I came up with a solution using pandas_udf. A pure spark or scala solution is preferred and yet to be offered.
Assume my data is

import pandas as pd
df_pd = pd.DataFrame([['cat1',10.],['cat1',20.],['cat1',11.],['cat1',21.],['cat1',22.],['cat1',9.],['cat2',101.],['cat2',201.],['cat2',111.],['cat2',214.],['cat2',224.],['cat2',99.]],columns=['cat','val'])
df_sprk = spark.createDataFrame(df_pd)

First solve the problem in pandas:

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=2,random_state=0)

def skmean(kmeans,x):
    X = np.array(x)
    kmeans.fit(X)
    return(kmeans.predict(X))

You can apply skmean() to a panda data frame (to make sure it works properly):

df_pd.groupby('cat').apply(lambda x:skmean(kmeans,x)).reset_index()

To apply the function to pyspark data frame, we use pandas_udf. But first define a schema for the output data frame:

from pyspark.sql.types import *
schema = StructType(
       [StructField('cat',StringType(),True),
        StructField('clusters',ArrayType(IntegerType()))])

Convert the function above to a pandas_udf:

from pyspark.sql.functions import pandas_udf
from pyspark.sql.functions import PandasUDFType

@pandas_udf(schema, functionType=PandasUDFType.GROUPED_MAP)
def skmean_udf(df):
    result = pd.DataFrame(
             df.groupby('cat').apply(lambda x: skmean(kmeans,x))
    result.reset_index(inplace=True, drop=False)
    return(result)

You can use the function as follows:

df_spark.groupby('cat').apply(skmean_udf).show()


问:
How to implement the social sharing in rails app?
I want to implement the social sharing feature of the articles which have been posted in my rails app. I tried following the documentation of gem 'social-share-button' where the following steps were followed :

step 1: Add //= require rails-social-share-button in app/assets/javascripts/application.js

step 2: Add *= require rails-social-share-button in app/assets/stylesheets/application.css

step 3: use the social_share_button_tag helper method in views to display the social share buttons. for e.g = rails_social_share_button_tag('Share to Facebook', url: article_path(@article), desc: @article.content)

Error:
undefined method `rails_social_share_button_tag' for #<#:0x00005574ff28ec30>

答:
You're missing a step or two from the gem's readme. The order of the instructions in the readme is a little misleading. Did you run rails generate rails_social_share_button:install? You may also want to check the contents of the "config/initializers/rails_social_share_button.rb" file after you've run that generator.

Alternatively, you may want to use the "social-share-button" gem. It looks like the one you're using, with its longer name, is a copy of everything in shorter-named "social-share-button" gem. Also it looks like the "social-share-button" gem has been around longer and is better maintained, as it already includes one bugfix that the gem you're using does not. I'd recommend first switching gems and then running bundle install. After switching gems, you should run the generator command listed in the readme for social-share-button, check the config file as the readme recommends, and then update your views accordingly.


问:
UsedRange lastrow computing extra rows
This code is supposed to make a formula go from C9 until the last row used in C. I am using UsedRange because from C1 to C9, there are empty values.

```<code>lastrow = ws1.UsedRange.Rows.Count

ws1.Range("C9:C" & lastrow).Formula = _
    "=INDEX(Tableau_Employés[EMPLOYÉ],MATCH('Overtime KRONOS'!$A9,Tableau_Employés[ORDRE D''ANCIENNETÉ]))"
</code>```

However this pastes the formula too far, going 11 rows after the last row. I'm not sure why.

答:
Changed to

lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row

Title: UsedRange lastrow computing extra rows

Body:
This code is supposed to make a formula go from C9 until the last row used in C. I am using UsedRange because from C1 to C9, there are empty values.

lastrow = ws1.UsedRange.Rows.Count

ws1.Range("C9:C" & lastrow).Formula = _
    "=INDEX(Tableau_Employés[EMPLOYÉ],MATCH('Overtime KRONOS'!$A9,Tableau_Employés[ORDRE D''ANCIENNETÉ]))"

However this pastes the formula too far, going 11 rows after the last row. I'm not sure why.


问:
Unreliable nested while loops?
Im having a logic confusion here and don't know whether a solution is possible with my setup.

I am trying to prompt the user for (in order)

user answer y/n (originally set to 'y')

a bet (based on their current money)

a guess on a number 1-6.

Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.

My code below works, if the user answers with a valid guess all the time:

```<code>def roll():
    return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]

# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
    return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0

# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
            break
</code>```

But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):

```<code>You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?
</code>```

I've tried

```<code>if (int(guess) < 1 or int(guess) > 6):
            guess = input('What number are you betting on? (number 1-6)')
</code>```

at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.

Is my setup all wrong or how can I fix this?

Updated attempt:

```<code>def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
        if(userAnswer.strip().lower() != 'y'):
            break
</code>```

答:
Change the while condition in the loop that asks for a valued number and put it inside the actual loop, so that when it is an invalid number, it asks for another one.

Edited while condition because of @AMC 's comment

Edited to put the whole code that solves the problem:

```<code>def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while true:
                if int(guess) < 1 or int(guess > 6):
                    guess = input("Please choose a valid number") #will keep asking for a valid number if it is wrong
                    continue
                else:
                    print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                    # Actually calculate the roll
                    theRoll = roll()
                    print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                    if (int(computeBetResult(theRoll, bet, guess)) > 0):
                        print('You won your bet!')
                        money += int(bet)
                    else:
                        print('You lost your bet :(')
                        money -= int(bet)
                        print('You now have $' + str(money).strip())
                    # Prompt again
                    userAnswer = input('Would you like to play again (y/n)?')
                    if userAnswer=="n":
                        break

</code>```

Title: Unreliable nested while loops?

Body:
Im having a logic confusion here and don't know whether a solution is possible with my setup.

I am trying to prompt the user for (in order)

user answer y/n (originally set to 'y')

a bet (based on their current money)

a guess on a number 1-6.

Until the user answers anything but y, I will loop this program.
At stage 2, I will loop asking for a bet if the bet is invalid/not in range of their current money.
At stage 3, I will loop asking for a guess if the guess is not 1-6 or invalid.

My code below works, if the user answers with a valid guess all the time:

def roll():
    return [random.randrange(1,6), random.randrange(1,6), random.randrange(1,6)]

# Returns positive [betamount] or negative [betamount] depending on if guess is in diceroll list
def computeBetResult(diceRolls, betAmount, guessed):
    return (int(betAmount) if (int(guessed) in diceRolls) else -1*int(betAmount)) if (int(betAmount) > 0) else 0

# PART 2 - prompt user input and continually ask for new bets and guesses, until user says to quit
def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
            break

But if I get through with a valid bet, but not a valid guess, the program will just move on back to the top of the outermost while loop and ask for a bet again (from console):

You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?0
You have $100. How much would you like to bet?100
What number are you betting on? (number 1-6)0
You have $100. How much would you like to bet?

I've tried

if (int(guess) < 1 or int(guess) > 6):
            guess = input('What number are you betting on? (number 1-6)')

at the very end of the outer while loop, but this then results in guess being asked for unnecessarily.

Is my setup all wrong or how can I fix this?

Updated attempt:

def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while (int(guess) >= 1 and int(guess) <= 6):
                print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                # Actually calculate the roll
                theRoll = roll()
                print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                if (int(computeBetResult(theRoll, bet, guess)) > 0):
                    print('You won your bet!')
                    money += int(bet)
                else:
                    print('You lost your bet :(')
                    money -= int(bet)
                print('You now have $' + str(money).strip())
                # Prompt again
                userAnswer = input('Would you like to play again (y/n)?')
                break
        if(userAnswer.strip().lower() != 'y'):
            break

Body:
Change the while condition in the loop that asks for a valued number and put it inside the actual loop, so that when it is an invalid number, it asks for another one.

Edited while condition because of @AMC 's comment

Edited to put the whole code that solves the problem:

def main():
    money = 100
    userAnswer = 'y'
    print('Welcome to Gambling.')
    while(userAnswer.strip().lower() == 'y'):
        bet = input('You have $' + str(money) + '. How much would you like to bet?')
        while(bet.strip().isnumeric() and int(bet) > 0 and int(bet) <= money):
            guess = input('What number are you betting on? (number 1-6)')
            while true:
                if int(guess) < 1 or int(guess > 6):
                    guess = input("Please choose a valid number") #will keep asking for a valid number if it is wrong
                    continue
                else:
                    print("Ok. You bet $" + str(bet).strip() + ' on the number ' + str(guess))
                    # Actually calculate the roll
                    theRoll = roll()
                    print('You rolled: ' + str(theRoll[0]) + ', ' + str(theRoll[1]) + ', ' + str(theRoll[2]))
                    if (int(computeBetResult(theRoll, bet, guess)) > 0):
                        print('You won your bet!')
                        money += int(bet)
                    else:
                        print('You lost your bet :(')
                        money -= int(bet)
                        print('You now have $' + str(money).strip())
                    # Prompt again
                    userAnswer = input('Would you like to play again (y/n)?')
                    if userAnswer=="n":
                        break


问:
how do i fix this, x not in list
this is the code for this sub routine

```<code>def elimination():
    global name
    global contestants
    global tempContestants
    global lipsync_songs
    global bottom_two
    bottom = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom)
    bottom1 = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom1)
    bottom_two = [bottom, bottom1]
    print(bottom_two[0], "and", bottom_two[1], "I'm sorry my dears but you are up for elimination")
    lipsync()
    eliminated = bottom_two[random.randint(0,len(bottom_two)-1)]
    bottom_two.remove(eliminated)
    safe = str(bottom_two)
    print("Ladies, I have made my decision")
    print(safe+", shantay you stay!")
    print(eliminated+", sashay away!")
    contestants.remove(eliminated)
    if eliminated == name:
        print("You have been eliminated!")
        quit()
</code>```

and here is the error message

```<code>    tempContestants.remove(bottom)
ValueError: list.remove(x): x not in list
</code>```

what does this mean and how do i fix it?

答:
This code will randomly discard one of the last two contestants. I don't know if this is your intent, but I will throw it out as a straw man.

```<code>import random

def elimination():
    # get last two contestants
    candidates = tempContestants[-2:]
    if len(candidates) != 2:
        print("Sorry, not enough players")
        quit()
    print("{} and {}, I'm sorry my dears but you are up for elimination".format(
            *candidates))
    lipsync()

    # select and and remove the loser
    eliminated = random.choice(candidates)
    candidates.remove(eliminated)
    safe = candidates[0]
    tempContestants.remove(eliminated)

    # report the news
    print("""Ladies, I have made my decision.
{}, shantay you stay!
{}, sashay away!""".format(safe, eliminated))

    # decide fate of game
    if eliminated == name:
        print("You have been eliminated!")
        quit()

def lipsync(): pass
tempContestants = ["A", "B", "C", "D", "E", "F"]
name = "F"
elimination()
</code>```

Running this, you will get two possible outputs because of the random choice. One run results in

```<code>E and F, I'm sorry my dears but you are up for elimination
Ladies, I have made my decision.
E, shantay you stay!
F, sashay away!
You have been eliminated!
</code>```

Title: how do i fix this, x not in list

Body:
this is the code for this sub routine

def elimination():
    global name
    global contestants
    global tempContestants
    global lipsync_songs
    global bottom_two
    bottom = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom)
    bottom1 = tempContestants[0:len(tempContestants)-1]
    tempContestants.remove(bottom1)
    bottom_two = [bottom, bottom1]
    print(bottom_two[0], "and", bottom_two[1], "I'm sorry my dears but you are up for elimination")
    lipsync()
    eliminated = bottom_two[random.randint(0,len(bottom_two)-1)]
    bottom_two.remove(eliminated)
    safe = str(bottom_two)
    print("Ladies, I have made my decision")
    print(safe+", shantay you stay!")
    print(eliminated+", sashay away!")
    contestants.remove(eliminated)
    if eliminated == name:
        print("You have been eliminated!")
        quit()

and here is the error message

    tempContestants.remove(bottom)
ValueError: list.remove(x): x not in list

what does this mean and how do i fix it?

Body:
This code will randomly discard one of the last two contestants. I don't know if this is your intent, but I will throw it out as a straw man.

import random

def elimination():
    # get last two contestants
    candidates = tempContestants[-2:]
    if len(candidates) != 2:
        print("Sorry, not enough players")
        quit()
    print("{} and {}, I'm sorry my dears but you are up for elimination".format(
            *candidates))
    lipsync()

    # select and and remove the loser
    eliminated = random.choice(candidates)
    candidates.remove(eliminated)
    safe = candidates[0]
    tempContestants.remove(eliminated)

    # report the news
    print("""Ladies, I have made my decision.
{}, shantay you stay!
{}, sashay away!""".format(safe, eliminated))

    # decide fate of game
    if eliminated == name:
        print("You have been eliminated!")
        quit()

def lipsync(): pass
tempContestants = ["A", "B", "C", "D", "E", "F"]
name = "F"
elimination()

Running this, you will get two possible outputs because of the random choice. One run results in

E and F, I'm sorry my dears but you are up for elimination
Ladies, I have made my decision.
E, shantay you stay!
F, sashay away!
You have been eliminated!


问:
In Java, is better maintain data in the ResultSet or transform to array?
I have two classes, a server and some clients. The server class make a query to database and retrieve a certain number of rows. The clients request a part of these rows, each one a different part.

In the server class, is better I maintain the result of the query in the ResultSet and transforming in a array of objects when the client class make the request or transforming all in a array of objects and sending him partially when the request occur?

I think that maintain in the ResultSet is more easier to do and control.

答: The biggest reason to not leave it in the ResultSet is that it doesn't release the connection back to the pool (unless I'm sorely mistaken). As such you end up holding onto resources that should be freed up for other operations.</p>


问:
Getting the email body using python
I'm quite new at this, but I've been trying to get the email body using python and I've tried almost all of the examples out there and I was able, with:

```<code>original = email.message_from_string(response_part[1].decode('utf-8'), policy=policy.default)

         data1 = original.get_body('text/plain')
</code>```

to get this:

```<code>Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64

SGkNCg==
</code>```

in which the last line is actual my email body encoded with base64 but what I'm trying to do now is to actually get just the last line:

```<code>SGkNCg==
</code>```

any suggestions?

答: Actually it was pretty simple, just had to use: get_payload()

Title: Getting the email body using python

Body:
I'm quite new at this, but I've been trying to get the email body using python and I've tried almost all of the examples out there and I was able, with:

original = email.message_from_string(response_part[1].decode('utf-8'), policy=policy.default)

         data1 = original.get_body('text/plain')

to get this:

Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64

SGkNCg==

in which the last line is actual my email body encoded with base64 but what I'm trying to do now is to actually get just the last line:

SGkNCg==

any suggestions?


问:
Filling empty DateTime type null values based on the contiguous/corresponding non null value column SQL Server 2012
I'm trying to build a query that fills empty DateTime type null values based on the contiguous/corresponding below non-null value column, while filtering out Ids. I've looked up some answers here in stack overflow but I've not had much success. I'm not sure if this problem can be solved or addressed with just SQL or I need T-SQL (I've seen that some people take advantage of cursors but when it comes to T-SQL, I'm a newbie).

Here is my code(I'm using a CTE, but I'm aware that the same result can be achieved without a CTE).

```<code>WITH CTE_C AS
(
    SELECT
        c.IdHistorial,
        CONCAT(P.PrimerNombre,' ' COLLATE MODERN_SPANISH_CI_AI,P.SegundoNombre,' 'COLLATE MODERN_SPANISH_CI_AI,P.ApellidoPaterno,' 'COLLATE MODERN_SPANISH_CI_AI,P.ApellidoMaterno) AS OCUPADA_POR,
        D.EstadoDivision,
        CONVERT(varchar, C.FechaInicio, 20) AS Starting_Date,
        CONVERT(varchar, C.FechaFinal, 20) AS Final_Date,
        C.Observaciones
    FROM
        DBO.HOSPITALIZACIONCAMAS AS C
    LEFT JOIN
        DBO.PACIENTES AS P ON C.IDPACIENTE = P.IDPACIENTE
    LEFT JOIN
        DBO.CatalogoDivisionEstado AS D ON C.IDESTADO = D.IDESTADODIVISION
    WHERE
        FECHAINICIO BETWEEN '2019-10-01 00:00:00.000' AND '2019-10-18 23:59:59.000'
        AND IDCAMA = '60'
)
SELECT
    *,
    DATEDIFF(HOUR,Starting_Date,Final_Date) AS Diferencia_en_HRS
FROM
    CTE_C
ORDER BY
    Starting_Date
</code>```

This is what the output looks like:

enter image description here

The focus is on the Final_Date column. There are NULL values for some records in that column.

What I want is that the empty Final_Date column gets filled up with the contiguos-below Initial_Date column.

The desired result set should look like this:

enter image description here

I've created a much simpler table(with the same problem and no need for fancy JOINs or even CTEs) for those who want to try at enter link description here

```<code>CREATE TABLE TEST1
(
    ID INT NOT NULL,
    Id_Bed INT NOT NULL,
    Patients_Name varchar(50) NULL,
    Starting_Date DATE NULL,
    Final_Date DATE NULL
)

INSERT INTO TEST1 VALUES
(4883,70,'   ','2017-11-13 12:26:58','2017-11-13 12:29:53'),
(4885,70,'   ','2017-11-13 12:29:53',NULL),
(5997,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-16 06:58:16',NULL),
(6268,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-16 16:47:47','2017-11-16 16:48:03'),
(6269,70,'   ','2017-11-16 16:48:03','2017-11-16 16:48:05'),
(6270,70,'   ','2017-11-16 16:48:05',NULL),
(6643,60,'   ','2017-11-17 16:19:36','2017-11-17 16:19:39'),
(6644,60,'   ','2017-11-17 16:19:39',NULL),
(7379,60,'   ','2017-11-21 09:43:53','2017-11-21 09:44:59'),
(7384,60,'   ','2017-11-21 09:44:59',NULL),
(8354,70,'JHOVANA ANDREA  LOPEZ RODRIGUEZ','2017-11-23 12:40:57','2017-11-23 13:14:37'),
(8384,70,'   ','2017-11-23 13:14:37','2017-11-23 13:14:38'),
(8385,70,'   ','2017-11-23 13:14:38',NULL),
(8604,60,'   ','2017-11-24 10:37:16','2017-11-24 10:37:17'),
(8605,60,'   ','2017-11-24 10:37:17',NULL),
(7076,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-19 12:53:03','2017-11-21 09:43:53'),
(7075,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-19 12:53:01',NULL),
(8716,60,'   ','2017-11-24 12:16:00','2017-11-24 12:16:02'),
(8717,60,'   ','2017-11-24 12:16:02',NULL),
(6744,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-17 20:42:57','2017-11-19 12:53:01'),
(8842,70,'   ','2017-11-24 17:33:01','2017-11-24 17:33:05'),
(8843,70,'   ','2017-11-24 17:33:05',NULL),
(6647,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-17 16:21:04','2017-11-17 20:42:57'),
(6512,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-17 12:46:59','2017-11-17 16:19:36'),
(6390,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-17 09:50:12',NULL),
(6272,70,'JHOVANA ANDREA  LOPEZ RODRIGUEZ','2017-11-16 16:48:43',NULL),
(4907,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-13 12:54:58','2017-11-16 06:58:16'),
(4886,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-13 12:31:17','2017-11-13 12:54:58'),
(9331,60,'   ','2017-11-26 13:34:15','2017-11-26 13:34:20'),
(9332,60,'   ','2017-11-26 13:34:20',NULL),
(4881,70,'JEMMY  VELASCO MORA','2017-11-13 12:15:55','2017-11-13 12:26:58'),
(4755,70,'JEMMY  VELASCO MORA','2017-11-13 08:14:12',NULL),
(3995,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-09 10:37:03','2017-11-17 09:50:12'),
(3860,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-08 17:19:11','2017-11-09 10:37:03'),
(3814,70,'JEMMY  VELASCO MORA','2017-11-08 15:07:45','2017-11-13 08:14:12'),
(3788,70,'JEMMY  VELASCO MORA','2017-11-08 12:53:55','2017-11-08 15:07:45'),
(8707,60,'EMILIA  BECERRIL RAMIREZ','2017-11-24 12:04:30',NULL),
(8615,60,'EMILIA  BECERRIL RAMIREZ','2017-11-24 10:46:14','2017-11-24 12:04:30'),
(11621,70,'   ','2017-12-03 11:04:21','2017-12-03 11:04:25'),
(11622,70,'   ','2017-12-03 11:04:25',NULL)
</code>```

enter image description here

Feel free to rewrite the query completely if necessary. Thanks in advance.

答:
You could use the lead function like this:</p>

```<code>select ID,ID_Bed,Patients_Name,Starting_Date,
        COALESCE(Final_date,lead(Starting_Date,1) Over(Partition by ID_Bed Order by ID)) as Final_Date
from #TEST1
</code>```

Body:
I'm trying to build a query that fills empty DateTime type null values based on the contiguous/corresponding below non-null value column, while filtering out Ids. I've looked up some answers here in stack overflow but I've not had much success. I'm not sure if this problem can be solved or addressed with just SQL or I need T-SQL (I've seen that some people take advantage of cursors but when it comes to T-SQL, I'm a newbie).

Here is my code(I'm using a CTE, but I'm aware that the same result can be achieved without a CTE).

WITH CTE_C AS
(
    SELECT
        c.IdHistorial,
        CONCAT(P.PrimerNombre,' ' COLLATE MODERN_SPANISH_CI_AI,P.SegundoNombre,' 'COLLATE MODERN_SPANISH_CI_AI,P.ApellidoPaterno,' 'COLLATE MODERN_SPANISH_CI_AI,P.ApellidoMaterno) AS OCUPADA_POR,
        D.EstadoDivision,
        CONVERT(varchar, C.FechaInicio, 20) AS Starting_Date,
        CONVERT(varchar, C.FechaFinal, 20) AS Final_Date,
        C.Observaciones
    FROM
        DBO.HOSPITALIZACIONCAMAS AS C
    LEFT JOIN
        DBO.PACIENTES AS P ON C.IDPACIENTE = P.IDPACIENTE
    LEFT JOIN
        DBO.CatalogoDivisionEstado AS D ON C.IDESTADO = D.IDESTADODIVISION
    WHERE
        FECHAINICIO BETWEEN '2019-10-01 00:00:00.000' AND '2019-10-18 23:59:59.000'
        AND IDCAMA = '60'
)
SELECT
    *,
    DATEDIFF(HOUR,Starting_Date,Final_Date) AS Diferencia_en_HRS
FROM
    CTE_C
ORDER BY
    Starting_Date

This is what the output looks like:

enter image description here

The focus is on the Final_Date column. There are NULL values for some records in that column.

What I want is that the empty Final_Date column gets filled up with the contiguos-below Initial_Date column.

The desired result set should look like this:

enter image description here

I've created a much simpler table(with the same problem and no need for fancy JOINs or even CTEs) for those who want to try at enter link description here

CREATE TABLE TEST1
(
    ID INT NOT NULL,
    Id_Bed INT NOT NULL,
    Patients_Name varchar(50) NULL,
    Starting_Date DATE NULL,
    Final_Date DATE NULL
)

INSERT INTO TEST1 VALUES
(4883,70,'   ','2017-11-13 12:26:58','2017-11-13 12:29:53'),
(4885,70,'   ','2017-11-13 12:29:53',NULL),
(5997,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-16 06:58:16',NULL),
(6268,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-16 16:47:47','2017-11-16 16:48:03'),
(6269,70,'   ','2017-11-16 16:48:03','2017-11-16 16:48:05'),
(6270,70,'   ','2017-11-16 16:48:05',NULL),
(6643,60,'   ','2017-11-17 16:19:36','2017-11-17 16:19:39'),
(6644,60,'   ','2017-11-17 16:19:39',NULL),
(7379,60,'   ','2017-11-21 09:43:53','2017-11-21 09:44:59'),
(7384,60,'   ','2017-11-21 09:44:59',NULL),
(8354,70,'JHOVANA ANDREA  LOPEZ RODRIGUEZ','2017-11-23 12:40:57','2017-11-23 13:14:37'),
(8384,70,'   ','2017-11-23 13:14:37','2017-11-23 13:14:38'),
(8385,70,'   ','2017-11-23 13:14:38',NULL),
(8604,60,'   ','2017-11-24 10:37:16','2017-11-24 10:37:17'),
(8605,60,'   ','2017-11-24 10:37:17',NULL),
(7076,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-19 12:53:03','2017-11-21 09:43:53'),
(7075,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-19 12:53:01',NULL),
(8716,60,'   ','2017-11-24 12:16:00','2017-11-24 12:16:02'),
(8717,60,'   ','2017-11-24 12:16:02',NULL),
(6744,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-17 20:42:57','2017-11-19 12:53:01'),
(8842,70,'   ','2017-11-24 17:33:01','2017-11-24 17:33:05'),
(8843,70,'   ','2017-11-24 17:33:05',NULL),
(6647,60,'CLAUDIA ELIZABETH PISCIL RODRIGUEZ','2017-11-17 16:21:04','2017-11-17 20:42:57'),
(6512,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-17 12:46:59','2017-11-17 16:19:36'),
(6390,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-17 09:50:12',NULL),
(6272,70,'JHOVANA ANDREA  LOPEZ RODRIGUEZ','2017-11-16 16:48:43',NULL),
(4907,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-13 12:54:58','2017-11-16 06:58:16'),
(4886,70,'LAURA PATRICIA  FIGUEROA MEDRANO','2017-11-13 12:31:17','2017-11-13 12:54:58'),
(9331,60,'   ','2017-11-26 13:34:15','2017-11-26 13:34:20'),
(9332,60,'   ','2017-11-26 13:34:20',NULL),
(4881,70,'JEMMY  VELASCO MORA','2017-11-13 12:15:55','2017-11-13 12:26:58'),
(4755,70,'JEMMY  VELASCO MORA','2017-11-13 08:14:12',NULL),
(3995,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-09 10:37:03','2017-11-17 09:50:12'),
(3860,60,'ANA ADRIANA  GARCIA VILLANUEVA','2017-11-08 17:19:11','2017-11-09 10:37:03'),
(3814,70,'JEMMY  VELASCO MORA','2017-11-08 15:07:45','2017-11-13 08:14:12'),
(3788,70,'JEMMY  VELASCO MORA','2017-11-08 12:53:55','2017-11-08 15:07:45'),
(8707,60,'EMILIA  BECERRIL RAMIREZ','2017-11-24 12:04:30',NULL),
(8615,60,'EMILIA  BECERRIL RAMIREZ','2017-11-24 10:46:14','2017-11-24 12:04:30'),
(11621,70,'   ','2017-12-03 11:04:21','2017-12-03 11:04:25'),
(11622,70,'   ','2017-12-03 11:04:25',NULL)

enter image description here

Feel free to rewrite the query completely if necessary. Thanks in advance.

Body:
You could use the lead function like this:

select ID,ID_Bed,Patients_Name,Starting_Date,
        COALESCE(Final_date,lead(Starting_Date,1) Over(Partition by ID_Bed Order by ID)) as Final_Date
from #TEST1


问:
Reducing size of dSYM files for symbolication
We are looking for ways to reduce the size of dSYM files from Apple platforms. We need dSYM files just for symbolicating stack traces of crashes and in Crashlytics blog I read this:

These mappings actually hold much more than needed just for
symbolication, presenting some opportunities for optimization. They
have everything required for a generalized symbolic debugger to step
through and inspect your program, which may be a huge amount of
information. On iOS, we have seen dSYMs greater than 1GB in size! This
is a real opportunity for optimization, and we take advantage of this
in two ways. First, we extract just the mapping info we need into a
lightweight, platform-agnostic format. This results in a typical
space-saving of 20x when compared to an iOS dSYM.

Reducing size by 20x sounds very good but I found little information on how this can be done. Do I need to learn details of Mach-O DWARF to achieve this or some of the command line tools can do this? I also wonder if the stripped version can be used direcly afterwards for symbolicating.

Thanks.

答: Crashlytics converts dSYMs to cSYMs and uses these cSYMs for symbolication. This conversion happens on client's Macs. You might want to look into the final size of this cSYM file that is actually uploaded to crashlytics.</p>


问:
WCF Service calling WCF Service - Where to put client service reference?
I'm looking at implementing a WCF Service which will in turn call one (or perhaps more) external WCF Services (or at least, web services which I will call from code using WCF Service reference(s))

My solution is broken down into ServiceLayer, BusinessLogicLayer, DomainLayer, DtoObjects etc.

My Question is:

The logic around the client will all be in the BusinessLogicLayer - but if I put the ServiceReferences in there then I will also need to put the service configuration in the ServiceLayer - since this is where the originating call will be made.

Is that the correct thing to do?

Or:

Create the client in the ServiceLayer and pass it into the BLL.

Not sure I like this idea...but it DOES mean only one config.

Or:

Is there another way?

答:
You can look at it as any code that calls a WCF service is a WCF client, even if that happens to be another bit of code that is itself hosted as a WCF service.  Because of this, you will need the client side configuration to be present and available wherever the call is being made.  I don't know if there is a good way to share configuration, or if it's even advisable... instead, I would opt for separate configuration files in each place.  There won't really be much duplication in that you've got service-side configuration in one place, and client side configuration in the other.

If you can use WCF Discovery (http://msdn.microsoft.com/en-us/library/dd456782.aspx), it can reduce the amount of configuration you'll have to create.  Also, using interfaces and ChannelFactory<T> instead of ServiceReferences will give you a cleaner setup.

Hope this helps.


问:
I am developing an Android app with ArcGIS offline map support. For that which one I have to use? MPK or MMPK package? How to download it?
I am developing an Android app with ArcGIS offline map support. To work with an offline map in android what I have to download? MPK or MMPK? By which tool I can generate the corresponding package? Does anyone have previous experience on the same? I am using com.esri.arcgisruntime:arcgis-android:100.7.0 dependancy. The documentation are totally confusing for me. We have already purchased a Development builder starter license too. Any help would be appreciated.

答:
There are two main ways to use a map offline.

Create a Web Map in ArcGIS Online and take that offline. This does not involve an MMPK.

OR: Create a MMPK using ArcGIS Pro (a desktop product for Windows)

I expect you might want to consider option 1?

Create and save a web map in ArcGIS Online.

In the Settings ensure it's enabled for Offline. You should also ensure the layers you're using are offline enabled.

Use the OfflineMapTask to generate and download the offline map.

This is explained here, but you might also find this technical session helpful.

If you need to go the other route of generating an MMPK, you will need ArcGIS Pro.

MPKs are not a format that Runtime supports.


问:
Postman Returning Null Values in SOAP Response
I am new to SOAP and POSTMAN and am wondering what I am doing wrong with the following. I have a sample java webservice using jax-ws:

```<code>@WebService(endpointInterface = "Soap1.SOAPInterface")
public class SOAPService implements SOAPInterface
{
public String message(String name)
{
    return "Hello " + name;
}
}
</code>```

I published this webservice using an Endpoint:

```<code>public class Publisher
{
public static void main(String[]args)
{
    Endpoint.publish("http://localhost:9006/Service", new SOAPService());
}
}
</code>```

Now when I run this in a client it works fine

```<code>    public static void main(String[] args) throws Exception
    {
    URL url = new URL("http://localhost:9006/Service?wsdl");
    QName qname = new QName("http://Soap1/","SOAPServiceService");
    Service s = Service.create(url,qname);
    SOAPInterface i = s.getPort(SOAPInterface.class);
    System.out.println(i.message("Bob"));
    }
</code>```

However when trying to use POSTMAN to analyze SOAP request/responses. By entering the following xml for a request:

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">

        <MyMessage xmlns="http://Soap1/">
            <name>Bob</name>
        </MyMessage>

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

<p>I get a response of Hello null</p>

<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><?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:MyMessageResponse xmlns:ns2="http://Soap1/">
            <returnedMessage>Hello null</returnedMessage>
        </ns2:MyMessageResponse>
    </S:Body>
</S:Envelope></code>```

I am wondering why this is because using the client, the parameters are passing fine but when using POSTMAN they seem not to be passing.

Screenshot of postman:

答:
If you open in browser URI http://localhost:9006/Service?wsdl, you'll see WSDL generated by JAX-WS for your service. It should contain following snippet:

```<code><types>
<xsd:schema>
<xsd:import namespace="http://example.soap.kdv.org/" schemaLocation="http://localhost:9006/Service?xsd=1"/>
</xsd:schema>
</types>
</code>```

It contains reference to XML schema defining structure of XML messages used in web-service. If you open URI http://localhost:9006/Service?xsd=1 as well (URI can differ, please check it), you'll see definition of request and response message:

```<code><xs:schema xmlns:tns="http://example.soap.kdv.org/" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0" targetNamespace="http://example.soap.kdv.org/">
<xs:element name="message" type="tns:message"/>
<xs:element name="messageResponse" type="tns:messageResponse"/>
<xs:complexType name="message">
<xs:sequence>
<xs:element name="arg0" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="messageResponse">
<xs:sequence>
<xs:element name="return" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
</code>```

It defines following structure of request message:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:exam="http://example.soap.kdv.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <exam:message>
         <!--Optional:-->
         <arg0>test</arg0>
      </exam:message>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

Try this message in postman, it should return you desired result.

Also I'd like to recommend SOAP UI tool for testing web services. When creating new SOAP project in this tool, it imports WSDLs and generates for you request messages.

Body:
I am new to SOAP and POSTMAN and am wondering what I am doing wrong with the following. I have a sample java webservice using jax-ws:

@WebService(endpointInterface = "Soap1.SOAPInterface")
public class SOAPService implements SOAPInterface
{
public String message(String name)
{
    return "Hello " + name;
}
}

I published this webservice using an Endpoint:

public class Publisher
{
public static void main(String[]args)
{
    Endpoint.publish("http://localhost:9006/Service", new SOAPService());
}
}

Now when I run this in a client it works fine

    public static void main(String[] args) throws Exception
    {
    URL url = new URL("http://localhost:9006/Service?wsdl");
    QName qname = new QName("http://Soap1/","SOAPServiceService");
    Service s = Service.create(url,qname);
    SOAPInterface i = s.getPort(SOAPInterface.class);
    System.out.println(i.message("Bob"));
    }

However when trying to use POSTMAN to analyze SOAP request/responses. By entering the following xml for a request:

<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">

        <MyMessage xmlns="http://Soap1/">
            <name>Bob</name>
        </MyMessage>

</Envelope>

I get a response of Hello null

<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:MyMessageResponse xmlns:ns2="http://Soap1/">
            <returnedMessage>Hello null</returnedMessage>
        </ns2:MyMessageResponse>
    </S:Body>
</S:Envelope>

I am wondering why this is because using the client, the parameters are passing fine but when using POSTMAN they seem not to be passing.

Screenshot of postman:

Body:
If you open in browser URI http://localhost:9006/Service?wsdl, you'll see WSDL generated by JAX-WS for your service. It should contain following snippet:

<types>
<xsd:schema>
<xsd:import namespace="http://example.soap.kdv.org/" schemaLocation="http://localhost:9006/Service?xsd=1"/>
</xsd:schema>
</types>

It contains reference to XML schema defining structure of XML messages used in web-service. If you open URI http://localhost:9006/Service?xsd=1 as well (URI can differ, please check it), you'll see definition of request and response message:

<xs:schema xmlns:tns="http://example.soap.kdv.org/" xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0" targetNamespace="http://example.soap.kdv.org/">
<xs:element name="message" type="tns:message"/>
<xs:element name="messageResponse" type="tns:messageResponse"/>
<xs:complexType name="message">
<xs:sequence>
<xs:element name="arg0" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="messageResponse">
<xs:sequence>
<xs:element name="return" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:schema>

It defines following structure of request message:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:exam="http://example.soap.kdv.org/">
   <soapenv:Header/>
   <soapenv:Body>
      <exam:message>
         <!--Optional:-->
         <arg0>test</arg0>
      </exam:message>
   </soapenv:Body>
</soapenv:Envelope>

Try this message in postman, it should return you desired result.

Also I'd like to recommend SOAP UI tool for testing web services. When creating new SOAP project in this tool, it imports WSDLs and generates for you request messages.


问:
Automatically running unit tests in Haskell
Is there a way to run my test suites with my build command? All I can find is that I can run e.g. cabal test after cabal build. What I want is a way to automatically run my tests when running e.g. cabal build.

I want a solution that will automate this for anyone building the package without requiring them to run a different script. An analogy would be a java build script where the default build target runs unit tests after compiling.

答:
I find this a really bad idea since it's unexpected, non-canonical behavior that breaks cross-compilation, but you can probably hack it together with a Custom build type.

Here's an example mypackage.cabal:

```<code>cabal-version:       >=2.0
name:                mypackage
version:             0.1.0.0
author:              None
maintainer:          none@example.com
build-type:          Custom

custom-setup
  setup-depends:
    base  >= 4.5,
    Cabal >= 2.0

executable mypackage
  main-is: Main.hs
  build-depends: base >= 4
  default-language: Haskell2010

test-suite test
  type: exitcode-stdio-1.0
  build-depends: base >= 4
  main-is: Test.hs
</code>```

and a corresponding Setup.hs:

```<code>import Control.Monad
import Distribution.Simple
import Distribution.Simple.Setup
import Distribution.Simple.Test
import Distribution.Simple.Build

main = defaultMainWithHooks simpleUserHooks {
  postBuild = myPostBuild
}

myPostBuild args flags desc info =
  when ("exe:mypackage" `elem` buildArgs flags) $ do
    build desc info defaultBuildFlags { buildDistPref = buildDistPref flags } []
    test ["test"] desc info defaultTestFlags {
      testDistPref = buildDistPref flags
    }
</code>```

This does result in a project where cabal build also builds and runs the tests on my Cabal 3.0.0.0 system, but I don't know which additional caveats this has.

Body:
I find this a really bad idea since it's unexpected, non-canonical behavior that breaks cross-compilation, but you can probably hack it together with a Custom build type.

Here's an example mypackage.cabal:

cabal-version:       >=2.0
name:                mypackage
version:             0.1.0.0
author:              None
maintainer:          none@example.com
build-type:          Custom

custom-setup
  setup-depends:
    base  >= 4.5,
    Cabal >= 2.0

executable mypackage
  main-is: Main.hs
  build-depends: base >= 4
  default-language: Haskell2010

test-suite test
  type: exitcode-stdio-1.0
  build-depends: base >= 4
  main-is: Test.hs

and a corresponding Setup.hs:

import Control.Monad
import Distribution.Simple
import Distribution.Simple.Setup
import Distribution.Simple.Test
import Distribution.Simple.Build

main = defaultMainWithHooks simpleUserHooks {
  postBuild = myPostBuild
}

myPostBuild args flags desc info =
  when ("exe:mypackage" `elem` buildArgs flags) $ do
    build desc info defaultBuildFlags { buildDistPref = buildDistPref flags } []
    test ["test"] desc info defaultTestFlags {
      testDistPref = buildDistPref flags
    }

This does result in a project where cabal build also builds and runs the tests on my Cabal 3.0.0.0 system, but I don't know which additional caveats this has.