问:
Looking for a simpler Objective-C solution
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

```<code>-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;
</code>```

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

答:
Does it have to be a dictionary? If not, perhaps resorting to some plain C might be easier to comprehend.</p>

```<code>typedef struct {
    unsigned strutCount;
    unsigned headAssembliesCount;
    BOOL leftVent;
    BOOL rightVent;
} Fields;

- (void) countFields:(Fields *) fields
{
    fields->strutCount = [self.struts count];
    fields->headAssembliesCount = [self.headAssemblies count];
    fields->leftVent = (self.leftVent != nil);
    fields->rightVent = (self.rightVent != nil);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

Body:
Does it have to be a dictionary? If not, perhaps resorting to some plain C might be easier to comprehend.

typedef struct {
    unsigned strutCount;
    unsigned headAssembliesCount;
    BOOL leftVent;
    BOOL rightVent;
} Fields;

- (void) countFields:(Fields *) fields
{
    fields->strutCount = [self.struts count];
    fields->headAssembliesCount = [self.headAssemblies count];
    fields->leftVent = (self.leftVent != nil);
    fields->rightVent = (self.rightVent != nil);
}

OwnerDisplayName: dreamlax


来源: stackexchange

问:
problem capturing keyboard input for Sprite
I an trying to capture keyboard and mouse events for square area on my UI, represented by Sprite. The mouse capture works, the keyboard capture doesn't work at all:

```<code>private var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000, 1);
square.graphics.drawRect(0, 0, 1024, 720);
square.graphics.endFill();
square.buttonMode = true;
...
square.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);

private function reportKeyDown(event:KeyboardEvent):void
{
trace("==>reportKeyDown: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " +         event.charCode + ")");
}
</code>```

I never see reportKeyDown executed, even though Sprite object has a focus.
Any idea what the problem is?
Thanks,
-V

答:
I answered a similar question very recently. As Flextras mentioned, controls that don't normally accept keyboard input won't dispatch the keyboard events.

As J_A_X mentioned, you can add an eventListener to the top level application for the KeyboardEvent.KEY_DOWN event and check for key combinations there however. From this article:

```<code><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
 layout="absolute" creationComplete="init()">
 <mx:Script>
 <![CDATA[
    private function init():void{
     this.addEventListener(MouseEvent.CLICK, clickHandler);
     this.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
    }
    private function clickHandler(event:MouseEvent):void {
      stage.focus = this;
    }
    private function keyPressed(evt:KeyboardEvent):void{
       if(evt.ctrlKey && evt.keyCode == 65)
             trace("CTRL A is pressed");
       if(evt.ctrlKey && evt.keyCode == 66)
             trace("CTRL B is pressed");
   }
 ]]>
 </mx:Script>
</mx:Application>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I an trying to capture keyboard and mouse events for square area on my UI, represented by Sprite. The mouse capture works, the keyboard capture doesn't work at all:

private var square:Sprite = new Sprite();
square.graphics.beginFill(0x000000, 1);
square.graphics.drawRect(0, 0, 1024, 720);
square.graphics.endFill();
square.buttonMode = true;
...
square.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);

private function reportKeyDown(event:KeyboardEvent):void
{
trace("==>reportKeyDown: " + String.fromCharCode(event.charCode) + " (key code: " +
event.keyCode + " character code: " +         event.charCode + ")");
}

I never see reportKeyDown executed, even though Sprite object has a focus.
Any idea what the problem is?
Thanks,
-V

Body:
I answered a similar question very recently. As Flextras mentioned, controls that don't normally accept keyboard input won't dispatch the keyboard events.

As J_A_X mentioned, you can add an eventListener to the top level application for the KeyboardEvent.KEY_DOWN event and check for key combinations there however. From this article:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
 layout="absolute" creationComplete="init()">
 <mx:Script>
 <![CDATA[
    private function init():void{
     this.addEventListener(MouseEvent.CLICK, clickHandler);
     this.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
    }
    private function clickHandler(event:MouseEvent):void {
      stage.focus = this;
    }
    private function keyPressed(evt:KeyboardEvent):void{
       if(evt.ctrlKey && evt.keyCode == 65)
             trace("CTRL A is pressed");
       if(evt.ctrlKey && evt.keyCode == 66)
             trace("CTRL B is pressed");
   }
 ]]>
 </mx:Script>
</mx:Application>


问:
Does it require to put load balancer before Redis cluster
I am using Redis Cluster on 3 Linux servers (CentOS 7). I have standard configuration i.e. 6 nodes, 3 master instances, and 3 slave instances (one master have one slave) distributed on these 3 Linux servers. I am using this setup for my web application for data caching, HTTP response caching. My aim is to read primary and write secondary i.e. Read operation should not fail or delayed.

Now I would like to ask is it necessary to configure any load balancer before by 3 Linux servers so that my web application requests to Redis cluster instances can be distributed properly on these Redis servers? Or Redis cluster itself able to handle the load distribution?

If Yes, then please mention any reference link to configure the same. I have checked official documentation  Redis Cluster but it does not specify anything regarding load balancer setup.

答:
If you're running Redis in "Cluster Mode" you don't need a load balancer. Your Redis client (assuming it's any good) should contact Redis for a list of which slots are on which nodes when your application starts up. It will hash keys locally (in your application) and send requests directly to the node which owns the slot for that key (which avoids the extra call to Redis which results in a MOVED response).

You should be able to configure your client to do reads on slave and writes on master - or to do both reads and writes on only masters. In addition to configuring your client, if you want to do reads on slaves, check out the READONLY command: https://redis.io/commands/readonly .

ContentLicense: CC BY-SA 4.0


问:
Python: How to retrive the best model from Optuna LightGBM study?
I would like to get the best model to use later in the notebook to predict using a different test batch.

reproducible example (taken from Optuna Github) :

```<code>import lightgbm as lgb
import numpy as np
import sklearn.datasets
import sklearn.metrics
from sklearn.model_selection import train_test_split

import optuna

# FYI: Objective functions can take additional arguments
# (https://optuna.readthedocs.io/en/stable/faq.html#objective-func-additional-args).
def objective(trial):
    data, target = sklearn.datasets.load_breast_cancer(return_X_y=True)
    train_x, valid_x, train_y, valid_y = train_test_split(data, target, test_size=0.25)
    dtrain = lgb.Dataset(train_x, label=train_y)
    dvalid = lgb.Dataset(valid_x, label=valid_y)

    param = {
        "objective": "binary",
        "metric": "auc",
        "verbosity": -1,
        "boosting_type": "gbdt",
        "lambda_l1": trial.suggest_loguniform("lambda_l1", 1e-8, 10.0),
        "lambda_l2": trial.suggest_loguniform("lambda_l2", 1e-8, 10.0),
        "num_leaves": trial.suggest_int("num_leaves", 2, 256),
        "feature_fraction": trial.suggest_uniform("feature_fraction", 0.4, 1.0),
        "bagging_fraction": trial.suggest_uniform("bagging_fraction", 0.4, 1.0),
        "bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
        "min_child_samples": trial.suggest_int("min_child_samples", 5, 100),
    }

    # Add a callback for pruning.
    pruning_callback = optuna.integration.LightGBMPruningCallback(trial, "auc")
    gbm = lgb.train(
        param, dtrain, valid_sets=[dvalid], verbose_eval=False, callbacks=[pruning_callback]
    )

    preds = gbm.predict(valid_x)
    pred_labels = np.rint(preds)
    accuracy = sklearn.metrics.accuracy_score(valid_y, pred_labels)
    return accuracy

</code>```

my understanding is that the study below will tune for accuracy. I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle, I just want to use the model somewhere else in my notebook.

```<code>
if __name__ == "__main__":
    study = optuna.create_study(
        pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
    )
    study.optimize(objective, n_trials=100)

    print("Best trial:")
    trial = study.best_trial

    print("  Params: ")
    for key, value in trial.params.items():
        print("    {}: {}".format(key, value))

</code>```

desired output would be

```<code>best_model = ~model from above~
new_target_pred = best_model.predict(new_data_test)
metrics.accuracy_score(new_target_test, new__target_pred)

</code>```

答:
I think you can use the callback argument of Study.optimize to save the best model. In the following code example, the callback checks if a given trial is corresponding to the best trial and saves the model as a global variable best_booster.

best_booster = None
gbm = None

def objective(trial):
    global gbm
    # ...

def callback(study, trial):
    global best_booster
    if study.best_trial == trial:
        best_booster = gbm

if __name__ == "__main__":
    study = optuna.create_study(
        pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
    )
    study.optimize(objective, n_trials=100, callbacks=[callback])

```

If you define your objective function as a class, you can remove the global variables. I created a notebook as a code example. Please take a look at it:
https://colab.research.google.com/drive/1ssjXp74bJ8bCAbvXFOC4EIycBto_ONp_?usp=sharing

I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle

FYI, if you can pickle the boosters, I think you can make the code simple by following this FAQ.

Body:
I would like to get the best model to use later in the notebook to predict using a different test batch.

reproducible example (taken from Optuna Github) :

import lightgbm as lgb
import numpy as np
import sklearn.datasets
import sklearn.metrics
from sklearn.model_selection import train_test_split

import optuna

# FYI: Objective functions can take additional arguments
# (https://optuna.readthedocs.io/en/stable/faq.html#objective-func-additional-args).
def objective(trial):
    data, target = sklearn.datasets.load_breast_cancer(return_X_y=True)
    train_x, valid_x, train_y, valid_y = train_test_split(data, target, test_size=0.25)
    dtrain = lgb.Dataset(train_x, label=train_y)
    dvalid = lgb.Dataset(valid_x, label=valid_y)

    param = {
        "objective": "binary",
        "metric": "auc",
        "verbosity": -1,
        "boosting_type": "gbdt",
        "lambda_l1": trial.suggest_loguniform("lambda_l1", 1e-8, 10.0),
        "lambda_l2": trial.suggest_loguniform("lambda_l2", 1e-8, 10.0),
        "num_leaves": trial.suggest_int("num_leaves", 2, 256),
        "feature_fraction": trial.suggest_uniform("feature_fraction", 0.4, 1.0),
        "bagging_fraction": trial.suggest_uniform("bagging_fraction", 0.4, 1.0),
        "bagging_freq": trial.suggest_int("bagging_freq", 1, 7),
        "min_child_samples": trial.suggest_int("min_child_samples", 5, 100),
    }

    # Add a callback for pruning.
    pruning_callback = optuna.integration.LightGBMPruningCallback(trial, "auc")
    gbm = lgb.train(
        param, dtrain, valid_sets=[dvalid], verbose_eval=False, callbacks=[pruning_callback]
    )

    preds = gbm.predict(valid_x)
    pred_labels = np.rint(preds)
    accuracy = sklearn.metrics.accuracy_score(valid_y, pred_labels)
    return accuracy

my understanding is that the study below will tune for accuracy. I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle, I just want to use the model somewhere else in my notebook.

if __name__ == "__main__":
    study = optuna.create_study(
        pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
    )
    study.optimize(objective, n_trials=100)

    print("Best trial:")
    trial = study.best_trial

    print("  Params: ")
    for key, value in trial.params.items():
        print("    {}: {}".format(key, value))

desired output would be

best_model = ~model from above~
new_target_pred = best_model.predict(new_data_test)
metrics.accuracy_score(new_target_test, new__target_pred)

Body:
I think you can use the callback argument of Study.optimize to save the best model. In the following code example, the callback checks if a given trial is corresponding to the best trial and saves the model as a global variable best_booster.

best_booster = None
gbm = None

def objective(trial):
    global gbm
    # ...

def callback(study, trial):
    global best_booster
    if study.best_trial == trial:
        best_booster = gbm

if __name__ == "__main__":
    study = optuna.create_study(
        pruner=optuna.pruners.MedianPruner(n_warmup_steps=10), direction="maximize"
    )
    study.optimize(objective, n_trials=100, callbacks=[callback])

If you define your objective function as a class, you can remove the global variables. I created a notebook as a code example. Please take a look at it:
https://colab.research.google.com/drive/1ssjXp74bJ8bCAbvXFOC4EIycBto_ONp_?usp=sharing

I would like to somehow retrieve the best model from the study (not just the parameters) without saving it as a pickle

FYI, if you can pickle the boosters, I think you can make the code simple by following this FAQ.


问:
How can I secure several azure web apps with one SSL Certificate
I would like to know if it is possible to secure several azure web apps with one SSL Certificate.

Example:

webapp1.azurewebsite.net => app.com

webapp2.azurewebsite.net => app2.com

webapp3.azurewebsite.net => app3.com

3 different domains 1 one SSL Certificate

答:
You can use a wildcard cert, *.foo.com. They are usually more $$ than a non-wildcard cert, however.

Your scenario, won't support wildcards, however because your you are using top-level domains (a.com, b.com etc), if they were a.foo.com and b.foo.com that would work.

Another option, and I don't know which CAs support this, is to use Subject Alternate Names https://en.wikipedia.org/wiki/Subject_Alternative_Name


问:
Blazor: Invoking C# static method from JS function called from HTML onclick--why can't the JS find the method?
Inside a Blazor component, I want to call a JS method from the HTML onclick event of an anchor tag, thus:

```<code><a onclick="window.LoadImage();" class="@CssClass">@DisplayName</a>
</code>```

My JS method is:

```<code>window.LoadImage = () => {
    DotNet.invokeMethodAsync('MyProject', 'FireEvent').then();
}
</code>```

Inside the JS method, I want to fire a C# static method to trigger an event, thus:

```<code>[JSInvokable]
public static void FireEvent()
{
   StateEngine.LoadImage(DisplayName, Target);
}
[Parameter]
public string DisplayName { get; set; }
[Parameter]
public string Target { get; set; }

</code>```

I can't get the JS method to find the C# method. I've tried multiple name configurations for the first parameter, like

```<code>MyProject (the assembly name)
MyProject.FolderName.ComponentName
FolderName.ComponentName
ComponentName
</code>```

to name a few. I've also tried shuffling names through the second parameter.

How is this supposed to work? What am I missing?

P.S. Please disregard the bit about the instance properties in the static method.  I've got a workaround for that, but don't want to clutter up the post.

答:
From the looks of it, you would be better off using the reference JSInterop so you can access the components properties.

Razor

```<code>@inject IJSRuntime JS
@implements IDisposable

 <a @onclick=Clicked>Click here</a>

@code
{
  private DotNetObjecctReference ObjRef;

  [JSInvokable]
  public void FireEvent()
  {
     StateEngine.LoadImage(DisplayName, Target);
  }

  private Task Clicked()
  {
    return JS.InvokeVoidAsync("window.LoadImage", ObjRef);
  }

  protected override Task OnInitializedAsync()
  {
    ObjRef = DotNetObjectReference.Create(this);
  }

  void IDisposable.Dispose()
  {
    ObjRef.Dispose();
  }
}
</code>```

JS

```<code>window.LoadImage = (dotNetObject) => {
    dotNetObject.invokeMethod('FireEvent');
}
</code>```

Body:
Inside a Blazor component, I want to call a JS method from the HTML onclick event of an anchor tag, thus:

@DisplayName

My JS method is:

window.LoadImage = () => {
    DotNet.invokeMethodAsync('MyProject', 'FireEvent').then();
}

Inside the JS method, I want to fire a C# static method to trigger an event, thus:

[JSInvokable]
public static void FireEvent()
{
   StateEngine.LoadImage(DisplayName, Target);
}
[Parameter]
public string DisplayName { get; set; }
[Parameter]
public string Target { get; set; }

I can't get the JS method to find the C# method. I've tried multiple name configurations for the first parameter, like

MyProject (the assembly name)
MyProject.FolderName.ComponentName
FolderName.ComponentName
ComponentName

to name a few. I've also tried shuffling names through the second parameter.

How is this supposed to work? What am I missing?

P.S. Please disregard the bit about the instance properties in the static method.  I've got a workaround for that, but don't want to clutter up the post.

Body:
From the looks of it, you would be better off using the reference JSInterop so you can access the components properties.

Razor

@inject IJSRuntime JS
@implements IDisposable

 <a @onclick=Clicked>Click here</a>

@code
{
  private DotNetObjecctReference ObjRef;

  [JSInvokable]
  public void FireEvent()
  {
     StateEngine.LoadImage(DisplayName, Target);
  }

  private Task Clicked()
  {
    return JS.InvokeVoidAsync("window.LoadImage", ObjRef);
  }

  protected override Task OnInitializedAsync()
  {
    ObjRef = DotNetObjectReference.Create(this);
  }

  void IDisposable.Dispose()
  {
    ObjRef.Dispose();
  }
}

JS

window.LoadImage = (dotNetObject) => {
    dotNetObject.invokeMethod('FireEvent');
}


问:
Link not working in anchor tag in django Template
I have a django project with custom user model. When the user registers, he also gives url of his company's website. I access and display it in the template using the USER. But it won't open as a separate link when I write it in an anchor tag as follows:

```<code><li><b>Company Website</b><br><a href="{{ detail.company_site }}" target="_blank">{{ detail.company_site }}</a></li>
</code>```

Instead it takes me to this link

```<code>http://localhost:8000/detail/ahftech.com
</code>```

答:
Well, I figured it out myself. I simply added https:// as follows:

Before:

```<code><li><b>Company Website</b><br><a href="{{ detail.company_site }}" target="_blank">{{ detail.company_site }}</a></li
</code>```

After:

```<code><li><b>Company Website</b><br><a href="https://{{ detail.company_site }}" target="_blank">{{ detail.company_site }}</a></li>
</code>```

Body:
I have a django project with custom user model. When the user registers, he also gives url of his company's website. I access and display it in the template using the USER. But it won't open as a separate link when I write it in an anchor tag as follows:

Company Website
{{ detail.company_site }}

Instead it takes me to this link

http://localhost:8000/detail/ahftech.com

Body:
Well, I figured it out myself. I simply added https:// as follows:

Before:

<li><b>Company Website</b><br><a href="{{ detail.company_site }}" target="_blank">{{ detail.company_site }}</a></li

After:

<li><b>Company Website</b><br><a href="https://{{ detail.company_site }}" target="_blank">{{ detail.company_site }}</a></li>


问:
How to Fix CWE-470: Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection')
I got a 470 on a line in my code and rightfully so as defined by Vera.

Vera says to fix:

Apply strict input validation by using whitelists or indirect
  selection to ensure that the user is only selecting allowable classes
  or code.

So I created a strict whitelist of what class name reflection can have access to as a Set<String>

I then wrapped the Class.forName in an

```<code>if (whitelist.contains(className) {
   Veracode still fires in here with a 470
}
</code>```

Anyone know what the fix has to look like for Vera not to fire? I feel I have followed their recommended remediation.

答:
I have managed to resolve it using sanitizer class/method that get className validate and return value from String from hard coded value - for example:

public class MySanitizer {

```<code>public static String sanitizeClassName(final String className) throws MyException {

    if(!className.equals("com.my.MyClass"))
        throw new MyException("Class not valid: "  + className);

    return "com.my.MyClass";
}
</code>```

Body:
I got a 470 on a line in my code and rightfully so as defined by Vera.

Vera says to fix:

Apply strict input validation by using whitelists or indirect
  selection to ensure that the user is only selecting allowable classes
  or code.

So I created a strict whitelist of what class name reflection can have access to as a Set<String>

I then wrapped the Class.forName in an

if (whitelist.contains(className) {
   Veracode still fires in here with a 470
}

Anyone know what the fix has to look like for Vera not to fire? I feel I have followed their recommended remediation.

Body:
I have managed to resolve it using sanitizer class/method that get className validate and return value from String from hard coded value - for example:

public class MySanitizer {

public static String sanitizeClassName(final String className) throws MyException {

    if(!className.equals("com.my.MyClass"))
        throw new MyException("Class not valid: "  + className);

    return "com.my.MyClass";
}


问:
fisheye distortion
I've found the code below written in java that places a fisheye effect on a buffered image. Is it possible to use this code on a different image format eg jpeg or bitmap? I've tried replacing the bufferedImage with bitmap and instead of using set/getARGB i've replaced with bitmap's get/setPixel. i just get a black bitmap.... i know was a bit of a long-shot:). </p>

```<code>import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.jhlabs.image.InterpolateFilter;

class Filters{
    float xscale;
    float yscale;
    float xshift;
    float yshift;
    int [] s;
    public Filters(){

    }

    public BufferedImage barrel (BufferedImage input, float k){

        float centerX=input.getWidth()/2; //center of distortion
        float centerY=input.getHeight()/2;

        int width = input.getWidth(); //image bounds
        int height = input.getHeight();

        BufferedImage dst = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); //output pic

          xshift = calc_shift(0,centerX-1,centerX,k);
          float newcenterX = width-centerX;
          float xshift_2 = calc_shift(0,newcenterX-1,newcenterX,k);

          yshift = calc_shift(0,centerY-1,centerY,k);
          float newcenterY = height-centerY;
          float yshift_2 = calc_shift(0,newcenterY-1,newcenterY,k);

          xscale = (width-xshift-xshift_2)/width;
          yscale = (height-yshift-yshift_2)/height;

          for(int j=0;j<dst.getHeight();j++){
              for(int i=0;i<dst.getWidth();i++){
                float x = getRadialX((float)i,(float)j,centerX,centerY,k);
                float y = getRadialY((float)i,(float)j,centerX,centerY,k);
                sampleImage(input,x,y);
                int color = ((s[1]&0x0ff)<<16)|((s[2]&0x0ff)<<8)|(s[3]&0x0ff);
    //            System.out.print(i+" "+j+" \\");

                dst.setRGB(i, j, color);

              }
            }
        return dst;
    }

    void sampleImage(BufferedImage arr, float idx0, float idx1)
    {
        s = new int [4];
      if(idx0<0 || idx1<0 || idx0>(arr.getHeight()-1) || idx1>(arr.getWidth()-1)){
        s[0]=0;
        s[1]=0;
        s[2]=0;
        s[3]=0;
        return;
      }

      float idx0_fl=(float) Math.floor(idx0);
      float idx0_cl=(float) Math.ceil(idx0);
      float idx1_fl=(float) Math.floor(idx1);
      float idx1_cl=(float) Math.ceil(idx1);

      int [] s1 = getARGB(arr,(int)idx0_fl,(int)idx1_fl);
      int [] s2 = getARGB(arr,(int)idx0_fl,(int)idx1_cl);
      int [] s3 = getARGB(arr,(int)idx0_cl,(int)idx1_cl);
      int [] s4 = getARGB(arr,(int)idx0_cl,(int)idx1_fl);

      float x = idx0 - idx0_fl;
      float y = idx1 - idx1_fl;

      s[0]= (int) (s1[0]*(1-x)*(1-y) + s2[0]*(1-x)*y + s3[0]*x*y + s4[0]*x*(1-y));
      s[1]= (int) (s1[1]*(1-x)*(1-y) + s2[1]*(1-x)*y + s3[1]*x*y + s4[1]*x*(1-y));
      s[2]= (int) (s1[2]*(1-x)*(1-y) + s2[2]*(1-x)*y + s3[2]*x*y + s4[2]*x*(1-y));
      s[3]= (int) (s1[3]*(1-x)*(1-y) + s2[3]*(1-x)*y + s3[3]*x*y + s4[3]*x*(1-y));
    }

    int [] getARGB(BufferedImage buf,int x, int y){
        int rgb = buf.getRGB(x, y); // Returns by default ARGB.
        int [] scalar = new int[4];
        scalar[0] = (rgb >>> 24) & 0xFF;
        scalar[1] = (rgb >>> 16) & 0xFF;
        scalar[2] = (rgb >>> 8) & 0xFF;
        scalar[3] = (rgb >>> 0) & 0xFF;
        return scalar;
    }

    float getRadialX(float x,float y,float cx,float cy,float k){
      x = (x*xscale+xshift);
      y = (y*yscale+yshift);
      float res = x+((x-cx)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy)));
      return res;
    }

    float getRadialY(float x,float y,float cx,float cy,float k){
      x = (x*xscale+xshift);
      y = (y*yscale+yshift);
      float res = y+((y-cy)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy)));
      return res;
    }

    float thresh = 1;

    float calc_shift(float x1,float x2,float cx,float k){
      float x3 = (float)(x1+(x2-x1)*0.5);
      float res1 = x1+((x1-cx)*k*((x1-cx)*(x1-cx)));
      float res3 = x3+((x3-cx)*k*((x3-cx)*(x3-cx)));

      if(res1>-thresh && res1 < thresh)
        return x1;
      if(res3<0){
        return calc_shift(x3,x2,cx,k);
      }
      else{
        return calc_shift(x1,x3,cx,k);
      }
    }
}
</code>```

答: The short answer is "yes, it is possible".  It will take some time for you to translate the BufferedImage methods to the Bitmap methods but there are plenty of good references online that will be able to help you out.</p>

Title: fisheye distortion

Body:
I've found the code below written in java that places a fisheye effect on a buffered image. Is it possible to use this code on a different image format eg jpeg or bitmap? I've tried replacing the bufferedImage with bitmap and instead of using set/getARGB i've replaced with bitmap's get/setPixel. i just get a black bitmap.... i know was a bit of a long-shot:).

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.jhlabs.image.InterpolateFilter;

class Filters{
    float xscale;
    float yscale;
    float xshift;
    float yshift;
    int [] s;
    public Filters(){

    }

    public BufferedImage barrel (BufferedImage input, float k){

        float centerX=input.getWidth()/2; //center of distortion
        float centerY=input.getHeight()/2;

        int width = input.getWidth(); //image bounds
        int height = input.getHeight();

        BufferedImage dst = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); //output pic

          xshift = calc_shift(0,centerX-1,centerX,k);
          float newcenterX = width-centerX;
          float xshift_2 = calc_shift(0,newcenterX-1,newcenterX,k);

          yshift = calc_shift(0,centerY-1,centerY,k);
          float newcenterY = height-centerY;
          float yshift_2 = calc_shift(0,newcenterY-1,newcenterY,k);

          xscale = (width-xshift-xshift_2)/width;
          yscale = (height-yshift-yshift_2)/height;

          for(int j=0;j<dst.getHeight();j++){
              for(int i=0;i<dst.getWidth();i++){
                float x = getRadialX((float)i,(float)j,centerX,centerY,k);
                float y = getRadialY((float)i,(float)j,centerX,centerY,k);
                sampleImage(input,x,y);
                int color = ((s[1]&0x0ff)<<16)|((s[2]&0x0ff)<<8)|(s[3]&0x0ff);
    //            System.out.print(i+" "+j+" \\");

                dst.setRGB(i, j, color);

              }
            }
        return dst;
    }

    void sampleImage(BufferedImage arr, float idx0, float idx1)
    {
        s = new int [4];
      if(idx0<0 || idx1<0 || idx0>(arr.getHeight()-1) || idx1>(arr.getWidth()-1)){
        s[0]=0;
        s[1]=0;
        s[2]=0;
        s[3]=0;
        return;
      }

      float idx0_fl=(float) Math.floor(idx0);
      float idx0_cl=(float) Math.ceil(idx0);
      float idx1_fl=(float) Math.floor(idx1);
      float idx1_cl=(float) Math.ceil(idx1);

      int [] s1 = getARGB(arr,(int)idx0_fl,(int)idx1_fl);
      int [] s2 = getARGB(arr,(int)idx0_fl,(int)idx1_cl);
      int [] s3 = getARGB(arr,(int)idx0_cl,(int)idx1_cl);
      int [] s4 = getARGB(arr,(int)idx0_cl,(int)idx1_fl);

      float x = idx0 - idx0_fl;
      float y = idx1 - idx1_fl;

      s[0]= (int) (s1[0]*(1-x)*(1-y) + s2[0]*(1-x)*y + s3[0]*x*y + s4[0]*x*(1-y));
      s[1]= (int) (s1[1]*(1-x)*(1-y) + s2[1]*(1-x)*y + s3[1]*x*y + s4[1]*x*(1-y));
      s[2]= (int) (s1[2]*(1-x)*(1-y) + s2[2]*(1-x)*y + s3[2]*x*y + s4[2]*x*(1-y));
      s[3]= (int) (s1[3]*(1-x)*(1-y) + s2[3]*(1-x)*y + s3[3]*x*y + s4[3]*x*(1-y));
    }

    int [] getARGB(BufferedImage buf,int x, int y){
        int rgb = buf.getRGB(x, y); // Returns by default ARGB.
        int [] scalar = new int[4];
        scalar[0] = (rgb >>> 24) & 0xFF;
        scalar[1] = (rgb >>> 16) & 0xFF;
        scalar[2] = (rgb >>> 8) & 0xFF;
        scalar[3] = (rgb >>> 0) & 0xFF;
        return scalar;
    }

    float getRadialX(float x,float y,float cx,float cy,float k){
      x = (x*xscale+xshift);
      y = (y*yscale+yshift);
      float res = x+((x-cx)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy)));
      return res;
    }

    float getRadialY(float x,float y,float cx,float cy,float k){
      x = (x*xscale+xshift);
      y = (y*yscale+yshift);
      float res = y+((y-cy)*k*((x-cx)*(x-cx)+(y-cy)*(y-cy)));
      return res;
    }

    float thresh = 1;

    float calc_shift(float x1,float x2,float cx,float k){
      float x3 = (float)(x1+(x2-x1)*0.5);
      float res1 = x1+((x1-cx)*k*((x1-cx)*(x1-cx)));
      float res3 = x3+((x3-cx)*k*((x3-cx)*(x3-cx)));

      if(res1>-thresh && res1 < thresh)
        return x1;
      if(res3<0){
        return calc_shift(x3,x2,cx,k);
      }
      else{
        return calc_shift(x1,x3,cx,k);
      }
    }
}


问:
Why do I get some errors using opus_demo command?
My goal is decoding opus file to pcm file.I try ffmpeg example[How do I decode opus file to pcm file using libavcodec from ffmpeg? not success.And I learn that libopus also can do it from Internet. So I download the libopus[https://opus-codec.org/release/stable/2019/04/12/libopus-1_3_1.html].After I get opus_demo from compiling opus_demo.c ,I run this.

```<code>./opus_demo
Usage: ./opus_demo [-e] <application> <sampling rate (Hz)> <channels (1/2)> <bits per second>  [options] <input> <output>
       ./opus_demo -d <sampling rate (Hz)> <channels (1/2)> [options] <input> <output>

application: voip | audio | restricted-lowdelay
options:
-e                   : only runs the encoder (output the bit-stream)
-d                   : only runs the decoder (reads the bit-stream as input)
-cbr                 : enable constant bitrate; default: variable bitrate
-cvbr                : enable constrained variable bitrate; default: unconstrained
-delayed-decision    : use look-ahead for speech/music detection (experts only); default: disabled
-bandwidth <NB|MB|WB|SWB|FB> : audio bandwidth (from narrowband to fullband); default: sampling rate
-framesize <2.5|5|10|20|40|60|80|100|120> : frame size in ms; default: 20
-max_payload <bytes> : maximum payload size in bytes, default: 1024
-complexity <comp>   : complexity, 0 (lowest) ... 10 (highest); default: 10
-inbandfec           : enable SILK inband FEC
-forcemono           : force mono encoding, even for stereo input
-dtx                 : enable SILK DTX
-loss <perc>         : simulate packet loss, in percent (0-100); default: 0

 ./opus_demo -d 16000 2 ./test.opus ./outfile.pcm
libopus 1.3.1
Decoding with 16000 Hz output (2 channels)
Invalid payload length: 440786851
bitrate statistics are undefined
</code>```

My opus file is captured from ffmpeg command.

```<code>ffmpeg -f avfoundation -i :0 out.opus
ffmpeg -i out.opus -acodec pcm_s16le -f s16le -ac 1 -ar 16000 ./out.pcm
ffplay -ar 16000 -ac 1 -f s16le -i ./out.pcm
</code>```

What should I do? And reach my goal.Please help me.

答:
Is this an Ogg Opus file?  opus_demo is more of a "tutorial" for learning to program with the libopus C library from what I remember.  You can decode using the CLI tools:

```<code>$ opusdec music.opus music.wav
</code>```

https://opus-codec.org/release/dev/2018/09/18/opus-tools-0_2.html

Body:
My goal is decoding opus file to pcm file.I try ffmpeg example[How do I decode opus file to pcm file using libavcodec from ffmpeg? not success.And I learn that libopus also can do it from Internet. So I download the libopus[https://opus-codec.org/release/stable/2019/04/12/libopus-1_3_1.html].After I get opus_demo from compiling opus_demo.c ,I run this.

./opus_demo
Usage: ./opus_demo [-e] <application> <sampling rate (Hz)> <channels (1/2)> <bits per second>  [options] <input> <output>
       ./opus_demo -d <sampling rate (Hz)> <channels (1/2)> [options] <input> <output>

application: voip | audio | restricted-lowdelay
options:
-e                   : only runs the encoder (output the bit-stream)
-d                   : only runs the decoder (reads the bit-stream as input)
-cbr                 : enable constant bitrate; default: variable bitrate
-cvbr                : enable constrained variable bitrate; default: unconstrained
-delayed-decision    : use look-ahead for speech/music detection (experts only); default: disabled
-bandwidth <NB|MB|WB|SWB|FB> : audio bandwidth (from narrowband to fullband); default: sampling rate
-framesize <2.5|5|10|20|40|60|80|100|120> : frame size in ms; default: 20
-max_payload <bytes> : maximum payload size in bytes, default: 1024
-complexity <comp>   : complexity, 0 (lowest) ... 10 (highest); default: 10
-inbandfec           : enable SILK inband FEC
-forcemono           : force mono encoding, even for stereo input
-dtx                 : enable SILK DTX
-loss <perc>         : simulate packet loss, in percent (0-100); default: 0

 ./opus_demo -d 16000 2 ./test.opus ./outfile.pcm
libopus 1.3.1
Decoding with 16000 Hz output (2 channels)
Invalid payload length: 440786851
bitrate statistics are undefined

My opus file is captured from ffmpeg command.

ffmpeg -f avfoundation -i :0 out.opus
ffmpeg -i out.opus -acodec pcm_s16le -f s16le -ac 1 -ar 16000 ./out.pcm
ffplay -ar 16000 -ac 1 -f s16le -i ./out.pcm

What should I do? And reach my goal.Please help me.

Body:
Is this an Ogg Opus file?  opus_demo is more of a "tutorial" for learning to program with the libopus C library from what I remember.  You can decode using the CLI tools:

$ opusdec music.opus music.wav

https://opus-codec.org/release/dev/2018/09/18/opus-tools-0_2.html


问:
How to find source for "Refused to execute inline event handler Because violates CSP blabla"
Keep getting this error and i know what it means, But can't find the source.

click the console source only leads me here.

答:
Just search your source code (html) for any inline instances of on*="..." (e.g. onClick, onclick, onSubmit, etc..) since you seem to have inline event handlers.

Other event handler names can be found here and in the linked documentation: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers


问:
React + Redux state deleted on page refresh
I currently have a component that pulls a deck of cards from the backend and tries to create a chart out of values from those cards. On first load, everything works and the chart populates. On refresh, however, it seems that the decks prop is undefined (although redux devtools shows it's still present).

UseEffect:

```<code>useEffect(() => {
  getDecks();                      // sets "decks"
  populateData();
}, []);
</code>```

```<code>  const populateData = () => {
    var data = [0, 0, 0, 0, 0];
    cardArray = decks[0].cards;                // crashes here on reload; decks is undef.

    ...
    createChart(data);
  };
</code>```

```<code>export const getDecks = () => async (dispatch) => {
  try {
    const res = await axios.get("/api/decks");
    dispatch({
      type: GET_DECKS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: DECK_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};
</code>```

Initial state in deck reducer:

```<code>const initialState = {
  decks: [],
  currentCard: 0,
  loading: true,
  error: {},
  isFlipped: false,
};
</code>```

I've looked at similar posts that suggest that I store decks in localstorage, but I have other components that call getDecks display data from them similar to this one without any issues. Does anybody have any tips or possible reasons why this might be doing this? Thanks.

答:
Try doing this and see if it works. The component that calls the useEffect() should look like so:

```<code>import PropTypes from "prop-types";
import { connect } from "react-redux";
const deckComponent = ({decks}) => {
useEffect(() => {
  getDecks();
}, []);
useEffect(() => {
  populateData();
}, [decks]);

// rest of the component goes here
 return(
.............
    );
};

deckComponent.propTypes = {
  decks: PropTypes.object.isRequired,
  getDecks: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
  decks: state.decks,
});

export default connect(mapStateToProps, {
  getDecks,
})(deckComponent);
</code>```

What this does is that anytime your component is loaded, the getDecks() function is called to the backend decks state changes. The 2nd useEffect watches for this change on the redux store and calls populateData().

Body:
I currently have a component that pulls a deck of cards from the backend and tries to create a chart out of values from those cards. On first load, everything works and the chart populates. On refresh, however, it seems that the decks prop is undefined (although redux devtools shows it's still present).

UseEffect:

useEffect(() => {
  getDecks();                      // sets "decks"
  populateData();
}, []);

  const populateData = () => {
    var data = [0, 0, 0, 0, 0];
    cardArray = decks[0].cards;                // crashes here on reload; decks is undef.

    ...
    createChart(data);
  };

export const getDecks = () => async (dispatch) => {
  try {
    const res = await axios.get("/api/decks");
    dispatch({
      type: GET_DECKS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: DECK_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

Initial state in deck reducer:

const initialState = {
  decks: [],
  currentCard: 0,
  loading: true,
  error: {},
  isFlipped: false,
};

I've looked at similar posts that suggest that I store decks in localstorage, but I have other components that call getDecks display data from them similar to this one without any issues. Does anybody have any tips or possible reasons why this might be doing this? Thanks.

Body:
Try doing this and see if it works. The component that calls the useEffect() should look like so:

import PropTypes from "prop-types";
import { connect } from "react-redux";
const deckComponent = ({decks}) => {
useEffect(() => {
  getDecks();
}, []);
useEffect(() => {
  populateData();
}, [decks]);

// rest of the component goes here
 return(
.............
    );
};

deckComponent.propTypes = {
  decks: PropTypes.object.isRequired,
  getDecks: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
  decks: state.decks,
});

export default connect(mapStateToProps, {
  getDecks,
})(deckComponent);

What this does is that anytime your component is loaded, the getDecks() function is called to the backend decks state changes. The 2nd useEffect watches for this change on the redux store and calls populateData().


问:
App crashes with error 'Could not execute method for android:onClick' when try to validate empty field
I tried to create empty field validation that if user don't put any String/Integer and just press on the button, he will recive popup stating that field is empty.

I would appriciate any help.

See my code below:

```<code>...

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        Integer userNum = Integer.parseInt(editText.getText().toString());
        String userField = editText.getText().toString().trim();
        String message = "";

        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            mynumber.number = userNum;
            if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == false)) {

                makeToast("The number " + userNum + " is a Square number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is a Triangular number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == false)) {
                makeToast("The number " + userNum + " is a not Square or Triangular shape");
            } else if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is both Square & Triangular shapes");
            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
</code>```

答:
Thanks @Hakob your suggestion worked very well.
My problem afterwared was beacuse my Toast command has not been defined correctly.

So i had this: message = "please input something!!!!!";

And i change to this:  makeToast("please input something!!!!!");

Actully i didn't defined Toast command at all so the app didn't understand it should popup a message :).

Thanks again for all the help.

Body:
I tried to create empty field validation that if user don't put any String/Integer and just press on the button, he will recive popup stating that field is empty.

I would appriciate any help.

See my code below:

...

    public void clickCheck (View view) {
        EditText editText = (EditText) findViewById(R.id.userType);
        Integer userNum = Integer.parseInt(editText.getText().toString());
        String userField = editText.getText().toString().trim();
        String message = "";

        if (userField.isEmpty()) {
            message = "please input something!!!!!";
        } else {
            Shape mynumber = new Shape();
            mynumber.number = userNum;
            if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == false)) {

                makeToast("The number " + userNum + " is a Square number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is a Triangular number.");
            } else if ((mynumber.isSquareNum() == false) && (mynumber.isTriangularNum() == false)) {
                makeToast("The number " + userNum + " is a not Square or Triangular shape");
            } else if ((mynumber.isSquareNum() == true) && (mynumber.isTriangularNum() == true)) {
                makeToast("The number " + userNum + " is both Square & Triangular shapes");
            }

        }
    }

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


问:
C# Create symlink through bash does nothing
I found this function to run any command through bash from C#. So I tried passing it a command to create a symlink, but it's not doing anything. If I run that same command directly in a Terminal, it works. I tried running other commands like "ls" and that printed the proper items. Why isn't the symlink command working?

```<code>string output = ExecuteBashCommand("ln -s \"/Users/tim/academy-v2/Shared/Client Code\" \"/Users/tim/academy-v2/Shared Assets/Assets/Shared Code/Client Code\"");
UnityEngine.Debug.Log(output); // Prints "" like it worked, but didn't actually do anything.
</code>```

...

```<code>static string ExecuteBashCommand(string command)
{
    command = command.Replace("\"", "\"\"");

    var proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "/bin/bash",
            Arguments = "-c \"" + command + "\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        }
    };

    proc.Start();
    proc.WaitForExit();

    return proc.StandardOutput.ReadToEnd();
}
</code>```

答:
Replacing the command with this seems to work, though not sure why.</p>

```<code>"ln -s /Users/tim/academy-v2/Shared/Client\\ Code /Users/tim/academy-v2/Shared\\ Assets/Assets/Shared\\ Code/Client\\ Code"
</code>```

Body:
I found this function to run any command through bash from C#. So I tried passing it a command to create a symlink, but it's not doing anything. If I run that same command directly in a Terminal, it works. I tried running other commands like "ls" and that printed the proper items. Why isn't the symlink command working?

string output = ExecuteBashCommand("ln -s \"/Users/tim/academy-v2/Shared/Client Code\" \"/Users/tim/academy-v2/Shared Assets/Assets/Shared Code/Client Code\"");
UnityEngine.Debug.Log(output); // Prints "" like it worked, but didn't actually do anything.

...

static string ExecuteBashCommand(string command)
{
    command = command.Replace("\"", "\"\"");

    var proc = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "/bin/bash",
            Arguments = "-c \"" + command + "\"",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true
        }
    };

    proc.Start();
    proc.WaitForExit();

    return proc.StandardOutput.ReadToEnd();
}

Body:
Replacing the command with this seems to work, though not sure why.

"ln -s /Users/tim/academy-v2/Shared/Client\\ Code /Users/tim/academy-v2/Shared\\ Assets/Assets/Shared\\ Code/Client\\ Code"


问:
How to avoid implicit 'null' substitution in GraphQL (AWS App Sync)?
Consider below query:

const fetchItemsQuery = `query(
  $paginationPageSize: Int!
  $paginationPageNumber: Int!
  $searchByNameRequest: String
  $categoryID: String
) {
  getItems(
    paginationPageSize: $paginationPageSize
    paginationPageNumber: $paginationPageNumber
    searchByNameRequest: $searchByNameRequest
    categoryID: $categoryID
  ) {
    // ...
  }
};
```

<p>If to submit it from client side with variables:</p>

```{
  paginationPageSize: 20,
  paginationPageNumber: 1
}
```

<p>in AWS App Sync logs, it reads:</p>

```{
  paginationPageSize: 20,
  paginationPageNumber: 1,
  searchByNameRequest: null,
  categoryID: null
}
```

<p>I checked the request payload from browser - no nulls, just</p>

```{
  paginationPageSize: 20,
  paginationPageNumber: 1
}
```

<p>So the cause is not in frontend side. </p>

<p>I found out that the <code>null</code> substitution occurring in <strong>request resolving template</strong>: </p>

```{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": {
    "field": "listProduct",
    "arguments": $util.toJson($context.args) // <- here
  }
}
```

$util.toJson uses Apache Velocity.

Can I avoid $util.toJson($context.args) will substitute the nulls in my request variables?

Important: the solution should not touch the explicitly submitted nulls .

答:
You could try to filter out null arguments from the $context.args map.

```<code>#set( $args = {} )
#foreach( $entry in $context.args.entrySet())
  #if( $entry.value != $null )
    #set( $junk = $args.put($entry.key, $entry.value) )
  #end
#end

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": {
    "field": "listProduct",
    "arguments": $util.toJson($args)
  }
}
</code>```

Body:
Consider below query:

const fetchItemsQuery = `query(
  $paginationPageSize: Int!
  $paginationPageNumber: Int!
  $searchByNameRequest: String
  $categoryID: String
) {
  getItems(
    paginationPageSize: $paginationPageSize
    paginationPageNumber: $paginationPageNumber
    searchByNameRequest: $searchByNameRequest
    categoryID: $categoryID
  ) {
    // ...
  }
};

If to submit it from client side with variables:

{
  paginationPageSize: 20,
  paginationPageNumber: 1
}

in AWS App Sync logs, it reads:

{
  paginationPageSize: 20,
  paginationPageNumber: 1,
  searchByNameRequest: null,
  categoryID: null
}

I checked the request payload from browser - no nulls, just

{
  paginationPageSize: 20,
  paginationPageNumber: 1
}

So the cause is not in frontend side.

I found out that the null substitution occurring in request resolving template:

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": {
    "field": "listProduct",
    "arguments": $util.toJson($context.args) // <- here
  }
}

$util.toJson uses Apache Velocity.

Can I avoid $util.toJson($context.args) will substitute the nulls in my request variables?

Important: the solution should not touch the explicitly submitted nulls .

Body:
You could try to filter out null arguments from the $context.args map.

#set( $args = {} )
#foreach( $entry in $context.args.entrySet())
  #if( $entry.value != $null )
    #set( $junk = $args.put($entry.key, $entry.value) )
  #end
#end

{
  "version" : "2017-02-28",
  "operation": "Invoke",
  "payload": {
    "field": "listProduct",
    "arguments": $util.toJson($args)
  }
}


问:
I am new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.</p>

```<code>
prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')
</code>```

答:
You must convert your input value to an integer before using comparators

lower() means you're converting it to lower chars

strip() means you're removing spaces surrounding the text

prompt = ''
while prompt.lower().strip() != 'quit':
    prompt = input("Enter your age (enter 'quit' to exit) : ")
    if prompt.lower().strip() != 'quit':
        age = int(prompt) # Converting prompt to an integer
        print(f"Your age : {age}")
        if age > 13:
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below\n')

        if age <= 13 and age >= 3:
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below\n')

        if age < 3:
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below\n')

print(f'Thank You Enjoy the show')
```

<p>Here is the result :</p>

```Enter your age (enter 'quit' to exit) : 2
Your age : 2
Your ticket price is free
Retrieve your ticket below

Enter your age (enter 'quit' to exit) : 3
Your age : 3
Your ticket price is $10.00.
Retrieve your ticket(s) below

Enter your age (enter 'quit' to exit) : 13
Your age : 13
Your ticket price is $10.00.
Retrieve your ticket(s) below

Enter your age (enter 'quit' to exit) : 16
Your age : 16
You ticket price is $15.00.
Retrieve your ticket(s) below

Enter your age (enter 'quit' to exit) : QuIt # Caps doesn't matter
Thank You Enjoy the show
```

Body:
My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.

prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''

while age != 'quit':

    age = input(prompt)
    print(age)
    if age != 'quit':
        if age > '13':
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below')

        if age <= '13' and age > '2':
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below')

        if age < '3':
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below')

print(f'Thank You Enjoy the show')

Body:
You must convert your input value to an integer before using comparators

lower() means you're converting it to lower chars

strip() means you're removing spaces surrounding the text

prompt = ''
while prompt.lower().strip() != 'quit':
    prompt = input("Enter your age (enter 'quit' to exit) : ")
    if prompt.lower().strip() != 'quit':
        age = int(prompt) # Converting prompt to an integer
        print(f"Your age : {age}")
        if age > 13:
            print(f'You ticket price is $15.00.')
            print(f'Retrieve your ticket(s) below\n')

        if age <= 13 and age >= 3:
            print(f'Your ticket price is $10.00.')
            print(f'Retrieve your ticket(s) below\n')

        if age < 3:
            print(f'Your ticket price is free')
            print(f'Retrieve your ticket below\n')

print(f'Thank You Enjoy the show')

Here is the result :

Enter your age (enter 'quit' to exit) : 2
Your age : 2
Your ticket price is free
Retrieve your ticket below

Enter your age (enter 'quit' to exit) : 3
Your age : 3
Your ticket price is $10.00.
Retrieve your ticket(s) below

Enter your age (enter 'quit' to exit) : 13
Your age : 13
Your ticket price is $10.00.
Retrieve your ticket(s) below

Enter your age (enter 'quit' to exit) : 16
Your age : 16
You ticket price is $15.00.
Retrieve your ticket(s) below

Enter your age (enter 'quit' to exit) : QuIt # Caps doesn't matter
Thank You Enjoy the show


问:
Store a mock object in the Environment
In my app, I want to store an object in Environment to perform network queries from various views. However, during development I'd like to use a mock instead, and retrieve the payload (in JSON format) from the app's bundle. These are the steps I've taken:

Specify the protocol

```<code>    typealias Token = String

    protocol MyAPIConforming {
        func signIn(username: String, password: String, completion: @escaping (Token?, Error?) -> Void)
    }
</code>```

Implement the two classes I need

```<code>    class MockMyAPIManager: MyAPIConforming, ObservableObject {
        func signIn(username: String, password: String, completion: @escaping (Token?, Error?) -> Void) {
            // Read the JSON document from the app's bundle
        }
    }

    class MyAPIManager: MyAPIConforming, ObservableObject {
        func signIn(username: String, password: String, completion: @escaping (Token?, Error?) -> Void) {
            // Perform the network request
        }
    }
</code>```

Inject the mock object in the Environment

```<code>    let myManager = MockMyAPIManager()

    // Create the SwiftUI view that provides the window contents.
    let contentView = LoginView().environmentObject(myManager)
</code>```

Declare the @Environment object in the view

```<code>    struct LoginView: View {
    @EnvironmentObject var myManager: MyAPIConforming
    ...
</code>```

I did declare myManager to be MyAPIConforming because I could be passing an object of type MockMyAPIManager or MyAPIManager.

However, in step #4 I get the following error:

Property type 'MyAPIConforming' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'

I'm not sure if the error means that there is no guarantee that the object adopting to MyAPIConforming will be also adopting the ObservableObject protocol.

So what do I need to do to store either MockMyAPIManager or MyAPIManager in the environment? Is this even possible?

答:
Here is a possible solution

```<code>struct LoginView<T: ObservableObject & MyAPIConforming>: View {
    @EnvironmentObject var myManager: T

        // other code here
}
</code>```

Update: usage

for content view

```<code>LoginView<MyAPIManager>().environmentObject(MyAPIManager())
</code>```

and for testing/preview

```<code>LoginView<MockMyAPIManager>().environmentObject(MockMyAPIManager())
</code>```

Title: Store a mock object in the Environment

Body:
In my app, I want to store an object in Environment to perform network queries from various views. However, during development I'd like to use a mock instead, and retrieve the payload (in JSON format) from the app's bundle. These are the steps I've taken:

Specify the protocol

    typealias Token = String

    protocol MyAPIConforming {
        func signIn(username: String, password: String, completion: @escaping (Token?, Error?) -> Void)
    }

Implement the two classes I need

    class MockMyAPIManager: MyAPIConforming, ObservableObject {
        func signIn(username: String, password: String, completion: @escaping (Token?, Error?) -> Void) {
            // Read the JSON document from the app's bundle
        }
    }

    class MyAPIManager: MyAPIConforming, ObservableObject {
        func signIn(username: String, password: String, completion: @escaping (Token?, Error?) -> Void) {
            // Perform the network request
        }
    }

Inject the mock object in the Environment

    let myManager = MockMyAPIManager()

    // Create the SwiftUI view that provides the window contents.
    let contentView = LoginView().environmentObject(myManager)

Declare the @Environment object in the view

    struct LoginView: View {
    @EnvironmentObject var myManager: MyAPIConforming
    ...

I did declare myManager to be MyAPIConforming because I could be passing an object of type MockMyAPIManager or MyAPIManager.

However, in step #4 I get the following error:

Property type 'MyAPIConforming' does not match that of the 'wrappedValue' property of its wrapper type 'EnvironmentObject'

I'm not sure if the error means that there is no guarantee that the object adopting to MyAPIConforming will be also adopting the ObservableObject protocol.

So what do I need to do to store either MockMyAPIManager or MyAPIManager in the environment? Is this even possible?

Body:
Here is a possible solution

struct LoginView<T: ObservableObject & MyAPIConforming>: View {
    @EnvironmentObject var myManager: T

        // other code here
}

Update: usage

for content view

LoginView<MyAPIManager>().environmentObject(MyAPIManager())

and for testing/preview

LoginView<MockMyAPIManager>().environmentObject(MockMyAPIManager())


问:
how to create a dynamic container in flutter according to image
I am trying to develop an app which has a container which contains a network image now I want that size of the container to adjust according to the size or image like if the image is in portrait the container height should set accordingly and if the image is in landscape it can adjust accordingly </p>

答:
If you want to adjust the size of the container with an image. I think it is easier to expand your image to the size of the container, so you only need to control the Container's size.

you can use the Expanded class.
Find the docs here.


问:
Optimize the code
I am new to python. I would like all the python gurus to suggest some ways to make the following code more pythonic and hence more efficient .
Its a simple code to find the edit distance between two words.

P.S. I would like improvements in code, not in the logic or algorithm optimization.

```<code>class test:
    def __init__(self,a,b,I=1,D=1,R=1):
        self.a = a
        self.b = b
        self.mem = dict()
        self.la = len(a)
        self.lb = len(b)
        self.I = I
        self.D = D
        self.R = R

    def diff(self,i=0,j=0):
        T = self.diff
        memo = self.mem
        if j == self.lb: return self.D * i
        if i == self.la: return self.D * j
        if (i,j) in memo:
            return memo[(i,j)]
        if self.a[i] == self.b[j]:
            memo[(i,j)] = T( i+1,j+1 )
            return memo[ (i,j) ]
        memo[(i,j)] = min(self.R + T(i+1,j+1) , self.D + T(i+1,j) , self.I + T(i,j+1) ,
         self.D + T(i,j+1) , self.I + T(i+1,j) )
        return memo[(i,j)]
</code>```

Variable explanation:

a,b are two string whose edit distance is to be found.
I,D,R Insertion Deletion and Replace cost of a single letter.
mem is dictionary used to memoize the recursive calls.
i and j are the pointers of the string a and b respectively

答:
Pythonic would be:

Write lots of unit tests.

Don't reinvent the wheel: search online for previous solutions to the problem. See the comments.

Don't optimise prematurely: profile your code to work out whether this really is
 a bottleneck and if it is improve the algorithm.

Meaningful variable names

Don't start local variable names with capital letters

Use normal whitespace inside parentheses T(i+1, j+1) not T( i+1,j+1 )

Don't use spurious parentheses round tuples: memo[i,j] not memo[(i,j)]

Don't optimise prematurely: self.diff(i+1, j+1) not T(i+1,j+1)

Title: Optimize the code

Body:
I am new to python. I would like all the python gurus to suggest some ways to make the following code more pythonic and hence more efficient .
Its a simple code to find the edit distance between two words.

P.S. I would like improvements in code, not in the logic or algorithm optimization.

class test:
    def __init__(self,a,b,I=1,D=1,R=1):
        self.a = a
        self.b = b
        self.mem = dict()
        self.la = len(a)
        self.lb = len(b)
        self.I = I
        self.D = D
        self.R = R

    def diff(self,i=0,j=0):
        T = self.diff
        memo = self.mem
        if j == self.lb: return self.D * i
        if i == self.la: return self.D * j
        if (i,j) in memo:
            return memo[(i,j)]
        if self.a[i] == self.b[j]:
            memo[(i,j)] = T( i+1,j+1 )
            return memo[ (i,j) ]
        memo[(i,j)] = min(self.R + T(i+1,j+1) , self.D + T(i+1,j) , self.I + T(i,j+1) ,
         self.D + T(i,j+1) , self.I + T(i+1,j) )
        return memo[(i,j)]

Variable explanation:

a,b are two string whose edit distance is to be found.
I,D,R Insertion Deletion and Replace cost of a single letter.
mem is dictionary used to memoize the recursive calls.
i and j are the pointers of the string a and b respectively


答:
For starters, you need to cast your input to an int. Input reads everything in as a string.

```<code>age = int(input(prompt))
</code>```

This would also mean you need to change

```<code>age != 'quit'
</code>```

After that, you need to make sure you are comparing int's not strings. A string can be greater than or less than another string, but not in the context that you are using them. Change '13' to 13 and so forth.

Title: I am new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?

Body:
For starters, you need to cast your input to an int. Input reads everything in as a string.

age = int(input(prompt))

This would also mean you need to change

age != 'quit'

After that, you need to make sure you are comparing int's not strings. A string can be greater than or less than another string, but not in the context that you are using them. Change '13' to 13 and so forth.


问:
InnoSetup: trying to Start [Code] section
For some reason my [Code] section not even run. Example

[Code]
procedure Test();
begin
    Log('test');
    MsgBox('test!!!', mbInformation, mb_Ok);
end;

When I run install.exe file, nothing happen. I suppose that the first line should use Function, not Procedure. What could be the reason?

答:
Define function/procedure is not enought to run the function/procedure.

You need also to call the function/procedure.

You can do it for example this way

```<code>procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep=ssDone then
  begin
    Test();
  end
end;
</code>```

More events and examples You can find here:

https://jrsoftware.org/ishelp/topic_scriptcheck.htm

https://jrsoftware.org/ishelp/topic_scriptevents.htm

Body:
Define function/procedure is not enought to run the function/procedure.

You need also to call the function/procedure.

You can do it for example this way

procedure CurStepChanged(CurStep: TSetupStep);
begin
  if CurStep=ssDone then
  begin
    Test();
  end
end;

More events and examples You can find here:

https://jrsoftware.org/ishelp/topic_scriptcheck.htm

https://jrsoftware.org/ishelp/topic_scriptevents.htm


问:
"Bus Error" and "munmap_chunk(): Invalid Pointer" in Fortran 95
I'm working on a python project which calls a fortran subroutine via f2py for efficiency reasons.

When I execute the code, it fails at seemingly random (non-consistent) points with Segmentation Fault errors. Using the faulthandler Python library, I have narrowed my search down to a Bus Error and munmap_chunk(): Invalid Pointer errors, though the errors are still not consistent.

Given the seemingly random nature of the error I'm afraid I can't provide a MWE. My Fortran code is (abridged -- full version here):

```<code>module event_rates
      contains
      subroutine event_rate_f95(events, edges, events_edges, lifetimes, lt_size, NBins)
            implicit none
            ! define input parameters
            ! define internal variables

            dtd = delay_time_distribution(lifetimes, edges, NBins)
            print *, "DTD generated"
            do i = 1, NBins+1
                  t1 = events_edges(i-1)
                  t2 = events_edges(i)
                  print *, "Ts done"

                  z1 = estimate_redshift(t1)
                  z2 = estimate_redshift(t2)

                  print *, 'computing sfr'

                  SFR = compute_SFR(z1, z2) / (1E-3) ** 3

                  print *, "about to enter inner loop"

                  do j = 0, i-1
                        ! do a computation
                  enddo

                  print *, "exited inner loop"
                  print *, i
            enddo
      end subroutine
end module event_rates
</code>```

Where delay_time_distribution, estimate_redshift, compute_SFR are functions I define earlier. For reference, NBins is approximately 50 whenever I call this. In the 3 most recent executions, it failed at:

1) i=20 inside estimate_redshift(),

2) In the delay_time_distribution() function,

3) After the Fortran code had terminated and returned control back to Python.

From reading background information on these errors, it appears to be a memory management problem, as Segmentation Faults are accessing memory I can't access, Bus Errors are accessing memory that isn't there, and munmap_chunk() is passing the wrong pointer to a FREE instruction. But I'm relying on Fortran 95's inbuilt memory management to handle this for me. Monitoring htop while code is executing shows me that my CPU usage on one core spikes, but memory usage stays constant.

My question is two-fold: what is causing these errors, and how can one debug this further in general?

答:
Debugging the issue

There is a simple way to debug this: use debug flags.

You may know that if you're compiling FORTRAN with gfortran, you can pass -fcheck=bounds to the gfortran command. Similarly, you can pass --opt='-fcheck=bounds' to the f2py3 command to debug the issue.

This specific issue

I was trying to access an array wrong. Consider line 122 of the pastebin:

bin_low = floor(NBins * (x1 - NBins) / (NBins))
```

<p>If <code>x1 = 0</code>, then <code>bin_low = -NBins</code>. Which, since <code>NBins</code> (the number of bins you have) is positive, becomes negative. You can't index into an array with a negative index in FORTRAN -- that's accessing invalid memory, a.k.a a seg fault. </p>

<p>The solution here is to constrain the index:</p>

<pre class="lang-py prettyprint-override"><code>bin_low = max(1, floor(NBins * (x1 - NBins) / (NBins)))
</code>```

That way, if the formula gives you a negative bin, you access the first bin instead. (Remember, FORTRAN is 1-indexed)

Body:
I'm working on a python project which calls a fortran subroutine via f2py for efficiency reasons.

When I execute the code, it fails at seemingly random (non-consistent) points with Segmentation Fault errors. Using the faulthandler Python library, I have narrowed my search down to a Bus Error and munmap_chunk(): Invalid Pointer errors, though the errors are still not consistent.

Given the seemingly random nature of the error I'm afraid I can't provide a MWE. My Fortran code is (abridged -- full version here):

module event_rates
      contains
      subroutine event_rate_f95(events, edges, events_edges, lifetimes, lt_size, NBins)
            implicit none
            ! define input parameters
            ! define internal variables

            dtd = delay_time_distribution(lifetimes, edges, NBins)
            print *, "DTD generated"
            do i = 1, NBins+1
                  t1 = events_edges(i-1)
                  t2 = events_edges(i)
                  print *, "Ts done"

                  z1 = estimate_redshift(t1)
                  z2 = estimate_redshift(t2)

                  print *, 'computing sfr'

                  SFR = compute_SFR(z1, z2) / (1E-3) ** 3

                  print *, "about to enter inner loop"

                  do j = 0, i-1
                        ! do a computation
                  enddo

                  print *, "exited inner loop"
                  print *, i
            enddo
      end subroutine
end module event_rates

Where delay_time_distribution, estimate_redshift, compute_SFR are functions I define earlier. For reference, NBins is approximately 50 whenever I call this. In the 3 most recent executions, it failed at:

1) i=20 inside estimate_redshift(),

2) In the delay_time_distribution() function,

3) After the Fortran code had terminated and returned control back to Python.

From reading background information on these errors, it appears to be a memory management problem, as Segmentation Faults are accessing memory I can't access, Bus Errors are accessing memory that isn't there, and munmap_chunk() is passing the wrong pointer to a FREE instruction. But I'm relying on Fortran 95's inbuilt memory management to handle this for me. Monitoring htop while code is executing shows me that my CPU usage on one core spikes, but memory usage stays constant.

My question is two-fold: what is causing these errors, and how can one debug this further in general?

Body:
Debugging the issue

There is a simple way to debug this: use debug flags.

You may know that if you're compiling FORTRAN with gfortran, you can pass -fcheck=bounds to the gfortran command. Similarly, you can pass --opt='-fcheck=bounds' to the f2py3 command to debug the issue.

This specific issue

I was trying to access an array wrong. Consider line 122 of the pastebin:

bin_low = floor(NBins * (x1 - NBins) / (NBins))

If x1 = 0, then bin_low = -NBins. Which, since NBins (the number of bins you have) is positive, becomes negative. You can't index into an array with a negative index in FORTRAN -- that's accessing invalid memory, a.k.a a seg fault.

The solution here is to constrain the index:

bin_low = max(1, floor(NBins * (x1 - NBins) / (NBins)))

That way, if the formula gives you a negative bin, you access the first bin instead. (Remember, FORTRAN is 1-indexed)


问:
Comparing excel cells using .value doesnt not match even though the data is identical
I have looked through all the other similar questions, but am unable to find any solution to my problem.

I am comparing two excel sheets for their cell.value, using vbs. when i run my script, the data shows as not identical, even though visually it looks exactly the same. Its numeric data with custom formatting.

75662.726506 this is the actual cell value, and what appears in the column is 75,663. Both the excel sheet displays the exact same data.

here is the code i am using to compare

```<code>For Each cell In objMyWorksheet1.UsedRange

If cell.Value <> objMyWorksheet2.Range(cell.Address).Value Then
        cell.Font.ColorIndex = 46
       Flag = "False"
 End If
Next
</code>```

The cell has a Custom format in excel - [$-en-US,1]#,##0;(#,##0)

One of the files is in the .xls format while the other is .xlsx .

i have compared length, ascii, format etc and everything matches. Not sure what else i could check.

Any help is highly appreciated.

Thanks
AD

答:
At First run this function and see the difference between two cells:

```<code>Function FindDifPoint(str1 As String, str2 As String) As String
    Dim result As String
    Dim difFound As Boolean
    difFound = False
    If str1 <> str2 Then
        For i = 1 To Len(str1)
            If Mid(str1, i, 1) <> Mid(str2, i, 1) Then
                difFound = True
                result = "the equal part is:<" & Mid(str1, 1, i - 1) & ">, and the different part in str1 is:<" & Mid(str1, i, Len(str1) - i + 1) & ">"
                Exit For
            End If
        Next
        If difFound = False Then
            For i = 1 To Len(str2)
                If Mid(str2, i, 1) <> Mid(str1, i, 1) Then
                    difFound = True
                    result = "the equal part is:<" & Mid(str2, 1, i - 1) & ">, and the different part in str2 is:<" & Mid(str2, i, Len(str2) - i + 1) & ">"
                    Exit For
                End If
            Next
            If difFound = False Then
                result = "Any thing is same, I dont know what happend, check the box I told you"
            End If
        End If
    Else
        result = "Two Cells are equal"
    End If
    FindDifPoint = result
 End Function
</code>```

for test I wrote two numbers =pi() and 3.14  in Range A3 and B3 with same format to find the difference with formula =FindDifPoint(A3;B3)

if that solution didn't work, I suppose to check the Set precision as displayed in Options/Advanced and then see the result.

Body:
I have looked through all the other similar questions, but am unable to find any solution to my problem.

I am comparing two excel sheets for their cell.value, using vbs. when i run my script, the data shows as not identical, even though visually it looks exactly the same. Its numeric data with custom formatting.

75662.726506 this is the actual cell value, and what appears in the column is 75,663. Both the excel sheet displays the exact same data.

here is the code i am using to compare

For Each cell In objMyWorksheet1.UsedRange

If cell.Value <> objMyWorksheet2.Range(cell.Address).Value Then
        cell.Font.ColorIndex = 46
       Flag = "False"
 End If
Next

The cell has a Custom format in excel - [$-en-US,1]#,##0;(#,##0)

One of the files is in the .xls format while the other is .xlsx .

i have compared length, ascii, format etc and everything matches. Not sure what else i could check.

Any help is highly appreciated.

Thanks
AD

Body:
At First run this function and see the difference between two cells:

Function FindDifPoint(str1 As String, str2 As String) As String
    Dim result As String
    Dim difFound As Boolean
    difFound = False
    If str1 <> str2 Then
        For i = 1 To Len(str1)
            If Mid(str1, i, 1) <> Mid(str2, i, 1) Then
                difFound = True
                result = "the equal part is:<" & Mid(str1, 1, i - 1) & ">, and the different part in str1 is:<" & Mid(str1, i, Len(str1) - i + 1) & ">"
                Exit For
            End If
        Next
        If difFound = False Then
            For i = 1 To Len(str2)
                If Mid(str2, i, 1) <> Mid(str1, i, 1) Then
                    difFound = True
                    result = "the equal part is:<" & Mid(str2, 1, i - 1) & ">, and the different part in str2 is:<" & Mid(str2, i, Len(str2) - i + 1) & ">"
                    Exit For
                End If
            Next
            If difFound = False Then
                result = "Any thing is same, I dont know what happend, check the box I told you"
            End If
        End If
    Else
        result = "Two Cells are equal"
    End If
    FindDifPoint = result
 End Function

for test I wrote two numbers =pi() and 3.14  in Range A3 and B3 with same format to find the difference with formula =FindDifPoint(A3;B3)

if that solution didn't work, I suppose to check the Set precision as displayed in Options/Advanced and then see the result.


问:
How to prevent program from deleting last index in method
I have created a method that will take the first two values of the previous array and add them together and repeating this until it has created a new array of the added values. However, what I want to add a rule where if the last number of the previous array is odd I don't want that number to be added. I was able to somewhat do this but unfortunately at the cost of deleting the 2nd to last value of the index. Example my array of {1, 4, 6, 8, 3, 4, 6, 7, 10, 1} is printing [5,14,7,13,1] while I got the last number I still want that 10 to exist but I am stumped on how to get the code to work while not erasing the 10.</p>

```<code>import java.util.*;
import java.io.*;
public class reduceNumbers{
     public static int[] reduce(int[] numArray){
         int[] returnedArray = new int[(numArray.length) / 2];
         if(returnedArray[returnedArray.length - 1] % 2 == 1){
         for(int i = 0; i < returnedArray.length; i++) {

         returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
    }

}
else{
  for(int i = 0; i < returnedArray.length - 1; i++) {

    returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
}

returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];

}

return returnedArray;
}

public static void main(String[] args){

int[] firstArray = {1, 4, 6, 8, 3, 4, 6, 7, 10, 1};

   int[] firstArrayA,

   firstArrayA= reduce(firstArray);

       System.out.println(Arrays.toString(firstArrayA) );

   }
}
</code>```

答:
is this what you wanted?

```<code>import java.util.*;
import java.io.*;
public class reduceNumbers{
    public static int[] reduce(int[] numArray){
        boolean even = numArray.length % 2 == 0;
        if(even) {
            int[] returnedArray = new int[numArray.length / 2];
            for(int i=0;i<returnedArray.length;i++) {
                returnedArray[i] = numArray[i * 2]  + numArray[i * 2 + 1];
            }
            return returnedArray;
        }
        else{
            int[] returnedArray = new int[(numArray.length + 1) / 2];
            for(int i = 0; i < returnedArray.length - 1; i++) {
                returnedArray[i] = numArray[i * 2] + numArray[i * 2 + 1];
            }
            returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];
            return returnedArray;
        }
    }

    public static void main(String[] args){
        int[] firstArray = {1, 4, 6, 8, 3, 4, 6, 7, 10, 1};
        int[] firstArrayA = reduce(firstArray);
        System.out.println(Arrays.toString(firstArrayA) );
    }
}
</code>```

I refactored your code by only allocating your returnedArray for each case instead of allocating it before you check the parity.

Body:
I have created a method that will take the first two values of the previous array and add them together and repeating this until it has created a new array of the added values. However, what I want to add a rule where if the last number of the previous array is odd I don't want that number to be added. I was able to somewhat do this but unfortunately at the cost of deleting the 2nd to last value of the index. Example my array of {1, 4, 6, 8, 3, 4, 6, 7, 10, 1} is printing [5,14,7,13,1] while I got the last number I still want that 10 to exist but I am stumped on how to get the code to work while not erasing the 10.

import java.util.*;
import java.io.*;
public class reduceNumbers{
     public static int[] reduce(int[] numArray){
         int[] returnedArray = new int[(numArray.length) / 2];
         if(returnedArray[returnedArray.length - 1] % 2 == 1){
         for(int i = 0; i < returnedArray.length; i++) {

         returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
    }

}
else{
  for(int i = 0; i < returnedArray.length - 1; i++) {

    returnedArray[i] = numArray[2 * i] + numArray[2 * i + 1];
}

returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];

}

return returnedArray;
}

public static void main(String[] args){

int[] firstArray = {1, 4, 6, 8, 3, 4, 6, 7, 10, 1};

   int[] firstArrayA,

   firstArrayA= reduce(firstArray);

       System.out.println(Arrays.toString(firstArrayA) );

   }
}

Body:
is this what you wanted?

import java.util.*;
import java.io.*;
public class reduceNumbers{
    public static int[] reduce(int[] numArray){
        boolean even = numArray.length % 2 == 0;
        if(even) {
            int[] returnedArray = new int[numArray.length / 2];
            for(int i=0;i<returnedArray.length;i++) {
                returnedArray[i] = numArray[i * 2]  + numArray[i * 2 + 1];
            }
            return returnedArray;
        }
        else{
            int[] returnedArray = new int[(numArray.length + 1) / 2];
            for(int i = 0; i < returnedArray.length - 1; i++) {
                returnedArray[i] = numArray[i * 2] + numArray[i * 2 + 1];
            }
            returnedArray[returnedArray.length - 1] = numArray[numArray.length - 1];
            return returnedArray;
        }
    }

    public static void main(String[] args){
        int[] firstArray = {1, 4, 6, 8, 3, 4, 6, 7, 10, 1};
        int[] firstArrayA = reduce(firstArray);
        System.out.println(Arrays.toString(firstArrayA) );
    }
}

I refactored your code by only allocating your returnedArray for each case instead of allocating it before you check the parity.


问:
Get last message sent to channel
I already have a variable containing a specific channel, but how can I obtain the last message sent to the channel? I want to make my bot only perform an action if the last message to the channel wasn't by it.</p>

答:
Recently I believe they've changed from channel.fetchMessages() to channel.messages.fetch()

```<code>channel.messages.fetch({ limit: 1 }).then(messages => {
  let lastMessage = messages.first();

  // do what you need with lastMessage below

})
.catch(console.error);
</code>```

Title: Get last message sent to channel

Body:
Recently I believe they've changed from channel.fetchMessages() to channel.messages.fetch()

channel.messages.fetch({ limit: 1 }).then(messages => {
  let lastMessage = messages.first();

  // do what you need with lastMessage below

})
.catch(console.error);


问:
Always output raw HTML using MVC3 and Razor
I’ve got a class with a property that looks like this:

```<code>[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
</code>```

I’ve already put in the [AllowHtml] attribute to let me submit HTML to this property via the form that I’ve built, but what I want to do is output the value of the property as the raw HTML without it being escaped.

I know I can use Html.Raw(Model.Description) but what I’m looking for is some way of telling Html.DisplayFor(m => m.Description) to always output the raw HTML. Is there an attribute I can use to decorate the properties in my class that I wish to behave like that?

Basically it’s me being lazy—I don’t want to have to remember which properties might contain HTML, so I don’t want to have to think about using Html.Raw(…) when I need to do the above—I’d much rather my Model know what it should do and do it automatically. I’ve tried searching for an answer, but either I’m not phrasing it correctly or there’s no way of doing it :(

Thanks,

答:
Change your Description proerpty to return an HtmlString.

Razor does not escape HtmlString values.

(In fact, all Html.Raw does is create an HtmlString)

Body:
I’ve got a class with a property that looks like this:

[AllowHtml]
[DataType(DataType.MultilineText)]
public string Description { get; set; }

I’ve already put in the [AllowHtml] attribute to let me submit HTML to this property via the form that I’ve built, but what I want to do is output the value of the property as the raw HTML without it being escaped.

I know I can use Html.Raw(Model.Description) but what I’m looking for is some way of telling Html.DisplayFor(m => m.Description) to always output the raw HTML. Is there an attribute I can use to decorate the properties in my class that I wish to behave like that?

Basically it’s me being lazy—I don’t want to have to remember which properties might contain HTML, so I don’t want to have to think about using Html.Raw(…) when I need to do the above—I’d much rather my Model know what it should do and do it automatically. I’ve tried searching for an answer, but either I’m not phrasing it correctly or there’s no way of doing it :(

Thanks,