问:
How to use Do While Loop / While End While Loop in this code instead of GoTo
I'm a bit new with Visual Basic and I'm trying to make a program that would generate random numbers from 1 to 9 without repetition using arrays. I've also read that instead of using GoTo statements (as they are generally frowned upon), Do While Loop or While End While Statements could be used. I've tried using these loops but have not made it work. Here is the code:</p>

```<code>Dim x As Integer = 0, y As Integer = 0, num As Integer = 0, arr(8) As Integer
        lstLoop.Items.Clear()
        For x = 0 To 8
Start:
            Randomize()
            num = Fix(Rnd() * 9) + 1
            For y = 0 To 8
                If num = arr(y) Then
                    GoTo Start
                End If
            Next
        arr(x) = num
        lstLoop.Items.Add(arr(x))
        Next
</code>```

答:
use dictionary.

```<code>Sub test()
    Dim dic As Object
    Dim n As Integer
    Dim Num As Integer
    Set dic = CreateObject("Scripting.Dictionary")

    Do Until n = 9
        num = WorksheetFunction.RandBetween(1, 9)
        If dic.Exists(num) Then
        Else
            n = n + 1
            dic.Add num, num
        End If

    Loop
    Range("a1").Resize(1, 9) = dic.Keys
End Sub
</code>```

or

```<code>Sub test()
    Dim dic As Object
    Dim Num As Integer
    Set dic = CreateObject("Scripting.Dictionary")

    Do Until dic.Count = 9
        num = WorksheetFunction.RandBetween(1, 9)
        If dic.Exists(num) Then
        Else
            dic.Add num, num
        End If
    Loop
    Range("a1").Resize(1, 9) = dic.Keys
End Sub
</code>```

Body:
I'm a bit new with Visual Basic and I'm trying to make a program that would generate random numbers from 1 to 9 without repetition using arrays. I've also read that instead of using GoTo statements (as they are generally frowned upon), Do While Loop or While End While Statements could be used. I've tried using these loops but have not made it work. Here is the code:

Dim x As Integer = 0, y As Integer = 0, num As Integer = 0, arr(8) As Integer
        lstLoop.Items.Clear()
        For x = 0 To 8
Start:
            Randomize()
            num = Fix(Rnd() * 9) + 1
            For y = 0 To 8
                If num = arr(y) Then
                    GoTo Start
                End If
            Next
        arr(x) = num
        lstLoop.Items.Add(arr(x))
        Next

Body:
use dictionary.

Sub test()
    Dim dic As Object
    Dim n As Integer
    Dim Num As Integer
    Set dic = CreateObject("Scripting.Dictionary")

    Do Until n = 9
        num = WorksheetFunction.RandBetween(1, 9)
        If dic.Exists(num) Then
        Else
            n = n + 1
            dic.Add num, num
        End If

    Loop
    Range("a1").Resize(1, 9) = dic.Keys
End Sub

or

Sub test()
    Dim dic As Object
    Dim Num As Integer
    Set dic = CreateObject("Scripting.Dictionary")

    Do Until dic.Count = 9
        num = WorksheetFunction.RandBetween(1, 9)
        If dic.Exists(num) Then
        Else
            dic.Add num, num
        End If
    Loop
    Range("a1").Resize(1, 9) = dic.Keys
End Sub


来源: stackexchange

问:
Practicing linked lists
So we learned about lists in class lately and I wanted to practice them. The program doesn't run. Did I fail in filling the nodes? I'm too dizzy to focus on finding the missing key. Sorry for posting such triviality!</p>

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int val;
    struct node *next;
}node_t;

node_t* create_node(int value,node_t *nextnode) {
    node_t *newnode=(node_t*)malloc(sizeof(node_t));
    if(newnode==NULL) {
        printf("ERROR ALLOCATING");
        exit(0);
    }
    newnode->val=value;
    newnode->next=nextnode;
    return newnode;
}

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

void print_list(node_t *head) {
    node_t *current=head;
    while(current) {
        printf("%d",current->val);
        current=current->next;
    }
}

int main() {
    node_t *head=NULL;
    fill_list(head);
    print_list(head);
    return 0;
}
</code>```

答:
Problem

Function arguments in C are 'pass-by-value'. The problem with this is that your fill_list function takes a pointer to a node_t called head, but any changes you make to this pointer, will not affect the value of head outside the function. head inside the function is a completely different thing to the  head in your main().

Quick Fix

If you really want to change the value of head (the one outside the function) then you have to pass the function a pointer to the bit of memory in which head resides. For your example, this means a pointer to a pointer to a node_t.

So your fill_list would look like:

```<code>void fill_list(node_t **head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i, *head);
        *head=current;
    }
}
</code>```

Note that you must now dereference the pointer before passing it to create_node.

By dereferencing in the assignment *head = current, you are setting the contents of the memory pointed to by head. Which is the same memory holding the head variable declared in your main(). This is what you want.

Now you can call fill_list like this:

fill_list(&head)

Better Fix

Have fill_list return a pointer to the head, such as:

```<code>node_t* fill_list() {
    int i=1;
    node_t *head = NULL;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i, head);
        head=current;
    }

    return head;
}
</code>```

and then main():

```<code>int main() {
    node_t *head = fill_list();
    print_list(head);
    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Practicing linked lists

Body:
So we learned about lists in class lately and I wanted to practice them. The program doesn't run. Did I fail in filling the nodes? I'm too dizzy to focus on finding the missing key. Sorry for posting such triviality!

#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    int val;
    struct node *next;
}node_t;

node_t* create_node(int value,node_t *nextnode) {
    node_t *newnode=(node_t*)malloc(sizeof(node_t));
    if(newnode==NULL) {
        printf("ERROR ALLOCATING");
        exit(0);
    }
    newnode->val=value;
    newnode->next=nextnode;
    return newnode;
}

void fill_list(node_t *head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i,head);
        head=current;
    }
}

void print_list(node_t *head) {
    node_t *current=head;
    while(current) {
        printf("%d",current->val);
        current=current->next;
    }
}

int main() {
    node_t *head=NULL;
    fill_list(head);
    print_list(head);
    return 0;
}

Body:
Problem

Function arguments in C are 'pass-by-value'. The problem with this is that your fill_list function takes a pointer to a node_t called head, but any changes you make to this pointer, will not affect the value of head outside the function. head inside the function is a completely different thing to the  head in your main().

Quick Fix

If you really want to change the value of head (the one outside the function) then you have to pass the function a pointer to the bit of memory in which head resides. For your example, this means a pointer to a pointer to a node_t.

So your fill_list would look like:

void fill_list(node_t **head) {
    int i=1;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i, *head);
        *head=current;
    }
}

Note that you must now dereference the pointer before passing it to create_node.

By dereferencing in the assignment *head = current, you are setting the contents of the memory pointed to by head. Which is the same memory holding the head variable declared in your main(). This is what you want.

Now you can call fill_list like this:

fill_list(&head)

Better Fix

Have fill_list return a pointer to the head, such as:

node_t* fill_list() {
    int i=1;
    node_t *head = NULL;
    node_t *current;
    for(;i<21;i++) {
        current=create_node(i, head);
        head=current;
    }

    return head;
}

and then main():

int main() {
    node_t *head = fill_list();
    print_list(head);
    return 0;
}


问:
teechart 2020 trial version install package missing entry point
I've just installed the trial version of Steema TeeChart Pro 2020 VCL/FMX for RAD Studio 10.2 Tokyo into my Win10 dev VM.  The installation went normally - it raised the issue of the missing GDI HPP files, which I downloaded and installed before continuing - and the install reported that it completed without errors.  However, when I start the IDE or when trying to enable the package from within the IDE, I get a missing-entry-point error for @System@Net@HttpClient@Win@TWinHttpLib@$bcctr$qqrv in C:\Program Files (x86)\Steema Software\Steema TeeChart Pro VCL FMX 2020.29\Delphi25\Delphi25.win32\Bin\DclTeePro925.bpl.  I've cleared any other potential conflicting packages.  Anyone else experienced this? Any ideas on clearing it?

答:
After further searching, I found a link to the Steema forum where this issue is discussed.
The answer to this is indeed one of versioning.  I was running 10.2.2 but not the last hotfix; the hotfix addresses a bug in the RTL's HTTP support, which was causing the load issue.

I've updated to 10.2.3, which clears the Steema problem, but be aware that the upgrade requires a full uninstall of the earlier version, so you'll need to save all your environment config, uninstall 10.2.x, install the 10.2.3 version (6Gb download) and re-install any GetIt or other 3rd-party packages.


问:
Problem with storing german words into the MySql DB....?
I am facing an small issue in my project When I am trying to store some German words into the MYSQL Database. When this German words contains umlauts i.e. characters ä, ö, ß, ü etc., they are not stored as they are.....?

I want to store them as it is into the Database.To do so I tried to change the COLLATION to UTF8-general-ci, and others in the list using PHP myAdmin. But none of them is working for me.

Am I in the right way or I have to do something else.

Please suggest some help.

Thanks In Advance......

答:
After connecting to the database, use the following codes:

```<code>SET NAMES XXX
</code>```

replace XXX with your working charset.

ContentLicense: CC BY-SA 3.0

Body:
After connecting to the database, use the following codes:

SET NAMES XXX

replace XXX with your working charset.


问:
How to install mono in centOS7 aarch64
How to install mono in centOS 7 aarch64? The official download page only support x86_x64.

Does mono support RHEL 7 arm64?

official download page

Can this package be installed into centOS7 aarch64?

If yes, how to install or build it?

Thank you for your help.

答: According to the Mono website, only x86_64 is available for CentOS/RHEL 7.</p>

Title: How to install mono in centOS7 aarch64


问:
Recylerview in fragment doesnt populate with items
Sorry for this noob questons, but I am starting to learn Firebase UI and 2 days in a row I am stuck with populating a RecyclerView in a fragment.
I tried to move my code around in onViewCreated , onCreateView methods but I think that is not the problem, in log it just throws one error:

```<code>2020-02-18 15:08:26.730 4467-4467/com.social.voteup E/RecyclerView: No adapter attached; skipping layout
</code>```

Double checked everything is linking with the xml file.
Here is my code:

```<code>  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }
</code>```

On View Created method

mRecyclerView = view.findViewById(R.id.posts_recyclerview);
    mSwipeRefreshLayout = view.findViewById(R.id.refreshLayout);

```<code>mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

setupAdapter();

// Refresh Action on Swipe Refresh Layout
mSwipeRefreshLayout.setOnRefreshListener(() -> mAdapter.refresh());
</code>```

I use the adapter inside the fragment as shown here:

```<code> private void setupAdapter() {

        // Init Paging Configuration
        PagedList.Config config = new PagedList.Config.Builder()
                .setEnablePlaceholders(false)
                .setPrefetchDistance(2)
                .setPageSize(10)
                .build();

        // Init Adapter Configuration
        FirestorePagingOptions<Post> options = new FirestorePagingOptions.Builder<Post>()
                .setLifecycleOwner(this)
                .setQuery(mQuery, config, Post.class)
                .build();

        // Instantiate Paging Adapter
        mAdapter = new FirestorePagingAdapter<Post, PostViewHolder>(options) {
            @NonNull
            @Override
            public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = getLayoutInflater().inflate(R.layout.item_post, parent, false);
                return new PostViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(@NonNull PostViewHolder viewHolder, int i, @NonNull Post post) {
                // Bind to ViewHolder
                viewHolder.bind(post);
            }

            @Override
            protected void onError(@NonNull Exception e) {
                super.onError(e);
                Log.e("MainActivity", Objects.requireNonNull(e.getMessage()));
            }

            protected void onLoadingStateChanged(@NonNull LoadingState state) {
                switch (state) {
                    case LOADING_INITIAL:
                    case LOADING_MORE:
                        mSwipeRefreshLayout.setRefreshing(true);
                        break;

                    case LOADED:
                        mSwipeRefreshLayout.setRefreshing(false);
                        break;

                    case ERROR:

                        mSwipeRefreshLayout.setRefreshing(false);
                        break;

                    case FINISHED:
                        mSwipeRefreshLayout.setRefreshing(false);
                        break;
                }
            }

        };

        // Finally Set the Adapter to mRecyclerView
        mRecyclerView.setAdapter(mAdapter);

    }
</code>```

Here is the full source file on pastebin:https://pastebin.com/YkzKRuUD

答:
Add this line of code in the On View Created method.

You have created an adapter but you haven't attached the adapter to the recyclerView

```<code>
mRecyclerView = view.findViewById(R.id.posts_recyclerview);
mSwipeRefreshLayout = view.findViewById(R.id.refreshLayout);

mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

mRecyclerView.setAdapter(new setupAdapter());

// Refresh Action on Swipe Refresh Layout
mSwipeRefreshLayout.setOnRefreshListener(() -> mAdapter.refresh());

</code>```

Body:
Sorry for this noob questons, but I am starting to learn Firebase UI and 2 days in a row I am stuck with populating a RecyclerView in a fragment.
I tried to move my code around in onViewCreated , onCreateView methods but I think that is not the problem, in log it just throws one error:

2020-02-18 15:08:26.730 4467-4467/com.social.voteup E/RecyclerView: No adapter attached; skipping layout

Double checked everything is linking with the xml file.
Here is my code:

  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_home, container, false);
        return view;
    }

On View Created method

mRecyclerView = view.findViewById(R.id.posts_recyclerview);
    mSwipeRefreshLayout = view.findViewById(R.id.refreshLayout);

mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

setupAdapter();

// Refresh Action on Swipe Refresh Layout
mSwipeRefreshLayout.setOnRefreshListener(() -> mAdapter.refresh());

I use the adapter inside the fragment as shown here:

 private void setupAdapter() {

        // Init Paging Configuration
        PagedList.Config config = new PagedList.Config.Builder()
                .setEnablePlaceholders(false)
                .setPrefetchDistance(2)
                .setPageSize(10)
                .build();

        // Init Adapter Configuration
        FirestorePagingOptions<Post> options = new FirestorePagingOptions.Builder<Post>()
                .setLifecycleOwner(this)
                .setQuery(mQuery, config, Post.class)
                .build();

        // Instantiate Paging Adapter
        mAdapter = new FirestorePagingAdapter<Post, PostViewHolder>(options) {
            @NonNull
            @Override
            public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = getLayoutInflater().inflate(R.layout.item_post, parent, false);
                return new PostViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(@NonNull PostViewHolder viewHolder, int i, @NonNull Post post) {
                // Bind to ViewHolder
                viewHolder.bind(post);
            }

            @Override
            protected void onError(@NonNull Exception e) {
                super.onError(e);
                Log.e("MainActivity", Objects.requireNonNull(e.getMessage()));
            }

            protected void onLoadingStateChanged(@NonNull LoadingState state) {
                switch (state) {
                    case LOADING_INITIAL:
                    case LOADING_MORE:
                        mSwipeRefreshLayout.setRefreshing(true);
                        break;

                    case LOADED:
                        mSwipeRefreshLayout.setRefreshing(false);
                        break;

                    case ERROR:

                        mSwipeRefreshLayout.setRefreshing(false);
                        break;

                    case FINISHED:
                        mSwipeRefreshLayout.setRefreshing(false);
                        break;
                }
            }

        };

        // Finally Set the Adapter to mRecyclerView
        mRecyclerView.setAdapter(mAdapter);

    }

Here is the full source file on pastebin:https://pastebin.com/YkzKRuUD

Body:
Add this line of code in the On View Created method.

You have created an adapter but you haven't attached the adapter to the recyclerView

mRecyclerView = view.findViewById(R.id.posts_recyclerview);
mSwipeRefreshLayout = view.findViewById(R.id.refreshLayout);

mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

mRecyclerView.setAdapter(new setupAdapter());

// Refresh Action on Swipe Refresh Layout
mSwipeRefreshLayout.setOnRefreshListener(() -> mAdapter.refresh());


问:
java - live view on collection contained within a collection contained within ... etc
I have a class A which can contain many instances of class B which may in turn contain many instances of Class C, which can contain many instances of class D

Now, in class A I have a method getAllD. Currently every time this is called there is a lot of iterating that takes place, and a rather large list is freshly created and returned. This cannot be very efficient.

I was wondering how I could do this better. This question Combine multiple Collections into a single logical Collection? seems to touch upon a similar topic, but I'm not really sure how I could apply it to my situation.

All comments are much appreciated!

答:
I would combine Iterables.concat with Iterables.transform to obtain a live view of Ds:

```<code>public class A {
    private Collection<B> bs;

    /**
     * @return a live concatenated view of the Ds contained in the Cs
     *         contained in the Bs contained in this A.
     */
    public Iterable<D> getDs() {
        Iterable<C> cs = Iterables.concat(Iterables.transform(bs, BToCsFunction.INSTANCE));
        Iterable<D> ds = Iterables.concat(Iterables.transform(cs, CToDsFunction.INSTANCE));
        return ds;
    }

    private enum BToCsFunction implements Function<B, Collection<C>> {
        INSTANCE;

        @Override
        public Collection<C> apply(B b) {
            return b.getCs();
        }
    }

    private enum CToDsFunction implements Function<C, Collection<D>> {
        INSTANCE;

        @Override
        public Collection<D> apply(C c) {
            return c.getDs();
        }
    }
}

public class B {
    private Collection<C> cs;

    public Collection<C> getCs() {
        return cs;
    }
}

public class C {
    private Collection<D> ds;

    public Collection<D> getDs() {
        return ds;
    }
}
</code>```

This works well if your goal is simply to iterate over  the Ds and you don't really need a collection view. It avoids the instantiation of a big temporary collection.

Body:
I would combine Iterables.concat with Iterables.transform to obtain a live view of Ds:

public class A {
    private Collection<B> bs;

    /**
     * @return a live concatenated view of the Ds contained in the Cs
     *         contained in the Bs contained in this A.
     */
    public Iterable<D> getDs() {
        Iterable<C> cs = Iterables.concat(Iterables.transform(bs, BToCsFunction.INSTANCE));
        Iterable<D> ds = Iterables.concat(Iterables.transform(cs, CToDsFunction.INSTANCE));
        return ds;
    }

    private enum BToCsFunction implements Function<B, Collection<C>> {
        INSTANCE;

        @Override
        public Collection<C> apply(B b) {
            return b.getCs();
        }
    }

    private enum CToDsFunction implements Function<C, Collection<D>> {
        INSTANCE;

        @Override
        public Collection<D> apply(C c) {
            return c.getDs();
        }
    }
}

public class B {
    private Collection<C> cs;

    public Collection<C> getCs() {
        return cs;
    }
}

public class C {
    private Collection<D> ds;

    public Collection<D> getDs() {
        return ds;
    }
}

This works well if your goal is simply to iterate over  the Ds and you don't really need a collection view. It avoids the instantiation of a big temporary collection.


问:
ThreeJs OBJLoader output looks very pixelated
I am trying to load .obj file through OBJLoader in angularjs. But the output is very pixelated.

Tried changing camera position & perspective(codes are commented), then it results in very smaller output, i need to zoom in through mouse in that case.But if i open the same .obj file in 3D Boulder or any other tools, it looks fine.

I have set camera & scene like this -

```<code>    this.renderer = new THREE.WebGLRenderer({ canvas: this.canvasRef.nativeElement });
    // this.renderer.setSize( window.innerWidth, window.innerHeight );
    // this.renderer.setSize(640, 720);

    // scene
    this.scene = new THREE.Scene();
    this.renderer.setClearColor(0xcdcbcb, 1);

    // camera
    this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
    // this.camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.01, 10000);
    this.camera.position.set(1, 1, 1);
    // this.camera.position.set(0, 0, 1);
    // this.camera.position.set(113, 111, 113);

    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.scene.add(new THREE.AmbientLight(0x222222));
    this.scene.add(this.camera); // required, because we are adding a light as a child of the camera

    // controls
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);

    // lights
    var light = new THREE.PointLight(0xffffff, 0.8);
    this.camera.add(light);

    var geometry = new THREE.BoxGeometry(1,1,1);
</code>```

Loading .obj file like this -

```<code>    var objLoader = new OBJLoader();
    objLoader.load("../../assets/temp_data/11.obj", function (object) {
      console.log(object);
      this.scene.add(object);
    }.bind(this));
    this.animate();
</code>```

what should be good camera & scene parameters so that it will work on all models & no need to zoom in or zoom out. Please Guide / Help.

答:
```<code>    this.renderer.setPixelRatio(window.devicePixelRatio);
</code>```

this works for me.

Body:
I am trying to load .obj file through OBJLoader in angularjs. But the output is very pixelated.

Tried changing camera position & perspective(codes are commented), then it results in very smaller output, i need to zoom in through mouse in that case.But if i open the same .obj file in 3D Boulder or any other tools, it looks fine.

I have set camera & scene like this -

    this.renderer = new THREE.WebGLRenderer({ canvas: this.canvasRef.nativeElement });
    // this.renderer.setSize( window.innerWidth, window.innerHeight );
    // this.renderer.setSize(640, 720);

    // scene
    this.scene = new THREE.Scene();
    this.renderer.setClearColor(0xcdcbcb, 1);

    // camera
    this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
    // this.camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.01, 10000);
    this.camera.position.set(1, 1, 1);
    // this.camera.position.set(0, 0, 1);
    // this.camera.position.set(113, 111, 113);

    this.camera.aspect = window.innerWidth / window.innerHeight;
    this.scene.add(new THREE.AmbientLight(0x222222));
    this.scene.add(this.camera); // required, because we are adding a light as a child of the camera

    // controls
    this.controls = new OrbitControls(this.camera, this.renderer.domElement);

    // lights
    var light = new THREE.PointLight(0xffffff, 0.8);
    this.camera.add(light);

    var geometry = new THREE.BoxGeometry(1,1,1);

Loading .obj file like this -

    var objLoader = new OBJLoader();
    objLoader.load("../../assets/temp_data/11.obj", function (object) {
      console.log(object);
      this.scene.add(object);
    }.bind(this));
    this.animate();

what should be good camera & scene parameters so that it will work on all models & no need to zoom in or zoom out. Please Guide / Help.

Body:
    this.renderer.setPixelRatio(window.devicePixelRatio);

this works for me.


问:
Gradle task for Sentry not compiling
I have to add the Analytics tool Sentry to our Android project. In order to make it work, one needs to create mappings for the obfuscated code (from Proguard/R8) and upload it later to Sentry.

On the website https://docs.sentry.io/platforms/android/ it is even described how to do that.
There it is written that one needs to create a gradle task looking like this:

```<code>gradle.projectsEvaluated {
    android.applicationVariants.each { variant ->
        def variantName = variant.name.capitalize();
        def proguardTask = project.tasks.findByName(
            "transformClassesAndResourcesWithProguardFor${variantName}")
        def dexTask = project.tasks.findByName(
            "transformClassesWithDexFor${variantName}")
        def task = project.tasks.create(
                name: "processSentryProguardFor${variantName}",
                type: Exec) {
            workingDir project.rootDir
            commandLine *[
                "sentry-cli",
                "upload-proguard",
                "--write-properties",
                "${project.rootDir.toPath()}/app/build/intermediates/assets" +
                    "/${variant.dirName}/sentry-debug-meta.properties",
                variant.getMappingFile(),
                "--no-upload"
            ]
        }
        dexTask.dependsOn task
        task.dependsOn proguardTask
    }
}
</code>```

This shall wait until Proguard is finished, than copy this properties file to the assets. However, when I add this to my Android gradle script I get the error:

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

No signature of method: java.util.ArrayList.multiply() is applicable for argument types: (ArrayList) values: [[sentry-cli, upload-proguard,
    --write-properties, {Application-Path}/app/build/intermediates/assets/playStoreStaging/debug/sentry-debug-meta.properties,
    ...]]   Possible solutions: multiply(java.lang.Number),
    multiply(java.lang.Number)

I assume there is something wrong with the multiplication symbol * before the commandLine array. But when I remove it I get the error

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

Cannot cast object 'sentry-cli' with class 'java.lang.String' to class 'int'

So I tried to test this with only that line

```<code>commandLine "sentry-cli", ...
</code>```

Which gave me another error

What went wrong: Cannot invoke method dependsOn() on null object

Thus I assume something went really wrong with that gradle script since it seems the dependend task can't be found. Does anyone have any idea how to fix this (or optionally have any other idea how to copy that sentry-debug-meta.properties file to my assets in another way, once Proguard/R8 is finished)?

Thanks!

-------- EDIT --------

I noticed something important.
The gradle tasks are defined in a different name than what was defined in the manual. Looking at my tasks I have them named

```<code>transformClassesAndResourcesWithR8For...
</code>```

and

```<code>transformClassesWithDexBuilderFor...
</code>```

However, I print the variantName then for checking but it seems my tasks are incomplete.

In my tasks list there exist

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

but not

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

and thus the task can't be found. I think that is the real problem here. So where are these gradle tasks defined?

------- EDIT 2 --------

Okay I noticed something strange here. Some variants don't have tasks. It makes sense that DEBUG tasks don't have R8 tasks but I found this here:

Variant: PlayStoreStagingRelease DexTask is null

Variant: PlayStorePreviewRelease DexTask is null

Variant: HockeyAppRelease DexTask is null

Variant: LocalServerRelease DexTask is null

Variant: PlayStoreProductionRelease DexTask is null

So how can this be?

答:
java.util.ArrayList.multiply() hints for that * in front of the [  ] list, which looks strange to me. Try removing the *[ ], only keeping List<String> (there's no ArrayList expected, to begin with):

```<code>commandLine "sentry-cli", "upload-proguard", "--write-properties", "${project.rootDir.toPath()}/app/build/intermediates/assets/${variant.dirName}/sentry-debug-meta.properties", variant.getMappingFile(), "--no-upload"
</code>```

You'd have to look up how your tasks are actually being called, but it should be something alike:

```<code>def r8Task = project.tasks.findByName("transformClassesAndResourcesWithR8For${variantName}")
def d8Task = project.tasks.findByName("transformClassesWithDexBuilderFor${variantName}")
</code>```

With a null check, because not every variant might have minifyEnabled true set:

```<code>if(r8Task != null) {
    d8Task.dependsOn task
    task.dependsOn r8Task
}
</code>```

Maybe even a previous null check is required, because variant.getMappingFile() needs R8.

And that some flavors have no D8 task might be based upon the absence of code (nothing to do).

Title: Gradle task for Sentry not compiling

Body:
I have to add the Analytics tool Sentry to our Android project. In order to make it work, one needs to create mappings for the obfuscated code (from Proguard/R8) and upload it later to Sentry.

On the website https://docs.sentry.io/platforms/android/ it is even described how to do that.
There it is written that one needs to create a gradle task looking like this:

gradle.projectsEvaluated {
    android.applicationVariants.each { variant ->
        def variantName = variant.name.capitalize();
        def proguardTask = project.tasks.findByName(
            "transformClassesAndResourcesWithProguardFor${variantName}")
        def dexTask = project.tasks.findByName(
            "transformClassesWithDexFor${variantName}")
        def task = project.tasks.create(
                name: "processSentryProguardFor${variantName}",
                type: Exec) {
            workingDir project.rootDir
            commandLine *[
                "sentry-cli",
                "upload-proguard",
                "--write-properties",
                "${project.rootDir.toPath()}/app/build/intermediates/assets" +
                    "/${variant.dirName}/sentry-debug-meta.properties",
                variant.getMappingFile(),
                "--no-upload"
            ]
        }
        dexTask.dependsOn task
        task.dependsOn proguardTask
    }
}

This shall wait until Proguard is finished, than copy this properties file to the assets. However, when I add this to my Android gradle script I get the error:

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

No signature of method: java.util.ArrayList.multiply() is applicable for argument types: (ArrayList) values: [[sentry-cli, upload-proguard,
    --write-properties, {Application-Path}/app/build/intermediates/assets/playStoreStaging/debug/sentry-debug-meta.properties,
    ...]]   Possible solutions: multiply(java.lang.Number),
    multiply(java.lang.Number)

I assume there is something wrong with the multiplication symbol * before the commandLine array. But when I remove it I get the error

Could not create task
  ':app:processSentryProguardForPlayStoreStagingDebug'.

Cannot cast object 'sentry-cli' with class 'java.lang.String' to class 'int'

So I tried to test this with only that line

commandLine "sentry-cli", ...

Which gave me another error

What went wrong: Cannot invoke method dependsOn() on null object

Thus I assume something went really wrong with that gradle script since it seems the dependend task can't be found. Does anyone have any idea how to fix this (or optionally have any other idea how to copy that sentry-debug-meta.properties file to my assets in another way, once Proguard/R8 is finished)?

Thanks!

-------- EDIT --------

I noticed something important.
The gradle tasks are defined in a different name than what was defined in the manual. Looking at my tasks I have them named

transformClassesAndResourcesWithR8For...

and

transformClassesWithDexBuilderFor...

However, I print the variantName then for checking but it seems my tasks are incomplete.

In my tasks list there exist

transformClassesAndResourcesWithR8ForPlayStoreStagingDebug

but not

transformClassesAndResourcesWithR8ForPlayStoreStagingRelease

and thus the task can't be found. I think that is the real problem here. So where are these gradle tasks defined?

------- EDIT 2 --------

Okay I noticed something strange here. Some variants don't have tasks. It makes sense that DEBUG tasks don't have R8 tasks but I found this here:

Variant: PlayStoreStagingRelease DexTask is null

Variant: PlayStorePreviewRelease DexTask is null

Variant: HockeyAppRelease DexTask is null

Variant: LocalServerRelease DexTask is null

Variant: PlayStoreProductionRelease DexTask is null

So how can this be?

Body:
java.util.ArrayList.multiply() hints for that * in front of the [  ] list, which looks strange to me. Try removing the *[ ], only keeping List<String> (there's no ArrayList expected, to begin with):

commandLine "sentry-cli", "upload-proguard", "--write-properties", "${project.rootDir.toPath()}/app/build/intermediates/assets/${variant.dirName}/sentry-debug-meta.properties", variant.getMappingFile(), "--no-upload"

You'd have to look up how your tasks are actually being called, but it should be something alike:

def r8Task = project.tasks.findByName("transformClassesAndResourcesWithR8For${variantName}")
def d8Task = project.tasks.findByName("transformClassesWithDexBuilderFor${variantName}")

With a null check, because not every variant might have minifyEnabled true set:

if(r8Task != null) {
    d8Task.dependsOn task
    task.dependsOn r8Task
}

Maybe even a previous null check is required, because variant.getMappingFile() needs R8.

And that some flavors have no D8 task might be based upon the absence of code (nothing to do).


问:
Skipping NA rows in index column
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3
</code>```

At the moment I'm doing it as:

```<code>i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)
</code>```

but that gives me

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5
</code>```

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

答:
```<code># example dataset
df = data.frame(VarA = c(TRUE, NA, NA, TRUE, TRUE))

# get cumulative sum based on cases where you don't have NA in VarA
df$ID = cumsum(!is.na(df$VarA))

# if you have NA in VarA use NA instead ofthe cumulative sum
df$ID = ifelse(is.na(df$VarA), df$VarA, df$ID)

df

#   VarA ID
# 1 TRUE  1
# 2   NA NA
# 3   NA NA
# 4 TRUE  2
# 5 TRUE  3
</code>```

You can combine the above in one command if you prefer like

```<code>df$ID = ifelse(is.na(df$VarA), df$VarA, cumsum(!is.na(df$VarA)))
</code>```

Title: Skipping NA rows in index column

Body:
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3

At the moment I'm doing it as:

i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)

but that gives me

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

Body:
# example dataset
df = data.frame(VarA = c(TRUE, NA, NA, TRUE, TRUE))

# get cumulative sum based on cases where you don't have NA in VarA
df$ID = cumsum(!is.na(df$VarA))

# if you have NA in VarA use NA instead ofthe cumulative sum
df$ID = ifelse(is.na(df$VarA), df$VarA, df$ID)

df

#   VarA ID
# 1 TRUE  1
# 2   NA NA
# 3   NA NA
# 4 TRUE  2
# 5 TRUE  3

You can combine the above in one command if you prefer like

df$ID = ifelse(is.na(df$VarA), df$VarA, cumsum(!is.na(df$VarA)))


问:
Call to undefined method Illuminate\Database\Eloquent\Builder::save() when running a Laravel Task Schedule Command
I am trying  to schedule a campaign that runs when

subendsat is greater or equal  to current time

subendsat is a column in user table

In my commands, I have this

```<code><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\User;
use Carbon\Carbon;

class ChangeRole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This Changes Role When The Subscription Expires';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $user = User::where('subendsat', '>=', Carbon::now())->get();
        $user->role = 'subscriber';
        $user->save();

    }
}
</code>```

In my Kernel, I have this

```<code>protected $commands = [
    //
    'App\Console\Commands\ChangeRole',
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
     $schedule->command('command:update')
              ->daily();
}
</code>```

I create a basic task like this in windows
  I have this inmy .bat file

c:\xampp\php\php.exe artisan schedule:run 1>> NUL 2>&1

Go to Windows Task Scheduler

Click Create a basic task, choose When I login trigger and then choose to Start a program -> your .bat file.

Check Open properties dialog option and click Finish.

In task properties click Triggers, then click New and add new trigger Repeat task every - 1 minute.

But when I run the command

php artisan command:update, it returned error

Call to undefined method Illuminate\Database\Eloquent\Builder::save()

But this is not updating my database when it runs. I don't know what I am doing. Can someone advise? thanks.

答:
Yes because you return a collection, not a single entry.

You can mass update your entries :

```<code>User::update(['role' => 'subscriber'])
      ->where('subendsat', '>=', Carbon::now());
</code>```

But I think you can't do this, you need to update the role_id field :

```<code>$roleSubscriber = Role::where('name', 'subscriber')->first();

User::update(['role_id' => $role->getKey()])
      ->where('subendsat', '>=', Carbon::now());
</code>```

Body:
I am trying  to schedule a campaign that runs when

subendsat is greater or equal  to current time

subendsat is a column in user table

In my commands, I have this

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\User;
use Carbon\Carbon;

class ChangeRole extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This Changes Role When The Subscription Expires';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $user = User::where('subendsat', '>=', Carbon::now())->get();
        $user->role = 'subscriber';
        $user->save();

    }
}

In my Kernel, I have this

protected $commands = [
    //
    'App\Console\Commands\ChangeRole',
];

/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
     $schedule->command('command:update')
              ->daily();
}

I create a basic task like this in windows
  I have this inmy .bat file

c:\xampp\php\php.exe artisan schedule:run 1>> NUL 2>&1

Go to Windows Task Scheduler

Click Create a basic task, choose When I login trigger and then choose to Start a program -> your .bat file.

Check Open properties dialog option and click Finish.

In task properties click Triggers, then click New and add new trigger Repeat task every - 1 minute.

But when I run the command

php artisan command:update, it returned error

Call to undefined method Illuminate\Database\Eloquent\Builder::save()

But this is not updating my database when it runs. I don't know what I am doing. Can someone advise? thanks.

Body:
Yes because you return a collection, not a single entry.

You can mass update your entries :

User::update(['role' => 'subscriber'])
      ->where('subendsat', '>=', Carbon::now());

But I think you can't do this, you need to update the role_id field :

$roleSubscriber = Role::where('name', 'subscriber')->first();

User::update(['role_id' => $role->getKey()])
      ->where('subendsat', '>=', Carbon::now());


问:
Bash regex that returns short alphanumeric operator name from AT command AT+COPS
I'm using a bash script with the AT command AT+COPS=? which returns the following string :

```<code>+COPS: (1,"Orange F","Orange","20801",2),(1,"Swisscom","Swisscom","22801",7),(1,"Swisscom","Swisscom","22801",2),(1,"Salt","Salt","22803",2),(1,"Sunrise","Sunrise","22802",2),(1,"Sunrise","Sunrise","22802",7),(1,"Sunrise","Sunrise","22802",0),(2,"Salt","Salt","22803",7),(1,"Free","Free","20815",2),(1,"F SFR","SFR","20810",7),(1,"F-Bouygues Telecom","BYTEL","20820",7),,(0-4),(0-2)
</code>```

And I'm trying to find a regular expression to match every short alphanumeric operator names. So here, it's :

```<code>Orange Swisscom Swisscom Salt Sunrise Sunrise Sunrise Salt Free SFR BYTEL
</code>```

For example, in the group

```<code>(1,"F-Bouygues Telecom","BYTEL","20820",7)
</code>```

It's the 'BYTEL' part that is interesting. 'BYTEL' could be also lower-case chars and numbers.

I tried multiple solution but they are all not 100% matching. For the moment, I'm using :

```<code> grep -oP '"([a-zA-z])\w+"'
</code>```

but it would not work in some special cases and is matching also the long alphanumeric operator names (first name between quotes).

答:
This is a pesky format to parse. I came up with

```<code>fugly command |
grep -o '([^()]*)' |
awk -F , 'NF==5 { x=$3; gsub(/\"/, "", x); print x }'
</code>```

which is unsatisfying in some sense, but easy enough to understand I hope.

Demo: https://ideone.com/jH0NKj

Here's a simplified pure Awk variation with slightly different assumptions:

```<code>awk -F , -v RS='(' 'NF>=5 { x=$3; gsub(/\"/, "", x); print x}'
</code>```

Demo: https://ideone.com/UvEXXH

Body:
I'm using a bash script with the AT command AT+COPS=? which returns the following string :

+COPS: (1,"Orange F","Orange","20801",2),(1,"Swisscom","Swisscom","22801",7),(1,"Swisscom","Swisscom","22801",2),(1,"Salt","Salt","22803",2),(1,"Sunrise","Sunrise","22802",2),(1,"Sunrise","Sunrise","22802",7),(1,"Sunrise","Sunrise","22802",0),(2,"Salt","Salt","22803",7),(1,"Free","Free","20815",2),(1,"F SFR","SFR","20810",7),(1,"F-Bouygues Telecom","BYTEL","20820",7),,(0-4),(0-2)

And I'm trying to find a regular expression to match every short alphanumeric operator names. So here, it's :

Orange Swisscom Swisscom Salt Sunrise Sunrise Sunrise Salt Free SFR BYTEL

For example, in the group

(1,"F-Bouygues Telecom","BYTEL","20820",7)

It's the 'BYTEL' part that is interesting. 'BYTEL' could be also lower-case chars and numbers.

I tried multiple solution but they are all not 100% matching. For the moment, I'm using :

 grep -oP '"([a-zA-z])\w+"'

but it would not work in some special cases and is matching also the long alphanumeric operator names (first name between quotes).

Body:
This is a pesky format to parse. I came up with

fugly command |
grep -o '([^()]*)' |
awk -F , 'NF==5 { x=$3; gsub(/\"/, "", x); print x }'

which is unsatisfying in some sense, but easy enough to understand I hope.

Demo: https://ideone.com/jH0NKj

Here's a simplified pure Awk variation with slightly different assumptions:

awk -F , -v RS='(' 'NF>=5 { x=$3; gsub(/\"/, "", x); print x}'

Demo: https://ideone.com/UvEXXH


答:
The code you posted would not throw that error... You don't have an instance of the Builder class, as ->get() returns a Collection. But regardless, modifying a property of a Collection, via $user->role = 'subscriber'; is not valid... You need to loop over $users (name your variables properly) and update each $user:

```<code>$users = User::where('subendsat', '>=', Carbon::now())->get();
foreach ($users as $user) {
  $user->role = 'subscriber';
  $user->save();
}
</code>```

Or call a batch update():

```<code>User::where('subendsat', '>=', Carbon::now())->update([
  'role' => 'subscriber'
]);
</code>```

Title: Call to undefined method Illuminate\Database\Eloquent\Builder::save() when running a Laravel Task Schedule Command

Body:
The code you posted would not throw that error... You don't have an instance of the Builder class, as ->get() returns a Collection. But regardless, modifying a property of a Collection, via $user->role = 'subscriber'; is not valid... You need to loop over $users (name your variables properly) and update each $user:

$users = User::where('subendsat', '>=', Carbon::now())->get();
foreach ($users as $user) {
  $user->role = 'subscriber';
  $user->save();
}

Or call a batch update():

User::where('subendsat', '>=', Carbon::now())->update([
  'role' => 'subscriber'
]);


问:
Update git repository with case-changed files
Due to the per-developer naming convention I had to rename a bunch of files of a laravel app, eg. supplyController.php to SupplyContoller.php. The files are created on windows, so the filesys is case-insensitive, but the production VPS has debian/case-sensitive, so it's important to have the right naming to deploy.

The changes are already committed and pushed, and afaik it's the normal behavior, the git repo contains the lower-case version of files. Beside git mv for each file, is there any better solution recommended to correct the repo?

答:
While git mv will work, it does require you to provide a mapping from fileName to FileName, which can be tedious - and most attempts to automate this would be error-prone.

On the other hand, if you have a clone whose worktree has the desired capitalization, then you can rebuild the index from that worktree.  (It may seem risky to wipe the index in this way; but even if something went wrong, you could easily rebuild the index with reset or, in the absolute worst case, restore from the origin - that being part of the point of distributed source control.)

So with the repo in a clean state (no untracked files that aren't ignored, no unstaged changes, and preferably also no staged-but-uncommitted changes):

```<code>git rm --cached -r -- :/:
git add -- :/:
</code>```

The trick here is simple:  In a case-insensitive configuration, git will understand that the worktree file MyFile is the same as the index entry myFile - so just doing an add doesn't change the name in the index.  But if the index has no matching entry, then the filename case will match what's currently in the worktree.

(It seems like maybe you're saying that's not the behavior you expect; I just re-tested, and at least as of 2.25.0.windows.1 that is the behavior I see.  I don't remember any version that behaved differently.)

Body:
While git mv will work, it does require you to provide a mapping from fileName to FileName, which can be tedious - and most attempts to automate this would be error-prone.

On the other hand, if you have a clone whose worktree has the desired capitalization, then you can rebuild the index from that worktree.  (It may seem risky to wipe the index in this way; but even if something went wrong, you could easily rebuild the index with reset or, in the absolute worst case, restore from the origin - that being part of the point of distributed source control.)

So with the repo in a clean state (no untracked files that aren't ignored, no unstaged changes, and preferably also no staged-but-uncommitted changes):

git rm --cached -r -- :/:
git add -- :/:

The trick here is simple:  In a case-insensitive configuration, git will understand that the worktree file MyFile is the same as the index entry myFile - so just doing an add doesn't change the name in the index.  But if the index has no matching entry, then the filename case will match what's currently in the worktree.

(It seems like maybe you're saying that's not the behavior you expect; I just re-tested, and at least as of 2.25.0.windows.1 that is the behavior I see.  I don't remember any version that behaved differently.)


问:
Is it normal for bokeh serve on Kubernetes to restart periodically?
I have a bokeh dashboard served in a docker container, which is running on kubernetes. I can access my dashboard remotely, no problems. But I noticed my pod containing the bokeh serve code restarts a lot, i.e. 14 times in the past 2 hours. Sometimes the status will come back as 'CrashLoopBackOff' and sometimes it will be 'Running' normally.

My question is, is there something about the way bokeh serve works that requires kubernetes to restart it so frequently? Is it something to do with memory (OOMKilled)?

Here is a section of my describe pod:

```<code>Name:               bokeh-744d4bc9d-5pkzq
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               10.183.226.51/10.183.226.51
Start Time:         Tue, 18 Feb 2020 11:55:44 +0000
Labels:             name=bokeh
                    pod-template-hash=744d4bc9d
Annotations:        kubernetes.io/psp: xyz-privileged-psp
Status:             Running
IP:                 172.30.255.130
Controlled By:      ReplicaSet/bokeh-744d4bc9d
Containers:
  dashboard-application:
    Container ID:   containerd://16d10dc5dd89235b0xyz2b5b31f8e313f3f0bb7efe82a12e00c1f01708e2f894
    Image:          us.icr.io/oss-data-science-np-dal/bokeh:118
    Image ID:       us.icr.io/oss-data-science-np-dal/bokeh@sha256:037a5b52a6e7c792fdxy80b01e29772dbfc33b10e819774462bee650cf0da
    Port:           5006/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Tue, 18 Feb 2020 14:25:36 +0000
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      Tue, 18 Feb 2020 14:15:26 +0000
      Finished:     Tue, 18 Feb 2020 14:23:54 +0000
    Ready:          True
    Restart Count:  17
    Limits:
      cpu:     800m
      memory:  600Mi
    Requests:
      cpu:        600m
      memory:     400Mi
    Liveness:     http-get http://:5006/ delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:    http-get http://:5006/ delay=10s timeout=1s period=3s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-cjhfk (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-cjhfk:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-cjhfk
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 600s
                 node.kubernetes.io/unreachable:NoExecute for 600s
Events:
  Type     Reason     Age                    From                    Message
  ----     ------     ----                   ----                    -------
  Warning  Unhealthy  36m (x219 over 150m)   kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  BackOff    21m (x34 over 134m)    kubelet, 10.183.226.51  Back-off restarting failed container
  Warning  Unhealthy  10m (x72 over 150m)    kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  6m4s (x957 over 150m)  kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  68s (x23 over 147m)    kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
</code>```

I'm new to k8s, so any information you have to spare on this kind of issue will be much appreciated!

答:
If a Container allocates more memory than its limit, the Container becomes a candidate for termination. If the Container continues to consume memory beyond its limit, the Container is terminated. If a terminated Container can be restarted, the kubelet restarts it, as with any other type of runtime failure. This is documented here.

You may have to increase limits and requests in your pod spec. Check the official doc here.

Other way to look at it is to try to optimize your code so that it does not exceed the memory specified in limits.

Body:
I have a bokeh dashboard served in a docker container, which is running on kubernetes. I can access my dashboard remotely, no problems. But I noticed my pod containing the bokeh serve code restarts a lot, i.e. 14 times in the past 2 hours. Sometimes the status will come back as 'CrashLoopBackOff' and sometimes it will be 'Running' normally.

My question is, is there something about the way bokeh serve works that requires kubernetes to restart it so frequently? Is it something to do with memory (OOMKilled)?

Here is a section of my describe pod:

Name:               bokeh-744d4bc9d-5pkzq
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               10.183.226.51/10.183.226.51
Start Time:         Tue, 18 Feb 2020 11:55:44 +0000
Labels:             name=bokeh
                    pod-template-hash=744d4bc9d
Annotations:        kubernetes.io/psp: xyz-privileged-psp
Status:             Running
IP:                 172.30.255.130
Controlled By:      ReplicaSet/bokeh-744d4bc9d
Containers:
  dashboard-application:
    Container ID:   containerd://16d10dc5dd89235b0xyz2b5b31f8e313f3f0bb7efe82a12e00c1f01708e2f894
    Image:          us.icr.io/oss-data-science-np-dal/bokeh:118
    Image ID:       us.icr.io/oss-data-science-np-dal/bokeh@sha256:037a5b52a6e7c792fdxy80b01e29772dbfc33b10e819774462bee650cf0da
    Port:           5006/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Tue, 18 Feb 2020 14:25:36 +0000
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      Tue, 18 Feb 2020 14:15:26 +0000
      Finished:     Tue, 18 Feb 2020 14:23:54 +0000
    Ready:          True
    Restart Count:  17
    Limits:
      cpu:     800m
      memory:  600Mi
    Requests:
      cpu:        600m
      memory:     400Mi
    Liveness:     http-get http://:5006/ delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:    http-get http://:5006/ delay=10s timeout=1s period=3s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-cjhfk (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-cjhfk:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-cjhfk
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 600s
                 node.kubernetes.io/unreachable:NoExecute for 600s
Events:
  Type     Reason     Age                    From                    Message
  ----     ------     ----                   ----                    -------
  Warning  Unhealthy  36m (x219 over 150m)   kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  BackOff    21m (x34 over 134m)    kubelet, 10.183.226.51  Back-off restarting failed container
  Warning  Unhealthy  10m (x72 over 150m)    kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  6m4s (x957 over 150m)  kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  68s (x23 over 147m)    kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)

I'm new to k8s, so any information you have to spare on this kind of issue will be much appreciated!


问:
Maximum Size List in Java
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

```<code>public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}
</code>```

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

答:
Here's a List with a size limit, based on Guava's ForwardingList:

A list which forwards all its method
  calls to another list. Subclasses
  should override one or more methods to
  modify the behavior of the backing
  list as desired per the decorator
  pattern.

Guava has base classes like this for all JDK-5 Collection types. Each of them fulfills the same purpose: making it easy to add value, while delegating all default functionality to the underlying collection.

```<code>public class LimitingList<E> extends ForwardingList<E> {

    private final class LimitingListIterator extends ForwardingListIterator<E> {

        private final ListIterator<E> innerListIterator;

        private LimitingListIterator(final ListIterator<E> innerListIterator) {
            this.innerListIterator = innerListIterator;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void add(final E element) {
            if (inner.size() < maxSize)
                innerListIterator.add(element);
            else
                throw new IndexOutOfBoundsException();
        }

        @Override
        protected ListIterator<E> delegate() {
            return innerListIterator;
        }
    }

    public LimitingList(final int maxSize) {
        this(new ArrayList<E>(), maxSize);
    }

    public LimitingList(final List<E> inner, final int maxSize) {
        super();
        this.inner = inner;
        this.maxSize = maxSize;
    }

    @Override
    public boolean addAll(final Collection<? extends E> collection) {
        boolean changed = false;
        for (final E item : collection) {
            final boolean tmpChanged = add(item);
            changed = changed || tmpChanged;
            if (!tmpChanged)
                break;
        }
        return changed;
    }

    @Override
    public boolean add(final E e) {
        if (inner.size() < maxSize)
            return super.add(e);
        else
            return false;
    }

    @Override
    public ListIterator<E> listIterator() {
        return new LimitingListIterator(inner.listIterator());
    }

    @Override
    public void add(final int index, final E element) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(final int index, final Collection<? extends E> elements) {
        throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<E> listIterator(final int index) {
        return new LimitingListIterator(inner.listIterator(index));
    }

    private final int maxSize;
    private final List<E> inner;

    @Override
    protected List<E> delegate() {
        return inner;
    }

}
</code>```

It delegates all real functionality to an underlying list, which is an ArrayList per default (single argument constructor), but you can also supply (two argument constructor)

Title: Maximum Size List in Java

Body:
It's useful to me to have a data structure in Java that has all the functionality of a List, but has a maximum storage capacity, and drops older data when newer data is added. Conceivably at some point I might want to implement a fixed size Queue which keeps a more general ordering of the data, and drops the old data lowest in that ordering, but that's the for the future.

At the moment I'm implementing it like this:

public class FixedSizeList<T> {

  private final int maxSize;
  private final LinkedList<T> list = new LinkedList<T>();

  public FixedSizeQueue(int maxSize) {
    this.maxSize = maxSize < 0 ? 0 : maxSize;
  }

  public T add(T t) {
    list.add(t);
    return list.size() > maxSize ? list.remove() : null;
  }

  // add remaining methods...

}

Is there either (a) an existing data structure that serves my needs, or (b) a better way of implementing this data structure?

Body:
Here's a List with a size limit, based on Guava's ForwardingList:

A list which forwards all its method
  calls to another list. Subclasses
  should override one or more methods to
  modify the behavior of the backing
  list as desired per the decorator
  pattern.

Guava has base classes like this for all JDK-5 Collection types. Each of them fulfills the same purpose: making it easy to add value, while delegating all default functionality to the underlying collection.

public class LimitingList<E> extends ForwardingList<E> {

    private final class LimitingListIterator extends ForwardingListIterator<E> {

        private final ListIterator<E> innerListIterator;

        private LimitingListIterator(final ListIterator<E> innerListIterator) {
            this.innerListIterator = innerListIterator;
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void add(final E element) {
            if (inner.size() < maxSize)
                innerListIterator.add(element);
            else
                throw new IndexOutOfBoundsException();
        }

        @Override
        protected ListIterator<E> delegate() {
            return innerListIterator;
        }
    }

    public LimitingList(final int maxSize) {
        this(new ArrayList<E>(), maxSize);
    }

    public LimitingList(final List<E> inner, final int maxSize) {
        super();
        this.inner = inner;
        this.maxSize = maxSize;
    }

    @Override
    public boolean addAll(final Collection<? extends E> collection) {
        boolean changed = false;
        for (final E item : collection) {
            final boolean tmpChanged = add(item);
            changed = changed || tmpChanged;
            if (!tmpChanged)
                break;
        }
        return changed;
    }

    @Override
    public boolean add(final E e) {
        if (inner.size() < maxSize)
            return super.add(e);
        else
            return false;
    }

    @Override
    public ListIterator<E> listIterator() {
        return new LimitingListIterator(inner.listIterator());
    }

    @Override
    public void add(final int index, final E element) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean addAll(final int index, final Collection<? extends E> elements) {
        throw new UnsupportedOperationException();
    }

    @Override
    public ListIterator<E> listIterator(final int index) {
        return new LimitingListIterator(inner.listIterator(index));
    }

    private final int maxSize;
    private final List<E> inner;

    @Override
    protected List<E> delegate() {
        return inner;
    }

}

It delegates all real functionality to an underlying list, which is an ArrayList per default (single argument constructor), but you can also supply (two argument constructor)


问:
I don't understand why my object doesn't receive notifications
I've create a custom class that looks like:

class FooDevice: Device {

  private var controller:FooController?
  private var device:Foo?

  override init() {
    super.init()
    if super.authGranted {
      NotificationCenter.default.addObserver(self, selector: #selector(self.discovered(_:)), name: NSNotification.Name(rawValue: FooDiscover), object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(self.connected(_:)), name: NSNotification.Name(rawValue: FooConnected), object: nil)
    }
  }

  @objc private func discovered(_ notification:Notification) {
    DDLogVerbose("FOO - discovered - \(notification)")
    super.scanner?.stopScanFor(._FOO)
    // TODO: Call super.connector and connect
  }

  @objc private func connected(_ notification:Notification) {
    DDLogVerbose("FOO - connected - \(notification)")
    // Do more stuff after connect
  }

  func start() {
    DDLogVerbose("FOO - startMeasurement()")
    super.scanner?.scanFor(._FOO)
  }
}

```

<p>The super class looks like:</p>

<pre class="lang-swift prettyprint-override"><code>class Device: NSObject {

  private let LICENSE = "my_license"

  private var authenticator:SDKAuthenticator?
  internal var scanner:SDKScanner?
  internal var connector:SDKConnector?
  internal var authGranted = false

  override init() {
    super.init()
    authGranted = self.authRequest(LICENSE)
    if authGranted {
      scanner = SDKScanner.getInstance()
      connector = SDKConnector.getInstance()
    } else {
      // TODO: Show error to user
    }
  }

  private func authRequest(_ data:String) -> Bool {
    // Do stuff using authenticator and authenticated, we can assume we return a true
    return status // true
  }
}
</code>```

In my ViewController I make an instance of FooDevice and start the process. I'm doing with the following:

class MyViewController:UIViewController {

 // A lot of properties
 override viewDidLoad() {
   // ViewDidLoad stuff
 }

 @IBAction func connectToDevice(_ sender: Any) {
  // Here I instantiate the object and start the scanning
  let myFooDevice = FooDevice()
  myFooDevice.start()
 }
}
```

In the console I could see how the scanner start and found the bluetooth device but the notification isn't captured and the log isn't printed. Also the notification names are right, I'm sure because the SDK return the strings.

I don't know what I'm missing. Hope you could throw some light to it.

答:
Your problem is that ARC will cleanup your myFooDevice variable before any notification can reach it.

You better store it in a property:

```<code>class MyViewController:UIViewController {

    var myFooDevice:FooDevice?

    override viewDidLoad() {
       // ViewDidLoad stuff
    }

    @IBAction func connectToDevice(_ sender: Any) {
        // Here I instantiate the object and start the scanning
        myFooDevice = FooDevice()
        myFooDevice!.start()
    }
}
</code>```

Body:
I've create a custom class that looks like:

class FooDevice: Device {

  private var controller:FooController?
  private var device:Foo?

  override init() {
    super.init()
    if super.authGranted {
      NotificationCenter.default.addObserver(self, selector: #selector(self.discovered(_:)), name: NSNotification.Name(rawValue: FooDiscover), object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(self.connected(_:)), name: NSNotification.Name(rawValue: FooConnected), object: nil)
    }
  }

  @objc private func discovered(_ notification:Notification) {
    DDLogVerbose("FOO - discovered - \(notification)")
    super.scanner?.stopScanFor(._FOO)
    // TODO: Call super.connector and connect
  }

  @objc private func connected(_ notification:Notification) {
    DDLogVerbose("FOO - connected - \(notification)")
    // Do more stuff after connect
  }

  func start() {
    DDLogVerbose("FOO - startMeasurement()")
    super.scanner?.scanFor(._FOO)
  }
}

The super class looks like:

class Device: NSObject {

  private let LICENSE = "my_license"

  private var authenticator:SDKAuthenticator?
  internal var scanner:SDKScanner?
  internal var connector:SDKConnector?
  internal var authGranted = false

  override init() {
    super.init()
    authGranted = self.authRequest(LICENSE)
    if authGranted {
      scanner = SDKScanner.getInstance()
      connector = SDKConnector.getInstance()
    } else {
      // TODO: Show error to user
    }
  }

  private func authRequest(_ data:String) -> Bool {
    // Do stuff using authenticator and authenticated, we can assume we return a true
    return status // true
  }
}

In my ViewController I make an instance of FooDevice and start the process. I'm doing with the following:

class MyViewController:UIViewController {

 // A lot of properties
 override viewDidLoad() {
   // ViewDidLoad stuff
 }

 @IBAction func connectToDevice(_ sender: Any) {
  // Here I instantiate the object and start the scanning
  let myFooDevice = FooDevice()
  myFooDevice.start()
 }
}

In the console I could see how the scanner start and found the bluetooth device but the notification isn't captured and the log isn't printed. Also the notification names are right, I'm sure because the SDK return the strings.

I don't know what I'm missing. Hope you could throw some light to it.

Body:
Your problem is that ARC will cleanup your myFooDevice variable before any notification can reach it.

You better store it in a property:

class MyViewController:UIViewController {

    var myFooDevice:FooDevice?

    override viewDidLoad() {
       // ViewDidLoad stuff
    }

    @IBAction func connectToDevice(_ sender: Any) {
        // Here I instantiate the object and start the scanning
        myFooDevice = FooDevice()
        myFooDevice!.start()
    }
}


问:
Unable to Resolve Module in React Native App for linked library
I have a problem "Unable to resolve module".

// Please, read the question before publish comments with links for first result from google.

This is the import line where I got the error:

```<code>import Interactor from 'react-native-native-orientation-interactor';
</code>```

What I did:

Create a react-native library

Run npm link inside the library folder

Run npm link react-native-native-orientation-interactor inside a demo react-native app

Add import statement

Got the error with import.

If I press Cmd+B on import statement I can open a file from node_modules folder. Also I can see my library (as a link) inside node_modules.

But I didn't find any solution for me.

Upd1: I added my library as a dependency in package.json

```<code>  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-native-orientation-interactor": "*"
  },
</code>```

答:
If you are able to link your package correctly, and problem still persists.</p>

```<code>From my experience you can do two things to resolve error.
1) Try to install pod in ios/ directory
or
2) Just close the Termianl and re-run
</code>```

Body:
I have a problem "Unable to resolve module".

// Please, read the question before publish comments with links for first result from google.

This is the import line where I got the error:

import Interactor from 'react-native-native-orientation-interactor';

What I did:

Create a react-native library

Run npm link inside the library folder

Run npm link react-native-native-orientation-interactor inside a demo react-native app

Add import statement

Got the error with import.

If I press Cmd+B on import statement I can open a file from node_modules folder. Also I can see my library (as a link) inside node_modules.

But I didn't find any solution for me.

Upd1: I added my library as a dependency in package.json

  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5",
    "react-native-native-orientation-interactor": "*"
  },

Body:
If you are able to link your package correctly, and problem still persists.

From my experience you can do two things to resolve error.
1) Try to install pod in ios/ directory
or
2) Just close the Termianl and re-run


问:
Python can't find the file pip.conf
I can't find the file pip.conf in the path ~/.config/pip/pip.conf  or the path ~/pip/pip.conf. My version of pip is 8.1.2

答:
I am using WSL ubuntu on win10, with only official python3-pip, and cannot find any pip.conf.

I just create ~/.pip/pip.conf, and then it speeds up my sudo pip3 install --upgrade pip!

Title: Python can't find the file pip.conf


问:
Multiple MySQL versions
We have a Linux server running Red Hat Enterprise 3 and MySQL 3.23. This server has a number of websites on it.

We have a new website that we want to put on this server that uses MySQL 4/5. Is it possible to run the two versions of MySQL in parallel?

If so, how?

答:
Yes you can. Of course on of the servers would have to use non-standard port number.

See the documentation http://dev.mysql.com/doc/refman/5.1/en/multiple-unix-servers.html

OwnerDisplayName: Blatfrig

ContentLicense: CC BY-SA 2.5

Title: Multiple MySQL versions

LastEditorDisplayName: Svante


问:
enable working with different timezones
I have an asp.net + c# application that uses System.DateTime.now for logging working hours of employees. the application is online and recently I have users connecting to it from outside of my country.

I have a client that wants his employees working abroad to log their working hours according to their timezone.

All the dates and hours that are documented in the db are not in universal time so I don't want to try and change backwards everything to UTC (I also think that's not applicable).

I'm aware of ways to detect the user's timezone- js and geo-location. the thing is I don't trust the accuracy level of both. in conclusion I thought i'd let the admin define through an interface time-zones and the user will pick the one he wishes to use.

Is this a proper way? What is the best practice for this?
10q very much.

答:
I think your approach of having an admin define the timezones for a group of users makes a lot of sense. You will quite often find that people have the wrong timezone defined on their desktop PCs, adding another complication. If you set it explicitly, you are safe.

I would urge you to use UTC in your database. If you start mixing DateTimes which are from different timezones in the same database this is going to come back to bite you!

Title: enable working with different timezones


问:
Launching a popup via in octobercms backend via javascript
Im trying to figure out how to launch a popup window with a relation widget in the backend using the Ajax framework for Octobercms.

The anchor provides a data-control='popup' option for creating a backend popups. The framework uses a jQuery method to call the backend $.request('onMethodName', { data: {id: id} });.

I've tried to add additional options for example $.request('onMethodname', { data: {id: tempMarker.id,control: 'popup' },control: 'popup',dataControl: 'popup' });

But with no luck. The documentation doesn't say how to do it either. I'm attaching this to a click event for a map marker (img tag) in the backend, a popup should appear to edit the marker data.

答:
This was simple as replacing the $.request('onSomething') with $.popup(handler: 'onSomething')

Found this thanks to https://octobertricks.com/tricks/update-records-from-list-view-in-a-popup


问:
Popup box if a negative number based from formula
I am trying to figure out a script that will popup a box if a number in column F goes negative. I think I may be running into an issue due to the negative number generating from a formula as opposed to someone manually typing it in. Here is the script I have been working with:

```<code>function onEdit(event){
  var sheet = event.source.getActiveSheet().getName()
  var editedCell = event.range.getSheet().getActiveCell();
  if(sheet=="Numbers"){
     if(editedCell.getColumn() == 6 && event.value==-0.1){
        Browser.msgBox('It looks like there is a negative number in Column F.');
  }}}
</code>```

I think it may have something to do with the 'editedcell' function but I am not 100%. Does anyone know of a better script that will popup a box even if a formula is generating a negative number (the value in column F will be a formula that may generate a negative)?

At this point, nothing happens with this code unless I manually type "-1" or some other negative in Column F.

答:
Answer:

The event object returns the range of the cells you edited, not the ones edited by a script or formulae. As well as this, there are a few things you can do to fix or optimise your code.

Code Fixes:

Firstly, you can change your conditional to optimise the script and only make calls when you need them - this I have done with a slightly different conditional order.

As well as this, rather than event.range.getSheet().getActiveCell() you need to specify the values of column F explicitly, and use the getDisplayValues() function as this will also pick up the values if the cell contains a formula:

function onEdit(event) {
  var sheet = event.source.getActiveSheet();
  if (sheet.getName() != "Numbers") {
    return;
  }

  var values = sheet.getRange('F:F').getDisplayValues()

  for (var i = 0; i < values.length; i++) {
    if (values[i] < 0) {
      Browser.msgBox('It looks like there is a negative number in Column F.');
      return;
    }
  }
}
```

References:

Google Apps Script - Event Objects

Google Apps Script - Best Practices

Body:
I am trying to figure out a script that will popup a box if a number in column F goes negative. I think I may be running into an issue due to the negative number generating from a formula as opposed to someone manually typing it in. Here is the script I have been working with:

function onEdit(event){
  var sheet = event.source.getActiveSheet().getName()
  var editedCell = event.range.getSheet().getActiveCell();
  if(sheet=="Numbers"){
     if(editedCell.getColumn() == 6 && event.value==-0.1){
        Browser.msgBox('It looks like there is a negative number in Column F.');
  }}}

I think it may have something to do with the 'editedcell' function but I am not 100%. Does anyone know of a better script that will popup a box even if a formula is generating a negative number (the value in column F will be a formula that may generate a negative)?

At this point, nothing happens with this code unless I manually type "-1" or some other negative in Column F.

Body:
Answer:

The event object returns the range of the cells you edited, not the ones edited by a script or formulae. As well as this, there are a few things you can do to fix or optimise your code.

Code Fixes:

Firstly, you can change your conditional to optimise the script and only make calls when you need them - this I have done with a slightly different conditional order.

As well as this, rather than event.range.getSheet().getActiveCell() you need to specify the values of column F explicitly, and use the getDisplayValues() function as this will also pick up the values if the cell contains a formula:

function onEdit(event) {
  var sheet = event.source.getActiveSheet();
  if (sheet.getName() != "Numbers") {
    return;
  }

  var values = sheet.getRange('F:F').getDisplayValues()

  for (var i = 0; i < values.length; i++) {
    if (values[i] < 0) {
      Browser.msgBox('It looks like there is a negative number in Column F.');
      return;
    }
  }
}

References:

Google Apps Script - Event Objects

Google Apps Script - Best Practices