问:
Animation only happens one time
```<code>public static Animator zoomInImage(ImageView smallImage, ImageView largeImage, long duration) {
    Rect startBounds    = new Rect();
    Rect endBounds      = new Rect();
    Point globalOffset  = new Point();

    smallImage.getGlobalVisibleRect(startBounds);
    largeImage.getGlobalVisibleRect(endBounds, globalOffset);

    startBounds.offset(-globalOffset.x, -globalOffset.y);
    endBounds.offset(-globalOffset.x, -globalOffset.y);

    float startScale;
    if ((float) endBounds.width() / endBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / endBounds.height();
        float startWidth = startScale * endBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / endBounds.width();
        float startHeight = startScale * endBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    smallImage.setAlpha(0f);

    largeImage.setPivotX(0f);
    largeImage.setPivotY(0f);

    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet
            .play(ObjectAnimator.ofFloat(largeImage, View.X, startBounds.left, endBounds.left))
            .with(ObjectAnimator.ofFloat(largeImage, View.Y, startBounds.top, endBounds.top))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_X, startScale, 1f))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_Y, startScale, 1f));

    animatorSet.setDuration(duration);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.start();
    largeImage.setVisibility(View.VISIBLE);
    return animatorSet;

}

public static Animator zoomOutImage(final ImageView smallImage, final ImageView largeImage, long duration) {
    Rect startBounds    = new Rect();
    Rect endBounds      = new Rect();
    Point globalOffset  = new Point();

    smallImage.getGlobalVisibleRect(startBounds);
    largeImage.getGlobalVisibleRect(endBounds, globalOffset);

    startBounds.offset(-globalOffset.x, -globalOffset.y);
    endBounds.offset(-globalOffset.x, -globalOffset.y);

    float startScale;
    if ((float) endBounds.width() / endBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / endBounds.height();
        float startWidth = startScale * endBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / endBounds.width();
        float startHeight = startScale * endBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    largeImage.setPivotX(0f);
    largeImage.setPivotY(0f);

    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet
            .play(ObjectAnimator.ofFloat(largeImage, View.X, startBounds.left))
            .with(ObjectAnimator.ofFloat(largeImage, View.Y, startBounds.top))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_X, startScale))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_Y, startScale));

    animatorSet.setDuration(duration);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            smallImage.setAlpha(1f);
            largeImage.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            smallImage.setAlpha(1f);
            largeImage.setVisibility(View.INVISIBLE);
        }
    });
    animatorSet.start();

    return animatorSet;
}
</code>```

The above two function is for animating zoomIn and zoomOut of image. The problem with above code is the zoomIn animation is happening one once that is at the beginning but not on later time. While zoomOut is working. The zoomIn and zoomOut function is being called on click action on image.

The behaviour is like on click of small image animation to zoom is correct and on click of large image animation to zoom out is also correct but when small image is clicked again the large image appears suddenly.

I am calling it like this

```<code>lImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (currentAnim != null) currentAnim.cancel();
        currentAnim = ZoomAnimator.zoomOutImage(sImageView, lImageView, getResources().getInteger(
                android.R.integer.config_shortAnimTime));
    }
});

sImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (currentAnim != null) currentAnim.cancel();
        currentAnim = ZoomAnimator.zoomInImage(sImageView, lImageView, getResources().getInteger(
                android.R.integer.config_shortAnimTime));
    }
});
</code>```

答:
I think your implementation is too complicated. Try to use Transition API from androidx (support) package, animations with it are much easier. Call TransitionManager.beginDelayedTransition then change view scale. There is default ChangeTransform transition which handle scale changes.

```<code>import androidx.transition.ChangeTransform;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;

private void onClick() {
    View imageView = findViewById(R.id.imageView);
    ViewGroup parent = findViewById(R.id.parent);

    Transition transition = new ChangeTransform();
    transition.setDuration(600);
    transition.addTarget(R.id.imageView);

    TransitionManager.beginDelayedTransition(parent, transition);
    float scale = zoom ? 1 : 0.5f;
    imageView.setScaleX(scale);
    imageView.setScaleY(scale);
}
</code>```

R.id.parent is parent ViewGroup of ImageView. Here is result:

Cool thing is that you can click on image in the middle of previous animation. TransitionManager will start new animation from current view scale values.

Title: Animation only happens one time

Body:
public static Animator zoomInImage(ImageView smallImage, ImageView largeImage, long duration) {
    Rect startBounds    = new Rect();
    Rect endBounds      = new Rect();
    Point globalOffset  = new Point();

    smallImage.getGlobalVisibleRect(startBounds);
    largeImage.getGlobalVisibleRect(endBounds, globalOffset);

    startBounds.offset(-globalOffset.x, -globalOffset.y);
    endBounds.offset(-globalOffset.x, -globalOffset.y);

    float startScale;
    if ((float) endBounds.width() / endBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / endBounds.height();
        float startWidth = startScale * endBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / endBounds.width();
        float startHeight = startScale * endBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    smallImage.setAlpha(0f);

    largeImage.setPivotX(0f);
    largeImage.setPivotY(0f);

    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet
            .play(ObjectAnimator.ofFloat(largeImage, View.X, startBounds.left, endBounds.left))
            .with(ObjectAnimator.ofFloat(largeImage, View.Y, startBounds.top, endBounds.top))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_X, startScale, 1f))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_Y, startScale, 1f));

    animatorSet.setDuration(duration);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.start();
    largeImage.setVisibility(View.VISIBLE);
    return animatorSet;

}

public static Animator zoomOutImage(final ImageView smallImage, final ImageView largeImage, long duration) {
    Rect startBounds    = new Rect();
    Rect endBounds      = new Rect();
    Point globalOffset  = new Point();

    smallImage.getGlobalVisibleRect(startBounds);
    largeImage.getGlobalVisibleRect(endBounds, globalOffset);

    startBounds.offset(-globalOffset.x, -globalOffset.y);
    endBounds.offset(-globalOffset.x, -globalOffset.y);

    float startScale;
    if ((float) endBounds.width() / endBounds.height()
            > (float) startBounds.width() / startBounds.height()) {
        // Extend start bounds horizontally
        startScale = (float) startBounds.height() / endBounds.height();
        float startWidth = startScale * endBounds.width();
        float deltaWidth = (startWidth - startBounds.width()) / 2;
        startBounds.left -= deltaWidth;
        startBounds.right += deltaWidth;
    } else {
        // Extend start bounds vertically
        startScale = (float) startBounds.width() / endBounds.width();
        float startHeight = startScale * endBounds.height();
        float deltaHeight = (startHeight - startBounds.height()) / 2;
        startBounds.top -= deltaHeight;
        startBounds.bottom += deltaHeight;
    }

    largeImage.setPivotX(0f);
    largeImage.setPivotY(0f);

    AnimatorSet animatorSet = new AnimatorSet();

    animatorSet
            .play(ObjectAnimator.ofFloat(largeImage, View.X, startBounds.left))
            .with(ObjectAnimator.ofFloat(largeImage, View.Y, startBounds.top))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_X, startScale))
            .with(ObjectAnimator.ofFloat(largeImage, View.SCALE_Y, startScale));

    animatorSet.setDuration(duration);
    animatorSet.setInterpolator(new DecelerateInterpolator());
    animatorSet.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            smallImage.setAlpha(1f);
            largeImage.setVisibility(View.INVISIBLE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            smallImage.setAlpha(1f);
            largeImage.setVisibility(View.INVISIBLE);
        }
    });
    animatorSet.start();

    return animatorSet;
}

The above two function is for animating zoomIn and zoomOut of image. The problem with above code is the zoomIn animation is happening one once that is at the beginning but not on later time. While zoomOut is working. The zoomIn and zoomOut function is being called on click action on image.

The behaviour is like on click of small image animation to zoom is correct and on click of large image animation to zoom out is also correct but when small image is clicked again the large image appears suddenly.

I am calling it like this

lImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (currentAnim != null) currentAnim.cancel();
        currentAnim = ZoomAnimator.zoomOutImage(sImageView, lImageView, getResources().getInteger(
                android.R.integer.config_shortAnimTime));
    }
});

sImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (currentAnim != null) currentAnim.cancel();
        currentAnim = ZoomAnimator.zoomInImage(sImageView, lImageView, getResources().getInteger(
                android.R.integer.config_shortAnimTime));
    }
});

Body:
I think your implementation is too complicated. Try to use Transition API from androidx (support) package, animations with it are much easier. Call TransitionManager.beginDelayedTransition then change view scale. There is default ChangeTransform transition which handle scale changes.

import androidx.transition.ChangeTransform;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;

private void onClick() {
    View imageView = findViewById(R.id.imageView);
    ViewGroup parent = findViewById(R.id.parent);

    Transition transition = new ChangeTransform();
    transition.setDuration(600);
    transition.addTarget(R.id.imageView);

    TransitionManager.beginDelayedTransition(parent, transition);
    float scale = zoom ? 1 : 0.5f;
    imageView.setScaleX(scale);
    imageView.setScaleY(scale);
}

R.id.parent is parent ViewGroup of ImageView. Here is result:

Cool thing is that you can click on image in the middle of previous animation. TransitionManager will start new animation from current view scale values.


来源: stackexchange

问:
grep multiple strings from multiple files and stop processing other files when first match found
I have ca 270 .bz2 log files (25 day logs) and one text file with ca 1500 usernames. What I need to do is find who of theese users are logged in in last 25 days. So I need to grep usernames from list of files and stop grepping when username is found in first file (when first match found).

My code works, but if in first file match found I do not need to process other files, break and search for another username, if it is found i.e. in third file, break and search for another username:

```<code>for i in $(cat /tmp/usernames.txt); do for j in $(ls *.bz2); do
bzgrep -o -m1 $i $j; done; done
</code>```

Here, if in fist file match found it breaks (-m1 flag) and starts searching for the same username in second file, but I do not need that anymore.

Problem: I need to inspect users who are not logged in in last 25 days. So I can reduce their permissions in the application. If user is logged at least once in last 25 days, I do not reduce his permissions.

Question is: I need to find whom of theese usernames exist in my log files. If username is found in one of the files at least one time stop searching for this user and start searching for another user.

Example: if user1 is found in file1, print it and stop searching for this user any more in this or other files. If user2 is found in file8, print it one time and stop searching in file9, file10, file11 ... file250. Hope it makes sense.

答:
Can't you just do this to get the list of user names that appear in any of the bzipped files:

```<code>bzgrep -o -w -F -f /tmp/usernames.txt *.bz2 | sort -u
</code>```

and then a diff of that output against usernames.txt to see who has/hasn't logged in? Wrap it in a loop if it turns out to be more efficient to check one .bz2 file at a time:

```<code>for file in *.bz2; do
    bzgrep -o -w -F -f /tmp/usernames.txt "$file"
done | sort -u
</code>```

and you could remove found user names from each iteration if that improves performance too:

```<code>sort -u /tmp/usernames.txt > /tmp/names.txt
for file in *.bz2; do
    bzgrep -o -w -F -f /tmp/names.txt "$file" | sort -u > /tmp/found.txt &&
    comm -23 /tmp/names.txt /tmp/found.txt > /tmp/left.txt &&
    mv /tmp/left.txt /tmp/names.txt &&
    cat /tmp/found.txt
    [[ -s /tmp/names.txt ]] || break
done
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have ca 270 .bz2 log files (25 day logs) and one text file with ca 1500 usernames. What I need to do is find who of theese users are logged in in last 25 days. So I need to grep usernames from list of files and stop grepping when username is found in first file (when first match found).

My code works, but if in first file match found I do not need to process other files, break and search for another username, if it is found i.e. in third file, break and search for another username:

for i in $(cat /tmp/usernames.txt); do for j in $(ls *.bz2); do
bzgrep -o -m1 $i $j; done; done

Here, if in fist file match found it breaks (-m1 flag) and starts searching for the same username in second file, but I do not need that anymore.

Problem: I need to inspect users who are not logged in in last 25 days. So I can reduce their permissions in the application. If user is logged at least once in last 25 days, I do not reduce his permissions.

Question is: I need to find whom of theese usernames exist in my log files. If username is found in one of the files at least one time stop searching for this user and start searching for another user.

Example: if user1 is found in file1, print it and stop searching for this user any more in this or other files. If user2 is found in file8, print it one time and stop searching in file9, file10, file11 ... file250. Hope it makes sense.

Body:
Can't you just do this to get the list of user names that appear in any of the bzipped files:

bzgrep -o -w -F -f /tmp/usernames.txt *.bz2 | sort -u

and then a diff of that output against usernames.txt to see who has/hasn't logged in? Wrap it in a loop if it turns out to be more efficient to check one .bz2 file at a time:

for file in *.bz2; do
    bzgrep -o -w -F -f /tmp/usernames.txt "$file"
done | sort -u

and you could remove found user names from each iteration if that improves performance too:

sort -u /tmp/usernames.txt > /tmp/names.txt
for file in *.bz2; do
    bzgrep -o -w -F -f /tmp/names.txt "$file" | sort -u > /tmp/found.txt &&
    comm -23 /tmp/names.txt /tmp/found.txt > /tmp/left.txt &&
    mv /tmp/left.txt /tmp/names.txt &&
    cat /tmp/found.txt
    [[ -s /tmp/names.txt ]] || break
done


问:
matlab switch + regexp
I tried to read up this but I think I might be fundamentally going about this the wrong way. Here's what I want:

I have a unpredictable user-input value e.g. a='test1' that may vary a lot

I want to test different scenarios for input strings, where some fuzzy matching should happen for all defined scenarios, but should revert to default if none apply

So ideally, I thought I want the case structure like this:

```<code>a='test1';
switch a
  case ~isempty(regexpi(a,'test','match','once')) %should handle all cases where 'test' is contained in the input string
    disp('this');
  otherwise %should handle everything else
    disp('that');
end
</code>```

but it always outputs that.

How to solve this problem?

答:
As written, you are comparing the result of a boolean expression with the value you are testing, a.  This is never going to match so simply use switch true instead.

The cases are evaluated in order so this is equivalent to using an

```<code>if ...
    % Do something
elseif ...
    % Do something else
else
    % Otherwise
end
</code>```

construction that some might argue is preferable.

Title: matlab switch + regexp

Body:
I tried to read up this but I think I might be fundamentally going about this the wrong way. Here's what I want:

I have a unpredictable user-input value e.g. a='test1' that may vary a lot

I want to test different scenarios for input strings, where some fuzzy matching should happen for all defined scenarios, but should revert to default if none apply

So ideally, I thought I want the case structure like this:

a='test1';
switch a
  case ~isempty(regexpi(a,'test','match','once')) %should handle all cases where 'test' is contained in the input string
    disp('this');
  otherwise %should handle everything else
    disp('that');
end

but it always outputs that.

How to solve this problem?

Body:
As written, you are comparing the result of a boolean expression with the value you are testing, a.  This is never going to match so simply use switch true instead.

The cases are evaluated in order so this is equivalent to using an

if ...
    % Do something
elseif ...
    % Do something else
else
    % Otherwise
end

construction that some might argue is preferable.


问:
Cannot resolve symbol 'logger' on DuplicateKeyException
In short: the object "logger" is not recognized unlike in many tutorials.

The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.

My snippet:

```<code>@Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
    String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";

    BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
    NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    try {
        vJdbcTemplate.update(vSQL, vParams);
    } catch (DuplicateKeyException pE){
        logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
    }
}
</code>```

Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.

答:
Recommend using sl4j

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
</code>```

Then instantiate:

```<code>//generic way to declare logger to be able to copy/paste to other classes
//without changing the class name
private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
</code>```

In dependency, include the binding for sl4j implementation ( can be log4j ).

Can refer here:

logging-with-slf4j

Body:
In short: the object "logger" is not recognized unlike in many tutorials.

The problem on its own is not very serious and I can easily go around it. However it is very frustrating to see this "logger" stays in red in my intellIj editor. I am going through docs and blogs and I don't see what the problem is.

My snippet:

@Override
public void insertTicketStatut(TicketStatut pTicketStatut) {
    String vSQL = "INSERT INTO statut {id, libelle} VALUES {:id, :libelle}";

    BeanPropertySqlParameterSource vParams = new BeanPropertySqlParameterSource(pTicketStatut);
    NamedParameterJdbcTemplate vJdbcTemplate = new NamedParameterJdbcTemplate(getDataSource());

    try {
        vJdbcTemplate.update(vSQL, vParams);
    } catch (DuplicateKeyException pE){
        logger.error("Le TicketStatut existe déjà ! id="+ pTicketStatut.getId(),pE);
    }
}

Hovering over logger shows "Cannot resolve symbol 'logger'
Thanks for your help.

Body:
Recommend using sl4j

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Then instantiate:

//generic way to declare logger to be able to copy/paste to other classes
//without changing the class name
private final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

In dependency, include the binding for sl4j implementation ( can be log4j ).

Can refer here:

logging-with-slf4j


问:
How to get an element's int value from a String matrix?
I would like to get an element's int value from a String matrix.

My task is to implement the easiest version of Uniqual (https://www.chiark.greenend.org.uk/~sgtatham/puzzles/js/unequal.html) with some kind of tree or graph search algorithm.

That's why I thought of implementing the table as a string, as it can contain both characters and digits.

I have already tried this method:
Character.isDigit(matrix[i].charAt(j))
for my issue. I guess it's not the correct way to do so.
Maybe if I get the element's char value, I could implement a simple function that checks whether it is a number or a digit or special char.

答:
I think this is what you are looking for -

```<code>char c = matrix[i].charAt(j);
int cVal = Character.getNumericValue(c);
</code>```

I am preferring this method because if c='1', cVal = 1.

Body:
I think this is what you are looking for -

char c = matrix[i].charAt(j);
int cVal = Character.getNumericValue(c);

I am preferring this method because if c='1', cVal = 1.


问:
Deleting ALL cells that contain a certain string, and shifting to the left
I have a customer database file where the data has been input incorrectly and the column names do not match up with the data.

I am using Google Sheets.

To fix this, I need to select all the cells that contain a time stamp, one example of such is:

```<code>2016-06-21 08:42:09 UTC
</code>```

I would like to not only select these cells, but delete their contents, and shift the cells to the left.

This would fix my problem! However, I have no idea if this is possible?

NOTE: These time stamps do not always appear in the same row, and sometimes appear more than once per row.

Here is a visual representation of my problem:

Body:
I have a customer database file where the data has been input incorrectly and the column names do not match up with the data.

I am using Google Sheets.

To fix this, I need to select all the cells that contain a time stamp, one example of such is:

2016-06-21 08:42:09 UTC

I would like to not only select these cells, but delete their contents, and shift the cells to the left.

This would fix my problem! However, I have no idea if this is possible?

NOTE: These time stamps do not always appear in the same row, and sometimes appear more than once per row.

Here is a visual representation of my problem:

Body:
press CTRL + H and do:

\d+-\d+-\d+ \d+:\d+:\d+ .*


问:
Automatically generate nodes in a Canoe configuration simulation
I am trying to automate and create a Canoe simulation.

My usecase :

I have a configuration (LibraryTest.cfg) with a CAN Network and a node ACAN in the network. I want to create another node BCAN automatically into the existing configuration along with ACAN. I am trying this using C# .NET Canoe Library for this.

```<code>        CANoe.Application mApp;
        CANoe.Measurement mMsr;
        CANoe.Networks mNet;
        mApp = new CANoe.Application();

        string ConfigFile=
      "C:\\Users\\deepasreeraj\\Desktop\\GAC\\TestUnit1\\LibraryTest.cfg";
        try
        {
            mApp.Open(ConfigFile, true, true);
            mMsr = (CANoe.Measurement)mApp.Measurement;
            mNet = mApp.Networks;
            CANoe.Simulation mSim = mApp.Simulation;

            if (mNet != null)
            {
                if(mNet != null)
                {
                    int count = mNet.Count;
                    for (int i = 0; i < count; i++)
                    {
                        mNet.Add("BCAN");
                        string Nodename = mNet[i].NetworkInterfaces;
                    }

                }
            }
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex.Message);
        }
    }
</code>```

In this, while the code reaches mNet.Add("BCAN"); it gives an exception "The method or operation is not implemented." Can someone please help me with this?

答:
If you want to add a node, the Networks property is wrong.

You have to use mApp.Configuration.SimulationSetup.Buses.Nodes. There you can call Add to add a new node.

Just check the page Technical References -> COM Interface -> Object Hierarchy in the CANoe help for the complete API Reference.

Body:
I am trying to automate and create a Canoe simulation.

My usecase :

I have a configuration (LibraryTest.cfg) with a CAN Network and a node ACAN in the network. I want to create another node BCAN automatically into the existing configuration along with ACAN. I am trying this using C# .NET Canoe Library for this.

        CANoe.Application mApp;
        CANoe.Measurement mMsr;
        CANoe.Networks mNet;
        mApp = new CANoe.Application();

        string ConfigFile=
      "C:\\Users\\deepasreeraj\\Desktop\\GAC\\TestUnit1\\LibraryTest.cfg";
        try
        {
            mApp.Open(ConfigFile, true, true);
            mMsr = (CANoe.Measurement)mApp.Measurement;
            mNet = mApp.Networks;
            CANoe.Simulation mSim = mApp.Simulation;

            if (mNet != null)
            {
                if(mNet != null)
                {
                    int count = mNet.Count;
                    for (int i = 0; i < count; i++)
                    {
                        mNet.Add("BCAN");
                        string Nodename = mNet[i].NetworkInterfaces;
                    }

                }
            }
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex.Message);
        }
    }

In this, while the code reaches mNet.Add("BCAN"); it gives an exception "The method or operation is not implemented." Can someone please help me with this?


问:
Using a constant in an AngularJS file

I'd need to use a constant to reference an URL address in my AngularJS Controller. Based on the examples I have found so far I have coded (small snippet):

```<code>var app = angular.module("customerManagement", []).constant('SERVER_URL','http://localhost:8080/customers');

app.controller("customerManagementController", function ($scope, $http) {

$scope.customers = [];
$scope.form = {
  id: -1,
  name: "",
  surname: ""
};
//Now load the data from server
_refreshPageData();
//HTTP POST/PUT methods for add/edit customers
$scope.update = function () {
  var method = "";
  var url = "";
  var data = {};
  if ($scope.form.id == -1) {
    //Id is absent so add customers - POST operation
    method = "POST";
    url = SERVER_URL;
    data.name = $scope.form.name;
    data.surname = $scope.form.surname;
  }
</code>```

But it does not seem to work. In the console I can see:

```<code>Error: SERVER_URL is not defined
</code>```

What's wrong with my constant definition?
Thanks

答:
You need to inject it in your controller:</p>

```<code>app.controller("customerManagementController", function ($scope, $http,
SERVER_URL) {
...
}
</code>```

Title: Using a constant in an AngularJS file

Body:
I'd need to use a constant to reference an URL address in my AngularJS Controller. Based on the examples I have found so far I have coded (small snippet):

var app = angular.module("customerManagement", []).constant('SERVER_URL','http://localhost:8080/customers');

app.controller("customerManagementController", function ($scope, $http) {

$scope.customers = [];
$scope.form = {
  id: -1,
  name: "",
  surname: ""
};
//Now load the data from server
_refreshPageData();
//HTTP POST/PUT methods for add/edit customers
$scope.update = function () {
  var method = "";
  var url = "";
  var data = {};
  if ($scope.form.id == -1) {
    //Id is absent so add customers - POST operation
    method = "POST";
    url = SERVER_URL;
    data.name = $scope.form.name;
    data.surname = $scope.form.surname;
  }

But it does not seem to work. In the console I can see:

Error: SERVER_URL is not defined

What's wrong with my constant definition?
Thanks

Body:
You need to inject it in your controller:

app.controller("customerManagementController", function ($scope, $http,
SERVER_URL) {
...
}


问:
renaming the extracted file from zipfile
I have lots of zipped files on a Linux server and each file includes multiple text files.

what I want is to extract some of those text files, which have the same name across zipped files and save it a folder; I am creating one folder for each zipped file and extract the text file to it. I need to add the parent zipped folder name to the end of file names and save all text files in one directory. For example, if the zipped folder was March132017.zip and I extracted holding.txt, my filename would be holding_march13207.txt.

My problem is that I am not able to change the extracted file's name.
I would appreciate if you could advise.

```<code>import os
import sys
import zipfile
os.chdir("/feeds/lipper/emaxx")

pwkwd = "/feeds/lipper/emaxx"

for item in os.listdir(pwkwd): # loop through items in dir
    if item.endswith(".zip"): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        fh = open(file_name, "rb")
        zip_ref = zipfile.ZipFile(fh)

        filelist = 'ISSUERS.TXT' , 'SECMAST.TXT' , 'FUND.TXT' , 'HOLDING.TXT'
        for name in filelist :
            try:
                outpath = "/SCRATCH/emaxx" + "/" + os.path.splitext(item)[0]
                zip_ref.extract(name, outpath)

            except KeyError:
                {}

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

答:
```<code>import zipfile

zipdata = zipfile.ZipFile('somefile.zip')
zipinfos = zipdata.infolist()

# iterate through each file
for zipinfo in zipinfos:
    # This will do the renaming
    zipinfo.filename = do_something_to(zipinfo.filename)
    zipdata.extract(zipinfo)
</code>```

Reference:
https://bitdrop.st0w.com/2010/07/23/python-extracting-a-file-from-a-zip-file-with-a-different-name/

Example:

from zipfile import ZipFile

src = "path/in/zip/file.txt"
dest = "extracted/path/file.txt"

with ZipFile("zipfile.zip", "r") as file:
    file.getinfo(src).filename = dest
    file.extract(src)
```

ContentLicense: CC BY-SA 3.0

Body:
I have lots of zipped files on a Linux server and each file includes multiple text files.

what I want is to extract some of those text files, which have the same name across zipped files and save it a folder; I am creating one folder for each zipped file and extract the text file to it. I need to add the parent zipped folder name to the end of file names and save all text files in one directory. For example, if the zipped folder was March132017.zip and I extracted holding.txt, my filename would be holding_march13207.txt.

My problem is that I am not able to change the extracted file's name.
I would appreciate if you could advise.

import os
import sys
import zipfile
os.chdir("/feeds/lipper/emaxx")

pwkwd = "/feeds/lipper/emaxx"

for item in os.listdir(pwkwd): # loop through items in dir
    if item.endswith(".zip"): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        fh = open(file_name, "rb")
        zip_ref = zipfile.ZipFile(fh)

        filelist = 'ISSUERS.TXT' , 'SECMAST.TXT' , 'FUND.TXT' , 'HOLDING.TXT'
        for name in filelist :
            try:
                outpath = "/SCRATCH/emaxx" + "/" + os.path.splitext(item)[0]
                zip_ref.extract(name, outpath)

            except KeyError:
                {}

        fh.close()

Body:
import zipfile

zipdata = zipfile.ZipFile('somefile.zip')
zipinfos = zipdata.infolist()

# iterate through each file
for zipinfo in zipinfos:
    # This will do the renaming
    zipinfo.filename = do_something_to(zipinfo.filename)
    zipdata.extract(zipinfo)

Reference:
https://bitdrop.st0w.com/2010/07/23/python-extracting-a-file-from-a-zip-file-with-a-different-name/

Example:

from zipfile import ZipFile

src = "path/in/zip/file.txt"
dest = "extracted/path/file.txt"

with ZipFile("zipfile.zip", "r") as file:
    file.getinfo(src).filename = dest
    file.extract(src)


问:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte - even though I opened the file in mode 'rb'
I'm trying to write an HTTP server, but it doesn't matter.
When I try to decode an image data (after writing 'data = file.read()', it gives an error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I opened the file in 'rb' mode.
Other people usually open the file in 'r' mode and that causes the error. But what is the error here?

What is the problem???

```<code>def get_content_file(file_path):
    """
    Gets a full path to a file and returns the content of it.
    file_path must be a valid path.
    :param file_path: str (path)
    :return: str (data)
    """

    print(file_path)
    file = open(file_path, 'rb')
    data = file.read()
    file.close()
    return data.decode()
</code>```

答: I'll suggest that you confirm the encoding format of 'file_path'. Download and open the file with Notepad++, check the lower right corner; there you can see whether your file was encoded in the compatible format, or if it has the Byte Order Marker or BOM sign, if either of these is true, simply 'save as' -the correct/required format.</p>

Body:
I'm trying to write an HTTP server, but it doesn't matter.
When I try to decode an image data (after writing 'data = file.read()', it gives an error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I opened the file in 'rb' mode.
Other people usually open the file in 'r' mode and that causes the error. But what is the error here?

What is the problem???

def get_content_file(file_path):
    """
    Gets a full path to a file and returns the content of it.
    file_path must be a valid path.
    :param file_path: str (path)
    :return: str (data)
    """

    print(file_path)
    file = open(file_path, 'rb')
    data = file.read()
    file.close()
    return data.decode()


问:
Nest js: npm run start fails
I'm trying to create a Nest js application, but when I follow the steps on their website, the first error I get is 'cannot find ts-node'. So, I installed that. There were a couple more typscript modules I needed to install (typscript and tsconfig-paths I believe) and when I cleared those errors up and run npm run start I got a 'Cannot find node module @nestjs/core'.</p>

答:
As soon as you are working with typescript you have to install it in order to be able to use the tsc command which will transpille your code to javascript.

you also need to install ts-node when you want to work with a transpillation on the fly. that's why you need it.

Finally, you missing to install the necessary packages to be able to work with nest which are listed at this url:
 https://docs.nestjs.com/

using the following command:
$ npm i --save @nestjs/core @nestjs/common rxjs reflect-metadata

Actually, you are missing the @nestjs/core as well as the @nestjs/common packages which are fundamental.

Title: Nest js: npm run start fails


问:
Exact Cochran's Q test in R
I need to run a Cochran's test with small sample sizes. I read that "If your sample size is inadequate, the asymptotic p-value may not be accurate, but you can run an "exact" version of Cochran's Q test that will generate a more accurate exact p-value" (here).

The "nonpar" package for R offers different tests and in many cases there is the option exact= TRUE which can be used if one wants to avoid approximation. However, there is no such option for the cochrans.q() function. How can I know whether an approximation or exact approach is used in cochrans.q()?

I am unsure whether to post the question here or on Cross Validated. So please migrate the question if it should go to SO.

答:
It uses the asymptotic approximation. It can be seen in the source code of (just type cochrans.q) as it contains

```<code>p = 1 - pchisq(Q, df)
</code>```

Title: Exact Cochran's Q test in R

Body:
It uses the asymptotic approximation. It can be seen in the source code of (just type cochrans.q) as it contains

p = 1 - pchisq(Q, df)


问:
Find mismatching files in two folders with bash
I have two folders - FolderA and FolderB - each containing thousands of files that should be named exactly the same before the extension.  One folder contains files with .jpg extension and the other with .txt extension.

My objective is to find any files that are in one but not in the other.  So for example if FolderA contains:

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

and FolderB contains:

```<code>foo.txt
baz.txt
qux.txt
</code>```

The script should return:

```<code>FolderA/bar.jpg
FolderB/qux.txt
</code>```

How would it be possible with bash to create such an output by inputting two separate directories ?  I was hoping to somehow modify the diff command which would give the Only in ... output but in this case since the extensions are different, diff would output all files

```<code>diff -rq FolderA FolderB
</code>```

答:
assume your filenames don't have special chars (like . or /), this awk "one-liner" will do the job:

```<code>awk -F'[./]' 'NR==FNR{a[$(NF-1)]=$0;next}
        $(NF-1) in a{delete a[$(NF-1)];next}
        {print}END{for(x in a)print a[x]}'
       <(find DIR1/ -name *.jpg)
       <(find DIR2/ -name *.txt)
</code>```

you replace the DIR1 and DIR2 by your real dir names

if your filenames do contain special chars, you need to quote the filenames or just cut the suffix. But it is the details of implementation, and it is not difficult. This answer shows you the direction to solve the problem.

Body:
I have two folders - FolderA and FolderB - each containing thousands of files that should be named exactly the same before the extension.  One folder contains files with .jpg extension and the other with .txt extension.

My objective is to find any files that are in one but not in the other.  So for example if FolderA contains:

foo.jpg
bar.jpg
baz.jpg

and FolderB contains:

foo.txt
baz.txt
qux.txt

The script should return:

FolderA/bar.jpg
FolderB/qux.txt

How would it be possible with bash to create such an output by inputting two separate directories ?  I was hoping to somehow modify the diff command which would give the Only in ... output but in this case since the extensions are different, diff would output all files

diff -rq FolderA FolderB

Body:
assume your filenames don't have special chars (like . or /), this awk "one-liner" will do the job:

awk -F'[./]' 'NR==FNR{a[$(NF-1)]=$0;next}
        $(NF-1) in a{delete a[$(NF-1)];next}
        {print}END{for(x in a)print a[x]}'
       <(find DIR1/ -name *.jpg)
       <(find DIR2/ -name *.txt)

you replace the DIR1 and DIR2 by your real dir names

if your filenames do contain special chars, you need to quote the filenames or just cut the suffix. But it is the details of implementation, and it is not difficult. This answer shows you the direction to solve the problem.


答:
You are using a char (character array) a as the switch variable and a logical (true/false) expression result as a case, it will always go to otherwise because a char is not a logical.

You can use the logical expression result as the switch variable and use true as a case:

```<code>a='test1';
switch ~isempty(regexpi(a,'test','match','once'))
  case  true %should handle all cases where 'test' is contained in the input string
    disp('this');
  otherwise %should handle everything else
    disp('that');
end
</code>```

Or simply use an if-else statement:

```<code>a='test1';
if ~isempty(regexpi(a,'test','match','once'))
    disp('this');
else %should handle everything else
    disp('that');
end
</code>```

Title: matlab switch + regexp

Body:
You are using a char (character array) a as the switch variable and a logical (true/false) expression result as a case, it will always go to otherwise because a char is not a logical.

You can use the logical expression result as the switch variable and use true as a case:

a='test1';
switch ~isempty(regexpi(a,'test','match','once'))
  case  true %should handle all cases where 'test' is contained in the input string
    disp('this');
  otherwise %should handle everything else
    disp('that');
end

Or simply use an if-else statement:

a='test1';
if ~isempty(regexpi(a,'test','match','once'))
    disp('this');
else %should handle everything else
    disp('that');
end


问:
What's the best way to track unique visits to a page?
I want to log unique visits to a particular page on my site. What is a pretty accurate yet simple way to do this? Simply by IP? Suggestions?

Let me clarify a bit:

I have a list of articles on my site. Every article is actually the same page like article.aspx. However the content is different based on thee article being viewed. I want to track unique views of a particular article.

Thanks!

答:
All approaches will have their drawbacks. Cookies may not be enabled in the browser, IP addresses may be duplicated due to NAT (I know at our work, all traffic to the outside world looks like it's coming from one IP address) or reused due to DHCP.

It depends on what you're going to use the information for. If you want to know how many unique people are viewing your site, that's incredibly difficult since many people may use one browser or IP address.

I would think most people are interested in how many useful accesses are made. This means that, even if the same IP address comes back one week later, that should count again.

We've used that exact system (and made sure our clients realize it's an imperfect one). Store the IP addresses and first and last date of access in a table.

If it's a newly added IP address, add one hit and store IP/dates. If it's an already existing IP, update the last date. Do a nightly sweep to remove IP's whose last date is older than 7 days or whose first date is older than 14 days (both configurable).

That way you catch the useful accesses:

people who visit continuously are assumed to have a useful access every two weeks.

people who visit then disappear for a year and visit again have had two useful accesses.

people who visit once have had one useful access.

As long as the inadequacies are understood, they can be managed.

OwnerDisplayName: Micah

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Micah

OwnerDisplayName: Pax


问:
django sort object_list by through field
Say I have the good old person/group/membership relationship

```<code>class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)
</code>```

and i want a generic view that displays a list of persons belonging to a group (specified in the URL) sorted by the date_joined field of the Membership class. I figured I could just do a view like this

```<code>def group_list(request, pagina):
    return list_detail.object_list(
        request,
        queryset = Person.objects.filter(group__name = slug),
        template_object_name = 'person',
        extra_context = { 'membership' : Membership.objects.all() },

        )
</code>```

And then just access the date_joined in the template via  membership__date_joined but no luck

答:
What you actually want to do is to start from the Membership object. This is the only thing that is unique for a particular combination of Person and Group - if you start from the Person, as you are doing, accessing their memberships gives you all of them, not the one you want. So:

```<code>return list_detail.object_list(
    request,
    queryset = Membership.objects.filter(group__name = slug),
    template_object_name = 'membership',
)
</code>```

Now in your template:

```<code>{% for member in membership %}
    {{ member.person.name }}: {{ member.date_joined }}
{% endif %}
</code>```

Body:
Say I have the good old person/group/membership relationship

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __unicode__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __unicode__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person)
    group = models.ForeignKey(Group)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

and i want a generic view that displays a list of persons belonging to a group (specified in the URL) sorted by the date_joined field of the Membership class. I figured I could just do a view like this

def group_list(request, pagina):
    return list_detail.object_list(
        request,
        queryset = Person.objects.filter(group__name = slug),
        template_object_name = 'person',
        extra_context = { 'membership' : Membership.objects.all() },

        )

And then just access the date_joined in the template via  membership__date_joined but no luck

Body:
What you actually want to do is to start from the Membership object. This is the only thing that is unique for a particular combination of Person and Group - if you start from the Person, as you are doing, accessing their memberships gives you all of them, not the one you want. So:

return list_detail.object_list(
    request,
    queryset = Membership.objects.filter(group__name = slug),
    template_object_name = 'membership',
)

Now in your template:

{% for member in membership %}
    {{ member.person.name }}: {{ member.date_joined }}
{% endif %}


问:
Adding default prop for a compound component
I'm using a Modal component from a library which is written on top of ReactModal and have the following API:

```<code><Modal {...props} /> // all props are passed to ReactModal
<Modal.Header />     // some styles of header are applied
<Modal.Body />       // some styles of body are applied
<Modal.Footer />     // some styles of footer
</code>```

Now I want to set 2 props parentSelector and appElement for all Modal usages I'm doing in my application. How do I do it? I've tried creating a wrapper to add these 2 props like this

function AppModal(props) {
    return (
        <Modal parentSelector={getParent} appElement={getParent()} {...props} />
    );
}
```

but this makes AppModal.Header, AppModal.Body, AppModal.Footer undefined.

答:
This is because you are actually only overwriting the Modal Component. Modal.Header, Modal.Body, and Modal.Footer are separate components that are set as static properties on the Modal class.

If you want to set the parentSelector and appElement props on all components, you should wrap all components.

```<code>function AppModal(props) {
  return (
    <Modal parentSelector={getParent} appElement={getParent()} {...props} />
  );
}

AppModal.Header = function (props) {
  return (
    <Modal.Header parentSelector={getParent} appElement={getParent()} {...props} />
  );
};

AppModal.Body = function (props) {
  return (
    <Modal.Body parentSelector={getParent} appElement={getParent()} {...props} />
  );
};

AppModal.Footer = function (props) {
  return (
    <Modal.Footer parentSelector={getParent} appElement={getParent()} {...props} />
  );
};
</code>```

If they are all the same as in the example above, I would probably create a wrapping function like so:

```<code>function wrap (Component) {
  return function (props) {
    return <Component parentSelector={getParent} appElement={getParent()} {...props} />
  }
}

const AppModal = wrap(Modal);

AppModal.Header = wrap(Modal.Header);
AppModal.Body = wrap(Modal.Body);
AppModal.Footer = wrap(Modal.Footer);
</code>```

Body:
I'm using a Modal component from a library which is written on top of ReactModal and have the following API:

<Modal {...props} /> // all props are passed to ReactModal
<Modal.Header />     // some styles of header are applied
<Modal.Body />       // some styles of body are applied
<Modal.Footer />     // some styles of footer

Now I want to set 2 props parentSelector and appElement for all Modal usages I'm doing in my application. How do I do it? I've tried creating a wrapper to add these 2 props like this

function AppModal(props) {
    return (
        <Modal parentSelector={getParent} appElement={getParent()} {...props} />
    );
}

but this makes AppModal.Header, AppModal.Body, AppModal.Footer undefined.

Body:
This is because you are actually only overwriting the Modal Component. Modal.Header, Modal.Body, and Modal.Footer are separate components that are set as static properties on the Modal class.

If you want to set the parentSelector and appElement props on all components, you should wrap all components.

function AppModal(props) {
  return (
    <Modal parentSelector={getParent} appElement={getParent()} {...props} />
  );
}

AppModal.Header = function (props) {
  return (
    <Modal.Header parentSelector={getParent} appElement={getParent()} {...props} />
  );
};

AppModal.Body = function (props) {
  return (
    <Modal.Body parentSelector={getParent} appElement={getParent()} {...props} />
  );
};

AppModal.Footer = function (props) {
  return (
    <Modal.Footer parentSelector={getParent} appElement={getParent()} {...props} />
  );
};

If they are all the same as in the example above, I would probably create a wrapping function like so:

function wrap (Component) {
  return function (props) {
    return <Component parentSelector={getParent} appElement={getParent()} {...props} />
  }
}

const AppModal = wrap(Modal);

AppModal.Header = wrap(Modal.Header);
AppModal.Body = wrap(Modal.Body);
AppModal.Footer = wrap(Modal.Footer);


问:
Wikimedia API: How to get page contents
I am trying to get the content of the wikimedia pages like these ones:

https://meta.wikimedia.org/wiki/MediaWiki:Centralnotice-FR2015_translations-smallamount-error

https://meta.wikimedia.org/wiki/MediaWiki:FundraisingBanners/SmallPrint-2017

I am working on something related to translations and banners but I'm stuck in this step.

I've been testing several of the endpoints in this API https://www.mediawiki.org/w/api.php with not succeed.

Could you help me please?

答:
These are what you want:

```<code>https://meta.wikimedia.org/w/api.php?action=query&prop=revisions&rvslots=*&rvprop=content&format=json&titles=MediaWiki:Centralnotice-FR2015_translations-smallamount-error

https://meta.wikimedia.org/w/api.php?action=query&prop=revisions&rvslots=*&rvprop=content&format=json&titles=MediaWiki:FundraisingBanners/SmallPrint-2017
</code>```

Let me know if you're struggling to extract the content from those.

Title: Wikimedia API: How to get page contents

Body:
These are what you want:

https://meta.wikimedia.org/w/api.php?action=query&prop=revisions&rvslots=*&rvprop=content&format=json&titles=MediaWiki:Centralnotice-FR2015_translations-smallamount-error

https://meta.wikimedia.org/w/api.php?action=query&prop=revisions&rvslots=*&rvprop=content&format=json&titles=MediaWiki:FundraisingBanners/SmallPrint-2017

Let me know if you're struggling to extract the content from those.


问:
laravel how to store image in 4 different folder at same time

my below code stores image 2 different at the same time but I am trying to
  store image in 4 different folders at the same time, but it not storing 4
  different folder it only passing image in 2 folders how to slow this
  problem

This code only Stores in Two Folder

```<code>public function store(Request $request)

    {

      $this->validate($request, [

          'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
          ]);

            $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
            $request->image->move(public_path('Folder-a/'), $input['image']);
            $folder1 = public_path('Folder-1/') . $input['image'];
            $folder2 = public_path(Folder-2/') . $input['image'];
            $folder3 = public_path('Folder-3/') . $input['image'];
            $folder4 = public_path(Folder-4/') . $input['image'];
            \File::copy($folder1, $folder2, $folder3, $folder4 );

        Service::create($input);

        return back()->with('success',' CREATED SUCCESSFULLY .');

    }
</code>```

@ Manojkiran.A you provided code

```<code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Illuminate\Support\Facades\File;
use saveFilesMultipleTimes;
class ServiceController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, ['image' => 'required|image|mimes:jpeg,png,jpg|max:2048',]);
$mainFolderPath = public_path('Folder-a/');
$folder1 = public_path('Folder-1/');
$folder2 = public_path('Folder-2/');
$folder3 = public_path('Folder-3/');
$folder4 = public_path('Folder-4/');
$fileObject = $request->image;
$filenamesWithPath = self::saveFilesMultipleTimes( $fileObject, $mainFolderPath, [$folder1, $folder2,
$folder3, $folder4]);
dd($filenamesWithPath);
function saveFilesMultipleTimes( \Illuminate\Http\UploadedFile$requestFile, $mainFolderPath,$paths)
{
$fileName = $requestFile->getClientOriginalName();
$movedFile = $requestFile->move($mainFolderPath, $fileName);
$currentFile = $movedFile->getPathName();
foreach ( (array) $paths as $eachPath)
{
@mkdir( $eachPath);
@copy($movedFile->getPathName(), $eachPath . $fileName);
$dirctory[] = $eachPath.$fileName;
}
return $dirctory;
}
Service::create($input);
return back()->with('success',' CREATED SUCCESSFULLY .');
}
</code>```

}

答:
ok i have tried many methods any finaly created the function

```<code>function saveFilesMultipleTimes( \Illuminate\Http\UploadedFile$requestFile, $mainFolderPath,$paths)
{

    $fileName = $requestFile->getClientOriginalName();

    $movedFile = $requestFile->move($mainFolderPath, $fileName);

    $currentFile = $movedFile->getPathName();

    foreach ( (array) $paths as $eachPath)
    {
        @mkdir( $eachPath);
        @copy($movedFile->getPathName(), $eachPath . $fileName);
        $dirctory[] = $eachPath.$fileName;
    }
    return $dirctory;
}
</code>```

Copy and Paste it in your Controller

Now How to use it

```<code>$mainFolderPath = public_path('Folder-a/');
$folder1 = public_path('Folder-1/');
$folder2 = public_path('Folder-2/');
$folder3 = public_path('Folder-3/');
$folder4 = public_path('Folder-4/');

$fileObject = $request->image;
$filenamesWithPath = saveFilesMultipleTimes( $fileObject, $mainFolderPath, [$folder1, $folder2, $folder3, $folder4]);

dd($filenamesWithPath);
</code>```

This dd Will give the all filenames along with the path

Hope its help

UPDATED WITH CONTROLLER

```<code><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Illuminate\Support\Facades\File;

class ServiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        $this->validate($request, ['image' => 'required|image|mimes:jpeg,png,jpg|max:2048',]);
        $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
        $mainFolderPath = public_path('Folder-a/');
        $folder1 = public_path('Folder-1/');
        $folder2 = public_path('Folder-2/');
        $folder3 = public_path('Folder-3/');
        $folder4 = public_path('Folder-4/');
        $fileObject = $request->image;
        $filenamesWithPath = self::saveFilesMultipleTimes($fileObject, $mainFolderPath, [$folder1, $folder2,
        $folder3, $folder4]);

        Service::create($input);

        return back()->with('success', ' CREATED SUCCESSFULLY .');
    }

    public function saveFilesMultipleTimes(\Illuminate\Http\UploadedFile$requestFile, $mainFolderPath, $paths)
    {
        $fileName = $requestFile->getClientOriginalName();
        $movedFile = $requestFile->move($mainFolderPath, $fileName);
        foreach ((array) $paths as $eachPath) {
            @mkdir($eachPath);
            @copy($movedFile->getPathName(), $eachPath . $fileName);
            $dirctory[] = $eachPath.$fileName;
        }
        return $dirctory;
    }

}
</code>```

IF you are facing any issues kindly comment below

AND IF THE FILE IS UPLOADING SUCCESSFULLY FOUR TIMES KINDLY MARK MY ANSWER AS ACCEPTED

Body:
my below code stores image 2 different at the same time but I am trying to
  store image in 4 different folders at the same time, but it not storing 4
  different folder it only passing image in 2 folders how to slow this
  problem

This code only Stores in Two Folder

public function store(Request $request)

    {

      $this->validate($request, [

          'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
          ]);

            $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
            $request->image->move(public_path('Folder-a/'), $input['image']);
            $folder1 = public_path('Folder-1/') . $input['image'];
            $folder2 = public_path(Folder-2/') . $input['image'];
            $folder3 = public_path('Folder-3/') . $input['image'];
            $folder4 = public_path(Folder-4/') . $input['image'];
            \File::copy($folder1, $folder2, $folder3, $folder4 );

        Service::create($input);

        return back()->with('success',' CREATED SUCCESSFULLY .');

    }

@ Manojkiran.A you provided code

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Illuminate\Support\Facades\File;
use saveFilesMultipleTimes;
class ServiceController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, ['image' => 'required|image|mimes:jpeg,png,jpg|max:2048',]);
$mainFolderPath = public_path('Folder-a/');
$folder1 = public_path('Folder-1/');
$folder2 = public_path('Folder-2/');
$folder3 = public_path('Folder-3/');
$folder4 = public_path('Folder-4/');
$fileObject = $request->image;
$filenamesWithPath = self::saveFilesMultipleTimes( $fileObject, $mainFolderPath, [$folder1, $folder2,
$folder3, $folder4]);
dd($filenamesWithPath);
function saveFilesMultipleTimes( \Illuminate\Http\UploadedFile$requestFile, $mainFolderPath,$paths)
{
$fileName = $requestFile->getClientOriginalName();
$movedFile = $requestFile->move($mainFolderPath, $fileName);
$currentFile = $movedFile->getPathName();
foreach ( (array) $paths as $eachPath)
{
@mkdir( $eachPath);
@copy($movedFile->getPathName(), $eachPath . $fileName);
$dirctory[] = $eachPath.$fileName;
}
return $dirctory;
}
Service::create($input);
return back()->with('success',' CREATED SUCCESSFULLY .');
}

}

Body:
ok i have tried many methods any finaly created the function

function saveFilesMultipleTimes( \Illuminate\Http\UploadedFile$requestFile, $mainFolderPath,$paths)
{

    $fileName = $requestFile->getClientOriginalName();

    $movedFile = $requestFile->move($mainFolderPath, $fileName);

    $currentFile = $movedFile->getPathName();

    foreach ( (array) $paths as $eachPath)
    {
        @mkdir( $eachPath);
        @copy($movedFile->getPathName(), $eachPath . $fileName);
        $dirctory[] = $eachPath.$fileName;
    }
    return $dirctory;
}

Copy and Paste it in your Controller

Now How to use it

$mainFolderPath = public_path('Folder-a/');
$folder1 = public_path('Folder-1/');
$folder2 = public_path('Folder-2/');
$folder3 = public_path('Folder-3/');
$folder4 = public_path('Folder-4/');

$fileObject = $request->image;
$filenamesWithPath = saveFilesMultipleTimes( $fileObject, $mainFolderPath, [$folder1, $folder2, $folder3, $folder4]);

dd($filenamesWithPath);

This dd Will give the all filenames along with the path

Hope its help

UPDATED WITH CONTROLLER

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Service;
use Illuminate\Support\Facades\File;

class ServiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        $this->validate($request, ['image' => 'required|image|mimes:jpeg,png,jpg|max:2048',]);
        $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
        $mainFolderPath = public_path('Folder-a/');
        $folder1 = public_path('Folder-1/');
        $folder2 = public_path('Folder-2/');
        $folder3 = public_path('Folder-3/');
        $folder4 = public_path('Folder-4/');
        $fileObject = $request->image;
        $filenamesWithPath = self::saveFilesMultipleTimes($fileObject, $mainFolderPath, [$folder1, $folder2,
        $folder3, $folder4]);

        Service::create($input);

        return back()->with('success', ' CREATED SUCCESSFULLY .');
    }

    public function saveFilesMultipleTimes(\Illuminate\Http\UploadedFile$requestFile, $mainFolderPath, $paths)
    {
        $fileName = $requestFile->getClientOriginalName();
        $movedFile = $requestFile->move($mainFolderPath, $fileName);
        foreach ((array) $paths as $eachPath) {
            @mkdir($eachPath);
            @copy($movedFile->getPathName(), $eachPath . $fileName);
            $dirctory[] = $eachPath.$fileName;
        }
        return $dirctory;
    }

}

IF you are facing any issues kindly comment below

AND IF THE FILE IS UPLOADING SUCCESSFULLY FOUR TIMES KINDLY MARK MY ANSWER AS ACCEPTED


问:
How to Combine Excel Workbooks into One Workbook and Name the Worksheets
I am trying to combine several Excel workbooks into a single workbook while naming the worksheets the file name of the copied workbook.

I've tried moving $Worksheet.Name within the for loop and outside.  It still only gives a name to the empty worksheet in the new workbook - naming it the last file copied.

```<code>$ExcelObject=New-Object -ComObject excel.application
$ExcelObject.visible=$true
$ExcelFiles=Get-ChildItem -Path C:\Users\u1\Documents\Testing

$Workbook=$ExcelObject.Workbooks.add()
$Worksheet=$Workbook.Sheets.Item("Sheet1")

foreach($ExcelFile in $ExcelFiles){

$Everyexcel=$ExcelObject.Workbooks.Open($ExcelFile.FullName)
$Everysheet=$Everyexcel.sheets.item(1)
$Everysheet.Copy($Worksheet)
$Worksheet.Name = [io.path]::GetFileNameWithoutExtension($ExcelFile)
$Everyexcel.Close()
}

$Workbook.SaveAs("C:\Users\u1\Documents\Testing\New\merged.xlsx")
$ExcelObject.Quit()
</code>```

The new workbook is created (merged.xlsx) but the worksheets are all named Sheet1(...) except for one empty worksheet that is named the last file in the directory.  I also get the following errors.
Excel cannot access 'New'.  The document may be read-only or encrypted.
You cannot call a method on a null-valued expression.

答:
The problem you're facing is that the $Everysheet.Copy($Worksheet) call is copying both the values and the sheet names from $Everysheet and placing it before $Worksheet. You can see the documentation of the Copy method here.

I'm unsure of how you'd track the sheet names to the individual workbooks in order to rename them, however I highly recommend using the ImportExcel module for any Excel-related files. It makes them much easier to work with and only takes a couple seconds to get it working. Moreover it has the benefit of using reading and editing Excel files without needing Microsoft Excel to be installed.

You can accomplish what you're looking to do in a few lines:

```<code>$exportExcelPath = "C:\Users\u1\Documents\Testing\New\merged.xlsx"

$excelFiles = Get-ChildItem -Path 'C:\Users\u1\Documents\Testing' -Filter "*.xlsx"
foreach ($excelFile in $excelFiles)
{
    Import-Excel -Path $excelFile.FullName | Export-Excel -Path $exportExcelPath -WorkSheetname ([io.path]::GetFileNameWithoutExtension($excelFile))
}
</code>```

Body:
I am trying to combine several Excel workbooks into a single workbook while naming the worksheets the file name of the copied workbook.

I've tried moving $Worksheet.Name within the for loop and outside.  It still only gives a name to the empty worksheet in the new workbook - naming it the last file copied.

$ExcelObject=New-Object -ComObject excel.application
$ExcelObject.visible=$true
$ExcelFiles=Get-ChildItem -Path C:\Users\u1\Documents\Testing

$Workbook=$ExcelObject.Workbooks.add()
$Worksheet=$Workbook.Sheets.Item("Sheet1")

foreach($ExcelFile in $ExcelFiles){

$Everyexcel=$ExcelObject.Workbooks.Open($ExcelFile.FullName)
$Everysheet=$Everyexcel.sheets.item(1)
$Everysheet.Copy($Worksheet)
$Worksheet.Name = [io.path]::GetFileNameWithoutExtension($ExcelFile)
$Everyexcel.Close()
}

$Workbook.SaveAs("C:\Users\u1\Documents\Testing\New\merged.xlsx")
$ExcelObject.Quit()

The new workbook is created (merged.xlsx) but the worksheets are all named Sheet1(...) except for one empty worksheet that is named the last file in the directory.  I also get the following errors.
Excel cannot access 'New'.  The document may be read-only or encrypted.
You cannot call a method on a null-valued expression.

Body:
The problem you're facing is that the $Everysheet.Copy($Worksheet) call is copying both the values and the sheet names from $Everysheet and placing it before $Worksheet. You can see the documentation of the Copy method here.

I'm unsure of how you'd track the sheet names to the individual workbooks in order to rename them, however I highly recommend using the ImportExcel module for any Excel-related files. It makes them much easier to work with and only takes a couple seconds to get it working. Moreover it has the benefit of using reading and editing Excel files without needing Microsoft Excel to be installed.

You can accomplish what you're looking to do in a few lines:

$exportExcelPath = "C:\Users\u1\Documents\Testing\New\merged.xlsx"

$excelFiles = Get-ChildItem -Path 'C:\Users\u1\Documents\Testing' -Filter "*.xlsx"
foreach ($excelFile in $excelFiles)
{
    Import-Excel -Path $excelFile.FullName | Export-Excel -Path $exportExcelPath -WorkSheetname ([io.path]::GetFileNameWithoutExtension($excelFile))
}


问:
Switching to master and back to working branch shows file modified in Git
I am working on library_backend project and it is git repository which have 2 branches :

master

multilanguage.

i have made some changes in multilanguage branch and pushed it to its remote branch and after it i want to check some functions on master branch.

so i have switched to master branch and after checking i have switched back to multilanguage branch but now it has modified file which is books_model.php, how can it has modified file if i have pushed it some seconds ago?

You can see what i have done after pushing to remote branch as below:

```<code>ABC@ABC-PC MINGW64 /c/xampp/htdocs/library_backend (multilanguage)
$ git checkout master
Switched to branch 'master'
M       application/models/api_model/books_model.php
Your branch and 'origin/master' have diverged,
and have 4 and 10 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

ABC@ABC-PC MINGW64 /c/xampp/htdocs/library_backend (master)
$ git checkout multilanguage
Switched to branch 'multilanguage'

ABC@ABC-PC MINGW64 /c/xampp/htdocs/library_backend (multilanguage)
$ git status
On branch multilanguage
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   application/models/api_model/books_model.php

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

答: Most possibly this change was already in place and you only pushed a commit containing other changes. This of course if you haven’t changed this file by mistake while you were on your local master branch.</p>

Body:
I am working on library_backend project and it is git repository which have 2 branches :

master

multilanguage.

i have made some changes in multilanguage branch and pushed it to its remote branch and after it i want to check some functions on master branch.

so i have switched to master branch and after checking i have switched back to multilanguage branch but now it has modified file which is books_model.php, how can it has modified file if i have pushed it some seconds ago?

You can see what i have done after pushing to remote branch as below:

ABC@ABC-PC MINGW64 /c/xampp/htdocs/library_backend (multilanguage)
$ git checkout master
Switched to branch 'master'
M       application/models/api_model/books_model.php
Your branch and 'origin/master' have diverged,
and have 4 and 10 different commits each, respectively.
  (use "git pull" to merge the remote branch into yours)

ABC@ABC-PC MINGW64 /c/xampp/htdocs/library_backend (master)
$ git checkout multilanguage
Switched to branch 'multilanguage'

ABC@ABC-PC MINGW64 /c/xampp/htdocs/library_backend (multilanguage)
$ git status
On branch multilanguage
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   application/models/api_model/books_model.php

no changes added to commit (use "git add" and/or "git commit -a")


问:
unable to load the haarcascadeshaarcascade.xml in opencv
Im trying face detection using opencv in android but I unable to load the object detection xml files.

The code is as follows,

.....

```<code>static CvHaarClassifierCascade* cascade = 0;
  CvMemStorage* storage = 0;
  LOGI("before haarcascade");

if (!cascade) {
    const char* file = "/Users/Downloads/OpenCV-

2.2.0/data/haarcascadeshaarcascade_frontalface_alt.xml";
    cascade = (CvHaarClassifierCascade *)cvLoad(file, 0, 0, 0);
    storage = cvCreateMemStorage(0);
  }

if(cascade)
      LOGI("xml loaded");
  else
          LOGI("unable to load the xml");
</code>```

......

In logcat it showing that unable to load the xml.

How to load the xml??

Please someone help me out.

Thanks,
Srinivasan

答:
Daft question... but the file does exist doesn't it?

If that code runs on your android device, but the file exists on the host (Mac OS) workstation you're out of luck!

Body:
Im trying face detection using opencv in android but I unable to load the object detection xml files.

The code is as follows,

.....

static CvHaarClassifierCascade* cascade = 0;
  CvMemStorage* storage = 0;
  LOGI("before haarcascade");

if (!cascade) {
    const char* file = "/Users/Downloads/OpenCV-

2.2.0/data/haarcascadeshaarcascade_frontalface_alt.xml";
    cascade = (CvHaarClassifierCascade *)cvLoad(file, 0, 0, 0);
    storage = cvCreateMemStorage(0);
  }

if(cascade)
      LOGI("xml loaded");
  else
          LOGI("unable to load the xml");

......

In logcat it showing that unable to load the xml.

How to load the xml??

Please someone help me out.

Thanks,
Srinivasan


问:
OpenCV(4.0.0) Python Error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'
I am trying to apply mask on an image using opencv bitwise-not. I am able to achieve this result if I read both original and mask  image in Greyscale mode, but it doesn't work on 3 channel images.

I have read this thread OpenCV Python Error: error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function cv::binary_op but my problem isn't shapes of arrays or mask not being in uint8 format.

import cv2
import numpy as np

img = cv2.imread("Original.png") # original image, shape 544,480,3, dtype uint8
label = cv2.imread("Mask.png") # black and white mask,shape 544,480,3, dtype uint 8
shape = img.shape # 544,480,3
black_background = np.zeros(shape=shape, dtype=np.uint8)
result = cv2.bitwise_not(img,black_background,mask=label) # this is where error occurs
cv2.imwrite("masked.png",result)
```

<p>I expect the output to be original image masked with label, I get error core </p>

```OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:245: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'

```

答:
As the error hints, the problem actually is the mask shape. From the docs:

mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

Your label is a 3-channel image, which is incompatible; that's the reason why the greyscale was working, but since your Mask.png actually is a black and white image you should go for it without any worries:

```<code>label = cv2.imread("Mask.png", cv2.IMREAD_GREYSCALE)
</code>```

Body:
I am trying to apply mask on an image using opencv bitwise-not. I am able to achieve this result if I read both original and mask  image in Greyscale mode, but it doesn't work on 3 channel images.

I have read this thread OpenCV Python Error: error: (-215) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function cv::binary_op but my problem isn't shapes of arrays or mask not being in uint8 format.

import cv2
import numpy as np

img = cv2.imread("Original.png") # original image, shape 544,480,3, dtype uint8
label = cv2.imread("Mask.png") # black and white mask,shape 544,480,3, dtype uint 8
shape = img.shape # 544,480,3
black_background = np.zeros(shape=shape, dtype=np.uint8)
result = cv2.bitwise_not(img,black_background,mask=label) # this is where error occurs
cv2.imwrite("masked.png",result)

I expect the output to be original image masked with label, I get error core

OpenCV(4.0.0) C:\projects\opencv-python\opencv\modules\core\src\arithm.cpp:245: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'cv::binary_op'

Body:
As the error hints, the problem actually is the mask shape. From the docs:

mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

Your label is a 3-channel image, which is incompatible; that's the reason why the greyscale was working, but since your Mask.png actually is a black and white image you should go for it without any worries:

label = cv2.imread("Mask.png", cv2.IMREAD_GREYSCALE)


问:
failed to complete security handshake on grpc?
I've already changed many times the port number on the server and client, but the server always get the incorrect port number.

when I execute the client the server will log this:
2017/05/07 15:06:07 grpc: Server.Serve failed to complete security handshake from "127.0.0.1:32763": remote error: tls: bad certificate
and on the client side, i got this:
2017/05/07 15:06:07 Failed to dial localhost:8070: connection error: desc = "transport: x509: certificate is not valid for any names, but wanted to match localhost:8070"; please retry.
rpc error: code = Internal desc = connection error: desc = "transport: x509: certificate is not valid for any names, but wanted to match localhost:8070"

I have this code for the server.go

```<code>func serve() {
    addr := "localhost:8070"
    crt, key := certificate.CreatePemKey()
    certificate, err := tls.X509KeyPair(crt, key)
    if err != nil {
        fmt.Println(err)
    }

    certPool := x509.NewCertPool()
    ca, err := ioutil.ReadFile("F:/GIAG3.crt")
    if err != nil {
        fmt.Println(err)
    }

    if ok := certPool.AppendCertsFromPEM(ca); !ok {
        fmt.Println("unable to append certificate")
    }

    lis, err := net.Listen("tcp", addr)
    if err != nil {
        fmt.Println("could not list on %s: %s", addr, err)
    }

    // Create the TLS credentials
    creds := credentials.NewTLS(&tls.Config{
        ClientAuth:   tls.RequireAndVerifyClientCert,
        Certificates: []tls.Certificate{certificate},
        ClientCAs:    certPool,
    })

    srv := grpc.NewServer(grpc.Creds(creds))
    pb.RegisterPingerServer(srv, &server{})

    if err := srv.Serve(lis); err != nil {
        fmt.Println("grpc serve error: %s", err)
    }
}
</code>```

and this is for the client.go

```<code>func testDial2() {
    addr := "localhost:8070"
    crt, key := certificate.CreatePemKey()
    certificate, err := tls.X509KeyPair(crt, key)
    if err != nil {
        fmt.Println(err)
    }

    certPool := x509.NewCertPool()
    ca, err := ioutil.ReadFile("F:/GIAG3.crt")
    if err != nil {
        fmt.Println(err)
    }

    if ok := certPool.AppendCertsFromPEM(ca); !ok {
        fmt.Println("unable to append certificate")
    }

    creds := credentials.NewTLS(&tls.Config{
        ServerName:   addr,
        Certificates: []tls.Certificate{certificate},
        RootCAs:      certPool,
    })

    conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(creds))
    if err != nil {
        fmt.Println(err)
    }

    defer conn.Close()
    c := pb.NewPingerClient(conn)
    r, err := c.Ping(context.Background(), &pb.Payload{Message: "Ping"})
    if err != nil {
        fmt.Println(err)
    }
    log.Printf("%s", r.Message)
}
</code>```

this is for the CreatePemKey, it is based on this example https://golang.org/src/crypto/tls/generate_cert.go

```<code>func publicKey(priv interface{}) interface{} {
    switch k := priv.(type) {
    case *rsa.PrivateKey:
        return &k.PublicKey
    case *ecdsa.PrivateKey:
        return &k.PublicKey
    default:
        return nil
    }
}

func pemBlockForKey(priv interface{}) *pem.Block {
    switch k := priv.(type) {
    case *rsa.PrivateKey:
        return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
    case *ecdsa.PrivateKey:
        b, err := x509.MarshalECPrivateKey(k)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err)
            os.Exit(2)
        }
        return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
    default:
        return nil
    }
}

func CreatePemKey() (certpem, keypem []byte) {
    priv, _ := rsa.GenerateKey(rand.Reader, 2048)
    notBefore := time.Now()
    notAfter := notBefore.AddDate(1, 0, 0)
    serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
    serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)

    template := x509.Certificate{
        SerialNumber: serialNumber,
        Subject: pkix.Name{
            Organization: []string{"Acme Co"},
        },
        NotBefore:             notBefore,
        NotAfter:              notAfter,
        KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
        BasicConstraintsValid: true,
    }
    // template.IPAddresses = append(template.IPAddresses, net.ParseIP("localhost"))
    template.IsCA = true
    derbytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
    certpem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derbytes})
    keypem = pem.EncodeToMemory(pemBlockForKey(priv))
    return certpem, keypem
}
</code>```

BTW the GIAG3.crt is came from here https://pki.goog/

Please help me, thanks

答:
If you found this log in journalctl -u docker:

```<code>mai 29 10:33:04 ca275nt dockerd[1523]: time="2019-05-29T10:33:04.454362399-03:00" level=warning msg="grpc: Server.Serve failed to complete security handshake from \"192.168.0.45:58392\": remote error: tls: bad certificate" module=grpc
</code>```

It can be related with docker swarm requests from another swarm cluster node host trying to connect to docker swarm master node with a invalid token.

You can discover the invalid cluster node hostname with:

```<code>nslookup 192.168.0.45
45.0.168.192.in-addr.arpa       name = hostabc.domain.com.
45.0.168.192.in-addr.arpa       name = hostabc.

Authoritative answers can be found from:
</code>```

By running a docker swarm leave on the reported host, resolve the issue.

I know it's not related with the main question, but I was searching for:
docker "grpc: Server.Serve failed to complete security handshake from" and this was the first question. then I think it's useful to put the troubleshooting here to save some time to others.

Body:
I've already changed many times the port number on the server and client, but the server always get the incorrect port number.

when I execute the client the server will log this:
2017/05/07 15:06:07 grpc: Server.Serve failed to complete security handshake from "127.0.0.1:32763": remote error: tls: bad certificate
and on the client side, i got this:
2017/05/07 15:06:07 Failed to dial localhost:8070: connection error: desc = "transport: x509: certificate is not valid for any names, but wanted to match localhost:8070"; please retry.
rpc error: code = Internal desc = connection error: desc = "transport: x509: certificate is not valid for any names, but wanted to match localhost:8070"

I have this code for the server.go

func serve() {
    addr := "localhost:8070"
    crt, key := certificate.CreatePemKey()
    certificate, err := tls.X509KeyPair(crt, key)
    if err != nil {
        fmt.Println(err)
    }

    certPool := x509.NewCertPool()
    ca, err := ioutil.ReadFile("F:/GIAG3.crt")
    if err != nil {
        fmt.Println(err)
    }

    if ok := certPool.AppendCertsFromPEM(ca); !ok {
        fmt.Println("unable to append certificate")
    }

    lis, err := net.Listen("tcp", addr)
    if err != nil {
        fmt.Println("could not list on %s: %s", addr, err)
    }

    // Create the TLS credentials
    creds := credentials.NewTLS(&tls.Config{
        ClientAuth:   tls.RequireAndVerifyClientCert,
        Certificates: []tls.Certificate{certificate},
        ClientCAs:    certPool,
    })

    srv := grpc.NewServer(grpc.Creds(creds))
    pb.RegisterPingerServer(srv, &server{})

    if err := srv.Serve(lis); err != nil {
        fmt.Println("grpc serve error: %s", err)
    }
}

and this is for the client.go

func testDial2() {
    addr := "localhost:8070"
    crt, key := certificate.CreatePemKey()
    certificate, err := tls.X509KeyPair(crt, key)
    if err != nil {
        fmt.Println(err)
    }

    certPool := x509.NewCertPool()
    ca, err := ioutil.ReadFile("F:/GIAG3.crt")
    if err != nil {
        fmt.Println(err)
    }

    if ok := certPool.AppendCertsFromPEM(ca); !ok {
        fmt.Println("unable to append certificate")
    }

    creds := credentials.NewTLS(&tls.Config{
        ServerName:   addr,
        Certificates: []tls.Certificate{certificate},
        RootCAs:      certPool,
    })

    conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(creds))
    if err != nil {
        fmt.Println(err)
    }

    defer conn.Close()
    c := pb.NewPingerClient(conn)
    r, err := c.Ping(context.Background(), &pb.Payload{Message: "Ping"})
    if err != nil {
        fmt.Println(err)
    }
    log.Printf("%s", r.Message)
}

this is for the CreatePemKey, it is based on this example https://golang.org/src/crypto/tls/generate_cert.go

func publicKey(priv interface{}) interface{} {
    switch k := priv.(type) {
    case *rsa.PrivateKey:
        return &k.PublicKey
    case *ecdsa.PrivateKey:
        return &k.PublicKey
    default:
        return nil
    }
}

func pemBlockForKey(priv interface{}) *pem.Block {
    switch k := priv.(type) {
    case *rsa.PrivateKey:
        return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
    case *ecdsa.PrivateKey:
        b, err := x509.MarshalECPrivateKey(k)
        if err != nil {
            fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err)
            os.Exit(2)
        }
        return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
    default:
        return nil
    }
}

func CreatePemKey() (certpem, keypem []byte) {
    priv, _ := rsa.GenerateKey(rand.Reader, 2048)
    notBefore := time.Now()
    notAfter := notBefore.AddDate(1, 0, 0)
    serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
    serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)

    template := x509.Certificate{
        SerialNumber: serialNumber,
        Subject: pkix.Name{
            Organization: []string{"Acme Co"},
        },
        NotBefore:             notBefore,
        NotAfter:              notAfter,
        KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
        BasicConstraintsValid: true,
    }
    // template.IPAddresses = append(template.IPAddresses, net.ParseIP("localhost"))
    template.IsCA = true
    derbytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv)
    certpem = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derbytes})
    keypem = pem.EncodeToMemory(pemBlockForKey(priv))
    return certpem, keypem
}

BTW the GIAG3.crt is came from here https://pki.goog/

Please help me, thanks

Body:
If you found this log in journalctl -u docker:

mai 29 10:33:04 ca275nt dockerd[1523]: time="2019-05-29T10:33:04.454362399-03:00" level=warning msg="grpc: Server.Serve failed to complete security handshake from \"192.168.0.45:58392\": remote error: tls: bad certificate" module=grpc

It can be related with docker swarm requests from another swarm cluster node host trying to connect to docker swarm master node with a invalid token.

You can discover the invalid cluster node hostname with:

nslookup 192.168.0.45
45.0.168.192.in-addr.arpa       name = hostabc.domain.com.
45.0.168.192.in-addr.arpa       name = hostabc.

Authoritative answers can be found from:

By running a docker swarm leave on the reported host, resolve the issue.

I know it's not related with the main question, but I was searching for:
docker "grpc: Server.Serve failed to complete security handshake from" and this was the first question. then I think it's useful to put the troubleshooting here to save some time to others.


问:
How to see my Compute Engine app in my browser?
I have created a virtual machine on Compute Engine of Google Cloud and I want to host my project made in Node and Angular on that virtual machine. I installed Node on the server and cloned my project from Git, its working perfectly.

My question is, how do I bring that project in the browser?

答:
You should: npm run build. After that you could find dist folder with your project and copy content of this folder to  any static web server (GitHub pages and etc)
Additional info


问:
How can Iist current user record on a select list in views in Ruby on rails
How can I list records that belong to the currently logged in user as a select list?

class User < ApplicationRecord
  has_many :offices, dependent: :destroy
  has_many :staffs, dependent: :destroy
end
```

<pre class="lang-rb prettyprint-override"><code>class Office < ApplicationRecord
  belongs_to :user
  has_many :staffs, dependent: :destroy
end
</code>```

class Staff < ApplicationRecord
  belongs_to :user
  belongs_to :user
end
```

<p>I tried the code below but still will have all offices listed instead of the current user's created offices available for selection</p>

``` <%= f.association :office,  label_method: :office_name, value_method: :user, include_blank: false, prompt: "Assign Staff To Office" %>
```

My expectations are that only offices created by the current user will be listed in the select list item on the staff creation form

答:
Try using a collection select like this</p>

```<code><%= f.collection_select(:office_id, current_user.offices, :id, :name) %>
</code>```

Body:
How can I list records that belong to the currently logged in user as a select list?

class User < ApplicationRecord
  has_many :offices, dependent: :destroy
  has_many :staffs, dependent: :destroy
end

class Office < ApplicationRecord
  belongs_to :user
  has_many :staffs, dependent: :destroy
end

class Staff < ApplicationRecord
  belongs_to :user
  belongs_to :user
end

I tried the code below but still will have all offices listed instead of the current user's created offices available for selection

 <%= f.association :office,  label_method: :office_name, value_method: :user, include_blank: false, prompt: "Assign Staff To Office" %>

My expectations are that only offices created by the current user will be listed in the select list item on the staff creation form

Body:
Try using a collection select like this

<%= f.collection_select(:office_id, current_user.offices, :id, :name) %>


问:
Kivy: play sound on android without delay
I'm creating a metronome app with kivy. Since the ticks need to be exactly on point I ran in a lot of issues.

I sheduled the clock-events as "free" events:

Config.set('kivy', 'kivy_clock', 'free_all')
Config.write()

Clock.schedule_once_free(self.callback, self.delay)
```

<p>If I trace the timings of the callbacks they are all great.
The widgets are updated in these callbacks and they are just on point.</p>

<p>But if I play a sound on the start of the callback it gets executed with different delays every time. So the sound does not relate to the intented bpm.</p>

<p>Different Sound-loaders have different behavior:
"SoundPygame" doesn't have a delay but can't be used for android (missing support for pygame)
The non-kivy module "play sound" works great, but can't be used with a buildozer because of missing module "gi".
"SoundSDL2" is used by default and does not work for this task.</p>

<pre class="lang-py prettyprint-override"><code>sound_norm = SoundPygame(source='sounds/tick.wav')

def callback(self, dt):
    self.sound_norm.play()
</code>```

Is there any way to play sound on android with kivy without event-based delays?

It's my first question here, so please excuse me if I asked something wrong or need to improve my question.
Best regards!

答:
Using Pyjnius soved the problem. I now have platform depandant code.
For Android:

from jnius import autoclass

MediaPlayer = autoclass('android.media.MediaPlayer')
mPlayer_norm = MediaPlayer()
mPlayer_norm.setDataSource(SOUND_NORM)
mPlayer_norm.prepare()
```

<p>later I can play the sound in the callback:</p>

<pre class="lang-py prettyprint-override"><code>self.sound_norm.play()
</code>```

This way there is no noticable delay so it works for me.

Body:
I'm creating a metronome app with kivy. Since the ticks need to be exactly on point I ran in a lot of issues.

I sheduled the clock-events as "free" events:

Config.set('kivy', 'kivy_clock', 'free_all')
Config.write()

Clock.schedule_once_free(self.callback, self.delay)

If I trace the timings of the callbacks they are all great.
The widgets are updated in these callbacks and they are just on point.

But if I play a sound on the start of the callback it gets executed with different delays every time. So the sound does not relate to the intented bpm.

Different Sound-loaders have different behavior:
"SoundPygame" doesn't have a delay but can't be used for android (missing support for pygame)
The non-kivy module "play sound" works great, but can't be used with a buildozer because of missing module "gi".
"SoundSDL2" is used by default and does not work for this task.

sound_norm = SoundPygame(source='sounds/tick.wav')

def callback(self, dt):
    self.sound_norm.play()

Is there any way to play sound on android with kivy without event-based delays?

It's my first question here, so please excuse me if I asked something wrong or need to improve my question.
Best regards!

Body:
Using Pyjnius soved the problem. I now have platform depandant code.
For Android:

from jnius import autoclass

MediaPlayer = autoclass('android.media.MediaPlayer')
mPlayer_norm = MediaPlayer()
mPlayer_norm.setDataSource(SOUND_NORM)
mPlayer_norm.prepare()

later I can play the sound in the callback:

self.sound_norm.play()

This way there is no noticable delay so it works for me.


问:
Flutter redux update the specific state variable without affecting other variable
I have a state like this

```<code>class NameState{
    List name;
    dynamic title;
    NameState({this.title, this.name});
}
</code>```

Action

```<code>class NameAction{
   List  showAction;
   NameAction(this.showAction);

}
</code>```

reducer like this

```<code>NameState reducer(NameState state, dynamic action) {

 if (action is NameAction) {
  return NameState(
    name: []..addAll(action.showAction)
  );
}

 return state;

}
</code>```

and initial state is defined like this
initialState: new NameState(title: 'this is title', name: []), middleware: [thunkMiddleware]);

Here is the main problem,

you can see I have given a static string to title variable. It works fine and visible in all pages.

But as soon as reducer is called this title gets a value of null. I don't want to pass any value to title. It should be as it is with it's own value.
I was updating only the name list.

In javascript state management, we can update any variable we want without affecting other variables in the state. How can I do it in flutter redux?

Thank you.

答:
You need to pass all the variables of the current state when returning a new state.</p>

```<code>NameState reducer(NameState state, dynamic action) {
  if (action is NameAction) {
    return NameState(
      name: []..addAll(action.showAction),
      title: state.title,
    );
  }

  return state;
}
</code>```

Body:
I have a state like this

class NameState{
    List name;
    dynamic title;
    NameState({this.title, this.name});
}

Action

class NameAction{
   List  showAction;
   NameAction(this.showAction);

}

reducer like this

NameState reducer(NameState state, dynamic action) {

 if (action is NameAction) {
  return NameState(
    name: []..addAll(action.showAction)
  );
}

 return state;

}

and initial state is defined like this
initialState: new NameState(title: 'this is title', name: []), middleware: [thunkMiddleware]);

Here is the main problem,

you can see I have given a static string to title variable. It works fine and visible in all pages.

But as soon as reducer is called this title gets a value of null. I don't want to pass any value to title. It should be as it is with it's own value.
I was updating only the name list.

In javascript state management, we can update any variable we want without affecting other variables in the state. How can I do it in flutter redux?

Thank you.

Body:
You need to pass all the variables of the current state when returning a new state.

NameState reducer(NameState state, dynamic action) {
  if (action is NameAction) {
    return NameState(
      name: []..addAll(action.showAction),
      title: state.title,
    );
  }

  return state;
}