问:
OOP best design practices for nested classes and helper functions
I'm programming a project in C# and I have two questions in regards to OOP best practices. To keep my questions simple I have simplified the code examples.

I have a class Map which holds the information to the 2D tile map. There will be only one instance of the Map class:

```<code>class Map {
    int height
    int width
    InventoryGrid iGrid
    TileGrid tGrid

    public Map(int height, int width) { ... }
}
</code>```

The Map class contains 2 grids that are related to the items and tiles on the map. These are technically nested classes since they do not get initialized anywhere else in the code. For example the InventoryGrid class might look like this:

```<code>class InventoryGrid {
    Dictionary<int, Item> inventory

    public function SetInventory(int index, item) { ... }
    public function GetInventory(int index) { ... }
}
</code>```

Let's assume we have a Job class which in case an action is completed needs to update the inventory.

```<code>class Job {
    public void FinishedJob()
    {
        // I need to update the inventory.
    }
}
</code>```

Let's assume the Job class makes an event call or has access to the Map instance.

The first question is, what is the best OO way to call the InventoryGrid.SetInventory() function on the inner class:

Create a getter function in the Map class and call map.iGrid.SetInventory() directly.

Create a new function inside the Map class, map.SetInventoryAt() for example, which in turn calls the iGrid.SetInventory() function.

Other solution?

Now in our example the map takes x and y coordinates. However the "grids" take a single unique deterministic index to store their information. A function to convert the coords to index is required.

```<code>public int CoordsToIndex(int x, int y) {...}
</code>```

This function will be used by all Grids (InventoryGrid, TileGrid, etc...)

My second question is where should the function reside according to best practise OO design? Who's responsibility is it?

Do I make a super class Grid containing the function from which all "grids" inherit to avoid duplication? C# specific: use an interface instead of super class?

Do I put it in the Map class and argue that the "Grids" should not be aware of the coords to index conversion. Would this affect the first question?

Do I make a separate (static) class called GridTools which holds helper methods?

Other solution?

答:
I would go a) #2 and b) #1 choices.

If Map is a Singleton make it static.

a) #2 because a getter alludes inventory is a member, a function gives you more encapsulation and in future ability to tap into inheritance and interfaces should you extend the object model. Getter's suit single value much better than nested classes. Edit: I see you're accessing the getter via iGrid in #1, it's not very obvious to caller that's how you would set inventory. IMO it would be equally acceptable solution to use a getter that exposes iGrid if it was named InventoryGrid. If you have sub-nested classes this would be a better way to go.

b) #1 because logically to avoid duplication in a scenario where 2 grid classes need the same method a base/super class is one of the best ways. You might choose each grid to implement an interface if they have implementation specific CoordsToIndex functionality, if this is the case you could also use an abstract base method.

This function will be used by all Grids (InventoryGrid, TileGrid, etc...)

I think though that both grids will share the exact same implementation and one CoordsToIndex base class for both InventoryGrid and TileGrid is what you want right now (at this point in your design). I'm assuming that CoordsToIndex relies on data in both grids, otherwise your idea of decoupling and putting CoordsToIndex in the Map class is a good idea.

With Helper classes keep them more for app wide stuff: Config, File, Encryption, Logging/Tracing, extension methods, etc.

Your top 2 choices for both scenarios are good, so you're on the right track. One piece of advice is that interfaces allow you to use unit test mocking so you may want to write a few unit tests to confirm you can test your oop architecture.

Body:
I'm programming a project in C# and I have two questions in regards to OOP best practices. To keep my questions simple I have simplified the code examples.

I have a class Map which holds the information to the 2D tile map. There will be only one instance of the Map class:

class Map {
    int height
    int width
    InventoryGrid iGrid
    TileGrid tGrid

    public Map(int height, int width) { ... }
}

The Map class contains 2 grids that are related to the items and tiles on the map. These are technically nested classes since they do not get initialized anywhere else in the code. For example the InventoryGrid class might look like this:

class InventoryGrid {
    Dictionary<int, Item> inventory

    public function SetInventory(int index, item) { ... }
    public function GetInventory(int index) { ... }
}

Let's assume we have a Job class which in case an action is completed needs to update the inventory.

class Job {
    public void FinishedJob()
    {
        // I need to update the inventory.
    }
}

Let's assume the Job class makes an event call or has access to the Map instance.

The first question is, what is the best OO way to call the InventoryGrid.SetInventory() function on the inner class:

Create a getter function in the Map class and call map.iGrid.SetInventory() directly.

Create a new function inside the Map class, map.SetInventoryAt() for example, which in turn calls the iGrid.SetInventory() function.

Other solution?

Now in our example the map takes x and y coordinates. However the "grids" take a single unique deterministic index to store their information. A function to convert the coords to index is required.

public int CoordsToIndex(int x, int y) {...}

This function will be used by all Grids (InventoryGrid, TileGrid, etc...)

My second question is where should the function reside according to best practise OO design? Who's responsibility is it?

Do I make a super class Grid containing the function from which all "grids" inherit to avoid duplication? C# specific: use an interface instead of super class?

Do I put it in the Map class and argue that the "Grids" should not be aware of the coords to index conversion. Would this affect the first question?

Do I make a separate (static) class called GridTools which holds helper methods?

Other solution?


来源: stackexchange

问:
Generating all variations of certain length out of string
I've seen few implementations of variations of string in C#, but none of them had any limitation on their length. Unfortunately, I cannot modify them to achieve my goal which is e.g.

for:

```<code>string = "ABCD" and variationLength = 2
</code>```

generate new strings:

```<code>AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC
</code>```

I'm looking for exactly this Python's itertools.permutations implementation but in C#. (https://docs.python.org/3/library/itertools.html#itertools.permutations)

Is there anything similar to its in C#? If not, then what is the easiest way to implement it?

Edit_2:
so far I came up with an idea to list all unique chars of given string and then get variations out of them

```<code>static void PrintAllKLengthPerm(string str, int k)
{
    int n = str.Length;
    PrintAllKLengthPermRec(str, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
    // Base case: k is 0, print prefix
    if (k == 0)
    {
        Console.WriteLine(prefix);
        return;
    }

    // One by one add all characters from str and recursively
    // call for k equals to k-1
    for (int i = 0; i < n; ++i)
    {
        // Next character of input added
        String newPrefix = prefix + str[i];

        // k is decreased, because we have added a new character
        PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
    }
}

static void Main(string[] args)
{
    string str = "ABCD";
    int permLen = 2;

    //get all unique characters in string
    string uniqStr = new String(str.Distinct().ToArray());

    // Print all possible strings of length permLen out of uniqStr characters
    PrintAllKLengthPerm(uniqStr, permLen);
}
</code>```

However I am looking for more optimal and effective solution

答:
I made the following recursive function which accomplishes your task:

```<code>static void Permutations(List<string> output, string str, int n, string curr)
    {
        if(curr.Length == n)
        {
            output.Add(curr);
            return;
        }
        foreach(char c in str)
            if(!curr.Contains(c.ToString()))
                Permutations(output, str, n, curr + c.ToString());
    }
</code>```

and then you call it like this:

```<code>string str = "ABCD";
int length = 2;
List<string> perms = new List<string>();
Permutations(perms, str, length, "");
// now the list "perms" will contain the permutations of "str" in length "n"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've seen few implementations of variations of string in C#, but none of them had any limitation on their length. Unfortunately, I cannot modify them to achieve my goal which is e.g.

for:

string = "ABCD" and variationLength = 2

generate new strings:

AB, AC, AD, BA, BC, BD, CA, CB, CD, DA, DB, DC

I'm looking for exactly this Python's itertools.permutations implementation but in C#. (https://docs.python.org/3/library/itertools.html#itertools.permutations)

Is there anything similar to its in C#? If not, then what is the easiest way to implement it?

Edit_2:
so far I came up with an idea to list all unique chars of given string and then get variations out of them

static void PrintAllKLengthPerm(string str, int k)
{
    int n = str.Length;
    PrintAllKLengthPermRec(str, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void PrintAllKLengthPermRec(string str, String prefix, int n, int k)
{
    // Base case: k is 0, print prefix
    if (k == 0)
    {
        Console.WriteLine(prefix);
        return;
    }

    // One by one add all characters from str and recursively
    // call for k equals to k-1
    for (int i = 0; i < n; ++i)
    {
        // Next character of input added
        String newPrefix = prefix + str[i];

        // k is decreased, because we have added a new character
        PrintAllKLengthPermRec(str, newPrefix, n, k - 1);
    }
}

static void Main(string[] args)
{
    string str = "ABCD";
    int permLen = 2;

    //get all unique characters in string
    string uniqStr = new String(str.Distinct().ToArray());

    // Print all possible strings of length permLen out of uniqStr characters
    PrintAllKLengthPerm(uniqStr, permLen);
}

However I am looking for more optimal and effective solution

Body:
I made the following recursive function which accomplishes your task:

static void Permutations(List<string> output, string str, int n, string curr)
    {
        if(curr.Length == n)
        {
            output.Add(curr);
            return;
        }
        foreach(char c in str)
            if(!curr.Contains(c.ToString()))
                Permutations(output, str, n, curr + c.ToString());
    }

and then you call it like this:

string str = "ABCD";
int length = 2;
List<string> perms = new List<string>();
Permutations(perms, str, length, "");
// now the list "perms" will contain the permutations of "str" in length "n"


问:
rxjs rate limit (requests per second) and concurrency
I am trying to figure out how to write a rate limiter in rxjs. Used to access most apis (twitter, facebook, etc) If not supported by out of the box methods, i would assume a scheduler could be written. For instance highland.js has ratelimit. I don't want to drop any items like with window, sample, etc.

```<code>var source = Rx.Observable.create(function (observer) {

  // queue of requests
  _.each(requests, function(r) {
    observer.onNext(r);
  });

  observer.onCompleted();

  // Any cleanup logic might go here
  return function () {
    console.log('disposed');
  }
})
  // what goes here, if built in (e.g. 2 requests per 2 seconds or 15 request per 15 minutes)

// SHOULD ONLY RUN
var subscription = source.subscribe(
  function (x) { console.log('onNext: %s', x); },
  function (e) { console.log('onError: %s', e); },
  function () { console.log('onCompleted'); });
</code>```

EDIT 1:
Thinking about something like this, using the token bucket algorithm, still really rough but...

Rx.Observable.prototype.tokenBucket = function(options, scheduler) {
  function time() {
    return new Date().getTime();
  }

  var BUCKET = {
    capacity: options.capacity || Infinity,
    left: options.capacity,
    last: time(),

    tokensPerInterval: options.tokensPerInterval,
    interval: options.interval
  };

  //var BUCKET = _.merge(defaultOptions, options);
  console.log(BUCKET);

  var source = this,
    scheduler = scheduler || (scheduler = Rx.Scheduler.timeout);

  return Rx.Observable.create(function(observer) {
    var d1 = source.subscribe(function(mainValue) {
      return throttle(mainValue);
    });

    function throttle(x, tokens) {
      if (BUCKET.capacity === Infinity) {
        return observer.onNext(x);
      } // return x;

      // the number of tokens to add every S milliseconds = (r*S)/1000.
      var self = BUCKET;
      var now = time();

      var deltaMS = Math.max(now - self.last, 0);
      self.last = now;
      var dripAmount = deltaMS * (self.tokensPerInterval / self.interval);
      self.left = Math.min(self.left + dripAmount, self.capacity);

      if (self.left < 1) {
        var interval = Math.ceil((1 - self.left) * self.interval);
        scheduler.scheduleWithRelative(interval, function (s, i) {
          return throttle(x);
        });
      } else {
        self.left -= tokens || 1;
        console.log('calling');
        return observer.onNext(x);
      }
    }

    return function() {
      d1.dispose();
      console.log('disposed tokenBucket');
    };
  });
};

var start = moment();
var source = Rx.Observable.range(1, 20)
  .tokenBucket({capacity: 2, tokensPerInterval: 2, interval: 2000})

var subscription = source.subscribe(
  function (x) { console.log('onNext: %s', x); addToDom(x); },
  function (e) { console.log('onError: %s', e); },
  function () { console.log('onCompleted'); });

function addToDom(x) {
  var ul = document.getElementById('c');
  var li = document.createElement('li');
  li.innerHTML = x + ' - ' + moment().diff(start, 'seconds') + 's ago';
  ul.appendChild(li);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/2.5.3/rx.all.js"></script>
<ul id="c"></ul></code>```

答:
I've faced a very similar issue in my personal project and decided to publish a reusable solution as a npm package https://www.npmjs.com/package/rx-op-lossless-throttle

Unlike http://www.g9labs.com/2016/03/21/lossless-rate-limiting-with-rxjs/ it doesn't force the delay on every single event.

Body:
I am trying to figure out how to write a rate limiter in rxjs. Used to access most apis (twitter, facebook, etc) If not supported by out of the box methods, i would assume a scheduler could be written. For instance highland.js has ratelimit. I don't want to drop any items like with window, sample, etc.

var source = Rx.Observable.create(function (observer) {

  // queue of requests
  _.each(requests, function(r) {
    observer.onNext(r);
  });

  observer.onCompleted();

  // Any cleanup logic might go here
  return function () {
    console.log('disposed');
  }
})
  // what goes here, if built in (e.g. 2 requests per 2 seconds or 15 request per 15 minutes)

// SHOULD ONLY RUN
var subscription = source.subscribe(
  function (x) { console.log('onNext: %s', x); },
  function (e) { console.log('onError: %s', e); },
  function () { console.log('onCompleted'); });

EDIT 1:
Thinking about something like this, using the token bucket algorithm, still really rough but...

Rx.Observable.prototype.tokenBucket = function(options, scheduler) {
  function time() {
    return new Date().getTime();
  }

  var BUCKET = {
    capacity: options.capacity || Infinity,
    left: options.capacity,
    last: time(),

    tokensPerInterval: options.tokensPerInterval,
    interval: options.interval
  };

  //var BUCKET = _.merge(defaultOptions, options);
  console.log(BUCKET);

  var source = this,
    scheduler = scheduler || (scheduler = Rx.Scheduler.timeout);

  return Rx.Observable.create(function(observer) {
    var d1 = source.subscribe(function(mainValue) {
      return throttle(mainValue);
    });

    function throttle(x, tokens) {
      if (BUCKET.capacity === Infinity) {
        return observer.onNext(x);
      } // return x;

      // the number of tokens to add every S milliseconds = (r*S)/1000.
      var self = BUCKET;
      var now = time();

      var deltaMS = Math.max(now - self.last, 0);
      self.last = now;
      var dripAmount = deltaMS * (self.tokensPerInterval / self.interval);
      self.left = Math.min(self.left + dripAmount, self.capacity);

      if (self.left < 1) {
        var interval = Math.ceil((1 - self.left) * self.interval);
        scheduler.scheduleWithRelative(interval, function (s, i) {
          return throttle(x);
        });
      } else {
        self.left -= tokens || 1;
        console.log('calling');
        return observer.onNext(x);
      }
    }

    return function() {
      d1.dispose();
      console.log('disposed tokenBucket');
    };
  });
};

var start = moment();
var source = Rx.Observable.range(1, 20)
  .tokenBucket({capacity: 2, tokensPerInterval: 2, interval: 2000})

var subscription = source.subscribe(
  function (x) { console.log('onNext: %s', x); addToDom(x); },
  function (e) { console.log('onError: %s', e); },
  function () { console.log('onCompleted'); });

function addToDom(x) {
  var ul = document.getElementById('c');
  var li = document.createElement('li');
  li.innerHTML = x + ' - ' + moment().diff(start, 'seconds') + 's ago';
  ul.appendChild(li);
}


问:
Deploying a Java EE application to Tomcat8
I'm trying to deploy a Java project on my Tomcat8 server running on Ubuntu machine.

I downloaded the Business suite Zip file from here then I copied the folder to /tomcat/webapps. When I start tomcat server everything seems fine but I'm not able to access localhost:8080 from my browser it keeps loading with no response.

Then I removed the project folder from /tomcat/webapps and restarted the server and everything working normal.
I don't know why localhost:8080 does not respond when I added the project to /webapps even if the server is running.

Please help me if you have any ideas !

NOTE: I tried to upload .war file to APP MANAGER after running jar cvf dirname.war . but I got an error related to max file size upload.

答:
Simply you can't deploy Java Enterprise App to Tomcat8 (Servlet Container). Because JEE apps requires Enterprise Container like JBoss, Glasfish, Weblogic Server, TomEE.

If you mean deploy Dynamic Web Application (composed like war) generated any Java Supported IDE to Tomcat8 -> You can simple copy it to /tomcat/webapps/ folder and access from browser

http://localhost:port/app_name

or you can config root context on /tomcat/conf/server.xml

```<code><Host>
<!-- Other code stuff -->
<Context path="" docBase="app_name" debug="0" reloadable="true"></Context>
</Host>
</code>```

after this you can access by typing on browser

http://localhost:port    (default port 8080)

Body:
Simply you can't deploy Java Enterprise App to Tomcat8 (Servlet Container). Because JEE apps requires Enterprise Container like JBoss, Glasfish, Weblogic Server, TomEE.

If you mean deploy Dynamic Web Application (composed like war) generated any Java Supported IDE to Tomcat8 -> You can simple copy it to /tomcat/webapps/ folder and access from browser

http://localhost:port/app_name

or you can config root context on /tomcat/conf/server.xml

<Host>
<!-- Other code stuff -->
<Context path="" docBase="app_name" debug="0" reloadable="true"></Context>
</Host>

after this you can access by typing on browser

http://localhost:port    (default port 8080)


问:
using parfor in matlab
I want to parallelize some part of my code in matlab. for example below part:

```<code>v1=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
 parfor i = 1:length(v1)
 m = v1(i);
 if m > 1
 gax(1:m-1,m-1) = ggx(1:m-1,m-1);
 end
 if m<nn
 gax(m+1:end,m) = ggx(m+1:end,m);
 end
 end
</code>```

But there is an error:
    Error: The variable gax in a parfor cannot be classified.See Parallel for Loops in MATLAB, "Overview".

Do anyone knows how can I remove the error? Other useful information is that v1 is an increasing vector which doesn't contain any repeated element.

答:
As mentioned in the error message, you must follow the Sliced Variable rule.
Both gax and gay breaks rules of Fixed Index Listing and  Form of Indexing. Also, you can this example A(i,20:30,end)  % 20:30 not scalar as an example of not sliced variables in the document.

Therefore, you should change the all part of the parfor to getting a proper parallel computation. In the other words, you must design a proper parallel algorithm which you can parallelized the method, based on the loop variable.

Type of First-Level Indexing — The first level of indexing is either parentheses, (), or braces, {}.

Fixed Index Listing — Within the first-level parentheses or braces, the list of indices is the same for all occurrences of a given variable.

Form of Indexing — Within the list of indices for the variable, exactly one index involves the loop variable.

Shape of Array — The array maintains a constant shape. In assigning to a sliced variable, the right side of the assignment cannot be [] or '', because these operators attempt to delete elements.

Title: using parfor in matlab

Body:
I want to parallelize some part of my code in matlab. for example below part:

v1=[1,3,6,8];
ggx=5.*ones(15,14);
gax=ones(15,14);
 parfor i = 1:length(v1)
 m = v1(i);
 if m > 1
 gax(1:m-1,m-1) = ggx(1:m-1,m-1);
 end
 if m<nn
 gax(m+1:end,m) = ggx(m+1:end,m);
 end
 end

But there is an error:
    Error: The variable gax in a parfor cannot be classified.See Parallel for Loops in MATLAB, "Overview".

Do anyone knows how can I remove the error? Other useful information is that v1 is an increasing vector which doesn't contain any repeated element.


问:
Convert a c hex value into a char*
How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

The docs say the following types are valid,

There are certain definitions for variable and function types which are used  throughout the kernel and drivers. They are available to applications in the vos.h header file.

Null pointer and logic definitions:

```<code>#define NULL                0
#define TRUE                1
#define FALSE               0
</code>```

Variable type definitions:

```<code>#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *
</code>```

Function type definitions:

```<code>typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);
</code>```

Any suggestions?

答:
Something like this should do it:

```<code>void to_hex(char *buffer, size_t size, unsigned n)
{
    size_t i;
    size_t j;
    char c;
    unsigned digit;

    // Print digits in the reverse order
    for (i = 0; i < size - 1; ++i)
    {
        digit = n & 0xf;
        buffer[i] = digit < 10 ? digit + '0' : digit - 10 + 'A';
        n >>= 4;

        if (n == 0)
        {
            break;
        }
    }

    // Append NUL
    buffer[i + 1] = 0;

    // Reverse the string
    for (j = 0; j < i / 2; ++j)
    {
        c = buffer[j];
        buffer[j] = buffer[i - j];
        buffer[i - j] = c;
    }
}
</code>```

But you are saying you have stdio available, so there's no need write anything like this yourself.

Edit:  Could be that the compiler expects K&R style prototype:

```<code>void to_hex(buffer, size, n)
    char *buffer;
    size_t size;
    unsigned n;
{
...
</code>```

Try this on Codepad.

Title: Convert a c hex value into a char*

Body:
How to convert a hex value in c into an equivalent char* value. For example if the hex value is 1df2 the char* should also contain 1df2.

I am using the VinC compiler and the VinL linker for the VNC2 USB Chip from FTDI. It has these following header files; stdlib, stdio and string. These are however subsets of the main c libraries and don't have the obvious answers such as snprintf or sprintf.

The docs say the following types are valid,

There are certain definitions for variable and function types which are used  throughout the kernel and drivers. They are available to applications in the vos.h header file.

Null pointer and logic definitions:

#define NULL                0
#define TRUE                1
#define FALSE               0

Variable type definitions:

#define uint8               unsigned char
#define int8                char
#define int16               short
#define uint16              unsigned short
#define uint32              unsigned int
#define pvoid               unsigned char *

Function type definitions:

typedef uint8 (*PF)(uint8);
typedef void (*PF_OPEN)(void *);
typedef void (*PF_CLOSE)(void *);
typedef uint8 (*PF_IOCTL)(pvoid);
typedef uint8 (*PF_IO)(uint8 *, unsigned short, unsigned short *);
typedef void (*PF_INT)(void);

Any suggestions?

Body:
Something like this should do it:

void to_hex(char *buffer, size_t size, unsigned n)
{
    size_t i;
    size_t j;
    char c;
    unsigned digit;

    // Print digits in the reverse order
    for (i = 0; i < size - 1; ++i)
    {
        digit = n & 0xf;
        buffer[i] = digit < 10 ? digit + '0' : digit - 10 + 'A';
        n >>= 4;

        if (n == 0)
        {
            break;
        }
    }

    // Append NUL
    buffer[i + 1] = 0;

    // Reverse the string
    for (j = 0; j < i / 2; ++j)
    {
        c = buffer[j];
        buffer[j] = buffer[i - j];
        buffer[i - j] = c;
    }
}

But you are saying you have stdio available, so there's no need write anything like this yourself.

Edit:  Could be that the compiler expects K&R style prototype:

void to_hex(buffer, size, n)
    char *buffer;
    size_t size;
    unsigned n;
{
...

Try this on Codepad.

ContentLicense: CC BY-SA 2.5


问:
Single Background for Multiple Divs
Is there a way of having one image (PNG or SVG) as a background for multiple divs? Please see the images below as to how it would work. Also when the screen width becomes smaller and the divs line up below each other, would there be a way of changing the background to match that aswell?

DIVs without background:

The background:

DIVs with background:

答:
How's it going? I'm still relatively new to HTML and CSS, but I think we can tackle this one together!

Your "WHOLE" picture might exist in a  that contains the other "WINDOW"  elements...where each of the window  elements is positioned relative to the parent div that contains the whole picture

.whole{

  position:relative;

}

.UpperL{

  position: absolute;
  height: 25px;
  width: 100px;

}
.UpperR{
  position:...;

}
.LowerL{

  position:...;

}
.LowerR{

  position:...;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="whole" img src="whole picture.png">
<!-- let the whole class contain the background image-->

  <div class="UpperL"> Upper Left Window</div>
  <div class="UpperR"> Upper Left Window</div>
  <div class="LowerL"> Upper Left Window</div>
  <div class="LowerR"> Upper Left Window</div>
</div></code>```

The code doesn't run well yet, but the point of setting four windows inside of a fifth window is to give the four an ability or property to see through the fifth;

If your parent  contains the image, but is still colored all white (opacity at 100%), the four window  elements should be able to see through the opacity of the fifth window (turning their opacity down to reveal the image).

hmm...

ContentLicense: CC BY-SA 4.0

Title: Single Background for Multiple Divs

Body:
How's it going? I'm still relatively new to HTML and CSS, but I think we can tackle this one together!

Your "WHOLE" picture might exist in a  that contains the other "WINDOW"  elements...where each of the window  elements is positioned relative to the parent div that contains the whole picture

.whole{

  position:relative;

}

.UpperL{

  position: absolute;
  height: 25px;
  width: 100px;

}
.UpperR{
  position:...;

}
.LowerL{

  position:...;

}
.LowerR{

  position:...;

}

<div class="whole" img src="whole picture.png">
<!-- let the whole class contain the background image-->

  <div class="UpperL"> Upper Left Window</div>
  <div class="UpperR"> Upper Left Window</div>
  <div class="LowerL"> Upper Left Window</div>
  <div class="LowerR"> Upper Left Window</div>
</div>

The code doesn't run well yet, but the point of setting four windows inside of a fifth window is to give the four an ability or property to see through the fifth;

If your parent  contains the image, but is still colored all white (opacity at 100%), the four window  elements should be able to see through the opacity of the fifth window (turning their opacity down to reveal the image).

hmm...


问:
NaN Cholesky's decomposition in Fortran if I don't use a printing subroutine
I programmed a function to obtain Cholesky's decomposition of a REAL matrix. The problem is that it returns NaN values in some spots of the matrix. Here is the code:

```<code>MODULE funciones2
IMPLICIT NONE
CONTAINS
FUNCTION cholesky(a)
USE ::comprob !Module to test whether or not a matrix is square and symmetric
IMPLICIT NONE
REAL, ALLOCATABLE :: cholesky(:,:),u(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n
LOGICAL :: comp

comp=symmat(a)

IF (comp) THEN
n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ELSE
    print*,"CHOLESKY: The matrix is not symmetric."
ENDIF
ENDFUNCTION
ENDMODULE
</code>```

And the program code is:

```<code>PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:)
CHARACTER(LEN=20) :: na

na='B.txt'

a=loadm(na)
CALL DISP('A =',a,ADVANCE='DOUBLE')

a=matmul(transpose(a),a)
!CALL DISP('ATA =',a,ADVANCE='DOUBLE')

af=cholesky(a)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM
</code>```

"dispmodule" is a module (Jonasson, 2009) for pretty-printing matrices (you can take a look about it here: https://notendur.hi.is/jonasson/greinar/dispmodule-report.pdf ). I discovered that if I use the subroutine DISP in this part:

```<code>a=matmul(transpose(a),a)
CALL DISP('ATA =',a,ADVANCE='DOUBLE')
</code>```

the problem of NaN disappears!(notice that in this last part, there is not "!" before "CALL DISP").

Why is this happening? I am going to use the Cholesky decomposition function for another function, and I can't call DISP all the time to avoid problems. How can I fix this?

Edit:
Here's the numerical result without compiling the program with the DISP subroutine:

```<code>A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

Ach 3.74166  0.26726  4.27618  2.93987
    0.00000      NaN      NaN      NaN
    0.00000  0.00000      NaN      NaN
    0.00000  0.00000  0.00000      NaN

AchT 3.74166  0.00000  0.00000  0.00000
     0.26726      NaN  0.00000  0.00000
     4.27618      NaN      NaN  0.00000
     2.93987      NaN      NaN      NaN
</code>```

Here is the numerical result when I do compile the DISP subroutine:

```<code>A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

ATA =14.0000   1.0000  16.0000  11.0000
      1.0000  14.0000   7.0000  16.0000
     16.0000   7.0000  21.0000  18.0000
     11.0000  16.0000  18.0000  29.0000

Ach 3.74166  0.26726  4.27618   2.93987
    0.00000  3.73210  1.56940   4.07660
    0.00000  0.00000  0.50128  -1.93350
    0.00000  0.00000  0.00000   0.00648

AchT 3.74166  0.00000   0.00000  0.00000
     0.26726  3.73210   0.00000  0.00000
     4.27618  1.56940   0.50128  0.00000
     2.93987  4.07660  -1.93350  0.00648
</code>```

EDIT 2: I assigned new variables to every new computed matrix, but the problem remains.

```<code>PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:),at(:,:),am(:,:),am1(:,:)
CHARACTER(LEN=20) :: na
INTEGER :: m,n

na='B.txt'

a=loadm(na)
!CALL DISP('A =',a,ADVANCE='DOUBLE')

m=size(a,1)
n=size(a,2)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
!CALL DISP('ATA =',am1,ADVANCE='DOUBLE')

af=cholesky(am)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM
</code>```

UPDATE: Minimum compilable example. I took out the subroutine DISP() with its respective module. I also took out the module and function that made the comprobation of the symmetry of the matrix. Moreover, I took out the function that I wrote for reading the matrix from a file (I wrote the same matrix directly on the program) and the function for printing the matrix. The problem gets worse, now there are no numbers, not even the first row as before, all the matrix becomes NaN after the use of cholesky(). The gfortran version is 5.3.0

```<code>PROGRAM pcholstack
IMPLICIT NONE
REAL, ALLOCATABLE :: af(:,:),at(:,:),am(:,:),am1(:,:)
REAL :: a(3,4)
INTEGER :: m,n,i,j

a(1,1)=3
a(2,1)=2
a(3,1)=1
a(1,2)=2
a(2,2)=-3
a(3,2)=1
a(1,3)=4
a(2,3)=1
a(3,3)=2
a(1,4)=5
a(2,4)=-2
a(3,4)=1

m=size(a,1)
n=size(a,2)

do i=1,m,1
    write(*,1017),(a(i,j),j=1,n)
    end do
        1017 format (10f15.2)

write(*,*)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
write(*,*) am1(1,1)
write(*,*)

do i=1,n,1
    write(*,1018),(at(i,j),j=1,m)
    end do
        1018 format (10f15.2)

write(*,*)

do i=1,n,1
    write(*,1019),(am(i,j),j=1,n)
    end do
        1019 format (10f15.2)

write(*,*)

af=cholesky(am)

!af=transpose(af)

do i=1,n,1
    write(*,1016),(af(i,j),j=1,n)
    end do
        1016 format (10f15.2)

CONTAINS

FUNCTION cholesky(a)
IMPLICIT NONE
REAL, ALLOCATABLE :: u(:,:),cholesky(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n

n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ENDFUNCTION

ENDPROGRAM
</code>```

答:
I believe your problem is in these two lines:

```<code>a=loadm(na)

a=matmul(transpose(a),a)
</code>```

I do not have the code for loadm, but your a matrix is 4x3.  You then call matmul and put a 4x4 into it (and thus using memory not reserved for it, which other things can write to).  The cholesky function will see it as a 4x3, not a 4x4.

UPDATE:

It actually worked in gfortran, which automatically allocated the variables.   But it failed in pgfortran.

Here's the problem: The return value of cholesky is not properly defined.  The easiest thing to do is simply return u:

```<code>FUNCTION cholesky(a) result (u)
</code>```

Take out the definition of the cholesky array, and do not assign to it at the end of the function.

Body:
I programmed a function to obtain Cholesky's decomposition of a REAL matrix. The problem is that it returns NaN values in some spots of the matrix. Here is the code:

MODULE funciones2
IMPLICIT NONE
CONTAINS
FUNCTION cholesky(a)
USE ::comprob !Module to test whether or not a matrix is square and symmetric
IMPLICIT NONE
REAL, ALLOCATABLE :: cholesky(:,:),u(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n
LOGICAL :: comp

comp=symmat(a)

IF (comp) THEN
n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ELSE
    print*,"CHOLESKY: The matrix is not symmetric."
ENDIF
ENDFUNCTION
ENDMODULE

And the program code is:

PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:)
CHARACTER(LEN=20) :: na

na='B.txt'

a=loadm(na)
CALL DISP('A =',a,ADVANCE='DOUBLE')

a=matmul(transpose(a),a)
!CALL DISP('ATA =',a,ADVANCE='DOUBLE')

af=cholesky(a)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM

"dispmodule" is a module (Jonasson, 2009) for pretty-printing matrices (you can take a look about it here: https://notendur.hi.is/jonasson/greinar/dispmodule-report.pdf ). I discovered that if I use the subroutine DISP in this part:

a=matmul(transpose(a),a)
CALL DISP('ATA =',a,ADVANCE='DOUBLE')

the problem of NaN disappears!(notice that in this last part, there is not "!" before "CALL DISP").

Why is this happening? I am going to use the Cholesky decomposition function for another function, and I can't call DISP all the time to avoid problems. How can I fix this?

Edit:
Here's the numerical result without compiling the program with the DISP subroutine:

A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

Ach 3.74166  0.26726  4.27618  2.93987
    0.00000      NaN      NaN      NaN
    0.00000  0.00000      NaN      NaN
    0.00000  0.00000  0.00000      NaN

AchT 3.74166  0.00000  0.00000  0.00000
     0.26726      NaN  0.00000  0.00000
     4.27618      NaN      NaN  0.00000
     2.93987      NaN      NaN      NaN

Here is the numerical result when I do compile the DISP subroutine:

A =3.00000   2.00000  4.00000   5.00000
   2.00000  -3.00000  1.00000  -2.00000
   1.00000   1.00000  2.00000   0.00000

ATA =14.0000   1.0000  16.0000  11.0000
      1.0000  14.0000   7.0000  16.0000
     16.0000   7.0000  21.0000  18.0000
     11.0000  16.0000  18.0000  29.0000

Ach 3.74166  0.26726  4.27618   2.93987
    0.00000  3.73210  1.56940   4.07660
    0.00000  0.00000  0.50128  -1.93350
    0.00000  0.00000  0.00000   0.00648

AchT 3.74166  0.00000   0.00000  0.00000
     0.26726  3.73210   0.00000  0.00000
     4.27618  1.56940   0.50128  0.00000
     2.93987  4.07660  -1.93350  0.00648

EDIT 2: I assigned new variables to every new computed matrix, but the problem remains.

PROGRAM pchol
USE :: funciones2
USE :: dispmodule
IMPLICIT NONE
REAL, ALLOCATABLE :: a(:,:),af(:,:),at(:,:),am(:,:),am1(:,:)
CHARACTER(LEN=20) :: na
INTEGER :: m,n

na='B.txt'

a=loadm(na)
!CALL DISP('A =',a,ADVANCE='DOUBLE')

m=size(a,1)
n=size(a,2)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
!CALL DISP('ATA =',am1,ADVANCE='DOUBLE')

af=cholesky(am)
CALL DISP('Ach ',af,ADVANCE='DOUBLE')

af=transpose(af)
CALL DISP('AchT ',af,ADVANCE='DOUBLE')

ENDPROGRAM

UPDATE: Minimum compilable example. I took out the subroutine DISP() with its respective module. I also took out the module and function that made the comprobation of the symmetry of the matrix. Moreover, I took out the function that I wrote for reading the matrix from a file (I wrote the same matrix directly on the program) and the function for printing the matrix. The problem gets worse, now there are no numbers, not even the first row as before, all the matrix becomes NaN after the use of cholesky(). The gfortran version is 5.3.0

PROGRAM pcholstack
IMPLICIT NONE
REAL, ALLOCATABLE :: af(:,:),at(:,:),am(:,:),am1(:,:)
REAL :: a(3,4)
INTEGER :: m,n,i,j

a(1,1)=3
a(2,1)=2
a(3,1)=1
a(1,2)=2
a(2,2)=-3
a(3,2)=1
a(1,3)=4
a(2,3)=1
a(3,3)=2
a(1,4)=5
a(2,4)=-2
a(3,4)=1

m=size(a,1)
n=size(a,2)

do i=1,m,1
    write(*,1017),(a(i,j),j=1,n)
    end do
        1017 format (10f15.2)

write(*,*)

ALLOCATE (at(n,m))
ALLOCATE (am(n,n))
ALLOCATE (af(n,n))

at=transpose(a)
am=matmul(at,a)
am1=am
write(*,*) am1(1,1)
write(*,*)

do i=1,n,1
    write(*,1018),(at(i,j),j=1,m)
    end do
        1018 format (10f15.2)

write(*,*)

do i=1,n,1
    write(*,1019),(am(i,j),j=1,n)
    end do
        1019 format (10f15.2)

write(*,*)

af=cholesky(am)

!af=transpose(af)

do i=1,n,1
    write(*,1016),(af(i,j),j=1,n)
    end do
        1016 format (10f15.2)

CONTAINS

FUNCTION cholesky(a)
IMPLICIT NONE
REAL, ALLOCATABLE :: u(:,:),cholesky(:,:)
REAL :: a(:,:),s
INTEGER :: i,j,k,n

n=size(a,1)
ALLOCATE (u(n,n))
u=0.0
u(1,1)=sqrt(a(1,1))

DO j=2,n,1
    u(1,j)=a(1,j)/u(1,1)
END DO

DO i=2,n,1
    DO k=1,i-1,1
        s=s+(u(k,i)**2)
    END DO
    u(i,i)=sqrt(a(i,i)-s)
    s=0
    DO j=i+1,n,1
        DO k=1,i-1,1
            s=s+u(k,i)*u(k,j)
        END DO
        u(i,j)=(1/u(i,i))*(a(i,j)-s)
        s=0
    END DO
END DO

cholesky=u

ENDFUNCTION

ENDPROGRAM

Body:
I believe your problem is in these two lines:

a=loadm(na)

a=matmul(transpose(a),a)

I do not have the code for loadm, but your a matrix is 4x3.  You then call matmul and put a 4x4 into it (and thus using memory not reserved for it, which other things can write to).  The cholesky function will see it as a 4x3, not a 4x4.

UPDATE:

It actually worked in gfortran, which automatically allocated the variables.   But it failed in pgfortran.

Here's the problem: The return value of cholesky is not properly defined.  The easiest thing to do is simply return u:

FUNCTION cholesky(a) result (u)

Take out the definition of the cholesky array, and do not assign to it at the end of the function.


问:
Php write line/strine once to code
I am making a search function with php and I need to add </pages> to the end of the file I am writing too. </pages> can be written only once, at the end.

```<code>$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]
["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image

// Check if file already exists
if (file_exists($target_file)) {
echo "ERR: 418 (File all ready exists)\n";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "ERR: 418 (File too large)\n";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "txt") {
echo "ERR: 418 (Supported file types - .txt)\n";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). "
has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}

$contentsbro = file_get_contents("links.xml");
$myfile = fopen("links.xml", "w") or die("Unable to open file!");
$txt = "<link><title>". basename( $_FILES["fileToUpload"]["name"]). "
</title>
<url>https://fidead.000webhostapp.com/uploads/". basename(
$_FILES["fileToUpload"]["name"]). "</url>
</link>";
$txto = $contentsbro . $txt;
fwrite($myfile, $txto);
fclose($myfile);

?>
</code>```

I need to know how to write the string once at the end, otherwise it would give me an error.

答:
Presumably you have something like this (with more entries):

```<code><?xml version="1.0" encoding="UTF-8" ?>
<pages>
    <url>https://fidead.000webhostapp.com/uploads/filename.jpg</url>
</pages>
</code>```

You should probably use an XML parser to do this properly:

```<code># Loads the content of the file
$XML    =   simplexml_load_file('links.xml');
# Adds to the URL array
$XML->addChild('url','https://fidead.000webhostapp.com/uploads/newfile.jpg');
# Saves the file back
file_put_contents('links.xml',$XML->asXml());
</code>```

Gives you:

```<code><?xml version="1.0" encoding="UTF-8"?>
<pages>
    <url>https://fidead.000webhostapp.com/uploads/filename.jpg</url>
<url>https://fidead.000webhostapp.com/uploads/newfile.jpg</url></pages>
</code>```

EDIT:

Instead of:

```<code>$contentsbro = file_get_contents("links.xml");
$myfile = fopen("links.xml", "w") or die("Unable to open file!");
etc....
</code>```

You should try:

```<code># Loads the content of the file
$XML    =   simplexml_load_file('links.xml');
# Make a new link child
$link   =   $XML->addChild('link');
# Create a new child under the link for title
$link->addChild('title',basename($_FILES["fileToUpload"]["name"]));
# Create a new child under the link for url
$link->addChild('url','https://fidead.000webhostapp.com/uploads/'.basename( $_FILES["fileToUpload"]["name"]));
# Saves the file back
file_put_contents('links.xml',$XML->asXml());
</code>```

Title: Php write line/strine once to code

Body:
I am making a search function with php and I need to add </pages> to the end of the file I am writing too. </pages> can be written only once, at the end.

$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]
["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image

// Check if file already exists
if (file_exists($target_file)) {
echo "ERR: 418 (File all ready exists)\n";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "ERR: 418 (File too large)\n";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "txt") {
echo "ERR: 418 (Supported file types - .txt)\n";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). "
has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
}

$contentsbro = file_get_contents("links.xml");
$myfile = fopen("links.xml", "w") or die("Unable to open file!");
$txt = "<link><title>". basename( $_FILES["fileToUpload"]["name"]). "
</title>
<url>https://fidead.000webhostapp.com/uploads/". basename(
$_FILES["fileToUpload"]["name"]). "</url>
</link>";
$txto = $contentsbro . $txt;
fwrite($myfile, $txto);
fclose($myfile);

?>

I need to know how to write the string once at the end, otherwise it would give me an error.

Body:
Presumably you have something like this (with more entries):

<?xml version="1.0" encoding="UTF-8" ?>
<pages>
    <url>https://fidead.000webhostapp.com/uploads/filename.jpg</url>
</pages>

You should probably use an XML parser to do this properly:

# Loads the content of the file
$XML    =   simplexml_load_file('links.xml');
# Adds to the URL array
$XML->addChild('url','https://fidead.000webhostapp.com/uploads/newfile.jpg');
# Saves the file back
file_put_contents('links.xml',$XML->asXml());

Gives you:

<?xml version="1.0" encoding="UTF-8"?>
<pages>
    <url>https://fidead.000webhostapp.com/uploads/filename.jpg</url>
<url>https://fidead.000webhostapp.com/uploads/newfile.jpg</url></pages>

EDIT:

Instead of:

$contentsbro = file_get_contents("links.xml");
$myfile = fopen("links.xml", "w") or die("Unable to open file!");
etc....

You should try:

# Loads the content of the file
$XML    =   simplexml_load_file('links.xml');
# Make a new link child
$link   =   $XML->addChild('link');
# Create a new child under the link for title
$link->addChild('title',basename($_FILES["fileToUpload"]["name"]));
# Create a new child under the link for url
$link->addChild('url','https://fidead.000webhostapp.com/uploads/'.basename( $_FILES["fileToUpload"]["name"]));
# Saves the file back
file_put_contents('links.xml',$XML->asXml());


问:
Getting a link from its anchor with Python
I have a list of urls with all the same anchor "view page" among other kind of urls, like this :

```<code><a href="url1" target="_blank">view page</a>

<a href="url2" target="_blank">view page</a>
</code>```

Is there a way to extract all the urls with this particular anchor text ?

Thank you

答:
To find links with text view page, you can use find_all('a', text='view page') and then loop through the result set and extract the url from it:

```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup("""<a href="url1" target="_blank">view page</a>
<a href="url2" target="_blank">view page</a>
<a href="url2" target="_blank"></a>""", "html.parser")

[a['href'] for a in soup.find_all('a', text='view page')]
# [u'url1', u'url2']
</code>```

Body:
I have a list of urls with all the same anchor "view page" among other kind of urls, like this :

view page

view page

Is there a way to extract all the urls with this particular anchor text ?

Thank you

Body:
To find links with text view page, you can use find_all('a', text='view page') and then loop through the result set and extract the url from it:

from bs4 import BeautifulSoup
soup = BeautifulSoup("""<a href="url1" target="_blank">view page</a>
<a href="url2" target="_blank">view page</a>
<a href="url2" target="_blank"></a>""", "html.parser")

[a['href'] for a in soup.find_all('a', text='view page')]
# [u'url1', u'url2']


问:
Why variables start out with random values in C
I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?</p>

答:
No. C is a very efficient language, one that has traditionally been faster that a lot of other languages. One of the reasons for this is that it doesn't do too much on it's own. The programmer controls this.

In the case of initialization, C variables are not initialized to a random value. Rather, they are not initialized and so they contain whatever was at the memory location before.

If you wanted to initialize a variable to, say, 1 in your program, then it would be inefficient if the variable had already been initialized to zero or null. That would mean it was initialized twice.


问:
Converting 'dataframe' to 'tuple' but getting a 'list' - Python
I want to convert a python dataframe into tuple. I tried to follow the method mentioned in below link, but what I am getting in return is a 'list'. - Pandas convert dataframe to array of tuples

```<code>def answer_six():
   df1 = df['% Renewable']
   df2=df1.reset_index()
   print(df2)
   print('df2 type -',type(df2))
   t1 = [tuple(x) for x in df2.values]
   print ('t1 type-',type(t1))
   return t1

answer_six()
</code>```

result

```<code>  Country % Renewable
  0  Brazil      69.648
  df2 type - <class 'pandas.core.frame.DataFrame'>
  t1 type- <class 'list'>
  Out[9]:
  [('Brazil', 69.64803)]
</code>```

Can you kindly help to convert it into a tuple ?

答:
You could change this line:

```<code>t1 = [tuple(x) for x in df2.values]
</code>```

To this:

```<code>t1 = [tuple(x) for x in df2.values][0]
</code>```

...provided df2 will never have more than 1 element.

Body:
I want to convert a python dataframe into tuple. I tried to follow the method mentioned in below link, but what I am getting in return is a 'list'. - Pandas convert dataframe to array of tuples

def answer_six():
   df1 = df['% Renewable']
   df2=df1.reset_index()
   print(df2)
   print('df2 type -',type(df2))
   t1 = [tuple(x) for x in df2.values]
   print ('t1 type-',type(t1))
   return t1

answer_six()

result

  Country % Renewable
  0  Brazil      69.648
  df2 type - <class 'pandas.core.frame.DataFrame'>
  t1 type- <class 'list'>
  Out[9]:
  [('Brazil', 69.64803)]

Can you kindly help to convert it into a tuple ?

Body:
You could change this line:

t1 = [tuple(x) for x in df2.values]

To this:

t1 = [tuple(x) for x in df2.values][0]

...provided df2 will never have more than 1 element.


问:
Changed name of Docker container, everything broke
I'm new to Docker/Kitematic, and I made a bonehead mistake, and I can't for the life of me figure out how to fix it.

I've got Wordpress running in Docker with nginx/mysqli/etc and all was running flawlessly. When I was in kitematic, I noticed a 'name' field, and it was something like 'travelsite_ngninx_1.' Being the dope I am, I was like 'hmmmm, maybe I can make that more semantic.' So I renamed it, and as soon as I did, everything broke. 'Error connecting to the database' and all that. The sad part is, I can't remember exactly what the name was, or if even reverting that will fix anything.

Is there a way to 'reset' the composer/docker so all of the containers are linked up again? I'm a newb when it comes to YML files, so I'm not even sure what to look for. Any help would be GREATLY appreciated. Here's my new error after enabling debugging mode on the renamed container:

'Warning: mysqli_real_connect(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/wp-includes/wp-db.php on line 1538'

then theres:

'Warning: mysqli_real_connect(): (HY000/2002): php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/html/wp-includes/wp-db.php on line 1538'

Please help this poor noob idiot out! Thanks in advance!

答: Ok, So I've figured it out. Apparently there's an issue with Kitematic that makes containers not fully destroy. Went into CLI, destroyed all containers, and ran docker-compose up and everything is A-1 now! Posted the answer just in case somebody else runs into that issue!


问:
Get rank of user based on levels in MySQL
I have a simple table called XP.

```<code>Id  User_id    Level
1   0032       12
2   0098       4
3   0013       8
4   0189       31
5   1150       11
</code>```

How would I get the rank of a User based on Level? For example User_id 1150 has 11 levels, he would be 3rd and User_id 0189 has 31 levels, he would be 1st.

答:
You could create a 'rank' field in the User class and get the data from the database using the Row_Number() for the field...

SELECT [Id], [User_id], [Level], Row_Number() Over (Order by [Level] DESC) as Rank FROM [XP] ORDER BY [Level] DESC

HTH,
Mike

Body:
I have a simple table called XP.

Id  User_id    Level
1   0032       12
2   0098       4
3   0013       8
4   0189       31
5   1150       11

How would I get the rank of a User based on Level? For example User_id 1150 has 11 levels, he would be 3rd and User_id 0189 has 31 levels, he would be 1st.


问:
What does Rust's lack of incremental compilation mean, exactly?

This question was asked before Rust officially supported incremental compilation. Rust 1.24.0 and later enable incremental compilation by default for development (debug) builds.

I'm an outsider trying to see if Rust is appropriate for my projects.

I've read that Rust lacks incremental compilation (beta features notwithstanding).

Is this similar to having everything be implemented in the headers in C++ (like in much of Boost)?

If the above is correct, does this limit Rust to rather small projects with small dependencies? (If, say, Qt or KDE were header-only libraries, then programs using them would be extremely painful to develop, since you'd effectively recompile Qt/KDE every time you want to compile your own code.)

答:
In C and C++, a compilation unit is usually a source file and all the header files it transitively includes. An application or library is usually comprised of multiple compilation units that are linked together. An application or library can additionally be linked with other libraries. This means that changing a source file requires recompiling that source file only and then relinking, changing an external library only requires relinking, but changing a header file (whether it's part of the project or external; the compiler can't tell the difference) requires recompiling all source files that use it and then relinking.

In Rust, the crate is the compilation unit. (A crate can be an application or a library.) Rust doesn't use header files; instead, the equivalent information is stored as metadata in the compiled crates (which is faster to parse, and has the same effect as precompiled headers in C/C++). A crate can additionally be linked with other crates. This means that changing any of the source files for a crate requires recompiling the whole crate, and changing a crate requires recompiling all crates that depend on it (currently, this means recompiling from source, even if the API happens to not have changed).

To answer your questions, no, Rust doesn't recompile all dependencies every time you recompile your project; quite the opposite in fact.

Incremental compilation in Rust is about reusing the work done in previous compilations of a crate to speed up compilation times. For example, if you change a module and it doesn't affect the other modules, the compiler would be able to reuse the data that was generated when the other modules were compiled last time. The lack of incremental compilation is usually only a problem with large or complex crates (e.g. those who make heavy use of macros).


问:
Using AWS Load Balancer as a Tunneling Proxy
I have ETL servers in a private subnet in my VPC on AWS. These ETL servers are locked down with specific outbound rules per approved outbound IP addresses. I have a service these ETL tools need to communicate with outside the VPC using TLS1.2/443 that uses a DNS name and not an IP address. Let's say "account.service.com". For this reason, it was suggested I consider using an elastic load balancer in the public subnet as a proxy.

If I send requests to the ELB private IP address from the ETL instance, how do I tell the ELB to send those requests on to "account.service.com"?

Essentially, I want the ELB to work as a tunneling proxy, since I can't specify "account.service.com" in my outbound security group rules in the private subnet.

答:
This is not possible.

Elastic Load Balancers can only send traffic to Amazon EC2 instances, and those instances need to be in the same VPC as the Load Balancer.

You would need to use some other technology (eg Squid proxy) in your Public Subnet to send traffic to a non-EC2 destination.


问:
Parallel programming in Java
How can we do Parallel Programming in Java? Is there any special framework for that? How can we make the stuff work?

I will tell you guys what I need, think that I developed a web crawler and it crawls a lot of data from the internet. One crawling system will not make things work properly, so I need more systems working in parallel. If this is the case can I apply parallel computing? Can you guys give me an example?

答:
There is a library called Habanero-Java (HJ), developed at Rice University that was built using lambda expressions and can run on any Java 8 JVM.

HJ-lib integrates a wide range of parallel programming constructs (e.g., async tasks, futures, data-driven tasks, forall, barriers, phasers, transactions, actors) in a single programming model that enables unique combinations of these constructs (e.g., nested combinations of task and actor parallelism).

The HJ runtime is responsible for orchestrating the creation, execution, and termination of HJ tasks, and features both work-sharing and work-stealing schedulers. You can follow the tutorial to set it up on your computer.

Here is a simple HelloWorld example:

```<code>import static edu.rice.hj.Module1.*;

public class HelloWorld {

public static void main(final String[] args) {

    launchHabaneroApp(() -> {

        finish(() -> {
            async(() -> System.out.println("Hello World - 1!"));
            async(() -> System.out.println("Hello World - 2!"));
            async(() -> System.out.println("Hello World - 3!"));
            async(() -> System.out.println("Hello World - 4!"));
        });

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

Each async method runs in parallel with the other async methods, while the content within these methods run sequentially. The program doesn't continue until all code within the finish method complete.

Title: Parallel programming in Java

Body:
There is a library called Habanero-Java (HJ), developed at Rice University that was built using lambda expressions and can run on any Java 8 JVM.

HJ-lib integrates a wide range of parallel programming constructs (e.g., async tasks, futures, data-driven tasks, forall, barriers, phasers, transactions, actors) in a single programming model that enables unique combinations of these constructs (e.g., nested combinations of task and actor parallelism).

The HJ runtime is responsible for orchestrating the creation, execution, and termination of HJ tasks, and features both work-sharing and work-stealing schedulers. You can follow the tutorial to set it up on your computer.

Here is a simple HelloWorld example:

import static edu.rice.hj.Module1.*;

public class HelloWorld {

public static void main(final String[] args) {

    launchHabaneroApp(() -> {

        finish(() -> {
            async(() -> System.out.println("Hello World - 1!"));
            async(() -> System.out.println("Hello World - 2!"));
            async(() -> System.out.println("Hello World - 3!"));
            async(() -> System.out.println("Hello World - 4!"));
        });

    });
}}

Each async method runs in parallel with the other async methods, while the content within these methods run sequentially. The program doesn't continue until all code within the finish method complete.


问:
Kotlin enum class in Android performance
In Java we are told to strictly avoid using enums on Android because they take up twice the memory.

Does this apply to enum class in Kotlin aswell? Will a Kotlin enum be compiled into a Java enum?

答: They are exactly the same thing, a Kotlin Enum is a Java JVM Enum.


答:
Execution speed and overhead (or lack thereof) are the main reasons why.  C is notorious for letting you walk off the proverbial cliff because it always assumes that the user knows better than it does.

Note that if you declared the variable as static it actually is guaranteed to be initialized to 0.

Title: Why variables start out with random values in C

Body: I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?


答:
Using background-attachment: fixed will give you the desired effect. You just need to make sure your background image works within the bounds of the div or else you will get tiling which can be turned off with background-repeat: none

.border {
  border: 1px solid #000;
  position: absolute;
}

div {
  background-image: url("https://dummyimage.com/500x250/000/fff.png");
  background-attachment: fixed;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div1" class="border" style="height:100px;width:200px"></div>
<div id="div2" class="border" style="left:225px;height:100px;width:200px"></div>
<div id="div3" class="border" style="top: 125px;height:100px;width:225px"></div>
<div id="div4" class="border" style="left:250px;top:125px;height:100px;width:175px"></div></code>```

Title: Single Background for Multiple Divs

Body:
Is there a way of having one image (PNG or SVG) as a background for multiple divs? Please see the images below as to how it would work. Also when the screen width becomes smaller and the divs line up below each other, would there be a way of changing the background to match that aswell?

DIVs without background:

The background:

DIVs with background:

Body:
Using background-attachment: fixed will give you the desired effect. You just need to make sure your background image works within the bounds of the div or else you will get tiling which can be turned off with background-repeat: none

.border {
  border: 1px solid #000;
  position: absolute;
}

div {
  background-image: url("https://dummyimage.com/500x250/000/fff.png");
  background-attachment: fixed;
}

<div id="div1" class="border" style="height:100px;width:200px"></div>
<div id="div2" class="border" style="left:225px;height:100px;width:200px"></div>
<div id="div3" class="border" style="top: 125px;height:100px;width:225px"></div>
<div id="div4" class="border" style="left:250px;top:125px;height:100px;width:175px"></div>


问:
Excel vba to read data from a oracle database which was set to readonly
I am trying to read data from oracle using adodb connection object from excel.But I am getting an error " oracle -160000 database was set to read only access".Please let me know how to resolve this.</p>

答:
Look at the recordset open method's LockType parameter and use adLockReadOnly. I'm not familiar with Oracle. You may also need to CursorType parameter to adOpenForwardOnly.

Example:

```<code>Dim lobjADOConnection As ADODB.Connection
Dim lobjADOData As ADODB.Recordset
Dim lstrSQL As String

Set lobjADOConnection = New ADODB.Connection
lobjADOConnection.Open ...

Set lobjADOData = New ADODB.Recordset

lstrSQL = "<your query here>"

lobjADOData.Open lstrSQL, lobjADOConnection, adOpenForwardOnly, adLockReadOnly '<===here
If Not lobjADOData.BOF Then
    lobjADOData.MoveFirst
    Do While Not lobjADOData.EOF
        DoEvents
        .
        .
        .
</code>```

or if you just want to dump the data into a worksheet

```<code>Dim lobjTargetSheet As Worksheet

Set lobjTargetSheet = ThisWorkbook.Sheets("<SomeSheetName>")
With lobjTargetSheet
    .Select
    .Range("1:" & .UsedRange.Rows.count + 1).Delete xlUp
    .Range("A1").Select
    .Range("A1").CopyFromRecordset lobjADOData
End With
</code>```

Body:
Look at the recordset open method's LockType parameter and use adLockReadOnly. I'm not familiar with Oracle. You may also need to CursorType parameter to adOpenForwardOnly.

Example:

Dim lobjADOConnection As ADODB.Connection
Dim lobjADOData As ADODB.Recordset
Dim lstrSQL As String

Set lobjADOConnection = New ADODB.Connection
lobjADOConnection.Open ...

Set lobjADOData = New ADODB.Recordset

lstrSQL = "<your query here>"

lobjADOData.Open lstrSQL, lobjADOConnection, adOpenForwardOnly, adLockReadOnly '<===here
If Not lobjADOData.BOF Then
    lobjADOData.MoveFirst
    Do While Not lobjADOData.EOF
        DoEvents
        .
        .
        .

or if you just want to dump the data into a worksheet

Dim lobjTargetSheet As Worksheet

Set lobjTargetSheet = ThisWorkbook.Sheets("<SomeSheetName>")
With lobjTargetSheet
    .Select
    .Range("1:" & .UsedRange.Rows.count + 1).Delete xlUp
    .Range("A1").Select
    .Range("A1").CopyFromRecordset lobjADOData
End With


问:
Best Js framework can be used with sharepoint
I new in Sharepoint, i wanna create forms, session, CRUD operations, send messages via Skype API.

i am confused which JS framework i have to use with Sharepoint in client-side and why?

Angular JS, View JS, Knockout JS, React JS.. Or other JS framework?

答: SharePoint is agnostic to these frameworks. Means, it does not use any of the listed frameworks. Also it does not require you to use any of those frameworks. So you can choose whatever you know better. Or you can go without any framework at all.</p>


问:
Perl Template with strict option: how to check whether a variable is defined?
The following code dies with a var.undef error because var is not defined. It works if I change the STRICT option to 0, but I'd like to keep strict checks, unless it's in an [% IF var %] check in the template. How do I do that?

```<code>use strict;
use warnings;
use Template;

my $t = Template->new(STRICT => 1) || die Template->error();
my $template = '[% IF var %][% var %][% END%]';
my $output = '';
$t->process(\$template, {}, \$output) || die $t->error(), "\n";
print "$output\n";
</code>```

答:
You are sending in an empty hash reference that doesn't contain the var variable that you're asking the template to display.

You can either check in your Perl code to set a sane default (in this example, I just hard-code it into the call to process()):

```<code>$t->process(\$template, {var => 55}, $output) || die $t->error(), "\n";
</code>```

Output:

```<code>55
</code>```

...or, you can tell the template to set its own sane default if the var variable isn't sent on the way in (ie, it's undefined):

```<code>my $template = '[% DEFAULT var = "sane" %][% IF var %][% var %][% END%]';
</code>```

Output:

```<code>sane
</code>```

Body:
The following code dies with a var.undef error because var is not defined. It works if I change the STRICT option to 0, but I'd like to keep strict checks, unless it's in an [% IF var %] check in the template. How do I do that?

use strict;
use warnings;
use Template;

my $t = Template->new(STRICT => 1) || die Template->error();
my $template = '[% IF var %][% var %][% END%]';
my $output = '';
$t->process(\$template, {}, \$output) || die $t->error(), "\n";
print "$output\n";

Body:
You are sending in an empty hash reference that doesn't contain the var variable that you're asking the template to display.

You can either check in your Perl code to set a sane default (in this example, I just hard-code it into the call to process()):

$t->process(\$template, {var => 55}, $output) || die $t->error(), "\n";

Output:

55

...or, you can tell the template to set its own sane default if the var variable isn't sent on the way in (ie, it's undefined):

my $template = '[% DEFAULT var = "sane" %][% IF var %][% var %][% END%]';

Output:

sane


问:
How to make CORS Request
I'm making a weather app with React.js and I want to make a CORS request for fetching data from weather underground website.
What I want is getting a city name, use autocomplete API for finding the city and fetch data for that city.

The problem is, everytime I give a city name (for example: tehran), the xhr.onerror event handler runs and I get this error:

XMLHttpRequest cannot load http://autocomplete.wunderground.com/aq?query=tehran. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my code for fetching data:

```<code>var axios = require('axios');

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }
    return xhr;
}

function makeCorsRequest(url) {
    var autoCompleteText;
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    xhr.onload = function() {
        var text = xhr.responseText;
        autoCompleteText = text;
    }
    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    }
    xhr.send();
    return autoCompleteText;
}

const WEATHER_UNDERGROUND_AUTOCOMPLETE = 'http://autocomplete.wunderground.com/aq?query=';
const WEATHER_UNDERGROUND_URL = 'http://api.wunderground.com/api/eda52d06d32d71e9/conditions/q/';

module.exports = {
    getTemp: function(city) {
        var encodedCity = encodeURIComponent(city);
        var requestAutoComplete = `${WEATHER_UNDERGROUND_AUTOCOMPLETE}${encodedCity}`;

        var autoCompleteText = makeCorsRequest(requestAutoComplete);
        var foundCity = autoCompleteText.RESULTS[0].name.split(', ');
        var requestUrl = `${WEATHER_UNDERGROUND_URL}${foundCity[1]}/${foundcity[0]}.json`;
        return axios.get(requestUrl).then(function(res) {
            return res.data.current_observation.temp_c;
        }, function(err) {
            throw new Error(res.data.error);
        });
    }
}
</code>```

Screenshot of the app:
localhost:3000/weather page

答:
Are you bound to using axios? if not I would highly recommend Mozilla's Fetch. To make a cors api call with fetch, do this:

```<code>var myInit = {
    method: 'GET',
    mode: 'cors',
    credentials: 'include'
};

fetch(YOUR_URL, myInit)
.then(function(response) {
    return response.json();
})
.then(function(json) {
    console.log(json)
});
</code>```

You can learn more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Title: How to make CORS Request

Body:
I'm making a weather app with React.js and I want to make a CORS request for fetching data from weather underground website.
What I want is getting a city name, use autocomplete API for finding the city and fetch data for that city.

The problem is, everytime I give a city name (for example: tehran), the xhr.onerror event handler runs and I get this error:

XMLHttpRequest cannot load http://autocomplete.wunderground.com/aq?query=tehran. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my code for fetching data:

var axios = require('axios');

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }
    return xhr;
}

function makeCorsRequest(url) {
    var autoCompleteText;
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    xhr.onload = function() {
        var text = xhr.responseText;
        autoCompleteText = text;
    }
    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    }
    xhr.send();
    return autoCompleteText;
}

const WEATHER_UNDERGROUND_AUTOCOMPLETE = 'http://autocomplete.wunderground.com/aq?query=';
const WEATHER_UNDERGROUND_URL = 'http://api.wunderground.com/api/eda52d06d32d71e9/conditions/q/';

module.exports = {
    getTemp: function(city) {
        var encodedCity = encodeURIComponent(city);
        var requestAutoComplete = `${WEATHER_UNDERGROUND_AUTOCOMPLETE}${encodedCity}`;

        var autoCompleteText = makeCorsRequest(requestAutoComplete);
        var foundCity = autoCompleteText.RESULTS[0].name.split(', ');
        var requestUrl = `${WEATHER_UNDERGROUND_URL}${foundCity[1]}/${foundcity[0]}.json`;
        return axios.get(requestUrl).then(function(res) {
            return res.data.current_observation.temp_c;
        }, function(err) {
            throw new Error(res.data.error);
        });
    }
}

Screenshot of the app:
localhost:3000/weather page

Body:
Are you bound to using axios? if not I would highly recommend Mozilla's Fetch. To make a cors api call with fetch, do this:

var myInit = {
    method: 'GET',
    mode: 'cors',
    credentials: 'include'
};

fetch(YOUR_URL, myInit)
.then(function(response) {
    return response.json();
})
.then(function(json) {
    console.log(json)
});

You can learn more here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


问:
Django Rest Framework: ModelSerializer and choosing fields per HTTP METHOD
Say I have a phone book with 3 fields and a model to represent it:

Name

Age

Phone

I'm writing an API to post new entries, get existing entries and modify existing entries. For the sake of this question, my constraints are:

for POST I'd like to be able to write all three fields when creating a new record.

for GET I'd like to return only the Age and Phone

for PUT I'd like to allow only the phone field to be updated.

Given the rigidness of the class meta and where I can define extra_kwargs with definitions for each field such as read_only and write_only -- Will I need three separate ModelSerializer classes? or can I somehow have some kind of condition in a single ModelSerializer in order to support my constraints.

Thanks

答:
or can I somehow have some kind of condition in a single
  ModelSerializer in order to support my constraints.

Yes, you can in fact when most people start off using DRF. This is the approach taken. Certainly, I went down that path myself. But it's just not worth it.

It's much much easier and fewer lines of code to use multiple serializes. Specially if you are using Views instead of Viewsets. If you are using Viewsets, override the get_serializer_class


问:
How to show all Case When Then records even if NULL in MySQL
i have to display how many users voted for poll 2, but separated in age ranges.

My current query works fine; but I'm having trouble when a specific range doesn't have any users in it. For example, if no users between the ages of 40-49 voted for poll 2, then the result should be:

age_1 [13-19] = 0

age_2 [20-29] = 3

age_3 [30-39] = 1

age_4 [40-49] = 0

age_5 [50+] = 0

...but instead I'm getting this:

age_2 [20-29] = 3

age_3 [30-39] = 1

So, what I need is for all age ranges to appear in the results, even when there are no matches. This is my current query:

```<code>SELECT
CASE
    WHEN age BETWEEN 13 AND 19 THEN "age_1"
    WHEN age BETWEEN 20 and 29 THEN "age_2"
    WHEN age BETWEEN 30 and 39 THEN "age_3"
    WHEN age BETWEEN 40 and 49 THEN "age_4"
    WHEN age >= 50 THEN "age_5"
END as age_range,
COUNT(*) AS q
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata
JOIN poll_vote ON poll_vote.id_user = udata.id_user
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL
GROUP BY age_range
ORDER BY age_range
</code>```

Here's the SQL Fiddle with the example data. Thanks!

答:
I'd use a left join with your totals and coalesce.

```<code>select totals.age_range, coalesce(ages.q,0) total from
(
    select 'age_1' age_range
    union select 'age_2' age_range
    union select 'age_3' age_range
    union select 'age_4' age_range
    union select 'age_5' age_range ) totals
left join (
  SELECT
CASE
    WHEN age BETWEEN 13 AND 19 THEN "age_1"
    WHEN age BETWEEN 20 and 29 THEN "age_2"
    WHEN age BETWEEN 30 and 39 THEN "age_3"
    WHEN age BETWEEN 40 and 49 THEN "age_4"
    WHEN age >= 50 THEN "age_5"
END as age_range,
COUNT(*) AS q
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata
JOIN poll_vote ON poll_vote.id_user = udata.id_user
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL
GROUP BY age_range
ORDER BY age_range
  ) ages
on totals.age_range = ages.age_range
</code>```

-- results

age_range   total

age_1   0

age_2   3

age_3   1

age_4   0

age_5   0

Body:
i have to display how many users voted for poll 2, but separated in age ranges.

My current query works fine; but I'm having trouble when a specific range doesn't have any users in it. For example, if no users between the ages of 40-49 voted for poll 2, then the result should be:

age_1 [13-19] = 0

age_2 [20-29] = 3

age_3 [30-39] = 1

age_4 [40-49] = 0

age_5 [50+] = 0

...but instead I'm getting this:

age_2 [20-29] = 3

age_3 [30-39] = 1

So, what I need is for all age ranges to appear in the results, even when there are no matches. This is my current query:

SELECT
CASE
    WHEN age BETWEEN 13 AND 19 THEN "age_1"
    WHEN age BETWEEN 20 and 29 THEN "age_2"
    WHEN age BETWEEN 30 and 39 THEN "age_3"
    WHEN age BETWEEN 40 and 49 THEN "age_4"
    WHEN age >= 50 THEN "age_5"
END as age_range,
COUNT(*) AS q
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata
JOIN poll_vote ON poll_vote.id_user = udata.id_user
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL
GROUP BY age_range
ORDER BY age_range

Here's the SQL Fiddle with the example data. Thanks!

Body:
I'd use a left join with your totals and coalesce.

select totals.age_range, coalesce(ages.q,0) total from
(
    select 'age_1' age_range
    union select 'age_2' age_range
    union select 'age_3' age_range
    union select 'age_4' age_range
    union select 'age_5' age_range ) totals
left join (
  SELECT
CASE
    WHEN age BETWEEN 13 AND 19 THEN "age_1"
    WHEN age BETWEEN 20 and 29 THEN "age_2"
    WHEN age BETWEEN 30 and 39 THEN "age_3"
    WHEN age BETWEEN 40 and 49 THEN "age_4"
    WHEN age >= 50 THEN "age_5"
END as age_range,
COUNT(*) AS q
FROM (SELECT user.id_user AS id_user, TIMESTAMPDIFF(YEAR, user.birthday, CURDATE()) AS age FROM user) AS udata
JOIN poll_vote ON poll_vote.id_user = udata.id_user
WHERE poll_vote.id_poll = 2 AND udata.age IS NOT NULL
GROUP BY age_range
ORDER BY age_range
  ) ages
on totals.age_range = ages.age_range

-- results

age_range   total

age_1   0

age_2   3

age_3   1

age_4   0

age_5   0


问:
Validating a String in a Class List C#
Im making a project in C# Console Application and it is a Sports Club Management Software for school. I created a Class List Athletes and I got several paramenters, one of it is the Athlete's ID... My question is, when I choose the "Add Athlete" option, how can I check if there´s already an ID in the whole list. You probably thinking: "Ohh... Well its preety ez, just a do while, and a for method in it and use the Contain method..." Well Ive tryed that and I didn't quite got it... Ive been programming for some months now... Its not that I am a very skilled programmer but :/ ...

This is what I tryed doing:

```<code>    do
    {
        for (int i = 0; i < Athletes.Count; i++)
        {
            if (Athletes[i].id.Contains(id))
            {
                Console.WriteLine("ID already exists, please insert another ID!");
                Console.WriteLine();
                Console.Write("Id: ");
                id = Console.ReadLine();
            }
        }
    } while (Athletes[i]);
</code>```

the thing is, as you can see, I cant use the [i] in the do while what makes it impossible to go through the list. I thought about getting a boolean but Im not really into booleans. Its probably a preety ez to fix problem but I really cant figger it out. Thanks guys. :)

答:
Override Equals() in Athlete class.

```<code>public override bool Equals (Object otherAthlete) {
    if (otherAthlete == null) return false;
    if (! otherAthlete is typeof(Athlete)) return false;

    return this.ID == otherAthlete.ID;
}
</code>```

That will make List<Athelete>.Contains() work. No need to iterate.

```<code>public void Add (Athlete newAthlete) {
    if (newAthelete == null) return;

    if (! athleteList.Contains(newAthlete))
       athleteList.Add(newAthlete);

}
</code>```

Title: Validating a String in a Class List C#

Body:
Im making a project in C# Console Application and it is a Sports Club Management Software for school. I created a Class List Athletes and I got several paramenters, one of it is the Athlete's ID... My question is, when I choose the "Add Athlete" option, how can I check if there´s already an ID in the whole list. You probably thinking: "Ohh... Well its preety ez, just a do while, and a for method in it and use the Contain method..." Well Ive tryed that and I didn't quite got it... Ive been programming for some months now... Its not that I am a very skilled programmer but :/ ...

This is what I tryed doing:

    do
    {
        for (int i = 0; i < Athletes.Count; i++)
        {
            if (Athletes[i].id.Contains(id))
            {
                Console.WriteLine("ID already exists, please insert another ID!");
                Console.WriteLine();
                Console.Write("Id: ");
                id = Console.ReadLine();
            }
        }
    } while (Athletes[i]);

the thing is, as you can see, I cant use the [i] in the do while what makes it impossible to go through the list. I thought about getting a boolean but Im not really into booleans. Its probably a preety ez to fix problem but I really cant figger it out. Thanks guys. :)

Body:
Override Equals() in Athlete class.

public override bool Equals (Object otherAthlete) {
    if (otherAthlete == null) return false;
    if (! otherAthlete is typeof(Athlete)) return false;

    return this.ID == otherAthlete.ID;
}

That will make List<Athelete>.Contains() work. No need to iterate.

public void Add (Athlete newAthlete) {
    if (newAthelete == null) return;

    if (! athleteList.Contains(newAthlete))
       athleteList.Add(newAthlete);

}


问:
When I call the function it shows nothing?
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

This is my script in python 3.5:

```<code>def plin1():
    for i in range(1000,1):
        for j in range(1000,1):
            if str(i*j)==str(i*j)[::-1]:
                break
            return i*j
        print(i,'*',j,'=',i*j)
</code>```

But when I call this function, nothing is printed. What's wrong?

答:
range(start, stop[, step]) -> range object

range() requires the first argument to be less than the second when step is positive, and step defaults to 1 when range() is called with 2 arguments. Hence the range object yields an empty sequence and the body of the for loop is never entered:

```<code>>>> list(range(1000, 1))
[]
</code>```

However, by specifying a negative value for step, you can get the sequence that you require e.g.:

```<code>>>> list(range(10, 1))
[]
>>> list(range(10, 1, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2]
</code>```

So in your case you would do this:

```<code>for i in range(999, 99, -1):
    for j in range(999, 99, -1):
        # etc...
</code>```

which would then iterate over all 3 digit numbers starting at the largest.

Also the use of return is incorrect and it will cause the function to terminate without printing anything. Here is a corrected version:

```<code>def plin1():
    for i in range(999, 99, -1):
        for j in range(999, 99, -1):
            if str(i*j) == str(i*j)[::-1]:
                return i*j
            print(i,'*',j,'=',i*j)
</code>```

Now the function returns the value only when it finds a palindrome. If there were no palindromes, the function would return None.

Notice, however, that this does not produce the largest palindrome that is the product of two 3 digit numbers. This function returns 580085 which is 995 * 583. But the largest one is 993 * 913 = 906609. You need to figure out which is the largest palindrome across all products, not just the first palindrome found. Here is a generator expression that will produce the required result:

```<code>max((i*j,i,j) for i in range(100, 1000) for j in range(100, 1000)
        if str(i*j) == str(i*j)[::-1])
</code>```

Which produces the tuple (906609, 993, 913).

Probably there are optimisations that could be made to reduce the number of calculations.

Body:
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

This is my script in python 3.5:

def plin1():
    for i in range(1000,1):
        for j in range(1000,1):
            if str(i*j)==str(i*j)[::-1]:
                break
            return i*j
        print(i,'*',j,'=',i*j)

But when I call this function, nothing is printed. What's wrong?

Body:
range(start, stop[, step]) -> range object

range() requires the first argument to be less than the second when step is positive, and step defaults to 1 when range() is called with 2 arguments. Hence the range object yields an empty sequence and the body of the for loop is never entered:

>>> list(range(1000, 1))
[]

However, by specifying a negative value for step, you can get the sequence that you require e.g.:

>>> list(range(10, 1))
[]
>>> list(range(10, 1, -1))
[10, 9, 8, 7, 6, 5, 4, 3, 2]

So in your case you would do this:

for i in range(999, 99, -1):
    for j in range(999, 99, -1):
        # etc...

which would then iterate over all 3 digit numbers starting at the largest.

Also the use of return is incorrect and it will cause the function to terminate without printing anything. Here is a corrected version:

def plin1():
    for i in range(999, 99, -1):
        for j in range(999, 99, -1):
            if str(i*j) == str(i*j)[::-1]:
                return i*j
            print(i,'*',j,'=',i*j)

Now the function returns the value only when it finds a palindrome. If there were no palindromes, the function would return None.

Notice, however, that this does not produce the largest palindrome that is the product of two 3 digit numbers. This function returns 580085 which is 995 * 583. But the largest one is 993 * 913 = 906609. You need to figure out which is the largest palindrome across all products, not just the first palindrome found. Here is a generator expression that will produce the required result:

max((i*j,i,j) for i in range(100, 1000) for j in range(100, 1000)
        if str(i*j) == str(i*j)[::-1])

Which produces the tuple (906609, 993, 913).

Probably there are optimisations that could be made to reduce the number of calculations.