问:
Re-uploading a file with AJAX after it was changed causes net::ERR_UPLOAD_FILE_CHANGED in Chrome
I have a simple HTML form that sends an selected file via AJAX to an API endpoint.

If I do the following steps:

Press the Upload button and make an POST request to upload the file

Change the selected file on the filesystem (in a text editor), without picking it again in the file picker.

Press the Upload button again, and make as second POST request

Chrome will fail the second request with an error: net::ERR_UPLOAD_FILE_CHANGED. Note that if you change the file before the initial upload, the file will be uploaded without a problem. The error happens only on the second upload, when you change the file after an initial successful upload. I am testing this with CSV files, and changing them in a text editor.

There does not seem to be a way to isolate that error.

Is there any way around this?

If not, is it possible to catch this specific error, and display a meaningful message to the user. The error that Fetch returns in the promise has no specific info about this. The only place where I see the ERR_UPLOAD_FILE_CHANGED is in the browser dev console.

I am pretty sure that there was not any problem with this about a year ago (early 2019), as the possibility to re-upload a changed file, played in nicely in our UI flow. Now we need to force the user to pick the file again. So my assumption that this was introduced with a recent chrome update.

Here is a simplified snippet of the code:

```<code><html>
<head>
        <script type='text/javascript'>
        document.addEventListener("DOMContentLoaded", function(){

                const button = document.querySelector('#btnSubmit');

                button.addEventListener('click', () => {
                        const form = new FormData(document.querySelector('#theForm'));
                        const url = '/my-api'
                        const request = new Request(url, {
                                method: 'POST',
                                body: form
                        });

                        fetch(request).then(function() {
                                console.log("ok");
                        }).catch(function(err) {
                                console.log(err);
                        });
                });
        });
        </script>

</head>
<body>
        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" /></td>
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>
</body>
</html>
</code>```

EDIT: The bug is marked as WontFix on bugs.chromium.org: https://bugs.chromium.org/p/chromium/issues/detail?id=1086707#c7

答:
No, if the user has changed file it already another file so you can't (should not) get access to this file without user explicit user action otherwise it would be a security issue.

You can save the file in the memory when user uploads it.

document.getElementById('fileInput').addEventListener('change', function() {
   saveFileConentInMemory(this.files[0].arrayBuffer());
});
```

<p>And when the user press the "Send" button just get this content from memory and send it</p>

<pre class="lang-js prettyprint-override"><code>button.addEventListener('click', () => {
   const file = getFileContentFromMemeory();
   send(file);
})
</code>```

Yes, you can't be sure that you send the latest version of the file but you should be sure that you send the content which was uploaded.

Also, you should aware of memory consumption and asynchronous API of reading file (so you still can get this error about changed content even when you write it in memory)

Body:
I have a simple HTML form that sends an selected file via AJAX to an API endpoint.

If I do the following steps:

Press the Upload button and make an POST request to upload the file

Change the selected file on the filesystem (in a text editor), without picking it again in the file picker.

Press the Upload button again, and make as second POST request

Chrome will fail the second request with an error: net::ERR_UPLOAD_FILE_CHANGED. Note that if you change the file before the initial upload, the file will be uploaded without a problem. The error happens only on the second upload, when you change the file after an initial successful upload. I am testing this with CSV files, and changing them in a text editor.

There does not seem to be a way to isolate that error.

Is there any way around this?

If not, is it possible to catch this specific error, and display a meaningful message to the user. The error that Fetch returns in the promise has no specific info about this. The only place where I see the ERR_UPLOAD_FILE_CHANGED is in the browser dev console.

I am pretty sure that there was not any problem with this about a year ago (early 2019), as the possibility to re-upload a changed file, played in nicely in our UI flow. Now we need to force the user to pick the file again. So my assumption that this was introduced with a recent chrome update.

Here is a simplified snippet of the code:

        <form enctype="multipart/form-data" action="" method="post" id='theForm'>
                <input type="file" name="csvfile" id="csvfile" value="" />
                <input type="button" name="uploadCSV" value="Upload" id='btnSubmit'/>
        </form>

EDIT: The bug is marked as WontFix on bugs.chromium.org: https://bugs.chromium.org/p/chromium/issues/detail?id=1086707#c7

Body:
No, if the user has changed file it already another file so you can't (should not) get access to this file without user explicit user action otherwise it would be a security issue.

You can save the file in the memory when user uploads it.

document.getElementById('fileInput').addEventListener('change', function() {
   saveFileConentInMemory(this.files[0].arrayBuffer());
});

And when the user press the "Send" button just get this content from memory and send it

button.addEventListener('click', () => {
   const file = getFileContentFromMemeory();
   send(file);
})

Yes, you can't be sure that you send the latest version of the file but you should be sure that you send the content which was uploaded.

Also, you should aware of memory consumption and asynchronous API of reading file (so you still can get this error about changed content even when you write it in memory)


来源: stackexchange

问:
In tensorflow.js, what is recommended way of reshaping a tensor?
I currently am working on getting a keras trained model working on a browser via tensorflow.js.  I have to reduce the size of the image to 48x48 before passing into my model since all the data I trained on was that size. I've gone about reducing the size of my webcam snapshot to 48x48 using:

```<code>let imgclone = tf.image.resizeBilinear(imgmod, [48,48], true).toFloat();
</code>```

This allows me to draw correctly to the canvas and get my realtime reduced-size webcam stream in a smaller canvas. I then went to pass the snapshot to my model and I am getting the below error:

expected conv2d_1_input to have shape [null,48,48,1] but got array
  with shape [1,48,48,3].

So I just wasn't sure on the proper way of getting my final shaped tensor would be when using tensorflow.js.  I did try to use tf.reshape(preprocedimg, [null, 48, 48, 1]) but ofcourse this only modified the shape and provided an error that my size didnt match.

Going to continue scouring Google, but thought I would post here as well.  Any info you might be able to provide would be greatly appreciated!

答:
I had the same problem. I just want to share the solution I found.

tf.browser.fromPixels (pixels, numChannels?)
numChannels default is 3(RGB), change it to 1 like below.

```<code>let tensor = tf.fromPixels(image,1)
</code>```

I hope that helps to you as well.

TensorFlow document (https://js.tensorflow.org/api/latest/#browser.fromPixels)

ContentLicense: CC BY-SA 4.0

Body:
I currently am working on getting a keras trained model working on a browser via tensorflow.js.  I have to reduce the size of the image to 48x48 before passing into my model since all the data I trained on was that size. I've gone about reducing the size of my webcam snapshot to 48x48 using:

let imgclone = tf.image.resizeBilinear(imgmod, [48,48], true).toFloat();

This allows me to draw correctly to the canvas and get my realtime reduced-size webcam stream in a smaller canvas. I then went to pass the snapshot to my model and I am getting the below error:

expected conv2d_1_input to have shape [null,48,48,1] but got array
  with shape [1,48,48,3].

So I just wasn't sure on the proper way of getting my final shaped tensor would be when using tensorflow.js.  I did try to use tf.reshape(preprocedimg, [null, 48, 48, 1]) but ofcourse this only modified the shape and provided an error that my size didnt match.

Going to continue scouring Google, but thought I would post here as well.  Any info you might be able to provide would be greatly appreciated!

Body:
I had the same problem. I just want to share the solution I found.

tf.browser.fromPixels (pixels, numChannels?)
numChannels default is 3(RGB), change it to 1 like below.

let tensor = tf.fromPixels(image,1)

I hope that helps to you as well.

TensorFlow document (https://js.tensorflow.org/api/latest/#browser.fromPixels)


问:
Find document with the biggest number of matches (and less number of unmatched) in an array
Considering I have the following documents (excluding the _id):

```<code>[
  {
    "array": [
      1,
      2,
      3,
      4
    ],
    "string": "doc1"
  },
  {
    "array": [
      3,
      4,
      5
    ],
    "string": "doc2"
  }
]
</code>```

I want to find the document that has the most common elements in “array” compared to [2,3,4]. The returned document should be:

```<code>{
    "array": [
      1,
      2,
      3,
      4
    ],
    "string": "doc1"
}
</code>```

(3 matches)

However if the search is [3,4,6] the returned document should be:

```<code>{
    "array": [
      3,
      4,
      5
    ],
    "string": "doc2"
  }
</code>```

Because both share the same number of matches (2) but the returned document has less elements that don’t match (1 element compared to 2 elements on the other document).

How can I accomplish a query that finds the “best” intersection of the query array with document’s ones?

答:
You can use the $setIntersection operator to calculate a new array and the filter by it's size along with the size of array:

```<code>db.collection.aggregate([
    {
        $addFields: {
            size: { $size: "$array" },
            intersectionSize: { $size: { $setIntersection: [ [2,3,4], "$array" ] } }
        }
    },
    {
        $sort: {
            intersectionSize: -1,
            size: 1
        }
    },
    {
        $limit: 1
    },
    {
        $project: {
            size: 0,
            intersectionSize: 0
        }
    }
])
</code>```

Mongo Playground (1)

Mongo Playground (2)

EDIT: sort by size ascending is needed because if there's the same number of matching elements the shorter array will be promoted

Body:
Considering I have the following documents (excluding the _id):

[
  {
    "array": [
      1,
      2,
      3,
      4
    ],
    "string": "doc1"
  },
  {
    "array": [
      3,
      4,
      5
    ],
    "string": "doc2"
  }
]

I want to find the document that has the most common elements in “array” compared to [2,3,4]. The returned document should be:

{
    "array": [
      1,
      2,
      3,
      4
    ],
    "string": "doc1"
}

(3 matches)

However if the search is [3,4,6] the returned document should be:

{
    "array": [
      3,
      4,
      5
    ],
    "string": "doc2"
  }

Because both share the same number of matches (2) but the returned document has less elements that don’t match (1 element compared to 2 elements on the other document).

How can I accomplish a query that finds the “best” intersection of the query array with document’s ones?

Body:
You can use the $setIntersection operator to calculate a new array and the filter by it's size along with the size of array:

db.collection.aggregate([
    {
        $addFields: {
            size: { $size: "$array" },
            intersectionSize: { $size: { $setIntersection: [ [2,3,4], "$array" ] } }
        }
    },
    {
        $sort: {
            intersectionSize: -1,
            size: 1
        }
    },
    {
        $limit: 1
    },
    {
        $project: {
            size: 0,
            intersectionSize: 0
        }
    }
])

Mongo Playground (1)

Mongo Playground (2)

EDIT: sort by size ascending is needed because if there's the same number of matching elements the shorter array will be promoted


问:
Firefox video support
I want to play html5 videos in my page but there are certain videos that cannot be played in firefox or edge, but can be played in chrome. Firefox says "Video can't be played because the file is corrupt." and edge just doesn't play it, no error or anything.

This is the codec for the video that all three browsers can play:

This is the codec for the video only the chrome can play:

I tried playing the video from a direct url, without an html5 video tag, but still the same things are happening. Does anyone know what might be the problem?

Update: I know that not every browser supports all the codecs but I am asking what is the exact codec problem here, because I could not find out which codec setting is causing the problem. I am using H264 MPEG-4 AVC codec for both of the videos.

答:
Decoded format: Planar 4:4:4 YUV

This sampling is not supported by the majority of decoders. You must reencode the file to 4:2:0

Title: Firefox video support


问:
Problem when i try to convert the htaccess to nginx file, triggers a download
How can i convert this .htaccess to NGINX?

```<code><IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.(js|css|jpeg|jpg|gif|png|ico|map)(\?|$) /404error.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

I've tried this:

```<code>  location / {

        try_files $uri $uri/ /index.php?$args;
    }

</code>```

but always when i click to another link to other address it trigger to download a file called download

This is an example to normal url
http://forum.example.net/index.php?/discover/

how should it be:
http://forum.example.net/discover/

I'm using ipboard v4.4.10

答:
try adding a php location block

```<code>location ~ \.php$ {
    ...
    include fastcgi_params;
    fastcgi_pass php;
}
</code>```

Reference: Nginx serves .php files as downloads, instead of executing them

Body:
How can i convert this .htaccess to NGINX?

<IfModule mod_rewrite.c>
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule \.(js|css|jpeg|jpg|gif|png|ico|map)(\?|$) /404error.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I've tried this:

  location / {

        try_files $uri $uri/ /index.php?$args;
    }

but always when i click to another link to other address it trigger to download a file called download

This is an example to normal url
http://forum.example.net/index.php?/discover/

how should it be:
http://forum.example.net/discover/

I'm using ipboard v4.4.10

Body:
try adding a php location block

location ~ \.php$ {
    ...
    include fastcgi_params;
    fastcgi_pass php;
}

Reference: Nginx serves .php files as downloads, instead of executing them


问:
Percentage ratio within each bin in stacked histogram
I have a stacked histogram corresponding to three categories (Cat-I, II, III), so that in each bin I can see the frequency of each category. I would prefer to have the Y-axis showing the percentage ratio of each category in each bin so that the ratios of the three categories in each bin add up to 1. I tried the following approach to get the stacked histogram, any help on how to tweak the code so that I can show the percentage ratio would be highly appreciated. I know that setting density=True will give the probability density but I am not looking for it.</p>

```<code>import numpy as np
import matplotlib.pyplot as plt
data1=np.loadtxt('C:/Users/Hrihaan/Desktop/Cat-I.txt')
data2=np.loadtxt('C:/Users/Hrihaan/Desktop/Cat-II.txt')
data3=np.loadtxt('C:/Users/Hrihaan/Desktop/Cat-III.txt')
x1=data1[:,1]
x2=data2[:,1]
x3=data3[:,1]
bins= 8
bins_list = [301, 340, 372, 405, 431, 472, 514, 599, 949] # I defined the bins range so that I have bins of equal elements, the first 7 bins all have 23 elemnets where the last has 24
plt.hist([x1,x3,x2], bins=bins_list, histtype='bar', color=["mediumspringgreen", "pink", "lightskyblue"], stacked=True, edgecolor='dimgrey', linewidth=20, density=False)
</code>```

答:
You can first convert x1, x2, and x3 data into respective bins using qcut and then get the percentage by dividing by total for every bin. Say x1[0]/(x1[0]+x2[0]+x3[0])</p>

```<code>pd.qcut(x1, q=bins_list, labels=False)
</code>```

Body:
I have a stacked histogram corresponding to three categories (Cat-I, II, III), so that in each bin I can see the frequency of each category. I would prefer to have the Y-axis showing the percentage ratio of each category in each bin so that the ratios of the three categories in each bin add up to 1. I tried the following approach to get the stacked histogram, any help on how to tweak the code so that I can show the percentage ratio would be highly appreciated. I know that setting density=True will give the probability density but I am not looking for it.

import numpy as np
import matplotlib.pyplot as plt
data1=np.loadtxt('C:/Users/Hrihaan/Desktop/Cat-I.txt')
data2=np.loadtxt('C:/Users/Hrihaan/Desktop/Cat-II.txt')
data3=np.loadtxt('C:/Users/Hrihaan/Desktop/Cat-III.txt')
x1=data1[:,1]
x2=data2[:,1]
x3=data3[:,1]
bins= 8
bins_list = [301, 340, 372, 405, 431, 472, 514, 599, 949] # I defined the bins range so that I have bins of equal elements, the first 7 bins all have 23 elemnets where the last has 24
plt.hist([x1,x3,x2], bins=bins_list, histtype='bar', color=["mediumspringgreen", "pink", "lightskyblue"], stacked=True, edgecolor='dimgrey', linewidth=20, density=False)

Body:
You can first convert x1, x2, and x3 data into respective bins using qcut and then get the percentage by dividing by total for every bin. Say x1[0]/(x1[0]+x2[0]+x3[0])

pd.qcut(x1, q=bins_list, labels=False)


问:
MySQL Query to automatically populate permanent events into a table without repeating the input process
I'm using MySQL dB and two tables are named "perm_events" for the repeated events and "reservations" to store the individual events that do not repeat, respectably. The "perm_events" table exists for the sole purpose of NOT having to type in the same information repeatedly. This is a question regarding the "perm_events".

For example:

Event A: Scheduled to go on every Sunday, 8am to 9am indefinitely.

Event B: Scheduled for every Tuesday, Thursday, between 12/1/2019 and 12/31/2019.

I'm using PHP UI to gather the information about events and I want to write a query base on the information collected from the UI.

Info gathered: (This will be stored in "perm_events" table.)

```<code>Event name: Event B
Location:   Rm. 1
Start time:  9:00AM
End Time:   10:00AM
Weekdays:   Tue, Thu
Start Date: 12/1/2019 (If NULL, the event is permanent)
End Date:   12/31/2019
</code>```

Base on the collected info above, I want to populate a table containing the below:

```<code>   DATE    WKDAY EVENT NAME LOCATION STARTING_TIME ENDING_TIME
---------- ----- ---------- -------- ------------- -----------
12/03/2019  TUE   EVENT B     Rm. 1    9:00AM        10:00AM
12/05/2019  THU   EVENT B     Rm. 1    9:00AM        10:00AM
12/10/2019  TUE   EVENT B     Rm. 1    9:00AM        10:00AM
12/12/2019  THU   EVENT B     Rm. 1    9:00AM        10:00AM
                            .
                            .
12/31/2019  TUE   EVENT B     Rm. 1    9:00AM        10:00AM
</code>```

Currently, I am entering the ABOVE event as a series of events for the duration from 12/3/2019 through 12/31/2019, as the UI shown below (The below are stored in "reservations" table):

```<code>event_name: Event B(1)
location: Rm. 1
start_time: 9:00AM
end_time: 10:00AM
date: 12/3/2019
end_date: 12/31/2019
(Reserve Button)
</code>```

After reserving this event, I'd go on to the next by repeating the process until the process is complete - as shown below.

```<code>event_name: Event B(2)
location: Rm. 1
start_time: 9:00AM
end_time: 10:00AM
date: 12/5/2019
end_date: 12/31/2019
(Reserve Button)
.
.
and so on...
</code>```

I'd have to do this seemingly endless process until the process is complete (I think there are 8 or 9 in the above example). Moreover, for the permanent events that DO NOT have END DATES, I'd have to continually enter the same event information over-and-over again.

Simply put, I am looking to save time by NOT entering the event information repeatedly for an extended event or permanent event - one-by-one. It would be much more efficient process.

How do I go about doing this?

thank you in advance to all the experts who'll read my question.

答:
I finally was able to solve the task with a help from Strawberry (many thanks to Strawberry).

I ended up NOT using MySQL query - rather, I utilized the "Bitwise Operator" to compare individual weekday-bits with combined week-bit, as introduced to me by Strawberry. (See code below with following comment:

// Compare bitwise operator(&) $wkDayBit(1 thru 127) and $daybit(pow(2,$i++)).)

The "Bitwise operator" technique was a key to solving this task.

the code below is a simplified version of what I'm using currently.

I hope the below will help someone who is in a similar situation.

```<code><?php
  // Initialize variables.
  $wkDayBit  = 0;
  $count     = 1;
  $frmWkday  = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
  $wkdays    = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
  $wkDayBits = array(1, 2, 4, 8, 16, 32, 64);
  $permEvtArray = array();

  // Credit to HADI for the below function.
  function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d') {
    $dates   = array();
    $current = strtotime($first);
    $last    = strtotime($last);

    while ($current <= $last) {
      $dates[] = date($format, $current);
      $current = strtotime($step, $current);
    }
    return $dates;
  }

  if (isset($_POST['addPermEvent'])) {
    if (isset($_POST['wkday'])) {
      $ttlRep = 0;                        // Initialize the variable $ttlRep.
      $tmpWkDayBits = $_POST['wkday'];    // Assign array 'wkday' to $tmpWkDayBits.

      // Loop through the newly assigned $tmpWkDayBits using foreach loop
      foreach ($tmpWkDayBits as $row => $tmpWkDayBit) {
        $wkDayBit = $wkDayBit + $tmpWkDayBit;
      }
    }

    // Call function dateRange() & get all dates that are between start date and end  date.
    $dateRange = dateRange($_POST['stDate'], $_POST['endDate']);

    // Convert the bitwise integer to an array (Credit to Sammitch for this bit).
    for ($i=0; $i<7; $i++) {          // $i = loop 0 thru 6
      $daybit = pow(2,$i);            // 1, 2, 4, 8, 16, 32, 64

      // Compare bitwise operator(&) $wkDayBit(1 thru 127) and $daybit(pow(2,$i++)).
      if ($wkDayBit & $daybit) {
        $newWkdays[]=$frmWkday[$i];
      }
    }

    // Increment $ttlRep with # days of dated perm events one at a time (e.g., #/$ttlRep)
    foreach ($dateRange as $rsvDate) {
      if (in_array(date('D', strtotime($rsvDate)), $newWkdays)) {
        $ttlRep ++;
      }
    }

    /*-----------------------------------------------------
    Compare to see if checked weekday(s), that is(are)
    in the date-range($dateRange) is in $newWkdays[] array.
     +-----------------------------------------------------*/
    foreach ($dateRange as $rsvDate) {
      if (in_array(date('D', strtotime($rsvDate)), $newWkdays)) {

        // Add a counter to the event title.
        $eventTitle = $_POST['permEvTtl'] . " [" . $count . "/" . $ttlRep . "]";
        $count++;

        // Assign each event details to an array.
        $permEvt = [
          'eventTitle' => $eventTitle,                         // Text field
          "reservDate" => $rsvDate,                            // 2020-06-01 format
          "wkDay" => $wkdays[date('w', strtotime($rsvDate))],  // $wkdays['n']
          "reservTime" => date('g:i A', strtotime($_POST['stTime'])), // 8:00 PM
          "endTime" => date('g:i A', strtotime($_POST['endTime'])), // 8:00 PM format
          'userGr' => $_POST['userGr'],                             // Text field
          'rmReserv' => $_POST['rmReserv'],                         // Text field
          'reservCreated' => date('Y-m-d H:i:s')  // 2020-06-01 22:32:06 format
        ];

        $permEvtArray[] = $permEvt;
      }
    }
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="chrome">
  <link rel='stylesheet' type='text/css' href='assets/css/testCodes.css'>
  <title>Permanent Events Test Codes</title>
</head>
<body>
<div class="permEvent-form">
  <form method="POST">
    <h3>BOOK PERM EVENT</h3>
  <div>
    <label for="permEvTtl">Perm Event Title:</label>
    <input type="text" name="permEvTtl" id="permEvTtl" required placeholder="Title"><br>
    <label for="rmReserv">Room/Loc:</label>
    <input type="text" name="rmReserv" id="rmReserv" required placeholder="Room"><br>
  </div>
  <div>
    <label for="stDate">Start/End Dates:</label>
    <input type="date" name="stDate" id="stDate" required>
    <input type="date" name="endDate" id="endDate" required>
  </div>
  <div>
    <label for="stTime">Start/End Times:</label>
    <input type="time" name="stTime" id="stTime" required>
    <input type="time" name="endTime" id="endTime" required>
  </div>
  <div>
    <label for="userGr">User Group:</label>
    <input type="text" name="userGr" id="userGr" required placeholder="Group"><br>
  </div>
  <div class="wkday_chk">
    <h3>Weekdays</h3>
    <?php for ($i=0; $i<7; $i++): ?>
      <input type="checkbox" name="wkday[]" id="<?php echo $frmWkday[$i]?>" value="<?php echo $wkDayBits[$i]?>">
      <label for="<?php echo $frmWkday[$i]?>"><?php echo $frmWkday[$i]?></label>
    <?php endfor ?>
  </div>
  <div class="permAdd_btn">
    <input type="submit" name="addPermEvent" value="ADD PERM EVENT">
  </div>
  </form>
</div>

<div class="reserv-table">
  <table>
    <thead>
      <tr>
        <th>DATE<br>WKDAY</th>
        <th>STA TIME<br>END TIME</th>
        <th>EVENT TITLE</th>
        <th>LOCATION<br>GROUP</th>
        <th>RESERVED ON</th>
      </tr>
   </thead>
   <tbody>
      <!-- loop through rm_reserved VIEW to populate Reservation table -->
      <?php if ($permEvtArray != NULL):?>
        <?php foreach ($permEvtArray as $rsv):?>
          <tr>
            <td><strong><?php echo $rsv["reservDate"]."<br>".$rsv["wkDay"]?></strong></td>
            <td><?php echo $rsv["reservTime"]."<br>".$rsv["endTime"]?></td>
            <td><?php echo $rsv["eventTitle"]?></td>
            <td><?php echo $rsv["rmReserv"]."<br>".$rsv["userGr"]?></td>
            <td><?php echo "<strong>".$rsv["reservCreated"]?></td>
          </tr>
        <?php endforeach?>
      <?php endif ?>
    </tbody>
  </table>
</div>
</body>
</html>
</code>```

Body:
I'm using MySQL dB and two tables are named "perm_events" for the repeated events and "reservations" to store the individual events that do not repeat, respectably. The "perm_events" table exists for the sole purpose of NOT having to type in the same information repeatedly. This is a question regarding the "perm_events".

For example:

Event A: Scheduled to go on every Sunday, 8am to 9am indefinitely.

Event B: Scheduled for every Tuesday, Thursday, between 12/1/2019 and 12/31/2019.

I'm using PHP UI to gather the information about events and I want to write a query base on the information collected from the UI.

Info gathered: (This will be stored in "perm_events" table.)

Event name: Event B
Location:   Rm. 1
Start time:  9:00AM
End Time:   10:00AM
Weekdays:   Tue, Thu
Start Date: 12/1/2019 (If NULL, the event is permanent)
End Date:   12/31/2019

Base on the collected info above, I want to populate a table containing the below:

   DATE    WKDAY EVENT NAME LOCATION STARTING_TIME ENDING_TIME
---------- ----- ---------- -------- ------------- -----------
12/03/2019  TUE   EVENT B     Rm. 1    9:00AM        10:00AM
12/05/2019  THU   EVENT B     Rm. 1    9:00AM        10:00AM
12/10/2019  TUE   EVENT B     Rm. 1    9:00AM        10:00AM
12/12/2019  THU   EVENT B     Rm. 1    9:00AM        10:00AM
                            .
                            .
12/31/2019  TUE   EVENT B     Rm. 1    9:00AM        10:00AM

Currently, I am entering the ABOVE event as a series of events for the duration from 12/3/2019 through 12/31/2019, as the UI shown below (The below are stored in "reservations" table):

event_name: Event B(1)
location: Rm. 1
start_time: 9:00AM
end_time: 10:00AM
date: 12/3/2019
end_date: 12/31/2019
(Reserve Button)

After reserving this event, I'd go on to the next by repeating the process until the process is complete - as shown below.

event_name: Event B(2)
location: Rm. 1
start_time: 9:00AM
end_time: 10:00AM
date: 12/5/2019
end_date: 12/31/2019
(Reserve Button)
.
.
and so on...

I'd have to do this seemingly endless process until the process is complete (I think there are 8 or 9 in the above example). Moreover, for the permanent events that DO NOT have END DATES, I'd have to continually enter the same event information over-and-over again.

Simply put, I am looking to save time by NOT entering the event information repeatedly for an extended event or permanent event - one-by-one. It would be much more efficient process.

How do I go about doing this?

thank you in advance to all the experts who'll read my question.

Body:
I finally was able to solve the task with a help from Strawberry (many thanks to Strawberry).

I ended up NOT using MySQL query - rather, I utilized the "Bitwise Operator" to compare individual weekday-bits with combined week-bit, as introduced to me by Strawberry. (See code below with following comment:

// Compare bitwise operator(&) $wkDayBit(1 thru 127) and $daybit(pow(2,$i++)).)

The "Bitwise operator" technique was a key to solving this task.

the code below is a simplified version of what I'm using currently.

I hope the below will help someone who is in a similar situation.

<?php
  // Initialize variables.
  $wkDayBit  = 0;
  $count     = 1;
  $frmWkday  = array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
  $wkdays    = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
  $wkDayBits = array(1, 2, 4, 8, 16, 32, 64);
  $permEvtArray = array();

  // Credit to HADI for the below function.
  function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d') {
    $dates   = array();
    $current = strtotime($first);
    $last    = strtotime($last);

    while ($current <= $last) {
      $dates[] = date($format, $current);
      $current = strtotime($step, $current);
    }
    return $dates;
  }

  if (isset($_POST['addPermEvent'])) {
    if (isset($_POST['wkday'])) {
      $ttlRep = 0;                        // Initialize the variable $ttlRep.
      $tmpWkDayBits = $_POST['wkday'];    // Assign array 'wkday' to $tmpWkDayBits.

      // Loop through the newly assigned $tmpWkDayBits using foreach loop
      foreach ($tmpWkDayBits as $row => $tmpWkDayBit) {
        $wkDayBit = $wkDayBit + $tmpWkDayBit;
      }
    }

    // Call function dateRange() & get all dates that are between start date and end  date.
    $dateRange = dateRange($_POST['stDate'], $_POST['endDate']);

    // Convert the bitwise integer to an array (Credit to Sammitch for this bit).
    for ($i=0; $i<7; $i++) {          // $i = loop 0 thru 6
      $daybit = pow(2,$i);            // 1, 2, 4, 8, 16, 32, 64

      // Compare bitwise operator(&) $wkDayBit(1 thru 127) and $daybit(pow(2,$i++)).
      if ($wkDayBit & $daybit) {
        $newWkdays[]=$frmWkday[$i];
      }
    }

    // Increment $ttlRep with # days of dated perm events one at a time (e.g., #/$ttlRep)
    foreach ($dateRange as $rsvDate) {
      if (in_array(date('D', strtotime($rsvDate)), $newWkdays)) {
        $ttlRep ++;
      }
    }

    /*-----------------------------------------------------
    Compare to see if checked weekday(s), that is(are)
    in the date-range($dateRange) is in $newWkdays[] array.
     +-----------------------------------------------------*/
    foreach ($dateRange as $rsvDate) {
      if (in_array(date('D', strtotime($rsvDate)), $newWkdays)) {

        // Add a counter to the event title.
        $eventTitle = $_POST['permEvTtl'] . " [" . $count . "/" . $ttlRep . "]";
        $count++;

        // Assign each event details to an array.
        $permEvt = [
          'eventTitle' => $eventTitle,                         // Text field
          "reservDate" => $rsvDate,                            // 2020-06-01 format
          "wkDay" => $wkdays[date('w', strtotime($rsvDate))],  // $wkdays['n']
          "reservTime" => date('g:i A', strtotime($_POST['stTime'])), // 8:00 PM
          "endTime" => date('g:i A', strtotime($_POST['endTime'])), // 8:00 PM format
          'userGr' => $_POST['userGr'],                             // Text field
          'rmReserv' => $_POST['rmReserv'],                         // Text field
          'reservCreated' => date('Y-m-d H:i:s')  // 2020-06-01 22:32:06 format
        ];

        $permEvtArray[] = $permEvt;
      }
    }
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="chrome">
  <link rel='stylesheet' type='text/css' href='assets/css/testCodes.css'>
  <title>Permanent Events Test Codes</title>
</head>
<body>
<div class="permEvent-form">
  <form method="POST">
    <h3>BOOK PERM EVENT</h3>
  <div>
    <label for="permEvTtl">Perm Event Title:</label>
    <input type="text" name="permEvTtl" id="permEvTtl" required placeholder="Title"><br>
    <label for="rmReserv">Room/Loc:</label>
    <input type="text" name="rmReserv" id="rmReserv" required placeholder="Room"><br>
  </div>
  <div>
    <label for="stDate">Start/End Dates:</label>
    <input type="date" name="stDate" id="stDate" required>
    <input type="date" name="endDate" id="endDate" required>
  </div>
  <div>
    <label for="stTime">Start/End Times:</label>
    <input type="time" name="stTime" id="stTime" required>
    <input type="time" name="endTime" id="endTime" required>
  </div>
  <div>
    <label for="userGr">User Group:</label>
    <input type="text" name="userGr" id="userGr" required placeholder="Group"><br>
  </div>
  <div class="wkday_chk">
    <h3>Weekdays</h3>
    <?php for ($i=0; $i<7; $i++): ?>
      <input type="checkbox" name="wkday[]" id="<?php echo $frmWkday[$i]?>" value="<?php echo $wkDayBits[$i]?>">
      <label for="<?php echo $frmWkday[$i]?>"><?php echo $frmWkday[$i]?></label>
    <?php endfor ?>
  </div>
  <div class="permAdd_btn">
    <input type="submit" name="addPermEvent" value="ADD PERM EVENT">
  </div>
  </form>
</div>

<div class="reserv-table">
  <table>
    <thead>
      <tr>
        <th>DATE<br>WKDAY</th>
        <th>STA TIME<br>END TIME</th>
        <th>EVENT TITLE</th>
        <th>LOCATION<br>GROUP</th>
        <th>RESERVED ON</th>
      </tr>
   </thead>
   <tbody>
      <!-- loop through rm_reserved VIEW to populate Reservation table -->
      <?php if ($permEvtArray != NULL):?>
        <?php foreach ($permEvtArray as $rsv):?>
          <tr>
            <td><strong><?php echo $rsv["reservDate"]."<br>".$rsv["wkDay"]?></strong></td>
            <td><?php echo $rsv["reservTime"]."<br>".$rsv["endTime"]?></td>
            <td><?php echo $rsv["eventTitle"]?></td>
            <td><?php echo $rsv["rmReserv"]."<br>".$rsv["userGr"]?></td>
            <td><?php echo "<strong>".$rsv["reservCreated"]?></td>
          </tr>
        <?php endforeach?>
      <?php endif ?>
    </tbody>
  </table>
</div>
</body>
</html>


问:
jScrollPane Over Video in Safari Resulting in Distorted Text
My site: http://shuttersonthebeach.com

My browser/os: Safari 5.0.4 +/Mac

The issue: click on either 'calendar' or 'specials' in the masthead of the page.  An overlay should reveal.  Inside of that overlay there are columns of text w/ custom scroll bars (jScrollPane).  In Safari, only on pages that have a flash header, the text inside of the custom scroll area is being distorted.  This is not the case in any other browser (including Chrome).

My best educated guess was that it had something to do with the wmode parameter of the flash object.  I tried changing the wmode from 'transparent' to 'opaque' but the problem persisted.  I also considered the possibility of a z-index related issue... from what I can tell, this also is not the problem.

I have searched the web high and low for someone else who is experiencing something similar but I have not been successful.  Any assistance you could provide would be greatly appreciated.

Thanks!

UPDATE: I determined that removing jScrollPane and adding overflow auto fixes the text distortion issue [Please see attached image].  Of course, this is not a solution because I do not want to use the default browser scrollbars but it may be useful info for debugging.

ANOTHER UPDATE: This issue is not related to flash specifically. The distorted/blurred text occurs over HTML5 video as well in Safari.

答:
I came across the following article when searching for something different and I thought it might be useful:

http://johanbrook.com/design/css/a-fix-for-antialiasing-issues-in-webkit-browsers/

It mentions hardware acceleration and position: relative being the culprits of the disappearing anti-aliasing. You can't do anything about position: relative (since jScrollPane needs that internally) but maybe changing the WMODE of the flash could help?

ContentLicense: CC BY-SA 3.0


问:
How can I spawn as many requests as needed to get unique results from an API?
I'm working on an excercise to get different random results from an API using JavaScript.

Mi idea is to have an array of results I already got and issue as many asynchronous requests as I need to get the job done.

I tried using Axios and jQuery (I'm supposed to use the first one but it didn't work and since I'm more experienced with jQuery I decided to give it a try) but neither one works.

Here's my code:

```<code>let categories = [];

    function fillCatsWithAxios() {
            let spawn = 5;
            while (categories.length < 5) {
                    if (spawn) {
                            let offset = Math.floor(Math.random() * 1000);
                            console.log('Spawning one with offset ' + offset);
                            axios.get('http://jservice.io/api/categories', {
                            params: {
                                    count: 1,
                                    offset: offset
                            }
                            }).then(function(value) {
                                    let id = value.data[0].id;
                                    console.log('Got one! Id = ' + id );
                                    if (categories.indexOf(id) == -1) {
                                            console.log('A new one, adding');
                                            categories.push(id);
                                    } else {
                                            console.log('Duplicated, try again');
                                            spawn++;
                                    }
                            });
                            spawn--;
                    }
            }

            console.log(categories);
    }

function fillCatsWithJQuery() {
                let spawn = 5;
                while (categories.length < 5) {
                        if (spawn) {
                                let offset = Math.floor(Math.random() * 1000);
                                console.log('Spawning one with offset ' + offset);
                                $.ajax({
                                        url: 'http://jservice.io/api/categories',
                                        data: {
                                                count: 1,
                                                offset: offset
                                        },
                                        success: function(value) {
                                                let id = value.data[0].id;
                                                console.log('Got one! Id = ' + id );
                                                if (categories.indexOf(id) == -1) {
                                                        console.log('A new one, adding');
                                                        categories.push(id);
                                                } else {
                                                        console.log('Duplicated, try again');
                                                        spawn++;
                                                }
                                        }});
                                spawn--;
                        }
                }

                console.log(categories);
        }
</code>```

When I run this script on my browser I never see the message "Got one!" and looking at the developer's console I don't see any XHR being performed either :(

The strange thing is, if I change the while condition to something fixed (Like a fixed number of iterations) it works...

Any idea?

答:
Thanks to @freedomn-m's comment I got to this solution:

```<code><script type="text/javascript">
    let categories = [];
    let spawn = 5;

    let catFiller = setInterval(function() {
            let offset;

            if ( categories.length < 5 ) {
                    for ( let i = 0; i < spawn; i++ ) {
                            offset = Math.floor(Math.random() * 1000);
                            console.log('Spawning one with offset ' + offset);
                            axios.get(
                                    'http://jservice.io/api/categories',
                                    {
                                            params: {
                                                    count: 1,
                                                    offset: offset
                                            }
                                    })
                                    .then(function(value) {
                                            let id = value.data[0].id;
                                            console.log('Got one! Id = ' + id );
                                            if (categories.indexOf(id) == -1) {
                                                    console.log('A new one, adding');
                                                    categories.push(id);
                                                    spawn--;
                                            } else {
                                                    console.log('Duplicated, try again');
                                            }
                                    });
                    }
            } else {
                    clearInterval(catFiller);
            }
    }, 1000 );
</code>```

Which is doing what I wanted (although in a much more complicated way than I envisioned :)

Thanks!

Body:
I'm working on an excercise to get different random results from an API using JavaScript.

Mi idea is to have an array of results I already got and issue as many asynchronous requests as I need to get the job done.

I tried using Axios and jQuery (I'm supposed to use the first one but it didn't work and since I'm more experienced with jQuery I decided to give it a try) but neither one works.

Here's my code:

let categories = [];

    function fillCatsWithAxios() {
            let spawn = 5;
            while (categories.length < 5) {
                    if (spawn) {
                            let offset = Math.floor(Math.random() * 1000);
                            console.log('Spawning one with offset ' + offset);
                            axios.get('http://jservice.io/api/categories', {
                            params: {
                                    count: 1,
                                    offset: offset
                            }
                            }).then(function(value) {
                                    let id = value.data[0].id;
                                    console.log('Got one! Id = ' + id );
                                    if (categories.indexOf(id) == -1) {
                                            console.log('A new one, adding');
                                            categories.push(id);
                                    } else {
                                            console.log('Duplicated, try again');
                                            spawn++;
                                    }
                            });
                            spawn--;
                    }
            }

            console.log(categories);
    }

function fillCatsWithJQuery() {
                let spawn = 5;
                while (categories.length < 5) {
                        if (spawn) {
                                let offset = Math.floor(Math.random() * 1000);
                                console.log('Spawning one with offset ' + offset);
                                $.ajax({
                                        url: 'http://jservice.io/api/categories',
                                        data: {
                                                count: 1,
                                                offset: offset
                                        },
                                        success: function(value) {
                                                let id = value.data[0].id;
                                                console.log('Got one! Id = ' + id );
                                                if (categories.indexOf(id) == -1) {
                                                        console.log('A new one, adding');
                                                        categories.push(id);
                                                } else {
                                                        console.log('Duplicated, try again');
                                                        spawn++;
                                                }
                                        }});
                                spawn--;
                        }
                }

                console.log(categories);
        }

When I run this script on my browser I never see the message "Got one!" and looking at the developer's console I don't see any XHR being performed either :(

The strange thing is, if I change the while condition to something fixed (Like a fixed number of iterations) it works...

Any idea?

Body:
Thanks to @freedomn-m's comment I got to this solution:

<script type="text/javascript">
    let categories = [];
    let spawn = 5;

    let catFiller = setInterval(function() {
            let offset;

            if ( categories.length < 5 ) {
                    for ( let i = 0; i < spawn; i++ ) {
                            offset = Math.floor(Math.random() * 1000);
                            console.log('Spawning one with offset ' + offset);
                            axios.get(
                                    'http://jservice.io/api/categories',
                                    {
                                            params: {
                                                    count: 1,
                                                    offset: offset
                                            }
                                    })
                                    .then(function(value) {
                                            let id = value.data[0].id;
                                            console.log('Got one! Id = ' + id );
                                            if (categories.indexOf(id) == -1) {
                                                    console.log('A new one, adding');
                                                    categories.push(id);
                                                    spawn--;
                                            } else {
                                                    console.log('Duplicated, try again');
                                            }
                                    });
                    }
            } else {
                    clearInterval(catFiller);
            }
    }, 1000 );

Which is doing what I wanted (although in a much more complicated way than I envisioned :)

Thanks!


问:
Conditional <router-link> in Vue.js dependant on prop value?
Hopefully this is a rather simple question / answer, but I can't find much info in the docs.

Is there a way to enable or disable the anchor generated by <router-link> dependent on whether a prop is passed in or not?

```<code><router-link class="Card__link" :to="{ name: 'Property', params: { id: id }}">
  <h1 class="Card__title">{{ title }}</h1>
  <p class="Card__description">{{ description }}</p>
</router-link>
</code>```

If there's no id passed to this component, I'd like to disable any link being generated.

Is there a way to do this without doubling up the content into a v-if?

Thanks!

答:
I sometimes do stuff like this:

```<code><component
    :is="hasSubLinks ? 'button' : 'router-link'"
    :to="hasSubLinks ? undefined : href"
    :some-prop="computedValue"
    @click="hasSubLinks ? handleClick() : navigate"
>
    <!-- arbitrary markup -->
</component>

...

computed: {
    computedValue() {
        if (this.hasSubLinks) return 'something';
        if (this.day === 'Friday') return 'tgif';
        return 'its-fine';
    },
},
</code>```

But I basically always wrap router-link, so you can gain control over disabled state, or pre-examine any state or props before rendering the link, with something like this:

```<code><template>
    <router-link
        v-slot="{ href, route, navigate, isActive, isExactActive }"
        :to="to"
    >
        <a
            :class="['nav-link-white', {
                'nav-link-white-active': isActive,
                'opacity-50': isDisabled,
            }]"
            :href="isDisabled ? undefined : href"
            @click="handler => handleClick(handler, navigate)"
        >
            <slot></slot>
        </a>

    </router-link>
</template>

<script>
export default {
    name: 'top-nav-link',

    props: {
        isDisabled: {
            type: Boolean,
            required: false,
            default: () => false,
        },

        to: {
            type: Object,
            required: true,
        },
    },

    data() {
        return {};
    },

    computed: {},

    methods: {
        handleClick(handler, navigate) {
            if (this.isDisabled) return undefined;
            return navigate(handler);
        },
    },

};
</script>
</code>```

In my app right now, I'm noticing that some combinations of @click="handler => handleClick(handler, navigate)" suffer significantly in performance.

For example this changes routes very slow:

```<code>@click="isDisabled ? undefined : handler => navigate(handler)"
</code>```

But the pattern in my full example code above works and has no performance issue.

In general, ternary operator in @click can be very dicey, so if you get issues, don't give up right away, try many different ways to bifurcate on predicates or switch over <component :is="" based on state. navigate itself is an ornery one because it requires the implicit first parameter to work.

I haven't tried, but you should be able to use something like Function.prototype.call(), Function.prototype.apply(), or Function.prototype.bind().

For example, you might be able to do:

```<code>@click="handler => setupNavigationTarget(handler, navigate)"

...

setupNavigationTarget(handler, cb) {
    if (this.isDisabled) return undefined;
    return this.$root.$emit('some-event', cb.bind(this, handler));
},

...

// another component
mounted() {
    this.$root.$on('some-event', (navigate) => {
        if (['Saturday', 'Sunday'].includes(currentDayOfTheWeek)) {
            // halt the navigation event
            return undefined;
        }

        // otherwise continue (and notice how downstream logic
        // no longer has to care about the bound handler object)
        return navigate();
    });
},
</code>```

Body:
Hopefully this is a rather simple question / answer, but I can't find much info in the docs.

Is there a way to enable or disable the anchor generated by <router-link> dependent on whether a prop is passed in or not?

<router-link class="Card__link" :to="{ name: 'Property', params: { id: id }}">

{{ title }}

{{ description }}

</router-link>

If there's no id passed to this component, I'd like to disable any link being generated.

Is there a way to do this without doubling up the content into a v-if?

Thanks!

Body:
I sometimes do stuff like this:

<component
    :is="hasSubLinks ? 'button' : 'router-link'"
    :to="hasSubLinks ? undefined : href"
    :some-prop="computedValue"
    @click="hasSubLinks ? handleClick() : navigate"
>
    <!-- arbitrary markup -->
</component>

...

computed: {
    computedValue() {
        if (this.hasSubLinks) return 'something';
        if (this.day === 'Friday') return 'tgif';
        return 'its-fine';
    },
},

But I basically always wrap router-link, so you can gain control over disabled state, or pre-examine any state or props before rendering the link, with something like this:

<template>
    <router-link
        v-slot="{ href, route, navigate, isActive, isExactActive }"
        :to="to"
    >
        <a
            :class="['nav-link-white', {
                'nav-link-white-active': isActive,
                'opacity-50': isDisabled,
            }]"
            :href="isDisabled ? undefined : href"
            @click="handler => handleClick(handler, navigate)"
        >
            <slot></slot>
        </a>

    </router-link>
</template>

<script>
export default {
    name: 'top-nav-link',

    props: {
        isDisabled: {
            type: Boolean,
            required: false,
            default: () => false,
        },

        to: {
            type: Object,
            required: true,
        },
    },

    data() {
        return {};
    },

    computed: {},

    methods: {
        handleClick(handler, navigate) {
            if (this.isDisabled) return undefined;
            return navigate(handler);
        },
    },

};
</script>

In my app right now, I'm noticing that some combinations of @click="handler => handleClick(handler, navigate)" suffer significantly in performance.

For example this changes routes very slow:

@click="isDisabled ? undefined : handler => navigate(handler)"

But the pattern in my full example code above works and has no performance issue.

In general, ternary operator in @click can be very dicey, so if you get issues, don't give up right away, try many different ways to bifurcate on predicates or switch over <component :is="" based on state. navigate itself is an ornery one because it requires the implicit first parameter to work.

I haven't tried, but you should be able to use something like Function.prototype.call(), Function.prototype.apply(), or Function.prototype.bind().

For example, you might be able to do:

@click="handler => setupNavigationTarget(handler, navigate)"

...

setupNavigationTarget(handler, cb) {
    if (this.isDisabled) return undefined;
    return this.$root.$emit('some-event', cb.bind(this, handler));
},

...

// another component
mounted() {
    this.$root.$on('some-event', (navigate) => {
        if (['Saturday', 'Sunday'].includes(currentDayOfTheWeek)) {
            // halt the navigation event
            return undefined;
        }

        // otherwise continue (and notice how downstream logic
        // no longer has to care about the bound handler object)
        return navigate();
    });
},


问:
Is there a Haskell equivalent way of iterable unpacking like in Python?
I wonder if it is possible to create variables from an iterable of things in Haskell. I found this when I search for it but I couldn't adapt it for my case. Maybe it's not possible or I'm missing something since I'm a beginner. Basically, I'm wondering if something like this is possible in Haskell:

>>> list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a, b, c = list_of_lists
>>> print(a)
[1, 2, 3]
```

答:
The answer given by luqui works when the list has exactly three elements. It is, however, partial, which means that it'll fail at run-time for lists of any other size.

A more idiomatic Haskell solution, I think, would be a function like this:

```<code>listToTriple :: [a] -> Maybe (a, a, a)
listToTriple [a, b, c] = Just (a, b, c)
listToTriple _ = Nothing
</code>```

You can safely call it with lists of any length:

```<code>*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Just ([1,2,3],[4,5,6],[7,8,9])
*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6]]
Nothing
*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
Nothing
</code>```

If, in the first case, you only want the first of those three lists, you can pattern-match on the triple:

```<code>*Q62157846> fmap (\(a, _, _) -> a) $ listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Just [1,2,3]
</code>```

Body:
The answer given by luqui works when the list has exactly three elements. It is, however, partial, which means that it'll fail at run-time for lists of any other size.

A more idiomatic Haskell solution, I think, would be a function like this:

listToTriple :: [a] -> Maybe (a, a, a)
listToTriple [a, b, c] = Just (a, b, c)
listToTriple _ = Nothing

You can safely call it with lists of any length:

*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Just ([1,2,3],[4,5,6],[7,8,9])
*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6]]
Nothing
*Q62157846> listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
Nothing

If, in the first case, you only want the first of those three lists, you can pattern-match on the triple:

*Q62157846> fmap (\(a, _, _) -> a) $ listToTriple [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Just [1,2,3]


问:
How to properly lock/unlock camera when drawing on SurfaceView?
I created an Activity with Augmented Reality functionality. Part of that is to have phone camera display in the background (which is SurfaceView in Activity layout).

in activity onCreate() method I do:

```<code>surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
</code>```

My callbacks are:

```<code>@Override
public void surfaceCreated(SurfaceHolder holder) {

    try {
        camera = Camera.open();
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(holder);
    } catch (Exception e) {
        // e.printStackTrace();
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    camera.startPreview();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    camera.stopPreview();
    camera.release();
}
</code>```

Right now when I close my application (while leaving it in the background) Camera app is not working because Camera is still locked inside my app.

How should I implement activity onResume() onPause() methods in order to lock/unlock camera?

Also leaving camera locked in the app takes up about 5% of CPU on Galaxy S and after I come back to my app - it crashes in surfaceChanged() when trying to camera.startPreview();

Help!

答:
Just add something like this to surfaceCreated callback:

```<code>    if (camera != null) {
        camera.release();
    }
    camera = Camera.open();
    camera.setDisplayOrientation(90);
    try {
        camera.setPreviewDisplay(holder);
    } catch (Exception e) {
    }
</code>```

And then inside onPause() add release and call to callback:

```<code>    camera.release();
    surfaceCreated(surfaceHolder);
</code>```

Now it works like a charm! Cheers!

Body:
I created an Activity with Augmented Reality functionality. Part of that is to have phone camera display in the background (which is SurfaceView in Activity layout).

in activity onCreate() method I do:

surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);

My callbacks are:

@Override
public void surfaceCreated(SurfaceHolder holder) {

    try {
        camera = Camera.open();
        camera.setDisplayOrientation(90);
        camera.setPreviewDisplay(holder);
    } catch (Exception e) {
        // e.printStackTrace();
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    camera.startPreview();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    camera.stopPreview();
    camera.release();
}

Right now when I close my application (while leaving it in the background) Camera app is not working because Camera is still locked inside my app.

How should I implement activity onResume() onPause() methods in order to lock/unlock camera?

Also leaving camera locked in the app takes up about 5% of CPU on Galaxy S and after I come back to my app - it crashes in surfaceChanged() when trying to camera.startPreview();

Help!

Body:
Just add something like this to surfaceCreated callback:

    if (camera != null) {
        camera.release();
    }
    camera = Camera.open();
    camera.setDisplayOrientation(90);
    try {
        camera.setPreviewDisplay(holder);
    } catch (Exception e) {
    }

And then inside onPause() add release and call to callback:

    camera.release();
    surfaceCreated(surfaceHolder);

Now it works like a charm! Cheers!


问:
iterate an actively used database table in cron jobs without missing any row
How would you correctly iterate all the rows of a database query when doing multiple passes of a long operation without missing any row? In my case i have alphanumeric IDs, so id column is not reliable...

The main problem is that the query results may change between each cron task execution.

A first idea could be to store the offset / "number of rows processed". But if one of the already processed rows is deleted the others would shift and the first one would be skipped.

If I store the id of the last processed row and skip to the one after it I have a worse problem: if that exact row is deleted the next cron job will skip every remaining row.

Is there any more "standard" way of iterating a table like this ?

I'm doing this in php with a third party orm engine using sql as data store, but i think it's more a general question so anyone feel free to retag  this more appropriately.

答:
Most DBMS have a reliable standard sorting. So the easiest solution would be not to use any sorting and use LIMIT and OFFSET definitions. E.g in the case of MySQL you could do something like this:

```<code>SELECT *
FROM mytable
LIMIT 10,10
;
</code>```

This should be reliable.

If you would like to take deleted rows into consideration, I would use some sort of queue. E.g.:

```<code>CREATE TABLE item(
    id INT PRIMARY KEY
);

CREATE TABLE job (
    id INT PRIMARY KEY
);

CREATE TABLE job_queue(
    id INT PRIMARY KEY,
    job_id INT,
    item INT,
    FOREIGN KEY job_id REFERENCES job(id),
    FOREIGN KEY item REFERENCES item(id)
);
</code>```

Then you could add all items to the queue by running:

```<code>INSERT INTO job_queue (job_id, item_id)
SELECT 1, id
FROM item;
</code>```

Now you could fetch the items reliably by running the query:

```<code>SELECT *
FROM job_queue
WHERE job_id = 1
LIMIT 10;

DELETE FROM job_queue WHERE id IN (
    SELECT id
    FROM job_queue
    WHERE job_id = 1
)
</code>```

But there are many possible valid solutions. A final answer heavily depends on your requirements.

Body:
Most DBMS have a reliable standard sorting. So the easiest solution would be not to use any sorting and use LIMIT and OFFSET definitions. E.g in the case of MySQL you could do something like this:

SELECT *
FROM mytable
LIMIT 10,10
;

This should be reliable.

If you would like to take deleted rows into consideration, I would use some sort of queue. E.g.:

CREATE TABLE item(
    id INT PRIMARY KEY
);

CREATE TABLE job (
    id INT PRIMARY KEY
);

CREATE TABLE job_queue(
    id INT PRIMARY KEY,
    job_id INT,
    item INT,
    FOREIGN KEY job_id REFERENCES job(id),
    FOREIGN KEY item REFERENCES item(id)
);

Then you could add all items to the queue by running:

INSERT INTO job_queue (job_id, item_id)
SELECT 1, id
FROM item;

Now you could fetch the items reliably by running the query:

SELECT *
FROM job_queue
WHERE job_id = 1
LIMIT 10;

DELETE FROM job_queue WHERE id IN (
    SELECT id
    FROM job_queue
    WHERE job_id = 1
)

But there are many possible valid solutions. A final answer heavily depends on your requirements.


问:
How do have both count and percent on barcharts in ggplot2? R
this is my data

```<code>data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))
</code>```

This is my plot

```<code>ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

</code>```

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

答:
Is this what you're looking for?

```<code>ggplot(data, aes(x=Name, y=Percent)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=paste0("N = ",data$Freq), vjust=-1) +
  ylab("")
</code>```

Body:
this is my data

data <- data.frame("Name" = c("Mark", "Jenny", "Linn"),
                   "Freq" = c("5","7", "3"),
                   "Percent" = c("33%", "47%", "20%"))

This is my plot

ggplot(data, aes(x=Name, y=Freq)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=data$Freq, vjust=-1)

How can I have both my percent label next to my freq label preferably in parenthesis or separated by a comma?

Body:
Is this what you're looking for?

ggplot(data, aes(x=Name, y=Percent)) +
  geom_bar(stat="identity", color = "black", fill="dodgerblue1")+
  geom_text(label=paste0("N = ",data$Freq), vjust=-1) +
  ylab("")


问:
Time delayed modal does not pop up
I am using this code to to have time delayed pop up modal. The end goal is to show  subscription box in the time delayed modal. I have the javascript in . The pop up modal is not working for me.

var count=-1; // initially -1 as we are having a delay of 1000ms

var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
{

  count=count+1;
  if (count >=6) //+1 than the req time as we have a delay of 1000ms
  {
     clearInterval(counter);
     /////////////what code should go here for the modal to pop up??///////////////////////
      $("#myModal1").modal();

     return;
  }
    document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!-- Modal --><span id="timer"></span></h5>

<!-- CODE FOR THE MODAL TO POP UP -->
  <div class="modal fade" id="myModal1" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div></code>```

答:
The only reason that this snippet is not working is lack of CSS / JS libraries (jquery + bootstrap). With them modal shows up like intended.

Docs: https://getbootstrap.com/docs/4.3/getting-started/introduction/

In bootstrap modal docs there is always string parameter in modal('') function so to open it it should be modal('show'), but actually code works without it (opens by default). But NOTICE that it could be required for older versions, so maybe this is why you have problems.

Docs: https://getbootstrap.com/docs/4.3/components/modal/

var count=-1; // initially -1 as we are having a delay of 1000ms

var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
{

  count=count+1;
  if (count >=6) //+1 than the req time as we have a delay of 1000ms
  {
     clearInterval(counter);
     /////////////what code should go here for the modal to pop up??///////////////////////
      $("#myModal1").modal();

     return;
  }
    document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<!-- Modal --><span id="timer"></span></h5>

<!-- CODE FOR THE MODAL TO POP UP -->
  <div class="modal fade" id="myModal1" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">×</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div></code>```

Edit:

Since you do not actually using bootstrap or any other library, and wanna use plain CSS/JS then all you need to do is: make fixed div with content you need, center it in v/h (flex can be useful) and hide it (display: none). Now with single line of JS code you can display it.

Just style it whatever you want and add functions like close button if needed.

setTimeout(test, 2000);

function test()
{
    document.getElementById('modal1').classList.add('show');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.modal {
  background: rgba(0, 0, 0, .5);
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  display: none;
}

.modal.show {
  display: flex;
}

.modal .modal-content {
  padding: 15px;
  background: #fff;
  max-width: 500px;
  box-shadow: 0 0 40px #000;
}</code>```

    Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. ```

Title: Time delayed modal does not pop up

Body:
I am using this code to to have time delayed pop up modal. The end goal is to show  subscription box in the time delayed modal. I have the javascript in . The pop up modal is not working for me.

var count=-1; // initially -1 as we are having a delay of 1000ms

var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
{

  count=count+1;
  if (count >=6) //+1 than the req time as we have a delay of 1000ms
  {
     clearInterval(counter);
     /////////////what code should go here for the modal to pop up??///////////////////////
      $("#myModal1").modal();

     return;
  }
    document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}

          <button type="button" class="close" data-dismiss="modal">×</button>

Modal Header

Some text in the modal.

          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Body:
The only reason that this snippet is not working is lack of CSS / JS libraries (jquery + bootstrap). With them modal shows up like intended.

Docs: https://getbootstrap.com/docs/4.3/getting-started/introduction/

In bootstrap modal docs there is always string parameter in modal('') function so to open it it should be modal('show'), but actually code works without it (opens by default). But NOTICE that it could be required for older versions, so maybe this is why you have problems.

Docs: https://getbootstrap.com/docs/4.3/components/modal/

var count=-1; // initially -1 as we are having a delay of 1000ms

var counter=setInterval(timer, 1000); //1000 will  run it every 1 second

function timer()
{

  count=count+1;
  if (count >=6) //+1 than the req time as we have a delay of 1000ms
  {
     clearInterval(counter);
     /////////////what code should go here for the modal to pop up??///////////////////////
      $("#myModal1").modal();

     return;
  }
    document.getElementById("timer").innerHTML=count + " secs"; // watch for spelling
}

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<!-- Modal --><span id="timer"></span></h5>

<!-- CODE FOR THE MODAL TO POP UP -->
  <div class="modal fade" id="myModal1" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

Edit:

Since you do not actually using bootstrap or any other library, and wanna use plain CSS/JS then all you need to do is: make fixed div with content you need, center it in v/h (flex can be useful) and hide it (display: none). Now with single line of JS code you can display it.

Just style it whatever you want and add functions like close button if needed.

setTimeout(test, 2000);

function test()
{
    document.getElementById('modal1').classList.add('show');
}

.modal {
  background: rgba(0, 0, 0, .5);
  position: fixed;
  z-index: 999;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  align-items: center;
  justify-content: center;
  display: none;
}

.modal.show {
  display: flex;
}

.modal .modal-content {
  padding: 15px;
  background: #fff;
  max-width: 500px;
  box-shadow: 0 0 40px #000;
}

<div id="modal1" class="modal">
  <div class="modal-content">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt.
  </div>
</div>

Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt. Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam nobis praesentium, reprehenderit repellendus libero commodi voluptates numquam autem velit quos aspernatur delectus similique voluptate blanditiis, nemo maxime cumque ab deserunt.


问:
How to use NextJS's 'useRouter()' hook inside Storybook
I've been attempting to use the useRouter hooks from Next.js inside Storybook. However, every time I load up Storybook, I get 'cannot read property 'pathname' of null'. How might I resolve this issue?

```<code>import { useRouter } from "next/router";

const NavStrip = () => {
  const router = useRouter();

  return (
    ...
            <Link href="/dashboard" passHref>
              <StyledLink active={router.pathname === "/dashboard"}>
                ...
              </StyledLink>
            </Link>
    ...
         )
}
</code>```

NavStrip.stories.tsx

```<code>import React from "react";
import NavStrip from "./index";

export default {
  component: NavStrip,
  title: "NavStrip",
};

export const Default = () => <NavStrip />;
</code>```

答:
Storybook components run outside of the Next environment and outside of the page component which enables the use of next/router. Therefore you will not be able to use this outside of your Next page and its children.

Next's router functionalities are created in a Context API provider, therefore in order to use useRouter your component must be a child of that provider (which in the case of storybook it will never be).

Body:
I've been attempting to use the useRouter hooks from Next.js inside Storybook. However, every time I load up Storybook, I get 'cannot read property 'pathname' of null'. How might I resolve this issue?

import { useRouter } from "next/router";

const NavStrip = () => {
  const router = useRouter();

  return (
    ...
            <Link href="/dashboard" passHref>

            </Link>
    ...
         )
}

NavStrip.stories.tsx

import React from "react";
import NavStrip from "./index";

export default {
  component: NavStrip,
  title: "NavStrip",
};

export const Default = () => <NavStrip />;


问:
Sending asynchronous request on clicking a sharepoint web part button control
I am new to this whole sharepoint and aspx programming. I have developed a sharepoint web part that has a button control. The onclick event is mapped to a method in my web part code. When I click the button the whole page reloads and the web part is rendered again. Is there a way to prevent this reloading of the page? Is there a way to call the function method in the background? Something similar to AJAX.

Thanks,
Jagannath

答:
Once you know the tricks needed to get SharePoint and ASP.NET AJAX to work together it's not that difficult.

Here are the steps required:

Ensure the ASP.NET AJAX Extensions are installed on all the front-end web servers (this is not required if you are using .NET 3.5 as the Extensions are included in the Framework)

Update the Web.config file for the SharePoint Application to support ASP.NET AJAX

Ensure any page that is going to use AJAX has a ScriptManager

Use an UpdatePanel or a client-side service call to get updated data and re-render the Web Part

This blog post has some resources from a talk I did on the subject at TechEd Barcelona 2008. These resources should give you the information you need to get started.

http://msmvps.com/blogs/windsor/archive/2008/11/13/teched-emea-resources-and-demos-integrating-asp-net-ajax-with-sharepoint-2007.aspx

OwnerDisplayName: Jagannath

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Rob Windsor - MVP

LastEditorDisplayName: Rob Windsor - MVP


问:
Converting Ruby 1.9.2 code to JavaScript?
Is it possible to convert Ruby code to Javascript at all?
I have heard of RubyJS but this appears to not work with Ruby 1.9.2 - is this the case?</p>

答:
There are many efforts that have tried to do this, but most have only been to an academic degree. For instance, this Ruby 1.9.2 VM in JavaScript.

Most efforts to port to JavaScript focus on the Google V8 engine and not necessarily the browser-side equivalent.


问:
How would I fill NA values in Pandas based on a lookup?
I have some NA values, but I want to replace them by specific look ups. Let me show you an example.

```>>> runners_df = pd.DataFrame(runners)
>>> runners_df
   year  name  miles
0  2010  Paul    6.0
1  2010  Paul    4.0
2  2010  Paul    NaN
3  2011  Paul    8.0
4  2011  Paul    8.0
5  2012  Paul    9.0
6  2012  Paul   12.0
>>> average_miles_per_year = runners_df.groupby(['year','name'])['miles'].mean().reset_index()
>>> average_miles_per_year
   year  name  miles
0  2010  Paul    5.0
1  2011  Paul    8.0
2  2012  Paul   10.5
>>>

```

In this case, I would like Pauls NaN value to be filled with 5.0 because in 2010 his average miles was 5.

Thanks so much.

答:
Try using fillna with groupby and transform:

```<code>runners['miles'] = runners['miles'].fillna(runners.groupby(['year','name'])['miles']
                                                  .transform('mean'))
</code>```

Output:

```<code>   year  name  miles
0  2010  Paul    6.0
1  2010  Paul    4.0
2  2010  Paul    5.0
3  2011  Paul    8.0
4  2011  Paul    8.0
5  2012  Paul    9.0
6  2012  Paul   12.0
</code>```

Body:
I have some NA values, but I want to replace them by specific look ups. Let me show you an example.

>>> runners_df = pd.DataFrame(runners)
>>> runners_df
   year  name  miles
0  2010  Paul    6.0
1  2010  Paul    4.0
2  2010  Paul    NaN
3  2011  Paul    8.0
4  2011  Paul    8.0
5  2012  Paul    9.0
6  2012  Paul   12.0
>>> average_miles_per_year = runners_df.groupby(['year','name'])['miles'].mean().reset_index()
>>> average_miles_per_year
   year  name  miles
0  2010  Paul    5.0
1  2011  Paul    8.0
2  2012  Paul   10.5
>>>

In this case, I would like Pauls NaN value to be filled with 5.0 because in 2010 his average miles was 5.

Thanks so much.

Body:
Try using fillna with groupby and transform:

runners['miles'] = runners['miles'].fillna(runners.groupby(['year','name'])['miles']
                                                  .transform('mean'))

Output:

   year  name  miles
0  2010  Paul    6.0
1  2010  Paul    4.0
2  2010  Paul    5.0
3  2011  Paul    8.0
4  2011  Paul    8.0
5  2012  Paul    9.0
6  2012  Paul   12.0


问:
Powershell error when passing a Hashtable via Invoke-Expression
I have the following Powershell script snippet that is calling another Powershell script using the Invoke-Expression cmdlet:

```<code>$headers=@{}
$headers.Add("Authorization", "Basic $encodedCredentials")

$ScriptPath = Split-Path $MyInvocation.InvocationName
$args = @()
$args += ("-arg1", $arg1)
$args += ("-arg2", $arg2)
$args += ("-headers", $headers)
$cmd = "$ScriptPath\subScript.ps1"

Invoke-Expression "$cmd $args"
</code>```

The list of parameters in subScript.ps1 is as follows:

```<code>param
(
    [Parameter(Mandatory=$true)]
    [String]$arg1 = $(throw "arg1 is mandatory, please provide a value."),

    [Parameter(Mandatory=$true)]
    [String]$arg2 = $(throw "arg2 is mandatory, please provide a value."),

    [Parameter(Mandatory=$true)]
    $headers = $(throw "headers is mandatory, please provide a value.")
)
</code>```

I have verified that the second script executes when I remove the "$headers" parameter in both scripts. Once I add it again I get the following error message:

Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert
  the "System.Collections.Hashtable" value of type "System.String" to
  type "System.Collections.IDictionary".

I tried adding both "System.Collections.Hashtable" and "hashtable" as the type of the parameter in subScript.ps1 but that only changes the error message to:

Cannot process argument transformation on parameter 'headers'. Cannot
  convert the "System.Collections.Hashtable" value of type
  "System.String" to type "System.Collections.Hashtable".

How can this be accomplished?

答:
Don't use Invoke-Expression (it's unsafe and only works on string input) and don't (re-)use $args (it's an automatic variable)!

Use the hashtable for splatting your arguments instead:

$headers=@{}
$headers.Add("Authorization", "Basic $encodedCredentials")

$ScriptPath = Split-Path $MyInvocation.InvocationName
$params = @{
    "arg1" = $arg1
    "arg2" = $arg2
    "headers" = $headers
}
$cmd = "$ScriptPath\subScript.ps1"

# use the `&` call operator to invoke the next script
& $cmd @params
```

For more information see the about_Splatting helpfile

Body:
I have the following Powershell script snippet that is calling another Powershell script using the Invoke-Expression cmdlet:

$headers=@{}
$headers.Add("Authorization", "Basic $encodedCredentials")

$ScriptPath = Split-Path $MyInvocation.InvocationName
$args = @()
$args += ("-arg1", $arg1)
$args += ("-arg2", $arg2)
$args += ("-headers", $headers)
$cmd = "$ScriptPath\subScript.ps1"

Invoke-Expression "$cmd $args"

The list of parameters in subScript.ps1 is as follows:

param
(
    [Parameter(Mandatory=$true)]
    [String]$arg1 = $(throw "arg1 is mandatory, please provide a value."),

    [Parameter(Mandatory=$true)]
    [String]$arg2 = $(throw "arg2 is mandatory, please provide a value."),

    [Parameter(Mandatory=$true)]
    $headers = $(throw "headers is mandatory, please provide a value.")
)

I have verified that the second script executes when I remove the "$headers" parameter in both scripts. Once I add it again I get the following error message:

Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert
  the "System.Collections.Hashtable" value of type "System.String" to
  type "System.Collections.IDictionary".

I tried adding both "System.Collections.Hashtable" and "hashtable" as the type of the parameter in subScript.ps1 but that only changes the error message to:

Cannot process argument transformation on parameter 'headers'. Cannot
  convert the "System.Collections.Hashtable" value of type
  "System.String" to type "System.Collections.Hashtable".

How can this be accomplished?

Body:
Don't use Invoke-Expression (it's unsafe and only works on string input) and don't (re-)use $args (it's an automatic variable)!

Use the hashtable for splatting your arguments instead:

$headers=@{}
$headers.Add("Authorization", "Basic $encodedCredentials")

$ScriptPath = Split-Path $MyInvocation.InvocationName
$params = @{
    "arg1" = $arg1
    "arg2" = $arg2
    "headers" = $headers
}
$cmd = "$ScriptPath\subScript.ps1"

# use the `&` call operator to invoke the next script
& $cmd @params

For more information see the about_Splatting helpfile