问:
Combination of JavaFX User Interface and Client-Server-Application; Issue with connecting client to server along many other things

Problem: Client won't connect to Server anymore.

I need the different objects of the UI, that are initialized in the start-Method of my Application class in my main. How do I pass them to the main?

Complete Background:
My goal with this whole Application is to create a little game that multiple people can play. It will be really simple with a few buttons and Labels and in the end there should also be a way for the players to interact. I also want this game to be accessed via a server, with every player having an Account, consisting of username and Password.
As I am new to Java-Programming, I know that is - at the moment - completely out of my league. But I am trying little by little to learn everything I need in order to get there.

The important part:
I managed to connect server and client locally with the UI, but couldn't get my program to create Accounts, which should be stored in my "AccountDatabase". This resulted in no-one being able to successfully "log in" (log in is here simulated by displaying the message "log in succesfull!")
Tried to fix that, discovered I needed to use threads in order for multiple clients and rewrote my code almost completely. Now I can't even connect a client to the server...
I have tried so many things and rewrote so much of the code that I don't know what is going wrong anymore. I would be extremely grateful if someone here could take a look at my probably super messy code to see what I need to do here.

Code of my main class:

public class Main extends Application {

```<code>@Override
public void start(Stage primaryStage) {
    LoginUI loginUI = new LoginUI(primaryStage);
    loginUI.setScene(primaryStage, loginUI.getScene());
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
    InetAddress ip = null;
    try {
        ip = InetAddress.getByName("localhost");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    Client client = new Client(ip, 9376);
    loginUI.getSignUpUI().setSignUpButtonAction(client);
    //how do I get the instance of LoginUI instantiated in the start-Method?
}
</code>```

}

Expected result:
Client connects to Server, UI (LoginUI) shows up with a Hyperlink that redirects to (SignUpUI). This scene should let the user enter Username and Password, check "AccountDataBase" for already existing Accounts with that Username and finally create the Account if possible. Back in the (LoginUI) the user should also be able to enter Username and Password, which get compared to Account-Data in my "AccountDataBase" and let the User log in.

Actual Results:
Client won't connect to server after rewriting code to use threads. The farthest I've gotten is to establish a connection, but failing to creating new Accounts, as the user-inputted Account-Date were probably not stored in the AccountDataBase...

If you have made it this far, you'll probably need to see code of the others classes I've written. I just haven't posted them bc Stackoverflow told me not to post whole files... Feel free to let me know, if you need any more of the Code!

答:
like this  </p>

```<code>public class Main extends Application {
    LoginUI loginUI
@Override
public void start(Stage primaryStage) {
    loginUI = new LoginUI(primaryStage);
    loginUI.setScene(primaryStage, loginUI.getScene());
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
InetAddress ip = null;
try {
    ip = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
    e.printStackTrace();
}
Client client = new Client(ip, 9376);
loginUI.getSignUpUI().setSignUpButtonAction(client);
//how do I get the instance of LoginUI instantiated in the start-Method?
}
}
</code>```

Body:
Problem: Client won't connect to Server anymore.

I need the different objects of the UI, that are initialized in the start-Method of my Application class in my main. How do I pass them to the main?

Complete Background:
My goal with this whole Application is to create a little game that multiple people can play. It will be really simple with a few buttons and Labels and in the end there should also be a way for the players to interact. I also want this game to be accessed via a server, with every player having an Account, consisting of username and Password.
As I am new to Java-Programming, I know that is - at the moment - completely out of my league. But I am trying little by little to learn everything I need in order to get there.

The important part:
I managed to connect server and client locally with the UI, but couldn't get my program to create Accounts, which should be stored in my "AccountDatabase". This resulted in no-one being able to successfully "log in" (log in is here simulated by displaying the message "log in succesfull!")
Tried to fix that, discovered I needed to use threads in order for multiple clients and rewrote my code almost completely. Now I can't even connect a client to the server...
I have tried so many things and rewrote so much of the code that I don't know what is going wrong anymore. I would be extremely grateful if someone here could take a look at my probably super messy code to see what I need to do here.

Code of my main class:

public class Main extends Application {

@Override
public void start(Stage primaryStage) {
    LoginUI loginUI = new LoginUI(primaryStage);
    loginUI.setScene(primaryStage, loginUI.getScene());
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
    InetAddress ip = null;
    try {
        ip = InetAddress.getByName("localhost");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    Client client = new Client(ip, 9376);
    loginUI.getSignUpUI().setSignUpButtonAction(client);
    //how do I get the instance of LoginUI instantiated in the start-Method?
}

}

Expected result:
Client connects to Server, UI (LoginUI) shows up with a Hyperlink that redirects to (SignUpUI). This scene should let the user enter Username and Password, check "AccountDataBase" for already existing Accounts with that Username and finally create the Account if possible. Back in the (LoginUI) the user should also be able to enter Username and Password, which get compared to Account-Data in my "AccountDataBase" and let the User log in.

Actual Results:
Client won't connect to server after rewriting code to use threads. The farthest I've gotten is to establish a connection, but failing to creating new Accounts, as the user-inputted Account-Date were probably not stored in the AccountDataBase...

If you have made it this far, you'll probably need to see code of the others classes I've written. I just haven't posted them bc Stackoverflow told me not to post whole files... Feel free to let me know, if you need any more of the Code!

Body:
like this

public class Main extends Application {
    LoginUI loginUI
@Override
public void start(Stage primaryStage) {
    loginUI = new LoginUI(primaryStage);
    loginUI.setScene(primaryStage, loginUI.getScene());
    primaryStage.show();
}

public static void main(String[] args) {
    launch(args);
InetAddress ip = null;
try {
    ip = InetAddress.getByName("localhost");
} catch (UnknownHostException e) {
    e.printStackTrace();
}
Client client = new Client(ip, 9376);
loginUI.getSignUpUI().setSignUpButtonAction(client);
//how do I get the instance of LoginUI instantiated in the start-Method?
}
}


来源: stackexchange

问:
Identifying object fields with strings in Scala
In ES6 we can refer to a field of an object as:

```<code>seller['firstname']
</code>```

to represent

```<code>seller.firstname
</code>```

Is there a way to do the same in Scala? I mean, to use strings to refer to object fields?

答:
With Scala 2.13, you should be able to do something more or less related by using case classes' new productElementNames method which returns an iterator over its field names.

By zipping field names with field values obtained with productIterator we can access a case class field value by using the string version of the field name:

```<code>implicit class CaseClassExtensions(obj: Product) {

  def select[T](field: String): Option[T] =
    (obj.productElementNames zip obj.productIterator)
      .collectFirst { case (`field`, value) => value.asInstanceOf[T] }
}
</code>```

// case class Seller(firstName: String, lastName: String)
Seller("Hello", "World").select[String]("firstName")
// Option[String] = Some(Hello)
```

Here, the implicit class is used to enrich the Product type (which is case class inherited type) in order to call this select method on any case class.

But contrary to what you're used to in Javascript:

This is limited to case classes.

This returns an Option of the value (or you'd have to deal with exceptions when trying to get the value of a field which isn't defined).

You have to specify the return type of the associated value.

ContentLicense: CC BY-SA 4.0

Body:
In ES6 we can refer to a field of an object as:

seller['firstname']

to represent

seller.firstname

Is there a way to do the same in Scala? I mean, to use strings to refer to object fields?

Body:
With Scala 2.13, you should be able to do something more or less related by using case classes' new productElementNames method which returns an iterator over its field names.

By zipping field names with field values obtained with productIterator we can access a case class field value by using the string version of the field name:

implicit class CaseClassExtensions(obj: Product) {

  def select[T](field: String): Option[T] =
    (obj.productElementNames zip obj.productIterator)
      .collectFirst { case (`field`, value) => value.asInstanceOf[T] }
}

// case class Seller(firstName: String, lastName: String)
Seller("Hello", "World").select[String]("firstName")
// Option[String] = Some(Hello)

Here, the implicit class is used to enrich the Product type (which is case class inherited type) in order to call this select method on any case class.

But contrary to what you're used to in Javascript:

This is limited to case classes.

This returns an Option of the value (or you'd have to deal with exceptions when trying to get the value of a field which isn't defined).

You have to specify the return type of the associated value.


问:
How to only allow a popup message to occur on first visit with jQuery
I'm working to include a GDPR-style / Cookie notification for when users visit our site for the first time, but not again until they clear their cache. I have a notification set up to show when the window opens, and a close button to close it.

I've tried using localStorage and sessionStorage jquery, similar to those used to help other users, including hiding the popup first then checking in localStorage to see if it's there:

```<code> $(document).ready(function() {
        $('#toast').hide();
        var element= localStorage.getItem('status');
        if (element == null || element == '') {
            localStorage.setItem('element', 1);
            $('#toast').show();
        }});
</code>```

But 1) I don't want to copy pasta because 2) it doesn't work.

html for the popup here:

```<code><div id="toast" class="toast-close fixed-bottom" style="background-color: #DB7232; color: white; opacity: .7; margin: 0 0 2rem 2rem; padding: 1rem; width: 18rem;">
     <small>By continuing to browse this site, you're accepting the use of cookies.</small>
     <small><button type="button" data-dismiss="toast" class="close" aria-label="Close">&times</button></small>
</div>
</code>```

the jquery to close the popup here:

```<code>    $(document).on('click', '.toast-close', function() {
        $(this).fadeOut(function(){
           $(this).remove();
        });
    });
</code>```

I expect when a user comes to our site for the first time (or since we add this feature) the popup will occur; once they x out of either the popup or the browser, the notification will not occur again until their cache is cleared.

答:
The part that you believe you are missing I am unsure of.

Your general code flow:
1) Check for cookie/localstorage
2) Conditionally render popup
3) Set cookie/localstorage if user Consents

I see you have a .hide() before your cookie logic.   I'd keep that html fragment somewhere else (display:none?) unless you specifically need it.

It seems like you know how to display/fade it in if you need it.

Body:
I'm working to include a GDPR-style / Cookie notification for when users visit our site for the first time, but not again until they clear their cache. I have a notification set up to show when the window opens, and a close button to close it.

I've tried using localStorage and sessionStorage jquery, similar to those used to help other users, including hiding the popup first then checking in localStorage to see if it's there:

 $(document).ready(function() {
        $('#toast').hide();
        var element= localStorage.getItem('status');
        if (element == null || element == '') {
            localStorage.setItem('element', 1);
            $('#toast').show();
        }});

But 1) I don't want to copy pasta because 2) it doesn't work.

html for the popup here:

     By continuing to browse this site, you're accepting the use of cookies.
     <button type="button" data-dismiss="toast" class="close" aria-label="Close">&times</button>

the jquery to close the popup here:

    $(document).on('click', '.toast-close', function() {
        $(this).fadeOut(function(){
           $(this).remove();
        });
    });

I expect when a user comes to our site for the first time (or since we add this feature) the popup will occur; once they x out of either the popup or the browser, the notification will not occur again until their cache is cleared.


问:
How to process css with postcss inside sapper-template with rollup
Having trouble using rollup-plugin-postcss with sapper-template:

npx degit sveltejs/sapper-template#rollup my-app

npm install rollup-plugin-postcss --save-dev

install various postcss plugin

create src/css/main.css

add import './css/main.css'; to the top line of src/client.js

*edit rollup.config.js

*add postcss.config.js

*going wrong here? I have tried several variations.

```<code>// rollup.config.js
...
import postcss from 'rollup-plugin-postcss'
...

export default {
    client: {
        input: config.client.input(),
        output: config.client.output(),
        plugins: [
            replace({
                'process.browser': true,
                'process.env.NODE_ENV': JSON.stringify(mode)
            }),
            svelte({
                dev,
                hydratable: true,
                emitCss: true
            }),
            resolve(),
            commonjs(),
            postcss({
                // extract: true,
                // sourceMap: true,
                plugins: [require('autoprefixer')]
            }),
...
</code>```

```<code>// postcss.config.js
module.exports = {
  plugins: {
    ...
    autoprefixer: {}
  }
};
</code>```

No real error message, once I add postcss to the plugins in the client:{} of rollup.config.js - css breaks on the site.

答:
This is a matter of simply putting the svelte plugin config together properly. I would recommend you use svelte-preprocess and setup your rollup.config.js as follows:

```<code>import autoPreprocess from 'svelte-preprocess';

const preprocessOptions = {
    postcss: {
        plugins: [
            require('postcss-import'),
            require('postcss-preset-env')({
                stage: 0,
                browsers: 'last 2 versions',
                autoprefixer: { grid: true }
            }),
            ...
        ]
      }
};

...
export default {
    client: {
        plugins: [
            svelte({
                preprocess: autoPreprocess(preprocessOptions),
                dev,
                hydratable: true,
                emitCss: true
            }),
            ...
</code>```

As you see here, you need to set the preprocess option of the svelte plugin.

Body:
Having trouble using rollup-plugin-postcss with sapper-template:

npx degit sveltejs/sapper-template#rollup my-app

npm install rollup-plugin-postcss --save-dev

install various postcss plugin

create src/css/main.css

add import './css/main.css'; to the top line of src/client.js

*edit rollup.config.js

*add postcss.config.js

*going wrong here? I have tried several variations.

// rollup.config.js
...
import postcss from 'rollup-plugin-postcss'
...

export default {
    client: {
        input: config.client.input(),
        output: config.client.output(),
        plugins: [
            replace({
                'process.browser': true,
                'process.env.NODE_ENV': JSON.stringify(mode)
            }),
            svelte({
                dev,
                hydratable: true,
                emitCss: true
            }),
            resolve(),
            commonjs(),
            postcss({
                // extract: true,
                // sourceMap: true,
                plugins: [require('autoprefixer')]
            }),
...

// postcss.config.js
module.exports = {
  plugins: {
    ...
    autoprefixer: {}
  }
};

No real error message, once I add postcss to the plugins in the client:{} of rollup.config.js - css breaks on the site.

Body:
This is a matter of simply putting the svelte plugin config together properly. I would recommend you use svelte-preprocess and setup your rollup.config.js as follows:

import autoPreprocess from 'svelte-preprocess';

const preprocessOptions = {
    postcss: {
        plugins: [
            require('postcss-import'),
            require('postcss-preset-env')({
                stage: 0,
                browsers: 'last 2 versions',
                autoprefixer: { grid: true }
            }),
            ...
        ]
      }
};

...
export default {
    client: {
        plugins: [
            svelte({
                preprocess: autoPreprocess(preprocessOptions),
                dev,
                hydratable: true,
                emitCss: true
            }),
            ...

As you see here, you need to set the preprocess option of the svelte plugin.


问:
LiteDB - Selecting multiple entries with one id
Okay, apologies if the title is misleading, I couldn't find the right wording for it.

So I have a collection from which I want to count all entries with UserId where the StatusId is a value.

I'm looking for something similar/the same as the SQL query below.
SELECT COUNT(*) FROM Warns WHERE UserId = uId AND StatusId = sId;

Does something like that exist for LiteDB?

答:
You can use the Count method directly:

```<code>var count = collection.Count(Query.EQ("Field", "Value"));
</code>```

Or use the standard collection methods:

```<code>var count = query.Run(...).LongCount();
</code>```

Body:
You can use the Count method directly:

var count = collection.Count(Query.EQ("Field", "Value"));

Or use the standard collection methods:

var count = query.Run(...).LongCount();


问:
Does GIL implementation became worse since Python3.2?
I have read great presentation about GIL:
http://www.dabeaz.com/python/UnderstandingGIL.pdf

And here Dave said, that since Python3.2 we have new and better version of GIL, and provide examples, that prove it (on slide 54).

But when I test them on my own on Python 3.4, the performance seems to be worse:

```<code>from threading import Thread

def count(n):
  while n > 0:
    n -= 1

def sequential_test():
  count(100000000)
  count(100000000)

def threaded_test():
  t1 = Thread(target=count,args=(100000000,))
  t1.start()
  t2 = Thread(target=count,args=(100000000,))
  t2.start()
  t1.join()
  t2.join()
</code>```

So on my Linux dual core laptop
in Python 2.7 I get:

```<code>sequential_test: 11s
threaded_test: 17s
</code>```

in Python 3.4 I get:

```<code>sequential_test: 18s
threaded_test: 28s
</code>```

So the question is why in Python 3.4 in both cases code works slower and why I do not see any improvement in GIL on two CPU-bound processes compare to Python2?

May be I do something wrong?

My guess is that in Python2 there is some C-code optimisation of such kind of code and that's why it works faster, but I have no proff of it

答:
I tested this loop:

```<code>    for (i=0; i<loops; i++)
    {
        Py_BEGIN_ALLOW_THREADS
        Py_END_ALLOW_THREADS
    }
</code>```

With loops set to 10,000,000 on Centos 7, i7-2600

Python 2.7
real    0m0.199s
user    0m0.109s
sys     0m0.011s

Python 3.7
real    0m0.912s
user    0m0.791s
sys     0m0.009s

2.7 is nearly 8x faster (CPU time)

ContentLicense: CC BY-SA 3.0

Body:
I have read great presentation about GIL:
http://www.dabeaz.com/python/UnderstandingGIL.pdf

And here Dave said, that since Python3.2 we have new and better version of GIL, and provide examples, that prove it (on slide 54).

But when I test them on my own on Python 3.4, the performance seems to be worse:

from threading import Thread

def count(n):
  while n > 0:
    n -= 1

def sequential_test():
  count(100000000)
  count(100000000)

def threaded_test():
  t1 = Thread(target=count,args=(100000000,))
  t1.start()
  t2 = Thread(target=count,args=(100000000,))
  t2.start()
  t1.join()
  t2.join()

So on my Linux dual core laptop
in Python 2.7 I get:

sequential_test: 11s
threaded_test: 17s

in Python 3.4 I get:

sequential_test: 18s
threaded_test: 28s

So the question is why in Python 3.4 in both cases code works slower and why I do not see any improvement in GIL on two CPU-bound processes compare to Python2?

May be I do something wrong?

My guess is that in Python2 there is some C-code optimisation of such kind of code and that's why it works faster, but I have no proff of it

Body:
I tested this loop:

    for (i=0; i<loops; i++)
    {
        Py_BEGIN_ALLOW_THREADS
        Py_END_ALLOW_THREADS
    }

With loops set to 10,000,000 on Centos 7, i7-2600

Python 2.7
real    0m0.199s
user    0m0.109s
sys     0m0.011s

Python 3.7
real    0m0.912s
user    0m0.791s
sys     0m0.009s

2.7 is nearly 8x faster (CPU time)


问:
Is there way with a SAS data step to add a record count column the increases when a variable changes?
I have a table which has dates in it and the member changes over time. I want to know when the member started and ended. If the member starts and ends and then restarts that needs to be a different indicator.

Sample of what I have (sorry I don't know how to make a table here):

```<code>member  yyyymm
Jim  201603
Jim  201606
Jim  201609
Bob  201709
Bob  201712
Jim  201806
Jef  201806
Jef  201809
</code>```

I tried a proc sql statement which finds min and max date but then the max date is wrong if the member restarts (code A below). I also tried a data step and that said it wasn't properly sorted (code B below)

code A

```<code>proc sql;
create table tst as
select
member,
max(yyyymm) as effective_until,
min(yyyymm) as effective_from
from tbl
group by 1,2;
quit;
</code>```

code B

```<code>data tst;
count + 1;
by member;
if first.member then count = 1;
run;
</code>```

What I'm hoping for:

```<code>member  yyyymm  id
Jim  201603  1
Jim  201606  1
Jim  201609  1
Bob  201709  2
Bob  201712  2
Jim  201803  3
Jef  201806  4
Jef  201809  4
</code>```

答:
```<code>proc sort data=have;
  by yyyymm member;

data want;
  set have;
  by yyyymm member;
if first.member then id+1;
run;
</code>```

Body:
I have a table which has dates in it and the member changes over time. I want to know when the member started and ended. If the member starts and ends and then restarts that needs to be a different indicator.

Sample of what I have (sorry I don't know how to make a table here):

member  yyyymm
Jim  201603
Jim  201606
Jim  201609
Bob  201709
Bob  201712
Jim  201806
Jef  201806
Jef  201809

I tried a proc sql statement which finds min and max date but then the max date is wrong if the member restarts (code A below). I also tried a data step and that said it wasn't properly sorted (code B below)

code A

proc sql;
create table tst as
select
member,
max(yyyymm) as effective_until,
min(yyyymm) as effective_from
from tbl
group by 1,2;
quit;

code B

data tst;
count + 1;
by member;
if first.member then count = 1;
run;

What I'm hoping for:

member  yyyymm  id
Jim  201603  1
Jim  201606  1
Jim  201609  1
Bob  201709  2
Bob  201712  2
Jim  201803  3
Jef  201806  4
Jef  201809  4


问:
Control UIView on Load
Hi everybody I am trying to make an app with a login page and profile page.

So i am using two view for them : login_view and profile_view

So login_view is my view in nib file i.e default view.

but i want to check if the user has already signed in before in viewdidLoad method like session and show him profile_view instead when app starts.

Can Anybody help me in it?

I tried this but failed

```<code>NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        if ([array count] == 0)
        {
            NSNumber * uud = [array objectAtIndex:0];
            [self.view = home];

        }
</code>```

答:
Might want to use a keychain. If not, you could run the risk of having unauthorized access. Lot's of other reasons too.
This sample app by Apple should help you:

http://developer.apple.com/library/ios/#samplecode/GenericKeychain/Introduction/Intro.html

Title: Control UIView on Load

Body:
Hi everybody I am trying to make an app with a login page and profile page.

So i am using two view for them : login_view and profile_view

So login_view is my view in nib file i.e default view.

but i want to check if the user has already signed in before in viewdidLoad method like session and show him profile_view instead when app starts.

Can Anybody help me in it?

I tried this but failed

NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        if ([array count] == 0)
        {
            NSNumber * uud = [array objectAtIndex:0];
            [self.view = home];

        }


问:
Hover function does not work in CSS Side Bar
I have written code for an HTML/CSS website sidebar, and I want to make sure that when a user hovers over an element in the sidebar, its background gets highlighted.

It just displays my normal list and the hover function does not work. What is the problem?

body {
  margin: 0;
}

.sidebar {
  float: right;
  background-color: #F4ECFC;
  /* Sidebar Background */
  width: 200px;
  /* Width of side bar */
  height: 900px;
  padding-top: 0px;
  /* Padding above the header */
  font-family: helvetica;
  /* Font for the sidebar */
}

.sidebar a {
  text-decoration: none;
  /* Removes the underline from links. */
  color: #0B0036;
  /* Text color of the menu items */
}

.sidebar ul {
  line-height: 40px;
  overflow: hidden;
  margin-left: 0;
  padding-left: 0;
}

.sidebar ul li .listItemA {
  /* list-style-type: none; */
  background-color: #F4ECFC;
  /* Background colour of the menu items. */
}

.sidebar ul li .listItemA a:hover {
  background-color: purple;
}

.listItemA {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <ul>
    <li class="listItemA">Class1</li>

    <li class="listItemA">Class2</li>

    <li class="listItemA">Class3</li>

    <li class="listItemA">Class4</li>

    <li class="listItemA">Class5</li>
  </ul>
</div></code>```

答:
One thing you want to do first is give your links display: block; which makes them take up 100% of the width available.

Then simplify the style of the link and the relative hover like so:

```<code>.sidebar ul .listItemA {
  /* list-style-type: none; */
  background-color: #F4ECFC;
  /* Background colour of the menu items. */
}

.sidebar ul .listItemA:hover a {
  background-color: purple;
}
</code>```

As pointed out in a comment on your question you had a space between li and .listItemA, I just removed li to achieve the correct selector but you could've also changed that part of the selector to li.listItemA.

Really important change here is to style the link on hover of the list item:

```<code>.sidebar ul .listItemA:hover a { ... }
</code>```

This tells the browser to change the background of the link when the list item is hovered.

body {
  margin: 0;
}

.sidebar {
  float: right;
  background-color: #F4ECFC;
  /* Sidebar Background */
  width: 200px;
  /* Width of side bar */
  height: 900px;
  padding-top: 0px;
  /* Padding above the header */
  font-family: helvetica;
  /* Font for the sidebar */
}

.sidebar a {
  display: block;
  text-decoration: none;
  /* Removes the underline from links. */
  color: #0B0036;
  /* Text color of the menu items */
}

.sidebar ul {
  line-height: 40px;
  overflow: hidden;
  margin-left: 0;
  padding-left: 0;
}

.sidebar ul .listItemA {
  /* list-style-type: none; */
  background-color: #F4ECFC;
  /* Background colour of the menu items. */
}

.sidebar ul .listItemA:hover a {
  background-color: purple;
}

.listItemA {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sidebar">
  <ul>
    <li class="listItemA">Class1</li>

    <li class="listItemA">Class2</li>

    <li class="listItemA">Class3</li>

    <li class="listItemA">Class4</li>

    <li class="listItemA">Class5</li>
  </ul>
</div></code>```

Body:
I have written code for an HTML/CSS website sidebar, and I want to make sure that when a user hovers over an element in the sidebar, its background gets highlighted.

It just displays my normal list and the hover function does not work. What is the problem?

body {
  margin: 0;
}

.sidebar {
  float: right;
  background-color: #F4ECFC;
  /* Sidebar Background */
  width: 200px;
  /* Width of side bar */
  height: 900px;
  padding-top: 0px;
  /* Padding above the header */
  font-family: helvetica;
  /* Font for the sidebar */
}

.sidebar a {
  text-decoration: none;
  /* Removes the underline from links. */
  color: #0B0036;
  /* Text color of the menu items */
}

.sidebar ul {
  line-height: 40px;
  overflow: hidden;
  margin-left: 0;
  padding-left: 0;
}

.sidebar ul li .listItemA {
  /* list-style-type: none; */
  background-color: #F4ECFC;
  /* Background colour of the menu items. */
}

.sidebar ul li .listItemA a:hover {
  background-color: purple;
}

.listItemA {
  text-align: center;
}

Class1

Class2

Class3

Class4

Class5

Body:
One thing you want to do first is give your links display: block; which makes them take up 100% of the width available.

Then simplify the style of the link and the relative hover like so:

.sidebar ul .listItemA {
  /* list-style-type: none; */
  background-color: #F4ECFC;
  /* Background colour of the menu items. */
}

.sidebar ul .listItemA:hover a {
  background-color: purple;
}

As pointed out in a comment on your question you had a space between li and .listItemA, I just removed li to achieve the correct selector but you could've also changed that part of the selector to li.listItemA.

Really important change here is to style the link on hover of the list item:

.sidebar ul .listItemA:hover a { ... }

This tells the browser to change the background of the link when the list item is hovered.

body {
  margin: 0;
}

.sidebar {
  float: right;
  background-color: #F4ECFC;
  /* Sidebar Background */
  width: 200px;
  /* Width of side bar */
  height: 900px;
  padding-top: 0px;
  /* Padding above the header */
  font-family: helvetica;
  /* Font for the sidebar */
}

.sidebar a {
  display: block;
  text-decoration: none;
  /* Removes the underline from links. */
  color: #0B0036;
  /* Text color of the menu items */
}

.sidebar ul {
  line-height: 40px;
  overflow: hidden;
  margin-left: 0;
  padding-left: 0;
}

.sidebar ul .listItemA {
  /* list-style-type: none; */
  background-color: #F4ECFC;
  /* Background colour of the menu items. */
}

.sidebar ul .listItemA:hover a {
  background-color: purple;
}

.listItemA {
  text-align: center;
}

<div class="sidebar">
  <ul>
    <li class="listItemA"><a href="#">Class1</a></li>

    <li class="listItemA"><a href="#">Class2</a></li>

    <li class="listItemA"><a href="#">Class3</a></li>

    <li class="listItemA"><a href="#">Class4</a></li>

    <li class="listItemA"><a href="#">Class5</a></li>
  </ul>
</div>


问:
How to decrypt a shifted message with XOR?
I have a message m that I encrypt by the code

```<code>c = m xor [m<<6] xor [m<<10]
</code>```

(m<<x means that I shift it by x bits - eg 1001<<2 = 0100)

I need to decrypt this message.

I have tried code like:

```<code>c xor [c<<6] xor [c<<10]
</code>```

OR

```<code>c xor [c>>6] xor [c>>10]
</code>```

but none of them worked.

答:
The function c = m xor [m<<6] xor [m<<10] is a bijection (i.e. reversible on a given modulo 2n). So you're good to go...

Just piece-wise de-XOR the value by 6 and 10 bits, starting from the lowest bits.

```<code>int main() {
    uint32_t n = 0xfffffff;
    for (uint32_t m = 0; m < n; ++m) {

        uint32_t c = m ^ (m << 6) ^ (m << 10); // c = encrypted value

        uint32_t x = c;
        x ^= ((x &       0x3F) << 6);
        x ^= ((x &      0x3FF) << 10);
        x ^= ((x &      0xFC0) << 6);
        x ^= ((x &    0x3F000) << 6);
        x ^= ((x &    0xFFC00) << 10);
        x ^= ((x &   0xFC0000) << 6);
        x ^= ((x & 0x3F000000) << 6);
        x ^= ((x & 0x3FF00000) << 10);

        if (m != x) {
            printf("Mismatch: %X > %X > %X\n", m, c, x); // should never happen
            break;
        }
    }
}
</code>```

Body:
I have a message m that I encrypt by the code

c = m xor [m<<6] xor [m<<10]

(m<<x means that I shift it by x bits - eg 1001<<2 = 0100)

I need to decrypt this message.

I have tried code like:

c xor [c<<6] xor [c<<10]

OR

c xor [c>>6] xor [c>>10]

but none of them worked.

Body:
The function c = m xor [m<<6] xor [m<<10] is a bijection (i.e. reversible on a given modulo 2n). So you're good to go...

Just piece-wise de-XOR the value by 6 and 10 bits, starting from the lowest bits.

int main() {
    uint32_t n = 0xfffffff;
    for (uint32_t m = 0; m < n; ++m) {

        uint32_t c = m ^ (m << 6) ^ (m << 10); // c = encrypted value

        uint32_t x = c;
        x ^= ((x &       0x3F) << 6);
        x ^= ((x &      0x3FF) << 10);
        x ^= ((x &      0xFC0) << 6);
        x ^= ((x &    0x3F000) << 6);
        x ^= ((x &    0xFFC00) << 10);
        x ^= ((x &   0xFC0000) << 6);
        x ^= ((x & 0x3F000000) << 6);
        x ^= ((x & 0x3FF00000) << 10);

        if (m != x) {
            printf("Mismatch: %X > %X > %X\n", m, c, x); // should never happen
            break;
        }
    }
}


问:
Integer taking a random value after a function call that doesn't even edit it
I'm executing a program from command line, it takes string integer string string parameters, I call a function that reads the following file:

sólo te lo diré mañana al mediodía en la biblioteca

It reads the file and prints what it is supposed to print but when it goes back to the main function the value NumHijos takes a random value, why does it happen? I am not even using it in any function

Main program, let's say we have this command line ./program -d 4 File1 File2

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include "file.h"

int main(int argc, char *argv[]) {
    /*command line args*/
    int NumHijos;
    int op = 0;

    size_t len = strlen(argv[1]);
    char * operacion = malloc(len+2);
    strcpy(operacion, argv[1]);

    NumHijos = atoi(argv[2]);

    len = strlen(argv[3]);
    char * file1 = malloc(len+5);
    strcpy(file1, argv[3]);
    strcat(file1,".txt");

    len = strlen(argv[4]);
    char * file2 = malloc(len+5);
    strcpy(file2, argv[4]);

    char vector [NumHijos];

    printf("Arg 1: %s\n",operacion);
    printf("Arg 2: %d\n",NumHijos);
    printf("Arg 3: %s\n", file1);
    printf("Arg 4: %s\n\n", file2);

    abrirArchivoEntrada(file1, vector, NumHijos);

    int i = 1;

    if (operacion[1] == 'd'){
        printf("decypher\n");
    }

    else if (operacion[1] == 'c'){
        printf("crypt\n");
    }
    return 0;
    printf("times %d", NumHijos);

}
</code>```

file.h

```<code>void llenarVector(FILE *e, char texto [], int n) {
    int l;
    while (!feof(e)){
        fgets(texto, 1000, e);
    }

    l = strlen(texto);
    printf("%s\n", texto);
    printf("%d\n", l);

 fclose(e);
}

void abrirArchivoEntrada (char * nombre, char texto[], int n){
    FILE *e;
    e = fopen(nombre, "r");
            if (e == NULL)

            {
                printf("error\n");
            }
            else {
                printf("loaded successfully\n");
                llenarVector(e,texto,n);
            }
}
</code>```

答:
```<code>len = strlen(argv[3]);
char * file1 = malloc(len+3);
strcpy(file1, argv[3]);
strcat(file1,".txt");
</code>```

Is undefined behavior. ".txt" needs 4 more characters, so you need to allocate strlen(argv[3]) + 5 bytes for file1 pointer.

while (!feof(e)) is always wrong.

fgets(texto, 1000, e); (most probably) is way into undefined behavior. The texto pointer points to char vector[NumHijos];. The variable is initialized with NumHijos = atoi(argv[2]);, where argv[2] is passed 2. So vector is a variable length array with only 2 bytes. Yet you try to write 1000 bytes into the vector with fgets call - this most probably accesses the pointer out of bounds and undefined behavior happens.

Once undefined behavior happens, you can't have any expectations as to what the program will produce. Probably the fgets function overwrites the memory behind NumHijos variable. Or strcat overwrites it. Debug the program to find out. How to debug small programs.

i don't know how many characters the var "texto" could have, is there any way I can reprogram this so I don't have to put that 1000?

Yes. Use getline if you have it, if not rewrite it on your own. Writing a function that reads a file char by char, reallocates some destination pointer and stores read character into that pointer looks like a good C training. Anyway, here's the libcs50 library with it's get_string() function which may serve as a good reference how to implement such function.

Body:
I'm executing a program from command line, it takes string integer string string parameters, I call a function that reads the following file:

sólo te lo diré mañana al mediodía en la biblioteca

It reads the file and prints what it is supposed to print but when it goes back to the main function the value NumHijos takes a random value, why does it happen? I am not even using it in any function

Main program, let's say we have this command line ./program -d 4 File1 File2

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include "file.h"

int main(int argc, char *argv[]) {
    /*command line args*/
    int NumHijos;
    int op = 0;

    size_t len = strlen(argv[1]);
    char * operacion = malloc(len+2);
    strcpy(operacion, argv[1]);

    NumHijos = atoi(argv[2]);

    len = strlen(argv[3]);
    char * file1 = malloc(len+5);
    strcpy(file1, argv[3]);
    strcat(file1,".txt");

    len = strlen(argv[4]);
    char * file2 = malloc(len+5);
    strcpy(file2, argv[4]);

    char vector [NumHijos];

    printf("Arg 1: %s\n",operacion);
    printf("Arg 2: %d\n",NumHijos);
    printf("Arg 3: %s\n", file1);
    printf("Arg 4: %s\n\n", file2);

    abrirArchivoEntrada(file1, vector, NumHijos);

    int i = 1;

    if (operacion[1] == 'd'){
        printf("decypher\n");
    }

    else if (operacion[1] == 'c'){
        printf("crypt\n");
    }
    return 0;
    printf("times %d", NumHijos);

}

file.h

void llenarVector(FILE *e, char texto [], int n) {
    int l;
    while (!feof(e)){
        fgets(texto, 1000, e);
    }

    l = strlen(texto);
    printf("%s\n", texto);
    printf("%d\n", l);

 fclose(e);
}

void abrirArchivoEntrada (char * nombre, char texto[], int n){
    FILE *e;
    e = fopen(nombre, "r");
            if (e == NULL)

            {
                printf("error\n");
            }
            else {
                printf("loaded successfully\n");
                llenarVector(e,texto,n);
            }
}

Body:
len = strlen(argv[3]);
char * file1 = malloc(len+3);
strcpy(file1, argv[3]);
strcat(file1,".txt");

Is undefined behavior. ".txt" needs 4 more characters, so you need to allocate strlen(argv[3]) + 5 bytes for file1 pointer.

while (!feof(e)) is always wrong.

fgets(texto, 1000, e); (most probably) is way into undefined behavior. The texto pointer points to char vector[NumHijos];. The variable is initialized with NumHijos = atoi(argv[2]);, where argv[2] is passed 2. So vector is a variable length array with only 2 bytes. Yet you try to write 1000 bytes into the vector with fgets call - this most probably accesses the pointer out of bounds and undefined behavior happens.

Once undefined behavior happens, you can't have any expectations as to what the program will produce. Probably the fgets function overwrites the memory behind NumHijos variable. Or strcat overwrites it. Debug the program to find out. How to debug small programs.

i don't know how many characters the var "texto" could have, is there any way I can reprogram this so I don't have to put that 1000?

Yes. Use getline if you have it, if not rewrite it on your own. Writing a function that reads a file char by char, reallocates some destination pointer and stores read character into that pointer looks like a good C training. Anyway, here's the libcs50 library with it's get_string() function which may serve as a good reference how to implement such function.


问:
MSBuildExtensionsPath on VSTS and WIX
I have a Visual Studio solution that we have been building with VS 2015 using the Visual Studio Online Build.  We want to convert the build to VS 2017.  It builds locally for me with no error.  However, when building online using the "VS2017 Hosted" build agent it fails with the following error when trying to build my WIX based MSI:

```<code>DEV\Setup\UISetup\UISetup.wixproj(56,3): Error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\WiX\v3.x\Wix.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
</code>```

Troubleshooting, the wixproj does have an import statement for this path:

```<code>$(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.targets
</code>```

I put some extra steps in the build and found the following as a comparison of the two build agents:

"Hosted" (build works on this VS 2015 build agent)

```<code> wix.targets Is Here:     C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\wix.targets

 With Diagnostic output on MSBuild, here are the MSBuild property settings
 2017-08-19T19:12:13.3864207Z MSBuildExtensionsPath   = C:\Program Files (x86)\MSBuild
 2017-08-19T19:12:13.3864207Z MSBuildExtensionsPath32 = C:\Program Files (x86)\MSBuild
 2017-08-19T19:12:13.3864207Z MSBuildExtensionsPath64 = C:\Program Files\MSBuild
</code>```

Hosted VS2017 (same build fails on this build agent)

```<code> Looking here for wix.targets:     C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\WiX\v3.x\Wix.targets <-- which errors

 But wix.targets is here:          C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\wix.targets <-- same as “Hosted” build agent

 With Diagnostic output on MSBuild, here are the MSBuild property settings
 2017-08-19T19:21:06.5320962Z MSBuildExtensionsPath   = C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild <-- Different on this build agent
 2017-08-19T19:21:06.5320962Z MSBuildExtensionsPath32 = C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild <-- Different on this build agent
 2017-08-19T19:21:06.5320962Z MSBuildExtensionsPath64 = C:\Program Files\MSBuild
</code>```

I have opened a ticket with Microsoft support, but so far, they have been no help.  The real issue is that MSBuildExtensionsPath32 is pointing to a different folder on the "VS2017 Hosted" build agent, but the wix.targets file is in the original folder.  I would hate to hard code the path to wix.targets, but I really don't see an alternative.

Any ideas?

Thanks.

答:
We are using Azure DevOps 2019 on-prem and received the same error. In the Build Pipeline, we were using an MSBuild Task with MSBuild Version = MSBuild 16.0 to to build the solution (which included the WIX project).

We switched the MSBuild Version = MSBuild 14.0, and the error went away. It is a somewhat temporary fix until we require a more recent MSBuild verion, but is suffices for now.

Title: MSBuildExtensionsPath on VSTS and WIX

Body:
I have a Visual Studio solution that we have been building with VS 2015 using the Visual Studio Online Build.  We want to convert the build to VS 2017.  It builds locally for me with no error.  However, when building online using the "VS2017 Hosted" build agent it fails with the following error when trying to build my WIX based MSI:

DEV\Setup\UISetup\UISetup.wixproj(56,3): Error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\WiX\v3.x\Wix.targets" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.

Troubleshooting, the wixproj does have an import statement for this path:

$(MSBuildExtensionsPath)\Microsoft\WiX\v3.x\Wix.targets

I put some extra steps in the build and found the following as a comparison of the two build agents:

"Hosted" (build works on this VS 2015 build agent)

 wix.targets Is Here:     C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\wix.targets

 With Diagnostic output on MSBuild, here are the MSBuild property settings
 2017-08-19T19:12:13.3864207Z MSBuildExtensionsPath   = C:\Program Files (x86)\MSBuild
 2017-08-19T19:12:13.3864207Z MSBuildExtensionsPath32 = C:\Program Files (x86)\MSBuild
 2017-08-19T19:12:13.3864207Z MSBuildExtensionsPath64 = C:\Program Files\MSBuild

Hosted VS2017 (same build fails on this build agent)

 Looking here for wix.targets:     C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\WiX\v3.x\Wix.targets <-- which errors

 But wix.targets is here:          C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\wix.targets <-- same as “Hosted” build agent

 With Diagnostic output on MSBuild, here are the MSBuild property settings
 2017-08-19T19:21:06.5320962Z MSBuildExtensionsPath   = C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild <-- Different on this build agent
 2017-08-19T19:21:06.5320962Z MSBuildExtensionsPath32 = C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild <-- Different on this build agent
 2017-08-19T19:21:06.5320962Z MSBuildExtensionsPath64 = C:\Program Files\MSBuild

I have opened a ticket with Microsoft support, but so far, they have been no help.  The real issue is that MSBuildExtensionsPath32 is pointing to a different folder on the "VS2017 Hosted" build agent, but the wix.targets file is in the original folder.  I would hate to hard code the path to wix.targets, but I really don't see an alternative.

Any ideas?

Thanks.


问:
Compare date stored as an integer with a datetime
I have a column having datatype integer which is in the format yyyymm (e.g. 201905). I want to check if this column is in between start and end date i.e.:

```<code>case
  when [cov_yyyymm] between [start_dt] and [end_dt] then 'Period1'
  else 'OtherPeriod'
end
</code>```

note: start and end dates are datetime

I have tried converting the Int to datetime/date. similarly vice versa from date to int and still could not get it to work.

I expect to use a CASE statement to compare if the Integer is in between 2 dates.

答:
Your period is in yyyymm format, so next statement is another possible approach. This approach is useful when period and dates are from one month - like period 201905 and dates 2019-05-03 and 2019-05-20. Adding a day (first or last day of month) to an integer period (yyymm) and comparing with datetime values is not always correct.

```<code>case
  when [cov_yyyymm] between
      (YEAR([start_dt])*100 + MONTH([start_dt])) and
      (YEAR([end_dt])*100 + MONTH([end_dt])) then 'Period1'
  else 'OtherPeriod'
end
</code>```

Body:
I have a column having datatype integer which is in the format yyyymm (e.g. 201905). I want to check if this column is in between start and end date i.e.:

case
  when [cov_yyyymm] between [start_dt] and [end_dt] then 'Period1'
  else 'OtherPeriod'
end

note: start and end dates are datetime

I have tried converting the Int to datetime/date. similarly vice versa from date to int and still could not get it to work.

I expect to use a CASE statement to compare if the Integer is in between 2 dates.

Body:
Your period is in yyyymm format, so next statement is another possible approach. This approach is useful when period and dates are from one month - like period 201905 and dates 2019-05-03 and 2019-05-20. Adding a day (first or last day of month) to an integer period (yyymm) and comparing with datetime values is not always correct.

case
  when [cov_yyyymm] between
      (YEAR([start_dt])*100 + MONTH([start_dt])) and
      (YEAR([end_dt])*100 + MONTH([end_dt])) then 'Period1'
  else 'OtherPeriod'
end


问:
How to count number of nodes of LinkedList using python
Given a linked list containing brand names of biscuits sold by a retail store, write a python function which finds and returns the total number of biscuit brands.

```<code>class Node:
    def __init__(self,data):
        self.__data=data
        self.__next=None

    def get_data(self):
        return self.__data

    def set_data(self,data):
        self.__data=data

    def get_next(self):
        return self.__next

    def set_next(self,next_node):
        self.__next=next_node

class LinkedList:
    def __init__(self):
        self.__head=None
        self.__tail=None

    def get_head(self):
        return self.__head

    def get_tail(self):
        return self.__tail

    def add(self,data):
        new_node=Node(data)
        if(self.__head is None):
                self.__head=self.__tail=new_node
        else:
                self.__tail.set_next(new_node)
                self.__tail=new_node

def count_nodes(biscuit_list):
    count=0
 #PLEASE HELP ME IN THIS CODE TO GET SUITABLE OUTPUT....
    temp = Node.get_data(biscuit_list.get_head())
    while(temp is not None):
        count += 1
        temp = Node(temp).get_next()
    return count

biscuit_list=LinkedList()
biscuit_list.add("Goodday")
biscuit_list.add("Bourbon")
biscuit_list.add("Hide&Seek")
biscuit_list.add("Nutrichoice")

print(count_nodes(biscuit_list))
</code>```

The output is 1, but that is wrong.
The correct output is 4.

答:
The temp items in your biscuit list are already a Node so you can go ahead and use the Node methods directly.

```<code>def count_nodes(biscuit_list):
  count=0

  temp = biscuit_list.get_head()
  while(temp is not None):
      count += 1
      temp = temp.get_next()
  return count
</code>```

Body:
Given a linked list containing brand names of biscuits sold by a retail store, write a python function which finds and returns the total number of biscuit brands.

class Node:
    def __init__(self,data):
        self.__data=data
        self.__next=None

    def get_data(self):
        return self.__data

    def set_data(self,data):
        self.__data=data

    def get_next(self):
        return self.__next

    def set_next(self,next_node):
        self.__next=next_node

class LinkedList:
    def __init__(self):
        self.__head=None
        self.__tail=None

    def get_head(self):
        return self.__head

    def get_tail(self):
        return self.__tail

    def add(self,data):
        new_node=Node(data)
        if(self.__head is None):
                self.__head=self.__tail=new_node
        else:
                self.__tail.set_next(new_node)
                self.__tail=new_node

def count_nodes(biscuit_list):
    count=0
 #PLEASE HELP ME IN THIS CODE TO GET SUITABLE OUTPUT....
    temp = Node.get_data(biscuit_list.get_head())
    while(temp is not None):
        count += 1
        temp = Node(temp).get_next()
    return count

biscuit_list=LinkedList()
biscuit_list.add("Goodday")
biscuit_list.add("Bourbon")
biscuit_list.add("Hide&Seek")
biscuit_list.add("Nutrichoice")

print(count_nodes(biscuit_list))

The output is 1, but that is wrong.
The correct output is 4.

Body:
The temp items in your biscuit list are already a Node so you can go ahead and use the Node methods directly.

def count_nodes(biscuit_list):
  count=0

  temp = biscuit_list.get_head()
  while(temp is not None):
      count += 1
      temp = temp.get_next()
  return count


问:
c++ how to use select to see if a socket has closed
Can someone provide me an example of how to use select() to see if a client has closed the connection on a socket?

FYI. I'm using linux.

Thanks!

答:
The below snippet first checks if the socket is marked readable (which it is when closed) and then if there's actually anything to be read.</p>

```<code>#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>

bool isclosed(int sock) {
  fd_set rfd;
  FD_ZERO(&rfd);
  FD_SET(sock, &rfd);
  timeval tv = { 0 };
  select(sock+1, &rfd, 0, 0, &tv);
  if (!FD_ISSET(sock, &rfd))
    return false;
  int n = 0;
  ioctl(sock, FIONREAD, &n);
  return n == 0;
}
</code>```

Body:
The below snippet first checks if the socket is marked readable (which it is when closed) and then if there's actually anything to be read.

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ioctl.h>

bool isclosed(int sock) {
  fd_set rfd;
  FD_ZERO(&rfd);
  FD_SET(sock, &rfd);
  timeval tv = { 0 };
  select(sock+1, &rfd, 0, 0, &tv);
  if (!FD_ISSET(sock, &rfd))
    return false;
  int n = 0;
  ioctl(sock, FIONREAD, &n);
  return n == 0;
}


问:
How to write to job log from Oracle Report Builder 10.1.2.3.0
I am touching an old report using Oracle Report Builder 10.1.2.3.0.  I believe I am having trouble with some function within the report, but the error is very generic and does not point to a specific object.

```<code>    MSG-00002: Init failed
    REP-1416: '': User exit 'G_Catgeory'. .
    REP-0069: Internal error
    REP-57054: In-process job terminated:Terminated with error:
    REP-1416: MSG-00002: Init failed
    REP-1416: '': User exit 'G_Catgeory'. .
</code>```

Is there a way to write to the concurrent request log file from an RDF (Report Builder data definition)?

I have tried using DBMS_OUTPUT commands within a RDF function but the object will not compile:

```<code>    'DBMS_OUTPUT is not a procedure or is undefined.'
</code>```

Any tips on how to debug these old school reports is appreciated.

答:
It appears that the author used the SRW built-in package and its USER_EXIT procedure, i.e.

```<code>srw.user_exit('G_Catgeory')
</code>```

(by the way, looks like category was misspelled. Maybe it should have been G_Category).

How to find it? Save the report as a JSP file. Then open it in any text editor (such as Notepad) and search for the above terms. Once you find where it is, you should be able to locate & fix it in Reports Builder.

As of the message you'd want to print: use the SRW package (again), but this time the MESSAGE procedure, e.g.

```<code>srw.message(1, 'This is a message');
</code>```

For more info have a look at Reports Online Help system.

Body:
I am touching an old report using Oracle Report Builder 10.1.2.3.0.  I believe I am having trouble with some function within the report, but the error is very generic and does not point to a specific object.

    MSG-00002: Init failed
    REP-1416: '': User exit 'G_Catgeory'. .
    REP-0069: Internal error
    REP-57054: In-process job terminated:Terminated with error:
    REP-1416: MSG-00002: Init failed
    REP-1416: '': User exit 'G_Catgeory'. .

Is there a way to write to the concurrent request log file from an RDF (Report Builder data definition)?

I have tried using DBMS_OUTPUT commands within a RDF function but the object will not compile:

    'DBMS_OUTPUT is not a procedure or is undefined.'

Any tips on how to debug these old school reports is appreciated.

Body:
It appears that the author used the SRW built-in package and its USER_EXIT procedure, i.e.

srw.user_exit('G_Catgeory')

(by the way, looks like category was misspelled. Maybe it should have been G_Category).

How to find it? Save the report as a JSP file. Then open it in any text editor (such as Notepad) and search for the above terms. Once you find where it is, you should be able to locate & fix it in Reports Builder.

As of the message you'd want to print: use the SRW package (again), but this time the MESSAGE procedure, e.g.

srw.message(1, 'This is a message');

For more info have a look at Reports Online Help system.


问:
Assigning characters of array data members
What is the best way to assign a char of array data member in class?

i tried using this

```<code>   void setName(char a[]) {
      strcpy(name, a);
   }
</code>```

but it gives me an error of

strcpy is unsafe...

答:
Because this might lead to a buffer overflow!

One solution might be avoiding strcpy().

Instead, use string that C++ already has!

```<code>void setName(char a[]) {
        std::string a_str = a;
        name = a_str;
}
</code>```

Note: Do not forget to define name as following:

```<code>std::string name;
</code>```

Body:
What is the best way to assign a char of array data member in class?

i tried using this

   void setName(char a[]) {
      strcpy(name, a);
   }

but it gives me an error of

strcpy is unsafe...

Body:
Because this might lead to a buffer overflow!

One solution might be avoiding strcpy().

Instead, use string that C++ already has!

void setName(char a[]) {
        std::string a_str = a;
        name = a_str;
}

Note: Do not forget to define name as following:

std::string name;


答:
Your count_nodes should start pointing to the list's head item and iterate as long as __next of the current item is not None -- check the links, not the data!

```<code>def count_nodes(biscuit_list):
    count=0
    current = biscuit_list.get_head()
    while current is not None:
        current = current.get_next()
        count += 1
    return count
</code>```

Better yet, go ahead and implement __len__ and, for convenience, __iter__ and __next__ for syntactic sugar. Put your count_nodes code into __len__, such that you can do:

```<code>print(len(biscuit_list))
</code>```

and

```<code>for node in biscuit_list:
    print(node)
</code>```

There's a great source for Python's magic methods, make sure to check that, it's worth a read.

Title: How to count number of nodes of LinkedList using python

Body:
Your count_nodes should start pointing to the list's head item and iterate as long as __next of the current item is not None -- check the links, not the data!

def count_nodes(biscuit_list):
    count=0
    current = biscuit_list.get_head()
    while current is not None:
        current = current.get_next()
        count += 1
    return count

Better yet, go ahead and implement __len__ and, for convenience, __iter__ and __next__ for syntactic sugar. Put your count_nodes code into __len__, such that you can do:

print(len(biscuit_list))

and

for node in biscuit_list:
    print(node)

There's a great source for Python's magic methods, make sure to check that, it's worth a read.


问:
Is it possible to add html to phpinfo page?
So I was creating my own phpinfo.php page. It echos out the phpinfo() which is good, but I wanted to add html to it. I wanted to add to the top of the page a back button to take me back to my home directory. Then underneath that link I was gonna display the phpinfo(). I noticed that phpinfo() generates a complete html document with a doctype and everything. Is there a workaround for this? Since if I add my own html tags before I call phpinfo(), the ending result will be an html document underneath some html tags (which obviously isn't w3 standards). I thought about just getting the html output from the phpinfo page and just copying it into the file so I wouldn't be calling phpinfo() but if i ever change something in the future, I'd have to remember to get the new info, copy, paste the html into the document again.

So is there a work around for this?

答:
Note: In most cases, you should use Genjo's answer. This answer here provides an alternative if you do not have the PHP DOM module (provided by the php-xml package in Debian), and for whatever reason, you do not want to install it.

You can add HTML to a phpinfo page like this:

Get the HTML for the original phpinfo.

Place the phpinfo's HTML into an iframe.

Use JavaScript to manipulate the DOM inside the iframe to add/remove HTML.

Example code that adds
Hello!
 to the top of the page:

```<code><?php
ob_start();
phpinfo();
$phpInfoHtml = htmlentities(ob_get_clean());
?>
<!DOCTYPE html>
<head>
    <title>phpinfo</title>
    <meta charset="utf-8">
</head>
<body>
    <style>
        #iframe {
            /* Make the iframe fill the whole page. */
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>

    <script>
        // Add HTML and CSS into the iframe.
        function editFrame() {
            var iframe = document.getElementById('iframe').contentDocument;
            var body = iframe.getElementsByTagName('body')[0];

            // Add a header.
            var div = iframe.createElement('div');
            div.innerHTML =
                '<div id="header">' +
                    '<h1>Hello!</h1>' +
                '</div>';
            body.insertBefore(div, body.firstChild);

            // Add CSS for the header.
            var css =  // Note: Only one CSS rule allowed per call of insertRule.
                '#header {' +
                    'width: 930px;' +
                    'margin: auto;' +
                '}';
            var sheet = iframe.styleSheets[0];
            sheet.insertRule(css, sheet.cssRules.length);
        }
    </script>

    <!-- The iframe. -->
    <iframe id="iframe" srcdoc="<?php echo $phpInfoHtml ?>" onload="editFrame();" />
</body>
</code>```

Result:

Body:
Note: In most cases, you should use Genjo's answer. This answer here provides an alternative if you do not have the PHP DOM module (provided by the php-xml package in Debian), and for whatever reason, you do not want to install it.

You can add HTML to a phpinfo page like this:

Get the HTML for the original phpinfo.

Place the phpinfo's HTML into an iframe.

Use JavaScript to manipulate the DOM inside the iframe to add/remove HTML.

Example code that adds <h1>Hello!</h1> to the top of the page:

<?php
ob_start();
phpinfo();
$phpInfoHtml = htmlentities(ob_get_clean());
?>
<!DOCTYPE html>
<head>
    <title>phpinfo</title>
    <meta charset="utf-8">
</head>
<body>
    <style>
        #iframe {
            /* Make the iframe fill the whole page. */
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>

    <script>
        // Add HTML and CSS into the iframe.
        function editFrame() {
            var iframe = document.getElementById('iframe').contentDocument;
            var body = iframe.getElementsByTagName('body')[0];

            // Add a header.
            var div = iframe.createElement('div');
            div.innerHTML =
                '<div id="header">' +
                    '<h1>Hello!</h1>' +
                '</div>';
            body.insertBefore(div, body.firstChild);

            // Add CSS for the header.
            var css =  // Note: Only one CSS rule allowed per call of insertRule.
                '#header {' +
                    'width: 930px;' +
                    'margin: auto;' +
                '}';
            var sheet = iframe.styleSheets[0];
            sheet.insertRule(css, sheet.cssRules.length);
        }
    </script>

    <!-- The iframe. -->
    <iframe id="iframe" srcdoc="<?php echo $phpInfoHtml ?>" onload="editFrame();" />
</body>

Result:


问:
My BottomAppBar is covering the last row in my RecyclerView
My reclerview's last row is being covered by my bottom app bar.

My code is as follows:

activity_home.xml

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

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"/>

            <com.google.android.material.bottomappbar.BottomAppBar
                    android:id="@id/BottomAppBar_fromHomeActivity_Main"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    app:fabAlignmentMode="center"
                    app:navigationIcon="@drawable/ic_menu_dark"
                    app:menu="@menu/menu_bottomappbar_main"/>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                    android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_add_dark"
                    android:backgroundTint="@color/colorAccent"
                    app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>
</code>```

My reclerview is in a fragment from my home activity:

fragment.xml

```<code><layout
    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">

<androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/todoList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>
</code>```

However, the last row is only half visible as such:

From the material guidelines, the Bottom App Bar and FAB SHOULD be inside a coordinator layout for them to work together. So how am i supposed to lift my recyclerview above the bottom app bar so that the last row is visible too?

I don't want to add padding or margin at the end because it doesn't seem to be good coding...

Please help!

答:
Quick fix:

Try with these attributes:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false">

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/todoList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="56dp"
        android:clipToPadding="false"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
My reclerview's last row is being covered by my bottom app bar.

My code is as follows:

activity_home.xml

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

<layout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <fragment
                android:id="@id/Container_fromHomeActivity_BottomAppBarFragments"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:defaultNavHost="@bool/Navigation_NavigationHost_Default"
                app:navGraph="@navigation/bottomappbar_navigation"/>

            <com.google.android.material.bottomappbar.BottomAppBar
                    android:id="@id/BottomAppBar_fromHomeActivity_Main"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    app:fabAlignmentMode="center"
                    app:navigationIcon="@drawable/ic_menu_dark"
                    app:menu="@menu/menu_bottomappbar_main"/>

            <com.google.android.material.floatingactionbutton.FloatingActionButton
                    android:id="@id/FAB_fromHomeActivity_BottomAppBarAttached"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/ic_add_dark"
                    android:backgroundTint="@color/colorAccent"
                    app:layout_anchor="@id/BottomAppBar_fromHomeActivity_Main"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

My reclerview is in a fragment from my home activity:

fragment.xml

<layout
    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">

<androidx.constraintlayout.widget.ConstraintLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/todoList"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

</layout>

However, the last row is only half visible as such:

From the material guidelines, the Bottom App Bar and FAB SHOULD be inside a coordinator layout for them to work together. So how am i supposed to lift my recyclerview above the bottom app bar so that the last row is visible too?

I don't want to add padding or margin at the end because it doesn't seem to be good coding...

Please help!

Body:
Quick fix:

Try with these attributes:

<androidx.constraintlayout.widget.ConstraintLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipToPadding="false">

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/todoList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="56dp"
        android:clipToPadding="false"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="8dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Styling option_ui and browser_action page for Firefox Mobile
I developed an extension for Firefox with an option popup for preferences.

On mobile, as it doesn't open as a popup but as a new tab moz-extension://(...)/popup.html, I had to apply some specific CSS media queries.

But as you can see below, it's definitely not working.

What should I do ?

CSS page is here https://github.com/ANN-MB/LEIA/blob/master/extension%20firefox/leia.css

答:
But you need @media querys for wanted solutions! Your Medium is provide an max range of size, you only need is to declare your style on diffents sizeranges:

```<code>@media(min-width:XXXpx) {
    // your style here
}
</code>```

for more information take a look at this: https://gist.github.com/gokulkrishh/242e68d1ee94ad05f488

Body:
But you need @media querys for wanted solutions! Your Medium is provide an max range of size, you only need is to declare your style on diffents sizeranges:

@media(min-width:XXXpx) {
    // your style here
}

for more information take a look at this: https://gist.github.com/gokulkrishh/242e68d1ee94ad05f488


问:
How do I get resource file values in Visual Basic?
I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.

```<code>Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.
</code>```

I think the issue is with the string "MyProjectName.My.Resources.Resources".

Would I be better off moving the strings into their own resource file?

答:
Try ResourceManager("MyProjectName.Resources", ...), otherwise if it's the application resources you can simply use My.Resources.HD (see here:My.Resources Object)

or

Open Reflector, load your assembly there, go to resources, a list of resources appears, search for the one containg 'HD', copy the name (it's like MyProjectName.Resources.resources), remove the last .resources and try with that.

Body:
I'm new to Visual Basic, and I'm having issues accessing the resource file for my project.

Dim rm As Resources.ResourceManager = New Resources.ResourceManager("MyProjectName.My.Resources.Resources", [Assembly].GetExecutingAssembly())
Dim myValue = rm.GetString(lookUpKey) 'boom Object reference not set to an instance of an object.

I think the issue is with the string "MyProjectName.My.Resources.Resources".

Would I be better off moving the strings into their own resource file?


问:
Returning values in a graphical interface
Trying to establish a GUI whereby the user clicks a button and set information appears in the relevant rows and columns.

Print doesn't achieve the desired outcome and I don't understand GUIs well enough to try other things. I'm a rookie so I'm very lost.

normal = {'Protein' : {'32.50'},
          'Carbohydrates' : {'60'},
          'Fat' : {'40.86'}}

from tkinter import *
from tkinter import ttk

root = Tk()
root.title('Diet Information')

frame = ttk.Frame(root, padding='150 150 300 300')
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)

d_label = ttk.Label(frame, text='Selected diet: ')
d_label.grid(column=1, row=3, sticky=W)
p_label = ttk.Label(frame, text='Protein (g): ')
p_label.grid(column=1, row=4, sticky=W)
c_label = ttk.Label(frame, text='Carbohydrates (g): ')
c_label.grid(column=1, row=5, sticky=W)
f_label = ttk.Label(frame, text='Fat (g): ')
f_label.grid(column=1, row=6, sticky=W)
k_label = ttk.Label(frame, text='Kilojoules (kJ): ')
k_label.grid(column=1, row=7, sticky=W)
s_label = ttk.Label(frame, text='Select a diet to display:')
s_label.grid(column=3, row=8, sticky=W)

n_button = ttk.Button(frame, text='Normal', command=print(normal))
n_button.grid(column=3, row=9, sticky=W)
```

I wish for the 'normal' button to return the information required for each label. I will then use this method for multiple buttons.

答:
In tkinter, instead of print statements there are labels. Just like if you wanted to print a variable print(fred) you set a Label to a variable. Instead of having ttk.Label(frame, text), have ttk.Label(frame, textvariable=variable).
In order to use a Label with variables correctly, you need to set up the variable correctly. Say I still want to display variable. First, before putting it in the Label, it needs to be set up. You need to set it up to take in the type of data you are going to give it. Some examples of this are StringVar(), IntVar(), BooleanVar() and DoubleVar(). They basically just state that the data will be a string (StringVar), Integer(IntVar), Boolean(BooleanVar), or a float(DoubleVar). Say you have data for 15 grams of Carbs. That is an integer, so you would use IntVar(). The way to set it all up would look like this.

```<code>variable = IntVar()
variable.set(carbs)
ttk.Label(frame, textvariable=variable).pack()
</code>```

In this example, carbs would be your float value the user input, and variable is the actual variable you put in the label. Hope this helps, happy coding!

Quick edit: Buttons work best when you assign a function to them, so I would suggest setting a function to use the values in normal (if that's the data you want to use) and take that and assign it to variables that you put into your Labels.

Body:
Trying to establish a GUI whereby the user clicks a button and set information appears in the relevant rows and columns.

Print doesn't achieve the desired outcome and I don't understand GUIs well enough to try other things. I'm a rookie so I'm very lost.

normal = {'Protein' : {'32.50'},
          'Carbohydrates' : {'60'},
          'Fat' : {'40.86'}}

from tkinter import *
from tkinter import ttk

root = Tk()
root.title('Diet Information')

frame = ttk.Frame(root, padding='150 150 300 300')
frame.grid(column=0, row=0, sticky=(N, W, E, S))
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)

d_label = ttk.Label(frame, text='Selected diet: ')
d_label.grid(column=1, row=3, sticky=W)
p_label = ttk.Label(frame, text='Protein (g): ')
p_label.grid(column=1, row=4, sticky=W)
c_label = ttk.Label(frame, text='Carbohydrates (g): ')
c_label.grid(column=1, row=5, sticky=W)
f_label = ttk.Label(frame, text='Fat (g): ')
f_label.grid(column=1, row=6, sticky=W)
k_label = ttk.Label(frame, text='Kilojoules (kJ): ')
k_label.grid(column=1, row=7, sticky=W)
s_label = ttk.Label(frame, text='Select a diet to display:')
s_label.grid(column=3, row=8, sticky=W)

n_button = ttk.Button(frame, text='Normal', command=print(normal))
n_button.grid(column=3, row=9, sticky=W)

I wish for the 'normal' button to return the information required for each label. I will then use this method for multiple buttons.

Body:
In tkinter, instead of print statements there are labels. Just like if you wanted to print a variable print(fred) you set a Label to a variable. Instead of having ttk.Label(frame, text), have ttk.Label(frame, textvariable=variable).
In order to use a Label with variables correctly, you need to set up the variable correctly. Say I still want to display variable. First, before putting it in the Label, it needs to be set up. You need to set it up to take in the type of data you are going to give it. Some examples of this are StringVar(), IntVar(), BooleanVar() and DoubleVar(). They basically just state that the data will be a string (StringVar), Integer(IntVar), Boolean(BooleanVar), or a float(DoubleVar). Say you have data for 15 grams of Carbs. That is an integer, so you would use IntVar(). The way to set it all up would look like this.

variable = IntVar()
variable.set(carbs)
ttk.Label(frame, textvariable=variable).pack()

In this example, carbs would be your float value the user input, and variable is the actual variable you put in the label. Hope this helps, happy coding!

Quick edit: Buttons work best when you assign a function to them, so I would suggest setting a function to use the values in normal (if that's the data you want to use) and take that and assign it to variables that you put into your Labels.


问:
Send an email using Gmail API in Typescript/Javascript
I want to send an email on my application using my gmail account. I am using Ionic and followed https://www.sitepoint.com/sending-emails-gmail-javascript-api/ and https://developers.google.com/gmail/api/v1/reference/users/messages/send to send emails.
This is what I have for initializing client

```<code>client_id: gapiKeys.client_id,
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
scope: [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.compose",
    "https://www.googleapis.com/auth/gmail.send"
].join(" ")
</code>```

When I only put "https://www.googleapis.com/auth/gmail.readonly" under scope, I can get the list of labels of the user, but I get error 401 when I use mail.google.com, modify, compose, and send. Below is my code for sending an email.

```<code>sendEmail() {
let top = {
  'To': 'someRecipient@gmail.com',
  'Subject': 'Test'
}

var email = '';
for(var header in top) {
  email += header += ": "+ top[header] + "\r\n";
}
email += "\r\n" + "this is a testing email message.";

var request = (gapi.client as any).gmail.users.messages.send({
  'userId': 'me',
  'resource': {
    'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
  }
});
request.execute();
}
</code>```

With this code, I get

```<code>POST https://content.googleapis.com/gmail/v1/users/me/messages/send?alt=json&key=someKey--M 401 ()
</code>```

The address in the error shows the following:

```<code>{
 "error": {
 "errors": [
 {
  "domain": "global",
  "reason": "required",
  "message": "Login Required",
  "locationType": "header",
  "location": "Authorization"
 }
],
"code": 401,
"message": "Login Required"
}
}
</code>```

What should I do to send an email on application using Ionic (not email composer provided by Ionic)? I don't have to use Gmail API.

答:
Your authorization to access the server is not existent.
Use basic trouble shooting to determine the problem.
Here is a link that tells you what is happening.
You will have to provide some sort of authentication in the header no matter how you send the email.

https://httpstatuses.com/401

Body:
I want to send an email on my application using my gmail account. I am using Ionic and followed https://www.sitepoint.com/sending-emails-gmail-javascript-api/ and https://developers.google.com/gmail/api/v1/reference/users/messages/send to send emails.
This is what I have for initializing client

client_id: gapiKeys.client_id,
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
scope: [
    "https://www.googleapis.com/auth/gmail.readonly",
    "https://mail.google.com/",
    "https://www.googleapis.com/auth/gmail.modify",
    "https://www.googleapis.com/auth/gmail.compose",
    "https://www.googleapis.com/auth/gmail.send"
].join(" ")

When I only put "https://www.googleapis.com/auth/gmail.readonly" under scope, I can get the list of labels of the user, but I get error 401 when I use mail.google.com, modify, compose, and send. Below is my code for sending an email.

sendEmail() {
let top = {
  'To': 'someRecipient@gmail.com',
  'Subject': 'Test'
}

var email = '';
for(var header in top) {
  email += header += ": "+ top[header] + "\r\n";
}
email += "\r\n" + "this is a testing email message.";

var request = (gapi.client as any).gmail.users.messages.send({
  'userId': 'me',
  'resource': {
    'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
  }
});
request.execute();
}

With this code, I get

POST https://content.googleapis.com/gmail/v1/users/me/messages/send?alt=json&key=someKey--M 401 ()

The address in the error shows the following:

{
 "error": {
 "errors": [
 {
  "domain": "global",
  "reason": "required",
  "message": "Login Required",
  "locationType": "header",
  "location": "Authorization"
 }
],
"code": 401,
"message": "Login Required"
}
}

What should I do to send an email on application using Ionic (not email composer provided by Ionic)? I don't have to use Gmail API.


问:
Recursively rename files using find and sed
I want to go through a bunch of directories and rename all files that end in _test.rb to end in _spec.rb instead. It's something I've never quite figured out how to do with bash so this time I thought I'd put some effort in to get it nailed. I've so far come up short though, my best effort is:

```<code>find spec -name "*_test.rb" -exec echo mv {} `echo {} | sed s/test/spec/` \;
</code>```

NB: there's an extra echo after exec so that the command is printed instead of run while I'm testing it.

When I run it the output for each matched filename is:

```<code>mv original original
</code>```

i.e. the substitution by sed has been lost. What's the trick?

答:
I share this post as it is a bit related to question. Sorry for not providing more details. Hope it helps someone else.
http://www.peteryu.ca/tutorials/shellscripting/batch_rename</p>

ContentLicense: CC BY-SA 2.5

Body:
I want to go through a bunch of directories and rename all files that end in _test.rb to end in _spec.rb instead. It's something I've never quite figured out how to do with bash so this time I thought I'd put some effort in to get it nailed. I've so far come up short though, my best effort is:

find spec -name "*_test.rb" -exec echo mv {} `echo {} | sed s/test/spec/` \;

NB: there's an extra echo after exec so that the command is printed instead of run while I'm testing it.

When I run it the output for each matched filename is:

mv original original

i.e. the substitution by sed has been lost. What's the trick?


问:
How to sort a list nested inside another list?
I have lists nested inside an outer list. I want to sort the elements in inner lists without changing the position of the elements(lists in this case) in outer list. How to do it?

I am getting space separated user input which I later convert to nested lists where each inner list contain the digits of the number separated from each other. All I want is to get the inner lists in sorted form

```<code>num = list(map(str, input().split()))
n_list = []
for i in range(len(num)):
    num_in_num = [int(j) for j in num[i]]
    n_list.append(num_in_num)
print(n_list)
</code>```

for this given input:

```<code>5654 3456 7215 7612 5463
</code>```

I get the list as:

```<code>[[5, 6, 5, 4], [3, 4, 5, 6], [7, 2, 1, 5], [7, 6, 1, 2], [5, 4, 6, 3]]
</code>```

I want the output to be like:

```<code>[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]
</code>```

How to get this output?

答:
```<code>inp = '5654 3456 7215 7612 5463' # user input
res= [] # list to store the final output

# iterating over each number which is divided into a list via inp.split()
for i in inp.split():
    # keeping internal list which will keep the each digit in int format
    tmp=[]
    for j in i: # iterating over the number eg 5654
         # converting each digit to int and adding it to temp list
         tmp.append(int(j))
    # sorting internal list and appending it to final result list
    res.append(sorted(tmp))

print(res) # printing final list
</code>```

output

```<code>[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]
</code>```

Body:
I have lists nested inside an outer list. I want to sort the elements in inner lists without changing the position of the elements(lists in this case) in outer list. How to do it?

I am getting space separated user input which I later convert to nested lists where each inner list contain the digits of the number separated from each other. All I want is to get the inner lists in sorted form

num = list(map(str, input().split()))
n_list = []
for i in range(len(num)):
    num_in_num = [int(j) for j in num[i]]
    n_list.append(num_in_num)
print(n_list)

for this given input:

5654 3456 7215 7612 5463

I get the list as:

[[5, 6, 5, 4], [3, 4, 5, 6], [7, 2, 1, 5], [7, 6, 1, 2], [5, 4, 6, 3]]

I want the output to be like:

[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]

How to get this output?

Body:
inp = '5654 3456 7215 7612 5463' # user input
res= [] # list to store the final output

# iterating over each number which is divided into a list via inp.split()
for i in inp.split():
    # keeping internal list which will keep the each digit in int format
    tmp=[]
    for j in i: # iterating over the number eg 5654
         # converting each digit to int and adding it to temp list
         tmp.append(int(j))
    # sorting internal list and appending it to final result list
    res.append(sorted(tmp))

print(res) # printing final list

output

[[4, 5, 5, 6], [3, 4, 5, 6], [1, 2, 5, 7], [1, 2, 6, 7], [3, 4, 5, 6]]


问:
Node.js Error: Cannot find module 'request'
Ok so this is a common error and I HAVE read this
node.js: cannot find module 'request'

The request module IS installed in my node_modules. My complete node app is

```<code>var r = require("request");

var s = r('http://www.foo.com/');

s.on('data',function(chunk){

    console.log(">>>Data>>> "+chunk);
});

s.on('end', function(){
    console.log(">>>Done!");
})
</code>```

I run my app by simply calling

```<code>node app
</code>```

But I keep getting the same error

What gives?

My directory structure is

```<code>app.js
node_modules
    request
        node_modules
            bl
            combined-stream
            form-data
            hawk
            mime-types
            tough-cookie
</code>```

The complete error trace is

```<code>module.js:340
    throw err;
          ^
Error: Cannot find module 'request'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/Users/foo/Documents/.../app.js:1:71)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
</code>```

答: I had the same problem, and i installed the request package like that: "npm install request --save" and that solved the problem.</p>

Body:
Ok so this is a common error and I HAVE read this
node.js: cannot find module 'request'

The request module IS installed in my node_modules. My complete node app is

var r = require("request");

var s = r('http://www.foo.com/');

s.on('data',function(chunk){

    console.log(">>>Data>>> "+chunk);
});

s.on('end', function(){
    console.log(">>>Done!");
})

I run my app by simply calling

node app

But I keep getting the same error

What gives?

My directory structure is

app.js
node_modules
    request
        node_modules
            bl
            combined-stream
            form-data
            hawk
            mime-types
            tough-cookie

The complete error trace is

module.js:340
    throw err;
          ^
Error: Cannot find module 'request'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (/Users/foo/Documents/.../app.js:1:71)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)


问:
Using JAX-WS: How can I set the user agent property
I've searched on this and found a few near misses.  I've created a java client to consume a web service using JAX-WS.  Is there a way when using JAX to set the HTTP_USER_AGENT value?  I would like to have my web service log when specific clients (mine) access it so I wanted a customized value.

I've seen options where you set it in the system properties but this doesn't seem to work.  The generated JAX classes don't seem to have a direct reference to the connection object so I don't see how I can manipulate those classes.

Any help would be great.
Thanks
ST

答: not sure if this is the best/most direct way to do it, but i think you could add a custom javax.xml.ws.handler.Handler to the handler chain in the dispatch javax.xml.ws.Binding.  in the Handler, you should be able to set a custom map of extra http headers on the outgoing MessageContext using the MessageContext.HTTP_REQUEST_HEADERS property.</p>