问:
RenderScript remove pixels with alpha at bitmap
I've got a bitmap and I need to remove all pixels that have alpha. Sounds easy, but I'm stuck with it.
I've got this Java code:

```<code> public static Bitmap overdrawAlphaBits(Bitmap image, int color) {
    Bitmap coloredBitmap = image.copy(Bitmap.Config.ARGB_8888, true);
    for (int y = 0; y < coloredBitmap.getHeight(); y++) {
        for (int x = 0; x < coloredBitmap.getWidth(); x++) {
            int pixel = coloredBitmap.getPixel(x, y);
            if (pixel != 0) {
                coloredBitmap.setPixel(x, y, color);
            }
        }
    }
    return coloredBitmap;
}
</code>```

And it works fine, but slowly, processing of one bitmap takes around 2 second.
I'my trying with RenderScript. It works fast, but not stable.
here is my code:

```<code>public static Bitmap overdrawAlphaBits(Bitmap image, Context context) {
    Bitmap blackbitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), image.getConfig());
    RenderScript mRS = RenderScript.create(context);
    ScriptC_replace_with_main_green_color script = new ScriptC_replace_with_main_green_color(mRS);

    Allocation allocationRaster0 = Allocation.createFromBitmap(mRS, image, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
    Allocation allocationRaster1 = Allocation.createTyped(mRS, allocationRaster0.getType());
    script.forEach_root(allocationRaster0, allocationRaster1);
    allocationRaster1.copyTo(blackbitmap);
    allocationRaster0.destroy();
    allocationRaster1.destroy();
    script.destroy();
    mRS.destroy();
    return blackbitmap;
}
</code>```

And my .rs file:

```<code>void root(const uchar4 *v_in, uchar4 *v_out) {
uint32_t rValue = v_in->r;
uint32_t gValue = v_in->g;
uint32_t bValue = v_in->b;
uint32_t aValue = v_in->a;
if(rValue!=0 || gValue!=0 || bValue!=0 || aValue!=0){
   v_out->r = 0x55;
   v_out->g = 0xED;
   v_out->b = 0x69;
}
}
</code>```

So I use this method on multiple bitmaps - at first bitmap is works fine, but than I receive corrupted images. By the way when I apply this method again on first bitmap it also corrupts it.
Looks like there is not closed memory allocation or shared resources, idk.

Any ideas, please?
Maybe there is an easier solution?
Thanks everyone in advance!

答:
Actually you can use getPixels method to read all pixels in array and than manipulate them. It works fast enough. The problem is that getPixel works slow.
So here is the code:</p>

```<code>public static Bitmap overdrawAlphaBits(Bitmap image, int color) {
    int[] pixels = new int[image.getHeight() * image.getWidth()];
    image.getPixels(pixels, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
    for (int i = 0; i < image.getWidth() * image.getHeight(); i++) {
        if (pixels[i] != 0) {
            pixels[i] = color;
        }
    }
    image.setPixels(pixels, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
    return image;
}
</code>```

Body:
I've got a bitmap and I need to remove all pixels that have alpha. Sounds easy, but I'm stuck with it.
I've got this Java code:

 public static Bitmap overdrawAlphaBits(Bitmap image, int color) {
    Bitmap coloredBitmap = image.copy(Bitmap.Config.ARGB_8888, true);
    for (int y = 0; y < coloredBitmap.getHeight(); y++) {
        for (int x = 0; x < coloredBitmap.getWidth(); x++) {
            int pixel = coloredBitmap.getPixel(x, y);
            if (pixel != 0) {
                coloredBitmap.setPixel(x, y, color);
            }
        }
    }
    return coloredBitmap;
}

And it works fine, but slowly, processing of one bitmap takes around 2 second.
I'my trying with RenderScript. It works fast, but not stable.
here is my code:

public static Bitmap overdrawAlphaBits(Bitmap image, Context context) {
    Bitmap blackbitmap = Bitmap.createBitmap(image.getWidth(), image.getHeight(), image.getConfig());
    RenderScript mRS = RenderScript.create(context);
    ScriptC_replace_with_main_green_color script = new ScriptC_replace_with_main_green_color(mRS);

    Allocation allocationRaster0 = Allocation.createFromBitmap(mRS, image, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
    Allocation allocationRaster1 = Allocation.createTyped(mRS, allocationRaster0.getType());
    script.forEach_root(allocationRaster0, allocationRaster1);
    allocationRaster1.copyTo(blackbitmap);
    allocationRaster0.destroy();
    allocationRaster1.destroy();
    script.destroy();
    mRS.destroy();
    return blackbitmap;
}

And my .rs file:

void root(const uchar4 *v_in, uchar4 *v_out) {
uint32_t rValue = v_in->r;
uint32_t gValue = v_in->g;
uint32_t bValue = v_in->b;
uint32_t aValue = v_in->a;
if(rValue!=0 || gValue!=0 || bValue!=0 || aValue!=0){
   v_out->r = 0x55;
   v_out->g = 0xED;
   v_out->b = 0x69;
}
}

So I use this method on multiple bitmaps - at first bitmap is works fine, but than I receive corrupted images. By the way when I apply this method again on first bitmap it also corrupts it.
Looks like there is not closed memory allocation or shared resources, idk.

Any ideas, please?
Maybe there is an easier solution?
Thanks everyone in advance!

Body:
Actually you can use getPixels method to read all pixels in array and than manipulate them. It works fast enough. The problem is that getPixel works slow.
So here is the code:

public static Bitmap overdrawAlphaBits(Bitmap image, int color) {
    int[] pixels = new int[image.getHeight() * image.getWidth()];
    image.getPixels(pixels, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
    for (int i = 0; i < image.getWidth() * image.getHeight(); i++) {
        if (pixels[i] != 0) {
            pixels[i] = color;
        }
    }
    image.setPixels(pixels, 0, image.getWidth(), 0, 0, image.getWidth(), image.getHeight());
    return image;
}


来源: stackexchange

问:
Is it possible to create a separate class where all your Java-XML linking code stays?
What I have tried?
I created a manifestUI() method and initialised all UI components and its working well. But I want to put the code for declaring and creating (as well as linking) UI to java code to a separate class, UICreation.java file. I copied all my code in the latter file and corrected small errors due to the code migration but it's not working out.

Objective: Keep the MainActivity.class lean and clean.

Do you think this will make the App function any quicker, slower or no effect whatsoever?

What I am trying to achieve, in a snapshot

Using UICreation class in MainActivity.java (I suspect I am doing something wrong here perhaps)

```<code>UICreation linkUI = new UICreation();
linkUI.manifestUI();
</code>```

Core Code:

```<code>//Link XML UI with Java: This method imparts the knowledge of the UI link to the compiler
 private void manifestUI() {

// Link TextViews
   bigText = (TextView) findViewById(R.id.big_text);
   expressionText = (TextView) findViewById(R.id.expression_text);

// Link Keypad
   zeroKey = (Button) findViewById(R.id.button_zero);
   oneKey = (Button) findViewById(R.id.button_one);
   twoKey = (Button) findViewById(R.id.button_two);
   threeKey = (Button) findViewById(R.id.button_three);
   fourKey = (Button) findViewById(R.id.button_four);
   fiveKey = (Button) findViewById(R.id.button_five);
   sixKey = (Button) findViewById(R.id.button_six);
   sevenKey = (Button) findViewById(R.id.button_seven);
   eightKey = (Button) findViewById(R.id.button_eight);
   nineKey = (Button) findViewById(R.id.button_nine);
   decimalKey = (Button)findViewById(R.id.button_decimal);
   backSpaceKey = (ImageButton) findViewById(R.id.button_delete);

    // Link Operators
    add = (Button) findViewById(R.id.button_add);
    subtract = (Button) findViewById(R.id.button_subtract);
    multiply = (Button) findViewById(R.id.button_multiply);
    divide = (Button) findViewById(R.id.button_divide);
    percentage = (Button) findViewById(R.id.button_percentage);
    squareRoot = (Button) findViewById(R.id.button_squareroot);
    operators = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
    }
</code>```

After I moved it to a separate class UI Creation

public class UICreation extends Activity {

```<code>//Declaring Key as Global Variables
protected Button zeroKey;
protected Button oneKey;
protected Button twoKey;
protected Button threeKey;
protected Button fourKey;
protected Button fiveKey;
protected Button sixKey;
protected Button sevenKey;
protected Button eightKey;
protected Button nineKey;
protected Button decimalKey;
protected ImageButton backSpaceKey;

//Declaring TextView as Global Variables
protected TextView expressionText;
protected TextView bigText;

//Declaring Operators as Global Variables
protected Button add;
protected Button subtract;
protected Button multiply;
protected Button divide;
protected Button percentage;
protected Button squareRoot;

protected HorizontalScrollView operators;

//Link XML UI with Java: This method imparts the knowledge of the UI link to the compiler
protected void manifestUI() {

    //setContentView(R.layout.calculator_ui_responsive);
    // Link TextViews
    bigText = (TextView) findViewById(R.id.big_text);
    expressionText = (TextView) findViewById(R.id.expression_text);

    // Link Keypad
    zeroKey = (Button) findViewById(R.id.button_zero);
    oneKey = (Button) findViewById(R.id.button_one);
    twoKey = (Button) findViewById(R.id.button_two);
    threeKey = (Button) findViewById(R.id.button_three);
    fourKey = (Button) findViewById(R.id.button_four);
    fiveKey = (Button) findViewById(R.id.button_five);
    sixKey = (Button) findViewById(R.id.button_six);
    sevenKey = (Button) findViewById(R.id.button_seven);
    eightKey = (Button) findViewById(R.id.button_eight);
    nineKey = (Button) findViewById(R.id.button_nine);
    decimalKey = (Button)findViewById(R.id.button_decimal);
    backSpaceKey = (ImageButton) findViewById(R.id.button_delete);

    // Link Operators
    add = (Button) findViewById(R.id.button_add);
    subtract = (Button) findViewById(R.id.button_subtract);
    multiply = (Button) findViewById(R.id.button_multiply);
    divide = (Button) findViewById(R.id.button_divide);
    percentage = (Button) findViewById(R.id.button_percentage);
    squareRoot = (Button) findViewById(R.id.button_squareroot);
    operators = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
}}
</code>```

Disclaimer: I am a product designer by profession and new to the exciting world of development.  Please don't be tough on me ;)

答:
Not sure why you would do this but in android development, views are only avaialable  starting from onCreate(). In the first image/doddle you got that right and called manifsetUI() method in onCreate(). Moving the code to another class is where you went wrong, It's a bad idea.

If you want to remove the hassle of instantiating views, there are several ways to do that now, for example you can get direct access using things like Kotlin Synthetics if you were using Kotlin or viewBinding which is also available for Java

ContentLicense: CC BY-SA 4.0

Body:
What I have tried?
I created a manifestUI() method and initialised all UI components and its working well. But I want to put the code for declaring and creating (as well as linking) UI to java code to a separate class, UICreation.java file. I copied all my code in the latter file and corrected small errors due to the code migration but it's not working out.

Objective: Keep the MainActivity.class lean and clean.

Do you think this will make the App function any quicker, slower or no effect whatsoever?

What I am trying to achieve, in a snapshot

Using UICreation class in MainActivity.java (I suspect I am doing something wrong here perhaps)

UICreation linkUI = new UICreation();
linkUI.manifestUI();

Core Code:

//Link XML UI with Java: This method imparts the knowledge of the UI link to the compiler
 private void manifestUI() {

// Link TextViews
   bigText = (TextView) findViewById(R.id.big_text);
   expressionText = (TextView) findViewById(R.id.expression_text);

// Link Keypad
   zeroKey = (Button) findViewById(R.id.button_zero);
   oneKey = (Button) findViewById(R.id.button_one);
   twoKey = (Button) findViewById(R.id.button_two);
   threeKey = (Button) findViewById(R.id.button_three);
   fourKey = (Button) findViewById(R.id.button_four);
   fiveKey = (Button) findViewById(R.id.button_five);
   sixKey = (Button) findViewById(R.id.button_six);
   sevenKey = (Button) findViewById(R.id.button_seven);
   eightKey = (Button) findViewById(R.id.button_eight);
   nineKey = (Button) findViewById(R.id.button_nine);
   decimalKey = (Button)findViewById(R.id.button_decimal);
   backSpaceKey = (ImageButton) findViewById(R.id.button_delete);

    // Link Operators
    add = (Button) findViewById(R.id.button_add);
    subtract = (Button) findViewById(R.id.button_subtract);
    multiply = (Button) findViewById(R.id.button_multiply);
    divide = (Button) findViewById(R.id.button_divide);
    percentage = (Button) findViewById(R.id.button_percentage);
    squareRoot = (Button) findViewById(R.id.button_squareroot);
    operators = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
    }

After I moved it to a separate class UI Creation

public class UICreation extends Activity {

//Declaring Key as Global Variables
protected Button zeroKey;
protected Button oneKey;
protected Button twoKey;
protected Button threeKey;
protected Button fourKey;
protected Button fiveKey;
protected Button sixKey;
protected Button sevenKey;
protected Button eightKey;
protected Button nineKey;
protected Button decimalKey;
protected ImageButton backSpaceKey;

//Declaring TextView as Global Variables
protected TextView expressionText;
protected TextView bigText;

//Declaring Operators as Global Variables
protected Button add;
protected Button subtract;
protected Button multiply;
protected Button divide;
protected Button percentage;
protected Button squareRoot;

protected HorizontalScrollView operators;

//Link XML UI with Java: This method imparts the knowledge of the UI link to the compiler
protected void manifestUI() {

    //setContentView(R.layout.calculator_ui_responsive);
    // Link TextViews
    bigText = (TextView) findViewById(R.id.big_text);
    expressionText = (TextView) findViewById(R.id.expression_text);

    // Link Keypad
    zeroKey = (Button) findViewById(R.id.button_zero);
    oneKey = (Button) findViewById(R.id.button_one);
    twoKey = (Button) findViewById(R.id.button_two);
    threeKey = (Button) findViewById(R.id.button_three);
    fourKey = (Button) findViewById(R.id.button_four);
    fiveKey = (Button) findViewById(R.id.button_five);
    sixKey = (Button) findViewById(R.id.button_six);
    sevenKey = (Button) findViewById(R.id.button_seven);
    eightKey = (Button) findViewById(R.id.button_eight);
    nineKey = (Button) findViewById(R.id.button_nine);
    decimalKey = (Button)findViewById(R.id.button_decimal);
    backSpaceKey = (ImageButton) findViewById(R.id.button_delete);

    // Link Operators
    add = (Button) findViewById(R.id.button_add);
    subtract = (Button) findViewById(R.id.button_subtract);
    multiply = (Button) findViewById(R.id.button_multiply);
    divide = (Button) findViewById(R.id.button_divide);
    percentage = (Button) findViewById(R.id.button_percentage);
    squareRoot = (Button) findViewById(R.id.button_squareroot);
    operators = (HorizontalScrollView) findViewById(R.id.horizontalScrollView);
}}

Disclaimer: I am a product designer by profession and new to the exciting world of development.  Please don't be tough on me ;)


问:
What are the performance implications, if any, of chaining too many `.then`s on Promises?
I have an implementation of reduce that could potentially chain many .then handlers together.

```<code>const reduceIterable = (fn, x0, x) => {
  const iter = x[Symbol.iterator].call(x)
  let cursor = iter.next()
  if (cursor.done) {
    throw new TypeError('reduce(...)(x); x cannot be empty')
  }
  let y = !isUndefined(x0) ? fn(x0, cursor.value) : (() => {
    const x0 = cursor.value
    cursor = iter.next()
    return cursor.done ? x0 : fn(x0, cursor.value)
  })()
  cursor = iter.next()
  while (!cursor.done) {
    const { value } = cursor
    y = isPromise(y) ? y.then(res => fn(res, value)) : fn(y, value)
    cursor = iter.next()
  }
  return y
}

// you would use reduce like reduce(add, 0)([1, 2, 3]) // => 6
const reduce = (fn, x0) => {
  if (!isFunction(fn)) {
    throw new TypeError('reduce(x, y); x is not a function')
  }
  return x => {
    if (isIterable(x)) return reduceIterable(fn, x0, x)
    if (isAsyncIterable(x)) return reduceAsyncIterable(fn, x0, x)
    if (is(Object)(x)) return reduceObject(fn, x0, x)
    throw new TypeError('reduce(...)(x); x invalid')
  }
}
</code>```

Specifically, I'm looking at y.then(res => fn(res, value)). This keeps me up at night because of this issue. I know Promises have come a long way since then, but this has never been resolved. I really want to know if I'm okay to consume the Promise API like this, or if I need to do something harder.

答:
Creating as many promises as iterable elements, all at once, probably isn’t good for a generic function. It breaks down completely for infinite iterables.

You could break out to an async function on detecting a promise:

const reduceAwait = async (fn, initial, iterable) => {
  let m = await initial

  for (const n of iterable) {
    m = await fn(m, n)
  }

  return m
}

const reduceIterable = (fn, initial, iterable) => {
  const iterator = iterable[Symbol.iterator]()
  let m = initial

  if (initial === undefined) {
    const first = iter.next()

    if (first.done) {
      throw new TypeError('reduce of empty iterable with no initial value')
    }

    m = first.value
  }

  for (const n of iterator) {
    m = fn(m, n)

    if (isPromise(m)) {
      return reduceAwait(fn, m, iterator)
    }
  }

  return m
}
```

<p><code>m = await fn(m, n)</code> can also become</p>

<pre class="lang-js prettyprint-override"><code>m = fn(m, n)

if (isPromise(m)) {
  m = await m
}
</code>```

if you want minimal microtasks for mixed inputs.

Body:
I have an implementation of reduce that could potentially chain many .then handlers together.

const reduceIterable = (fn, x0, x) => {
  const iter = x[Symbol.iterator].call(x)
  let cursor = iter.next()
  if (cursor.done) {
    throw new TypeError('reduce(...)(x); x cannot be empty')
  }
  let y = !isUndefined(x0) ? fn(x0, cursor.value) : (() => {
    const x0 = cursor.value
    cursor = iter.next()
    return cursor.done ? x0 : fn(x0, cursor.value)
  })()
  cursor = iter.next()
  while (!cursor.done) {
    const { value } = cursor
    y = isPromise(y) ? y.then(res => fn(res, value)) : fn(y, value)
    cursor = iter.next()
  }
  return y
}

// you would use reduce like reduce(add, 0)([1, 2, 3]) // => 6
const reduce = (fn, x0) => {
  if (!isFunction(fn)) {
    throw new TypeError('reduce(x, y); x is not a function')
  }
  return x => {
    if (isIterable(x)) return reduceIterable(fn, x0, x)
    if (isAsyncIterable(x)) return reduceAsyncIterable(fn, x0, x)
    if (is(Object)(x)) return reduceObject(fn, x0, x)
    throw new TypeError('reduce(...)(x); x invalid')
  }
}

Specifically, I'm looking at y.then(res => fn(res, value)). This keeps me up at night because of this issue. I know Promises have come a long way since then, but this has never been resolved. I really want to know if I'm okay to consume the Promise API like this, or if I need to do something harder.

Body:
Creating as many promises as iterable elements, all at once, probably isn’t good for a generic function. It breaks down completely for infinite iterables.

You could break out to an async function on detecting a promise:

const reduceAwait = async (fn, initial, iterable) => {
  let m = await initial

  for (const n of iterable) {
    m = await fn(m, n)
  }

  return m
}

const reduceIterable = (fn, initial, iterable) => {
  const iterator = iterable[Symbol.iterator]()
  let m = initial

  if (initial === undefined) {
    const first = iter.next()

    if (first.done) {
      throw new TypeError('reduce of empty iterable with no initial value')
    }

    m = first.value
  }

  for (const n of iterator) {
    m = fn(m, n)

    if (isPromise(m)) {
      return reduceAwait(fn, m, iterator)
    }
  }

  return m
}

m = await fn(m, n) can also become

m = fn(m, n)

if (isPromise(m)) {
  m = await m
}

if you want minimal microtasks for mixed inputs.


问:
Wordpress Plugin Calling Database Results via AJAX
I have written a Wordpress plugin which generates content for a page, then tries to call Update.php via jQuery.load to refresh the results. For example:

Plugin generates this content:

```<code>global $wpdb;
$sql = "SELECT * FROM table ORDER BY id;";
$results = $wpdb->get_results($sql);
<div id="content">Database Results Here Via Loop</div>
</code>```

jQuery calls Update.php:

```<code><script type="text/javascript">
$(function() {
  var refresh = setInterval(function() {
    $("#content").load("Update.php");
  }, 5000);
});
</code>```

Update.php contains:

```<code><?php
function update_page() {
  global $wpdb;
  $sql = "SELECT * FROM table ORDER BY id;";
  $results = $wpdb->get_results($sql);
  echo "Parsed results go here";
}
update_page();
?>
</code>```

After 5 seconds, this results in a 'Fatal error: Call to a member function get_results() on a non-object' on the main page.

If I simply make Update.php return something like rand(), then it works fine and updates the div with a random number.  However, if I attempt to include the header that defines all the Wordpress classes (i.e. $wpdb) in the Update.php file (e.g. require_once("wp-blog-header.php");) then the AJAX simply stops working altogether, and won't even return a rand(), yet it will prevent the fatal error mentioned above from occurring.

I am completely lost.  Any help or just pointing me in the right direction would be greatly appreciated.  Thank you in advance, kind sirs.

答:
you are calling update.php file using ajax so wordpress is unable to load other its files so it is not finding $wpdb objects definition so you need to do is
require_once the wp-config.php and wp-includes/wp-db.php files

and create an object as $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

before the function update_page();

ContentLicense: CC BY-SA 2.5

Body:
I have written a Wordpress plugin which generates content for a page, then tries to call Update.php via jQuery.load to refresh the results. For example:

Plugin generates this content:

global $wpdb;
$sql = "SELECT * FROM table ORDER BY id;";
$results = $wpdb->get_results($sql);

Database Results Here Via Loop

jQuery calls Update.php:

ContentLicense: CC BY-SA 3.0


问:
Prevent font rendering as an emoji
I'm trying to render a custom checkbox in an Electron app.

:before {
    content: '✔';
}
```

It renders differently at random without any code changes:

It seems that it defaults to a font Segoe UI Emoji. Is it possible to force rendering as left picture (not as emoji)?

答:
It's possible to override the Emoji rendering of a psuedo element. I would recommend trying to use a special unicode character. U+FE0E (0xFE0E). Like so: content: "\2714 \FE0E";

content: "[enter your emoji unicode here] \FE0E";

I used this convert tool to get the right CSS unicode for the emoji to place inside the 'content': https://r12a.github.io/app-conversion/

About U+FE0E

This codepoint may change the appearance of the preceding character.
  If that is a symbol, dingbat or emoji, U+FE0E forces it to be rendered
  in a textual fashion as compared to a colorful image. The Unicode
  standard defines some standardized variants. See also “Unicode symbol
  as text or emoji” for a discussion of this codepoint.

Sources: https://codepoints.net/U+FE0E, https://mts.io/2015/04/21/unicode-symbol-render-text-emoji/

Example:

.test:before {
  content: "✔";
}

.test2:before {
  content: "\2714 \FE0E";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- if your looking in Chrome or Firefox this will both look the same -->
<div class="test"></div>
<div class="test2"></div></code>```

Title: Prevent font rendering as an emoji

Body:
I'm trying to render a custom checkbox in an Electron app.

:before {
    content: '✔';
}

It renders differently at random without any code changes:

It seems that it defaults to a font Segoe UI Emoji. Is it possible to force rendering as left picture (not as emoji)?

Body:
It's possible to override the Emoji rendering of a psuedo element. I would recommend trying to use a special unicode character. U+FE0E (0xFE0E). Like so: content: "\2714 \FE0E";

content: "[enter your emoji unicode here] \FE0E";

I used this convert tool to get the right CSS unicode for the emoji to place inside the 'content': https://r12a.github.io/app-conversion/

About U+FE0E

This codepoint may change the appearance of the preceding character.
  If that is a symbol, dingbat or emoji, U+FE0E forces it to be rendered
  in a textual fashion as compared to a colorful image. The Unicode
  standard defines some standardized variants. See also “Unicode symbol
  as text or emoji” for a discussion of this codepoint.

Sources: https://codepoints.net/U+FE0E, https://mts.io/2015/04/21/unicode-symbol-render-text-emoji/

Example:

.test:before {
  content: "✔";
}

.test2:before {
  content: "\2714 \FE0E";
}

<!-- if your looking in Chrome or Firefox this will both look the same -->
<div class="test"></div>
<div class="test2"></div>


问:
Can't pip install Tensorflow 'msvcp140_1.dll' missing
I am currently trying to pip install tensorflow, which works but after I install it, and then import it into my python module via import tensorflow as tf I get following error message:

```<code>ImportError: Could not find the DLL(s) 'msvcp140_1.dll'. TensorFlow requires that
these DLLs be installed in a directory that is named in your %PATH% environment
variable. You may install these DLLs by downloading "Microsoft C++ Redistributable
for Visual Studio 2015, 2017 and 2019" for your platform from this URL:
https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads
</code>```

I installed the msvcp140_1.dll and put it into C:\Users\User\AppData\Local\Programs\Python\Python37 which is contained in my path environment variable.

As you can see I am using Python 3.7 as 3.8 is not supported by tensorflow.
Any ideas how to fix this?

答:
In my case, Downloading Visual C++ from the url below works.

https://support.microsoft.com/en-gb/help/2977003/the-latest-supported-visual-c-downloads

Body:
I am currently trying to pip install tensorflow, which works but after I install it, and then import it into my python module via import tensorflow as tf I get following error message:

ImportError: Could not find the DLL(s) 'msvcp140_1.dll'. TensorFlow requires that
these DLLs be installed in a directory that is named in your %PATH% environment
variable. You may install these DLLs by downloading "Microsoft C++ Redistributable
for Visual Studio 2015, 2017 and 2019" for your platform from this URL:
https://support.microsoft.com/help/2977003/the-latest-supported-visual-c-downloads

I installed the msvcp140_1.dll and put it into C:\Users\User\AppData\Local\Programs\Python\Python37 which is contained in my path environment variable.

As you can see I am using Python 3.7 as 3.8 is not supported by tensorflow.
Any ideas how to fix this?


问:
Get time and number of OBIEE 12c users login
My requirement is just to monitor and know how many a user log in per month.I need to count number of logins for a user with the time they login

Can anyone please help me in how to do this?

Is there any log file such as obis1-query log file for queries processing monitoring in OBIEE to get these info?

Thanks

答:
I am going to share with you my finding about my question which has asked. As you may know, OBIEE repository tables, which can be used to show to end users as subject area that this is usgae tracking utility, just track information around sent queries to BI server and not more about users specifically. In this occasion, you can use a method which called enhanced usage tracking for OBIEE that is presented completely here: https://www.rittmanmead.com/blog/2016/12/enhanced-usage-tracking-for-obiee-now-available-as-open-source/

This is exactly what you want. All detail information about users activities in OBIEE and even some redundant ones. You can create a physical table, then add it to repository file and display as subject area to end user with any permission. Of course, according to your software environment or implementation structure, you are supposed to make some changes in this manner.

I hope this goes well.


问:
How to find acrued billing charges for Windows Azure
Is there a way or place to go to find out how much usage and ultimately costs have accrued against your Windows Azure account ? I am really interested in usage details so that I can get an estimate of costs for our application in test and try to predict when I scale it out.</p>

答:
In addition to David's answer, there are some tools starting to come through to assist with this problem  - e.g. see http://www.questcloudtools.com/azure/subscription-manager/

Disclaimer: I've not actually installed or used this myself


问:
How to change the labels to the image (icon) in bar chart.js
Help me, please.
How to change the labels to the image (icon) in bar chart.js ?
I mean, change from this
change labels: "LifeWall_files/logo.png","Bodily Functions","Sleep"

to this
bottom icons

答:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images (icons) instead of tick labels directly on the canvas using CanvasRenderingContext2D.

You'll also have to instruct Chart.js not to display the default tick labels. This can be done through the following definition inside the chart options.

```<code>scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }],
</code>```

Further you need to define some padding at the bottom of the chart, otherwise you'll see only part of the images.

```<code>layout: {
  padding: {
    bottom: 30
  }
},
</code>```

Please have a look at the runnable code snippet below.

const labels = ['red vans', 'blue vans', 'green vans', 'gray vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
const values = [48, 56, 33, 44];

new Chart(document.getElementById("myChart"), {
  type: "bar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
        var x = xAxis.getPixelForTick(index);
        var image = new Image();
        image.src = images[index],
        ctx.drawImage(image, x - 12, yAxis.bottom + 10);
      });
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      backgroundColor: ['red', 'blue', 'green', 'lightgray']
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        bottom: 30
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        }
      }],
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas></code>```

Body:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images (icons) instead of tick labels directly on the canvas using CanvasRenderingContext2D.

You'll also have to instruct Chart.js not to display the default tick labels. This can be done through the following definition inside the chart options.

scales: {
  xAxes: [{
    ticks: {
      display: false
    }
  }],

Further you need to define some padding at the bottom of the chart, otherwise you'll see only part of the images.

layout: {
  padding: {
    bottom: 30
  }
},

Please have a look at the runnable code snippet below.

const labels = ['red vans', 'blue vans', 'green vans', 'gray vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png'];
const values = [48, 56, 33, 44];

new Chart(document.getElementById("myChart"), {
  type: "bar",
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.chart.ctx;
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {
        var x = xAxis.getPixelForTick(index);
        var image = new Image();
        image.src = images[index],
        ctx.drawImage(image, x - 12, yAxis.bottom + 10);
      });
    }
  }],
  data: {
    labels: labels,
    datasets: [{
      label: 'My Dataset',
      data: values,
      backgroundColor: ['red', 'blue', 'green', 'lightgray']
    }]
  },
  options: {
    responsive: true,
    layout: {
      padding: {
        bottom: 30
      }
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        }
      }],
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>


问:
ERRORS in NetBeans " Class.forName("com.mysql.jdbc.Driver");"
i am using netbeans 8.2 and mysql 8.0 and inport mysql connector 8.0.11 to the library file as well for my following java codes,

```<code>package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBC {

    public static void main(String[] args) {
        String SQL="Insert into Customer Values('C111','Somadasa','Matugama',34000)";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
        Statement stm=connection.createStatement();
        stm.executeUpdate(SQL);
    }

}
</code>```

but following lines have been highlighted
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "mysql");

with the message 'unreported exception ClassNotFoundException; must be caught or declared to be thrown
----'
how could fix this problem?

答:
Just add throws in method signature, like this:</p>

```<code>public static void main(String[] args) throws ClassNotFoundException{
   //method body
}
</code>```

Body:
i am using netbeans 8.2 and mysql 8.0 and inport mysql connector 8.0.11 to the library file as well for my following java codes,

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBC {

    public static void main(String[] args) {
        String SQL="Insert into Customer Values('C111','Somadasa','Matugama',34000)";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
        Statement stm=connection.createStatement();
        stm.executeUpdate(SQL);
    }

}

but following lines have been highlighted
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "mysql");

with the message 'unreported exception ClassNotFoundException; must be caught or declared to be thrown
----'
how could fix this problem?

Body:
Just add throws in method signature, like this:

public static void main(String[] args) throws ClassNotFoundException{
   //method body
}


问:
query database for results within a certain time using the user's timezone
How can I query a set of results that belong to a specific time period according to the user's time.

For example: "select * from table where datestamp like ".date("Y-m-d",strtotime("-1 day"))."%"

would give me results within the past 24 hours based on the server time. How can I do this query to be based on the user's time rather than the server's time?

答: In order to find out how to get your web client timezone, please read this question</p>


问:
$.each return [object Object] while .map() do it correctly
I have some code:

```<code>$.getJSON(url, results => {

                    $('.search-output').html(`
                    <div class = "general">
                   ${results.generalinfo.map( (item, index) => {
                             return     `<h1>${item.title}</h1>`
                            })}
                        </div>

                    <div class = "profiles">

                     ${$.each(results.profiles, function(index, item) {

                     return     `<h1>${item.title}</h1>`

                     })}
                    </div> `)
                })
</code>```

With .map() function I can get all I want, but $.each() return [object Object]. What I tried in $.each function: JSON.stringify, .join() at the end - nothing changed. What is the difference between this functions and how I can use $.each() in this situation? Thanks.

答:
That's because you're setting the data on the tr and then filling it with your html, but still concatinating an object, which converts it to a string... aka

"[object Object]"
Not exactly sure what you're after but you might try changing this...

html += tr.data('trackinfo',value).html(tr_data);

To this...

html += tr.data('trackinfo',value).html(tr_data).html();

Body:
I have some code:

$.getJSON(url, results => {

                    $('.search-output').html(`

                   ${results.generalinfo.map( (item, index) => {
                             return     `<h1>${item.title}</h1>`
                            })}

                     ${$.each(results.profiles, function(index, item) {

                     return     `<h1>${item.title}</h1>`

                     })}

 `)
                })

With .map() function I can get all I want, but $.each() return [object Object]. What I tried in $.each function: JSON.stringify, .join() at the end - nothing changed. What is the difference between this functions and how I can use $.each() in this situation? Thanks.


问:
Conditional if else list data in react
I have json data and I have on the list. Here I want to use an empty data approval condition.

But I have not succeeded:

```<code>   componentDidMount(){
        this.getJson();
    }

 getJson= () => {

        const url = `https://example.com/priceon?ori=${a}&des=${b}`
        fetch(url)
          ....
    };

render() {
    //here I make a condition if the data exists and does not exist
    if (this.state.results == '') {
        return(
        <View>
            <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
        </View>
        );
    } else {
        return (
        <Container style={styles.container}>
                    <List
                        keyExtractor = {(item, index)=> index.toString()}
                        dataArray={this.state.results}
                        renderRow={(results) =>
                        <ListItem>
                            <Body>
                                <CardItem>
                                    <Text>{results.tipe} - {results.service}</Text>
                                </CardItem>
                            </Body>
                        </ListItem>
                    }>

      </Container>
    );
      }
    }
</code>```

How to make the right conditions?

If the data exists then it appears, if it is empty then display  null data

答:
Here is the code below :)</p>

```<code>render() {
//you can use ternary if statement, this is much more better than normal if(s)
return((this.state.results.length)?
    (<View>
        <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
    </View>):
    (<Container style={styles.container}>
                <List
                    keyExtractor = {(item, index)=> index.toString()}
                    dataArray={this.state.results}
                    renderRow={(results) =>
                    <ListItem>
                        <Body>
                            <CardItem>
                                <Text>{results.tipe} - {results.service}</Text>
                            </CardItem>
                        </Body>
                    </ListItem>
                }>
  </Container>));
}
</code>```

Title: Conditional if else list data in react

Body:
I have json data and I have on the list. Here I want to use an empty data approval condition.

But I have not succeeded:

   componentDidMount(){
        this.getJson();
    }

 getJson= () => {

        const url = `https://example.com/priceon?ori=${a}&des=${b}`
        fetch(url)
          ....
    };

render() {
    //here I make a condition if the data exists and does not exist
    if (this.state.results == '') {
        return(
        <View>
            <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
        </View>
        );
    } else {
        return (
        <Container style={styles.container}>
                    <List
                        keyExtractor = {(item, index)=> index.toString()}
                        dataArray={this.state.results}
                        renderRow={(results) =>
                        <ListItem>

                                <CardItem>
                                    <Text>{results.tipe} - {results.service}</Text>
                                </CardItem>

                        </ListItem>
                    }>

      </Container>
    );
      }
    }

How to make the right conditions?

If the data exists then it appears, if it is empty then display  null data

Body:
Here is the code below :)

render() {
//you can use ternary if statement, this is much more better than normal if(s)
return((this.state.results.length)?
    (<View>
        <Text style={{fontWeight:'bold',fontSize:16}}>DATA NULL</Text>
    </View>):
    (<Container style={styles.container}>
                <List
                    keyExtractor = {(item, index)=> index.toString()}
                    dataArray={this.state.results}
                    renderRow={(results) =>
                    <ListItem>
                        <Body>
                            <CardItem>
                                <Text>{results.tipe} - {results.service}</Text>
                            </CardItem>
                        </Body>
                    </ListItem>
                }>
  </Container>));
}


问:
How to build an image upload object and append to request in Laravel
i am trying to build an image upload object and append to a request in Laravel.

I currently have a middleware that intercepts requests and check if there are base64 image strings in it and if there are, it converts it to image object and appends it back to the request.

I have been unsuccessful in appending the converted images back to the request as an instance of Illuminate\Http\UploadedFile i have tried a few things the closest thing i found was UploadedFile::fake()->image('avatar.jpg'); but how can i use my own base64 converted image instead of the generate fake image as looking through the UploadedFile Api i could not come up with a solution.

This is what i have so far

```<code><?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Support\Facades\Validator;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Http\UploadedFile;

    class Base64EncodedImageHandler
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if ($request->has('photos')) {

                $validator = Validator::make($request->all(), [
                    'photos' => 'nullable|array|filled',
                    'photos.*' => 'required_unless:photos,'.null.'|image',
                ]);

                if ($validator->fails()) {

                    $images = collect($request->input('photos'))->map(function ($item, $key) {

                        if (preg_match('/^data:image\/(\w+);base64,/', $item)) {
                            $data = substr($item, strpos($item, ',') + 1);

                            $data = base64_decode($data);

                            // Testing to see if the image decoding worked
                            // Storage::disk('local')->put("public/test/".uniqid().".png", $data);

                            // Build image object

                            return $data;

                        }

                        return $item;
                    });

                    $request = $request->merge(['photos' => $images]);

                }

                // Dumping request object here
                dd($request);

            }

            return $next($request);
        }
    }
</code>```

Based on the answers i got i was able to achieve my initial objective as so

```<code><?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Http\UploadedFile;

    class Base64EncodedImageHandler
    {
        /**
         * Handle an incoming request.
         *
         * @author Sayra
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // Add an additional method
            $request::macro('setConvertedFiles', function ($files) {
                $this->convertedFiles = $files;
                return $this;
            });

            if ($request->has('portrait')) {

                $images = collect($request->input('portrait'))->map(function ($item, $key) {

                    if (preg_match('/^data:image\/(\w+);base64,/', $item)) {
                        $item = substr($item, strpos($item, ',') + 1);
                        $image = base64_decode($item);

                        $path = 'public/test/';
                        $name = uniqid();
                        $extension = '.jpg';

                        // Store converted file
                        if (Storage::put($path.$name, $image)){

                            return new UploadedFile(storage_path('app/').$path.$name, $name.$extension, 'image/jpeg');
                        }
                    }

                })->all();

                // Added base64 converted files to request, clear base64 params
                $photos = $request->photos? $request->photos : [];
                $merge = array_merge($photos, $images);
                $request->setConvertedFiles(['photos' => $merge]);
                $request->merge(['photos' => $merge]);
                $request->merge(['portrait' => []]);

                // the isValid() method fails as the file was not a direct upload
                dd($request->file('photos.0')->isValid(),$request->file('photos'),$request);

            }

            return $next($request);
        }
    }
</code>```

My current and only issue is that when isValid or is_uploaded_file() is called the image is seen as an invalid image i would like to properly fake the image upload so that the base64 converted images will work and go through the same process as the normal images. Thanks.

答:
You can try with Symfony\Component\HttpFoundation\File\UploadedFile to create image object (you should first save your base64 file somewhere temporary, since UploadedFile requires path). Then in your Base64EncodedImageHandler use trait Illuminate\Http\Concerns\InteractsWithInput.

You will need this method: protected function convertUploadedFiles(array $files) which accepts array of symfony UploadedFile. This will make Illuminate\Http\UploadedFile object. Now when you say $request->merge(['photos' => $images]) your 'photos' will be array of UploadedFile objects which you can manipulate.

I am not sure, but maybe your $request->file() will be still empty. If this is true you can create new request, fill it with all other data from original one, but for files give converted UploadedFile array.

Also check this https://github.com/laravel/framework/issues/10791#issuecomment-213529251
They are using custom FormRequest trait to overwrite ->all() method. You may try the same with ->allFiles() or even overwrite $files property. Keep in mind it accepts FileBag, not array

Body:
i am trying to build an image upload object and append to a request in Laravel.

I currently have a middleware that intercepts requests and check if there are base64 image strings in it and if there are, it converts it to image object and appends it back to the request.

I have been unsuccessful in appending the converted images back to the request as an instance of Illuminate\Http\UploadedFile i have tried a few things the closest thing i found was UploadedFile::fake()->image('avatar.jpg'); but how can i use my own base64 converted image instead of the generate fake image as looking through the UploadedFile Api i could not come up with a solution.

This is what i have so far

<?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Support\Facades\Validator;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Http\UploadedFile;

    class Base64EncodedImageHandler
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            if ($request->has('photos')) {

                $validator = Validator::make($request->all(), [
                    'photos' => 'nullable|array|filled',
                    'photos.*' => 'required_unless:photos,'.null.'|image',
                ]);

                if ($validator->fails()) {

                    $images = collect($request->input('photos'))->map(function ($item, $key) {

                        if (preg_match('/^data:image\/(\w+);base64,/', $item)) {
                            $data = substr($item, strpos($item, ',') + 1);

                            $data = base64_decode($data);

                            // Testing to see if the image decoding worked
                            // Storage::disk('local')->put("public/test/".uniqid().".png", $data);

                            // Build image object

                            return $data;

                        }

                        return $item;
                    });

                    $request = $request->merge(['photos' => $images]);

                }

                // Dumping request object here
                dd($request);

            }

            return $next($request);
        }
    }

Based on the answers i got i was able to achieve my initial objective as so

<?php

    namespace App\Http\Middleware;

    use Closure;
    use Illuminate\Support\Facades\Storage;
    use Illuminate\Http\UploadedFile;

    class Base64EncodedImageHandler
    {
        /**
         * Handle an incoming request.
         *
         * @author Sayra
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // Add an additional method
            $request::macro('setConvertedFiles', function ($files) {
                $this->convertedFiles = $files;
                return $this;
            });

            if ($request->has('portrait')) {

                $images = collect($request->input('portrait'))->map(function ($item, $key) {

                    if (preg_match('/^data:image\/(\w+);base64,/', $item)) {
                        $item = substr($item, strpos($item, ',') + 1);
                        $image = base64_decode($item);

                        $path = 'public/test/';
                        $name = uniqid();
                        $extension = '.jpg';

                        // Store converted file
                        if (Storage::put($path.$name, $image)){

                            return new UploadedFile(storage_path('app/').$path.$name, $name.$extension, 'image/jpeg');
                        }
                    }

                })->all();

                // Added base64 converted files to request, clear base64 params
                $photos = $request->photos? $request->photos : [];
                $merge = array_merge($photos, $images);
                $request->setConvertedFiles(['photos' => $merge]);
                $request->merge(['photos' => $merge]);
                $request->merge(['portrait' => []]);

                // the isValid() method fails as the file was not a direct upload
                dd($request->file('photos.0')->isValid(),$request->file('photos'),$request);

            }

            return $next($request);
        }
    }

My current and only issue is that when isValid or is_uploaded_file() is called the image is seen as an invalid image i would like to properly fake the image upload so that the base64 converted images will work and go through the same process as the normal images. Thanks.


问:
React. How to implement scrolling to active list item?
I build music player with search by the artist.

CODE SANDBOX

this how my SongsList component looks like:

```<code>    const SongsList = (props) => {
  const {
    loading,
    errorMessage,
    songsList,
    toggleActive,
    setToggleActive,
  } = props;
  return (
    <div className='player-list'>
      <div className='songs__list'>
        {loading && !errorMessage ? (
          <span>Loading...</span>
        ) : errorMessage ? (
          <div className='errorMessage'>{errorMessage}</div>
        ) : (
          songsList.map((song, index) => (
            <Song
              key={`${index}`}
              song={song}
              index={index}
              active={toggleActive === index}
              setToggleActive={() => {
                setToggleActive(index);
                // console.log(toggleActive);
              }}
            />
          ))
        )}
      </div>
    </div>
  );
};
</code>```

Now I want to implement scrolling the SongList based on the activeSong position, so the active song will always change scrollbar position automatically
to make it visible. What is the best way to do this?

答:
I have resolved this using ref for a single song

```<code>  const SongsList = (props) => {
</code>```

...

```<code>const refs = songsList.reduce((song, value) => {
    song[value.id] = React.createRef();
    return song;
  }, {});
</code>```

...

and method call scrollIntoView

```<code> const handleClick = id =>
    refs[id].current.scrollIntoView({
      behavior: "smooth",
      block: "start"
    });
</code>```

...

then in the Song.js component add this scroll() method

```<code>const Song = ({...}) => {
  const scroll = () => (active ? scrollView(song.id) : undefined);
  useEffect(() => scroll());
</code>```

...

CodeSandbox finall resolve

Body:
I build music player with search by the artist.

CODE SANDBOX

this how my SongsList component looks like:

    const SongsList = (props) => {
  const {
    loading,
    errorMessage,
    songsList,
    toggleActive,
    setToggleActive,
  } = props;
  return (

        {loading && !errorMessage ? (
          Loading...
        ) : errorMessage ? (

{errorMessage}

        ) : (
          songsList.map((song, index) => (
            <Song
              key={`${index}`}
              song={song}
              index={index}
              active={toggleActive === index}
              setToggleActive={() => {
                setToggleActive(index);
                // console.log(toggleActive);
              }}
            />
          ))
        )}

  );
};

Now I want to implement scrolling the SongList based on the activeSong position, so the active song will always change scrollbar position automatically
to make it visible. What is the best way to do this?

Body:
I have resolved this using ref for a single song

  const SongsList = (props) => {

...

const refs = songsList.reduce((song, value) => {
    song[value.id] = React.createRef();
    return song;
  }, {});

...

and method call scrollIntoView

 const handleClick = id =>
    refs[id].current.scrollIntoView({
      behavior: "smooth",
      block: "start"
    });

...

then in the Song.js component add this scroll() method

const Song = ({...}) => {
  const scroll = () => (active ? scrollView(song.id) : undefined);
  useEffect(() => scroll());

...

CodeSandbox finall resolve


问:
how to fix "import win32api # noqa: E402 ImportError: DLL load failed while importing win32api: %1 is not a valid"
import win32api
from pywinauto import application

app = application.Application
app.start("Notepad.exe")

答:
This is can be due to different bit versions of applications you are using here

refer:https://www.youtube.com/watch?v=fGuHMVAruAE

so better to check the bit versions


问:
Akka-stream group only Right elements of Either
I have a source which emits Either[String, MyClass].

I want to call an external service with batches of MyClass and continue downstream with Either[String, ExternalServiceResponse], that's why I need to group elements of stream.

If the stream would emit only MyClass elements, it would be easy - just call grouped:

```<code>val source: Source[MyClass, NotUsed] = <custom implementation>
source
  .grouped(10)                 // Seq[MyClass]
  .map(callExternalService(_)) // ExternalServiceResponse
</code>```

But how to group only elements on the right side of Either in my scenario?

```<code>val source: Source[Either[String, MyClass], NotUsed] = <custom implementation>
source
  .???                                                      // Either[String, Seq[MyClass]]
  .map {
    case Right(myClasses) => callExternalService(myClasses)
    case Left(string) => Left(string)
  }                                                         // Either[String, ExternalServiceResponse]
</code>```

The following works, but is there any more idiomatic way?

```<code>val source: Source[Either[String, MyClass], NotUsed] = <custom implementation>
source
  .groupBy(2, either => either.isRight)
  .grouped(10)
  .map(input => input.headOption match {
    case Some(Right(_)) =>
      callExternalService(input.map(item => item.right.get))
    case _ =>
      input
  })
  .mapConcat(_.to[scala.collection.immutable.Iterable])
  .mergeSubstreams
</code>```

答:
You could divide your source of eithers in two branches in order to process rights their own way and then merge back the two sub-flows:</p>

```<code>// case class MyClass(x: Int)
// case class ExternalServiceResponse(xs: Seq[MyClass])
// def callExternalService(xs: Seq[MyClass]): ExternalServiceResponse =
//    ExternalServiceResponse(xs)
// val source: Source[Either[String, MyClass], _] =
//   Source(List(Right(MyClass(1)), Left("2"), Right(MyClass(3)), Left("4"), Right(MyClass(5))))

val lefts: Source[Either[String, Nothing], _] =
  source
    .collect { case Left(l) => Left(l) }

val rights: Source[Either[Nothing, ExternalServiceResponse], _] =
  source
    .collect { case Right(x: MyClass) => x }
    .grouped(2)
    .map(callExternalService)
    .map(Right(_))

val out: Source[Either[String, ExternalServiceResponse], _] = rights.merge(lefts)

// out.runForeach(println)
// Left(2)
// Right(ExternalServiceResponse(Vector(MyClass(1), MyClass(3))))
// Left(4)
// Right(ExternalServiceResponse(Vector(MyClass(5))))
</code>```

Body:
I have a source which emits Either[String, MyClass].

I want to call an external service with batches of MyClass and continue downstream with Either[String, ExternalServiceResponse], that's why I need to group elements of stream.

If the stream would emit only MyClass elements, it would be easy - just call grouped:

val source: Source[MyClass, NotUsed] = <custom implementation>
source
  .grouped(10)                 // Seq[MyClass]
  .map(callExternalService(_)) // ExternalServiceResponse

But how to group only elements on the right side of Either in my scenario?

val source: Source[Either[String, MyClass], NotUsed] = <custom implementation>
source
  .???                                                      // Either[String, Seq[MyClass]]
  .map {
    case Right(myClasses) => callExternalService(myClasses)
    case Left(string) => Left(string)
  }                                                         // Either[String, ExternalServiceResponse]

The following works, but is there any more idiomatic way?

val source: Source[Either[String, MyClass], NotUsed] = <custom implementation>
source
  .groupBy(2, either => either.isRight)
  .grouped(10)
  .map(input => input.headOption match {
    case Some(Right(_)) =>
      callExternalService(input.map(item => item.right.get))
    case _ =>
      input
  })
  .mapConcat(_.to[scala.collection.immutable.Iterable])
  .mergeSubstreams

Body:
You could divide your source of eithers in two branches in order to process rights their own way and then merge back the two sub-flows:

// case class MyClass(x: Int)
// case class ExternalServiceResponse(xs: Seq[MyClass])
// def callExternalService(xs: Seq[MyClass]): ExternalServiceResponse =
//    ExternalServiceResponse(xs)
// val source: Source[Either[String, MyClass], _] =
//   Source(List(Right(MyClass(1)), Left("2"), Right(MyClass(3)), Left("4"), Right(MyClass(5))))

val lefts: Source[Either[String, Nothing], _] =
  source
    .collect { case Left(l) => Left(l) }

val rights: Source[Either[Nothing, ExternalServiceResponse], _] =
  source
    .collect { case Right(x: MyClass) => x }
    .grouped(2)
    .map(callExternalService)
    .map(Right(_))

val out: Source[Either[String, ExternalServiceResponse], _] = rights.merge(lefts)

// out.runForeach(println)
// Left(2)
// Right(ExternalServiceResponse(Vector(MyClass(1), MyClass(3))))
// Left(4)
// Right(ExternalServiceResponse(Vector(MyClass(5))))


问:
AWS certificate renewal failed, problem trying to update CNAME records
I received an email from AWS:

To renew this certificate, you must ensure that the proper CNAME
  records are present in your DNS configuration for each domain listed
  below

So I went to https://ap-northeast-2.console.aws.amazon.com/acm/ and grabbed the CNAME and tried to create a CNAME record in route-53

It fails with message

[RRSet of type CNAME with DNS name example.kr. is not permitted at
  apex in zone example.kr.]

I have a A record for example.kr which I created by following directions in https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-elb-load-balancer.html

RRSet of type CNAME with DNS name foo.com. is not permitted at apex in zone bar.com says I'm getting the error message because I have SOA record for the domain, I have no idea why I have this record, and if I need it or not.

Can I simply delete SOA record and proceed or should I take different steps?

答:
It seems to me that the error you're seeing is because you're setting a CNAME on your root record (referred to as Apex record). This should be an A record (or Alias record in Route 53 when possible).

For validating your certificate via CNAME you will be given both a CNAME record and a value.

The CNAME record should start with an underscore followed by a large hash such as

_a79865eb4cd1a6ab990a45779b4e0b96.yourdomain.com.

If using Route 53 you should only need to enter _a79865eb4cd1a6ab990a45779b4e0b96 as the domain name of type CNAME

You would then have a value similar to _x2.acm-validations.aws.. This would need to be your value.


问:
Is it possible to detect that your javascript code is executing because of an event?
If you don't control the invocation of your code, but would like to know if it's being executed by an event handler, is this possible?</p>

答:
You could maybe do this if you had a way to look up the stack, but that's not a very good way to do it. This article shows how to access the stack.

A Javascript stacktrace in any browser

OwnerDisplayName: daveb

OwnerDisplayName: sjbotha


问:
How do I append CSV using CSV helper?
I went through documentation and I didn't see anything for it. I'm using the same exact write function from documentation but the problem is I also need to append. So far I've tried reading it than adding the CSV into a list than I write the list to CSV. Is there a better way I could append?

The exact write function I use with my own variables

```<code>var records = new List<Foo>
{
    new Foo { Id = 1, Name = "one" },
};

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
}
</code>```

What I use to read but with my own variables:

```<code>using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<Foo>();
}
</code>```

Hopefully someone can help!

答:
Use the StreamWriter(String, Boolean)  constructor to specify you want to append to an existing file:

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Parameters

path

String

The complete file path to write to.

append

Boolean

true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

As for your CsvHelper CsvWriter, you need to configure it to omit the header depending on if you are appending or creating:

```<code>bool append = true;
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
config.HasHeaderRecord = !append;

using (var writer = new StreamWriter("path\\to\\file.csv", append))
{
    using (var csv = new CsvWriter(writer, config))
    {
        csv.WriteRecords(records);
    }
}
</code>```

Title: How do I append CSV using CSV helper?

Body:
I went through documentation and I didn't see anything for it. I'm using the same exact write function from documentation but the problem is I also need to append. So far I've tried reading it than adding the CSV into a list than I write the list to CSV. Is there a better way I could append?

The exact write function I use with my own variables

var records = new List<Foo>
{
    new Foo { Id = 1, Name = "one" },
};

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
}

What I use to read but with my own variables:

using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<Foo>();
}

Hopefully someone can help!

Body:
Use the StreamWriter(String, Boolean)  constructor to specify you want to append to an existing file:

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Parameters

path

String

The complete file path to write to.

append

Boolean

true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

As for your CsvHelper CsvWriter, you need to configure it to omit the header depending on if you are appending or creating:

bool append = true;
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
config.HasHeaderRecord = !append;

using (var writer = new StreamWriter("path\\to\\file.csv", append))
{
    using (var csv = new CsvWriter(writer, config))
    {
        csv.WriteRecords(records);
    }
}


问:
JShell error "unexpected type" when using specific class name
I was just playing around with JShell, and it seems that defining class Z{} and then defining
var z = new Z() does not work. But using different class names, like class X and class A, does work.

Surely I must be missing something obvious...?

```<code>|  Welcome to JShell -- Version 14.0.1
|  For an introduction type: /help intro

jshell> class X{}
|  created class X

jshell> class Z{}
|  created class Z

jshell> var x = new X()
x ==> X@26a1ab54
|  created variable x : X

jshell> var z = new Z()
|  Error:
|  unexpected type
|    required: class
|    found:    type parameter Z
|  var z = new Z();
|              ^

jshell> class A{}
|  created class A

jshell> var a = new A()
a ==> A@2ef1e4fa
|  created variable a : A
</code>```

答:
Use of var can lead to a variable having a non-denotable type. For example, looking at the return type of an expression that could be String or Integer:

```<code>jshell> /set feedback verbose
jshell> var x = true ? "a" : 1
x ==> "a"
|  created variable x : Serializable&Comparable<? extends Serializable&Comparable<?>&java.lang.constant.Constable&java.lang.constant.ConstantDesc>&java.lang.constant.Constable&java.lang.constant.ConstantDesc
</code>```

When jshell is evaluating your code fragment, if this is the case, it wraps it in a block of code so that it can record this type for later use. The wrapping fragment includes a generic type parameter called Z:

```<code>        // private static <Z> Z do_itAux() {
        //     wtype x_ = y;
        //     @SuppressWarnings("unchecked")
        //     Z x__ = (Z) x_;
        //     return x__;
</code>```

This parameter's name leaks into the code block being evaluated, meaning the class's name is shadowed by the type parameter. This makes Z a special case -- the other single character examples are fine.

Body:
I was just playing around with JShell, and it seems that defining class Z{} and then defining
var z = new Z() does not work. But using different class names, like class X and class A, does work.

Surely I must be missing something obvious...?

|  Welcome to JShell -- Version 14.0.1
|  For an introduction type: /help intro

jshell> class X{}
|  created class X

jshell> class Z{}
|  created class Z

jshell> var x = new X()
x ==> X@26a1ab54
|  created variable x : X

jshell> var z = new Z()
|  Error:
|  unexpected type
|    required: class
|    found:    type parameter Z
|  var z = new Z();
|              ^

jshell> class A{}
|  created class A

jshell> var a = new A()
a ==> A@2ef1e4fa
|  created variable a : A

Body:
Use of var can lead to a variable having a non-denotable type. For example, looking at the return type of an expression that could be String or Integer:

jshell> /set feedback verbose
jshell> var x = true ? "a" : 1
x ==> "a"
|  created variable x : Serializable&Comparable<? extends Serializable&Comparable<?>&java.lang.constant.Constable&java.lang.constant.ConstantDesc>&java.lang.constant.Constable&java.lang.constant.ConstantDesc

When jshell is evaluating your code fragment, if this is the case, it wraps it in a block of code so that it can record this type for later use. The wrapping fragment includes a generic type parameter called Z:

        // private static <Z> Z do_itAux() {
        //     wtype x_ = y;
        //     @SuppressWarnings("unchecked")
        //     Z x__ = (Z) x_;
        //     return x__;

This parameter's name leaks into the code block being evaluated, meaning the class's name is shadowed by the type parameter. This makes Z a special case -- the other single character examples are fine.


答:
You can use the scales argument in facet_grid. free_y will rescale the y-axis per facet, free_x does the same for the x-axis.

```<code>  geom_line(aes(y = actual_data, color = "actual_data"), size = 1) +
  geom_line(aes(y = point_forecast,  color = "point_forecast"), size = 1) +
  geom_line(aes(y = forecast_upper_interval, color = "forecast_interval"), size = 1) +
  geom_line(aes(y = forecast_lower_interval, color = "forecast_interval"), size = 1) +
  scale_colour_manual("",
                      breaks = c("actual_data","point_forecast","forecast_interval"),
                      values = c("black","red","blue")) +
  geom_vline(xintercept = 2019.917) +
  labs(title = "...",
       subtitle = "...",
       y = "Demand", x = "Period") +
  facet_grid(group ~ method, scales = "free_y")
</code>```

Title: R ggplot : How to set y-axis limit / scale differently on multiple plot

Body:
My name is Ihsan, sorry if my English isn't understandable,
I need help to set the y-axis limit/scale on my multiple plots differently for each group/row because some plot is not quite obvious.

This is my multiple plots :

As you can see, the plot in "smooth" is not quite obvious. I also wonder if there is a way to set the y-axis adaptively follows the data range.

This is my data :

coba <- structure(list(time = c(2018, 2018.08333333333, 2018.16666666667,
2018.25, 2018.33333333333, 2018.41666666667, 2018.5, 2018.58333333333,
2018.66666666667, 2018.75, 2018.83333333333, 2018.91666666667,
2019, 2019.08333333333, 2019.16666666667, 2019.25, 2019.33333333333,
2019.41666666667, 2019.5, 2019.58333333333, 2019.66666666667,
2019.75, 2019.83333333333, 2019.91666666667, 2020, 2020.08333333333,
2020.16666666667, 2018, 2018.08333333333, 2018.16666666667, 2018.25,
2018.33333333333, 2018.41666666667, 2018.5, 2018.58333333333,
2018.66666666667, 2018.75, 2018.83333333333, 2018.91666666667,
2019, 2019.08333333333, 2019.16666666667, 2019.25, 2019.33333333333,
2019.41666666667, 2019.5, 2019.58333333333, 2019.66666666667,
2019.75, 2019.83333333333, 2019.91666666667, 2020, 2020.08333333333,
2020.16666666667, 2018, 2018.08333333333, 2018.16666666667, 2018.25,
2018.33333333333, 2018.41666666667, 2018.5, 2018.58333333333,
2018.66666666667, 2018.75, 2018.83333333333, 2018.91666666667,
2019, 2019.08333333333, 2019.16666666667, 2019.25, 2019.33333333333,
2019.41666666667, 2019.5, 2019.58333333333, 2019.66666666667,
2019.75, 2019.83333333333, 2019.91666666667, 2020, 2020.08333333333,
2020.16666666667, 2018, 2018.08333333333, 2018.16666666667, 2018.25,
2018.33333333333, 2018.41666666667, 2018.5, 2018.58333333333,
2018.66666666667, 2018.75, 2018.83333333333, 2018.91666666667,
2019, 2019.08333333333, 2019.16666666667, 2019.25, 2019.33333333333,
2019.41666666667, 2019.5, 2019.58333333333, 2019.66666666667,
2019.75, 2019.83333333333, 2019.91666666667, 2020, 2020.08333333333,
2020.16666666667), group = c("smooth", "smooth", "smooth", "smooth",
"smooth", "smooth", "smooth", "smooth", "smooth", "smooth", "smooth",
"smooth", "smooth", "smooth", "smooth", "smooth", "smooth", "smooth",
"smooth", "smooth", "smooth", "smooth", "smooth", "smooth", "smooth",
"smooth", "smooth", "intermittent", "intermittent", "intermittent",
"intermittent", "intermittent", "intermittent", "intermittent",
"intermittent", "intermittent", "intermittent", "intermittent",
"intermittent", "intermittent", "intermittent", "intermittent",
"intermittent", "intermittent", "intermittent", "intermittent",
"intermittent", "intermittent", "intermittent", "intermittent",
"intermittent", "intermittent", "intermittent", "intermittent",
"erratic", "erratic", "erratic", "erratic", "erratic", "erratic",
"erratic", "erratic", "erratic", "erratic", "erratic", "erratic",
"erratic", "erratic", "erratic", "erratic", "erratic", "erratic",
"erratic", "erratic", "erratic", "erratic", "erratic", "erratic",
"erratic", "erratic", "erratic", "lumpy", "lumpy", "lumpy", "lumpy",
"lumpy", "lumpy", "lumpy", "lumpy", "lumpy", "lumpy", "lumpy",
"lumpy", "lumpy", "lumpy", "lumpy", "lumpy", "lumpy", "lumpy",
"lumpy", "lumpy", "lumpy", "lumpy", "lumpy", "lumpy", "lumpy",
"lumpy", "lumpy"), actual_data = c(0, 148, 94, 48, 151, 0, 0,
14, 70, 48, 59, 89, 103, 85, 72, 249, 70, 46, 63, 0, 43, 117,
183, 62, NA, NA, NA, 0, 0, 0, 0, 0, 2, 120, 351, 740, 0, 394,
669, 770, 349, 742, 915, 268, 296, 481, 0, 63, 0, 429, 228, NA,
NA, NA, 0, 0, 0, 393, 361, 262, 237, 149, 181, 776, 383, 150,
545, 284, 1076, 1167, 447, 19, 51, 13, 13, 169, 538, 570, NA,
NA, NA, 0, 0, 0, 0, 0, 0, 0, 0, 585, 61, 0, 0, 0, 0, 0, 3984,
347, 59, 0, 2, 17, 1, 0, 0, NA, NA, NA), method = c("svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr", "svr",
"svr", "svr", "svr", "svr", "svr", "svr", "svr"), point_forecast = c(NA,
NA, NA, 48.0996753799743, 79.5763438172094, 48.0168972734219,
48.0168972734219, 48.0168972734219, 69.9006492400514, 48.0996753799743,
59.0996753799743, 79.5763438172094, 79.5763438172094, 79.5763438172094,
71.9006492400514, 79.5763438172094, 69.8996753799743, 48.0168972734219,
63.7966205453156, 63.7966225343945, 63.7966205453156, 63.7966205453156,
63.7966205453156, 63.7966205453156, 63.7966205453156, 63.7966205453156,
63.7966205453156, NA, NA, NA, 119.710429582372, 119.710429582372,
119.710429582372, 120.000076084306, 137.39733157014, 179.964594161607,
270.374297388654, 271.837813656059, 385.11113900032, 233.638110791947,
349.000038463594, 386.717352711958, 437.389525425775, 343.279790315616,
394.438380626949, 429.986683473783, 282.09801758862, 241.1518231132,
266.213987530171, 125.039828056053, 199.439585161278, 185.69329793194,
286.371735962498, 239.492466873368, NA, NA, NA, 313.799269157967,
360.999742531489, 288.862188705292, 237.000573000286, 255.272473592413,
258.315891228577, 281.838344144049, 382.99969919893, 210.885123868099,
183.464705260668, 323.498548254514, 233.87978297062, 394.527456786046,
343.803751510101, 100.114046104047, 138.16020518945, 272.138049378457,
303.624284268614, 307.559874757169, 328.144675742086, 354.374346612312,
284.447520684868, 188.434018129088, 224.321511121496, NA, NA,
NA, 1, 1, 1, 1, 1, 1, 12.0605783660873, 1, 1, 1, 1, 1, 1, 12.0605783660873,
12.0605783660873, 5.74024787118026, 5.74024787118026, 5.73200607066632,
5.74024787118026, 5.74024787118026, 5.74024787118026, 3.59820241512781,
5.74008590554601, 5.74024787118026), forecast_upper_interval = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 170.452414082618, 170.452414082618,
170.452414082618, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 706.442123116566,
807.120561147124, 760.241292057993, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, 876.133361363783, 780.119858808003, 816.007351800411, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 1709.16785604818, 1711.3097395386,
1711.30990150424), forecast_lower_interval = c(NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, 0, 0, 0, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0,
0, 0, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0, 0, 0, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 0, 0, 0)), row.names = 244:351, class = "data.frame")

This is my code :

library(ggplot2)
ggplot(data = coba, aes(x = time)) +
  geom_line(aes(y = actual_data, color = "actual_data"), size = 1) +
  geom_line(aes(y = point_forecast,  color = "point_forecast"), size = 1) +
  geom_line(aes(y = forecast_upper_interval, color = "forecast_interval"), size = 1) +
  geom_line(aes(y = forecast_lower_interval, color = "forecast_interval"), size = 1) +
  scale_colour_manual("",
                      breaks = c("actual_data","point_forecast","forecast_interval"),
                      values = c("black","red","blue")) +
  geom_vline(xintercept = 2019.917) +
  labs(title = "...",
       subtitle = "...",
       y = "Demand", x = "Period") +
  facet_grid(group ~ method)

Thank you! I'd really appreciate any help or suggestion

Body:
You can use the scales argument in facet_grid. free_y will rescale the y-axis per facet, free_x does the same for the x-axis.

  geom_line(aes(y = actual_data, color = "actual_data"), size = 1) +
  geom_line(aes(y = point_forecast,  color = "point_forecast"), size = 1) +
  geom_line(aes(y = forecast_upper_interval, color = "forecast_interval"), size = 1) +
  geom_line(aes(y = forecast_lower_interval, color = "forecast_interval"), size = 1) +
  scale_colour_manual("",
                      breaks = c("actual_data","point_forecast","forecast_interval"),
                      values = c("black","red","blue")) +
  geom_vline(xintercept = 2019.917) +
  labs(title = "...",
       subtitle = "...",
       y = "Demand", x = "Period") +
  facet_grid(group ~ method, scales = "free_y")