问:
generate color from number
There is a way for get color from a number? it's mathematically possible?

I have an array of positive number like this:

array(1, 2, 1000, 564, 30, 113) and I need a color (humanly distinguishable) for each of these. I can use PHP or JS for this purpose.

I need this because i'm using http://www.chartjs.org/ with dynamic values.

edit:
this is an example from chartjs documentation:

```<code><canvas id="myChart" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero:true
                }
            }]
        }
    }
});
</script>
</code>```

In this example are defined 6 bars (red, blue, yellow, green, purple and orange)
In my case this bars are dynamically generated and I don't know how many bars I have to show.
How I can associate a color for each bar? (this color must be the same everytime page refresh)

答:
Using a method from https://stackoverflow.com/a/2262117/2737978 you can convert an integer into an rgb value.

$("#slider1").on("input", function() {
  var value = $(this).val();
  var rgbColor = intToRGB(value);

  $(".number").html(value);
  $(".example").css('background-color', rgbColor);

});

var intToRGB = function(value) {
  //credit to https://stackoverflow.com/a/2262117/2737978 for the idea of how to implement
  var blue = Math.floor(value % 256);
  var green = Math.floor(value / 256 % 256);
  var red = Math.floor(value / 256 / 256 % 256);

  return "rgb(" + red + "," + green + "," + blue + ")";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#slider1 {
  width: 100%
}

.example {
  width: 50px;
  height: 50px;
  margin 0 auto;
  background-color: #000000;
  transition: background-color 100ms ease-in;
}</code>```

<input id="slider1" type="range" min="0" max="16777215" step="1" value="0" />

0

```
</div>
</div>
</p>

<p>You would just need to use the <code>intToRGB</code> function in your code. Perhaps though if your numbers are all between 1-1000 you might not see such a gradient so would need to adjust the values (either the 256 or adjust the value going in by a certain factor)</p>

<p>---UPDATE</p>

<p>and here is a live example using your graph and a large factor to give a nice range of colour. You would probably want to add some validation into this to ensure the data does not go above the max but here is a quick go.</p>

<p>Here the int to RGB function has been updated to take in a max value that you would like to represent the top colour. On this a scale can more easily be created to give more diversity between ints, depending on your max the colours will be different as they land on a different part of the overall scale of what can be represented.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var intToRGB = function(value, alpha, max) {
  var valueAsPercentageOfMax = value / max;
  // actual max is 16777215 but represnts white so we will take a max that is
  // below this to avoid white
  var MAX_RGB_INT = 16600000;
  var valueFromMaxRgbInt = Math.floor(MAX_RGB_INT * valueAsPercentageOfMax);

  //credit to https://stackoverflow.com/a/2262117/2737978 for the idea of how to implement
  var blue = Math.floor(valueFromMaxRgbInt % 256);
  var green = Math.floor(valueFromMaxRgbInt / 256 % 256);
  var red = Math.floor(valueFromMaxRgbInt / 256 / 256 % 256);

  return "rgba(" + red + "," + green + "," + blue + "," + alpha + ")";
}

var data = [12, 19, 3, 5, 2, 3];

var MAX = 19;

var backgroundColors = data.map(function(item) {
  return intToRGB(item, 0.8, MAX);
});

var borderColors = data.map(function(item) {
  return intToRGB(item, 1, MAX);
});
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: data,
      backgroundColor: backgroundColors,
      borderColor: borderColors,
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});</code>```

<canvas id="myChart" width="400" height="400">
</canvas>```

Title: generate color from number

Body:
There is a way for get color from a number? it's mathematically possible?

I have an array of positive number like this:

array(1, 2, 1000, 564, 30, 113) and I need a color (humanly distinguishable) for each of these. I can use PHP or JS for this purpose.

I need this because i'm using http://www.chartjs.org/ with dynamic values.

edit:
this is an example from chartjs documentation:

<canvas id="myChart" width="400" height="400"></canvas>

In this example are defined 6 bars (red, blue, yellow, green, purple and orange)
In my case this bars are dynamically generated and I don't know how many bars I have to show.
How I can associate a color for each bar? (this color must be the same everytime page refresh)

Body:
Using a method from https://stackoverflow.com/a/2262117/2737978 you can convert an integer into an rgb value.

$("#slider1").on("input", function() {
  var value = $(this).val();
  var rgbColor = intToRGB(value);

  $(".number").html(value);
  $(".example").css('background-color', rgbColor);

});

var intToRGB = function(value) {
  //credit to https://stackoverflow.com/a/2262117/2737978 for the idea of how to implement
  var blue = Math.floor(value % 256);
  var green = Math.floor(value / 256 % 256);
  var red = Math.floor(value / 256 / 256 % 256);

  return "rgb(" + red + "," + green + "," + blue + ")";
}

#slider1 {
  width: 100%
}

.example {
  width: 50px;
  height: 50px;
  margin 0 auto;
  background-color: #000000;
  transition: background-color 100ms ease-in;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="slider1" type="range" min="0" max="16777215" step="1" value="0" />
<div class="number">0</div>
<div class="example"></div>

You would just need to use the intToRGB function in your code. Perhaps though if your numbers are all between 1-1000 you might not see such a gradient so would need to adjust the values (either the 256 or adjust the value going in by a certain factor)

---UPDATE

and here is a live example using your graph and a large factor to give a nice range of colour. You would probably want to add some validation into this to ensure the data does not go above the max but here is a quick go.

Here the int to RGB function has been updated to take in a max value that you would like to represent the top colour. On this a scale can more easily be created to give more diversity between ints, depending on your max the colours will be different as they land on a different part of the overall scale of what can be represented.

var intToRGB = function(value, alpha, max) {
  var valueAsPercentageOfMax = value / max;
  // actual max is 16777215 but represnts white so we will take a max that is
  // below this to avoid white
  var MAX_RGB_INT = 16600000;
  var valueFromMaxRgbInt = Math.floor(MAX_RGB_INT * valueAsPercentageOfMax);

  //credit to https://stackoverflow.com/a/2262117/2737978 for the idea of how to implement
  var blue = Math.floor(valueFromMaxRgbInt % 256);
  var green = Math.floor(valueFromMaxRgbInt / 256 % 256);
  var red = Math.floor(valueFromMaxRgbInt / 256 / 256 % 256);

  return "rgba(" + red + "," + green + "," + blue + "," + alpha + ")";
}

var data = [12, 19, 3, 5, 2, 3];

var MAX = 19;

var backgroundColors = data.map(function(item) {
  return intToRGB(item, 0.8, MAX);
});

var borderColors = data.map(function(item) {
  return intToRGB(item, 1, MAX);
});
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: data,
      backgroundColor: backgroundColors,
      borderColor: borderColors,
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.js"></script>
<canvas id="myChart" width="400" height="400">
</canvas>


来源: stackexchange

问:
Where should I store a Computer wide license/Computer wide settings?
I've been looking for all most a day now. Is there any place to store a Computer-wide license. I don't want to use the Registry, so don't suggest that.

This license will be installed during the program's runtime, so what I need is a place to store computer wide settings that can have read/write access without running as Admin.

I've looked online, and Microsoft, in their infinite 'wisdom' for security apparently locked down all methods of saving application wide settings.

答:
In Windows 7 I use the hidden ProgramData folder.  I have just checked and it is available to users, they just can't see it by default.

I normally use it for storing .ini files in for applications.

Hope that helps

ContentLicense: CC BY-SA 2.5


问:
Communication between content script and background script in Microsoft Edge
I have a problem with communication based on browser.runtime.connect between a content script and a background script of my test echo extension. I have published my code and extension package on github.

Short description of this extension. You can run the extension on this GitHub test page. The content script connects to the background script using browser.runtime.connect and sends a message via browser.runtime.Port object when “Submit” button is clicked. The background script receives the message, converts it to upper case and sends back. Then content script receives the modified message and displays it on the page (received message field).

This extension works fine when I add it to Edge using Load extension button as described in the Microsoft Edge documentation. So if you open the test page with the loaded extension you should see “HELLO FROM BACKGROUND SCRIPT” text in the received message field.

But there is a strange problem if this extension is installed from a package… The extension doesn’t work until I open the background page of this extension and reload the test page…
So you can try to reproduce it:

Install this extension from the package

Open the test page. The background script doesn’t work properly (received message field is empty) and this script doesn’t receive sent messages… Page reloading or turning off\on of the extension doesn’t help.

Open background page of this extension. Then this page may be closed.

Reload the test page

Extension starts to work properly…

Note: this test extension is based on the runtime.connect example published on MDN (sorry, but I can not insert more than two links...).

Could you help me to solve this problem? Maybe I missed something in the documentation...

答: This is by design since your extension manifest specified persistent flag as false. On Microsoft Edge, the default behavior for background script is non-persistent.</p>

ContentLicense: CC BY-SA 3.0


问:
Merging columns with overlapping data in R data frames
```<code>a<-data.frame(cbind("Sample"=c("100","101","102","103"),"Status"=c("Y","","","partial")))
b<-data.frame(cbind("Sample"=c("100","101","102","103","106"),"Status"=c("NA","Y","","","Y")))

desired<-data.frame(cbind("Sample"=c("100","101","102","103","106"),"Status"=c("Y","Y","","partial","Y")))
</code>```

I have sample processing data in multiple sources and I'd like to combine them into a master list. How can I merge the "Status" column between 2 data frames such that a overrules b in order to collate "Y" and "partial" for each sample? Thank you in advance.

答:
I assume you want to keep the values from a and b with an order of priority, Y covers partial that covers NA that covers nothing.</p>

```<code>d <- merge(a,b,by="Sample",all=TRUE)
d$Status <- ""
d$Status[apply(c,1,function(x){any(is.na(x))})] <- "" # cleaning the NAs I introduced with the merge
d$Status[apply(c,1,`%in%`, x = "NA")] <- NA # or "NA" if you want to keep it this way, or "" if you want to get rid of them
d$Status[apply(c,1,`%in%`, x = "partial")] <- "partial"
d$Status[apply(c,1,`%in%`, x = "Y")] <- "Y"
d <- d[,c(1,4)]

# Sample  Status
# 1    100       Y
# 2    101       Y
# 3    102
# 4    103 partial
# 5    106       Y
</code>```

Body:
a<-data.frame(cbind("Sample"=c("100","101","102","103"),"Status"=c("Y","","","partial")))
b<-data.frame(cbind("Sample"=c("100","101","102","103","106"),"Status"=c("NA","Y","","","Y")))

desired<-data.frame(cbind("Sample"=c("100","101","102","103","106"),"Status"=c("Y","Y","","partial","Y")))

I have sample processing data in multiple sources and I'd like to combine them into a master list. How can I merge the "Status" column between 2 data frames such that a overrules b in order to collate "Y" and "partial" for each sample? Thank you in advance.

Body:
I assume you want to keep the values from a and b with an order of priority, Y covers partial that covers NA that covers nothing.

d <- merge(a,b,by="Sample",all=TRUE)
d$Status <- ""
d$Status[apply(c,1,function(x){any(is.na(x))})] <- "" # cleaning the NAs I introduced with the merge
d$Status[apply(c,1,`%in%`, x = "NA")] <- NA # or "NA" if you want to keep it this way, or "" if you want to get rid of them
d$Status[apply(c,1,`%in%`, x = "partial")] <- "partial"
d$Status[apply(c,1,`%in%`, x = "Y")] <- "Y"
d <- d[,c(1,4)]

# Sample  Status
# 1    100       Y
# 2    101       Y
# 3    102
# 4    103 partial
# 5    106       Y


问:
Forum SQL syntax Error
Hello I am trying to build a forum, but when I click over the topic of my forum I can view the page. I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''7'' at line 1

Here is my code from the view_topic.php page that I am trying to build:

```<code>    <?php
    session_start();

    ?>
    <!DOCTYPE html>
    <html>
    <head>
         <title>View Category</title>
         <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
    <div id="wrapper">
           <h2>Timkipptutorials</h2>

        <?php
         if(!isset($_SESSION ['uid'])){
             echo "<form action='login_parse.php' method='post'>
              Username: <input type='text' name='username'>
              Password <input type='text' name='password'>
              <input type='submit' name='submit' value='Log In'>" ;
        }
         else{
           echo "<p>You are logged in as ".$_SESSION['username']." • <a            href='logout_parse.php'> Logout</a>";
        }
           ?>

    <hr>
    <div id="content">
            <?php
                include_once("connect.php");

                $cid = $_GET['cid'];
                $tid = $_GET['tid'];
                $sql = "SELECT * FROM topics WHERE category_id='".$cid."' AND           id='".$tid."' LIMIT 1";
                    $res = mysql_query($sql) or die(mysql_error());
                if(mysql_num_rows($res) == 1){
                    echo "<table width='100%'>";
                    if(isset($_SESSION['uid'])){
                            echo "<tr><td colspan='2'><input type='submit'          value='Add Reply' onClick=\"window.location = 'post_reply.php?          cid=".$cid."$tid=".$tid."'\"/><hr>";
                    }else{
                        echo "<tr><td colspan='2'><p>Please log in to add a reply</p><hr></td></tr>";
                    }
                    while ($row = mysql_fetch_assoc($res)) {
                        $sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id '".$tid."'";
                        $res2 = mysql_query($sql2) or die(mysql_error());
                        while($row2 = mysql_fetch_assoc($res2)){
                            echo "<tr><td valign='top' style='border: 1px           solid #000000;'><div style='min-height: 125px;'>".$row['topic_title']."<br> by          ".$row2['post_creator']. " - ".$row2['post_date']."<hr>".$row2['post_content']."        </div></td><td width='200' valign='top' align='center' style='border: 1px solid         #000000;'>User Info Here</td></tr><tr><td colspan='2'><hr></td></tr>";
                        }
                        $old_views = $row['topic_views'];
                        $new_views = $old_views + 1;
                        $sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE category_id='".$cid."' AND id='".$tid."' LIMIT 1";
                        $res3 = mysql_query($sql3) or die(mysql_error());
                    }

                    echo "</table>";

                }else{
                    echo "<p>This topic does not exist.</p>";
                }
            ?>

        </div>
    </div>
    </body>
    </html>
</code>```

Please help me with that. Thanks

答:
$sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id '".$tid."'";

is missing the = sign on the second compare... as in

$sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id =  '".$tid."'";

Title: Forum SQL syntax Error

Body:
Hello I am trying to build a forum, but when I click over the topic of my forum I can view the page. I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''7'' at line 1

Here is my code from the view_topic.php page that I am trying to build:

    <?php
    session_start();

    ?>
    <!DOCTYPE html>

         <title>View Category</title>
         <link rel="stylesheet" type="text/css" href="style.css">

Timkipptutorials

        <?php
         if(!isset($_SESSION ['uid'])){
             echo "<form action='login_parse.php' method='post'>
              Username: <input type='text' name='username'>
              Password <input type='text' name='password'>
              <input type='submit' name='submit' value='Log In'>" ;
        }
         else{
           echo "
You are logged in as ".$_SESSION['username']." •  Logout";
        }
           ?>

            <?php
                include_once("connect.php");

                $cid = $_GET['cid'];
                $tid = $_GET['tid'];
                $sql = "SELECT * FROM topics WHERE category_id='".$cid."' AND           id='".$tid."' LIMIT 1";
                    $res = mysql_query($sql) or die(mysql_error());
                if(mysql_num_rows($res) == 1){
                    echo "
";
                    if(isset($_SESSION['uid'])){
                            echo "
<input type='submit'          value='Add Reply' onClick=\"window.location = 'post_reply.php?          cid=".$cid."$tid=".$tid."'\"/>
";
                    }else{
                        echo "

Please log in to add a reply

";
                    }
                    while ($row = mysql_fetch_assoc($res)) {
                        $sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id '".$tid."'";
                        $res2 = mysql_query($sql2) or die(mysql_error());
                        while($row2 = mysql_fetch_assoc($res2)){
                            echo "

".$row['topic_title']."
 by          ".$row2['post_creator']. " - ".$row2['post_date']."
".$row2['post_content']."
	User Info Here

";
                        }
                        $old_views = $row['topic_views'];
                        $new_views = $old_views + 1;
                        $sql3 = "UPDATE topics SET topic_views='".$new_views."' WHERE category_id='".$cid."' AND id='".$tid."' LIMIT 1";
                        $res3 = mysql_query($sql3) or die(mysql_error());
                    }

                    echo "
";

                }else{
                    echo "
This topic does not exist.
";
                }
            ?>

Please help me with that. Thanks


问:
When Service Account creates Google Sheets,The permission is needed. How can I give a permission?
I am using Google Sheet API (V4).

I had my google account like "test@google.com". To use google api, I made a project in Google Console and created service account.

I want to create a Google Sheet that can be accessed by only authorized person and myself who create the sheet. The authorized person can read and edit. Either do i.

But whenever I tired my code, it went well and I can get the sheet url. but when I click the url they show I need a permission.
 It is the url that I created [https://docs.google.com/spreadsheets/d/1RKR-ErUaC_LujUUDf8o_yIprEz223U1EltJ7zYPo7us/edit]

I think the problem is I am using a service account for OAuth. I need to use this.

So.. I want to create google sheet and give a permission to read and edit to person I select.

Please help me out...!

```<code> /**
 * Application name.
 */
private static final String APPLICATION_NAME = "Google Sheets API Java";

/**
 * Global instance of the JSON factory.
 */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/**
 * Global instance of the HTTP transport.
 */
private static HttpTransport HTTP_TRANSPORT;

/**
 * Global instance of the scopes required by this quickstart.
 * <p>
 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/sheets.googleapis.com-java-quickstart
 */
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GoogleSheetConfig.class.getResourceAsStream("/My Service Account Information.json");
    GoogleCredential credential = GoogleCredential
            .fromStream(in)
            .createScoped(SCOPES);
    return credential;
}

/**
 * Build and return an authorized Sheets API client service.
 *
 * @return an authorized Sheets API client service
 * @throws IOException
 */
@Bean
public Sheets getSheetsService() throws Exception {
    Credential credential = authorize();
    return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}
</code>```

my Service Account Information is like :

```<code>{
"type": "service_account",
"project_id": "my project id ",
"private_key_id": "fb925c0954********",
"private_key":
"client_email": "test-service-accoun@admin-auth-
test.iam.gserviceaccount.com",
"client_id": "my client id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":
"https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":
"https://www.googleapis.com/robot/v1/metadata/x509/admin-auth-test-
service-accoun%40admin-auth-test.iam.gserviceaccount.com"
}
</code>```

Below is my test code to create the sheet :

```<code>Spreadsheet requestBody = new Spreadsheet();

Sheets.Spreadsheets.Create request = sheets.spreadsheets().create(requestBody);

Spreadsheet response = request.execute();
System.out.println(response);
</code>```

答:
You are correct, since you are using a service account the file created by it is only accessible to that account. As stated in this tutorial about service account:

Using a service account to access Google Drive API can be very useful but it is important to remember that a service account is not you. If you want to be able to access the files it uploads you must grant yourself access to them though the service account.

To add your self a permission to the file:

Use Drive API

use Permissions: update or Permissions: create

I suggest that you create the sheets using Drive API to add permission in the sheet creation. Then use Sheets API to edit the content.

Hope this helps.

Body:
I am using Google Sheet API (V4).

I had my google account like "test@google.com". To use google api, I made a project in Google Console and created service account.

I want to create a Google Sheet that can be accessed by only authorized person and myself who create the sheet. The authorized person can read and edit. Either do i.

But whenever I tired my code, it went well and I can get the sheet url. but when I click the url they show I need a permission.
 It is the url that I created [https://docs.google.com/spreadsheets/d/1RKR-ErUaC_LujUUDf8o_yIprEz223U1EltJ7zYPo7us/edit]

I think the problem is I am using a service account for OAuth. I need to use this.

So.. I want to create google sheet and give a permission to read and edit to person I select.

Please help me out...!

 /**
 * Application name.
 */
private static final String APPLICATION_NAME = "Google Sheets API Java";

/**
 * Global instance of the JSON factory.
 */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/**
 * Global instance of the HTTP transport.
 */
private static HttpTransport HTTP_TRANSPORT;

/**
 * Global instance of the scopes required by this quickstart.
 *

 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/sheets.googleapis.com-java-quickstart
 */
private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 *
 * @return an authorized Credential object.
 * @throws IOException
 */
public Credential authorize() throws IOException {
    // Load client secrets.
    InputStream in = GoogleSheetConfig.class.getResourceAsStream("/My Service Account Information.json");
    GoogleCredential credential = GoogleCredential
            .fromStream(in)
            .createScoped(SCOPES);
    return credential;
}

/**
 * Build and return an authorized Sheets API client service.
 *
 * @return an authorized Sheets API client service
 * @throws IOException
 */
@Bean
public Sheets getSheetsService() throws Exception {
    Credential credential = authorize();
    return new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

my Service Account Information is like :

{
"type": "service_account",
"project_id": "my project id ",
"private_key_id": "fb925c0954********",
"private_key":
"client_email": "test-service-accoun@admin-auth-
test.iam.gserviceaccount.com",
"client_id": "my client id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url":
"https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url":
"https://www.googleapis.com/robot/v1/metadata/x509/admin-auth-test-
service-accoun%40admin-auth-test.iam.gserviceaccount.com"
}

Below is my test code to create the sheet :

Spreadsheet requestBody = new Spreadsheet();

Sheets.Spreadsheets.Create request = sheets.spreadsheets().create(requestBody);

Spreadsheet response = request.execute();
System.out.println(response);


问:
Why EditorBrowsable doesn't work?
I tried to hide inherited property in intellisense with EditorBrowsable (as said here Hiding user control properties from IntelliSense), when testing in client form though I can still see it why ?

```<code>[
Category("Main"),
Description("Text"),
Obsolete("Don't use this"),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override String Text
{
    get { return null; }
}
</code>```

答:
Are you using ReSharper? It seems like ReSharper doesn't obey the EditorBrowsable attribute.
 If I turn off ReSharper, I don't see my property. If I turn ReSharper on, it does show.

In ReSharper Options, go to Environment | IntelliSense | Completion Appearance and check "Filter members by [EditorBrowsable] attribute".

You still have to reference the assembly though, it doesn't work within a solution if you reference your usercontrol's project.

Title: Why EditorBrowsable doesn't work?

Body:
I tried to hide inherited property in intellisense with EditorBrowsable (as said here Hiding user control properties from IntelliSense), when testing in client form though I can still see it why ?

[
Category("Main"),
Description("Text"),
Obsolete("Don't use this"),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public override String Text
{
    get { return null; }
}

ContentLicense: CC BY-SA 4.0


答:
You have a typo in your code which is leading to an error. Your code is

```<code>$sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id '".$tid."'";
</code>```

At the very end you forgot to add an "=" to check the equality of topic_id to $tid. It should be

```<code>$sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id = '".$tid."'";
</code>```

Title: Forum SQL syntax Error

Body:
You have a typo in your code which is leading to an error. Your code is

$sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id '".$tid."'";

At the very end you forgot to add an "=" to check the equality of topic_id to $tid. It should be

$sql2 = "SELECT * FROM posts WHERE category_id = '".$cid."' AND topic_id = '".$tid."'";


问:
Retrieving card data in card-badges
I have an overlay and I'm able to save data using

```<code>t.set('card', 'shared', 'key', 'value')
</code>```

Also i'm able to read that data using

```<code>return Promise.all([
    t.get('card', 'shared', 'key1'),
    t.get('card', 'shared', 'key2')
  ])
  .spread(function(key1, key2){
</code>```

My problem is that I want to read those values from the TrelloPowerUp.initialize and inside the card-badges

I tried using

var x = t.get('card', 'shared', 'key1');

If I put console.log(x), the value is in there but is inside an object and can't make it work. The name of the property is _settledValue

I already tried x.getValue() and x.value()

file.png

答:
Ok, answer myself</p>

```<code>t.get('card', 'shared', 'var_name').then(function(var_name){ /* operations with var_name here */ }
</code>```

Title: Retrieving card data in card-badges

Body:
I have an overlay and I'm able to save data using

t.set('card', 'shared', 'key', 'value')

Also i'm able to read that data using

return Promise.all([
    t.get('card', 'shared', 'key1'),
    t.get('card', 'shared', 'key2')
  ])
  .spread(function(key1, key2){

My problem is that I want to read those values from the TrelloPowerUp.initialize and inside the card-badges

I tried using

var x = t.get('card', 'shared', 'key1');

If I put console.log(x), the value is in there but is inside an object and can't make it work. The name of the property is _settledValue

I already tried x.getValue() and x.value()

file.png

Body:
Ok, answer myself

t.get('card', 'shared', 'var_name').then(function(var_name){ /* operations with var_name here */ }


问:
How to check copyright status of livestreaming
I'm livestreaming an event and I use some songs from other author. The live video now show the Youtube logo because youtube detect the copyright. The question is can I get the copyright status of video through Youtube API ? So I can stop the song before youtube stop my stream ? </p>

答:
You may want to check the docs regarding the contentDetails, as stated you can use contentDetails.licensedContent to check if the video is copyrighted:

Indicates whether the video represents licensed content, which means that the content was uploaded to a channel linked to a YouTube content partner and then claimed by that partner.

Hope this helps.


问:
The type provided ('video/mp2t; codecs="avc1.100.42,mp4a.40.2"') is unsupported
I have a user trying to cast an m3u8 video and he keeps getting that error.

```<code>The type provided ('video/mp2t; codecs="avc1.100.42,mp4a.40.2"') is unsupported.
</code>```

Is that codec supposed to be supported?

Thank.

答:
As stated in some threads and related SO post, some builds of Chromecast were rejected so it is recommended to use supported media type like "avc1.66.30" instead. As stated in this forum, a workaround would be trying to update the playlist or use host.processManifest.

Hope this helps.

Body:
I have a user trying to cast an m3u8 video and he keeps getting that error.

The type provided ('video/mp2t; codecs="avc1.100.42,mp4a.40.2"') is unsupported.

Is that codec supposed to be supported?

Thank.


问:
What is the difference between an .appxupload and an .appxbundle and which one should I upload to the store?
I have just build my application for UWP for the Windows store.

Visual Studio had produced a collection of files. Some of which are:

```<code>MyApp.appxupload
MyApp.appxBundle
</code>```

What is the difference between these two files? and which one should I upload to the store?

答:
From this link: https://learn.microsoft.com/en-us/windows/uwp/packaging/packaging-uwp-apps it states:

To sell your Universal Windows Platform (UWP) app or distribute it to
  other users, you need to create an appxupload package for it. When you
  create the appxupload, another appx package will be generated to use
  for testing and sideloading. You can distribute your app directly by
  sideloading the appx package to a device. This article describes the
  process of configuring, creating and testing a UWP app package. For
  more information about sideloading, see Sideload Apps in Windows 10.

also on this page: https://learn.microsoft.com/en-us/windows/uwp/publish/upload-app-packages it states:

Important For Windows 10, you should always upload the .appxupload
  file here, not the .appx or .appxbundle. For more info about packaging
  UWP apps for the Store, see Packaging Universal Windows apps for
  Windows 10.

So in conclusion the appxupload is for uploading to the Windows store and the appxbundle is for sideloading

Body:
I have just build my application for UWP for the Windows store.

Visual Studio had produced a collection of files. Some of which are:

MyApp.appxupload
MyApp.appxBundle

What is the difference between these two files? and which one should I upload to the store?


问:
JavaScript - Form validation loop through specific fields
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

```<code><form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>
</code>```

答:
You really should use some javascript toolkit for help with this, but if not this might help:

```<code>validateSelectChoices = function(){
  return document.getElementById('choice1').selectedIndex || document.getElementById('choice2').selectedIndex;
}
</code>```

This will check to see if one of the select boxes has the 'hello' value selected (keep in mind that dropdowns will always default to the first option in the list, in your case 'bye'.

Body:
I'm wondering, what would be a short/good way of performing form validation in JavaScript by looping through all input-text as well as <select>, however, the condition on the select is that out of the 2 selects, ONLY one needs to be selected.

<form id="daform">
<input type="text" value="" name="name" id="name" />
<input type="text" value="" name="last" id="last" />

<select id="choice1" name="choice1">
 <option>Bye</option>
 <option>Hello</option>
</select>

<select id="choice2" name="choice2">
 <option>Bye</option>
 <option>Hello</option>
</select>

<input type="submit" />
</form>

Body:
You really should use some javascript toolkit for help with this, but if not this might help:

validateSelectChoices = function(){
  return document.getElementById('choice1').selectedIndex || document.getElementById('choice2').selectedIndex;
}

This will check to see if one of the select boxes has the 'hello' value selected (keep in mind that dropdowns will always default to the first option in the list, in your case 'bye'.


问:
How to normalize comma separated values within column of table and then run query
Let's say I have a table with the following structure:

```<code> | column1    |    column2       |
 |------------|------------------|
 | a          |    1,L,3,K,5,    |
 | b          |    R,6,7,8,9     |
 | c          |    8,9,10,D      |
 | d          |    1,2,3,H       |
</code>```

Let's say that column1 can potentially continue on through z and that column2 can continue on with random numbers and letters. I would like a general solution that can apply to any number of rows and columns, and number of values in column2.

I want to run a query in MySQL that will search all the values in column2 and output the letters in column1 that contain a 3 in column2. The output should be:

```<code> | column1    |
 |------------|
 | a          |
 | d          |
</code>```

Many posts have answers with queries that directly accomplish this, but I would like to do it the correct way. I am new to sql, but I believe that would mean to normalize the data in column2 by creating a new table and running a query on this new table instead.

Can someone help me with the code to normalize and run this query in MySQL? Thanks.

答:
I know this is old post but I thought I'd contribute since I needed to perform this exercise myself and this gave me some ideas.

Here is the solution I arrived at,  the proviso here is that the values in the comma delimited list were defined uniquely in another table:

```<code>create table `defined_values` (
  id int(11) not null auto_increment primary key,
  label varchar(12) not null,
  constraint `defined_values_uidx` unique (`label`)
) engine = innodb charset utf8;

create table `delimited_string` (
  id int(11) not null auto_increment primary key,
  `str_delim` varchar(32) not null
) engine = innodb charset utf8;

insert into `defined_values` (`label`) values
('YVR'),
('YEG'),
('YXJ'),
('YYC'),
('YMM')
;

insert into `delimited_string` (`str_delim`) values
('YVR,YEG,YXJ,YYC,YMM')
;

select
  v.`label` as `normalized`
from
  `delimited_string` s
  join `defined_values` v on (v.`label` = substring(s.`str_delim`, position(v.`label` in s.`str_delim`), length(v.`label`)))
</code>```

;

// Yields:

```<code>+------------+
| normalized |
+------------+
| YEG        |
| YMM        |
| YVR        |
| YXJ        |
| YYC        |
+------------+
</code>```

5 rows in set (0.00 sec)

Body:
Let's say I have a table with the following structure:

 | column1    |    column2       |
 |------------|------------------|
 | a          |    1,L,3,K,5,    |
 | b          |    R,6,7,8,9     |
 | c          |    8,9,10,D      |
 | d          |    1,2,3,H       |

Let's say that column1 can potentially continue on through z and that column2 can continue on with random numbers and letters. I would like a general solution that can apply to any number of rows and columns, and number of values in column2.

I want to run a query in MySQL that will search all the values in column2 and output the letters in column1 that contain a 3 in column2. The output should be:

 | column1    |
 |------------|
 | a          |
 | d          |

Many posts have answers with queries that directly accomplish this, but I would like to do it the correct way. I am new to sql, but I believe that would mean to normalize the data in column2 by creating a new table and running a query on this new table instead.

Can someone help me with the code to normalize and run this query in MySQL? Thanks.

Body:
I know this is old post but I thought I'd contribute since I needed to perform this exercise myself and this gave me some ideas.

Here is the solution I arrived at,  the proviso here is that the values in the comma delimited list were defined uniquely in another table:

create table `defined_values` (
  id int(11) not null auto_increment primary key,
  label varchar(12) not null,
  constraint `defined_values_uidx` unique (`label`)
) engine = innodb charset utf8;

create table `delimited_string` (
  id int(11) not null auto_increment primary key,
  `str_delim` varchar(32) not null
) engine = innodb charset utf8;

insert into `defined_values` (`label`) values
('YVR'),
('YEG'),
('YXJ'),
('YYC'),
('YMM')
;

insert into `delimited_string` (`str_delim`) values
('YVR,YEG,YXJ,YYC,YMM')
;

select
  v.`label` as `normalized`
from
  `delimited_string` s
  join `defined_values` v on (v.`label` = substring(s.`str_delim`, position(v.`label` in s.`str_delim`), length(v.`label`)))

;

// Yields:

+------------+
| normalized |
+------------+
| YEG        |
| YMM        |
| YVR        |
| YXJ        |
| YYC        |
+------------+

5 rows in set (0.00 sec)


问:
Calling a method of MainActivity from other class
I am developing an Android app and thus, I have a MainActivity class. Inside of that MainActivity class, I have a method, let's call it doSomething():

```<code>public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void doSomething(){
        // bla bla bla
    }
}
</code>```

I also have a different class (with different layout) that is called OtherActivity. I want to use the doSomething method inside it:

```<code>public class OtherActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
    }
}
</code>```

I tried this:

```<code>public class OtherActivity extends AppCompatActivity {
    MainActivity main;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        MainActivity main = new MainActivity();
        main.doSomething();
    }
}
</code>```

But it does not work. I also tried to make OtherActivity to extend the MainActivity, doing the following:

```<code>public class OtherActivity extends MainActivity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        super.doSomething();
    }
}
</code>```

But it does not allow me to initialize the layout...

How can I do?

Thanks in advance.

答:
To communicate between to Activity Broadcast is the best way, and for the same application, we can use local broadcast using LocalBroadcastManager.

First, we should register one broadcast in MainActivity,

```<code>public class MainActivity1 extends AppCompatActivity {

    public static final String INTENT_FILTER = "do_some_action";
    public static final String INTENT_BUNDLE_VALUE = "value1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main1);

        LocalBroadcastManager.getInstance(this).registerReceiver(
                mChangeListener, new IntentFilter(INTENT_FILTER));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(mChangeListener);
    }

    private BroadcastReceiver mChangeListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intentData) {
            // you can do anything here
            if (intentData != null && intentData.hasExtra(INTENT_BUNDLE_VALUE)) {
                String value = intentData.getStringExtra(INTENT_BUNDLE_VALUE);

                doSomeAction(value);
            }
        }
    };
    private void doSomeAction(String value) {

    }
}
</code>```

Then to do some action in MainActivity from OtherActivity, we can send Local broadcast from OtherActivity it will reach the receiver of Which we register in MainActivity,

```<code>public class OtherActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);

        // You can call MainActivity to do some actions
        Intent intent = new Intent(MainActivity1.INTENT_FILTER);

        intent.putExtra(MainActivity1.INTENT_BUNDLE_VALUE, "Any string or any value");

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}
</code>```

Done!!!.

Body:
I am developing an Android app and thus, I have a MainActivity class. Inside of that MainActivity class, I have a method, let's call it doSomething():

public class MainActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void doSomething(){
        // bla bla bla
    }
}

I also have a different class (with different layout) that is called OtherActivity. I want to use the doSomething method inside it:

public class OtherActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
    }
}

I tried this:

public class OtherActivity extends AppCompatActivity {
    MainActivity main;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        MainActivity main = new MainActivity();
        main.doSomething();
    }
}

But it does not work. I also tried to make OtherActivity to extend the MainActivity, doing the following:

public class OtherActivity extends MainActivity{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.other_activity_layout);

        // Let's use doSomething()
        super.doSomething();
    }
}

But it does not allow me to initialize the layout...

How can I do?

Thanks in advance.

Body:
To communicate between to Activity Broadcast is the best way, and for the same application, we can use local broadcast using LocalBroadcastManager.

First, we should register one broadcast in MainActivity,

public class MainActivity1 extends AppCompatActivity {

    public static final String INTENT_FILTER = "do_some_action";
    public static final String INTENT_BUNDLE_VALUE = "value1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main1);

        LocalBroadcastManager.getInstance(this).registerReceiver(
                mChangeListener, new IntentFilter(INTENT_FILTER));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(mChangeListener);
    }

    private BroadcastReceiver mChangeListener = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intentData) {
            // you can do anything here
            if (intentData != null && intentData.hasExtra(INTENT_BUNDLE_VALUE)) {
                String value = intentData.getStringExtra(INTENT_BUNDLE_VALUE);

                doSomeAction(value);
            }
        }
    };
    private void doSomeAction(String value) {

    }
}

Then to do some action in MainActivity from OtherActivity, we can send Local broadcast from OtherActivity it will reach the receiver of Which we register in MainActivity,

public class OtherActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);

        // You can call MainActivity to do some actions
        Intent intent = new Intent(MainActivity1.INTENT_FILTER);

        intent.putExtra(MainActivity1.INTENT_BUNDLE_VALUE, "Any string or any value");

        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

Done!!!.


问:
simplexml_load_string cannot load XML / No error / result not === false
XML:

```<code>    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<result sync="false" version="2">
    <action>start-subscription</action>
    <action_result>
        <code>103</code>
        <detail>1 missing parameter</detail>
        <missing_parameters>
            <missing_parameter>
                <key>operator</key>
            </missing_parameter>
        </missing_parameters>
        <status>1</status>
    </action_result>
    <custom_parameters>
        <custom_parameter>
            <key>cp_REF</key>
            <value>simpleLPADULTCHSMSV2___WoopGang------___Adjomo___external___paid___android___CH___WIFI___locale=fr_FR</value>
        </custom_parameter>
    </custom_parameters>
    <customer>
        <country>CH</country>
        <language>en</language>
    </customer>
    <payment_parameters>
        <channel>web</channel>
        <method>OPERATOR</method>
        <order>90330</order>
    </payment_parameters>
    <transactions>
        <transaction>
            <id>1308636894</id>
            <status>-1</status>
        </transaction>
    </transactions>
    <request_id>1591621_t593818e0f3913</request_id>
    <reference>09045c8e-9ec1-4306-8699-5ac5306983b2</reference>
</result>
</code>```

PHP:

```<code>    $xml = file_get_contents("php://input");
    $datas = array();
    parse_str($xml, $datas);
    $data = $datas['data'];
    libxml_use_internal_errors(true);

    $xml = simplexml_load_string($data);

    if($xml === false){
        foreach(libxml_get_errors() as $error) {
            $this->_logCall(self::LOG_DIMOCO, $error->message,"--");
         }
     }else{
         $this->_logCall(self::LOG_DIMOCO, 'loaded simpleXML '.print_r($xml), ' --');
     }
</code>```

Running that ends in the last ELSE and the result is "1"

Any idea what I'm doing wrong ?
I have to add some text because apparently its mostly code and not understandable. Now ? Now ? Now ? Now ?

答:
print_r() (by default) doesn't return output, it prints it -- so you can't use it in a string context. If you want to do that, you can pass a truthy value as the second parameter to have it return the output instead of printing it:

```<code>$this->_logCall(self::LOG_DIMOCO, 'loaded simpleXML '.print_r($xml, true), ' --');
</code>```

Body:
XML:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<result sync="false" version="2">
    <action>start-subscription</action>
    <action_result>
        103
        <detail>1 missing parameter</detail>
        <missing_parameters>
            <missing_parameter>
                <key>operator</key>
            </missing_parameter>
        </missing_parameters>
        <status>1</status>
    </action_result>
    <custom_parameters>
        <custom_parameter>
            <key>cp_REF</key>
            <value>simpleLPADULTCHSMSV2___WoopGang------___Adjomo___external___paid___android___CH___WIFI___locale=fr_FR</value>
        </custom_parameter>
    </custom_parameters>
    <customer>
        <country>CH</country>
        <language>en</language>
    </customer>
    <payment_parameters>
        <channel>web</channel>
        <method>OPERATOR</method>
        <order>90330</order>
    </payment_parameters>
    <transactions>
        <transaction>
            <id>1308636894</id>
            <status>-1</status>
        </transaction>
    </transactions>
    <request_id>1591621_t593818e0f3913</request_id>
    <reference>09045c8e-9ec1-4306-8699-5ac5306983b2</reference>
</result>

PHP:

    $xml = file_get_contents("php://input");
    $datas = array();
    parse_str($xml, $datas);
    $data = $datas['data'];
    libxml_use_internal_errors(true);

    $xml = simplexml_load_string($data);

    if($xml === false){
        foreach(libxml_get_errors() as $error) {
            $this->_logCall(self::LOG_DIMOCO, $error->message,"--");
         }
     }else{
         $this->_logCall(self::LOG_DIMOCO, 'loaded simpleXML '.print_r($xml), ' --');
     }

Running that ends in the last ELSE and the result is "1"

Any idea what I'm doing wrong ?
I have to add some text because apparently its mostly code and not understandable. Now ? Now ? Now ? Now ?

Body:
print_r() (by default) doesn't return output, it prints it -- so you can't use it in a string context. If you want to do that, you can pass a truthy value as the second parameter to have it return the output instead of printing it:

$this->_logCall(self::LOG_DIMOCO, 'loaded simpleXML '.print_r($xml, true), ' --');


答:
```<code>require(data.table)

a<-data.table(cbind("Sample"=c("100","101","102","103"),"Status"=c("Y","","","partial")))
b<-data.table("Sample"=c("100","101","102","103","106"),"Status"=c("NA","Y","","","Y"))

c <- merge(a, b, by = "Sample", all=TRUE)
c[,Status := ifelse(!is.na(Status.x), Status.x, Status.y)]
c[,`:=` (Status.x=NULL, Status.y = NULL)]
</code>```

Title: Merging columns with overlapping data in R data frames

Body:
a<-data.frame(cbind("Sample"=c("100","101","102","103"),"Status"=c("Y","","","partial")))
b<-data.frame(cbind("Sample"=c("100","101","102","103","106"),"Status"=c("NA","Y","","","Y")))

desired<-data.frame(cbind("Sample"=c("100","101","102","103","106"),"Status"=c("Y","Y","","partial","Y")))

I have sample processing data in multiple sources and I'd like to combine them into a master list. How can I merge the "Status" column between 2 data frames such that a overrules b in order to collate "Y" and "partial" for each sample? Thank you in advance.


问:
Enum trick in C++/CLI
In native C++ we could use enum trick in class definition:

```<code>namespace EFoo
{
  enum { a = 10; };
}

class Foo
{
   // Declare an array of 10 integers.
   int m_Arr[EFoo::a];
};
</code>```

However, with managed enum in C++/CLI,

```<code>public enum class EFoo
{
  a = 10,
};
</code>```

EFoo::a couldn't be converted implicitly to int,
so the enum trick wouldn't be allowed.

Is there any workaround?

Thanks.

答:
If you are just trying to achieve the 'enum hack', you should not have to do that in any recent compiler, as they will support static const member declarations.

```<code>class Foo
{
private:
    static const int ARRAY_SIZE = 10;
    int m_arr[ARRAY_SIZE];
};
</code>```

Otherwise, doing an int cast like Jonathan Wood answered would work to change from a managed enum to an int.

Title: Enum trick in C++/CLI

Body:
In native C++ we could use enum trick in class definition:

namespace EFoo
{
  enum { a = 10; };
}

class Foo
{
   // Declare an array of 10 integers.
   int m_Arr[EFoo::a];
};

However, with managed enum in C++/CLI,

public enum class EFoo
{
  a = 10,
};

EFoo::a couldn't be converted implicitly to int,
so the enum trick wouldn't be allowed.

Is there any workaround?

Thanks.

Body:
If you are just trying to achieve the 'enum hack', you should not have to do that in any recent compiler, as they will support static const member declarations.

class Foo
{
private:
    static const int ARRAY_SIZE = 10;
    int m_arr[ARRAY_SIZE];
};

Otherwise, doing an int cast like Jonathan Wood answered would work to change from a managed enum to an int.


问:
How to compare variable from js and twig
I need to check statement of two variables one comes from my server and I access this from TWIG, second, comes from javascript (data table column value). I need to check like this

```<code>{% if key.orderid == 19 %}
</code>```

Where 19 should be replaced with js variable.

Code for research:

```<code>// format function for row details
var fnFormatDetails = function( datatable, tr ) {
var data = datatable.fnGetData( tr );
            return [
                    '<table class="table mb-none">',
                    '<tr class="b-top-none">',
                    '<td><label class="mb-none">Produkt:</label></td>',
                    '<td>Ilość:</td>',
                    '</tr>',
                    '{% for index, key in orderProducts %}{% if key.orderid == 19 %}<tr class="b-top-none">',
                    '<td><label class="mb-none">{{ index }}</label></td>',
                    '<td>{{ key.productid }}   {{ key.amount }}</td>',
                    '</tr>{% endif %}{% endfor %}',
                    '</table>'
                ].join('');
};
</code>```

答:
Write your conditional statement in JS instead of twig.</p>

```<code>var tmp = ['<table class="table mb-none">'];
{% for index, key in orderProducts %}
  if (19 == {{ key.orderid }}) {
    tmp.push('<tr class="b-top-none">','<td></td>','</tr>');
  }
{% endfor %}
tmp.push('</table>');
return tmp.join('');
</code>```

Body:
I need to check statement of two variables one comes from my server and I access this from TWIG, second, comes from javascript (data table column value). I need to check like this

{% if key.orderid == 19 %}

Where 19 should be replaced with js variable.

Code for research:

// format function for row details
var fnFormatDetails = function( datatable, tr ) {
var data = datatable.fnGetData( tr );
            return [
                    '
',
                    '
',
                    'Produkt:	',
                    'Ilość:	',
                    '
',
                    '{% for index, key in orderProducts %}{% if key.orderid == 19 %}
',
                    '{{ index }}	',
                    '{{ key.productid }}   {{ key.amount }}	',
                    '
{% endif %}{% endfor %}',
                    '
'
                ].join('');
};

Body:
Write your conditional statement in JS instead of twig.

var tmp = ['<table class="table mb-none">'];
{% for index, key in orderProducts %}
  if (19 == {{ key.orderid }}) {
    tmp.push('<tr class="b-top-none">','<td></td>','</tr>');
  }
{% endfor %}
tmp.push('</table>');
return tmp.join('');


问:
using scrollview to show button behind edittext keyboard
I have a layout in which I have an image,textview, editbox and a button so whenever the keyboard opens I wanted my screen to scroll down to the button so that the user can always type and press submit button. I did do this by using scrollview but than I removed the scroll view did some changes and now when I again use a scrollview it does not work.
here is the code please check.

layout_file:

```<code><?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="myapp.anis.hotel.MainActivity"
android:background="@drawable/backgroundhotel"
android:fitsSystemWindows="true">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scroll">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
    android:text="Please share your feedback"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView6"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:textColor="@android:color/background_dark"
    android:fontFamily="serif"
    android:layout_below="@+id/imageView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp" />

<TextView
    android:text="@string/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/thanks"
    android:shadowColor="@android:color/background_light"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:textColorHighlight="@android:color/background_dark"
    android:textColor="@android:color/background_dark"
    android:fontFamily="serif"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp" />

<ImageView
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/hotellogo"
    android:id="@+id/imageView"

    android:layout_height="150dp"
    android:layout_marginTop="15dp"
    android:layout_below="@+id/thanks"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="match_parent"
    android:ems="10"
    android:maxLines="50"
    android:background="@android:drawable/editbox_background"
    android:layout_marginTop="15dp"
    android:id="@+id/feedback"
    android:hint="Enter FeedBack"
    android:inputType="textMultiLine"
    android:gravity="left"
    android:textColorHint="@android:color/background_dark"
    android:textColor="@android:color/background_dark"
    android:textColorHighlight="@android:color/background_dark"
    android:layout_below="@+id/textView6"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_height="180dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/submitting1"
        android:background="@android:color/transparent"
        android:onClick="onSubmit"
        android:id="@+id/submit"
        android:layout_below="@id/feedback"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>
</ScrollView>
    </RelativeLayout>
</code>```

and in my main activity I am using the scrollto method to go to my image button.

```<code>public class MainActivity extends AppCompatActivity {

ImageButton submit;
EditText feedBack;
static public String saveFeedBack="";
ScrollView view;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    submit = (ImageButton) findViewById(R.id.submit);
    feedBack = (EditText) findViewById(R.id.feedback);
    view = (ScrollView) findViewById(R.id.scroll);
    view.scrollTo(submit.getScrollX(),submit.getScrollY());
    }

public void onSubmit(View view){

    saveFeedBack = feedBack.getText().toString();
    if(saveFeedBack.length() >=4) {
        Intent intent = new Intent(this, Main3Activity.class);
        startActivity(intent);
    }
    else{
        Toast.makeText(getApplicationContext(),"Enter valid Feedback please.",Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onRestart() {
    super.onRestart();
    feedBack.setText("");
    feedBack.setHint("Enter Feedback");
}
</code>```

}

but when I run my application the scrollview scrolls to my edit text but not my button. I have tried adjustResize,adjustPan and all those things but none of them worked.

答:
ok after much of research I have solved your problem. Actually the thing is when you use scroll to any position inside onCreate it doesn't work because a small delay is required to inflate the view.

So use the below code inside your onCreate:

```<code>view.postDelayed(new Runnable() {
            @Override
            public void run() {
                view.fullScroll(ScrollView.FOCUS_DOWN);
            }
        },200);
</code>```

Hope it Helps!!!

Body:
I have a layout in which I have an image,textview, editbox and a button so whenever the keyboard opens I wanted my screen to scroll down to the button so that the user can always type and press submit button. I did do this by using scrollview but than I removed the scroll view did some changes and now when I again use a scrollview it does not work.
here is the code please check.

layout_file:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context="myapp.anis.hotel.MainActivity"
android:background="@drawable/backgroundhotel"
android:fitsSystemWindows="true">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/scroll">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<TextView
    android:text="Please share your feedback"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textView6"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:textColor="@android:color/background_dark"
    android:fontFamily="serif"
    android:layout_below="@+id/imageView"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp" />

<TextView
    android:text="@string/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/thanks"
    android:shadowColor="@android:color/background_light"
    android:textAppearance="@style/TextAppearance.AppCompat.Large"
    android:textColorHighlight="@android:color/background_dark"
    android:textColor="@android:color/background_dark"
    android:fontFamily="serif"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="15dp" />

<ImageView
    android:layout_width="wrap_content"
    app:srcCompat="@drawable/hotellogo"
    android:id="@+id/imageView"

    android:layout_height="150dp"
    android:layout_marginTop="15dp"
    android:layout_below="@+id/thanks"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="match_parent"
    android:ems="10"
    android:maxLines="50"
    android:background="@android:drawable/editbox_background"
    android:layout_marginTop="15dp"
    android:id="@+id/feedback"
    android:hint="Enter FeedBack"
    android:inputType="textMultiLine"
    android:gravity="left"
    android:textColorHint="@android:color/background_dark"
    android:textColor="@android:color/background_dark"
    android:textColorHighlight="@android:color/background_dark"
    android:layout_below="@+id/textView6"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_height="180dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/submitting1"
        android:background="@android:color/transparent"
        android:onClick="onSubmit"
        android:id="@+id/submit"
        android:layout_below="@id/feedback"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>
</ScrollView>
    </RelativeLayout>

and in my main activity I am using the scrollto method to go to my image button.

public class MainActivity extends AppCompatActivity {

ImageButton submit;
EditText feedBack;
static public String saveFeedBack="";
ScrollView view;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    submit = (ImageButton) findViewById(R.id.submit);
    feedBack = (EditText) findViewById(R.id.feedback);
    view = (ScrollView) findViewById(R.id.scroll);
    view.scrollTo(submit.getScrollX(),submit.getScrollY());
    }

public void onSubmit(View view){

    saveFeedBack = feedBack.getText().toString();
    if(saveFeedBack.length() >=4) {
        Intent intent = new Intent(this, Main3Activity.class);
        startActivity(intent);
    }
    else{
        Toast.makeText(getApplicationContext(),"Enter valid Feedback please.",Toast.LENGTH_SHORT).show();
    }
}

@Override
protected void onRestart() {
    super.onRestart();
    feedBack.setText("");
    feedBack.setHint("Enter Feedback");
}

}

but when I run my application the scrollview scrolls to my edit text but not my button. I have tried adjustResize,adjustPan and all those things but none of them worked.

Body:
ok after much of research I have solved your problem. Actually the thing is when you use scroll to any position inside onCreate it doesn't work because a small delay is required to inflate the view.

So use the below code inside your onCreate:

view.postDelayed(new Runnable() {
            @Override
            public void run() {
                view.fullScroll(ScrollView.FOCUS_DOWN);
            }
        },200);

Hope it Helps!!!


问:
Django - Handling several file upload requests at a time?
I am developing a django application which handles lots of file uploads from multiple clients periodically. Each file is around 1 to 10 megabytes.

Since uploads are thread blocking I can only serve a number of requests equivalent to the number of uwsgi workers/processes (4 in my case).

What should I do to increase throughput?

Is it advisable to increase number of processes/workers in uwsgi?

What should be the upper limit?

Is there any other solution that I can use in this scenario?

Stack: django+uwsgi+nginx running on amazon ec2 and s3 buckets used for storing zip files.

答:
You need to use asynchronous task queue to upload multiple files at a time.
These tasks can execute asynchronously (in the background)

I am using Celery/Disque to acheive the same .

Read about disque here

You can do it via

```<code>pip install django-queued-storage
</code>```

For more refer here

Body:
You need to use asynchronous task queue to upload multiple files at a time.
These tasks can execute asynchronously (in the background)

I am using Celery/Disque to acheive the same .

Read about disque here

You can do it via

pip install django-queued-storage

For more refer here


问:
The URL '/session' did not map to a valid resource | How to run desktop application test using winAppDriver / windows application driver using java?
I'm trying to run automate test for windows calculator app on windows10 using Windows application driver (winAppDriver), appium and java as below example:  https://github.com/Microsoft/WinAppDriver/tree/master/Samples/Java/CalculatorTest, but when I run the test after started the appium getting below mentioned error:

```<code>org.openqa.selenium.UnsupportedCommandException: The URL '/session' did not map to a valid resource
Command duration or timeout: 204 milliseconds
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'LKXXXX', ip: '10.88.68.53', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: io.appium.java_client.ios.IOSDriver
</code>```

My code is as below:

```<code>import org.junit.*;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.concurrent.TimeUnit;
import java.net.URL;
import io.appium.java_client.ios.IOSDriver;

public class CalculatorTest {

    private static IOSDriver CalculatorSession = null;
    private static WebElement CalculatorResult = null;

    @BeforeClass
    public static void setup() {
        try {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("app", "C:\\Windows\\System32\\calc.exe");
            CalculatorSession = new IOSDriver(new URL("http://127.0.0.1:4723"), capabilities);
            CalculatorSession.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

            CalculatorSession.findElementByName("Clear").click();
            CalculatorSession.findElementByName("Seven").click();
            CalculatorResult = CalculatorSession.findElementByName("Display is  7 ");
            Assert.assertNotNull(CalculatorResult);

        }catch(Exception e){
            e.printStackTrace();
        } finally {
        }
    }
}
</code>```

My Dev Environment

Windows 10 (Developer mode enabled)

appium v1.6.5

java v1.8

winappdriver v0.9-beta

IDE - Eclipse

I will be glad if anyone can help me to fix this issue.

Thanks in advance.

答:
to my testing, the calculator app in windows doesn't open when you giving the system path you have to use
Microsoft.WindowsCalculator_8wekyb3d8bbwe!App

and you don't need to open appium sever has appium has the older version of winappdriver(0.7)

and just saying the winappdriver server should be running in the background

Body:
I'm trying to run automate test for windows calculator app on windows10 using Windows application driver (winAppDriver), appium and java as below example:  https://github.com/Microsoft/WinAppDriver/tree/master/Samples/Java/CalculatorTest, but when I run the test after started the appium getting below mentioned error:

org.openqa.selenium.UnsupportedCommandException: The URL '/session' did not map to a valid resource
Command duration or timeout: 204 milliseconds
Build info: version: '2.53.0', revision: '35ae25b1534ae328c771e0856c93e187490ca824', time: '2016-03-15 10:43:46'
System info: host: 'LKXXXX', ip: '10.88.68.53', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: io.appium.java_client.ios.IOSDriver

My code is as below:

import org.junit.*;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.util.concurrent.TimeUnit;
import java.net.URL;
import io.appium.java_client.ios.IOSDriver;

public class CalculatorTest {

    private static IOSDriver CalculatorSession = null;
    private static WebElement CalculatorResult = null;

    @BeforeClass
    public static void setup() {
        try {
            DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("app", "C:\\Windows\\System32\\calc.exe");
            CalculatorSession = new IOSDriver(new URL("http://127.0.0.1:4723"), capabilities);
            CalculatorSession.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);

            CalculatorSession.findElementByName("Clear").click();
            CalculatorSession.findElementByName("Seven").click();
            CalculatorResult = CalculatorSession.findElementByName("Display is  7 ");
            Assert.assertNotNull(CalculatorResult);

        }catch(Exception e){
            e.printStackTrace();
        } finally {
        }
    }
}

My Dev Environment

Windows 10 (Developer mode enabled)

appium v1.6.5

java v1.8

winappdriver v0.9-beta

IDE - Eclipse

I will be glad if anyone can help me to fix this issue.

Thanks in advance.


问:
How do I detect when a pdf's text was successfully extracted with PyPDF2.extractText?
I'm using the PyPDF2 library to extract text from PDF files via its extractText function, and for most PDFs, it works great!

However, some PDFs produce text that looks like this:

\n!"#$%&'()"+,"-.".)/"0$-1"2)+3-$.45\n""!"#$%&'()#'+),$!"#-.#$-/$0.1+"#+12$\n!"#"$!%"&#"%$'$()%+,-$(%.($#"$(%"&#%/%0!%\n$0"&$(%1(0,$2%3(%0"%0!%"&$%1(34+5"%36%1(0,$!7\n%%8%!"#$%&'($)%"\n%0!%#%+,-$(%"&#"%0!%3*9)%40'0!0-9$%-)%/%#*4%0"!$967\n%%:%0!%"&$%3*9)%$'$%\n1(0,$%+,-$(7\n%%;3%099+!"(#"$%6+4#,$"#9%"&$3($,%36%#(0"&,$"052%<%90!"%-$93=%"&$%1(0,$%6#5"3(0>#"03*%\n36%+,-$(!%-$"=$$%/%#4%:?7%@(0,$%+,-$(!%#($%0*%\n6.'78"AB%,$#*!%,+9"019)7C\n%"/D%E$0"&$(%1(0,$%*3(%53,13!0"$7%\n%:D%9%%%%%%%/FD%:BG\n%HD%:%%%%%%%/?D%HB?\n%%FD%:B:\n%3(

According to the docs, this be expected:

This works well for some PDF files, but poorly for others, depending
  on the generator used.

Unfortunately, the extractText() function doesn't raise any exceptions when it outputs text like the above.

So, my question is, is there a way to programmatically detect when the extractText() function returns gibberish?

答:
Based on @DYZ's comment, here's the solution.

document_path is assumed to the path to the PDF file you're opening. The rest should be pretty self-explanatory.

```<code>from PyPDF2 import PdfFileReader
from nltk.corpus import words

words = words.words()
document_file = PdfFileReader(open(document_path, 'rb'))
num_pages = document_file.getNumPages()
for page_num in range(0, num_pages):
    page = document_file.getPage(page_num)
    page_contents = page.extractText()
    if set(page_contents.lower().split()).intersection(words):
        # process page_contents
</code>```

Body:
Based on @DYZ's comment, here's the solution.

document_path is assumed to the path to the PDF file you're opening. The rest should be pretty self-explanatory.

from PyPDF2 import PdfFileReader
from nltk.corpus import words

words = words.words()
document_file = PdfFileReader(open(document_path, 'rb'))
num_pages = document_file.getNumPages()
for page_num in range(0, num_pages):
    page = document_file.getPage(page_num)
    page_contents = page.extractText()
    if set(page_contents.lower().split()).intersection(words):
        # process page_contents


问:
Change color of underline input and label in Materialize.css framework
I'm using the Materialize.css framework and I noticed that the color of the text input fields is green and so is the label.

Is there a way to change the color to something different?

```<code><input type="text" id="username" />
<label for="username">Username</label>
</code>```

答:
The dippas answer is correct, but if you want textareas to be the same colour you have to set this CSS rules:

```<code>/* label focus color */
    .input-field input[type=text]:focus + label, .materialize-textarea:focus:not([readonly]) + label {
     color: #005eed !important;
    }

/* label underline focus color */
    .input-field input[type=text]:focus, .materialize-textarea:focus:not([readonly]) {
     border-bottom: 1px solid #005eed !important;
     box-shadow: 0 1px 0 0 #005eed !important;
    }
</code>```

Note the .materialize-textarea rule for label and border bottom.

Body:
I'm using the Materialize.css framework and I noticed that the color of the text input fields is green and so is the label.

Is there a way to change the color to something different?

<input type="text" id="username" />
Username

Body:
The dippas answer is correct, but if you want textareas to be the same colour you have to set this CSS rules:

/* label focus color */
    .input-field input[type=text]:focus + label, .materialize-textarea:focus:not([readonly]) + label {
     color: #005eed !important;
    }

/* label underline focus color */
    .input-field input[type=text]:focus, .materialize-textarea:focus:not([readonly]) {
     border-bottom: 1px solid #005eed !important;
     box-shadow: 0 1px 0 0 #005eed !important;
    }

Note the .materialize-textarea rule for label and border bottom.


问:
Convert SVG polygon to a 3d polygon in svg not canvas
I have JSON data to generate some SVG (2D) polygons. I'm looking for a way to draw these polygons in SVG with three dimensions. I've found many libraries to draw 3D paths and polygons in canvas but I need SVG to have access to my polygons as a DOM object.
For better understanding, I want something like this but I want the output in SVG:
JSModeler

答:
SVG was never created to do 3D, but you can emulate 3D by having multiple polygons stand-in for polygon faces:

var Polygon = (function() {
  function Polygon(lines, fill) {
    if (lines === void 0) {
      lines = [];
    }
    if (fill === void 0) {
      fill = "rgba(" + (Math.round(Math.random() * 255)) + "," + (Math.round(Math.random() * 255)) + "," + (Math.round(Math.random() * 255)) + ",0.15)";
    }
    this.lines = lines;
    this.fill = fill;
    this.svgshape = document.createElementNS('http://www.w3.org/2000/svg', "polygon");
    this.svgshape.style.stroke = 'black';
  }
  Polygon.prototype.render = function(position) {
    if (position === void 0) {
      position = {
        x: 0,
        y: 0
      };
    }
    this.svgshape.style.fill = this.fill;
    var points = [];
    for (var lineIndex = 0; lineIndex < this.lines.length; lineIndex++) {
      var line = this.lines[lineIndex];
      points.push((line.x + 0.3 * line.z + position.x) + "," + (line.y + 0.3 * line.z + position.y));
    }
    this.svgshape.setAttribute("points", points.join(" "));
  };
  return Polygon;
}());
var PolygonSet = (function() {
  function PolygonSet(polygons, position) {
    if (polygons === void 0) {
      polygons = [];
    }
    if (position === void 0) {
      position = {
        x: 0,
        y: 0
      };
    }
    this.polygons = polygons;
    this.position = position;
  }
  PolygonSet.prototype.render = function(svg) {
    if (svg === void 0) {
      svg = null;
    }
    for (var pIndex = 0; pIndex < this.polygons.length; pIndex++) {
      var polygon = this.polygons[pIndex];
      polygon.render(this.position);
      if (svg != null) {
        svg.appendChild(polygon.svgshape);
      }
    }
  };
  return PolygonSet;
}());
//TEST
var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
svg.setAttribute("width", "200");
svg.setAttribute("height", "200");
svg.setAttribute("xmlns", 'http://www.w3.org/2000/svg');
var box = new PolygonSet([
  //Floor
  /* */
  new Polygon([{
      x: 0,
      y: 100,
      z: 100
    },
    {
      x: 100,
      y: 100,
      z: 100
    },
    {
      x: 100,
      y: 100,
      z: 0
    },
    {
      x: 0,
      y: 100,
      z: 0
    }
  ]),
  //Wall 1 - right
  /* */
  new Polygon([{
      x: 100,
      y: 0,
      z: 0
    },
    {
      x: 100,
      y: 100,
      z: 0
    },
    {
      x: 100,
      y: 100,
      z: 100
    },
    {
      x: 100,
      y: 0,
      z: 100
    },
  ]),
  //Wall 2
  /* */
  new Polygon([{
      x: 0,
      y: 0,
      z: 0
    },
    {
      x: 100,
      y: 0,
      z: 0
    },
    {
      x: 100,
      y: 100,
      z: 0
    },
    {
      x: 0,
      y: 100,
      z: 0
    },
  ]),
  //Wall 3 - left
  /* */
  new Polygon([{
      x: 0,
      y: 0,
      z: 0
    },
    {
      x: 0,
      y: 100,
      z: 0
    },
    {
      x: 0,
      y: 100,
      z: 100
    },
    {
      x: 0,
      y: 0,
      z: 100
    },
  ]),
  //Wall 4
  /* */
  new Polygon([{
      x: 0,
      y: 0,
      z: 100
    },
    {
      x: 100,
      y: 0,
      z: 100
    },
    {
      x: 100,
      y: 100,
      z: 100
    },
    {
      x: 0,
      y: 100,
      z: 100
    },
  ]),
  //Roof
  /* */
  new Polygon([{
      x: 0,
      y: 0,
      z: 0
    },
    {
      x: 100,
      y: 0,
      z: 0
    },
    {
      x: 100,
      y: 0,
      z: 100
    },
    {
      x: 0,
      y: 0,
      z: 100
    }
  ]),
], {
  x: 10,
  y: 10
});
box.render(svg);
document.body.appendChild(svg);
setInterval(function() {
  var polygon = box.polygons[Math.round((box.polygons.length - 1) * Math.random())];
  polygon.fill = "rgba(" + (Math.round(Math.random() * 255)) + "," + (Math.round(Math.random() * 255)) + "," + (Math.round(Math.random() * 255)) + ",0.5)";
  box.render();
}, 1000 / 4);```


问:
Double check my IF AND OR statement
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }
</code>```

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

答:
Not quite. You want to execute //.. do code as long as $dirchk1 exists, and otherwise execute the else if $dirchk2 exists, so:

```<code>if (is_file($dirchk1)) {
    //.. do code
} elseif (is_file($dirchk2)) {
    // only $dirchk2 exist
}
</code>```

Title: Double check my IF AND OR statement

Body:
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

Body:
Not quite. You want to execute //.. do code as long as $dirchk1 exists, and otherwise execute the else if $dirchk2 exists, so:

if (is_file($dirchk1)) {
    //.. do code
} elseif (is_file($dirchk2)) {
    // only $dirchk2 exist
}


问:
Behaviour on setting a pointer to a dangling pointer
I've come across some assertions that the behaviour on setting a pointer to something that isn't the address of a scalar or one past the address of a scalar is undefined (with similar restrictions for arrays).

So consider this:

```<code>int main()
{
    int* bar;
    {
        int foo = 1;
        int* b = &foo;
        bar = b;
    }
    int* copy = bar;
}
</code>```

Is the behaviour of int* copy = bar; defined? bar no longer points to a scalar as it's out of scope.

答:
The value of bar is indeterminate after the close bracket.

Quoting ISO/IEC 9899:2011, section 6.2.4 §2:

[…] The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.

The exact behavior of int* copy = bar; is ambiguous — see N1793 — Stability of indeterminate values in C11 provided by eugene-sh.

Body:
I've come across some assertions that the behaviour on setting a pointer to something that isn't the address of a scalar or one past the address of a scalar is undefined (with similar restrictions for arrays).

So consider this:

int main()
{
    int* bar;
    {
        int foo = 1;
        int* b = &foo;
        bar = b;
    }
    int* copy = bar;
}

Is the behaviour of int* copy = bar; defined? bar no longer points to a scalar as it's out of scope.


问:
Cannot access test resource from production class
I have the following class which I want to unit test:

```<code>class PropsProvider {

    String propsfileLocation;

    void init() {
        Path path = getPropsPath();
        loadPropertiesFromPath(path);
    }

    private Path getPropsPath() throws URISyntaxException {
        URI fileUri = new URI(propsfileLocation);
        return Paths.get(fileUri); // << failure here
    }

    // ...

}
</code>```

I am unit testing the above class and I keep getting a failure on the line Paths.get(fileUri). I get an IllegalArgumentException. I am passing in a relative path from my unit test, which is src/test/resources/app.properties. I believe this is happening because I haven't included the prefix file:. The unit test resides in the same package as the above class albeit in the /src/test/java folder. How can I fix this?

答:
You can get the path of any resource using Google's Guava library.

```<code>URL myFileLocation=Resources.getResource("myFile.txt");
</code>```

For more look here.
http://google.github.io/guava/releases/22.0/api/docs/com/google/common/io/Resources.html#getResource-java.lang.Class-java.lang.String-

Body:
I have the following class which I want to unit test:

class PropsProvider {

    String propsfileLocation;

    void init() {
        Path path = getPropsPath();
        loadPropertiesFromPath(path);
    }

    private Path getPropsPath() throws URISyntaxException {
        URI fileUri = new URI(propsfileLocation);
        return Paths.get(fileUri); // << failure here
    }

    // ...

}

I am unit testing the above class and I keep getting a failure on the line Paths.get(fileUri). I get an IllegalArgumentException. I am passing in a relative path from my unit test, which is src/test/resources/app.properties. I believe this is happening because I haven't included the prefix file:. The unit test resides in the same package as the above class albeit in the /src/test/java folder. How can I fix this?

Body:
You can get the path of any resource using Google's Guava library.

URL myFileLocation=Resources.getResource("myFile.txt");

For more look here.
http://google.github.io/guava/releases/22.0/api/docs/com/google/common/io/Resources.html#getResource-java.lang.Class-java.lang.String-


问:
Error while calling a class object from another object in Angular 4 Typescript component
Introduction to the problem
Here is my newcomp.component.ts file from Angular 4 project. I created the project using Angular CLI so it is well organized. My app name is cvfy. So the folder and file structure is as follows:
CVFY

-e2e (folder)

-node_modules (folder)

-server (folder)

-src (folder)

--environments (folder)

--assets (folder)

--app (folder)

---app.component.css (file)

---app.component.html (file)

---app.component.spec.ts (file)

---app.component.ts (file)

---app.module.ts (file)

---clientlogos.ts (file)

---imageclass.ts (file)

---clientscomp (folder)

----clientscomp.component.html (file)

----clientscomp.component.spec.ts (file)

----clientscomp.component.ts (file)

I have mentioned the important files and folders above for my problem
I am writing my code in clientscomp.component.ts file and using classes clientlogos.ts and imageclass.ts

clientscomp.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Clientlogos } from "./../clientlogos";
import { Imageclass } from "./../imageclass";

@Component({
  selector: 'app-clientscomp',
  templateUrl: './clientscomp.component.html',
  styleUrls: ['./clientscomp.component.css']
})

export class ClientscompComponent implements OnInit {

  private imageone: Imageclass[] = [
    {"_id":"1", "altClient":"Play Station", "srcClient":"https://cdn3.iconfinder.com/data/icons/flat-icons-web/40/PlayStation-128.png"},
    {"_id":"2", "altClient":"Twitter", "srcClient":"https://cdn1.iconfinder.com/data/icons/flat-and-simple-part-1/128/twitter-128.png"}
  ];

  private myrows: Clientlogos[] = [
    {
      "_id":"1",
      "imagenew": this.imageone
    }
  ];

  constructor() { }

  ngOnInit() {
  }

}
</code>```

clientlogos.ts

```<code>import { Imageclass } from "./imageclass";

export class Clientlogos {
    "_id":string;
    "imagenew":Imageclass[];
}
</code>```

imageclass.ts

```<code>export class Imageclass {
    "_id": string;
    "altClient": string;
    "srcClient": string;
}
</code>```

The error it shows on running the application is:

```<code>Failed to compile.

C:/Users/Dell/Desktop/Learning/cvfy/src/app/clientscomp/clientscomp.component.ts (40,7): Type '{ "_id": string; "imagenew": Imageclass[]; }[]' is not assignable to type 'Clientlogos[]'.
  Type '{ "_id": string; "imagenew": Imageclass[]; }' is not assignable to type 'Clientlogos'.
    Object literal may only specify known properties, and '"imagenew"' does not exist in type 'Clientlogos'.
</code>```

答:
You can use Array in you class, to make it more statically typed.

```<code>class Menu {
  name: string;
  categories: Array<Category>; // initialize it as applicable
}
class Category {
  name: string;
  dishes: Array<Dish>;// initialize it as applicable
}
class Dish {
  name: string;
}
</code>```

Component

You can try fill this.menus which will also be strongly typed Array // make sure the code is written to compile.

```<code>getMenus() {
    this.globals.getMenus().subscribe(
      data => {
        this.menus = new Array<Menu>();
        Object.keys(data).forEach(name => {
          //Initialize and push items as per data structure.
          this.menus.push(new Menu(data[name]));
        });

        console.log(this.menus);
      },
      err => { console.log(err) }
    );
  }
</code>```

template Arrange the following as a combination of Un-ordered and ordered list.

```<code><ul>
    <li *ngFor="let menu of menus">
        {{ menu.name }}
        <ul>
            <li *ngFor="let category of menu.categories">
                {{ category.name }}
                <ul>
                    <li *ngFor="let dish of category.dishes">
                        {{ dish.name }}
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>
</code>```

Body:
Introduction to the problem
Here is my newcomp.component.ts file from Angular 4 project. I created the project using Angular CLI so it is well organized. My app name is cvfy. So the folder and file structure is as follows:
CVFY

-e2e (folder)

-node_modules (folder)

-server (folder)

-src (folder)

--environments (folder)

--assets (folder)

--app (folder)

---app.component.css (file)

---app.component.html (file)

---app.component.spec.ts (file)

---app.component.ts (file)

---app.module.ts (file)

---clientlogos.ts (file)

---imageclass.ts (file)

---clientscomp (folder)

----clientscomp.component.html (file)

----clientscomp.component.spec.ts (file)

----clientscomp.component.ts (file)

I have mentioned the important files and folders above for my problem
I am writing my code in clientscomp.component.ts file and using classes clientlogos.ts and imageclass.ts

clientscomp.component.ts

import { Component, OnInit } from '@angular/core';
import { Clientlogos } from "./../clientlogos";
import { Imageclass } from "./../imageclass";

@Component({
  selector: 'app-clientscomp',
  templateUrl: './clientscomp.component.html',
  styleUrls: ['./clientscomp.component.css']
})

export class ClientscompComponent implements OnInit {

  private imageone: Imageclass[] = [
    {"_id":"1", "altClient":"Play Station", "srcClient":"https://cdn3.iconfinder.com/data/icons/flat-icons-web/40/PlayStation-128.png"},
    {"_id":"2", "altClient":"Twitter", "srcClient":"https://cdn1.iconfinder.com/data/icons/flat-and-simple-part-1/128/twitter-128.png"}
  ];

  private myrows: Clientlogos[] = [
    {
      "_id":"1",
      "imagenew": this.imageone
    }
  ];

  constructor() { }

  ngOnInit() {
  }

}

clientlogos.ts

import { Imageclass } from "./imageclass";

export class Clientlogos {
    "_id":string;
    "imagenew":Imageclass[];
}

imageclass.ts

export class Imageclass {
    "_id": string;
    "altClient": string;
    "srcClient": string;
}

The error it shows on running the application is:

Failed to compile.

C:/Users/Dell/Desktop/Learning/cvfy/src/app/clientscomp/clientscomp.component.ts (40,7): Type '{ "_id": string; "imagenew": Imageclass[]; }[]' is not assignable to type 'Clientlogos[]'.
  Type '{ "_id": string; "imagenew": Imageclass[]; }' is not assignable to type 'Clientlogos'.
    Object literal may only specify known properties, and '"imagenew"' does not exist in type 'Clientlogos'.

Body:
You can use Array in you class, to make it more statically typed.

class Menu {
  name: string;
  categories: Array<Category>; // initialize it as applicable
}
class Category {
  name: string;
  dishes: Array<Dish>;// initialize it as applicable
}
class Dish {
  name: string;
}

Component

You can try fill this.menus which will also be strongly typed Array // make sure the code is written to compile.

getMenus() {
    this.globals.getMenus().subscribe(
      data => {
        this.menus = new Array<Menu>();
        Object.keys(data).forEach(name => {
          //Initialize and push items as per data structure.
          this.menus.push(new Menu(data[name]));
        });

        console.log(this.menus);
      },
      err => { console.log(err) }
    );
  }

template Arrange the following as a combination of Un-ordered and ordered list.

<ul>
    <li *ngFor="let menu of menus">
        {{ menu.name }}
        <ul>
            <li *ngFor="let category of menu.categories">
                {{ category.name }}
                <ul>
                    <li *ngFor="let dish of category.dishes">
                        {{ dish.name }}
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>


问:
Xcode 9 : Module compiled with Swift 3.1 cannot be imported in Swift 4.0
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

```<code>@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0
</code>```

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !

答:
I have

```<code>pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'
</code>```

in my project and import FBSDKLoginKit, after cleaning the target i didn't have any issue

Since the pod you are using is in swift and is a beta pod, it is likely that you would have some issues with the swift 4 compiler, you should use the objective-c version of the pod for the time being

Body:
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !

Body:
I have

pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

in my project and import FBSDKLoginKit, after cleaning the target i didn't have any issue

Since the pod you are using is in swift and is a beta pod, it is likely that you would have some issues with the swift 4 compiler, you should use the objective-c version of the pod for the time being