答:
You project build.gradle should be similar to this

```<code>buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.0.1"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

And you should use the same version for your libraries like this:

```<code>implementation "com.android.support:appcompat-v7:26.0.1"
implementation "com.android.support:design:26.0.1"
</code>```

Title: How to solve this error: Failed to resolve: com.android.support:appcompat-v7:26.1.0

Body:
You project build.gradle should be similar to this

buildscript {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:3.0.1"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And you should use the same version for your libraries like this:

implementation "com.android.support:appcompat-v7:26.0.1"
implementation "com.android.support:design:26.0.1"


来源: stackexchange

问:
Animating a UIImage or UIImageView?
I'm trying to animate an image's height (from height of 0 pixels to 480 pixels) to create the effect of the image being rendered top-down.

With an UIImageView i noticed that it appears correct in the Interface Builder. But when it runs in the simulator the size (width and height) is always set to whatever the size of the image is; meaning, if I set the height of the image view to be 50% the original height, the image is still rendered in full height.

I also tried do this effect with an UIImage. However, although the size of the image appears correct, the image is scaled to reflect the size/aspect-ratio.

Question:
How can i achieve this dynamic sizing (i.e. animation of an image's size) while NOT scaling the image? I thought about using CGImageCreateWithMask, but im pretty sure that would create huge performance hiccups.

* Update *

The effect that im looking for is this:
Animate an image by making it grow in height, from to-down (like a set of blinds being pulled on a window). This image cannot be scaled (as it would lose the visual effect of looking like a "blind"). This image must also be rendered on top of another image. So there are 2 images total.

* ANSWER *

For the top-most imageview, i set the content mode to Top (so it doesnt scale). Then in code, i set the clipsToBounds to True. Now i am able to animate the top-most imageview height thus giving me the effect i am looking for.

答:
Use an animation block like so:</p>

```<code>imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 0)];
imageView.image = ...;
[imageView setClipsToBounds:YES];
[imageView setContentMode:UIViewContentModeTop];

[self.view addSubview:imageView];
[imageView release];

[UIView animateWithDuration:4.0f
                      delay:1.0f
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^(void) {
                     imageView.frame = CGRectMake(0, 0, 320, 480);
                 }
                 completion:NULL];
</code>```

ContentLicense: CC BY-SA 2.5

Title: Animating a UIImage or UIImageView?

Body:
Use an animation block like so:

imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 0)];
imageView.image = ...;
[imageView setClipsToBounds:YES];
[imageView setContentMode:UIViewContentModeTop];

[self.view addSubview:imageView];
[imageView release];

[UIView animateWithDuration:4.0f
                      delay:1.0f
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^(void) {
                     imageView.frame = CGRectMake(0, 0, 320, 480);
                 }
                 completion:NULL];


问:
How to get TextView of an activity in an Adapter class while that TextView is not in row of recyclerView?
How to get TextView of an Activity  in  RecyclerViewAdapter class and TextView is not in layout of row For  RecyclerView  item.As in RecyclerViewAdapter we override method

```<code>onBindViewHolder(ViewHolder holder, int position){
   NewsModel newsModel=values.get(position);  //to get the current object
        holder.news_title.setText(newsModel.getTitle());
        holder.news_body.setText(newsModel.getDescription());
        holder.news_published_at.setText("Date "+GiveMeDate(values.get(position).getDate()));}
</code>```

and as it get only those which are declared in ViewHolder extends RecyclerView.ViewHolder   and ViewHolder  will only get ui that are in View v = inflater.inflate(R.layout.news_item, parent, false);but I want to get ui from activity's layout so that I can update TextView value in Adapter So please Help to do that work. Image to reflect Layout is as follows:

答:
get it by </p>

```<code>TextView requiredTextView = (TextView) ActivityName.findViewById(R.id.requiredTextView);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to get TextView of an Activity  in  RecyclerViewAdapter class and TextView is not in layout of row For  RecyclerView  item.As in RecyclerViewAdapter we override method

onBindViewHolder(ViewHolder holder, int position){
   NewsModel newsModel=values.get(position);  //to get the current object
        holder.news_title.setText(newsModel.getTitle());
        holder.news_body.setText(newsModel.getDescription());
        holder.news_published_at.setText("Date "+GiveMeDate(values.get(position).getDate()));}

and as it get only those which are declared in ViewHolder extends RecyclerView.ViewHolder   and ViewHolder  will only get ui that are in View v = inflater.inflate(R.layout.news_item, parent, false);but I want to get ui from activity's layout so that I can update TextView value in Adapter So please Help to do that work. Image to reflect Layout is as follows:

Body:
get it by

TextView requiredTextView = (TextView) ActivityName.findViewById(R.id.requiredTextView);


问:
What is a usecase for the fabric-kafka and fabric-order containers in same network
I can see there are 3 types of orderer. When I  deploy  a  fabric-network  up to 2 types are used.

https://hub.docker.com/r/hyperledger/fabric-orderer/
https://hub.docker.com/r/hyperledger/fabric-kafka/

https://hub.docker.com/r/hyperledger/fabric-ca-orderer/

The order documentation describes usage

https://github.com/hyperledger/fabric/blob/master/orderer/README.md

but I do not expect to see fabric-orderer  and fabric-kafka containers in  a  fabric network.

What  am I  misunderstanding here?

答:
The architecture for Hyperledger Fabric allows for multiple types of ordering services.  At the heart of the architecture is a common atomic broadcast interface.

The orderer interfaces are implemented in the orderer executable which is packaged as the fabric-orderer Docker image.

There are two configuration modes for the orderer:

1) Solo - this is a standalone, single process orderer primarily for use during development and test (although nothing would stop someone from using it for production - it would just not be fault tolerant)

2) Kafka - this leverages Kafka as the "consensus" mechanism to make multiple orderer processes crash fault tolerant and order transactions.  In this case, multiple orderer processes communicate with a Kafka cluster which ensures that each orderer process receives transactions and generates blocks in the same order.  The orderer process (or fabric-orderer containers) communicate with a Kafka cluster (which can be run using the fabric-kafka and fabric-zookeeper Docker images).


问:
css - @media isn't working
Okay, I found a solution: with @media I'm accessing the image's width and the bar separately and it's working but is there any shorter way codewise?

I searched the internet for a solution but none of what I found helped me so far.

I'm trying to make my header to be responsive to the browser's width but it isn't working.

I tried to make just the image responsive or just the top bar but nothing works...

Any ideas?

```<code><header class="header">
  <div class="top-bar">
    <div class="nav-container">
      <ul class="navbar">
        <li><a href="#החשבון שלי">החשבון שלי</a></li>
        <li><a href="#המתכונים שלי">המתכונים שלי</a></li>
        <li><a href="#אודות">אודות</a></li>
        <li class="last-btn"><a href="#צרו קשר">צרו קשר</a></li>
      </ul>
    </div>
  </div>
  <div class="banner">
    <a href="#banner"><img src="Images\maadanot_winter_banners.jpg" alt="אפייה חורפית"/></a>
  </div>
</header>
</code>```

and this is the css:

```<code>body {
margin: 0;
}

.top-bar {
    width: 100%;
    background-color: #404040;
    padding: 12px;
}

.nav-container {
    width: 68%;
    margin: auto;
}

.navbar {
    margin: 0;
    list-style-type: none;
    background-color: #404040;
    display: table;
    font-family: Helvetica;
    font-size: 14px;
}

.navbar li {
    display: table-cell;
    border-left: 1px solid white;
    padding: 0px 10px;
    overflow: hidden;
    width: 85px;
    text-align: center;
}

.navbar a {
    color: white;
    text-decoration: none;
}

.navbar a:hover {
    font-weight: bold;
}

@media screen and (max-width:900px) {
    .header {
        width: 100%;
    }
}

.banner {
    margin-top: 33px;
    width: 100%;
    text-align: center;
}
</code>```

答:
Try to change it into:</p>

```<code>@media screen and (max-width:900px) {
    .header {
        width: 100vw; /* viewport width */
    }
}
</code>```

Title: css - @media isn't working

Body:
Okay, I found a solution: with @media I'm accessing the image's width and the bar separately and it's working but is there any shorter way codewise?

I searched the internet for a solution but none of what I found helped me so far.

I'm trying to make my header to be responsive to the browser's width but it isn't working.

I tried to make just the image responsive or just the top bar but nothing works...

Any ideas?

החשבון שלי

המתכונים שלי

אודות

צרו קשר

and this is the css:

body {
margin: 0;
}

.top-bar {
    width: 100%;
    background-color: #404040;
    padding: 12px;
}

.nav-container {
    width: 68%;
    margin: auto;
}

.navbar {
    margin: 0;
    list-style-type: none;
    background-color: #404040;
    display: table;
    font-family: Helvetica;
    font-size: 14px;
}

.navbar li {
    display: table-cell;
    border-left: 1px solid white;
    padding: 0px 10px;
    overflow: hidden;
    width: 85px;
    text-align: center;
}

.navbar a {
    color: white;
    text-decoration: none;
}

.navbar a:hover {
    font-weight: bold;
}

@media screen and (max-width:900px) {
    .header {
        width: 100%;
    }
}

.banner {
    margin-top: 33px;
    width: 100%;
    text-align: center;
}

Body:
Try to change it into:

@media screen and (max-width:900px) {
    .header {
        width: 100vw; /* viewport width */
    }
}


问:
onMessageReceived not called when phone is asleep
I have created an app that starts an alarm when a message from FCM was received. The app works fine when it is in the foreground, in the background or when the activity is closed.

But when the phone has been in sleep mode for a long time (don't know the exact time) the onMessageReceived method isn't called until the phone is woken up manually. The FCM messages are data messages with high priority, which according to the documentation should be able to wake up the phone.

What are ways to fix this problem?
Is using WakeLock the way to go, or is it to heavy on the battery life ?

答:
Send notifications with this format from back end :

```<code>{

"notification" : {
    "click_action" : ".MainActivity",
    "body" : "new Symulti update !",
    "title" : "new Symulti update !",
    "icon" : "ic_notif_symulti" },

"data": { ... },

"to" : "c9Vaa3ReGdk:APA91bH-AuXgg3lDN2WMcBrNhJZoFtYF9" }
</code>```

The key here is add

```<code>"click_action" : ".MainActivity"
</code>```

for handle click action.

Body:
Send notifications with this format from back end :

{

"notification" : {
    "click_action" : ".MainActivity",
    "body" : "new Symulti update !",
    "title" : "new Symulti update !",
    "icon" : "ic_notif_symulti" },

"data": { ... },

"to" : "c9Vaa3ReGdk:APA91bH-AuXgg3lDN2WMcBrNhJZoFtYF9" }

The key here is add

"click_action" : ".MainActivity"

for handle click action.


问:
Access the MouseDoubleClick Events of a textbox in a UserControl
I have an form that have a UserControl. The user control has a textbox. I want to access the MouseDoubleClick events of the textbox since when I tried using the MouseDoubleClick event of the UserControl nothing happens when I double clicks it. I have a copy of the source code of the UserControl. Please see below code that i am trying.

```<code>  private void UserControl_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        MessageBox.Show("Mouse Double Click!");
    }
</code>```

答:
I already resolve it: I added an event in the user control.

public event MouseEventHandler txtMouseDoubleClick;

```<code>private void TextBox_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (this.txtMouseDoubleClick!= null)
            this.txtMouseDoubleClick(this, e);
    }
</code>```

Body:
I have an form that have a UserControl. The user control has a textbox. I want to access the MouseDoubleClick events of the textbox since when I tried using the MouseDoubleClick event of the UserControl nothing happens when I double clicks it. I have a copy of the source code of the UserControl. Please see below code that i am trying.

  private void UserControl_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        MessageBox.Show("Mouse Double Click!");
    }

Body:
I already resolve it: I added an event in the user control.

public event MouseEventHandler txtMouseDoubleClick;

private void TextBox_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        if (this.txtMouseDoubleClick!= null)
            this.txtMouseDoubleClick(this, e);
    }


问:
Discussion about how to retrieve an i-th element in the j-th level of a binary tree algorithm
I am solving some problems from a site called codefights and the last one solved was about a binary tree in which are:

Consider a special family of Engineers and Doctors. This family has
  the following rules:

Everybody has two children. The first child of an Engineer is an
  Engineer and the second child is a Doctor. The first child of a Doctor
  is a Doctor and the second child is an Engineer. All generations of
  Doctors and Engineers start with an Engineer.

We can represent the situation using this diagram:

```<code>            E
       /         \
      E           D
    /   \        /  \
   E     D      D    E
  / \   / \    / \   / \
 E   D D   E  D   E E   D
</code>```

Given the level and position of a person in the ancestor tree above,
  find the profession of the person. Note: in this tree first child is
  considered as left child, second - as right.

As there is some space and time restrictions, the solution can not be based on actually constructing the tree until the level required and check which element is in the position asked. So far so good. My proposed solution written in python was:

```<code>def findProfession(level, pos):

    size = 2**(level-1)
    shift = False

    while size > 2:
        if pos <= size/2:
            size /= 2
        else:
            size /= 2
            pos -= size
            shift = not shift

    if pos == 1 and shift == False:
        return 'Engineer'
    if pos == 1 and shift == True:
        return 'Doctor'
    if pos == 2 and shift == False:
        return 'Doctor'
    if pos == 2 and shift == True:
        return 'Engineer'
</code>```

As it solved the problem, I got access to the solutions of other used and I was astonished by this one:

```<code>def findProfession(level, pos):
    return ['Engineer', 'Doctor'][bin(pos-1).count("1")%2]
</code>```

Even more, I did not understand the logic behind it and so we arrived to this question. Someone could explain to me this algorithm?

答:
Let's number the nodes of the tree in the following way:

1) the root has number 1

2) the first child of node x has number 2*x

3) the second child of node x has number 2*x+1

Now, notice that each time you go to the first child, the profession stays the same, and you add a 0 to the binary representation of the node.
And each time you go to the second child, the profession flips and you add a 1 to the binary representation.

Example:  Let's find the profession of the 4th node in the 4th level (last level in the diagram you have in the question). First we start at the root with number 1, then we go to the first child with number 2 (10 binary). After that we go to the second child of 2 which is 5 (101 binary). Finally, we go to the second child of 5 which is 11 (1011 binary).

Notice that we started with only one bit equal to 1, then every 1 bit we added to the binary representation flipped the profession. So the number of times we flip a profession is equal to the (number of bits equal to 1) - 1. The parity of this amount decides the profession.

This leads us to the following solution:

X = number of bits equal to 1 in [ 2^(level-1) + pos - 1 ]

Y = (X-1) mod 2

if Y is 0 then the answer is "Engineer"
Otherwise the answer is "Doctor"

since 2^(level-1) is a power of 2, it has exactly one bit equal to 1, therefore you can write:

X = number of bits equal to 1 in [ pos-1 ]

Y = X mod 2

Which is equal to the solution you mentioned in the question.

Body:
I am solving some problems from a site called codefights and the last one solved was about a binary tree in which are:

Consider a special family of Engineers and Doctors. This family has
  the following rules:

Everybody has two children. The first child of an Engineer is an
  Engineer and the second child is a Doctor. The first child of a Doctor
  is a Doctor and the second child is an Engineer. All generations of
  Doctors and Engineers start with an Engineer.

We can represent the situation using this diagram:

            E
       /         \
      E           D
    /   \        /  \
   E     D      D    E
  / \   / \    / \   / \
 E   D D   E  D   E E   D

Given the level and position of a person in the ancestor tree above,
  find the profession of the person. Note: in this tree first child is
  considered as left child, second - as right.

As there is some space and time restrictions, the solution can not be based on actually constructing the tree until the level required and check which element is in the position asked. So far so good. My proposed solution written in python was:

def findProfession(level, pos):

    size = 2**(level-1)
    shift = False

    while size > 2:
        if pos <= size/2:
            size /= 2
        else:
            size /= 2
            pos -= size
            shift = not shift

    if pos == 1 and shift == False:
        return 'Engineer'
    if pos == 1 and shift == True:
        return 'Doctor'
    if pos == 2 and shift == False:
        return 'Doctor'
    if pos == 2 and shift == True:
        return 'Engineer'

As it solved the problem, I got access to the solutions of other used and I was astonished by this one:

def findProfession(level, pos):
    return ['Engineer', 'Doctor'][bin(pos-1).count("1")%2]

Even more, I did not understand the logic behind it and so we arrived to this question. Someone could explain to me this algorithm?


答:
It's not really clear what you want, but to get your image span the whole width in all sizes, you can add this rule:

```<code>.banner img {
  width: 100%;
}
</code>```

This will size the image within  its container (which has 100% width, so eventually the image will span the width).

BTW: .banner is a DIV that will be 100% wide anyway, so you actually can erase the 100% width for .banner

body {
  margin: 0;
}

.top-bar {
  width: 100%;
  background-color: #404040;
  padding: 12px;
}

.nav-container {
  width: 68%;
  margin: auto;
}

.navbar {
  margin: 0;
  list-style-type: none;
  background-color: #404040;
  display: table;
  font-family: Helvetica;
  font-size: 14px;
}

.navbar li {
  display: table-cell;
  border-left: 1px solid white;
  padding: 0px 10px;
  overflow: hidden;
  width: 85px;
  text-align: center;
}

.navbar a {
  color: white;
  text-decoration: none;
}

.navbar a:hover {
  font-weight: bold;
}

@media screen and (max-width:900px) {
  .header {
    width: 100%;
  }
}

.banner {
  margin-top: 33px;
}
.banner img {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header">
  <div class="top-bar">
    <div class="nav-container">
      <ul class="navbar">
        <li>החשבון שלי</li>
        <li>המתכונים שלי</li>
        <li>אודות</li>
        <li class="last-btn">צרו קשר</li>
      </ul>
    </div>
  </div>
  <div class="banner">
    <img src="http://placehold.it/1200x90/fa0" alt="אפייה חורפית" />
  </div>
</header></code>```

Title: css - @media isn't working

Body:
It's not really clear what you want, but to get your image span the whole width in all sizes, you can add this rule:

.banner img {
  width: 100%;
}

This will size the image within  its container (which has 100% width, so eventually the image will span the width).

BTW: .banner is a DIV that will be 100% wide anyway, so you actually can erase the 100% width for .banner

body {
  margin: 0;
}

.top-bar {
  width: 100%;
  background-color: #404040;
  padding: 12px;
}

.nav-container {
  width: 68%;
  margin: auto;
}

.navbar {
  margin: 0;
  list-style-type: none;
  background-color: #404040;
  display: table;
  font-family: Helvetica;
  font-size: 14px;
}

.navbar li {
  display: table-cell;
  border-left: 1px solid white;
  padding: 0px 10px;
  overflow: hidden;
  width: 85px;
  text-align: center;
}

.navbar a {
  color: white;
  text-decoration: none;
}

.navbar a:hover {
  font-weight: bold;
}

@media screen and (max-width:900px) {
  .header {
    width: 100%;
  }
}

.banner {
  margin-top: 33px;
}
.banner img {
  width: 100%;
}

<header class="header">
  <div class="top-bar">
    <div class="nav-container">
      <ul class="navbar">
        <li><a href="#החשבון שלי">החשבון שלי</a></li>
        <li><a href="#המתכונים שלי">המתכונים שלי</a></li>
        <li><a href="#אודות">אודות</a></li>
        <li class="last-btn"><a href="#צרו קשר">צרו קשר</a></li>
      </ul>
    </div>
  </div>
  <div class="banner">
    <a href="#"><img src="http://placehold.it/1200x90/fa0" alt="אפייה חורפית" /></a>
  </div>
</header>


问:
How to set a fixed windows size for a GTK+ app in C?
How do I set a fixed window size for a GTK+ app? I have:

```<code>gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
gtk_window_set_policy (GTK_WINDOW(mainWindow), FALSE, FALSE, FALSE);
</code>```

but the window gets very small. There are no widgets yet.

答:
Use gtk_window_set_resizable function for this purpose

```<code>gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
gtk_window_set_resizable (GTK_WINDOW(mainWindow), FALSE);
</code>```

Body:
How do I set a fixed window size for a GTK+ app? I have:

gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
gtk_window_set_policy (GTK_WINDOW(mainWindow), FALSE, FALSE, FALSE);

but the window gets very small. There are no widgets yet.

Body:
Use gtk_window_set_resizable function for this purpose

gtk_window_set_default_size(GTK_WINDOW(mainWindow), 400, 300);
gtk_window_set_resizable (GTK_WINDOW(mainWindow), FALSE);


问:
Angularjs : How to display float number to nearst rounded number
I have an angularjs variable bill_amount which store 500.44. How can I display it to 501 without using controller function.
I use{{bill_amount | number: 0}} but it show 500 when the amount is greater than .5 then it adds +1 on the amount but I need to add +1  on the amount if the amount is greater then .0 like if the amount is 500.1 than I want to show 501.

答: Use bill_amount = Math.ceil(1.4) in your controller and then use {{bill_amount}} in your view.</p>


问:
.NET datetime Millisecond precision issue when converting from string to datetime

Hi.
I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume.

Example:

```<code>string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }
</code>```

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?

答:
Precision of date and time values is more complex than you might think. There are different levels of precision involved:

Precision of DateTime

DateTime stores the number of ticks since 01.01.0001 00:00 as a 64 bit value. One tick is 100 nanoseconds. Since this is the maximum precision that can be stored, it makes no sense to format to a precision higher than that. You can just add as many zeros as you need to represent a higher precision. If you need to represent shorter timespans than 100 nanoseconds, you need to use a different type, such as an Int64 with a custom tick size.

Precision of DateTime.Now

When you call DateTime.Now, you get a much lower precision than DateTime can store. The exact value depends on the system clock, but it is usually in the milliseconds range.

Precision of Stopwatch

When you measure the time with Stopwatch, depending on your system, you might get the time from a high performance clock, which more precise than the clock used for DateTime.Now, but still less than 100 nanoseconds. On a system without high performance clock, the precision is the one of the regular system clock.

Summary

Unless the value that you are parsing originates from a high precision clock (like an atomic clock), parsing it to the full precision of DateTime, makes not much practical sense. And if it comes from such a source, you need to resort to a different data type to represent the value.

Body:
Hi.
I am trying to convert an incoming datetime value that comes to our system in a string format. It seems that when the precision of milliseconds is higher than 7, the datetime parsing in .NET does not seem to like the value and cannot convert/parse the value. I am a bit stuck on what to do for this? My only current thought is there is a limit on the millisecond size and that anymore precision is not possible? But I want to confirm this is the case rather than assume.

Example:

string candidateDateTimeString = "2017-12-08T15:14:38.123456789Z";
if (!success)
        {
            success = DateTime.TryParseExact(trayportDateTimeString, "yyyy-
MM-dd'T'HH:mm:ss.fffffffff'Z'",
                CultureInfo.InvariantCulture, dateTimeStyles, out dateTime);
        }

If I reduce the 'f' values down to just 7, then date time parsing works fine. Is there a limit? Or am I doing something obvious wrong?


问:
Execution order of anonymous function
```<code>(function() {
  f();
  f = function() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();
</code>```

prints 9, 8.

Why isn't it 8, 9?

Why doesn't the anonymous function execute first?

答:
If you need the output you can modify it like this

```<code>(function() {
  f();
  function f() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();
</code>```

But let me explains why it executes that way.

```<code>(function() {
  f(); // Line Number -a
  f = function() { //b
    console.log(8);
  }
})()

function f() { //c
  console.log(9)
}

f() //d
</code>```

There is the difference.The line 'b' is a function expression.It is only defined when it is reached.So when it reaches 'a' i doesn't actually know about the 'b' function.On the contrary, c is a function declaration and when it encouters 'f()' it immediately knows.
Right after 'a' is executed (which executes 'c',it will be modified by 'b' to its new defanition.

To make it more clear consider this function

```<code>function printMe(){
  var a;
  console.log(a);
  a = 10;//It an expression
}
</code>```

The output you would get is it is defined.Because untill that line a=10 is not executed, it doesn't have a value.

There is this little code written by Philip Roberts which actually shows how your code is being executed .Please have a look here

Title: Execution order of anonymous function

Body:
(function() {
  f();
  f = function() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();

prints 9, 8.

Why isn't it 8, 9?

Why doesn't the anonymous function execute first?

Body:
If you need the output you can modify it like this

(function() {
  f();
  function f() {
    console.log(8);
  }
})()

function f() {
  console.log(9)
}

f();

But let me explains why it executes that way.

(function() {
  f(); // Line Number -a
  f = function() { //b
    console.log(8);
  }
})()

function f() { //c
  console.log(9)
}

f() //d

There is the difference.The line 'b' is a function expression.It is only defined when it is reached.So when it reaches 'a' i doesn't actually know about the 'b' function.On the contrary, c is a function declaration and when it encouters 'f()' it immediately knows.
Right after 'a' is executed (which executes 'c',it will be modified by 'b' to its new defanition.

To make it more clear consider this function

function printMe(){
  var a;
  console.log(a);
  a = 10;//It an expression
}

The output you would get is it is defined.Because untill that line a=10 is not executed, it doesn't have a value.

There is this little code written by Philip Roberts which actually shows how your code is being executed .Please have a look here


答:
device-width is not correct value for width.
Use : <
meta name="viewport" content="width=device-width, initial-scale=1">

The width property controls the size of the viewport. It can be set to a specific number of pixels like width=600 or to the special value device-width, which is the width of the screen in CSS pixels at a scale of 100%.

The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.

Title: css - @media isn't working


问:
Does Google Analytics for Cordova still work?
I have noticed that if you try configuring Google Analytics for a mobile app - it points you to Firebase Analytics.

Can Google Analytics still be used for a Cordova app?  If yes - shall it set as separate web property to track?  What should be the site URL?

答:
Yes. I recently used Google Analytics for Ionic3 app. One important thing I was missing initially was to create account for mobile app in Google Analytics. If you use website account, GA events will not be fired from mobile devices.

You can use this Cordova plugin for GA.

Follow steps mentined bwlow to create GA account for mobile app.

1. Go to Admin panel from side bar.

2. Create new account

3. Select account type as Mobile App


问:
How to pass arguments from wrapper shell script to Java application?
I want to run Java programs I am creating at on the command line (linux and mac).  I don't want to type "java" and arguments all the time, so I am thinking about creating wrapper scripts.  What's the best way to do this so that they work everywhere?  I want to be able to pass arguments, too.  I was thinking of using "shift" to do this (removing first argument).

Is there a better way to do this without using scripts at all?  Perhaps make an executable that doesn't require invocation through the "java" command?

答:
Assuming that you are using a shell that is compatible with the Bourne shell; e.g. sh, bash, ksh, etc, the following wrapper will pass all command line arguments to the java command:

```<code>#!/bin/sh
OPTS=...
java $OPTS com.example.YourApp "$@"
</code>```

The $@ expands to the remaining arguments for the shell script, and putting quotes around it causes the arguments to be individually quoted, so that the following will pass a single argument to Java:

```<code>$ wrapper "/home/person/Stupid Directory Name/foo.txt"
</code>```

Without the double quotes around "$@" in the wrapper script, Java would receive three arguments for the above.

Note that this does not work with "$*".  According to the bash manual entry:

"$*" is equivalent to "$1c$2c...", where c
                is the first character of the value of the IFS variable.

In other words, all shell arguments would be concatenated into a single command argument for your Java application, ignoring the original word boundaries.

Refer to the bash or sh manual ... or the POSIX shell spec ... for more information on how the shell handles quoting.

Body:
Assuming that you are using a shell that is compatible with the Bourne shell; e.g. sh, bash, ksh, etc, the following wrapper will pass all command line arguments to the java command:

#!/bin/sh
OPTS=...
java $OPTS com.example.YourApp "$@"

The $@ expands to the remaining arguments for the shell script, and putting quotes around it causes the arguments to be individually quoted, so that the following will pass a single argument to Java:

$ wrapper "/home/person/Stupid Directory Name/foo.txt"

Without the double quotes around "$@" in the wrapper script, Java would receive three arguments for the above.

Note that this does not work with "$*".  According to the bash manual entry:

"$*" is equivalent to "$1c$2c...", where c
                is the first character of the value of the IFS variable.

In other words, all shell arguments would be concatenated into a single command argument for your Java application, ignoring the original word boundaries.

Refer to the bash or sh manual ... or the POSIX shell spec ... for more information on how the shell handles quoting.

ContentLicense: CC BY-SA 4.0


问:
ASP.net Core MVC 2.0 Passing FormEditModel from view to controller

Hello, i am doing a simple blog using Microsoft asp.net MVC Core 2.0 for a school project and have encountered a problem while implementing CRUD operations for Articles. More precisely i have an issue only with the edit article method.
Here is my controller method

```<code>[HttpPost]
[ValidateModelState]
     public async Task<IActionResult> EditArticle(ArticleEditServiceModel parameter)
        {
            parameter.Title = this.html.Sanitize(parameter.Title);
            parameter.Content = this.html.Sanitize(parameter.Content);

            //var user = this.userManager.GetUserName(User.Identity.Name)

            await this.articles.EditAsync(parameter.Id, parameter.Title, parameter.Content);

            return RedirectToAction(nameof(Index));
        }
</code>```

And here is my service "EditAsync" method:

```<code>public async Task<bool> EditAsync(int id, string title, string content)
        {
            var article = await this.db.Articles.Where(a => a.Id == id).FirstOrDefaultAsync();

            if (article == null)
            {
                return false;
            }

            article.Title = title;
            article.Content = content;

            await this.db.SaveChangesAsync();
            return true;
        }
</code>```

The View:

```<code>@model ArticleEditServiceModel

@{
    ViewData["Title"] = "Edit Article";
}

<h2>@ViewData["Title"]</h2>

<div class="row">
    <div class="col-md-4">
        <form asp-controller="Article" asp-action="EditArticle"  asp-route-parameter=@Model method="post">
            <div class="form-group">
                <label asp-for="Title"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="form-text text-danger"></span>
            </div>

            <div class="form-group">
                <label asp-for="Content"></label>
                <input asp-for="Content"  required class="form-control" />
                <span asp-validation-for="Content" class="form-text text-danger"></span>
            </div>
            <a asp-controller="Article" asp-action="Index" class="btn btn-default">Back</a>
            <button type="submit" formmethod="post" class="btn btn-success">Edit Article</button>
        </form>
    </div>
</div>

@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}
</code>```

It finds the correct article by Id and gives me the two input fields where i can edit the text, but when i click the submit button there are no changes applied to the Article. I tried debugging and found out that the view send a null model to the controller post method. I can't seem to find what's wrong with the code so i figured i should ask more experienced developers for input.

答:
I tried debugging and found out that the view send a null model to the
  controller post method.

I believe the view sends correct request but error happens during model binding on server side.

To fix the problem, you should add [FromBody] attribute for ArticleEditServiceModel parameter in controller action:

```<code>public async Task<IActionResult> EditArticle([FromBody] ArticleEditServiceModel parameter)
</code>```

FromBody attribute instructs ASP.NET Core framework that action parameter should be deserialized from request body with media type formatter based on Content-Type http header. Check this article for details, it explains the difference in model binding between ASP.NET MVC and ASP.NET Core MVC.

Body:
Hello, i am doing a simple blog using Microsoft asp.net MVC Core 2.0 for a school project and have encountered a problem while implementing CRUD operations for Articles. More precisely i have an issue only with the edit article method.
Here is my controller method

[HttpPost]
[ValidateModelState]
     public async Task<IActionResult> EditArticle(ArticleEditServiceModel parameter)
        {
            parameter.Title = this.html.Sanitize(parameter.Title);
            parameter.Content = this.html.Sanitize(parameter.Content);

            //var user = this.userManager.GetUserName(User.Identity.Name)

            await this.articles.EditAsync(parameter.Id, parameter.Title, parameter.Content);

            return RedirectToAction(nameof(Index));
        }

And here is my service "EditAsync" method:

public async Task<bool> EditAsync(int id, string title, string content)
        {
            var article = await this.db.Articles.Where(a => a.Id == id).FirstOrDefaultAsync();

            if (article == null)
            {
                return false;
            }

            article.Title = title;
            article.Content = content;

            await this.db.SaveChangesAsync();
            return true;
        }

The View:

@model ArticleEditServiceModel

@{
    ViewData["Title"] = "Edit Article";
}

@ViewData["Title"]

        <form asp-controller="Article" asp-action="EditArticle"  asp-route-parameter=@Model method="post">

                <input asp-for="Title" class="form-control" />

                <input asp-for="Content"  required class="form-control" />

            Back
            <button type="submit" formmethod="post" class="btn btn-success">Edit Article</button>
        </form>

@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
}

It finds the correct article by Id and gives me the two input fields where i can edit the text, but when i click the submit button there are no changes applied to the Article. I tried debugging and found out that the view send a null model to the controller post method. I can't seem to find what's wrong with the code so i figured i should ask more experienced developers for input.

Body:
I tried debugging and found out that the view send a null model to the
  controller post method.

I believe the view sends correct request but error happens during model binding on server side.

To fix the problem, you should add [FromBody] attribute for ArticleEditServiceModel parameter in controller action:

public async Task<IActionResult> EditArticle([FromBody] ArticleEditServiceModel parameter)

FromBody attribute instructs ASP.NET Core framework that action parameter should be deserialized from request body with media type formatter based on Content-Type http header. Check this article for details, it explains the difference in model binding between ASP.NET MVC and ASP.NET Core MVC.


问:
How to handle complicated input form in Python according PHP approach?
I have got the following HTML form with several complicated input elements:

```<code><input type="text" name="images[1]">
<input type="text" name="images[2]">
<input type="text" name="video[1]">
<input type="text" name="video[2]">
</code>```

When I talk about cimplicated inputs I mean sophisticated name of elements:

```<code>name="images[1]"
</code>```

Where images is indicate group of input and [1] number or identificator of input.

Using PHP approach of handling form It can be achieved like:

```<code>if(isset($_POST['images'])) {
    foreach($_POST['images'] as $index) { // $key
         echo $_POST['images'][$index]; // or key
    }
}
</code>```

How to reproduce this in Python?

答:
It is easy with  HTMLParser.

Take a look at this example.

```<code>from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Start tag:", tag
        for attr in attrs:
            print "     attr:", attr

    def handle_endtag(self, tag):
        print "End tag  :", tag

    def handle_data(self, data):
        print "Data     :", data

    def handle_comment(self, data):
        print "Comment  :", data

    def handle_entityref(self, name):
        c = unichr(name2codepoint[name])
        print "Named ent:", c

    def handle_decl(self, data):
        print "Decl     :", data

parser = MyHTMLParser()

parser.feed('<input type="text" name="images[1]">')
</code>```

Than you have

```<code>python a1.py
Start tag: input
     attr: ('type', 'text')
     attr: ('name', 'images[1]')
</code>```

Body:
I have got the following HTML form with several complicated input elements:

<input type="text" name="images[1]">
<input type="text" name="images[2]">
<input type="text" name="video[1]">
<input type="text" name="video[2]">

When I talk about cimplicated inputs I mean sophisticated name of elements:

name="images[1]"

Where images is indicate group of input and [1] number or identificator of input.

Using PHP approach of handling form It can be achieved like:

if(isset($_POST['images'])) {
    foreach($_POST['images'] as $index) { // $key
         echo $_POST['images'][$index]; // or key
    }
}

How to reproduce this in Python?

Body:
It is easy with  HTMLParser.

Take a look at this example.

from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Start tag:", tag
        for attr in attrs:
            print "     attr:", attr

    def handle_endtag(self, tag):
        print "End tag  :", tag

    def handle_data(self, data):
        print "Data     :", data

    def handle_comment(self, data):
        print "Comment  :", data

    def handle_entityref(self, name):
        c = unichr(name2codepoint[name])
        print "Named ent:", c

    def handle_decl(self, data):
        print "Decl     :", data

parser = MyHTMLParser()

parser.feed('<input type="text" name="images[1]">')

Than you have

python a1.py
Start tag: input
     attr: ('type', 'text')
     attr: ('name', 'images[1]')


问:
Accessing object's property inside generic method
How can access the property of an object inside generic method?

I can't use where T: A because this method will receive different objects, but all objects have a common property to work on.

(I also can't make for them a common interface)

```<code>public class A
{
    public int Number {get;set;}
}

List<A> listA = new List<A>{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work<A>(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}
</code>```

An update: I need also to set the property

答:
You have a few choices:

Make a common interface.

Use reflection.

Use the dynamic type in .NET 4.

I know you said you can't do the first, but it's the best option for performance and maintainability so please reconsider if its possible before choosing one of the other methods. Remember that even if you can't modify the original code you might still be able to choose the first option. For example if your classes are partial classes you can implement the interface in another file:

File 1:

```<code>// Automatically generated code that you can't change.
partial class A
{
    public int Number { get; set; }
}
</code>```

File 2:

```<code>interface IHasNumber
{
    int Number { get; set; }
}

partial class A : IHasNumber
{
}
</code>```

If the original class isn't defined as partial you could write wrapper classes around them that implement the interface.

Once you have the common interface you can change your generic constraint to require this interface:

```<code>where T : IHasNumber
</code>```

Body:
How can access the property of an object inside generic method?

I can't use where T: A because this method will receive different objects, but all objects have a common property to work on.

(I also can't make for them a common interface)

public class A
{
    public int Number {get;set;}
}

List listA = new List{
                new A {Number =4},
                new A {Number =1},
                new A {Number =5}
};

Work(listA);

public static void Work<T>(List<T> list1)
{
    foreach(T item in list1)
    {
        do something with item.Number;
    }
}

An update: I need also to set the property

Body:
You have a few choices:

Make a common interface.

Use reflection.

Use the dynamic type in .NET 4.

I know you said you can't do the first, but it's the best option for performance and maintainability so please reconsider if its possible before choosing one of the other methods. Remember that even if you can't modify the original code you might still be able to choose the first option. For example if your classes are partial classes you can implement the interface in another file:

File 1:

// Automatically generated code that you can't change.
partial class A
{
    public int Number { get; set; }
}

File 2:

interface IHasNumber
{
    int Number { get; set; }
}

partial class A : IHasNumber
{
}

If the original class isn't defined as partial you could write wrapper classes around them that implement the interface.

Once you have the common interface you can change your generic constraint to require this interface:

where T : IHasNumber


问:
How to take a screenshot of a current Activity and then share it?
I need to take a screenshot of Activity (without the title bar, and the user should NOT see that a screenshot has actually been taken) and then share it via an action menu button "share". I have already tried some solutions, but they didn't work for me. Any ideas?

答:
This is what I use to take a screenshot. The solutions described above work fine for API < 24, but for API 24 and greater another solution is needed. I've tested this method on API 15, 24, & 27.

I placed the following methods in MainActivity.java:

```<code>public class MainActivity {

...

String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
View sshotView;

...

private boolean checkPermission() {
List arrayList = new ArrayList();
for (String str : this.permissions) {
if (ContextCompat.checkSelfPermission(this, str) != 0) {
arrayList.add(str);
}
}
if (arrayList.isEmpty()) {
return true;
}
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[arrayList.size()]), 100);
return false;
}

protected void onCreate(Bundle savedInstanceState) {
...

this.sshotView = getWindow().getDecorView().findViewById(R.id.parent);
...

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
switch (id) {

case R.id.action_shareScreenshot:
boolean checkPermission = checkPermission();
Bitmap screenShot = getScreenShot(this.sshotView);
if (!checkPermission) {
return true;
}
shareScreenshot(store(screenShot));
return true;

case R.id.option2:
...
return true;
}

return false;
}

private void shareScreenshot(File file) {
Parcelable fromFile = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".com.redtiger.applehands.provider", file);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setAction("android.intent.action.SEND");
intent.setType("image/*");
intent.putExtra("android.intent.extra.SUBJECT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.TEXT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.STREAM", fromFile);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Communication Platform Available", Toast.LENGTH_SHORT).show();
}
}

public static Bitmap getScreenShot(View view) {
View rootView = view.getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap createBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
return createBitmap;

public File store(Bitmap bitmap) {
String str = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Screenshots";
File file = new File(str);
if (!file.exists()) {
file.mkdirs();
}
file = new File(str + "/sshot.png");
try {
OutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "External Storage Permission Is Required", Toast.LENGTH_LONG).show();
}
return file;
}
}
</code>```

I placed the following permissions and provider in my AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redtiger.applehands">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

<application

...

<provider
android:name="com.redtiger.applehands.util.GenericFileProvider"
android:authorities="${applicationId}.com.redtiger.applehands.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>

...

</application>

</manifest>
</code>```

I created a file called provider_paths.xml (please see below) to direct the FileProvider where to save the screenshot. The file contains a simple tag that points to the root of the external directory.

The File was placed in the resource folder res/xml (if you don't have an xml folder here, just create one and place your file there).

provider_paths.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
</code>```

Body:
This is what I use to take a screenshot. The solutions described above work fine for API < 24, but for API 24 and greater another solution is needed. I've tested this method on API 15, 24, & 27.

I placed the following methods in MainActivity.java:

public class MainActivity {

...

String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};
View sshotView;

...

private boolean checkPermission() {
List arrayList = new ArrayList();
for (String str : this.permissions) {
if (ContextCompat.checkSelfPermission(this, str) != 0) {
arrayList.add(str);
}
}
if (arrayList.isEmpty()) {
return true;
}
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[arrayList.size()]), 100);
return false;
}

protected void onCreate(Bundle savedInstanceState) {
...

this.sshotView = getWindow().getDecorView().findViewById(R.id.parent);
...

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
switch (id) {

case R.id.action_shareScreenshot:
boolean checkPermission = checkPermission();
Bitmap screenShot = getScreenShot(this.sshotView);
if (!checkPermission) {
return true;
}
shareScreenshot(store(screenShot));
return true;

case R.id.option2:
...
return true;
}

return false;
}

private void shareScreenshot(File file) {
Parcelable fromFile = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".com.redtiger.applehands.provider", file);
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setAction("android.intent.action.SEND");
intent.setType("image/*");
intent.putExtra("android.intent.extra.SUBJECT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.TEXT", XmlPullParser.NO_NAMESPACE);
intent.putExtra("android.intent.extra.STREAM", fromFile);
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Communication Platform Available", Toast.LENGTH_SHORT).show();
}
}

public static Bitmap getScreenShot(View view) {
View rootView = view.getRootView();
rootView.setDrawingCacheEnabled(true);
Bitmap createBitmap = Bitmap.createBitmap(rootView.getDrawingCache());
rootView.setDrawingCacheEnabled(false);
return createBitmap;

public File store(Bitmap bitmap) {
String str = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Screenshots";
File file = new File(str);
if (!file.exists()) {
file.mkdirs();
}
file = new File(str + "/sshot.png");
try {
OutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "External Storage Permission Is Required", Toast.LENGTH_LONG).show();
}
return file;
}
}

I placed the following permissions and provider in my AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redtiger.applehands">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

<application

...

<provider
android:name="com.redtiger.applehands.util.GenericFileProvider"
android:authorities="${applicationId}.com.redtiger.applehands.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>

...

</application>

</manifest>

I created a file called provider_paths.xml (please see below) to direct the FileProvider where to save the screenshot. The file contains a simple tag that points to the root of the external directory.

The File was placed in the resource folder res/xml (if you don't have an xml folder here, just create one and place your file there).

provider_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>


问:
variable initialization using class member function
Why the head is not NULL at the beginning if I initialized it with the class member function? It is a tricky part.

```<code>#include <iostream>
using namespace std;

struct node
{
    int data;
    node *next;
};

class linked_list
{
private:
    node *head;
public:

    void push(node *head, int data);
    void printList(node *head);
    void printMiddle(node *head);
    void makeHeadNull(node *head);
};

void linked_list::push(node *head, int data)
{
    node *newNode=new node;
    if(head==NULL)
    {
        head=newNode;
    }
    else {
        newNode->data = data;
        newNode->next = head;
        head = newNode;
    }
}

void linked_list::printMiddle(node *head)
{

        node *slow_ptr = head;
        node *fast_ptr = head;

        if (head!=NULL)
        {
            while (fast_ptr != NULL && fast_ptr->next != NULL)
            {
                fast_ptr = fast_ptr->next->next;
                slow_ptr = slow_ptr->next;
            }
            cout<<slow_ptr->data<<" ";
    }

void linked_list::printList(node *head)
{
    while(head!=NULL)
    {
        cout<<head->data<<" ";
        head=head->next;

    }
}

void linked_list::makeHeadNull(node *head)
{
    head=NULL;
}

int main()
{
    node *head;
    linked_list l;
    l.makeHeadNull(head);

    l.push(head, 0);
    l.push(head, 1);
    l.push(head, 2);
    l.push(head, 3);
    l.push(head, 4);

    l.printMiddle(head);
}
</code>```

I wanted to initialize head inside a constructor, but when I initialized head like that, the head node has always been NULL inside main. When I initialize head in the constructor and then I want to pass it as a parameter of a function push I get errors.

答:
why the head is not NULL at the beginning if I initialized it with the class member function.

You never use that member variable. Instead you pass head that is local variable in main and you've left that variable uninitialized.

Note that your push neither modifies the member head nor does it modify the local variable in main. head = newNode; modifies the variable that is local to the member function which is destroyed when the function returns making the assignment pointless.

I suspect that your intention was to modify either the member, or the pointer passed to the function. To modify the passed pointer, pass a reference to it. To modify the member variable, use this-> or don't hide the member with a local variable with the same name.

Body:
Why the head is not NULL at the beginning if I initialized it with the class member function? It is a tricky part.

#include <iostream>
using namespace std;

struct node
{
    int data;
    node *next;
};

class linked_list
{
private:
    node *head;
public:

    void push(node *head, int data);
    void printList(node *head);
    void printMiddle(node *head);
    void makeHeadNull(node *head);
};

void linked_list::push(node *head, int data)
{
    node *newNode=new node;
    if(head==NULL)
    {
        head=newNode;
    }
    else {
        newNode->data = data;
        newNode->next = head;
        head = newNode;
    }
}

void linked_list::printMiddle(node *head)
{

        node *slow_ptr = head;
        node *fast_ptr = head;

        if (head!=NULL)
        {
            while (fast_ptr != NULL && fast_ptr->next != NULL)
            {
                fast_ptr = fast_ptr->next->next;
                slow_ptr = slow_ptr->next;
            }
            cout<<slow_ptr->data<<" ";
    }

void linked_list::printList(node *head)
{
    while(head!=NULL)
    {
        cout<data<<" ";
        head=head->next;

    }
}

void linked_list::makeHeadNull(node *head)
{
    head=NULL;
}

int main()
{
    node *head;
    linked_list l;
    l.makeHeadNull(head);

    l.push(head, 0);
    l.push(head, 1);
    l.push(head, 2);
    l.push(head, 3);
    l.push(head, 4);

    l.printMiddle(head);
}

I wanted to initialize head inside a constructor, but when I initialized head like that, the head node has always been NULL inside main. When I initialize head in the constructor and then I want to pass it as a parameter of a function push I get errors.


问:
Loop over both the x-axis and y-axis variables in ggplot list and print plots
I went through this question but it only loops through the x-axis, how can I loop through both x and y axis. I tried it as follows but it does not print each plot in grid:
Thanks!

For example I have a dataframe:

```<code>t <- data.frame(w = c(1, 2, 3, 4), x = c(23,45,23, 34),
                y = c(23,34,54, 23), z = c(23,12,54, 32))
</code>```

Function to get common legend on the right:

```<code> grid_arrange_shared_legend <- function(...) {
      plots <- list(...)
      g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
      legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
      lw <- sum(legend$width)
      gl <- lapply(plots, function(x) x + theme(legend.position="none"))
      grid.arrange(arrangeGrob(grobs = gl), legend,
                   ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
    }
</code>```

Actual plotting loop:

```<code>qual = c("w", "x")
for(q in qual){
  p = lapply(list("y", "z"), function(l) ggplot(t, aes_string(x=l, y=q)) +
               geom_point(aes(col=plate_name), size=2.0) +
               xlab(l) + ylab(q) +
               geom_smooth(method="lm") +
               scale_color_brewer(palette = "Paired") +
               theme_bw())
  #pdf("x_vs_y_gg.pdf", h=3.5*3, w=14)
  print(grid_arrange_shared_legend(p[[1]], p[[2]], p[[3]], p[[4]], p[[5]], p[[6]], p[[7]], p[[8]]))
  }
</code>```

答:
What about this ?

```<code>library(ggplot2)
library(gridExtra)

t <- data.frame(w = c(1, 2, 3, 4), x = c(23,45,23, 34),
                y = c(23,34,54, 23), z = c(23,12,54, 32),
                plate_name=LETTERS[1:4])

 grid_arrange_shared_legend <- function(plots) {
      g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
      legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
      lw <- sum(legend$width)
      gl <- lapply(plots, function(x) x + theme(legend.position="none"))
      grid.arrange(arrangeGrob(grobs = gl), legend,
                   ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
    }

myfun <- function(l,q) ggplot(t, aes(x=get(l), y=get(q))) +
               geom_point(aes(col=plate_name), size=2.0) +
               xlab(l) + ylab(q) +
               geom_smooth(method="lm") +
               scale_color_brewer(palette = "Paired") +
               theme_bw()

cmb <- combn(names(t)[-ncol(t)],2)
lst <- mapply(myfun, cmb[1,], cmb[2,], SIMPLIFY = F)

grid_arrange_shared_legend(lst)
</code>```

Body:
I went through this question but it only loops through the x-axis, how can I loop through both x and y axis. I tried it as follows but it does not print each plot in grid:
Thanks!

For example I have a dataframe:

t <- data.frame(w = c(1, 2, 3, 4), x = c(23,45,23, 34),
                y = c(23,34,54, 23), z = c(23,12,54, 32))

Function to get common legend on the right:

 grid_arrange_shared_legend <- function(...) {
      plots <- list(...)
      g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
      legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
      lw <- sum(legend$width)
      gl <- lapply(plots, function(x) x + theme(legend.position="none"))
      grid.arrange(arrangeGrob(grobs = gl), legend,
                   ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
    }

Actual plotting loop:

qual = c("w", "x")
for(q in qual){
  p = lapply(list("y", "z"), function(l) ggplot(t, aes_string(x=l, y=q)) +
               geom_point(aes(col=plate_name), size=2.0) +
               xlab(l) + ylab(q) +
               geom_smooth(method="lm") +
               scale_color_brewer(palette = "Paired") +
               theme_bw())
  #pdf("x_vs_y_gg.pdf", h=3.5*3, w=14)
  print(grid_arrange_shared_legend(p[[1]], p[[2]], p[[3]], p[[4]], p[[5]], p[[6]], p[[7]], p[[8]]))
  }

Body:
What about this ?

library(ggplot2)
library(gridExtra)

t <- data.frame(w = c(1, 2, 3, 4), x = c(23,45,23, 34),
                y = c(23,34,54, 23), z = c(23,12,54, 32),
                plate_name=LETTERS[1:4])

 grid_arrange_shared_legend <- function(plots) {
      g <- ggplotGrob(plots[[1]] + theme(legend.position="right"))$grobs
      legend <- g[[which(sapply(g, function(x) x$name) == "guide-box")]]
      lw <- sum(legend$width)
      gl <- lapply(plots, function(x) x + theme(legend.position="none"))
      grid.arrange(arrangeGrob(grobs = gl), legend,
                   ncol = 2, widths = unit.c(unit(1, "npc") - lw, lw))
    }

myfun <- function(l,q) ggplot(t, aes(x=get(l), y=get(q))) +
               geom_point(aes(col=plate_name), size=2.0) +
               xlab(l) + ylab(q) +
               geom_smooth(method="lm") +
               scale_color_brewer(palette = "Paired") +
               theme_bw()

cmb <- combn(names(t)[-ncol(t)],2)
lst <- mapply(myfun, cmb[1,], cmb[2,], SIMPLIFY = F)

grid_arrange_shared_legend(lst)


问:
problem with sizeof operator
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result.
here is one demo program to show you, what i want to do.

```<code>//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------
</code>```

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

```<code>array size(in function):2
array size:19
</code>```

please explain ,why this is happening.
what can be done to solve this problem.

答:
To prevent this type of accidental misuse of sizeof, you can define a function which only works on arrays:

```<code>template<class T, int N>
int array_size(T (&)[N]) {
  return N;
}
</code>```

If you use this in your code, you'll see a compiler error when applied to S1, as it is not an array.  Plus, it's shorter and a bit more explicit than sizeof array / sizeof array[0] (using the size of the first item means you don't have to repeat the array type).

This also already exists in Boost in a more general form (accepting anything with a size method, such as std::vector).

Title: problem with sizeof operator

Body:
As i want to find array size dynamically in function, i used sizeof operator. But i got some unexpected result.
here is one demo program to show you, what i want to do.

//------------------------------------------------------------------------------------------
#include <iostream>

void getSize(int *S1){

    int S_size = sizeof S1/sizeof(int);
    std::cout<<"array size(in function):"<<S_size<<std::endl;
}

int main(){

    int S[]={1,2,3,2,5,6,25,1,6,21,121,36,1,31,1,31,1,661,6};
    getSize(S);
    std::cout<<"array size:"<<sizeof S/sizeof(int)<<std::endl;
    return 0;
}
//------------------------------------------------------------------------------------------

compilation command : g++ demo1.cc -o demo1 {fedora 12}

output:

array size(in function):2
array size:19

please explain ,why this is happening.
what can be done to solve this problem.

Body:
To prevent this type of accidental misuse of sizeof, you can define a function which only works on arrays:

template<class T, int N>
int array_size(T (&)[N]) {
  return N;
}

If you use this in your code, you'll see a compiler error when applied to S1, as it is not an array.  Plus, it's shorter and a bit more explicit than sizeof array / sizeof array[0] (using the size of the first item means you don't have to repeat the array type).

This also already exists in Boost in a more general form (accepting anything with a size method, such as std::vector).


问:
Entityframework 6.2.0 IQueryable.Count VS IQueryable.ToList().Count
This is a very weird problem
In short

```<code>var q = (some query).Count();
</code>```

Gives my a number and

```<code>var q = (some query).ToList().Count();
</code>```

Gives me entirely different number...

with mentioning that (some query) has two includes (joins)

is there a sane explanation for that???

EDIT: here is my query

```<code>var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).Count();
</code>```

this gives me a wrong number

and this:

```<code>var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).ToList().Count();
</code>```

Gives me accurate number..

EDIT 2
Wher I wrote my query as linq query it worked perfectly...

```<code>var q1 = (from d in db.membership_renewals where d.isDeleted == false join m in db.members on d.mr_memberId equals m.m_id join s in db.sports on d.mr_sportId equals s.s_id select d.mr_id).Count();
</code>```

I think the problem that entity framework doesn't execute the joins in the original query but forced to execute them in (ToList())...

答:
I Finally figured out what's going on...
The database tables are not linked together in the database (there are no relationship or constraints defined in the database itself) so the code doesn't execute the (inner join) part.
However my classes on the other hand are well written so when I perform (ToList()) it automatically ignores the unbound rows...
And when I wrote the linq query defining the relation ship keys (primary and foreign) it worked alright because now the database understands my relation between tables...
Thanks everyone you've been great....</p>

Body:
This is a very weird problem
In short

var q = (some query).Count();

Gives my a number and

var q = (some query).ToList().Count();

Gives me entirely different number...

with mentioning that (some query) has two includes (joins)

is there a sane explanation for that???

EDIT: here is my query

var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).Count();

this gives me a wrong number

and this:

var q = db.membership_renewals.Include(i => i.member).Include(i => i.sport).Where(w => w.isDeleted == false).ToList().Count();

Gives me accurate number..

EDIT 2
Wher I wrote my query as linq query it worked perfectly...

var q1 = (from d in db.membership_renewals where d.isDeleted == false join m in db.members on d.mr_memberId equals m.m_id join s in db.sports on d.mr_sportId equals s.s_id select d.mr_id).Count();

I think the problem that entity framework doesn't execute the joins in the original query but forced to execute them in (ToList())...


问:
Can I server the Rancher Server through a hosted Traefik container?
I have a single dedicated server where I have installed a Rancher server and a Rancher client and is used to host some dockerized services.

I have succesfully installed Traefik and it is configured with the Rancher API backend, and it reverse proxies my services, hosting them behind HTTPS and everything is working fine.

But I still access my Rancher server through htttp://12.34.56.78:8080.  I would like to also put the Rancher server behind Traefik with https enabled too.

I tried starting the Rancher server with:

```<code>sudo docker run -d \
  -v /data/rancher/server/data:/var/lib/mysql \
  --restart=unless-stopped \
  -p 8080:8080 \
  -l traefik.frontend.rule=Host:rancher.mydomainname.com \
  -l traefik.enable=true \
  -l traefik.backend=rancher \
  -l traefik.default.protocol=http \
  -l traefik.port=8080 \
  rancher/server:v1.6.12
</code>```

(the same way I configured all my other services) but it is not picked up by Traefik because (I think) the Rancher Server does NOT appear in the Rancher API requests that Traefik is monitoring (since Rancher server is started outside Rancher and not hosted by it).

Coming from Rancher Active Proxy, this is something that it was supported by that tool

If my reasoning is correct, that Traefik cannot "pick up" the Rancher server that way, an alternative solution I was thinking was that maybe I would have to create a separate [file] section solely for the Rancher server and add it to the Traefik .toml file...

Is this the correct approach to achieve what I want, or is there some better way of doing this...?

Thanks!

答:
Partially, answering my question...

Creating a separate static rancherserver.toml file:

```<code>[backends]
[backends.rancherserver]
    [backends.rancherserver.servers.server1]
    url = "http://12.34.56.78:8080"
    weight = 10

[frontends]
[frontends.rancherserver]
backend = "rancherserver"
passHostHeader = true
entrypoints = ["https"]
    [frontends.rancherserver.routes.onlyone]
    rule = "Host:rancher.mydomain.com"
</code>```

(where 12.34.56.78 is the real physical IP address ofthe physical server) seems that solves my problem, able to access the Rancher server at htttps://rancher.mydomain.com (with automatic forward from http to https)

BUT for some reason, I'm still able to access the Rancher server from htttp://12.34.56.78:8080 (note, this is not https) although the physical server has firewalled all ports (ufw on Ubuntu) except 80 and 433 (and some others):

```<code>me@server:~$ sudo ufw status verbose
[sudo] password for me:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22                         ALLOW IN    Anywhere
443                        ALLOW IN    Anywhere
80                         ALLOW IN    Anywhere
1143                       ALLOW IN    Anywhere
1110                       ALLOW IN    Anywhere
Anywhere on docker0        ALLOW IN    Anywhere
22 (v6)                    DENY IN     Anywhere (v6)
443 (v6)                   ALLOW IN    Anywhere (v6)
80 (v6)                    ALLOW IN    Anywhere (v6)
1143 (v6)                  ALLOW IN    Anywhere (v6)
1110 (v6)                  ALLOW IN    Anywhere (v6)
Anywhere (v6) on docker0   ALLOW IN    Anywhere (v6)
</code>```

So, I still think I'm misusing Traefik somewhow and allowing the 8080 port to leak trough my Traefik configuration... :(

Body:
I have a single dedicated server where I have installed a Rancher server and a Rancher client and is used to host some dockerized services.

I have succesfully installed Traefik and it is configured with the Rancher API backend, and it reverse proxies my services, hosting them behind HTTPS and everything is working fine.

But I still access my Rancher server through htttp://12.34.56.78:8080.  I would like to also put the Rancher server behind Traefik with https enabled too.

I tried starting the Rancher server with:

sudo docker run -d \
  -v /data/rancher/server/data:/var/lib/mysql \
  --restart=unless-stopped \
  -p 8080:8080 \
  -l traefik.frontend.rule=Host:rancher.mydomainname.com \
  -l traefik.enable=true \
  -l traefik.backend=rancher \
  -l traefik.default.protocol=http \
  -l traefik.port=8080 \
  rancher/server:v1.6.12

(the same way I configured all my other services) but it is not picked up by Traefik because (I think) the Rancher Server does NOT appear in the Rancher API requests that Traefik is monitoring (since Rancher server is started outside Rancher and not hosted by it).

Coming from Rancher Active Proxy, this is something that it was supported by that tool

If my reasoning is correct, that Traefik cannot "pick up" the Rancher server that way, an alternative solution I was thinking was that maybe I would have to create a separate [file] section solely for the Rancher server and add it to the Traefik .toml file...

Is this the correct approach to achieve what I want, or is there some better way of doing this...?

Thanks!

Body:
Partially, answering my question...

Creating a separate static rancherserver.toml file:

[backends]
[backends.rancherserver]
    [backends.rancherserver.servers.server1]
    url = "http://12.34.56.78:8080"
    weight = 10

[frontends]
[frontends.rancherserver]
backend = "rancherserver"
passHostHeader = true
entrypoints = ["https"]
    [frontends.rancherserver.routes.onlyone]
    rule = "Host:rancher.mydomain.com"

(where 12.34.56.78 is the real physical IP address ofthe physical server) seems that solves my problem, able to access the Rancher server at htttps://rancher.mydomain.com (with automatic forward from http to https)

BUT for some reason, I'm still able to access the Rancher server from htttp://12.34.56.78:8080 (note, this is not https) although the physical server has firewalled all ports (ufw on Ubuntu) except 80 and 433 (and some others):

me@server:~$ sudo ufw status verbose
[sudo] password for me:
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22                         ALLOW IN    Anywhere
443                        ALLOW IN    Anywhere
80                         ALLOW IN    Anywhere
1143                       ALLOW IN    Anywhere
1110                       ALLOW IN    Anywhere
Anywhere on docker0        ALLOW IN    Anywhere
22 (v6)                    DENY IN     Anywhere (v6)
443 (v6)                   ALLOW IN    Anywhere (v6)
80 (v6)                    ALLOW IN    Anywhere (v6)
1143 (v6)                  ALLOW IN    Anywhere (v6)
1110 (v6)                  ALLOW IN    Anywhere (v6)
Anywhere (v6) on docker0   ALLOW IN    Anywhere (v6)

So, I still think I'm misusing Traefik somewhow and allowing the 8080 port to leak trough my Traefik configuration... :(


答:
fscanf() is like scanf(), instead of scanning from user you are trying to scan from file but after scanning where you are storing ? ItemI[i] should be &ItemI[i] isn't it ?

```<code> while(fscanf(f,"%d%d%d",&ItemI[i],&ItemQ[i],&Price[i])>0){
                ++i;
</code>```

Edit : I think you want output in one way but you wrote in different way So I edited your code.

```<code>int DisplayItemInfoForAParticularItem(){
        FILE* f = fopen("items.txt", "r");
        if(f == 0) {
                printf("file is not present :\n");
                return 0;
        }
        int ItemID,ItemQuantity,PricePerUnit, i = 0,flag = 0;
        int ItemI[10], ItemQ[10],Price[10];

        while(fscanf(f,"%d%d%d",&ItemI[i],&ItemQ[i],&Price[i])>0){
                ++i;
        }

        for(i=0; i<10; i++)
        {
                printf("Enter itemID: ");
                scanf("%d",&ItemID);
                if(ItemI[i]==ItemID)
                {
                        flag = 1;
                        printf("ItemID  Quantity    Price Per Unit (SAR)\n");
                        printf("%d  %d  %d\n",ItemI[i],ItemQ[i],Price[i]);
                        break;
                }
                if(flag==0)
                {
                        printf("Error: Invalid item ID");
                }
        }
        fclose(f);
        return ;
}
</code>```

I hope it helps.

Title: about Search in Arrays

Body:
...........................................................................................................................................................
Hi everyone i got a little problem when i search for element in arrays
when i enter the number like 1007 he give me Error: Invalid item ID all the time

this is Myfile

1007 5 30

1004 4 10

1003 3 20

And this is my function

void DisplayItemInfoForAParticularItem(){
    FILE* f = fopen("items.txt", "r");
    int ItemID,ItemQuantity,PricePerUnit, i = 0,flag = 0;
    int ItemI[10], ItemQ[10],Price[10];

    while(fscanf(f,"%d%d%d",ItemI[i],ItemQ[i],Price[i]) != EOF){
        ++i;
    }
    printf("Enter itemID: ");
    scanf("%d",&ItemID);
    for(i=0; i<10; i++)
    {

        if(ItemI[i]==ItemID)
        {
            flag = 1;
            printf("ItemID  Quantity    Price Per Unit (SAR)");
            printf("%d  %d  %d",ItemI[i],ItemQ[i],Price[i]);
            break;
        }
    }
    if(flag==0)
    {
         printf("Error: Invalid item ID");
    }

    fclose(f);
   return ;
}

thank you for your help ............................................................................................................................................................................................................................................................................................................

Body:
fscanf() is like scanf(), instead of scanning from user you are trying to scan from file but after scanning where you are storing ? ItemI[i] should be &ItemI[i] isn't it ?

 while(fscanf(f,"%d%d%d",&ItemI[i],&ItemQ[i],&Price[i])>0){
                ++i;

Edit : I think you want output in one way but you wrote in different way So I edited your code.

int DisplayItemInfoForAParticularItem(){
        FILE* f = fopen("items.txt", "r");
        if(f == 0) {
                printf("file is not present :\n");
                return 0;
        }
        int ItemID,ItemQuantity,PricePerUnit, i = 0,flag = 0;
        int ItemI[10], ItemQ[10],Price[10];

        while(fscanf(f,"%d%d%d",&ItemI[i],&ItemQ[i],&Price[i])>0){
                ++i;
        }

        for(i=0; i<10; i++)
        {
                printf("Enter itemID: ");
                scanf("%d",&ItemID);
                if(ItemI[i]==ItemID)
                {
                        flag = 1;
                        printf("ItemID  Quantity    Price Per Unit (SAR)\n");
                        printf("%d  %d  %d\n",ItemI[i],ItemQ[i],Price[i]);
                        break;
                }
                if(flag==0)
                {
                        printf("Error: Invalid item ID");
                }
        }
        fclose(f);
        return ;
}

I hope it helps.


问:
I cannot center my header in the middle
I'm trying to get my header with ul in the center. Another page suggested having overflow:hidden  but when I shrink the window, a second scroll bar still appears.

Every time I try something, the li isn't in line with my logo.
Also tried to have the class 'container' margin: auto but nothing happens.

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
}

/*Global styling */

.container {
  width: 100%;
  overflow: visible;
}

ul {
  margin: 0;
  padding: 0;
}

/*Header*/

header {
  background: #100806;
  color: #f2f2f2;
  min-height: 75px;
  border-bottom: #ffffff 3px solid;
  text-align: center;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 15px;
}

header li {
  display: inline-block;
  padding: 0 30px 10px 0;
  float: left;
}

header .center-logo img {
  width: 100px;
  padding-left: 30px;
  padding-right: 30px;
}

header nav span {
  float: left;
}

header nav span:first-child {
  padding-right: 50px;
  /* half the logo width */
  padding-top: 20px;
}

header nav span:last-child {
  padding-left: 50px;
  padding-top: 20px;
  /* half the logo width */
}

header .highlight,
header .current a {
  color: #e8491d;
  font-weight: bold;
}

header a:hover {
  color: #666666;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">
    <nav>
      <ul>
        <span>
          <li class="current"> Home</li>
          <li> Photography</li>
        </span>
        <div class="center-logo">
          <li><img src="https://placehold.it/100x50"></li>
        </div>
        <span>
          <li> Biography</li>
          <li> Contact Us</li>
        </span>
      </ul>
    </nav>
  </div>
</header></code>```

答:
The Issue

float rules declared on the list-items (li)

Consider removing the float rules declared on list-items, this will negate any attempt at horizontally center aligning your menu items using typical methods other than flex-box.

The Fix

text-align: center (on containing element)

display: inline-block (on nested elements to center)

Since there is text-align: center rule already declared on a containing parent element (header in this case), and the list-items have already been declared as inline-block items, the list-item elements will center after removing the float rules declared on them.

Further Concerns:

The only direct descendant elements of an unordered (ul) or ordered (ol) list should be list-items (li) - any element other than this would be considered invalid markup.

Code Snippet Demonstration: (view "Full Page")

Summary:

Markup cleaned/simplified

Invalid list elements removed (direct descendants)

Styles improved (omitting redundant rules, vertically centering
navigation)

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
}

/*Global styling */

.container {
  width: 100%;
  overflow: visible;
}

ul {
  margin: 0;
  padding: 0;
}

/*Header*/

header {
  background: #100806;
  color: #f2f2f2;
  min-height: 75px;
  border-bottom: #ffffff 3px solid;
  text-align: center;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 15px;
}

header li {
  display: inline-block;
  padding: 0 30px 0 0; /* remove the bottom padding */
  /* float removed */
  vertical-align: middle; /* additional */
}

/* Additional */

li.logo {
    padding-left: 50px;
    padding-right: 50px;
}

header nav > ul { /* using the "child combinator" here (>) so that this rule doesn't apply to any dropdown or sub-menus */
    padding: 10px 0 10px 0;
}

/*
header .center-logo img {
  width: 100px;
  padding-left: 30px;
  padding-right: 30px;
}

header nav span {
  float: left;
}

header nav span:first-child {
  padding-right: 50px;
  padding-top: 20px;
}

header nav span:last-child {
  padding-left: 50px;
  padding-top: 20px;
}
*/

header .highlight,
header .current a {
  color: #e8491d;
  font-weight: bold;
}

header a:hover {
  color: #666666;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    <ul>
      <li class="current"> Home</li>
      <li> Photography</li>
      <li class="logo"><img src="https://placehold.it/100x50"></li>
      <li> Biography</li>
      <li> Contact Us</li>
    </ul>
  </nav>
</header>

<!--

Change Log:

1) Invalid nested elements removed from list (span & div)
2) Superfluous ".container" containing element removed (as providing no tangible benefits)

--></code>```

Practical Demonstrations for Further Reference:

Horizontal Alignment (Text Elements)

Horizontal Alignment (Arbitrary Elements)

Title: I cannot center my header in the middle

Body:
I'm trying to get my header with ul in the center. Another page suggested having overflow:hidden  but when I shrink the window, a second scroll bar still appears.

Every time I try something, the li isn't in line with my logo.
Also tried to have the class 'container' margin: auto but nothing happens.

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
}

/*Global styling */

.container {
  width: 100%;
  overflow: visible;
}

ul {
  margin: 0;
  padding: 0;
}

/*Header*/

header {
  background: #100806;
  color: #f2f2f2;
  min-height: 75px;
  border-bottom: #ffffff 3px solid;
  text-align: center;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 15px;
}

header li {
  display: inline-block;
  padding: 0 30px 10px 0;
  float: left;
}

header .center-logo img {
  width: 100px;
  padding-left: 30px;
  padding-right: 30px;
}

header nav span {
  float: left;
}

header nav span:first-child {
  padding-right: 50px;
  /* half the logo width */
  padding-top: 20px;
}

header nav span:last-child {
  padding-left: 50px;
  padding-top: 20px;
  /* half the logo width */
}

header .highlight,
header .current a {
  color: #e8491d;
  font-weight: bold;
}

header a:hover {
  color: #666666;
  font-weight: bold;
}

 Home

 Photography

 Biography

 Contact Us

Body:
The Issue

float rules declared on the list-items (li)

Consider removing the float rules declared on list-items, this will negate any attempt at horizontally center aligning your menu items using typical methods other than flex-box.

The Fix

text-align: center (on containing element)

display: inline-block (on nested elements to center)

Since there is text-align: center rule already declared on a containing parent element (header in this case), and the list-items have already been declared as inline-block items, the list-item elements will center after removing the float rules declared on them.

Further Concerns:

The only direct descendant elements of an unordered (ul) or ordered (ol) list should be list-items (li) - any element other than this would be considered invalid markup.

Code Snippet Demonstration: (view "Full Page")

Summary:

Markup cleaned/simplified

Invalid list elements removed (direct descendants)

Styles improved (omitting redundant rules, vertically centering
navigation)

body {
  font: 15px/1.5 Arial, Helvetica, sans-serif;
  padding: 0;
  margin: 0;
  background-color: #f4f4f4;
}

/*Global styling */

.container {
  width: 100%;
  overflow: visible;
}

ul {
  margin: 0;
  padding: 0;
}

/*Header*/

header {
  background: #100806;
  color: #f2f2f2;
  min-height: 75px;
  border-bottom: #ffffff 3px solid;
  text-align: center;
}

header a {
  color: #ffffff;
  text-decoration: none;
  text-transform: uppercase;
  font-size: 15px;
}

header li {
  display: inline-block;
  padding: 0 30px 0 0; /* remove the bottom padding */
  /* float removed */
  vertical-align: middle; /* additional */
}

/* Additional */

li.logo {
    padding-left: 50px;
    padding-right: 50px;
}

header nav > ul { /* using the "child combinator" here (>) so that this rule doesn't apply to any dropdown or sub-menus */
    padding: 10px 0 10px 0;
}

/*
header .center-logo img {
  width: 100px;
  padding-left: 30px;
  padding-right: 30px;
}

header nav span {
  float: left;
}

header nav span:first-child {
  padding-right: 50px;
  padding-top: 20px;
}

header nav span:last-child {
  padding-left: 50px;
  padding-top: 20px;
}
*/

header .highlight,
header .current a {
  color: #e8491d;
  font-weight: bold;
}

header a:hover {
  color: #666666;
  font-weight: bold;
}

<header>
  <nav>
    <ul>
      <li class="current"><a href="homePage.html"> Home</a></li>
      <li><a href="about.html"> Photography</a></li>
      <li class="logo"><img src="https://placehold.it/100x50"></li>
      <li><a href="services.html"> Biography</a></li>
      <li><a href="contactus.html"> Contact Us</a></li>
    </ul>
  </nav>
</header>

<!--

Change Log:

1) Invalid nested elements removed from list (span & div)
2) Superfluous ".container" containing element removed (as providing no tangible benefits)

-->

Practical Demonstrations for Further Reference:

Horizontal Alignment (Text Elements)

Horizontal Alignment (Arbitrary Elements)