问:
Using mouse to paint row of characters in ncurses
I'm trying to use ncurses to paint a row of characters on the screen with the mouse. I'm able to distinguish between a BUTTON1_CLICKED event and BUTTON1_RELEASED event on the screen, but haven't figured out how to paint between them.

The following code prints BUTTON1_CLICKED and BUTTON1_RELEASED at their event positions:

```<code>void obstacle_draw(WINDOW * boardWin, int array[LINES][COLS]) {

int ch;
MEVENT event;

keypad(boardWin, TRUE);
mousemask(BUTTON1_CLICKED | BUTTON1_RELEASED | REPORT_MOUSE_POSITION, NULL);
mouseinterval(0);

while(1) {
    ch = wgetch(boardWin);
    if (ch == KEY_MOUSE) {
        getmouse(&event);
        if (event.bstate & BUTTON1_CLICKED) {
            wattron(boardWin, COLOR_PAIR(BLACK_ON_WHITE) | A_REVERSE);
            mvwprintw(boardWin, event.y, event.x, "CLICKED at %d,%d", event.y, event.x);
            wrefresh(boardWin);
        } else if (event.bstate & BUTTON1_RELEASED) {
                wattron(boardWin, COLOR_PAIR(BLACK_ON_WHITE) | A_REVERSE);
            mvwprintw(boardWin, event.y, event.x, "RELEASED at %d,%d", event.y, event.x);
            wrefresh(boardWin);
        }
    }
    if (ch == '\n') {
        break;
    }
}
return;
}
</code>```

Adding the following line before my while loop allows me to paint these coordinates once I've made the first mouse click, and without holding the button. But I can't seem to turn it off (I also don't understand how it works):

```<code>printf("\033[?1003h\n");
</code>```

I feel like I've read every ncurses mouse post on stack overflow. What am I missing?

答:
The mousemask function is used for this:

To make mouse events visible, use the mousemask  function.   This  will
         set  the  mouse events to be reported.  By default, no mouse events are
         reported.  The function will return a mask to  indicate  which  of  the
         specified  mouse events can be reported; on complete failure it returns
         0.  If oldmask is non-NULL, this function fills the indicated  location
         with the previous value of the given window's mouse event mask.

As  a  side  effect,  setting  a  zero mousemask may turn off the mouse
         pointer; setting a nonzero mask may turn it on.  Whether  this  happens
         is device-dependent.

That's actually two questions.  The one specific to ncurses is how to turn the mouse off/on (using printf is guaranteed to provide disappointment).  The other question is how to enable "any event", and is terminal-specific, seen by ncurses as a different initialization string for the mouse.  The terminal descriptions xterm-1002 and xterm-1003 provide examples of this.  The XM capability (which is what ncurses looks at) is described in the user_caps manual page.

Just in case there's a third question, the pros/cons of turning the any-event mode have been mentioned a few times on the bug-ncurses mailing list.

Body:
I'm trying to use ncurses to paint a row of characters on the screen with the mouse. I'm able to distinguish between a BUTTON1_CLICKED event and BUTTON1_RELEASED event on the screen, but haven't figured out how to paint between them.

The following code prints BUTTON1_CLICKED and BUTTON1_RELEASED at their event positions:

void obstacle_draw(WINDOW * boardWin, int array[LINES][COLS]) {

int ch;
MEVENT event;

keypad(boardWin, TRUE);
mousemask(BUTTON1_CLICKED | BUTTON1_RELEASED | REPORT_MOUSE_POSITION, NULL);
mouseinterval(0);

while(1) {
    ch = wgetch(boardWin);
    if (ch == KEY_MOUSE) {
        getmouse(&event);
        if (event.bstate & BUTTON1_CLICKED) {
            wattron(boardWin, COLOR_PAIR(BLACK_ON_WHITE) | A_REVERSE);
            mvwprintw(boardWin, event.y, event.x, "CLICKED at %d,%d", event.y, event.x);
            wrefresh(boardWin);
        } else if (event.bstate & BUTTON1_RELEASED) {
                wattron(boardWin, COLOR_PAIR(BLACK_ON_WHITE) | A_REVERSE);
            mvwprintw(boardWin, event.y, event.x, "RELEASED at %d,%d", event.y, event.x);
            wrefresh(boardWin);
        }
    }
    if (ch == '\n') {
        break;
    }
}
return;
}

Adding the following line before my while loop allows me to paint these coordinates once I've made the first mouse click, and without holding the button. But I can't seem to turn it off (I also don't understand how it works):

printf("\033[?1003h\n");

I feel like I've read every ncurses mouse post on stack overflow. What am I missing?


来源: stackexchange

问:
Angular - Convert vertical scroll to horizontal scroll
I'm currently trying to implement a horizontal scroll. It works, but I'm trying to make some changes:

Since the web-app is a one screener and solely consists of this horizontal scroll, I'd like to convert vertical scroll to horizontal scroll. But how? What's the approach?

I've tried the following js library, but this one solely works if overflow is set to visible, which kind of breaks my app.

My horizontal scroll:

```<code><div class="scroll-container align-self-center d-flex">
    <div class="cart-container align-self-center" *ngFor="let cart of carts; let i = index">
      <div class="cart-item cursor-hover position-relative" [ngStyle]="{'background-image': 'url(' + cart.image + ')'}" [class.cart-item-even]="i % 2 !== 0"
      (mouseenter)="changeBackgroundColor(i)">
        <h1 class="hover-title">{{cart.title}}</h1>
      </div>
    </div>
</div>

CSS:
.cart-item {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  width: 22.5vw;
  height: 65vh;
}

.cart-item-even {
  height: 55vh;
  width: 20vw;
}

.cart-container {
  display: inline-block;
}

.scroll-container {
  padding: 0 15vw 0 15vw;
  box-sizing: border-box;
  overflow: auto;
  white-space: nowrap;
}
</code>```

答:
//ts

scroll = () => {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('main-content').scrollLeft -= (delta*40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('main-content').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('main-content').addEventListener("mousewheel", scrollHorizontally, false);
        // Firefox
        document.getElementById('main-content').addEventListener("DOMMouseScroll", scrollHorizontally, false);
    } else {
        // IE 6/7/8
        // document.getElementById('main-content').attachEvent("onmousewheel", scrollHorizontally);
    }
}

ngOnInit(): void {
    this.scroll();
  }```

ContentLicense: CC BY-SA 4.0

Body:
I'm currently trying to implement a horizontal scroll. It works, but I'm trying to make some changes:

Since the web-app is a one screener and solely consists of this horizontal scroll, I'd like to convert vertical scroll to horizontal scroll. But how? What's the approach?

I've tried the following js library, but this one solely works if overflow is set to visible, which kind of breaks my app.

My horizontal scroll:

{{cart.title}}

CSS:
.cart-item {
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  width: 22.5vw;
  height: 65vh;
}

.cart-item-even {
  height: 55vh;
  width: 20vw;
}

.cart-container {
  display: inline-block;
}

.scroll-container {
  padding: 0 15vw 0 15vw;
  box-sizing: border-box;
  overflow: auto;
  white-space: nowrap;
}


问:
android recyclerview - TextView is not expanding properly with setmaxlines method
I am new to android development. For my learning purpose, I am developing an android application to list the fibonacci numbers in a recycler view. The list gets appended with new numbers as the user scrolls down the recycler view.

The image shows the app displaying the index and respective fibonacci number for the index in the recycler view

This is the layout xml of single item in recycler view.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="false"
    android:focusable="false"
    android:padding="5dp">

    <TextView
        android:id="@+id/info_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

    <TextView
        android:id="@+id/info_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

</LinearLayout>
</code>```

Excerpt from the adaptor class,

```<code>public class ViewHolder extends RecyclerView.ViewHolder {
        final TextView index;
        final TextView value;

        ViewHolder(View itemView) {
            super(itemView);
            index = itemView.findViewById(R.id.info_index);
            value = itemView.findViewById(R.id.info_value);
        }
    }

    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final TextView value = holder.value;
        final TextView index = holder.index;
        value.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                if (value.getMaxLines() == 1000) {
                    value.setMaxLines(1);
                    notifyItemChanged(position);
                } else {
                    value.setMaxLines(1000);
                    notifyItemChanged(position);
                }
            }
        });
        Log.d(TAG, "position-value:" + String.valueOf(position));

        holder.index.setBackgroundColor(Color.WHITE);
        holder.index.setText(String.valueOf(position + 1));
        holder.value.setBackgroundColor(Color.WHITE);
        holder.value.setText(mData.get(position));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            holder.index.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
            holder.value.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        }

    }
</code>```

When I click on the value textview, the textview does not expand on the first click, instead I have to press two times to make it expand. The first time only the flickering happens. I have tried disabling the animator for recyclerview, tried re using the same view in the recycler view, but nothings helps.

My requirement is to expand fibonacci-value textview on click. By default it should be 1 line and when clicked it should show the whole content with multiple lines (as many as required).

currently this happens with two clicks. first time flickering and second time expands.

I believe this is a bug in android code. But just want to confirm here for any solutions that I might have missed.

答:
The reason of the flickering is that, each time an item is clicked, just after setting maxLines, you are calling notifyItemChanged (which is the correct thing to do), but as a result, before redrawing the item onBindViewHolder is called again. So, when it is called again, there should be a way to know current max lines for that item.

Besides, if you try adding lots of items and scroll up and down, you'll see more bugs (since viewholders are reused) Thus, it is important to set/reset maxlines for each item inside onBindViewHolder (but outside click listener)

Secondly, DefaultItemAnimator of RecyclerView uses cross-fade animation when an item changes and by default, it creates two viewholders for that position for cross-fading between the two. So, above, you set a clicklistener on your "value" textview and interfere with the textview inside onClick callback. However,  when you later click and inform adapter that the item is changed, it binds the second viewholder instance. So when you click, your click is consumed with the previous "value" instance, and right afterwards a new instance is bound and you set a new clicklistener to this second viewholder instance.

This is one of many reasons that interfering with viewholder items inside the click listener is error-prone. Sometimes people solve this kind of problems with setTag/getTag but I think it is similarly error-prone as well.

I think the easiest solution is to use a POJO (plain old java object) for each item and include the maxLine state in this POJO. Something like FibonacciItem with fields such as int: index, String: fibonacciNumber, boolean : expanded. Then you will provide the list as a list of FibonacciItems. And inside your click listener, you'll update maxlines of the clicked item. Something like this:

```<code>public void onClick(View v) {
      if (mList.get(position).isExpanded()) {
          mList.get(position).setExpanded(false);
          notifyItemChanged(position);
      } else {
          mList.get(position).setExpanded(true);
          notifyItemChanged(position);
      }
</code>```

}

And inside your onBindViewHolder, (but outside your click listener) you should set max lines for each item according to this value:

```<code>if(mList.get(position).isExpanded(){
    holder.value.setMaxLines(1);
 } else {
    holder.value.setMaxLines(1000);
 }
</code>```

This will solve the issue. Besides, we usually use POJOs (or data classes) for each item in a list. It is easier to manage.

Body:
I am new to android development. For my learning purpose, I am developing an android application to list the fibonacci numbers in a recycler view. The list gets appended with new numbers as the user scrolls down the recycler view.

The image shows the app displaying the index and respective fibonacci number for the index in the recycler view

This is the layout xml of single item in recycler view.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:clickable="false"
    android:focusable="false"
    android:padding="5dp">

    <TextView
        android:id="@+id/info_index"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

    <TextView
        android:id="@+id/info_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#CDD6D5"
        android:gravity="center"
        android:maxLines="1" />

</LinearLayout>

Excerpt from the adaptor class,

public class ViewHolder extends RecyclerView.ViewHolder {
        final TextView index;
        final TextView value;

        ViewHolder(View itemView) {
            super(itemView);
            index = itemView.findViewById(R.id.info_index);
            value = itemView.findViewById(R.id.info_value);
        }
    }

    public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
        final TextView value = holder.value;
        final TextView index = holder.index;
        value.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View v) {
                if (value.getMaxLines() == 1000) {
                    value.setMaxLines(1);
                    notifyItemChanged(position);
                } else {
                    value.setMaxLines(1000);
                    notifyItemChanged(position);
                }
            }
        });
        Log.d(TAG, "position-value:" + String.valueOf(position));

        holder.index.setBackgroundColor(Color.WHITE);
        holder.index.setText(String.valueOf(position + 1));
        holder.value.setBackgroundColor(Color.WHITE);
        holder.value.setText(mData.get(position));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            holder.index.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
            holder.value.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        }

    }

When I click on the value textview, the textview does not expand on the first click, instead I have to press two times to make it expand. The first time only the flickering happens. I have tried disabling the animator for recyclerview, tried re using the same view in the recycler view, but nothings helps.

My requirement is to expand fibonacci-value textview on click. By default it should be 1 line and when clicked it should show the whole content with multiple lines (as many as required).

currently this happens with two clicks. first time flickering and second time expands.

I believe this is a bug in android code. But just want to confirm here for any solutions that I might have missed.

Body:
The reason of the flickering is that, each time an item is clicked, just after setting maxLines, you are calling notifyItemChanged (which is the correct thing to do), but as a result, before redrawing the item onBindViewHolder is called again. So, when it is called again, there should be a way to know current max lines for that item.

Besides, if you try adding lots of items and scroll up and down, you'll see more bugs (since viewholders are reused) Thus, it is important to set/reset maxlines for each item inside onBindViewHolder (but outside click listener)

Secondly, DefaultItemAnimator of RecyclerView uses cross-fade animation when an item changes and by default, it creates two viewholders for that position for cross-fading between the two. So, above, you set a clicklistener on your "value" textview and interfere with the textview inside onClick callback. However,  when you later click and inform adapter that the item is changed, it binds the second viewholder instance. So when you click, your click is consumed with the previous "value" instance, and right afterwards a new instance is bound and you set a new clicklistener to this second viewholder instance.

This is one of many reasons that interfering with viewholder items inside the click listener is error-prone. Sometimes people solve this kind of problems with setTag/getTag but I think it is similarly error-prone as well.

I think the easiest solution is to use a POJO (plain old java object) for each item and include the maxLine state in this POJO. Something like FibonacciItem with fields such as int: index, String: fibonacciNumber, boolean : expanded. Then you will provide the list as a list of FibonacciItems. And inside your click listener, you'll update maxlines of the clicked item. Something like this:

public void onClick(View v) {
      if (mList.get(position).isExpanded()) {
          mList.get(position).setExpanded(false);
          notifyItemChanged(position);
      } else {
          mList.get(position).setExpanded(true);
          notifyItemChanged(position);
      }

}

And inside your onBindViewHolder, (but outside your click listener) you should set max lines for each item according to this value:

if(mList.get(position).isExpanded(){
    holder.value.setMaxLines(1);
 } else {
    holder.value.setMaxLines(1000);
 }

This will solve the issue. Besides, we usually use POJOs (or data classes) for each item in a list. It is easier to manage.


问:
Best way to implement HTML5 video
I understand that HTML5 video is way more complicated than its proponents would like us to believe. Safari uses the proprietary H.264 codec, whereas Firefox, Chrome and Opera all support the open-source Theora. Internet Explorer doesn't support either, so needs a fallback, such as .mov or Flash.

I found a superb guide somewhere that put together a step-by-step guide for HTML5 on all these browsers, but I can't find it anywhere. Very annoying :(

What's the best way to implement HTML5 video so that all these browsers are covered? (Unfortunately, Flash is not an option.)

Edit: Ok, from what I've read, here is my own answer: This is the best way to implement HTML 5 video...

```<code>    <video id="video" width="450" height="170" preload="auto" autoplay="autoplay">
        <source src="../static/video/video.mp4" />
        <source src="../static/video/video.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/video.ogv" type='video/ogg; codecs="theora, vorbis"' />
        <!-- Fallback (either Flash, an image, or a "Video not supported" message, etc.) -->
    </video>
</code>```

It's the only way that's worked as expected on every browser so far. Unfortunately autoplay doesn't seem to be working in Chrome? :(

Update: Chrome doesn't support Autoplay. Update update: Autoplay works with the "muted" attribute.

答:
So if Flash is not an option, you've not said why but I suppose that doesn't matter, what is aceptable for IE? Are you happy to supply no video at all for IE, or what is it you want?

The examples given above are all good and valid. Where the Flash option has been entered, you can replace that with whatever you want, an image, some text informing the user that their browser isn't supported and provide them with a link to the video to download instead. Whatever you want really as basically the browser will ignore anything it doesn't understand until it gets to something that it does.

Title: Best way to implement HTML5 video

Body:
I understand that HTML5 video is way more complicated than its proponents would like us to believe. Safari uses the proprietary H.264 codec, whereas Firefox, Chrome and Opera all support the open-source Theora. Internet Explorer doesn't support either, so needs a fallback, such as .mov or Flash.

I found a superb guide somewhere that put together a step-by-step guide for HTML5 on all these browsers, but I can't find it anywhere. Very annoying :(

What's the best way to implement HTML5 video so that all these browsers are covered? (Unfortunately, Flash is not an option.)

Edit: Ok, from what I've read, here is my own answer: This is the best way to implement HTML 5 video...

    <video id="video" width="450" height="170" preload="auto" autoplay="autoplay">
        <source src="../static/video/video.mp4" />
        <source src="../static/video/video.webm" type='video/webm; codecs="vp8, vorbis"' />
        <source src="../static/video/video.ogv" type='video/ogg; codecs="theora, vorbis"' />

    </video>

It's the only way that's worked as expected on every browser so far. Unfortunately autoplay doesn't seem to be working in Chrome? :(

Update: Chrome doesn't support Autoplay. Update update: Autoplay works with the "muted" attribute.

ContentLicense: CC BY-SA 3.0


问:
How to create two functions with the same name and different return type and runned based on boolean parameter
I have two functions with the same name but different return types. I want to run the function based on their third parameter. If the third parameter is true I want to run the first and If the parameter is false to run the second function. I was trying different things on my own because I couldn't find information online and I wasn't sure how is this called. Here is what I tried to do:

```<code>static int function(int a, int b, const bool=true);
static std::string function(int a, int b, const bool=false);
</code>```

I would be grateful if someone can explain how to do this or at least give me a link to some information.

答:
This solution is not about having two different functions but if you wanted the function to return a different type depending on the bool value using boost::any.

```<code>boost::any function(int a, int b, const bool c) {
    std::string str = "Hello world!";
    int num = 10;

    if ( c ) {
        return boost::any(num);
    } else {
        return boost::any(str);
    }
}
</code>```

This would use the third parameter in the function in order to decide which return you should do. Depending on how big function is this might be a worse solution but if you really wanted to use a boolean as a parameter I believe this should work.

Docs: Boost

Related question to this answer: Function which returns an unknown type

Body:
I have two functions with the same name but different return types. I want to run the function based on their third parameter. If the third parameter is true I want to run the first and If the parameter is false to run the second function. I was trying different things on my own because I couldn't find information online and I wasn't sure how is this called. Here is what I tried to do:

static int function(int a, int b, const bool=true);
static std::string function(int a, int b, const bool=false);

I would be grateful if someone can explain how to do this or at least give me a link to some information.

Body:
This solution is not about having two different functions but if you wanted the function to return a different type depending on the bool value using boost::any.

boost::any function(int a, int b, const bool c) {
    std::string str = "Hello world!";
    int num = 10;

    if ( c ) {
        return boost::any(num);
    } else {
        return boost::any(str);
    }
}

This would use the third parameter in the function in order to decide which return you should do. Depending on how big function is this might be a worse solution but if you really wanted to use a boolean as a parameter I believe this should work.

Docs: Boost

Related question to this answer: Function which returns an unknown type


问:
React Transition Group not applying classes
I'm using React Transition Group to animate each item with diffrent timeout. The problem is that my links did not receive any classes. However when I wrap ScollLinks tag by TransitionGroup, the animation will work, but the console displays warnings. I have no idea where is the problem.

Props param receive the object with boolean property.

```<code>const NavItems = (props) => {
 const items = ["section1", "section2", "section3", "section4", "section5"];

 return (
  <>
  <NavItemsOverlay open={props.open} />

  <ScollLinks open={props.open}>
    <TransitionGroup component={null}>
      {items.map((item, index) => {
        return (
          <CSSTransition
            in={props.open}
            key={index}
            timeout={{
              enter: 100 * index,
              exit: 0,
            }}
            classNames="fade"
            unmountOnExit >
            <Link>{item}</Link>
          </CSSTransition>
        );
      })}
    </TransitionGroup>
  </ScollLinks>
 </>
 );
};
</code>```

答:
Declare your items outside of the TransitionGroup like this:

const NavItems = (props) => {
  const items = ["section1", "section2", "section3", "section4", "section5"];
  const itemsList = items.map((item, index) => {
    return (
      <CSSTransition
        in={props.open}
        key={index}
        timeout={{
          enter: 100 * index,
          exit: 0,
        }}
        classNames="fade"
        unmountOnExit
      >
        <Link>{item}</Link>
      </CSSTransition>
    );
  });
  return (
    <>
      <NavItemsOverlay open={props.open} />

      <ScollLinks open={props.open}>
        <TransitionGroup component={null}>{itemsList}</TransitionGroup>
      </ScollLinks>
    </>
  );
};
```

Body:
I'm using React Transition Group to animate each item with diffrent timeout. The problem is that my links did not receive any classes. However when I wrap ScollLinks tag by TransitionGroup, the animation will work, but the console displays warnings. I have no idea where is the problem.

Props param receive the object with boolean property.

const NavItems = (props) => {
 const items = ["section1", "section2", "section3", "section4", "section5"];

 return (
  <>
  <NavItemsOverlay open={props.open} />

  <ScollLinks open={props.open}>
    <TransitionGroup component={null}>
      {items.map((item, index) => {
        return (
          <CSSTransition
            in={props.open}
            key={index}
            timeout={{
              enter: 100 * index,
              exit: 0,
            }}
            classNames="fade"
            unmountOnExit >
            <Link>{item}</Link>
          </CSSTransition>
        );
      })}
    </TransitionGroup>
  </ScollLinks>
 </>
 );
};


问:
TortoiseGit asks me for a password when I try to Push
I am using TortoiseGit (latest version) on Windows10. I installed Git as well. My company uses GitLab.

I downloaded the files from GitLab, set up a directory on my Xampp server and started to make change on the website.

Then setup the repository on my Xampp project folder and tried to use TortoiseGit.

I manage to commit changes but when I want to Push TortoiseGit asks me for  git@dev.cobweb.biz password although I use SSH key.

I haven't setup any password during the installation TortoiseGit and it never ask me to set up a password. I don't understand what password I am asking for when I hit Sync - Push.

I setup Putty keygen and added it's path in settings.
My URL is correct: http://dev.cobweb.biz:2380
Push URL is correct as well: ssh://git@dev.cobweb.biz:2323/upwork/drinkrosevibes.com.git

Please help me as I can't push the commits and actually I can't do my job.

答:
It asks for a password, because TortoiseGit does not find your SSH key.

No key means: fallback to the next authentication method: the remote account password (the one for git, which you don't have and should never have)

Make sure you have:

register your public key on Your GitLab reunning on dev.cobweb.biz

put our putty key associated to your origin SSH URL, as seen in this tutorial

<img src="https://i.stack.imgur.com/W9CjI.png" alt="https://p13.zdusercontent.com/attachment/205656/PkK2R6Z4dtQYzXaBUrcEeEVvK?token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..E6Bn4yhz4IVbXhTIJiPV4A.4ZsG9H_MCTg26SOJ07JIe49KVm6wfgWLnOy7EgbqDdvtURYBPopjAJ-reWuUp28sVb87WeNN39bjJuhsg4qWa-nPC4MKeo_RFjv_cfcBCLAzwxDyyRs33fE_YL1kDwmtjGcSJkE37PoafIObvszA42K9pDLtAUSm8IvNkgkYm4vfr2Z3cWORks23cnTlyGORJTvhCx8-rXnMyMEuFNPyjKWbnsbyt_XOaZYP5f3ab-Fe23iT2VpwuLb9zqgZpWtJ1gbXVtNDCOqrk71jle_7XA.xGLcUNqn0Yog-zxKWg9P6w">

For the pull URL, make sure to use the full HTTP URL:

```<code>http://dev.cobweb.biz:2380/upwork/drinkrosevibes.com.git
</code>```

(not just http://dev.cobweb.biz:2380/, which is the URL if the server, not of the repository on that server)

Body:
It asks for a password, because TortoiseGit does not find your SSH key.

No key means: fallback to the next authentication method: the remote account password (the one for git, which you don't have and should never have)

Make sure you have:

register your public key on Your GitLab reunning on dev.cobweb.biz

put our putty key associated to your origin SSH URL, as seen in this tutorial

<img src="https://i.stack.imgur.com/W9CjI.png" alt="https://p13.zdusercontent.com/attachment/205656/PkK2R6Z4dtQYzXaBUrcEeEVvK?token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..E6Bn4yhz4IVbXhTIJiPV4A.4ZsG9H_MCTg26SOJ07JIe49KVm6wfgWLnOy7EgbqDdvtURYBPopjAJ-reWuUp28sVb87WeNN39bjJuhsg4qWa-nPC4MKeo_RFjv_cfcBCLAzwxDyyRs33fE_YL1kDwmtjGcSJkE37PoafIObvszA42K9pDLtAUSm8IvNkgkYm4vfr2Z3cWORks23cnTlyGORJTvhCx8-rXnMyMEuFNPyjKWbnsbyt_XOaZYP5f3ab-Fe23iT2VpwuLb9zqgZpWtJ1gbXVtNDCOqrk71jle_7XA.xGLcUNqn0Yog-zxKWg9P6w">

For the pull URL, make sure to use the full HTTP URL:

http://dev.cobweb.biz:2380/upwork/drinkrosevibes.com.git

(not just http://dev.cobweb.biz:2380/, which is the URL if the server, not of the repository on that server)


问:
Update RTC on STM32F4 when flashing the uC
Is there a way to update the RTC with computer information when the program is uploaded on the STM32F4 ? For example, the information of date and hour on the computer is: 12h40 11/09/2018, and when I flash the microcontroler with IAR/AC6, then the RTC is set whith these pieces of information ?</p>

答:
You can modify most port registers through SWD (or JTAG) in the same way as flash and RAM addresses.

Maybe some of the budget-class debug adapters lack a scriptable option, but at least the mainstream range of adapters allows you to write values to any address the CPU can reach through the internal buses (AHB, APBx etc.).
If you read the reference manual carefully, you can at least find out the raw addresses (and bit patterns) of the registers you have to assign.
If you are lucky, the software tools of your debug adapter even provide you a feature where you can do this with lots of syntactic sugar - without having to dive into the manuals.


问:
Writing JUnit tests for Kafka Consumer
I have a kafka consumer which is subscribing on a topic. Implementation is working fine. But when trying to implement unit tests for that, there's a problem because of it's implementing by Runnable interface.

Implementation

```<code>@Override
public void run() {
    kafkaConsumer.subscribe(kafkaTopics);

    while (true) {
        ConsumerRecords<String, String> records = kafkaConsumer.poll(1000);
        Map<String, InventoryStock> skuMap = new LinkedHashMap<>();

        try {
            // populating sku map with consumer record
            for (ConsumerRecord<String, String> record : records) {
                populateMap(skuMap, record.value());
            }

            if (MapUtils.isNotEmpty(skuMap)) {
                // writing sku inventory with populated sku map
                inventoryDao.updateInventoryTable(INVENTORY_JOB_ID, skuMap);
            }
        } catch (Exception e) {

        }
        kafkaConsumer.commitAsync();
    }
}
</code>```

I tried to implement the tests using MockConsumer. But it needs to be assigned to the consumer in implementation. But consumer in implementation doesn't expose out side. Here what I tried.

```<code>@Before
public void onBefore() {
    MockitoAnnotations.initMocks(this);

    Properties consumerProps = new Properties();
    consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
    consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

    consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
    skuInventoryConsumer = new SkuInventoryConsumer(consumerProps);

    KafkaConsumer kafkaConsumerMock = mock(KafkaConsumer.class);

    Whitebox.setInternalState(skuInventoryConsumer, "LOGGER", LOGGER);
    Whitebox.setInternalState(skuInventoryConsumer, "kafkaConsumer", kafkaConsumerMock);

}

@Test
public void should_subscribe_on_topic() {
    consumer.assign(Arrays.asList(new TopicPartition("my_topic", 0)));

    HashMap<TopicPartition, Long> beginningOffsets = new HashMap<>();
    beginningOffsets.put(new TopicPartition("my_topic", 0), 0L);
    consumer.updateBeginningOffsets(beginningOffsets);

    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 0L, "mykey", "myvalue0"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 1L, "mykey", "myvalue1"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 2L, "mykey", "myvalue2"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 3L, "mykey", "myvalue3"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 4L, "mykey", "myvalue4"));
}
</code>```

Since it's a runnable and consumer is not exposed this test not working as expected. How may I fix this?

答:
I would suggest to use Mockito, like below sample</p>
```<code>Consumer<String, String> kafkaConsumerLocal = mock(Consumer.class);
KafkaConsumer kafkaConsumer = spy(new KafkaConsumer("topic-name"));

ReflectionTestUtils.setField(kafkaConsumer, "threadPoolCount", 1);
ReflectionTestUtils.setField(kafkaConsumer, "consumer", kafkaConsumerLocal);

doNothing().when(kafkaConsumer).runConsumer();
doNothing().when(kafkaConsumer).addShutDownHook();
doReturn(kafkaConsumerLocal).when(consumerInit).getKafkaConsumer();
</code>```

Title: Writing JUnit tests for Kafka Consumer

Body:
I have a kafka consumer which is subscribing on a topic. Implementation is working fine. But when trying to implement unit tests for that, there's a problem because of it's implementing by Runnable interface.

Implementation

@Override
public void run() {
    kafkaConsumer.subscribe(kafkaTopics);

    while (true) {
        ConsumerRecords<String, String> records = kafkaConsumer.poll(1000);
        Map<String, InventoryStock> skuMap = new LinkedHashMap<>();

        try {
            // populating sku map with consumer record
            for (ConsumerRecord<String, String> record : records) {
                populateMap(skuMap, record.value());
            }

            if (MapUtils.isNotEmpty(skuMap)) {
                // writing sku inventory with populated sku map
                inventoryDao.updateInventoryTable(INVENTORY_JOB_ID, skuMap);
            }
        } catch (Exception e) {

        }
        kafkaConsumer.commitAsync();
    }
}

I tried to implement the tests using MockConsumer. But it needs to be assigned to the consumer in implementation. But consumer in implementation doesn't expose out side. Here what I tried.

@Before
public void onBefore() {
    MockitoAnnotations.initMocks(this);

    Properties consumerProps = new Properties();
    consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
    consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

    consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
    skuInventoryConsumer = new SkuInventoryConsumer(consumerProps);

    KafkaConsumer kafkaConsumerMock = mock(KafkaConsumer.class);

    Whitebox.setInternalState(skuInventoryConsumer, "LOGGER", LOGGER);
    Whitebox.setInternalState(skuInventoryConsumer, "kafkaConsumer", kafkaConsumerMock);

}

@Test
public void should_subscribe_on_topic() {
    consumer.assign(Arrays.asList(new TopicPartition("my_topic", 0)));

    HashMap<TopicPartition, Long> beginningOffsets = new HashMap<>();
    beginningOffsets.put(new TopicPartition("my_topic", 0), 0L);
    consumer.updateBeginningOffsets(beginningOffsets);

    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 0L, "mykey", "myvalue0"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 1L, "mykey", "myvalue1"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 2L, "mykey", "myvalue2"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 3L, "mykey", "myvalue3"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 4L, "mykey", "myvalue4"));
}

Since it's a runnable and consumer is not exposed this test not working as expected. How may I fix this?

Body:
I would suggest to use Mockito, like below sample

Consumer<String, String> kafkaConsumerLocal = mock(Consumer.class);
KafkaConsumer kafkaConsumer = spy(new KafkaConsumer("topic-name"));

ReflectionTestUtils.setField(kafkaConsumer, "threadPoolCount", 1);
ReflectionTestUtils.setField(kafkaConsumer, "consumer", kafkaConsumerLocal);

doNothing().when(kafkaConsumer).runConsumer();
doNothing().when(kafkaConsumer).addShutDownHook();
doReturn(kafkaConsumerLocal).when(consumerInit).getKafkaConsumer();


问:
Python Spacy KeyError: "[E018] Can't retrieve string for hash
I am trying to make my code run on Raspberry Pi 4 and been stuck on this error for hours. This code segment throws an error on it but runs perfectly on windows with the same project

def create_lem_texts(data):  # as a list
    def sent_to_words(sentences):
        for sentence in sentences:
            yield (gensim.utils.simple_preprocess(str(sentence), deacc=True))  # deacc=True removes punctuations

```<code>data_words = list(sent_to_words(data))
bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100)  # higher threshold fewer phrases.
bigram_mod = gensim.models.phrases.Phraser(bigram)

def remove_stopwords(texts):
    return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]

def make_bigrams(texts):
    return [bigram_mod[doc] for doc in texts]

def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):
    """https://spacy.io/api/annotation"""
    texts_out = []
    print(os.getcwd())
    for sent in texts:
        doc = nlp(" ".join(sent))
        texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
    return texts_out

data_words_nostops = remove_stopwords(data_words)
data_words_bigrams = make_bigrams(data_words_nostops)
print(os.getcwd())
nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])

# Do lemmatization keeping only noun, adj, vb, adv
data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])

return data_lemmatized
</code>```

This code is in turned called by this function:

```<code>def assign_topics_tweet(tweets):
owd = os.getcwd()
print(owd)
os.chdir('/home/pi/Documents/pycharm_project_twitter/topic_model/')
print(os.getcwd())
lda = LdaModel.load("LDA26")
print(lda)
id2word = Dictionary.load('Id2Word')
print(id2word)
os.chdir(owd)
data = create_lem_texts(tweets)
corpus = [id2word.doc2bow(text) for text in data]
topics = []
for tweet in corpus:
    topics_dist = lda.get_document_topics(tweet)
    topics.append(topics_dist)
return topics
</code>```

And here is the error message

```<code>    Traceback (most recent call last):
  File "/home/pi/Documents/pycharm_project_twitter/Twitter_Import.py", line 193, in <module>
    main()
  File "/home/pi/Documents/pycharm_project_twitter/Twitter_Import.py", line 169, in main
    topics = assign_topics_tweet(data)
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 238, in assign_topics_tweet
    data = create_lem_texts(tweets)
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 76, in create_lem_texts
    data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 67, in lemmatization
    texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 67, in <listcomp>
    texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
  File "token.pyx", line 871, in spacy.tokens.token.Token.lemma_.__get__
  File "strings.pyx", line 136, in spacy.strings.StringStore.__getitem__
KeyError: "[E018] Can't retrieve string for hash '18446744073541552667'. This usually refers to an issue with the `Vocab` or `StringStore`."

Process finished with exit code 1
</code>```

I tried reinstalling spacy and the en model, running it directly on pi, spacy versions are the same on both my windows machine and on the Pi. And there is basically no information online on this error

答: After three days of testing problem was solved by simply installing an older version of Spacy 2.0.1</p>

Body:
I am trying to make my code run on Raspberry Pi 4 and been stuck on this error for hours. This code segment throws an error on it but runs perfectly on windows with the same project

def create_lem_texts(data):  # as a list
    def sent_to_words(sentences):
        for sentence in sentences:
            yield (gensim.utils.simple_preprocess(str(sentence), deacc=True))  # deacc=True removes punctuations

data_words = list(sent_to_words(data))
bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100)  # higher threshold fewer phrases.
bigram_mod = gensim.models.phrases.Phraser(bigram)

def remove_stopwords(texts):
    return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]

def make_bigrams(texts):
    return [bigram_mod[doc] for doc in texts]

def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):
    """https://spacy.io/api/annotation"""
    texts_out = []
    print(os.getcwd())
    for sent in texts:
        doc = nlp(" ".join(sent))
        texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
    return texts_out

data_words_nostops = remove_stopwords(data_words)
data_words_bigrams = make_bigrams(data_words_nostops)
print(os.getcwd())
nlp = spacy.load('en_core_web_sm', disable=['parser', 'ner'])

# Do lemmatization keeping only noun, adj, vb, adv
data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])

return data_lemmatized

This code is in turned called by this function:

def assign_topics_tweet(tweets):
owd = os.getcwd()
print(owd)
os.chdir('/home/pi/Documents/pycharm_project_twitter/topic_model/')
print(os.getcwd())
lda = LdaModel.load("LDA26")
print(lda)
id2word = Dictionary.load('Id2Word')
print(id2word)
os.chdir(owd)
data = create_lem_texts(tweets)
corpus = [id2word.doc2bow(text) for text in data]
topics = []
for tweet in corpus:
    topics_dist = lda.get_document_topics(tweet)
    topics.append(topics_dist)
return topics

And here is the error message

    Traceback (most recent call last):
  File "/home/pi/Documents/pycharm_project_twitter/Twitter_Import.py", line 193, in <module>
    main()
  File "/home/pi/Documents/pycharm_project_twitter/Twitter_Import.py", line 169, in main
    topics = assign_topics_tweet(data)
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 238, in assign_topics_tweet
    data = create_lem_texts(tweets)
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 76, in create_lem_texts
    data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 67, in lemmatization
    texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
  File "/home/pi/Documents/pycharm_project_twitter/TopicModel.py", line 67, in <listcomp>
    texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
  File "token.pyx", line 871, in spacy.tokens.token.Token.lemma_.__get__
  File "strings.pyx", line 136, in spacy.strings.StringStore.__getitem__
KeyError: "[E018] Can't retrieve string for hash '18446744073541552667'. This usually refers to an issue with the `Vocab` or `StringStore`."

Process finished with exit code 1

I tried reinstalling spacy and the en model, running it directly on pi, spacy versions are the same on both my windows machine and on the Pi. And there is basically no information online on this error


问:
Output on more rows in R
I have a text inside a dataframe that does not fit in the page I get doing the report. Is there a way to display it on more rows?

As an example

```<code>This sentence is way to long to fit on one row, it would be a lot better having it on multiple lines, like two, three, or maybe four
</code>```

Should be output like:

```<code>This sentence is way to long to fit on one row,
it would be a lot better having it on multiple lines, like two,
three, or maybe four
</code>```

答:
We can use str_wrap

```<code>library(stringr)
cat(str_wrap(str1, width = 40))
This sentence is way to long to fit on
one row, it would be a lot better having
it on multiple lines, like two, three,
or maybe four
</code>```

Or it can be split

```<code>strsplit(str_wrap(str1, width = 40), '\n')[[1]]
</code>```

data

```<code>str1 <- "This sentence is way to long to fit on one row, it would be a lot better having it on multiple lines, like two, three, or maybe four"
</code>```

Title: Output on more rows in R

Body:
I have a text inside a dataframe that does not fit in the page I get doing the report. Is there a way to display it on more rows?

As an example

This sentence is way to long to fit on one row, it would be a lot better having it on multiple lines, like two, three, or maybe four

Should be output like:

This sentence is way to long to fit on one row,
it would be a lot better having it on multiple lines, like two,
three, or maybe four

Body:
We can use str_wrap

library(stringr)
cat(str_wrap(str1, width = 40))
This sentence is way to long to fit on
one row, it would be a lot better having
it on multiple lines, like two, three,
or maybe four

Or it can be split

strsplit(str_wrap(str1, width = 40), '\n')[[1]]

data

str1 <- "This sentence is way to long to fit on one row, it would be a lot better having it on multiple lines, like two, three, or maybe four"


问:
Unexpected application shutdown
I have tried to launch this code, in order to print lines onTouch. The code contains no error, but when i launch it...the emulator shutdown unexpectedly. Can you help me figure out the problem?

```<code>import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class Usama3 extends Activity {

        ImageView imageView;
        Bitmap bitmap;
        Canvas canvas;
        Paint paint;

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) this.findViewById(R.id.imageView11);

        Display currentDisplay = getWindowManager().getDefaultDisplay();
        float dw = currentDisplay.getWidth();
        float dh = currentDisplay.getHeight();
        bitmap = Bitmap.createBitmap((int)dw,(int)dh,Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        paint = new Paint();
        paint.setColor(Color.GREEN);
        imageView.setImageBitmap(bitmap);
        imageView.setOnTouchListener((OnTouchListener) this);

        }
        public boolean onTouch(View v, MotionEvent event) {

        int action = event.getAction();
        float upx;
        float upy;
        float downy = 0;
        float downx = 0;
        switch (action)
        {
            case MotionEvent.ACTION_MOVE:
            upx = event.getX();
            upy = event.getY();
            canvas.drawLine(downx, downy, upx, upy, paint);
            imageView.invalidate();
            downx = upx;
            downy = upy;
            break;
        }
        return false;
}

}
</code>```

I will be really thankful

答: Check Usama3 is in your AndroidManifest.  You might also need to have the activity speficifally implement OnTouchListener instead of trying to class cast this.  The Android Developers site has a section on debugging that you might find useful to read.

Title: Unexpected application shutdown

Body:
I have tried to launch this code, in order to print lines onTouch. The code contains no error, but when i launch it...the emulator shutdown unexpectedly. Can you help me figure out the problem?

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;

public class Usama3 extends Activity {

        ImageView imageView;
        Bitmap bitmap;
        Canvas canvas;
        Paint paint;

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) this.findViewById(R.id.imageView11);

        Display currentDisplay = getWindowManager().getDefaultDisplay();
        float dw = currentDisplay.getWidth();
        float dh = currentDisplay.getHeight();
        bitmap = Bitmap.createBitmap((int)dw,(int)dh,Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        paint = new Paint();
        paint.setColor(Color.GREEN);
        imageView.setImageBitmap(bitmap);
        imageView.setOnTouchListener((OnTouchListener) this);

        }
        public boolean onTouch(View v, MotionEvent event) {

        int action = event.getAction();
        float upx;
        float upy;
        float downy = 0;
        float downx = 0;
        switch (action)
        {
            case MotionEvent.ACTION_MOVE:
            upx = event.getX();
            upy = event.getY();
            canvas.drawLine(downx, downy, upx, upy, paint);
            imageView.invalidate();
            downx = upx;
            downy = upy;
            break;
        }
        return false;
}

}

I will be really thankful


问:
How do deploy a site on netlify thats build with webpack commands?
I am trying to deploy my site on netlify. But every time I run npm run build no build folder is created.

```<code>"build": "webpack --mode production"
</code>```

Is the command I'm using

I got the site to deploy but nothing loads I've been stuck on this for hours can someone please help?

The webpack file is below.

Apparently webpack builds a dist folder instead of a build folder so I will set my netlify to publish directory to it and see what happens

Update it worked!

```<code>const HtmlWebPackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');
// const outputPath = path.join(__dirname, "dist");
const extractSass = new ExtractTextPlugin({
  filename: '[name].[hash].css',
  disable: process.env.NODE_ENV === 'development',
});
module.exports = {
  mode: 'production',
  entry: { app: './src/index.js' },
  output: {
    filename: '[name].[hash].js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.(png|jpg|gif)$/,
        // exclude: /node_modules/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: "[path]/[name].[ext]",
              outputPath: './assets/img/',
              context: 'src/assets/img/',
            },
          },
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
                quality: 70,
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false,
              },
              pngquant: {
                quality: '70-90',
                speed: 4,
              },
              gifsicle: {
                interlaced: false,
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75,
              },
            },
          },
        ],
      },
      {
        test: /\.(woff|woff2|eot|ttf|svg)$/,
        loader: 'file-loader',
        options: {
          name: "./[name].[ext]",
          outputPath: './assets/fonts/'
        },
      },
      {
        test: /\.html$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'html-loader',
            options: { minimize: true },
          },
        ],
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: extractSass.extract({
          use: [
            {
              loader: 'css-loader',
            },
            {
              loader: 'sass-loader',
            },
          ],
          // use style-loader in development
          fallback: 'style-loader',
        }),
      },
      {
        test: /\.css$/,
        use: extractSass.extract({
          fallback: 'style-loader',
          use: 'css-loader',
        }),
      },
    ],
  },
  devServer: {
    contentBase: './dist',
    historyApiFallback: true,
    hot: true
  },
  plugins: [
    extractSass,
    // new ExtractTextPlugin('[name].[hash].css'),
    new HtmlWebPackPlugin({
      template: './src/index.html',
      filename: './index.html',
    }),
    new CleanWebpackPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'all',
        },
      },
    },
  },
};
</code>```

答: set netlify build directory to dist with webpack</p>

Body:
I am trying to deploy my site on netlify. But every time I run npm run build no build folder is created.

"build": "webpack --mode production"

Is the command I'm using

I got the site to deploy but nothing loads I've been stuck on this for hours can someone please help?

The webpack file is below.

Apparently webpack builds a dist folder instead of a build folder so I will set my netlify to publish directory to it and see what happens

Update it worked!

const HtmlWebPackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const webpack = require('webpack');
// const outputPath = path.join(__dirname, "dist");
const extractSass = new ExtractTextPlugin({
  filename: '[name].[hash].css',
  disable: process.env.NODE_ENV === 'development',
});
module.exports = {
  mode: 'production',
  entry: { app: './src/index.js' },
  output: {
    filename: '[name].[hash].js',
    publicPath: '/'
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
      {
        test: /\.(png|jpg|gif)$/,
        // exclude: /node_modules/,
        use: [
          {
            loader: 'file-loader',
            options: {
              name: "[path]/[name].[ext]",
              outputPath: './assets/img/',
              context: 'src/assets/img/',
            },
          },
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpeg: {
                progressive: true,
                quality: 70,
              },
              // optipng.enabled: false will disable optipng
              optipng: {
                enabled: false,
              },
              pngquant: {
                quality: '70-90',
                speed: 4,
              },
              gifsicle: {
                interlaced: false,
              },
              // the webp option will enable WEBP
              webp: {
                quality: 75,
              },
            },
          },
        ],
      },
      {
        test: /\.(woff|woff2|eot|ttf|svg)$/,
        loader: 'file-loader',
        options: {
          name: "./[name].[ext]",
          outputPath: './assets/fonts/'
        },
      },
      {
        test: /\.html$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'html-loader',
            options: { minimize: true },
          },
        ],
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        use: extractSass.extract({
          use: [
            {
              loader: 'css-loader',
            },
            {
              loader: 'sass-loader',
            },
          ],
          // use style-loader in development
          fallback: 'style-loader',
        }),
      },
      {
        test: /\.css$/,
        use: extractSass.extract({
          fallback: 'style-loader',
          use: 'css-loader',
        }),
      },
    ],
  },
  devServer: {
    contentBase: './dist',
    historyApiFallback: true,
    hot: true
  },
  plugins: [
    extractSass,
    // new ExtractTextPlugin('[name].[hash].css'),
    new HtmlWebPackPlugin({
      template: './src/index.html',
      filename: './index.html',
    }),
    new CleanWebpackPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery"
    })
  ],
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendor',
          chunks: 'all',
        },
      },
    },
  },
};


问:
use passed data before build method flutter
I'm trying to access the information I've passed over from a previous class before the build method begins. But it's saying only static members can be accessed in initializers. I don't really want to use the static property, partially because I wouldn't know how to use it, but also because I think it seems unnecessary. In previous pages I've been able to access the data but only after the build method, does anyone know how I can access it before? Thanks all

```<code>class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {

  List<MyProvider> myList;

@override
  Widget build(BuildContext context) {

return Scaffold(

  body: ListView.builder(
          itemCount: myList.length,
          itemBuilder: (context, index) {

            String imgPath = myList[index].image;
            String myTextPath = myList[index].name;
            String locationNamePath = myList[index].location;
            double distancePath = myList[index].distance;

            String myName = '${myTextPath} ''${locationNamePath}';

            return MyCard(
              locationText: locationNamePath,
              myText: myTextPath,
              assetImage: Image.network(imgPath),

              function: (){
                Provider.of<Data>(context, listen: false).addLogo(Image.network(imgPath));
                Navigator.push(context, MaterialPageRoute(builder: (context) => SecondPage(myName: myName,)));
              },
            );
          }),

    );

  }

}
</code>```

My next page accesses the data using a key but it seems not to be able to use it before the build method, and that's what I need to get around!

```<code>class SecondPage extends StatefulWidget {

  final String myName;

  const SecondPage({Key key, this.myName})
      : super(key: key);

  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> with TickerProviderStateMixin {

    final CollectionReference myItemsReference = Firestore.instance.collection('${widget.myName}');
    // This is where the error is

  @override
  Widget build(BuildContext context) {

      return Scaffold();

    }

}
</code>```

答:
Use the initState method for anything related to initialization of State. See this for more on initState.

Example:

```<code>CollectionReference myItemsReference;

@override
void initState() {
  myItemsReference = Firestore.instance.collection('${widget.myName}');
}
</code>```

Body:
I'm trying to access the information I've passed over from a previous class before the build method begins. But it's saying only static members can be accessed in initializers. I don't really want to use the static property, partially because I wouldn't know how to use it, but also because I think it seems unnecessary. In previous pages I've been able to access the data but only after the build method, does anyone know how I can access it before? Thanks all

class FirstPage extends StatefulWidget {
  @override
  _FirstPageState createState() => _FirstPageState();
}

class _FirstPageState extends State<FirstPage> {

  List<MyProvider> myList;

@override
  Widget build(BuildContext context) {

return Scaffold(

  body: ListView.builder(
          itemCount: myList.length,
          itemBuilder: (context, index) {

            String imgPath = myList[index].image;
            String myTextPath = myList[index].name;
            String locationNamePath = myList[index].location;
            double distancePath = myList[index].distance;

            String myName = '${myTextPath} ''${locationNamePath}';

            return MyCard(
              locationText: locationNamePath,
              myText: myTextPath,
              assetImage: Image.network(imgPath),

              function: (){
                Provider.of<Data>(context, listen: false).addLogo(Image.network(imgPath));
                Navigator.push(context, MaterialPageRoute(builder: (context) => SecondPage(myName: myName,)));
              },
            );
          }),

    );

  }

}

My next page accesses the data using a key but it seems not to be able to use it before the build method, and that's what I need to get around!

class SecondPage extends StatefulWidget {

  final String myName;

  const SecondPage({Key key, this.myName})
      : super(key: key);

  @override
  _SecondPageState createState() => _SecondPageState();
}

class _SecondPageState extends State<SecondPage> with TickerProviderStateMixin {

    final CollectionReference myItemsReference = Firestore.instance.collection('${widget.myName}');
    // This is where the error is

  @override
  Widget build(BuildContext context) {

      return Scaffold();

    }

}

Body:
Use the initState method for anything related to initialization of State. See this for more on initState.

Example:

CollectionReference myItemsReference;

@override
void initState() {
  myItemsReference = Firestore.instance.collection('${widget.myName}');
}


问:
Firebase : Loggin in after logout stuck on loading
I use Firebase authentication and when I Login or Register it works properly and advance me to the Home page but when I Logout, it log me out successfully
But when I Login again it stuck on Loading screen

My app flow is: main->Wrapper->Authenticate->Login/Register->Home

Here is Wrapper:

```<code>class _WrapperState extends State<Wrapper> {
  int _currentTab = 1;

  final _page = [
    Search(),
    Home(),
    Account(),
  ];

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user.uid);

    if (user == null) {
      return Authenticate();
    } else {
      return
//        Home();
       }
}
</code>```

Here is Login :

```<code>RaisedButton(
                color: Colors.green[400],
                child: Text(
                  'دخول',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () async {
                  if(_formKey.currentState.validate()){
                    setState(() => loading = true);
                    dynamic result = await _auth.signInWithEmailAndPassword(email, password);
                    if(result == null) {
                      setState(() {
                        loading = false;
                        error = 'Could not sign in with those credentials';
                      });
                    }
                  }
                }
            ),
</code>```

and here is signIn method implementation for FirebasE:

```<code>Future signInWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      return user;
    } catch (error) {
      print(error.toString());
      return null;
    }
  }
</code>```

答:
It gets stuck on the loading because you have two setState, whenever you are pressing the button the first setState is getting called and assigns true to the variable loading. You should change it to the following:

```<code>onPressed: () async {
                  if(_formKey.currentState.validate()){
                    setState(()async{
                       loading = true;
                       dynamic result = await _auth.signInWithEmailAndPassword(email, password);
                    if(result == null) {
                        loading = false;
                        error = 'Could not sign in with those credentials';
                      });
                    }
                  }
                }
</code>```

Body:
I use Firebase authentication and when I Login or Register it works properly and advance me to the Home page but when I Logout, it log me out successfully
But when I Login again it stuck on Loading screen

My app flow is: main->Wrapper->Authenticate->Login/Register->Home

Here is Wrapper:

class _WrapperState extends State<Wrapper> {
  int _currentTab = 1;

  final _page = [
    Search(),
    Home(),
    Account(),
  ];

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context);
    print(user.uid);

    if (user == null) {
      return Authenticate();
    } else {
      return
//        Home();
       }
}

Here is Login :

RaisedButton(
                color: Colors.green[400],
                child: Text(
                  'دخول',
                  style: TextStyle(color: Colors.white),
                ),
                onPressed: () async {
                  if(_formKey.currentState.validate()){
                    setState(() => loading = true);
                    dynamic result = await _auth.signInWithEmailAndPassword(email, password);
                    if(result == null) {
                      setState(() {
                        loading = false;
                        error = 'Could not sign in with those credentials';
                      });
                    }
                  }
                }
            ),

and here is signIn method implementation for FirebasE:

Future signInWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
      return user;
    } catch (error) {
      print(error.toString());
      return null;
    }
  }

Body:
It gets stuck on the loading because you have two setState, whenever you are pressing the button the first setState is getting called and assigns true to the variable loading. You should change it to the following:

onPressed: () async {
                  if(_formKey.currentState.validate()){
                    setState(()async{
                       loading = true;
                       dynamic result = await _auth.signInWithEmailAndPassword(email, password);
                    if(result == null) {
                        loading = false;
                        error = 'Could not sign in with those credentials';
                      });
                    }
                  }
                }


问:
Dealing with rejected promises without messy try catch
I have a simple function, which looks similar to the following

```<code>const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

}

</code>```

apiRequest returns a number.

This function is surrounded by a function which handles errors for many functions.

However for this specific function, I don't just want to return an error to the user in the case of one of the apiRequests failing in the second part of the ternary.

```<code>const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

// intended logic for second part of ternary
if apiRequest and apiRequest resolve, return apiRequest + apiRequest2
if apiRequest fails, return apiRequest2
if apiRequest 2 fails, return apiRequest
}
</code>```

I'm not exactly sure of the way I should be going about this. Perhaps I could surround each part with try and catch, and in the catch statement I could then try the next part of the logic?

I feel like I will end up with a super messy function in this case

答:
First of all, await needs to occur in an async function, so the code in your question cannot run.

If I understand correctly, you still want the function to return a rejected promise when both promises reject.

You could define a utility function that takes an array as promises and returns a single promise that only rejects when all given promises reject (with the reason of the rejection of the first promise). In all other cases it will resolve to an array with the individual fulfilled values, or with the default value when the corresponding promise rejected.

This utility function could look like this:

```<code>async function fulfilled(promises, defValue) {
    const res = await Promise.allSettled(promises);
    if (res.every(p => p.status == "rejected")) throw res[0].reason;
    return res.map(p => p.status == "fulfilled" ? p.value : defValue);
}
</code>```

Then your function could look like this:

```<code>const foo = async (bar) => {
    return ![val1, val2].includes(bar) ? apiRequest :
        (await fulfilled([apiRequest, apiRequest2], 0)).reduce((a, b) => a + b);
}

</code>```

Body:
I have a simple function, which looks similar to the following

const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

}

apiRequest returns a number.

This function is surrounded by a function which handles errors for many functions.

However for this specific function, I don't just want to return an error to the user in the case of one of the apiRequests failing in the second part of the ternary.

const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

// intended logic for second part of ternary
if apiRequest and apiRequest resolve, return apiRequest + apiRequest2
if apiRequest fails, return apiRequest2
if apiRequest 2 fails, return apiRequest
}

I'm not exactly sure of the way I should be going about this. Perhaps I could surround each part with try and catch, and in the catch statement I could then try the next part of the logic?

I feel like I will end up with a super messy function in this case

Body:
First of all, await needs to occur in an async function, so the code in your question cannot run.

If I understand correctly, you still want the function to return a rejected promise when both promises reject.

You could define a utility function that takes an array as promises and returns a single promise that only rejects when all given promises reject (with the reason of the rejection of the first promise). In all other cases it will resolve to an array with the individual fulfilled values, or with the default value when the corresponding promise rejected.

This utility function could look like this:

async function fulfilled(promises, defValue) {
    const res = await Promise.allSettled(promises);
    if (res.every(p => p.status == "rejected")) throw res[0].reason;
    return res.map(p => p.status == "fulfilled" ? p.value : defValue);
}

Then your function could look like this:

const foo = async (bar) => {
    return ![val1, val2].includes(bar) ? apiRequest :
        (await fulfilled([apiRequest, apiRequest2], 0)).reduce((a, b) => a + b);
}


问:
Problem in using scipy.spatial.cKDTree or queryBallPoint with random 2d points using nearest neighbors between two datasets
I have P_0 points spread randomly in a 2d box. Then I divide them in two groups S and I. If some points of S come too close to I, they are deleted from the S group and added to the I group. The problem I am facing is that sometimes they are not correctly deleted from S, but they are properly added to I. Hence, the total number of points keeps erroneously growing.
Here is the code:

```<code>from scipy.spatial import cKDTree
import numpy as np
import matplotlib.pyplot as plt
P_0 = 100 # initial susceptible population
# dimensions of box
Lx = 5.0
Ly = 5.0
# generate P_0 random points inside box
X = np.random.uniform(0, Lx, P_0)
Y = np.random.uniform(0, Ly, P_0)
pts = np.column_stack((X, Y)) # array of 2d points
S = np.arange(10, P_0) # indices of the susceptible
I = np.arange(10) # indices of the infected
# Divide points into infected and susceptible groups
r_I = pts[I]
r_S = pts[S]
tree = cKDTree(r_S)
# idx represents the indices to points in r_S which are closer than r to
# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

plt.figure('S group')
plt.plot (pts[S, 0], pts[S, 1], 'bo') # plot the updated r_S points

plt.figure('I group')
plt.plot (pts[I, 0], pts[I, 1], 'ro') # plot the updated r_I points
print len(S), len(I), len(S)+len(I), len(idx)
plt.show()
</code>```

So, I don't know why not all points in r_S closer than r, sometimes aren't deleted from S.
One might have to run the code a few times for the error to appear, or just increase P_0 to 1000 for example or increase the value of r. it might be a problem with idx and the way I am using numpy delete.

答:
You could double check your assumption by swapping the actions (doing a move by doing the deletion first and the addition second, only on a successful deletion) and testing the deletion in a separate variable.

Compare the resulting size after deletion with the original size of the group. If sizes match, no deletion had occurred (for whatever reason), which is a signal not to add something on the other side.

Then you could have a print of groups on the upper case and see the indexes which participate to shed some light into the tunnel.

Body:
I have P_0 points spread randomly in a 2d box. Then I divide them in two groups S and I. If some points of S come too close to I, they are deleted from the S group and added to the I group. The problem I am facing is that sometimes they are not correctly deleted from S, but they are properly added to I. Hence, the total number of points keeps erroneously growing.
Here is the code:

from scipy.spatial import cKDTree
import numpy as np
import matplotlib.pyplot as plt
P_0 = 100 # initial susceptible population
# dimensions of box
Lx = 5.0
Ly = 5.0
# generate P_0 random points inside box
X = np.random.uniform(0, Lx, P_0)
Y = np.random.uniform(0, Ly, P_0)
pts = np.column_stack((X, Y)) # array of 2d points
S = np.arange(10, P_0) # indices of the susceptible
I = np.arange(10) # indices of the infected
# Divide points into infected and susceptible groups
r_I = pts[I]
r_S = pts[S]
tree = cKDTree(r_S)
# idx represents the indices to points in r_S which are closer than r to
# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

# points in r_I
idx = tree.query_ball_point(r_I, r=0.4)
idx = np.hstack(idx) # flatten the lists into one numpy array
idx = idx.astype(int) # Make sure idx indices have int type
print idx

# plot points
plt.figure()
plt.plot (r_S[:, 0], r_S[:, 1], 'bo') # plot all r_S points
plt.plot (r_S[idx, 0], r_S[idx, 1], 'ko') # color those points nearest to r_I
plt.plot (r_I[:, 0], r_I[:, 1], 'ro') # identify the r_I points
print len(S), len(I), len(S)+len(I)
I= np.append(I, S[idx]) # add the closest points to I
S = np.delete(S, idx) # delete the closest points from S

plt.figure('S group')
plt.plot (pts[S, 0], pts[S, 1], 'bo') # plot the updated r_S points

plt.figure('I group')
plt.plot (pts[I, 0], pts[I, 1], 'ro') # plot the updated r_I points
print len(S), len(I), len(S)+len(I), len(idx)
plt.show()

So, I don't know why not all points in r_S closer than r, sometimes aren't deleted from S.
One might have to run the code a few times for the error to appear, or just increase P_0 to 1000 for example or increase the value of r. it might be a problem with idx and the way I am using numpy delete.


问:
Getting a number of digits
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...

```<code>    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'
</code>```

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe

答:
```<code>"%.3f" % math.pi
</code>```

<p>I know its using the old syntax but I personally prefer it. </p>

Title: Getting a number of digits

Body:
I've been searching for a way in python to get only 4 digits on the right of the comma of a decimal number, but i couldn't find. Took a look on this post,---> Rounding decimals with new Python format function
,but the function written there...

    >>> n = 4
    >>> p = math.pi
    >>> '{0:.{1}f}'.format(p, n)
    '3.1416'

...seems not to work in my case.

I imported the modules "math" and "decimal", but maybe i'm missing some others to import, but i don't know which of them to import.

Thanks everyone, and sorry if this issue has already been posted.

Peixe

Body:
"%.3f" % math.pi

I know its using the old syntax but I personally prefer it.


问:
jsPDF html method with addPage to split pages in generated PDF
I am using jsPDF's html method to generate a PDF for some html that comprises of multiple paragraphs p with each p containing words between 50-500. The PDF is generated properly with the styles I have defined. The only issue I am facing is when the contents of the p tags overflow to a new page in PDF cutting off parts of text as can be seen here:

To counter this, I need to introduce addPage into my code to insert a "page break" where I wish. Here is a sample of addPage that works with jsPDF's text function:

```<code>var doc = new jsPDF('p', 'pt', 'letter');
doc.text(20, 20, 'first text');
doc.addPage();
doc.text(20, 20, 'second text');
doc.addPage();
doc.text(20, 20, 'third text');
doc.save();
</code>```

I want to do the same for html and here is the code I used:

```<code>var doc = new jsPDF('p', 'pt', 'letter');
doc.html($("#p1")[0], {
    callback: function (doc) {
        doc.addPage('letter', 'p');

        doc.html($("#p2")[0], {
            callback: function (doc) {
                doc.save();
            }
        });
    }
});
</code>```

The above generates a PDF with the contents with 2 pages as desired. But the contents that are suppose to be on the second page are on the first, on top of the contents of first page. In other words, #p2 contents are pasted on top of #p1 contents.

Here is the code snippet but please note, SO is throwing cross-origin error when you try to run the code so you will need to run the below outside SO:

function wrap() {
  var doc = new jsPDF('p', 'pt', 'letter');
  doc.html($("#p1")[0], {
    callback: function(doc) {
      doc.addPage('letter', 'p');
      doc.html($("#p2")[0], {
        callback: function(doc) {
          doc.save();
        }
      });
    }
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-alpha.12/dist/html2canvas.js"></script>

<button id="btn" onclick="wrap()">Test</button>
<div id="lipsum">
  <p id="p1">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed risus at orci elementum consequat. Suspendisse laoreet rhoncus dignissim. Aliquam a ultrices orci, in elementum nibh. Aliquam mollis erat at vehicula pellentesque. Nunc suscipit, leo
    at convallis lobortis, odio ipsum euismod sapien, auctor accumsan velit eros non risus. Cras sagittis nisi non orci finibus porta. Sed finibus ac eros eu tincidunt. Nam viverra egestas augue vestibulum elementum. Suspendisse convallis felis sodales,
    ornare neque ut, elementum dui. Mauris ac orci mattis, tristique nisi quis, ultricies urna. In tincidunt, dolor vitae euismod mattis, lorem arcu placerat velit, quis auctor est est et sem. Aenean convallis finibus posuere. Sed feugiat orci a lacinia
    efficitur. Ut semper, purus quis convallis vehicula, mi risus rhoncus arcu, et feugiat neque turpis non tellus.
  </p>
  <p id="p2">
    Mauris dapibus felis leo, vitae vestibulum purus feugiat sit amet. Fusce ac dapibus nunc. Etiam congue mi neque. Maecenas eget blandit turpis. Suspendisse volutpat, urna eu facilisis congue, elit felis faucibus velit, venenatis semper sem sem ut ante.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent blandit congue sapien. Curabitur non fermentum felis, sit amet auctor nunc. Cras id tellus nunc.
  </p>
  <p id="p3">
    In lacinia lectus nec quam dapibus eleifend. Phasellus iaculis eget massa non aliquam. Cras interdum gravida hendrerit. Suspendisse rhoncus pretium erat non malesuada. Fusce sit amet finibus est. Phasellus quis dapibus orci. Nunc iaculis felis odio, et
    dictum leo mollis sed. Morbi ultrices turpis at mi pellentesque, sit amet consectetur tortor volutpat. Mauris ac nunc ac nunc pellentesque lacinia. Duis at ligula tristique, maximus sapien sit amet, pulvinar neque.
  </p>

</div></code>```

Please also note that the version used for html2canvas js is important here. See this for more info.

答:
Using this, specifically the template (lines 125-150), I found a solution that "moves" the second (subsequent) page to the correct y (y: 792) coordinates:

```<code>function wrap() {
  var doc = new jsPDF('p', 'pt', 'letter');
  doc.html($("#p1")[0], {
    callback: function(doc) {
      doc.addPage('letter', 'p');
      doc.html($("#p2")[0], {
        callback: function(doc) {
          doc.save();
        }, y:792
      });
    }, html2canvas: {scale: 1}
  });
}
</code>```

Where 792 is the vertial length of a single letter page. In other words, the p2 renders on a position with a defined y-axis coordinate.

One can update the code above (recursive function) to do this for multiple p elements or even split the pages on other criteria. I hope this helps someone.

Note: html2canvas: {scale: 1} is used to resolve another problem that I had with page scaling of produced PDF on mobile devices.

Body:
I am using jsPDF's html method to generate a PDF for some html that comprises of multiple paragraphs p with each p containing words between 50-500. The PDF is generated properly with the styles I have defined. The only issue I am facing is when the contents of the p tags overflow to a new page in PDF cutting off parts of text as can be seen here:

To counter this, I need to introduce addPage into my code to insert a "page break" where I wish. Here is a sample of addPage that works with jsPDF's text function:

var doc = new jsPDF('p', 'pt', 'letter');
doc.text(20, 20, 'first text');
doc.addPage();
doc.text(20, 20, 'second text');
doc.addPage();
doc.text(20, 20, 'third text');
doc.save();

I want to do the same for html and here is the code I used:

var doc = new jsPDF('p', 'pt', 'letter');
doc.html($("#p1")[0], {
    callback: function (doc) {
        doc.addPage('letter', 'p');

        doc.html($("#p2")[0], {
            callback: function (doc) {
                doc.save();
            }
        });
    }
});

The above generates a PDF with the contents with 2 pages as desired. But the contents that are suppose to be on the second page are on the first, on top of the contents of first page. In other words, #p2 contents are pasted on top of #p1 contents.

Here is the code snippet but please note, SO is throwing cross-origin error when you try to run the code so you will need to run the below outside SO:

function wrap() {
  var doc = new jsPDF('p', 'pt', 'letter');
  doc.html($("#p1")[0], {
    callback: function(doc) {
      doc.addPage('letter', 'p');
      doc.html($("#p2")[0], {
        callback: function(doc) {
          doc.save();
        }
      });
    }
  });
}

<button id="btn" onclick="wrap()">Test</button>

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas sed risus at orci elementum consequat. Suspendisse laoreet rhoncus dignissim. Aliquam a ultrices orci, in elementum nibh. Aliquam mollis erat at vehicula pellentesque. Nunc suscipit, leo
    at convallis lobortis, odio ipsum euismod sapien, auctor accumsan velit eros non risus. Cras sagittis nisi non orci finibus porta. Sed finibus ac eros eu tincidunt. Nam viverra egestas augue vestibulum elementum. Suspendisse convallis felis sodales,
    ornare neque ut, elementum dui. Mauris ac orci mattis, tristique nisi quis, ultricies urna. In tincidunt, dolor vitae euismod mattis, lorem arcu placerat velit, quis auctor est est et sem. Aenean convallis finibus posuere. Sed feugiat orci a lacinia
    efficitur. Ut semper, purus quis convallis vehicula, mi risus rhoncus arcu, et feugiat neque turpis non tellus.

    Mauris dapibus felis leo, vitae vestibulum purus feugiat sit amet. Fusce ac dapibus nunc. Etiam congue mi neque. Maecenas eget blandit turpis. Suspendisse volutpat, urna eu facilisis congue, elit felis faucibus velit, venenatis semper sem sem ut ante.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent blandit congue sapien. Curabitur non fermentum felis, sit amet auctor nunc. Cras id tellus nunc.

    In lacinia lectus nec quam dapibus eleifend. Phasellus iaculis eget massa non aliquam. Cras interdum gravida hendrerit. Suspendisse rhoncus pretium erat non malesuada. Fusce sit amet finibus est. Phasellus quis dapibus orci. Nunc iaculis felis odio, et
    dictum leo mollis sed. Morbi ultrices turpis at mi pellentesque, sit amet consectetur tortor volutpat. Mauris ac nunc ac nunc pellentesque lacinia. Duis at ligula tristique, maximus sapien sit amet, pulvinar neque.

Please also note that the version used for html2canvas js is important here. See this for more info.

Body:
Using this, specifically the template (lines 125-150), I found a solution that "moves" the second (subsequent) page to the correct y (y: 792) coordinates:

function wrap() {
  var doc = new jsPDF('p', 'pt', 'letter');
  doc.html($("#p1")[0], {
    callback: function(doc) {
      doc.addPage('letter', 'p');
      doc.html($("#p2")[0], {
        callback: function(doc) {
          doc.save();
        }, y:792
      });
    }, html2canvas: {scale: 1}
  });
}

Where 792 is the vertial length of a single letter page. In other words, the p2 renders on a position with a defined y-axis coordinate.

One can update the code above (recursive function) to do this for multiple p elements or even split the pages on other criteria. I hope this helps someone.

Note: html2canvas: {scale: 1} is used to resolve another problem that I had with page scaling of produced PDF on mobile devices.


问:
Angular is it possible to sort array alphabetically in ngFor?
I need to sort my ngFor alphabatically here is my code

```<code><div *ngFor="let main of data.mainCategories; let i = index" class="category-container">
  <ion-grid class="categories-card5" no-padding>
  <ion-row><ion-col class="ion-text-center">
  <ion-item lines="none" button="true" (click)="showSubCategory(i)" detail="false">
    <ion-thumbnail slot="start">
      <img *ngIf="main.image?.src" src="{{main.image.src}}">
    </ion-thumbnail>
    <ion-label>
      <h2 [innerHTML]="main.name"></h2>
      <h2 [innerHTML]="main.slug"></h2>
      <p [innerHTML]="main.description"></p>
    </ion-label>
    <ion-icon *ngIf="main.show" name="chevron-up-outline" mode="ios" color="medium"></ion-icon>
    <ion-icon *ngIf="!main.show" name="chevron-down-outline" mode="ios" color="medium"></ion-icon>
  </ion-item>
</ion-col>
</ion-row>
</ion-grid>
</div>
</code>```

In this i have main.slug i need to sort it by this example in main.slug which start alphabet is a it will show first like this

答:
one solution is to order the array that you currently have into a new array and use *ngFor on that.

class YourComponent {

  mainCategories: object[]
  sortedCategories: object[];

  constructor() {
    this.sortedCategories = this.mainCategories.sort(this.sortBySlug);
  }

  sortBySlug(a: object, b: object): number {
    // this is the typical structure of a custom sort function in plain JavaScript

    if (a.slug  b.slug) { return 1; }
  }
}

```

You can also create a custom pipe if you want as well. I made a custom stackblitz repo that you can follow here. The pipe I created simply applies a specified sort function to the array.

Hope this helps.

Body:
I need to sort my ngFor alphabatically here is my code

  <ion-grid class="categories-card5" no-padding>
  <ion-row><ion-col class="ion-text-center">
  <ion-item lines="none" button="true" (click)="showSubCategory(i)" detail="false">
    <ion-thumbnail slot="start">

    </ion-thumbnail>
    <ion-label>

    </ion-label>
    <ion-icon *ngIf="main.show" name="chevron-up-outline" mode="ios" color="medium"></ion-icon>
    <ion-icon *ngIf="!main.show" name="chevron-down-outline" mode="ios" color="medium"></ion-icon>
  </ion-item>
</ion-col>
</ion-row>
</ion-grid>

In this i have main.slug i need to sort it by this example in main.slug which start alphabet is a it will show first like this

Body:
one solution is to order the array that you currently have into a new array and use *ngFor on that.

class YourComponent {

  mainCategories: object[]
  sortedCategories: object[];

  constructor() {
    this.sortedCategories = this.mainCategories.sort(this.sortBySlug);
  }

  sortBySlug(a: object, b: object): number {
    // this is the typical structure of a custom sort function in plain JavaScript

    if (a.slug < b.slug) { return -1; }
    if (a.slug === b.slug) { return 0; }
    if (a.slug > b.slug) { return 1; }
  }
}

You can also create a custom pipe if you want as well. I made a custom stackblitz repo that you can follow here. The pipe I created simply applies a specified sort function to the array.

Hope this helps.


问:
How linux daemon will read xml file in worker service .Net Core 3.1
I am working with new worker service project template in .Net Core. Reading credentials from config file. Config file location in windows machine "D:/LC2/Files/Config.xml".

When I will run worker service as linux daemon, how linux will read config file? because there is only windows machine's path available not linux.

This is my code to read config file

```<code>static List<intervalValue> GetConfig()
{
    XmlDocument doc = new XmlDocument();
    doc.Load("D:/LC2/Files/Config.xml");
    XmlNode node = doc.DocumentElement.SelectSingleNode("/parameters/intervalValue");
    {
        for (int i = 0; i < node.ChildNodes.Count; i++)
        {
            IntervalTypeList.Add(new intervalValue { Name = node.ChildNodes[i].Attributes["Name"].Value);
        }
    }
    return IntervalTypeList;
}
</code>```

How can I fix this issue?

答:
You are right that a Linux daemon will not be able to read paths that dont exist on Linux.

There are a couple of approaches you can look at:

Your services can look at the OS and read a different path/file on Linux. For example, for Windows you are reading the hard-coded location @'D:\LC2\Files\Config.xml', and on Linux, you can use another hard-coded like /opt/LC2/config.xml.

You can provide an argument to the worker service. That requires parsing arguments and teaching your worker service about an argument, like --config /path/to/file. Then your worker service will just read that passed-in path and not have to worry about the path. Whatever runs/configures your service will provide a correct path on Windows and on Linux.

You can add support for reading the file location via an environment variable like LC2_CONFIG. If it's set and points to a file, use that location as the config file. Otherwise fall back to the hard-coded value. On Linux, the tool that runs your daemon can provide it a path that is appropriate for Linux.

There are other options and variants possible, but these seem like the most obvious approaches.

Depending on the audience of the program, you might want all three. For example, git will use a default location for a config file. But it will let users provide specific configuration values both via command line and also let users specify configuration via environment variables.

Body:
I am working with new worker service project template in .Net Core. Reading credentials from config file. Config file location in windows machine "D:/LC2/Files/Config.xml".

When I will run worker service as linux daemon, how linux will read config file? because there is only windows machine's path available not linux.

This is my code to read config file

static List<intervalValue> GetConfig()
{
    XmlDocument doc = new XmlDocument();
    doc.Load("D:/LC2/Files/Config.xml");
    XmlNode node = doc.DocumentElement.SelectSingleNode("/parameters/intervalValue");
    {
        for (int i = 0; i < node.ChildNodes.Count; i++)
        {
            IntervalTypeList.Add(new intervalValue { Name = node.ChildNodes[i].Attributes["Name"].Value);
        }
    }
    return IntervalTypeList;
}

How can I fix this issue?


问:
What does pwn mean in server exploitation (in CTFs)?
Pwn - I know that this is a category in CTFs in which you exploit a server to find the flag.

there is a library called pwntools, it's a CTF framework and exploit development library in python.

What I can't understand is why is it called "PWN" and is it an abbreviation?

pwn is also owning/dominating someone, but does this definition fit?

Thanks for helping ^^

答:
In the context of internet/hacking slang, it indeed means that your server (or data or anything else) has been taken over control, that you "lost the game".

I think this is an abbreviation from "pawned", from the verb "to pawn", used in games, though I can't find a reliable and authoritative source for it (same as current wiktionary word article is stating).

I feel like it has roots in the chess game (where you used pieces called "pawns").

It sounds like "owned" and "punched". It might also be some invented word.