问:
Mongorestore is not working Error Image not fount
When I am restoring mongo data from a specific position, then it is giving an error image not found.</p>

```<code> ✘ ankitrajpoot@Ankits-MacBook-Pro-2  ~  mongorestore --db z2pNew /Downloads/z2p/
dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
  Referenced from: /usr/local/bin/mongorestore
  Reason: image not found
[1]    17642 abort      mongorestore --db z2pNew /Downloads/z2p/
</code>```

答:
First Switch your openssl

```<code>brew switch openssl 1.0.2q
</code>```

Then

```<code>mongorestore --db z2pNew /Downloads/z2p/
</code>```

Body:
When I am restoring mongo data from a specific position, then it is giving an error image not found.

 ✘ ankitrajpoot@Ankits-MacBook-Pro-2  ~  mongorestore --db z2pNew /Downloads/z2p/
dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib
  Referenced from: /usr/local/bin/mongorestore
  Reason: image not found
[1]    17642 abort      mongorestore --db z2pNew /Downloads/z2p/

Body:
First Switch your openssl

brew switch openssl 1.0.2q

Then

mongorestore --db z2pNew /Downloads/z2p/


来源: stackexchange

问:
pop record from ActiveRecord without deleting in database Rails 5.2
In rails 3.2 pop helps in removing the record from ActiveRecord.

```<code>rec = User.find(1).histories
rec.pop => remove last history and output class will be in ActiveRecord
</code>```

In Rails 5.2, same pop is not working.

Looking for same ActiveRecord class as output.

Also, the record should not be removed in the database.

答:
```<code>rec = User.find(1).histories.to_a.pop
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In rails 3.2 pop helps in removing the record from ActiveRecord.

rec = User.find(1).histories
rec.pop => remove last history and output class will be in ActiveRecord

In Rails 5.2, same pop is not working.

Looking for same ActiveRecord class as output.

Also, the record should not be removed in the database.

Body: rec = User.find(1).histories.to_a.pop


问:
Create dynamic PDF for users and send with email in nodes
I have list of users. When I click submit detail then
I want to create PDF file dynamically according to users detail and send with email to all users in nodejs.</p>

答:
If you want to create a PDF dynamically i would suggest you to use pdf-creator-node

and for sending mails i would suggest you to use nodemailer

 you can use this repo.


问:
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same
This:

```<code>device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

for data in dataloader:
    inputs, labels = data
    outputs = model(inputs)
</code>```

Gives the error:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

答:
First check cuda is available or not:

```<code>  if torch.cuda.is_available():
      device = 'cuda'
  else:
      device = 'cpu'
</code>```

In case you want to load some model do this:

```<code>  checkpoint = torch.load('./generator_release.pth', map_location=device)
  G = Generator().to(device)
</code>```

Now you probably get this error:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

It is needed to convert the type of input data from torch.tensor to torch.cuda.tensor by :

```<code>if torch.cuda.is_available():
  data = data.cuda()
result = G(data)
</code>```

and then convert the result from torch.cuda.tensor to torch.tensor:

```<code>if torch.cuda.is_available():
    result = result.cpu()
</code>```

Body:
This:

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

for data in dataloader:
    inputs, labels = data
    outputs = model(inputs)

Gives the error:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

Body:
First check cuda is available or not:

  if torch.cuda.is_available():
      device = 'cuda'
  else:
      device = 'cpu'

In case you want to load some model do this:

  checkpoint = torch.load('./generator_release.pth', map_location=device)
  G = Generator().to(device)

Now you probably get this error:

RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

It is needed to convert the type of input data from torch.tensor to torch.cuda.tensor by :

if torch.cuda.is_available():
  data = data.cuda()
result = G(data)

and then convert the result from torch.cuda.tensor to torch.tensor:

if torch.cuda.is_available():
    result = result.cpu()


问:
Swift 2D Array Performance
I am working on creating an iOS version of an Android app I created.  It involves a lot of two-dimensional array access and assignment, and it worked very quickly on Java.  However, when I converted to Swift, I noticed a very significant slowdown.  After some research on two dimensional Swift arrays, I thought the problem might be coming from the 2D arrays, so I decided to create and time a simple program to test 2D array performance.  I compared the execution times of a 2D and 1D array, and there was a significant difference.  Below is the program I used to test performance:

```<code>import Foundation

var numberOfItems = 1000
var myArray1 = [[Double]](repeating: [Double](repeating: 0.0, count: numberOfItems), count: numberOfItems)
var myArray2 = [[Double]](repeating: [Double](repeating: 0.0, count: numberOfItems), count: numberOfItems)
var myArray3 = [Double](repeating: 0.0, count: numberOfItems * numberOfItems)
var myArray4 = [Double](repeating: 0.0, count: numberOfItems * numberOfItems)

// 2D array assignment
let start1 = CFAbsoluteTimeGetCurrent()
var x = 0.0
for i in 0..<numberOfItems {
    for j in 0..<numberOfItems {
        myArray1[i][j] = x
        x += 1
    }
}
let diff1 = CFAbsoluteTimeGetCurrent() - start1
print(diff1 * 1000)

// 2D array access and assignment
let start2 = CFAbsoluteTimeGetCurrent()
for i in 0..<numberOfItems {
    for j in 0..<numberOfItems {
        myArray2[i][j] = myArray1[i][j]
    }
}
let diff2 = CFAbsoluteTimeGetCurrent() - start2
print(diff2 * 1000)

// 1D array assignment
var y = 0.0
let start3 = CFAbsoluteTimeGetCurrent()
for i in 0..<(numberOfItems * numberOfItems) {
    myArray3[i] = y
    y += 1
}
let diff3 = CFAbsoluteTimeGetCurrent() - start3
print(diff3 * 1000)

// 1D array access and assignment
let start4 = CFAbsoluteTimeGetCurrent()
for i in 0..<(numberOfItems * numberOfItems) {
    myArray4[i] = myArray3[i]
}
let diff4 = CFAbsoluteTimeGetCurrent() - start4
print(diff4 * 1000)
</code>```

I ran it on the command line using the -Ounchecked option.  I got the following output (in ms, some variation but usually pretty close):

```<code>6.0759782791137695
24.2689847946167
2.4139881134033203
1.5819072723388672
</code>```

Clearly there is a considerable performance difference between the 2D and 1D array implementations, especially when both accessing and assigning.

Is there a way to create a more efficient 2D array in Swift?  Performance is important for me in this instance, so is it better to use a 1D array and do some math for indexing?

答:
If you really want to stick to a 2D array then you can use unsafe buffer pointers for faster access. However, 1D arrays are still going to be more efficient. Give this a shot.</p>

```<code>    // 2D array assignment
    myArray1.withUnsafeMutableBufferPointer { outer1 -> Void in
        for i in 0..<numberOfItems {
            outer1[i].withUnsafeMutableBufferPointer { inner1 -> Void in
                for j in 0..<numberOfItems {
                    inner1[j] = x
                    x += 1
                }
            }
        }
    }

    // 2D array access and assignment
    myArray1.withUnsafeMutableBufferPointer { outer1 -> Void in
        myArray2.withUnsafeMutableBufferPointer { outer2 -> Void in
            for i in 0..<numberOfItems {
                outer1[i].withUnsafeMutableBufferPointer { inner1 -> Void in
                    outer2[i].withUnsafeMutableBufferPointer { inner2 -> Void in
                        for j in 0..<numberOfItems {
                            inner2[j] = inner1[j]
                        }
                    }
                }
            }
        }
    }
</code>```

Title: Swift 2D Array Performance

Body:
I am working on creating an iOS version of an Android app I created.  It involves a lot of two-dimensional array access and assignment, and it worked very quickly on Java.  However, when I converted to Swift, I noticed a very significant slowdown.  After some research on two dimensional Swift arrays, I thought the problem might be coming from the 2D arrays, so I decided to create and time a simple program to test 2D array performance.  I compared the execution times of a 2D and 1D array, and there was a significant difference.  Below is the program I used to test performance:

import Foundation

var numberOfItems = 1000
var myArray1 = [[Double]](repeating: [Double](repeating: 0.0, count: numberOfItems), count: numberOfItems)
var myArray2 = [[Double]](repeating: [Double](repeating: 0.0, count: numberOfItems), count: numberOfItems)
var myArray3 = [Double](repeating: 0.0, count: numberOfItems * numberOfItems)
var myArray4 = [Double](repeating: 0.0, count: numberOfItems * numberOfItems)

// 2D array assignment
let start1 = CFAbsoluteTimeGetCurrent()
var x = 0.0
for i in 0..<numberOfItems {
    for j in 0..<numberOfItems {
        myArray1[i][j] = x
        x += 1
    }
}
let diff1 = CFAbsoluteTimeGetCurrent() - start1
print(diff1 * 1000)

// 2D array access and assignment
let start2 = CFAbsoluteTimeGetCurrent()
for i in 0..<numberOfItems {
    for j in 0..<numberOfItems {
        myArray2[i][j] = myArray1[i][j]
    }
}
let diff2 = CFAbsoluteTimeGetCurrent() - start2
print(diff2 * 1000)

// 1D array assignment
var y = 0.0
let start3 = CFAbsoluteTimeGetCurrent()
for i in 0..<(numberOfItems * numberOfItems) {
    myArray3[i] = y
    y += 1
}
let diff3 = CFAbsoluteTimeGetCurrent() - start3
print(diff3 * 1000)

// 1D array access and assignment
let start4 = CFAbsoluteTimeGetCurrent()
for i in 0..<(numberOfItems * numberOfItems) {
    myArray4[i] = myArray3[i]
}
let diff4 = CFAbsoluteTimeGetCurrent() - start4
print(diff4 * 1000)

I ran it on the command line using the -Ounchecked option.  I got the following output (in ms, some variation but usually pretty close):

6.0759782791137695
24.2689847946167
2.4139881134033203
1.5819072723388672

Clearly there is a considerable performance difference between the 2D and 1D array implementations, especially when both accessing and assigning.

Is there a way to create a more efficient 2D array in Swift?  Performance is important for me in this instance, so is it better to use a 1D array and do some math for indexing?

Body:
If you really want to stick to a 2D array then you can use unsafe buffer pointers for faster access. However, 1D arrays are still going to be more efficient. Give this a shot.

    // 2D array assignment
    myArray1.withUnsafeMutableBufferPointer { outer1 -> Void in
        for i in 0..<numberOfItems {
            outer1[i].withUnsafeMutableBufferPointer { inner1 -> Void in
                for j in 0..<numberOfItems {
                    inner1[j] = x
                    x += 1
                }
            }
        }
    }

    // 2D array access and assignment
    myArray1.withUnsafeMutableBufferPointer { outer1 -> Void in
        myArray2.withUnsafeMutableBufferPointer { outer2 -> Void in
            for i in 0..<numberOfItems {
                outer1[i].withUnsafeMutableBufferPointer { inner1 -> Void in
                    outer2[i].withUnsafeMutableBufferPointer { inner2 -> Void in
                        for j in 0..<numberOfItems {
                            inner2[j] = inner1[j]
                        }
                    }
                }
            }
        }
    }


问:
Getting an error android.util.SuperNotCalledException: Activity {} did not call through to super.onCreate()
I'm making a TV that plays music and youtube videos. I get the following error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.newapp, PID: 12965
    android.util.SuperNotCalledException: Activity {com.example.newapp/com.example.newapp.YoutubeActivity} did not call through to super.onCreate()
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3081)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:209)
        at android.app.ActivityThread.main(ActivityThread.java:7021)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)
</code>```

This is my code for the youtube activity

```<code>public class YoutubeActivity extends YouTubeBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("youtube", "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youtube_main);

        setupVideoPlayer();
    }
</code>```

And this is the code (in another file) that initializes the Activity

```<code> private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                                  RowPresenter.ViewHolder rowViewHolder, Row row) {

            if (item instanceof Radio) {
                Radio radio = (Radio) item;
                Log.d(TAG, "RadioItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                intent.putExtra(DetailsActivity.RADIO, radio);

                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        DetailsActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            } else if (item instanceof Video) {
                Video video = (Video) item;
                Log.e(TAG, "VideoItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), YoutubeActivity.class);
                intent.putExtra(YoutubeActivity.VIDEO, video);
                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        YoutubeActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            }
            else if (item instanceof String) {
                if (((String) item).contains(getString(R.string.error_fragment))) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
</code>```

As you can see, if the item clicked is a radio, then it goes to another activity that plays the radio. This works perfectly. But if the item clicked is a video, it goes to the youtube player activity, which gives the exception given in the first code block.

In addition, you can see that I have the super.OnCreate() function, so I am unsure where I'm messing up.

答: Please be sure YouTubeBaseActivity has the super.onCreate() method inside the onCreate event.

Body:
I'm making a TV that plays music and youtube videos. I get the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.newapp, PID: 12965
    android.util.SuperNotCalledException: Activity {com.example.newapp/com.example.newapp.YoutubeActivity} did not call through to super.onCreate()
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3081)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3237)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:81)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1929)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:209)
        at android.app.ActivityThread.main(ActivityThread.java:7021)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)

This is my code for the youtube activity

public class YoutubeActivity extends YouTubeBaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("youtube", "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youtube_main);

        setupVideoPlayer();
    }

And this is the code (in another file) that initializes the Activity

 private final class ItemViewClickedListener implements OnItemViewClickedListener {
        @Override
        public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item,
                                  RowPresenter.ViewHolder rowViewHolder, Row row) {

            if (item instanceof Radio) {
                Radio radio = (Radio) item;
                Log.d(TAG, "RadioItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), DetailsActivity.class);
                intent.putExtra(DetailsActivity.RADIO, radio);

                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        DetailsActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            } else if (item instanceof Video) {
                Video video = (Video) item;
                Log.e(TAG, "VideoItem: " + item.toString());
                System.out.println(getActivity());
                Intent intent = new Intent(getActivity(), YoutubeActivity.class);
                intent.putExtra(YoutubeActivity.VIDEO, video);
                Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation(
                        getActivity(),
                        ((ImageCardView) itemViewHolder.view).getMainImageView(),
                        YoutubeActivity.SHARED_ELEMENT_NAME)
                        .toBundle();
                getActivity().startActivity(intent, bundle);
            }
            else if (item instanceof String) {
                if (((String) item).contains(getString(R.string.error_fragment))) {
                    Intent intent = new Intent(getActivity(), BrowseErrorActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

As you can see, if the item clicked is a radio, then it goes to another activity that plays the radio. This works perfectly. But if the item clicked is a video, it goes to the youtube player activity, which gives the exception given in the first code block.

In addition, you can see that I have the super.OnCreate() function, so I am unsure where I'm messing up.


问:
ALL possible issues of 404 NOT found laravel 6
I've been stuck in a weird problem for a couple of days. All my web application routes are working fine except one. Its has a 404 not found issue. So I checked:

My Routes list. It exists.

```<code>|        | GET|HEAD      | dashboard/profile/create                                                      | profile.create                   | App\Http\Controllers\Dashboard\ProfileController@create                                            | web
</code>```

URI in Routes list & Request URL in search box matches.
Request URL: http://localhost/CMSsk/CMS/public/dashboard/profile/create

Checked my blade Layout. No Problems.

```<code><a href="{{ route('profile.create') }}" class="nav-link"><i class="fas fa-briefcase fa-2x mr-2"></i>Add Credentials</a>
</code>```

Cheked Controller. It exists.

```<code>public function create()
    {
        $user       = Auth::user();
        return view('Dashboard.Profile.profile-create',compact('user'));
    }
</code>```

Cheked Apache2 Rewrite module (Enabled) & Override ALL.

Used PHPUnit & Chrome Browser devtools to check networks,console,Apllication Cookies,storage. Can't find any issues other than 404.

Used PHPUnit testing and XDebug,dd() to trace problem. The Code doesn't reach Controller method.

Checked ALL possible Stack Overflow issues. Did not solve the problem.

Cleared browser Cache.

Did:

```<code>php artisan route:cache
</code>```

Q: What are other possible issues that I might not have checked to solve this simple yet complicated issue?

Note: I referenced the form Page from another page which has a Social Media Sharing 3rd party Plugin Installed(AddThis). Hence I tried other form pages & other links from there and it works. So I'm confused why Only one page has issue(I thought the Plugin may have effect).

答:
Update:

I fixed the Solution but I wanted to share how I did just so that anyone who stumbles upon this scenario finds some help.So here it goes:

Solution:

I created a Route group first which had the prefix named profile. It had 19 routes. Immediately after that I Created a Resource Route which had it's name prefix. So the two Identical names had a conflict for which I was not getting the page.

How I figured out:

I almost ran out of all possible solutions. So I started Manually testing the routes just to figure out if there's a pattern developing. I know it's not the most effective way but I wanted to figure out a pattern that's why I did it. After testing the Route group prefix named profile I figured out that all routes inside this group are NOT working from where I called it. Then I tested Routes outside that group from that specific blade view and it was working. So I changed the name of the Resource Route just to make it distinct from the Route group  prefix. And it worked!

Body:
I've been stuck in a weird problem for a couple of days. All my web application routes are working fine except one. Its has a 404 not found issue. So I checked:

My Routes list. It exists.

|        | GET|HEAD      | dashboard/profile/create                                                      | profile.create                   | App\Http\Controllers\Dashboard\ProfileController@create                                            | web

URI in Routes list & Request URL in search box matches.
Request URL: http://localhost/CMSsk/CMS/public/dashboard/profile/create

Checked my blade Layout. No Problems.

Add Credentials

Cheked Controller. It exists.

public function create()
    {
        $user       = Auth::user();
        return view('Dashboard.Profile.profile-create',compact('user'));
    }

Cheked Apache2 Rewrite module (Enabled) & Override ALL.

Used PHPUnit & Chrome Browser devtools to check networks,console,Apllication Cookies,storage. Can't find any issues other than 404.

Used PHPUnit testing and XDebug,dd() to trace problem. The Code doesn't reach Controller method.

Checked ALL possible Stack Overflow issues. Did not solve the problem.

Cleared browser Cache.

Did:

php artisan route:cache

Q: What are other possible issues that I might not have checked to solve this simple yet complicated issue?

Note: I referenced the form Page from another page which has a Social Media Sharing 3rd party Plugin Installed(AddThis). Hence I tried other form pages & other links from there and it works. So I'm confused why Only one page has issue(I thought the Plugin may have effect).


问:
Issue passing an object and array as a multi-cast type into a function argument for Angular 2 (Typescript Question)
My problem is very simple. I want to pass an object (of Class CircuitBreaker) into my arguments.  I want it to be reusable, however, so I would like to also use | to pass an array of this same Class as well.

This creates syntax errors where the compiler is confused on accepting array functions (such as .some)

Property 'some' does not exist on type 'CircuitBreakerThresholdBreakdown | CircuitBreakerThresholdBreakdown[]

and/or a property of a potential object:

Property 'threshold' does not exist on type 'CircuitBreakerThresholdBreakdown | CircuitBreakerThresholdBreakdown[]

What am I missing here?

```<code>public thresholdFunction(cBreakdowns: CircuitBreaker | CircuitBreaker[]): boolean {
    if (cBreakdowns.length > 1) {
        return cBreakdowns.some(singleBreakdown => {
            return singleBreakdown.breakdown.count > singleBreakdown.threshold.maximum ||
            singleBreakdown.breakdown.count < singleBreakdown.threshold.minimum;
        });
    } else {
        return cBreakdowns.breakdown.count < cBreakdowns.threshold.minimum;
    }
}
</code>```

答:
Modify your if statement this way:

```<code>if (cBreakdowns instanceof Array) {
 // ...
} else {
 // ...
}
</code>```

Body:
My problem is very simple. I want to pass an object (of Class CircuitBreaker) into my arguments.  I want it to be reusable, however, so I would like to also use | to pass an array of this same Class as well.

This creates syntax errors where the compiler is confused on accepting array functions (such as .some)

Property 'some' does not exist on type 'CircuitBreakerThresholdBreakdown | CircuitBreakerThresholdBreakdown[]

and/or a property of a potential object:

Property 'threshold' does not exist on type 'CircuitBreakerThresholdBreakdown | CircuitBreakerThresholdBreakdown[]

What am I missing here?

public thresholdFunction(cBreakdowns: CircuitBreaker | CircuitBreaker[]): boolean {
    if (cBreakdowns.length > 1) {
        return cBreakdowns.some(singleBreakdown => {
            return singleBreakdown.breakdown.count > singleBreakdown.threshold.maximum ||
            singleBreakdown.breakdown.count < singleBreakdown.threshold.minimum;
        });
    } else {
        return cBreakdowns.breakdown.count < cBreakdowns.threshold.minimum;
    }
}

Body:
Modify your if statement this way:

if (cBreakdowns instanceof Array) {
 // ...
} else {
 // ...
}


问:
My Search Icon Disappears after Transition
I added a search icon with font awesome on my website that has a transition to the left but for some reason when I hover and the transition starts the font awesome icon disappears.
I'm having a hard time figuring this out because it works fine on my CodePen.

Please click on the link below to see the code in action on my website.

http://lonestarwebandgraphics.com/

答:
Consider adding display: flex; to search-box.

I inspected your website in firefox and added display: flex; to search-box and it works.


问:
kubectl exec does not work with kubectl proxy
I wanted to execute kubectl exec command and connect to a container, so that I can execute some commands on it.
I have set the proxy with the following command:

```<code>kubectl proxy -p=8080 --kubeconfig=/directory_path/remote-kubeconfig &
</code>```

proxy started running. I tried executing kubectl exec command:

```<code>kubectl exec -it <pod> --namespace=<namespace> -c <container> -- ls -l
</code>```

I got the following error:

```<code>error: unable to upgrade connection: <h3>Unauthorized</h3>
</code>```

Did I missed anything while executing kubectl exec command ?? Please help.

答:
By default, kubectl proxy rejects API commands matching ^/api/./pods/./exec.

All you need to do in order to "bypass" this is start kubectl proxy with the appropriate flags:

kubectl proxy --port 8080 --reject-paths "^/api/./pods/./attach"

Of course, this comes with the security risk that anyone with access to your proxy can now exec into any of the pods on the cluster.

If you actually need to do this in a production environment, I highly recommend restricting what the proxy has access to using RBAC authorization - run the proxy as a Deployment with a ServiceAccount.

For more information, see:

https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#proxy
https://kubernetes.io/docs/reference/access-authn-authz/rbac/

ContentLicense: CC BY-SA 3.0

Body:
I wanted to execute kubectl exec command and connect to a container, so that I can execute some commands on it.
I have set the proxy with the following command:

kubectl proxy -p=8080 --kubeconfig=/directory_path/remote-kubeconfig &

proxy started running. I tried executing kubectl exec command:

kubectl exec -it <pod> --namespace=<namespace> -c <container> -- ls -l

I got the following error:

error: unable to upgrade connection:
Unauthorized

Did I missed anything while executing kubectl exec command ?? Please help.


问:
Java 7 underscore in numeric literals
When we must use a _ to separate digits in a number I don't understand the following case in which I can't use it:

In positions where a string of digits is expected

(as documented in the JDK7 guide here)

Some examples?

答:
no idea, but here's the grammar, enjoy. (I don't see "string of digits" anywhere)

http://download.oracle.com/otndocs/jcp/enhancements-0.875-pr-oth-JSpec/

```<code>IntegerLiteral:
    DecimalIntegerLiteral
    HexIntegerLiteral
    OctalIntegerLiteral
    BinaryIntegerLiteral

BinaryIntegerLiteral:
    BinaryNumeral IntegerTypeSuffixopt

BinaryNumeral:
    0 b BinaryDigits
    0 B BinaryDigits

DecimalNumeral:
    0
    NonZeroDigit Digitsopt
    NonZeroDigit Underscores Digits

Underscores:
    _
    Underscores _

Digits:
    Digit
    Digit DigitsAndUnderscoresopt Digit

DigitsAndUnderscores:
    DigitOrUnderscore
    DigitsAndUnderscores DigitOrUnderscore

DigitOrUnderscore:
    Digit
    _

HexDigits:
    HexDigit
    HexDigit HexDigitsAndUnderscoresopt HexDigit

HexDigitsAndUnderscores:
    HexDigitOrUnderscore
    HexDigitsAndUnderscores HexDigitOrUnderscore

HexDigitOrUnderscore:
    HexDigit
    _

OctalNumeral:
    0 OctalDigits
    0 Underscores OctalDigits

OctalDigits:
    OctalDigit
    OctalDigit OctalDigitsAndUnderscoresopt OctalDigit

OctalDigitsAndUnderscores:
    OctalDigitOrUnderscore
    OctalDigitsAndUnderscores OctalDigitOrUnderscore

OctalDigitOrUnderscore:
    OctalDigit
    _

BinaryDigits:
    BinaryDigit
    BinaryDigit BinaryDigitsAndUnderscoresopt BinaryDigit

BinaryDigitsAndUnderscores:
    BinaryDigitOrUnderscore
    BinaryDigitsAndUnderscores BinaryDigitOrUnderscore

BinaryDigitOrUnderscore:
    BinaryDigit
    _

BinaryDigit: one of
    0 1
</code>```

Title: Java 7 underscore in numeric literals

Body:
no idea, but here's the grammar, enjoy. (I don't see "string of digits" anywhere)

http://download.oracle.com/otndocs/jcp/enhancements-0.875-pr-oth-JSpec/

IntegerLiteral:
    DecimalIntegerLiteral
    HexIntegerLiteral
    OctalIntegerLiteral
    BinaryIntegerLiteral

BinaryIntegerLiteral:
    BinaryNumeral IntegerTypeSuffixopt

BinaryNumeral:
    0 b BinaryDigits
    0 B BinaryDigits

DecimalNumeral:
    0
    NonZeroDigit Digitsopt
    NonZeroDigit Underscores Digits

Underscores:
    _
    Underscores _

Digits:
    Digit
    Digit DigitsAndUnderscoresopt Digit

DigitsAndUnderscores:
    DigitOrUnderscore
    DigitsAndUnderscores DigitOrUnderscore

DigitOrUnderscore:
    Digit
    _

HexDigits:
    HexDigit
    HexDigit HexDigitsAndUnderscoresopt HexDigit

HexDigitsAndUnderscores:
    HexDigitOrUnderscore
    HexDigitsAndUnderscores HexDigitOrUnderscore

HexDigitOrUnderscore:
    HexDigit
    _

OctalNumeral:
    0 OctalDigits
    0 Underscores OctalDigits

OctalDigits:
    OctalDigit
    OctalDigit OctalDigitsAndUnderscoresopt OctalDigit

OctalDigitsAndUnderscores:
    OctalDigitOrUnderscore
    OctalDigitsAndUnderscores OctalDigitOrUnderscore

OctalDigitOrUnderscore:
    OctalDigit
    _

BinaryDigits:
    BinaryDigit
    BinaryDigit BinaryDigitsAndUnderscoresopt BinaryDigit

BinaryDigitsAndUnderscores:
    BinaryDigitOrUnderscore
    BinaryDigitsAndUnderscores BinaryDigitOrUnderscore

BinaryDigitOrUnderscore:
    BinaryDigit
    _

BinaryDigit: one of
    0 1


问:
logd shortcut doesn't work in Intellij with Kotlin
Logging Java in Intellij is easy with shortcuts such as 'logt', 'logd', 'loge'... and so on. But I moved to Kotlin, I noticed that those shortcuts doesn't work anymore. I don't know if it has something to do with my configuration, but if not, how can I fix this?</p>

答: In Android Studio 4.0 there's new AndroidLogKotlin block. You can implement @LeoDroidcoder's solution there.


问:
How would I parse multiple variables through a dynamic link in html?
This may be a relatively simple answer, although I can't seem to find any solution online.

I've been parsing a variable through a dynamic link by using the following line:
a href="play.php?inputType=album"

inputType being the variable I want to parse. Although I also want to parse another variable through the hyperlink although I'm not sure if or how I can add it to the url.

答:
Multiple parameters can be passed through the URL by separating them with multiple "&". Here is an example of the same:</p>

```<code><a href="play.php?inputType=album&name=test">
</code>```

Body:
Multiple parameters can be passed through the URL by separating them with multiple "&". Here is an example of the same:

<a href="play.php?inputType=album&name=test">


问:
Conditionally launch Spring Cloud Task on a specific node of Kubernetes cluster
I am building a data pipeline for batch processing. And I find that Spring Cloud Data Flow is a quite attractive framework to use. Without much knowledge in SCDF and Kubernetes, I am not sure whether it is possible to conditionally launch a Spring Cloud Task on a specific machine.

Suppose I have two physical servers that are for running the batch process (Server A and Server B). By default, I would like  my Spring cloud task to be launched on Server A. If the Server A is shut down, the task should be deployed on server B. Can Kubernetes / SCDF handle this kind of mechanism? I am wondering whether the nodeselector is the thing that I should look into.

答:
Yes, you can pass deployment.nodeSelector as a deployment property when launching the task.

The deployment.nodeSelector is a Kubernetes deployment property and hence, you need to pass something like this:

```<code>task launch mytask --properties "deployer.<taskAppName>.kubernetes.deployment.nodeSelector=foo1:bar1,foo2:bar2"
</code>```

You can check the list of supported Kubernetes deployer properties here

Body:
Yes, you can pass deployment.nodeSelector as a deployment property when launching the task.

The deployment.nodeSelector is a Kubernetes deployment property and hence, you need to pass something like this:

task launch mytask --properties "deployer.<taskAppName>.kubernetes.deployment.nodeSelector=foo1:bar1,foo2:bar2"

You can check the list of supported Kubernetes deployer properties here


问:
error while putting correct git commit commands
Can you outline why I am receiving this message in git commit despite correct codes. I have tried all the alternatives and even restarting it again but no positive responses.
Here's the error https://i.stack.imgur.com/cr9zd.png</p>

答:
If there are un-staged files, you should put

git commit -am “first commit”

You need to fist add the un-staged files which -a in the command does. m is just for the commit message.

If all the modified files are staged, you can give this command

git commit -m “first commit” //This will do. Notice the space between commit and -m (m is for commit message )


问:
Deploy Qt ODBC application
My application uses Qt SQL this way

```<code>QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};DBQ="+QDir::currentPath()+"/database.mdb");
</code>```

and all the rest is done using QSqlRelationalTableModel.

Now that deployment stage has come, the application works perfectly on the system where Qt (4.6.3) is installed , but on another clean system, there is this error while loading the database

```<code>"Driver not loaded"
</code>```

I know this has something to do with copying the ODBC plugins... but simply copying qsqlodbc4.dll to the app dir and

```<code>qApp->addLibraryPath(QDir::currentPath());
</code>```

does not work!!

What is the solution to this?

Note: The app is not linked to the driver DLL, it uses Qt plugin mechanism.

答:
Create this directory structure same as it was on pc having qt installation.

your.app.dir/plugins/your.plugin.folder (i.e your.plugin.folder is sqldrivers)

Copy your plugin under your.app.dir/plugins/your.plugin_folder

Then add this code

```<code>qApp->addLibraryPath( qApp->applicationDirPath() + "/plugins");
</code>```

I hope this helps.

Title: Deploy Qt ODBC application

Body:
My application uses Qt SQL this way

QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={Microsoft Access Driver (*.mdb)};DBQ="+QDir::currentPath()+"/database.mdb");

and all the rest is done using QSqlRelationalTableModel.

Now that deployment stage has come, the application works perfectly on the system where Qt (4.6.3) is installed , but on another clean system, there is this error while loading the database

"Driver not loaded"

I know this has something to do with copying the ODBC plugins... but simply copying qsqlodbc4.dll to the app dir and

qApp->addLibraryPath(QDir::currentPath());

does not work!!

What is the solution to this?

Note: The app is not linked to the driver DLL, it uses Qt plugin mechanism.

Body:
Create this directory structure same as it was on pc having qt installation.

your.app.dir/plugins/your.plugin.folder (i.e your.plugin.folder is sqldrivers)

Copy your plugin under your.app.dir/plugins/your.plugin_folder

Then add this code

qApp->addLibraryPath( qApp->applicationDirPath() + "/plugins");

I hope this helps.


问:
Python not writing whole output into file
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

```<code>with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)
</code>```

Content of writing.txt

```<code>/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&
</code>```

Output of internallinks.txt

```<code>www.icom.org.cn/icom/faculty/viewer/?id=470&
</code>```

Output of command print (combined) before with is closed

```<code>PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>
</code>```

答:
When dealing with input files, I recommend you assume the source is extremely large and code accordingly.  For example, dealing with it line by line and not reading the entire file into memory:

```<code>with open(r"C:\Users\xingj\Desktop\writing.txt") as input_file:
    with open(r"C:\Users\xingj\internallinks.txt", 'w') as output_file:
        for link in input_file:
            output_file.write('www.icom.org.cn' + link)
</code>```

You can combine both open() statements into one with statement, but I see no advantage into doing so.  If there is one, please comment!

Body:
I am trying to join every_line in a txt file with a header text. But after successfully joining
up the lines. I cannot seem to write the file correctly as it will only write the last joined line into the internallinks.txt. How can I make it to write the whole output of combined into the file?

Any help would be appreciated, thank you very much!

Python code

with open(r"C:\Users\xingj\Desktop\writing.txt") as f:
    internallink = ("www.icom.org.cn")
    for every_line in f:
        combined = (internallink + every_line.strip())
        out_str = "".join(combined)

with open("C:\\Users\\xingj\\internallinks.txt",'w') as b:
    b.write(out_str)

Content of writing.txt

/icom/faculty/viewer/?id=1122
/icom/faculty/viewer/?id=1125
/icom/faculty/viewer/?id=586&
/icom/faculty/viewer/?id=1126
/icom/faculty/viewer/?id=470&

Output of internallinks.txt

www.icom.org.cn/icom/faculty/viewer/?id=470&

Output of command print (combined) before with is closed

PS C:\Users\xingj> & python c:/Users/xingj/testingagain.py
www.icom.org.cn/icom/faculty/viewer/?id=1122
www.icom.org.cn/icom/faculty/viewer/?id=1125
www.icom.org.cn/icom/faculty/viewer/?id=586&
www.icom.org.cn/icom/faculty/viewer/?id=1126
www.icom.org.cn/icom/faculty/viewer/?id=470&
PS C:\Users\xingj>

Body:
When dealing with input files, I recommend you assume the source is extremely large and code accordingly.  For example, dealing with it line by line and not reading the entire file into memory:

with open(r"C:\Users\xingj\Desktop\writing.txt") as input_file:
    with open(r"C:\Users\xingj\internallinks.txt", 'w') as output_file:
        for link in input_file:
            output_file.write('www.icom.org.cn' + link)

You can combine both open() statements into one with statement, but I see no advantage into doing so.  If there is one, please comment!


问:
Creating nested array from flat array - Data Structure
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

```<code>const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];
</code>```

Output:

```<code>const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];
</code>```

The best approach would be something recursive.
Any suggestions for this algorithm?

答:
was thinking along the same terms as Aadith but came up from an iterative approach. I think the most performant way to do it is to use a linked list structure and then flatten it though.

```<code>const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];

let newList = [];
list.forEach((location) =>
{
  console.log('Handling location ',location);
  if(location.path.split('.').length==1)
  {
    location.children = [];
    newList.push(location);
  }
  else
  {
    newList.forEach(loc => {
      console.log('checking out: ',loc);
      let found = false;
      while(!found)
      {
        console.log(loc.path,'==',location.path.substring(0, location.path.lastIndexOf('.')));
        found = loc.path == location.path.substring(0, location.path.lastIndexOf('.'));
        if(!found)
        {
          for(let i=0;i<loc.children.length;i++)
          {
            let aloc = loc.children[i];

            found = aloc.path == location.path.substring(0, location.path.lastIndexOf('.'));
            if(found)
            {
              console.log('found it...', loc);
              location.children = [];
              aloc.children.push(location);
              break;
            }
          }

        }
        else
        {
          console.log('found it...', loc);
          location.children = [];
          loc.children.push(location);
        }
      }
    } );
  }
});

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

This was my quick and dirty way of how to go about it

Body:
I need to create a nested array using the path as reference for the children.
E.g: 4.1 is a child of 4, 4.1.1 is a child of 4.1, 4.2 is a child of 4...
I have this flat array, with all the data and paths. How would be the best approach to create a nested array where the children are nested to its parent based on its path.

Input:

const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];

Output:

const  list = [
  {
    location: 1,
    path: '4',
        children: [
            {
            location: 2,
            path: '4.1',
            children: [
                {
                    location: 3,
                    path: '4.1.1'
                },
                {
                    location: 4,
                    path: '4.1.2'
                },
            ]
        },
            {
                location: 5,
                path: '4.2',
                children: [
                    {
                        location: 6,
                        path: '4.2.1'
                    },
                ]
            },
            {
                location: 7,
                path: '4.3',
                children: [
                    {
                        location: 8,
                        path: '4.3.1'
                    }
                ]
            },
        ]
  },
];

The best approach would be something recursive.
Any suggestions for this algorithm?

Body:
was thinking along the same terms as Aadith but came up from an iterative approach. I think the most performant way to do it is to use a linked list structure and then flatten it though.

const list = [
  {
    location: 1,
    path: '4'
  },
  {
    location: 2,
    path: '4.1'
  },
  {
    location: 3,
    path: '4.1.1'
  },
  {
    location: 4,
    path: '4.1.2'
  },
  {
    location: 5,
    path: '4.2'
  },
  {
    location: 6,
    path: '4.2.1'
  },
  {
    location: 7,
    path: '4.3'
  },
  {
    location: 8,
    path: '4.3.1'
  }
];

let newList = [];
list.forEach((location) =>
{
  console.log('Handling location ',location);
  if(location.path.split('.').length==1)
  {
    location.children = [];
    newList.push(location);
  }
  else
  {
    newList.forEach(loc => {
      console.log('checking out: ',loc);
      let found = false;
      while(!found)
      {
        console.log(loc.path,'==',location.path.substring(0, location.path.lastIndexOf('.')));
        found = loc.path == location.path.substring(0, location.path.lastIndexOf('.'));
        if(!found)
        {
          for(let i=0;i<loc.children.length;i++)
          {
            let aloc = loc.children[i];

            found = aloc.path == location.path.substring(0, location.path.lastIndexOf('.'));
            if(found)
            {
              console.log('found it...', loc);
              location.children = [];
              aloc.children.push(location);
              break;
            }
          }

        }
        else
        {
          console.log('found it...', loc);
          location.children = [];
          loc.children.push(location);
        }
      }
    } );
  }
});

console.log(newList);

This was my quick and dirty way of how to go about it


答:
You can use spread operator in paramter (...).

When calling the function if you want to pass object then use thresholdFunction(obj);.

If you want to pass array use thresholdFunction(...array);. And update your code like below.

You can also pass multiple objects with thresholdFunction(obj1, obj2, obj3);

```<code>public thresholdFunction(...cBreakdowns: CircuitBreaker[]): boolean {
    return cBreakdowns.some(singleBreakdown => {
        return singleBreakdown.breakdown.count > singleBreakdown.threshold.maximum ||
            singleBreakdown.breakdown.count < singleBreakdown.threshold.minimum;
    });
}
</code>```

Title: Issue passing an object and array as a multi-cast type into a function argument for Angular 2 (Typescript Question)

Body:
You can use spread operator in paramter (...).

When calling the function if you want to pass object then use thresholdFunction(obj);.

If you want to pass array use thresholdFunction(...array);. And update your code like below.

You can also pass multiple objects with thresholdFunction(obj1, obj2, obj3);

public thresholdFunction(...cBreakdowns: CircuitBreaker[]): boolean {
    return cBreakdowns.some(singleBreakdown => {
        return singleBreakdown.breakdown.count > singleBreakdown.threshold.maximum ||
            singleBreakdown.breakdown.count < singleBreakdown.threshold.minimum;
    });
}


问:
Flutter - How to change the Color class' value that placed inside a custom widget?
I'd like to create a widget that I'll use it a lot of times, so I don't have to create it manully.

here's what I've built:

```<code>    Widget keyWidget(String keyNumber, String keyName) {
          return Container(
              width: 100.0,
              height: 50.0,
              color: Colors.red, //How I change the color's value? (Colors.{this_one})?
              child: FlatButton(
                onPressed: () {
                  final player = AudioCache();
                  player.play('key$keyNumber.mp3');
                },
                child: Text('$keyName'),
              ),
            );
}
</code>```

How do I change the color's value (color: Colors.{this_one},) so I could set it in the keyWidget properties?

答:
You can pass your Color as argument in your keyWidget() method

Try this way

```<code> Widget keyWidget(String keyNumber, String keyName,Color mColor) {
          return Container(
              width: 100.0,
              height: 50.0,
              color: mColor, //How I change the color's value? (Colors.{this_one})?
              child: FlatButton(
                onPressed: () {
                  final player = AudioCache();
                  player.play('key$keyNumber.mp3');
                },
                child: Text('$keyName'),
              ),
            );
}
</code>```

Now you can call this method like this.

```<code>keyWidget('keyNumber','keyName',Colors.red);
keyWidget('keyNumber','keyName',Colors.pink);
keyWidget('keyNumber','keyName',Color(0xffACACAC));
</code>```

You can also make Color parameter optional

SAMPLE CODE

```<code>Widget keyWidget(String keyNumber, String keyName,{ mColor=Colors.red}) {
    return Container(
      width: 100.0,
      height: 50.0,
      color: mColor, //How I change the color's value? (Colors.{this_one})?
      child: FlatButton(
        onPressed: () {
          final player = AudioCache();
          player.play('key$keyNumber.mp3');
        },
        child: Text('$keyName'),
      ),
    );
  }
</code>```

Now you can call this method like this.

```<code>keyWidget('keyNumber', 'keyName');
keyWidget('keyNumber', 'keyName',mColor:  Colors.accents);
</code>```

Body:
I'd like to create a widget that I'll use it a lot of times, so I don't have to create it manully.

here's what I've built:

    Widget keyWidget(String keyNumber, String keyName) {
          return Container(
              width: 100.0,
              height: 50.0,
              color: Colors.red, //How I change the color's value? (Colors.{this_one})?
              child: FlatButton(
                onPressed: () {
                  final player = AudioCache();
                  player.play('key$keyNumber.mp3');
                },
                child: Text('$keyName'),
              ),
            );
}

How do I change the color's value (color: Colors.{this_one},) so I could set it in the keyWidget properties?

Body:
You can pass your Color as argument in your keyWidget() method

Try this way

 Widget keyWidget(String keyNumber, String keyName,Color mColor) {
          return Container(
              width: 100.0,
              height: 50.0,
              color: mColor, //How I change the color's value? (Colors.{this_one})?
              child: FlatButton(
                onPressed: () {
                  final player = AudioCache();
                  player.play('key$keyNumber.mp3');
                },
                child: Text('$keyName'),
              ),
            );
}

Now you can call this method like this.

keyWidget('keyNumber','keyName',Colors.red);
keyWidget('keyNumber','keyName',Colors.pink);
keyWidget('keyNumber','keyName',Color(0xffACACAC));

You can also make Color parameter optional

SAMPLE CODE

Widget keyWidget(String keyNumber, String keyName,{ mColor=Colors.red}) {
    return Container(
      width: 100.0,
      height: 50.0,
      color: mColor, //How I change the color's value? (Colors.{this_one})?
      child: FlatButton(
        onPressed: () {
          final player = AudioCache();
          player.play('key$keyNumber.mp3');
        },
        child: Text('$keyName'),
      ),
    );
  }

Now you can call this method like this.

keyWidget('keyNumber', 'keyName');
keyWidget('keyNumber', 'keyName',mColor:  Colors.accents);


问:
StaleElementReferenceException error after button press with selenium + python
I am working on a web scraping project using selenium. In this project, I am trying to scrape the links of products from multiple pages in amazon. For example, when I type laptop in the search bar in Amazon, multiple products are populated, and there exist multiple pages. I want to scrape all the product links from all pages and store them in a list.

This is my code so far

```<code>def scrape_pages_selenium(product, total_pages):

    driver = webdriver.Chrome('./chromedriver')

    url = f'https://www.amazon.com/s?k={product}&page=1&ref=nb_sb_noss'

    driver.get(url)
    links = driver.find_elements_by_class_name("a-size-mini")

    product_links = []
    for page in range(1, total_pages+1):

        for link in links:
            product_links.append(link.find_element_by_css_selector('a').get_attribute('href'))

        print(len(product_links))

        try:
            next_page_button = driver.find_element_by_class_name("a-last")
            next_page_button.click()
        except:
            continue

    return product_links

product_links = scrape_pages_selenium('laptop', 7)
</code>```

This code works correctly on the first page. The next_page_button is used to go to the next page. But when the code tries to scrape the links from the second page, I get the following error

```<code>StaleElementReferenceException            Traceback (most recent call last)
<ipython-input-50-09cc65b63734> in <module>
     23     return product_links
     24
---> 25 product_links = scrape_pages_selenium('gatorade', 7)
     26

<ipython-input-50-09cc65b63734> in scrape_pages_selenium(product, total_pages)
     12
     13         for link in links:
---> 14             product_links.append(link.find_element_by_css_selector('a').get_attribute('href'))
     15
     16         print(len(product_links))

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in find_element_by_css_selector(self, css_selector)
    428             element = element.find_element_by_css_selector('#foo')
    429         """
--> 430         return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
    431
    432     def find_elements_by_css_selector(self, css_selector):

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in find_element(self, by, value)
    657
    658         return self._execute(Command.FIND_CHILD_ELEMENT,
--> 659                              {"using": by, "value": value})['value']
    660
    661     def find_elements(self, by=By.ID, value=None):

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in _execute(self, command, params)
    631             params = {}
    632         params['id'] = self._id
--> 633         return self._parent.execute(command, params)
    634
    635     def find_element(self, by=By.ID, value=None):

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    319         response = self.command_executor.execute(driver_command, params)
    320         if response:
--> 321             self.error_handler.check_response(response)
    322             response['value'] = self._unwrap_value(
    323                 response.get('value', None))

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    240                 alert_text = value['alert'].get('text')
    241             raise exception_class(message, screen, stacktrace, alert_text)
--> 242         raise exception_class(message, screen, stacktrace)
    243
    244     def _value_or_default(self, obj, key, default):

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=83.0.4103.61)
</code>```

I am not sure where I am going wrong.

答:
Move links = driver.find_elements_by_class_name("a-size-mini") inside your loop. This is because when you move to the next page, the links collection is no more valid

find_elements_by_class_name is giving you a snapshot of what exists and the current page, when you move to the next page, that snapshot of dom elements is no more valid

Body:
I am working on a web scraping project using selenium. In this project, I am trying to scrape the links of products from multiple pages in amazon. For example, when I type laptop in the search bar in Amazon, multiple products are populated, and there exist multiple pages. I want to scrape all the product links from all pages and store them in a list.

This is my code so far

def scrape_pages_selenium(product, total_pages):

    driver = webdriver.Chrome('./chromedriver')

    url = f'https://www.amazon.com/s?k={product}&page=1&ref=nb_sb_noss'

    driver.get(url)
    links = driver.find_elements_by_class_name("a-size-mini")

    product_links = []
    for page in range(1, total_pages+1):

        for link in links:
            product_links.append(link.find_element_by_css_selector('a').get_attribute('href'))

        print(len(product_links))

        try:
            next_page_button = driver.find_element_by_class_name("a-last")
            next_page_button.click()
        except:
            continue

    return product_links

product_links = scrape_pages_selenium('laptop', 7)

This code works correctly on the first page. The next_page_button is used to go to the next page. But when the code tries to scrape the links from the second page, I get the following error

StaleElementReferenceException            Traceback (most recent call last)
<ipython-input-50-09cc65b63734> in <module>
     23     return product_links
     24
---> 25 product_links = scrape_pages_selenium('gatorade', 7)
     26

<ipython-input-50-09cc65b63734> in scrape_pages_selenium(product, total_pages)
     12
     13         for link in links:
---> 14             product_links.append(link.find_element_by_css_selector('a').get_attribute('href'))
     15
     16         print(len(product_links))

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in find_element_by_css_selector(self, css_selector)
    428             element = element.find_element_by_css_selector('#foo')
    429         """
--> 430         return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
    431
    432     def find_elements_by_css_selector(self, css_selector):

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in find_element(self, by, value)
    657
    658         return self._execute(Command.FIND_CHILD_ELEMENT,
--> 659                              {"using": by, "value": value})['value']
    660
    661     def find_elements(self, by=By.ID, value=None):

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webelement.py in _execute(self, command, params)
    631             params = {}
    632         params['id'] = self._id
--> 633         return self._parent.execute(command, params)
    634
    635     def find_element(self, by=By.ID, value=None):

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    319         response = self.command_executor.execute(driver_command, params)
    320         if response:
--> 321             self.error_handler.check_response(response)
    322             response['value'] = self._unwrap_value(
    323                 response.get('value', None))

~/anaconda3/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    240                 alert_text = value['alert'].get('text')
    241             raise exception_class(message, screen, stacktrace, alert_text)
--> 242         raise exception_class(message, screen, stacktrace)
    243
    244     def _value_or_default(self, obj, key, default):

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=83.0.4103.61)

I am not sure where I am going wrong.


问:
Certificates for authentication and signing
I have a client server scenario.

I have both thick client and a thin client (browser) which communicates with my server.

My thick client  uses X-509 system certificate for client certificate authentication scenario and communicates with the server

Also this certificate is used for used to generate signed URL (with expiration time) for my thin client to communicate with my server which is used for integrity and authorization purpose. I also have a token based approach for authentication purpose in this case.

Now i want to complete move my authentication mechanism to OAuth based flow using client credentials or auth code based.

I understand that authentication and authorization can be moved to OAuth based communication. But how do i move my signing (digital signature) based use case to OAuth from certificate based ?

I don't think there is any other way than to use certificate based PKI mechanism for digital signing. Can the private and public keys be distributed other than the certificates ?

Best Regards,

Saurav

答:
Can the private and public keys be distributed other than the certificates ?

You may generate key pair using openssl (command line - openssl.exe) or any cryptographic library or CSP of crypto device.  Instead of distributing it, you may have a piece of software which user may use at his end to generate public key and private key and share public key if required and store private key securely.  But question remains how user would store private key securely and there comes certificate storage formats like PFX which is password protected (encrypted using password you provide) or storing private key in smartcard or usb token which are cryptographic devices.  You may program these devices to generate our own keys and not necessarily store certificate issued by CA.

For browser based access to user's private key, you may need to use browser extension.
Refer to this SO answer for accessing user's keys from browser for authentication.


问:
Make a list with non-decreasing order elements of a list in Python
I have a list a = [2,2,1,3,4,1] .
I want to make a new list c with the non-decreasing elements lists of list a.
That means my expected form is -

```<code>c = [[2,2],[1,3,4],[1]]
</code>```

Here is my code:

```<code>>>> c = []
>>> for x in a:
...     xx = a[0]
...     if xx > x:
...             b = a[:x]
...             c.append(b)
...             a = a[x:]
</code>```

but my output is:

```<code>>>> c
[[2], [2]]
</code>```

How can i make a list with all non-decreasing part of list a?

答:
You can initialise the first entry of c with [a[0]] and then either append the current value from a to the end of the current list in c if it is >= the previous value, otherwise append a new list containing that value to c:

```<code>a = [2,2,1,3,4,1]
c = [[a[0]]]
last = a[0]
for x in a[1:]:
    if x >= last:
        c[-1].append(x)
    else:
        c.append([x])
    last = x

print(c)
</code>```

Output:

```<code>[[2, 2], [1, 3, 4], [1]]
</code>```

Body:
I have a list a = [2,2,1,3,4,1] .
I want to make a new list c with the non-decreasing elements lists of list a.
That means my expected form is -

c = [[2,2],[1,3,4],[1]]

Here is my code:

>>> c = []
>>> for x in a:
...     xx = a[0]
...     if xx > x:
...             b = a[:x]
...             c.append(b)
...             a = a[x:]

but my output is:

>>> c
[[2], [2]]

How can i make a list with all non-decreasing part of list a?

Body:
You can initialise the first entry of c with [a[0]] and then either append the current value from a to the end of the current list in c if it is >= the previous value, otherwise append a new list containing that value to c:

a = [2,2,1,3,4,1]
c = [[a[0]]]
last = a[0]
for x in a[1:]:
    if x >= last:
        c[-1].append(x)
    else:
        c.append([x])
    last = x

print(c)

Output:

[[2, 2], [1, 3, 4], [1]]


问:
How to pass ref to children of children using array of refs React?
I'm trying to pass multiple times refs to children of children but it is not working. I have a functional component called AvatarBuilder that uses the Avatars component. This component renders a list of Avatar components. The idea is to have in AvatarBuilder references to each of the Avatar component.

Here is the code snippet summarized:

const AvatarBuilder = props => {
    ...
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = URLS.map(item => ({ ref: React.createRef() }));
    return (
        <>
            <Avatars
                ref={refs}
                urlList={URLS}
            />
        </>
    );

const Avatars = React.forwardRef((props, ref) => {
    let urlList = props.urlList.map((url, index) => {
        return (
            <Avatar
                ref={ref[index].ref}
                url={url}
            />
        )
    })
    return (

            {urlList}

    )
});

const Avatar = React.forwardRef((props, ref) => {
    return (

    )
});

```

<p>I get the following warning and the refs array is not updated when all the components are mounted.</p>

```index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef`.
    in h (at Avatar.js:11)
    in li (at Avatar.js:10)
    in ForwardRef (at Avatars.js:10)
    in ul (at Avatars.js:24)
    in ForwardRef (at AvatarBuilder.js:189)
    in AvatarBuilder (at App.js:19)
    in div (at App.js:14)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)
```

Any idea how should this be fixed? Thanks!

答:
Try this one.</p>

```<code>const AvatarBuilder = props => {
    ...
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = URLS.map(item => React.createRef());
    return (
        <>
            <Avatars
                refs={refs}
                urlList={URLS}
            />
        </>
    );

// you don't need to make it with `fowardRef()`
const Avatars = (props) => {
    const {refs} = props;
    let urlList = props.urlList.map((url, index) => {
        console.log(url, index, typeof (index), ref);
        return (
            <Avatar
                ref={refs[index]}
                url={url}
            />
        )
    })
    return (
        <ul className="Avatars" >
            {urlList}
        </ul>
    )
};

const Avatar = React.forwardRef((props, ref) => {
    return (
        <li className="Avatar">
            <img
                src={props.url}
                ref={ref}
            />
        </li>
    )
});
</code>```

Body:
I'm trying to pass multiple times refs to children of children but it is not working. I have a functional component called AvatarBuilder that uses the Avatars component. This component renders a list of Avatar components. The idea is to have in AvatarBuilder references to each of the Avatar component.

Here is the code snippet summarized:

const AvatarBuilder = props => {
    ...
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = URLS.map(item => ({ ref: React.createRef() }));
    return (
        <>
            <Avatars
                ref={refs}
                urlList={URLS}
            />
        </>
    );

const Avatars = React.forwardRef((props, ref) => {
    let urlList = props.urlList.map((url, index) => {
        return (
            <Avatar
                ref={ref[index].ref}
                url={url}
            />
        )
    })
    return (

            {urlList}

    )
});

const Avatar = React.forwardRef((props, ref) => {
    return (

    )
});

I get the following warning and the refs array is not updated when all the components are mounted.

index.js:1 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef`.
    in h (at Avatar.js:11)
    in li (at Avatar.js:10)
    in ForwardRef (at Avatars.js:10)
    in ul (at Avatars.js:24)
    in ForwardRef (at AvatarBuilder.js:189)
    in AvatarBuilder (at App.js:19)
    in div (at App.js:14)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)

Any idea how should this be fixed? Thanks!

Body:
Try this one.

const AvatarBuilder = props => {
    ...
    // in this dummy example i would have 5 avatars
    const URLS=[1,2,3,4,5];
    const refs = URLS.map(item => React.createRef());
    return (
        <>
            <Avatars
                refs={refs}
                urlList={URLS}
            />
        </>
    );

// you don't need to make it with `fowardRef()`
const Avatars = (props) => {
    const {refs} = props;
    let urlList = props.urlList.map((url, index) => {
        console.log(url, index, typeof (index), ref);
        return (
            <Avatar
                ref={refs[index]}
                url={url}
            />
        )
    })
    return (
        <ul className="Avatars" >
            {urlList}
        </ul>
    )
};

const Avatar = React.forwardRef((props, ref) => {
    return (
        <li className="Avatar">
            <img
                src={props.url}
                ref={ref}
            />
        </li>
    )
});


问:
How to tell PyTorch to not use the GPU?
I want to do some timing comparisons between CPU & GPU as well as some profiling and would like to know if there's a way to tell pytorch to not use the GPU and instead use the CPU only? I realize I could install another CPU-only pytorch, but hoping there's an easier way.</p>

答:
Simplest way using Python is:</p>
```<code>os.environ["CUDA_VISIBLE_DEVICES"]=""
</code>```

Title: How to tell PyTorch to not use the GPU?

Body:
Simplest way using Python is:

os.environ["CUDA_VISIBLE_DEVICES"]=""


问:
How can we get regression coefficients from a Keras linear regression model?
A multiple linear regression model with k predictors X1, X2, ..., Xk
and a response Y , can be written as y = β0 + β1X1 + β2X2 + ··· βkXk + ".

I followed the tutorial here to use tf.keras to do basic regression. https://www.tensorflow.org/tutorials/keras/regression. Is it possible to output the β variables so I can examine how they contribute to the response?

The model the tutorial has you build looks like this by the way:

```<code>def build_model():
  model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=[len(train_dataset.keys())]),
    layers.Dense(64, activation='relu'),
    layers.Dense(1)
  ])

  optimizer = tf.keras.optimizers.RMSprop(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae', 'mse'])
  return model
</code>```

Where len(train_dataset.keys()) is 9.

答:
The weights are stored in:

```<code>model.layers[n].weights
</code>```

with layers a list and n the layer index in the model.

In your example, because input shape is (9,)

```<code>>>> len(model.layers[0].weights)
2
>>> model.layers[0].weights[0].shape
TensorShape([9, 64])
>>> model.layers[0].weights[1].shape
TensorShape([64])
</code>```

To interpret these, imagine the first layer is to compute h = ReLU(Ax+b) with x a vector of (9,) then A is a matrix of shape (9,64) and b a vector of shape (64,), and h also a vector of shape (64,). Therefore, model.layers[0].weights is the list [A, b] of two weight tensors.

It is not linear regression. If you want it to be, you need to make a simpler model:

```<code>def build_model():
  model = keras.Sequential([
    layers.Dense(1, input_shape=[len(train_dataset.keys())])
  ])

  optimizer = tf.keras.optimizers.RMSprop(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae', 'mse'])
  return model
</code>```

Then, after training with data, model.layers[0].weights[0] will have shape (9,1), which are your  β1, β2, ..., βk; and model.layers[0].weights[1] will have shape (1,), which is your β0

Body:
A multiple linear regression model with k predictors X1, X2, ..., Xk
and a response Y , can be written as y = β0 + β1X1 + β2X2 + ··· βkXk + ".

I followed the tutorial here to use tf.keras to do basic regression. https://www.tensorflow.org/tutorials/keras/regression. Is it possible to output the β variables so I can examine how they contribute to the response?

The model the tutorial has you build looks like this by the way:

def build_model():
  model = keras.Sequential([
    layers.Dense(64, activation='relu', input_shape=[len(train_dataset.keys())]),
    layers.Dense(64, activation='relu'),
    layers.Dense(1)
  ])

  optimizer = tf.keras.optimizers.RMSprop(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae', 'mse'])
  return model

Where len(train_dataset.keys()) is 9.

Body:
The weights are stored in:

model.layers[n].weights

with layers a list and n the layer index in the model.

In your example, because input shape is (9,)

>>> len(model.layers[0].weights)
2
>>> model.layers[0].weights[0].shape
TensorShape([9, 64])
>>> model.layers[0].weights[1].shape
TensorShape([64])

To interpret these, imagine the first layer is to compute h = ReLU(Ax+b) with x a vector of (9,) then A is a matrix of shape (9,64) and b a vector of shape (64,), and h also a vector of shape (64,). Therefore, model.layers[0].weights is the list [A, b] of two weight tensors.

It is not linear regression. If you want it to be, you need to make a simpler model:

def build_model():
  model = keras.Sequential([
    layers.Dense(1, input_shape=[len(train_dataset.keys())])
  ])

  optimizer = tf.keras.optimizers.RMSprop(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae', 'mse'])
  return model

Then, after training with data, model.layers[0].weights[0] will have shape (9,1), which are your  β1, β2, ..., βk; and model.layers[0].weights[1] will have shape (1,), which is your β0


问:
RabbitMQ conf file location
Where do I put my rabbitmq.conf file and how do I make it known to the rabbitmq-server?

All documentation and what I can find only clarifies that this file is not there initially, and the example config file is referenced. Official doc says that I can override the RABBITMQ_CONFIG_FILE env variable. It is unset on my system, but how would I set it so that it is known to rabbitmq-server?

答:
As @Taschi mentioned, the default location of the rabbitmq.conf file is /etc/rabbitmq folder.

Also, you can place it in a custom location and let the rabbitmq-server know the location by setting in in the rabbitmq-env.conf file.

Contents of rabbitmq-env.conf file

```<code>CONFIG_FILE=/path/to/rabbitmq.conf
</code>```

Reference: https://www.rabbitmq.com/configure.html#config-location

Title: RabbitMQ conf file location

Body:
As @Taschi mentioned, the default location of the rabbitmq.conf file is /etc/rabbitmq folder.

Also, you can place it in a custom location and let the rabbitmq-server know the location by setting in in the rabbitmq-env.conf file.

Contents of rabbitmq-env.conf file

CONFIG_FILE=/path/to/rabbitmq.conf

Reference: https://www.rabbitmq.com/configure.html#config-location


问:
How to create a directory in Laravel
I'm trying to create a folder in the storage folder in Laravel, but I keep getting this error:

```<code>mkdir(): No such file or directory
</code>```

I get what that means, but I thought it would be possible to create one with either:

```<code>File::makeDirectory(storage_path("story/$story->id"));
</code>```

or

```<code>mkdir(storage_path("story/$story->id"));
</code>```

but both of them are giving me the error above.

答:
Try using a defined permission:

```<code>File::makeDirectory('/path/to/directory', 0775);
</code>```

Also, refer to:
"How to create directory if not exists in Laravel 7.x and 6.x?".

Title: How to create a directory in Laravel

Body:
I'm trying to create a folder in the storage folder in Laravel, but I keep getting this error:

mkdir(): No such file or directory

I get what that means, but I thought it would be possible to create one with either:

File::makeDirectory(storage_path("story/$story->id"));

or

mkdir(storage_path("story/$story->id"));

but both of them are giving me the error above.

Body:
Try using a defined permission:

File::makeDirectory('/path/to/directory', 0775);

Also, refer to:
"How to create directory if not exists in Laravel 7.x and 6.x?".


问:
Upload Image through API in CKEditor 4
I'm using Ckeditor 4 to upload image. I want to send image to api and output will be a image url. Here is my ckeditor:

HTML:

```<code><textarea cols="80" rows="10" id="ckeditor1" name="ckeditor1" data-sample-short></textarea>
</code>```

JS:

```<code>CKEDITOR.replace('ckeditor1', {
  height: 300,
  filebrowserImageUploadUrl: 'https://example.com/api/image/editor',
  filebrowserUploadMethod: 'form',
  fileTools_requestHeaders: {
       'X-Requested-With': 'XMLHttpRequest',
       'access-token': 'token'
  }
});
</code>```

At the end. It alert 'Image Source URL Is Missing'. Because my API return:

```<code>{image_url: "https://exmaple.com/image/image.png"}
</code>```

Is there any way that I can handle this object, and add image to ckeditor ?

答:
Trying to estimate what you need in this case.

From what I can see you were using this example.

Basically what you have in this case are three steps:

You use the upload image function inside the CKEditor.

You process the uploaded image server-side with a function you prepared or an external image processing API.

You return a JSON response with the object: {image_url: ...absolute url to image...}.

I have a similar implementation using TinyMCE so basically what I do in my case is I specify the URL for my upload and have a server-side function that receives the upload, moves the uploaded file to a specific folder and then proceeds to make a smaller, optimized version of the uploaded image and in the end I just return a JSON array with the image's absolute URL. What I do next is I just handle the response from my function in my TinyMCE initializer. I suppose it's similar for CKEditor.

My TinyMCE code example (irrelevant parts reduced with ...):

tinymce.init({
    ...
    plugins: '...imagetools...',
    images_upload_handler: function (blobInfo, success, failure) {
        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.open('POST', 'https://www.example.com/images/upload');

        xhr.onload = function() {
            var json;

            if (xhr.status != 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }

            json = JSON.parse(xhr.responseText);

            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }

            success(json.location);
        };

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
    }
});
```

<p>So basically what this does is that it appends an image with that file location to the editor. I know it's not CKEditor, but the principle is the same. Hope it helps.</p>

<p><strong>EDIT FOR SPECIFIC DETAILS</strong></p>

<p>Just to clarify the insertion of the image inside TinyMCE.</p>

<p>The function that handles what is to be done once you insert an uploaded image to the TinyMCE instance is <code>images_upload_handler</code>. It is automatically triggered once you use the <code>imagetools</code> plugin. There are different options to handle it, you can check here, but I am showing you my specific example which worked for my needs.</p>

<p><img src="https://i.stack.imgur.com/C4w8z.png" alt="Image Upload"></p>

<p>This is the icon you can use or you can also also the Insert -> Image menu.</p>

<p><img src="https://i.stack.imgur.com/ayvPt.png" alt="Image Upload Menu"></p>

<p>Once you use that function you get this dialog (the regular one has only the General tab available):</p>

<p><img src="https://i.stack.imgur.com/6BdLo.png" alt="enter image description here"></p>

<p>So once you upload an image, tinyMCE calls the <code>images_upload_handler</code> function and sends the information of the uploaded image via XHR.</p>

<p>You send the image file via POST to your URL function, it can be relative or absolute, I prefer absolute URLs in my case.</p>

<p>Then you get to this part of the code:</p>

```xhr.onload = function() {
    var json;

    // If your http response code is not 200 you get an error
    if (xhr.status != 200) {
        failure('HTTP Error: ' + xhr.status);
        return;
    }

    // If not you receive a JSON response.
    // In my case the PHP response is:
    // echo json_encode(array('location' => site_url($path.'/'.$data['file_name'])));
    // $data['file_name'] is the original name of my uploaded file
    json = JSON.parse(xhr.responseText);

    // So the result of this is basically something like:
    // { location: "https://www.example.com/images/2020/06/theimage.jpg" }

    // Then what I check is if the location response is defined
    // and if it's a string
    // if not error
    if (!json || typeof json.location != 'string') {
        failure('Invalid JSON: ' + xhr.responseText);
        return;
    }

    // If it is correct you indicate a successful upload and the next thing
    // TinyMCE does is go back to your upload dialog
    success(json.location);
};
```

Just that in this case your dialog now has this:

Once you click on OK, TinyMCE inserts the image in the regular fashion it uses for image URLs and you can keep editing your content.

As for the PHP image upload/processing function that's up to you, you just need to return the location of the processed file to this handler.

Title: Upload Image through API in CKEditor 4

Body:
I'm using Ckeditor 4 to upload image. I want to send image to api and output will be a image url. Here is my ckeditor:

HTML:

<textarea cols="80" rows="10" id="ckeditor1" name="ckeditor1" data-sample-short></textarea>

JS:

CKEDITOR.replace('ckeditor1', {
  height: 300,
  filebrowserImageUploadUrl: 'https://example.com/api/image/editor',
  filebrowserUploadMethod: 'form',
  fileTools_requestHeaders: {
       'X-Requested-With': 'XMLHttpRequest',
       'access-token': 'token'
  }
});

At the end. It alert 'Image Source URL Is Missing'. Because my API return:

{image_url: "https://exmaple.com/image/image.png"}

Is there any way that I can handle this object, and add image to ckeditor ?

Body:
Trying to estimate what you need in this case.

From what I can see you were using this example.

Basically what you have in this case are three steps:

You use the upload image function inside the CKEditor.

You process the uploaded image server-side with a function you prepared or an external image processing API.

You return a JSON response with the object: {image_url: ...absolute url to image...}.

I have a similar implementation using TinyMCE so basically what I do in my case is I specify the URL for my upload and have a server-side function that receives the upload, moves the uploaded file to a specific folder and then proceeds to make a smaller, optimized version of the uploaded image and in the end I just return a JSON array with the image's absolute URL. What I do next is I just handle the response from my function in my TinyMCE initializer. I suppose it's similar for CKEditor.

My TinyMCE code example (irrelevant parts reduced with ...):

tinymce.init({
    ...
    plugins: '...imagetools...',
    images_upload_handler: function (blobInfo, success, failure) {
        var xhr, formData;

        xhr = new XMLHttpRequest();
        xhr.withCredentials = true;
        xhr.open('POST', 'https://www.example.com/images/upload');

        xhr.onload = function() {
            var json;

            if (xhr.status != 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }

            json = JSON.parse(xhr.responseText);

            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }

            success(json.location);
        };

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
    }
});

So basically what this does is that it appends an image with that file location to the editor. I know it's not CKEditor, but the principle is the same. Hope it helps.

EDIT FOR SPECIFIC DETAILS

Just to clarify the insertion of the image inside TinyMCE.

The function that handles what is to be done once you insert an uploaded image to the TinyMCE instance is images_upload_handler. It is automatically triggered once you use the imagetools plugin. There are different options to handle it, you can check here, but I am showing you my specific example which worked for my needs.

This is the icon you can use or you can also also the Insert -> Image menu.

Once you use that function you get this dialog (the regular one has only the General tab available):

So once you upload an image, tinyMCE calls the images_upload_handler function and sends the information of the uploaded image via XHR.

You send the image file via POST to your URL function, it can be relative or absolute, I prefer absolute URLs in my case.

Then you get to this part of the code:

xhr.onload = function() {
    var json;

    // If your http response code is not 200 you get an error
    if (xhr.status != 200) {
        failure('HTTP Error: ' + xhr.status);
        return;
    }

    // If not you receive a JSON response.
    // In my case the PHP response is:
    // echo json_encode(array('location' => site_url($path.'/'.$data['file_name'])));
    // $data['file_name'] is the original name of my uploaded file
    json = JSON.parse(xhr.responseText);

    // So the result of this is basically something like:
    // { location: "https://www.example.com/images/2020/06/theimage.jpg" }

    // Then what I check is if the location response is defined
    // and if it's a string
    // if not error
    if (!json || typeof json.location != 'string') {
        failure('Invalid JSON: ' + xhr.responseText);
        return;
    }

    // If it is correct you indicate a successful upload and the next thing
    // TinyMCE does is go back to your upload dialog
    success(json.location);
};

Just that in this case your dialog now has this:

Once you click on OK, TinyMCE inserts the image in the regular fashion it uses for image URLs and you can keep editing your content.

As for the PHP image upload/processing function that's up to you, you just need to return the location of the processed file to this handler.


答:
If I understand what you are after correctly then what you want is to split the list every time the number decreases.  If so then this should do what you need

```<code>c = []
previous_element = a[0]
sub_list = [previous_element]
for element in a[1:]:
    if previous_element > element:
        c.append(sub_list)
        sub_list = []
    previous_element = element
    sub_list.append(previous_element)
c.append(sub_list)
</code>```

Output:

In [1]: c

Out[2]: [[2, 2], [1, 3, 4], [1]]

There is possibly a clearer way to right the above, but it's pre coffee for me ;)

Also note that this code assumes that a will contain at least one item, if that is not always the case then you will need to either add an if statement around this, or re-structure the loop in a more while loop

Title: Make a list with non-decreasing order elements of a list in Python

Body:
If I understand what you are after correctly then what you want is to split the list every time the number decreases.  If so then this should do what you need

c = []
previous_element = a[0]
sub_list = [previous_element]
for element in a[1:]:
    if previous_element > element:
        c.append(sub_list)
        sub_list = []
    previous_element = element
    sub_list.append(previous_element)
c.append(sub_list)

Output:

In [1]: c

Out[2]: [[2, 2], [1, 3, 4], [1]]

There is possibly a clearer way to right the above, but it's pre coffee for me ;)

Also note that this code assumes that a will contain at least one item, if that is not always the case then you will need to either add an if statement around this, or re-structure the loop in a more while loop


问:
How do I toggle a .setAttribute?
I know there’s a .toggle for things like toggling a class, but for this specifically, I can’t do that it seems. I’m trying to toggle an image from a moon to sun (light and dark theme).

I’ve gotten a function that, when an anchor tag is clicked, it will change from a moon to a sun, but I can’t manage to figure out how to make it toggle.

If I can’t use .toggle, then what do I use? Do I possibly need to create my own function using Javascript logic? Are there scripts that do this already?

The Javascript Code:

```<code>function changeTheme() {
  document.getElementById("theme").setAttribute("src", "sun.png");
}
</code>```

The HTML Code:

```<code><img onclick="changeTheme()" src="moon.png" id="theme" class="toggle-theme">
</code>```

(The class is in there for the actual theme change...)

Thanks for any answers!

Note: This is my first post on Stack Overflow. If I did something wrong or you need more information, please, do tell me. Thank you.

答:
Just suggestions as it helped me allot during creating the theme-switch, use the
HTML attribute property to keep track of them.

Never ever write conditions based on the image name or source it makes your code dependable and it's not a good way of programming.

Tracking of CSS is very important when you have to switch the theme of your website

function changeTheme() {
  const domRef = document.getElementById("theme");

  if (domRef.getAttribute("data-theme-name") === "dark") {
    domRef.setAttribute("data-theme-name", "light");
    domRef.setAttribute("src",
    "https://img.icons8.com/bubbles/50/000000/adobe-photoshop.png");
  } else {
    domRef.setAttribute("data-theme-name", "dark");
    domRef.setAttribute("src","https://img.icons8.com/bubbles/50/000000/adobe-animate.png");
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.toggle-theme {
   height: 15vh;

}</code>```

   ```

Title: How do I toggle a .setAttribute?

Body:
I know there’s a .toggle for things like toggling a class, but for this specifically, I can’t do that it seems. I’m trying to toggle an image from a moon to sun (light and dark theme).

I’ve gotten a function that, when an anchor tag is clicked, it will change from a moon to a sun, but I can’t manage to figure out how to make it toggle.

If I can’t use .toggle, then what do I use? Do I possibly need to create my own function using Javascript logic? Are there scripts that do this already?

The Javascript Code:

function changeTheme() {
  document.getElementById("theme").setAttribute("src", "sun.png");
}

The HTML Code:

(The class is in there for the actual theme change...)

Thanks for any answers!

Note: This is my first post on Stack Overflow. If I did something wrong or you need more information, please, do tell me. Thank you.

Body:
Just suggestions as it helped me allot during creating the theme-switch, use the
HTML attribute property to keep track of them.

Never ever write conditions based on the image name or source it makes your code dependable and it's not a good way of programming.

Tracking of CSS is very important when you have to switch the theme of your website

function changeTheme() {
  const domRef = document.getElementById("theme");

  if (domRef.getAttribute("data-theme-name") === "dark") {
    domRef.setAttribute("data-theme-name", "light");
    domRef.setAttribute("src",
    "https://img.icons8.com/bubbles/50/000000/adobe-photoshop.png");
  } else {
    domRef.setAttribute("data-theme-name", "dark");
    domRef.setAttribute("src","https://img.icons8.com/bubbles/50/000000/adobe-animate.png");
  }
}

.toggle-theme {
   height: 15vh;

}

   <img onclick="changeTheme()"
    data-theme-name="dark"
    src="https://img.icons8.com/bubbles/50/000000/adobe-animate.png" id="theme" class="toggle-theme">