问:
WSO2 METRIC DB corrupted
For my qa instance of WSO2 API Manager (2.0.0), I am facing issues with the log files increasing rapidly. I tried to manage the log file sizes through config settings (Carbon and Audit). However, I find the other logs files are filling fast - especially the http_access*.log and wso2-apigw-errors.log. Right now I have written a shell script to remove them periodically. The real problem behind these growing logs files has to do with the corrupted METRIC H2 DB, I think.

```<code>TID: [] [] [2017-11-11 08:45:37,589] ERROR
{org.wso2.carbon.metrics.jdbc.reporter.JDBCReporter} -  Error when
reporting gauges {org.wso2.carbon.metrics.jdbc.reporter.JDBCReporter}
org.h2.jdbc.JdbcSQLException: Sequence
"SYSTEM_SEQUENCE_1AC7F1C3_AD26_4518_BBF0_1E63028E0201" not found; SQL statement:
CREATE CACHED TABLE PUBLIC.METRIC_TIMER(
    ID BIGINT DEFAULT (NEXT VALUE FOR PUBLIC.SYSTEM_SEQUENCE_1AC7F1C3_AD26_4518_BBF0_1E63028E0201) NOT NULL NULL_TO_DEFAULT SEQUENCE PUBLIC.SYSTEM_SEQUENCE_1AC7F1C3_AD26_4518_BBF0_1E63028E0201,
SOURCE VARCHAR(255) NOT NULL,
TIMESTAMP BIGINT NOT NULL,
NAME VARCHAR(255) NOT NULL,
COUNT BIGINT NOT NULL,
MAX DOUBLE NOT NULL,
MEAN DOUBLE NOT NULL,
MIN DOUBLE NOT NULL,
STDDEV DOUBLE NOT NULL,
P50 DOUBLE NOT NULL,
P75 DOUBLE NOT NULL,
P95 DOUBLE NOT NULL,
P98 DOUBLE NOT NULL,
P99 DOUBLE NOT NULL,
P999 DOUBLE NOT NULL,
MEAN_RATE DOUBLE NOT NULL,
M1_RATE DOUBLE NOT NULL,
M5_RATE DOUBLE NOT NULL,
M15_RATE DOUBLE NOT NULL,
RATE_UNIT VARCHAR(50) NOT NULL,
DURATION_UNIT VARCHAR(50) NOT NULL
) [90036-140]
</code>```

For now, I have disabled the Metrics (metrics.xml). How can I reset the Metrics H2 DB and start collecting metrics again? Or how can I point the Metrics DB to an RDBMS?

答:
1) To get the H2 working:

Shut down the server.

Delete WSO2METRICS_DB.h2.db and WSO2METRICS_DB.lock.db files in
<APIM_HOME>/repository/database/.

Start the server again with ./wso2server.sh -Dsetup

2) Update <APIM_HOME>/repository/conf/datasources/metrics-datasources.xml with your RDBMS database details and restart the server.

Title: WSO2 METRIC DB corrupted

Body:
For my qa instance of WSO2 API Manager (2.0.0), I am facing issues with the log files increasing rapidly. I tried to manage the log file sizes through config settings (Carbon and Audit). However, I find the other logs files are filling fast - especially the http_access*.log and wso2-apigw-errors.log. Right now I have written a shell script to remove them periodically. The real problem behind these growing logs files has to do with the corrupted METRIC H2 DB, I think.

TID: [] [] [2017-11-11 08:45:37,589] ERROR
{org.wso2.carbon.metrics.jdbc.reporter.JDBCReporter} -  Error when
reporting gauges {org.wso2.carbon.metrics.jdbc.reporter.JDBCReporter}
org.h2.jdbc.JdbcSQLException: Sequence
"SYSTEM_SEQUENCE_1AC7F1C3_AD26_4518_BBF0_1E63028E0201" not found; SQL statement:
CREATE CACHED TABLE PUBLIC.METRIC_TIMER(
    ID BIGINT DEFAULT (NEXT VALUE FOR PUBLIC.SYSTEM_SEQUENCE_1AC7F1C3_AD26_4518_BBF0_1E63028E0201) NOT NULL NULL_TO_DEFAULT SEQUENCE PUBLIC.SYSTEM_SEQUENCE_1AC7F1C3_AD26_4518_BBF0_1E63028E0201,
SOURCE VARCHAR(255) NOT NULL,
TIMESTAMP BIGINT NOT NULL,
NAME VARCHAR(255) NOT NULL,
COUNT BIGINT NOT NULL,
MAX DOUBLE NOT NULL,
MEAN DOUBLE NOT NULL,
MIN DOUBLE NOT NULL,
STDDEV DOUBLE NOT NULL,
P50 DOUBLE NOT NULL,
P75 DOUBLE NOT NULL,
P95 DOUBLE NOT NULL,
P98 DOUBLE NOT NULL,
P99 DOUBLE NOT NULL,
P999 DOUBLE NOT NULL,
MEAN_RATE DOUBLE NOT NULL,
M1_RATE DOUBLE NOT NULL,
M5_RATE DOUBLE NOT NULL,
M15_RATE DOUBLE NOT NULL,
RATE_UNIT VARCHAR(50) NOT NULL,
DURATION_UNIT VARCHAR(50) NOT NULL
) [90036-140]

For now, I have disabled the Metrics (metrics.xml). How can I reset the Metrics H2 DB and start collecting metrics again? Or how can I point the Metrics DB to an RDBMS?


来源: stackexchange

问:
When I change the orientation and if the player is started, it automatically goes to stop
I have a player that plays the track. after changing orientation I check the state player!.currentTime().seconds and -  it is reset.

how to make that when the track is started, it is not reset after changing orientation but continues to play from the same second.
I check change orientation and input this code, but this don't work.

```<code>override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if(player != nil){
            if !isPause {
                print("currentTime player\(player!.currentTime().seconds)")
                player!.play()

            }
        }
}
</code>```

print - currentTime player0.0

my action, tap play btn:

```<code>    //MARK: P L A Y   &   P A U S E

 @IBAction func actionButton(_ sender: UIButton) { if playbackSlider.value < 30 {
            if player?.rate != 0{
                isPause = true
                print("currentTime \(player!.currentTime().seconds)")
                player?.pause()
                actionButton?.setImage(UIImage(named: "ic_play"), for: .normal)
                playIndicator.isHidden = true
                playIndicator.stopAnimating()
            }else{
                player?.play()
                print("currentTime \(player!.currentTime().seconds)")
                isPause = false
                actionButton?.setImage(UIImage(named: "ic_pause"), for: .normal)
                playIndicator.isHidden = false
                playIndicator.startAnimating()
            }
        }
    }
</code>```

Thx.

答:
Please check in viewWillTransition you are re-instantiating the player. add some condition to prevent this scenario. Issue will resolve.</p>

```<code>        guard player == nil else {
        return
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a player that plays the track. after changing orientation I check the state player!.currentTime().seconds and -  it is reset.

how to make that when the track is started, it is not reset after changing orientation but continues to play from the same second.
I check change orientation and input this code, but this don't work.

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if(player != nil){
            if !isPause {
                print("currentTime player\(player!.currentTime().seconds)")
                player!.play()

            }
        }
}

print - currentTime player0.0

my action, tap play btn:

    //MARK: P L A Y   &   P A U S E

 @IBAction func actionButton(_ sender: UIButton) { if playbackSlider.value < 30 {
            if player?.rate != 0{
                isPause = true
                print("currentTime \(player!.currentTime().seconds)")
                player?.pause()
                actionButton?.setImage(UIImage(named: "ic_play"), for: .normal)
                playIndicator.isHidden = true
                playIndicator.stopAnimating()
            }else{
                player?.play()
                print("currentTime \(player!.currentTime().seconds)")
                isPause = false
                actionButton?.setImage(UIImage(named: "ic_pause"), for: .normal)
                playIndicator.isHidden = false
                playIndicator.startAnimating()
            }
        }
    }

Thx.

Body:
Please check in viewWillTransition you are re-instantiating the player. add some condition to prevent this scenario. Issue will resolve.

        guard player == nil else {
        return
    }


问:
System.NotImplementedException: 'ID3v2 Version 2 is not supported.'
hope all is well.  I am getting the error below while trying to obtain the meta tags from an MP3 file on Visual Studio within a C# form application.  Any help is appreciated. Thanks in advance.

System.NotImplementedException: 'ID3v2 Version 2 is not supported.'

this is what my code looks like so far:

```<code>Mp3Lib.Mp3File mFile = new Mp3Lib.Mp3File(file: @"C:\Users\user\Music\song.mp3");
string mArtist = mFile.TagHandler.Artist;
</code>```

答:
It would seem that the 'MP3Lib' library you're using does not support ID3v2 Version 2.

As alternatives, I'd suggest you use either ATL.NET (https://github.com/Zeugma440/atldotnet) or TagLibSharp (https://github.com/mono/taglib-sharp).

Both are up-to-date libraries that can read ID3v2.x metadata from MP3 files, and much more.

Body:
hope all is well.  I am getting the error below while trying to obtain the meta tags from an MP3 file on Visual Studio within a C# form application.  Any help is appreciated. Thanks in advance.

System.NotImplementedException: 'ID3v2 Version 2 is not supported.'

this is what my code looks like so far:

Mp3Lib.Mp3File mFile = new Mp3Lib.Mp3File(file: @"C:\Users\user\Music\song.mp3");
string mArtist = mFile.TagHandler.Artist;


问:
how to use jquery auto-complete to load from mysql database
What I want to do is to be able to load data from the database which will show up as an auto-complete text below the textbox.
I'm using the ajax function in jquery to load data from the database. My problem now is how to put that data in the auto-suggest box.</p>

```<code><html>
  <head>
    <script src="js/jq.js"></script>
    <link rel="stylesheet" href="css/otocomplete.css" type="text/css" />
    <link rel="stylesheet" href="css/otocomplete.css" type="text/css" />
    <script type="text/javascript" src="js/bigiframe.js"></script>
    <script type="text/javascript" src="js/otocomplete.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $('#example').keyup(function(){
          var inpval = $('#example').val();
          $.ajax({
                type: 'POST',
            data: ({p : inpval}),
                url: 'query.php',
                success: function(data) {
                      $("#yoh").autocomplete(data);
                }
            });
         });
      });
    </script>
  </head>
  <body>
     text: <input id="example" />
     <div id="yoh"></div>
  </body>
</html>
</code>```

答:
Are otocomplete.js/otocomplete.css the autocomplete plugin & its stylesheet? I'll assume that they are.

Is there a reason you are putting the autocomplete inside of an ajax method? It works without it.

```<code><link rel="stylesheet" type="text/css" href="http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.css">
<script src="http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#example").autocomplete("query.php", {
            width: 260,
            selectFirst: false
        });
    });
</script>
</code>```

Your php file should output one result per line, like so:

```<code>Gyr Falcon
Lanner Falcon
Red Falcon
...
</code>```

This is all lifted straight from http://view.jquery.com/trunk/plugins/autocomplete/demo/ but I tested it, so I know it will work.

EDIT: I just read that the plugin's author no longer supports it, and recommends using jQuery UI's autocomplete. Personally, I'm not a big fan of jQuery UI, I just want the author's intent to be represented here.

EDIT 2: I didn't realize that you're trying to do some kind of custom UI for the auto suggest. Feel free to ignore this.

ContentLicense: CC BY-SA 2.5

Body:
What I want to do is to be able to load data from the database which will show up as an auto-complete text below the textbox.
I'm using the ajax function in jquery to load data from the database. My problem now is how to put that data in the auto-suggest box.

    <link rel="stylesheet" href="css/otocomplete.css" type="text/css" />
    <link rel="stylesheet" href="css/otocomplete.css" type="text/css" />

     text: <input id="example" />

Body:
Are otocomplete.js/otocomplete.css the autocomplete plugin & its stylesheet? I'll assume that they are.

Is there a reason you are putting the autocomplete inside of an ajax method? It works without it.

<link rel="stylesheet" type="text/css" href="http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.css">
<script src="http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#example").autocomplete("query.php", {
            width: 260,
            selectFirst: false
        });
    });
</script>

Your php file should output one result per line, like so:

Gyr Falcon
Lanner Falcon
Red Falcon
...

This is all lifted straight from http://view.jquery.com/trunk/plugins/autocomplete/demo/ but I tested it, so I know it will work.

EDIT: I just read that the plugin's author no longer supports it, and recommends using jQuery UI's autocomplete. Personally, I'm not a big fan of jQuery UI, I just want the author's intent to be represented here.

EDIT 2: I didn't realize that you're trying to do some kind of custom UI for the auto suggest. Feel free to ignore this.


问:
Logic to pic odd dates using python
I have a dates in PDF with following pages with dates. I need the following 08/30/1941 pages alone using python. Looking for logic?</p>

```<code>{'05/20/2016': [1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6],
 '06/20/2016': [4],
 '08/30/1941': [1, 5]}
</code>```

答:
So what you will  need to do is Use PyPDF2 or PDFMiner to extract text from your PDF`s

PDFMiner

```<code>from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO

def convert_pdf_to_txt(path):
  rsrcmgr = PDFResourceManager()
  retstr = StringIO()
  codec = 'utf-8'
  laparams = LAParams()
  device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
  fp = open(path, 'rb')
  interpreter = PDFPageInterpreter(rsrcmgr, device)
  password = ""
  maxpages = 0
  caching = True
  pagenos=set()

  for pageNumber, pages in enumerate(PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True)):
    interpreter.process_page(pages)

#for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
    #interpreter.process_page(0)

 text = retstr.getvalue()

 fp.close()
 device.close()
 retstr.close()
 words = text.split('\n')
 return words
</code>```

Use the above function to extract text

```<code>a_list = convert_pdf_to_txt(path)
</code>```

This will return a list and the you can basically go through the elements in list

import re

```<code>try:
   for index, values in enumerate(a_list):
     date_to_find = re.compile(r"08/30/1941")
     Date_to_find = filter(date_to_find.match, values))
     if Date_to_find == []:
        print("The Date is not available")
     else:
        found = a_list[index]
        Date_to_find = re.match(r"(08/30/1941:)(.*\Z)")
        Date_Found = Date_to_find.group(2)
  print(Date_Found)
except:
   print("There was some error")
</code>```

Title: Logic to pic odd dates using python

Body:
I have a dates in PDF with following pages with dates. I need the following 08/30/1941 pages alone using python. Looking for logic?

{'05/20/2016': [1, 1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6],
 '06/20/2016': [4],
 '08/30/1941': [1, 5]}

Body:
So what you will  need to do is Use PyPDF2 or PDFMiner to extract text from your PDF`s

PDFMiner

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO

def convert_pdf_to_txt(path):
  rsrcmgr = PDFResourceManager()
  retstr = StringIO()
  codec = 'utf-8'
  laparams = LAParams()
  device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
  fp = open(path, 'rb')
  interpreter = PDFPageInterpreter(rsrcmgr, device)
  password = ""
  maxpages = 0
  caching = True
  pagenos=set()

  for pageNumber, pages in enumerate(PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True)):
    interpreter.process_page(pages)

#for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
    #interpreter.process_page(0)

 text = retstr.getvalue()

 fp.close()
 device.close()
 retstr.close()
 words = text.split('\n')
 return words

Use the above function to extract text

a_list = convert_pdf_to_txt(path)

This will return a list and the you can basically go through the elements in list

import re

try:
   for index, values in enumerate(a_list):
     date_to_find = re.compile(r"08/30/1941")
     Date_to_find = filter(date_to_find.match, values))
     if Date_to_find == []:
        print("The Date is not available")
     else:
        found = a_list[index]
        Date_to_find = re.match(r"(08/30/1941:)(.*\Z)")
        Date_Found = Date_to_find.group(2)
  print(Date_Found)
except:
   print("There was some error")


问:
LINQ Using Max() to select a single row
I'm using LINQ on an IQueryable returned from NHibernate and I need to select the row with the maximum value(s) in a couple of fields.

I've simplified the bit that I'm sticking on. I need to select the one row from my table with the maximum value in one field.

var table = new Table { new Row(id: 1, status: 10), new Row(id: 2, status: 20) }

from u in table
group u by 1 into g
where u.Status == g.Max(u => u.Status)
select u
```

<p>This is incorrect but I can't work out the right form.</p>

<p>BTW, what I'm actually trying to achieve is approximately this:</p>

<pre class="lang-cs prettyprint-override"><code>var clientAddress = this.repository.GetAll()
    .GroupBy(a => a)
    .SelectMany(
            g =>
            g.Where(
                a =>
                a.Reference == clientReference &&
                a.Status == ClientStatus.Live &&
                a.AddressReference == g.Max(x => x.AddressReference) &&
                a.StartDate == g.Max(x => x.StartDate)))
    .SingleOrDefault();
</code>```

I started with the above lambda but I've been using LINQPad to try and work out the syntax for selecting the Max().

UPDATE

Removing the GroupBy was key.

var all = this.repository.GetAll();

var address = all
            .Where(
                a =>
                a.Reference == clientReference &&
                a.Status == ClientStatus.Live &&
                a.StartDate == all.Max(x => x.StartDate) &&
                a.AddressReference == all.Max(x => x.AddressReference))
            .SingleOrDefault();
```

答:
Simply in one line:

```<code>var result = table.First(x => x.Status == table.Max(y => y.Status));
</code>```

Notice that there are two action.
the inner action is for finding the max value,
the outer action is for get the desired object.

Title: LINQ Using Max() to select a single row

Body:
I'm using LINQ on an IQueryable returned from NHibernate and I need to select the row with the maximum value(s) in a couple of fields.

I've simplified the bit that I'm sticking on. I need to select the one row from my table with the maximum value in one field.

var table = new Table { new Row(id: 1, status: 10), new Row(id: 2, status: 20) }

from u in table
group u by 1 into g
where u.Status == g.Max(u => u.Status)
select u

This is incorrect but I can't work out the right form.

BTW, what I'm actually trying to achieve is approximately this:

var clientAddress = this.repository.GetAll()
    .GroupBy(a => a)
    .SelectMany(
            g =>
            g.Where(
                a =>
                a.Reference == clientReference &&
                a.Status == ClientStatus.Live &&
                a.AddressReference == g.Max(x => x.AddressReference) &&
                a.StartDate == g.Max(x => x.StartDate)))
    .SingleOrDefault();

I started with the above lambda but I've been using LINQPad to try and work out the syntax for selecting the Max().

UPDATE

Removing the GroupBy was key.

var all = this.repository.GetAll();

var address = all
            .Where(
                a =>
                a.Reference == clientReference &&
                a.Status == ClientStatus.Live &&
                a.StartDate == all.Max(x => x.StartDate) &&
                a.AddressReference == all.Max(x => x.AddressReference))
            .SingleOrDefault();

Body:
Simply in one line:

var result = table.First(x => x.Status == table.Max(y => y.Status));

Notice that there are two action.
the inner action is for finding the max value,
the outer action is for get the desired object.


问:
graphql-JS Express cannot resolve a field
When I execute the below code in node server. I see an error that graphql-JS cannot resolve the field "product.productTax."

Using graphql-express, visual studio code, I was trying to exactly mimic the following code from http://graphql.org/graphql-js/object-types/

```<code><!-- language: lang-js -->
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Product{
    product_id: Int!
    sku: String
    short_nm: String
    retl_price: Float!
    productTax(tax_rate: Float!): [Float!]
  }

  type Query {
    getproduct(product_id: Int, sku: String, short_nm: String, retl_price: Float): Product
  }
`);

// This class implements the Product GraphQL type
class Product {

  constructor(product_id, sku, short_nm, retl_price) {
    this.product_id = product_id;
    this.sku = sku;
    this.short_nm = short_nm;
    this.retl_price = retl_price;
  }

  productTax({tax_rate}){
    return this.retl_price * tax_rate / 100;
  }

}

// The root provides the top-level API endpoints
var root = {
  getproduct: function ({product_id, sku, short_nm, retl_price}) {
    return new Product(product_id, sku, short_nm, retl_price);
  }
}

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
</code>```

Response

答:
In your schema you have

```<code>    productTax(tax_rate: Float!): [Float!]
</code>```

so graphql is expecting an array of float values. It seems that it should be

```<code>    productTax(tax_rate: Float!): Float!
</code>```

since your productTax() method is returning one float value.

You can also add default tax rate. I don't see you are passing it anyway, so

```<code>    productTax(tax_rate: Float = 20): Float!
</code>```

Body:
When I execute the below code in node server. I see an error that graphql-JS cannot resolve the field "product.productTax."

Using graphql-express, visual studio code, I was trying to exactly mimic the following code from http://graphql.org/graphql-js/object-types/

var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Product{
    product_id: Int!
    sku: String
    short_nm: String
    retl_price: Float!
    productTax(tax_rate: Float!): [Float!]
  }

  type Query {
    getproduct(product_id: Int, sku: String, short_nm: String, retl_price: Float): Product
  }
`);

// This class implements the Product GraphQL type
class Product {

  constructor(product_id, sku, short_nm, retl_price) {
    this.product_id = product_id;
    this.sku = sku;
    this.short_nm = short_nm;
    this.retl_price = retl_price;
  }

  productTax({tax_rate}){
    return this.retl_price * tax_rate / 100;
  }

}

// The root provides the top-level API endpoints
var root = {
  getproduct: function ({product_id, sku, short_nm, retl_price}) {
    return new Product(product_id, sku, short_nm, retl_price);
  }
}

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

Response

Body:
In your schema you have

    productTax(tax_rate: Float!): [Float!]

so graphql is expecting an array of float values. It seems that it should be

    productTax(tax_rate: Float!): Float!

since your productTax() method is returning one float value.

You can also add default tax rate. I don't see you are passing it anyway, so

    productTax(tax_rate: Float = 20): Float!


问:
How to randomize the location of a button in kivy python screen manager?
I'm a newbie when it comes to python and kivy, and I have been working on this problem for a while and getting nowhere, so any help is greatly appreciated.  I am working on a behavioral task for rats, in which they would need to press a white square button on a screen to get a treat.  I want the white square to appear in one of three locations each time the stimulus screen appears.  Here is the relevant code that I have so far:

main.kv:

```<code><Stimulus>:
    on_pre_enter: self.update_pos()
    FloatLayout:
        StimButton:
            id: stimbutton
            on_press: root.manager.current = 'screen1'

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3
</code>```

and within the python main.py:

```<code>class Stimulus(Screen):
    a = ObjectProperty(None)
    def update_pos(self):
        b = randint(1,3)
        if b==1:
            a = {'x':0.1,'y':0.33}
        elif b==2:
            a = {'x':0.4,'y':0.33}
        elif b==3:
            a = {'x':0.7,'y':0.33}
        self.ids.stimbutton.pos_hint = a

class StimButton(Button):
    def on_press(self):
        deliver_pellet()
</code>```

What should happen is that a white square appears, when the rat presses it they get a treat and it switches to a dark screen.  After a delay, a white square shows up in a different one of the 3 possible locations, and they go again.  What ends up happening is that I get one white square in the lower left corner, and the next time the screen appears I have a square in one of the random 3 positions, and one in the lower left corner.  Pressing either square produces the desired outcome.  How do I get that square in the lower left to go away?

答:
You don´t show how you implement the screen1 class, however it seems as if you create another instance of your button.

A simple and reproducible example based on your code would be:

main.kv:

```<code><ScreenManagement>:
    Stimulus:
    BlackScreen:

<BlackScreen>
    name: "black_screen"
    on_pre_enter: self._sleep()

<Stimulus>:
    name: "stimulus_screen"
    stimButton_pos: self._random_pos()
    on_pre_enter: self._update_pos()

    FloatLayout:
        StimButton:
            id: stimbutton
            pos_hint: root.stimButton_pos
            on_press: root.manager.current = 'black_screen'

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3
</code>```

main.py:

```<code>import kivy
kivy.require('1.0.5')

import random
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen

class ScreenManagement(ScreenManager):
    pass

class BlackScreen(Screen):
    def _sleep(self):
        Clock.schedule_once(self._change_screen, 3)

    def _change_screen(self,  dt):
        self.manager.current = "stimulus_screen"

class Stimulus(Screen):
    stimButton_pos = ObjectProperty(None)

    def _update_pos(self):
        self.stimButton_pos = self._random_pos()

    def _random_pos(self):
        pos = random.choice(({'x':0.1,'y':0.33},
                             {'x':0.4,'y':0.33},
                             {'x':0.7,'y':0.33}))

        return pos

class StimButton(Button):
    def on_press(self):
        #deliver_pellet()
        pass

class MainApp(App):
    def build(self):
        return ScreenManagement()

if __name__ == '__main__':
    MainApp().run()
</code>```

I use kivy.clock.Clock.schedule_once to provide a delay of 3 seconds between screens.

Output:

Body:
I'm a newbie when it comes to python and kivy, and I have been working on this problem for a while and getting nowhere, so any help is greatly appreciated.  I am working on a behavioral task for rats, in which they would need to press a white square button on a screen to get a treat.  I want the white square to appear in one of three locations each time the stimulus screen appears.  Here is the relevant code that I have so far:

main.kv:

<Stimulus>:
    on_pre_enter: self.update_pos()
    FloatLayout:
        StimButton:
            id: stimbutton
            on_press: root.manager.current = 'screen1'

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3

and within the python main.py:

class Stimulus(Screen):
    a = ObjectProperty(None)
    def update_pos(self):
        b = randint(1,3)
        if b==1:
            a = {'x':0.1,'y':0.33}
        elif b==2:
            a = {'x':0.4,'y':0.33}
        elif b==3:
            a = {'x':0.7,'y':0.33}
        self.ids.stimbutton.pos_hint = a

class StimButton(Button):
    def on_press(self):
        deliver_pellet()

What should happen is that a white square appears, when the rat presses it they get a treat and it switches to a dark screen.  After a delay, a white square shows up in a different one of the 3 possible locations, and they go again.  What ends up happening is that I get one white square in the lower left corner, and the next time the screen appears I have a square in one of the random 3 positions, and one in the lower left corner.  Pressing either square produces the desired outcome.  How do I get that square in the lower left to go away?

Body:
You don´t show how you implement the screen1 class, however it seems as if you create another instance of your button.

A simple and reproducible example based on your code would be:

main.kv:

<ScreenManagement>:
    Stimulus:
    BlackScreen:

<BlackScreen>
    name: "black_screen"
    on_pre_enter: self._sleep()

<Stimulus>:
    name: "stimulus_screen"
    stimButton_pos: self._random_pos()
    on_pre_enter: self._update_pos()

    FloatLayout:
        StimButton:
            id: stimbutton
            pos_hint: root.stimButton_pos
            on_press: root.manager.current = 'black_screen'

<StimButton>
    background_normal: ''
    color: 1,1,1,1
    size_hint: 0.2, 0.3

main.py:

import kivy
kivy.require('1.0.5')

import random
from kivy.app import App
from kivy.clock import Clock
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen

class ScreenManagement(ScreenManager):
    pass

class BlackScreen(Screen):
    def _sleep(self):
        Clock.schedule_once(self._change_screen, 3)

    def _change_screen(self,  dt):
        self.manager.current = "stimulus_screen"

class Stimulus(Screen):
    stimButton_pos = ObjectProperty(None)

    def _update_pos(self):
        self.stimButton_pos = self._random_pos()

    def _random_pos(self):
        pos = random.choice(({'x':0.1,'y':0.33},
                             {'x':0.4,'y':0.33},
                             {'x':0.7,'y':0.33}))

        return pos

class StimButton(Button):
    def on_press(self):
        #deliver_pellet()
        pass

class MainApp(App):
    def build(self):
        return ScreenManagement()

if __name__ == '__main__':
    MainApp().run()

I use kivy.clock.Clock.schedule_once to provide a delay of 3 seconds between screens.

Output:


问:
Angular site with Web API and SharePoint Online
We are thinking of creating a site in Angular that would get the information from SharePoint Online site using a Web API. The site and the Web API will be  on Azure. The problem that I have is weather or not it is feaseable to query SharePoint Online using on single generic user that would authenticate for each request, or maybe using some sort of additional unique identifier for identifiyng each request, but same user overall. Do you believe it is possible? I have little experience on Azure and SharePoint Online, so any suggestion is welcomed. Thank you in advance.

BR,
Anisia

答: Yes, it is possible. At Web API level you can call sharepoint (use client-side object model (CSOM) for this) using single user for authentication.</p>


问:
laravel 5 pdf create, download & print
I have this kind of blade view right now to show customer's invoice

I saw most of the sites they are creating a pdf and show it in the browser. then I think browser allows to print and dowload and also zoom in/out. exactly like this

So any hint or way to do that easily. I have tried DomPDF but it won't let me do complex styles. I want it like open pdf in browser and do print and download

答:
using laravel 5.4 on a 32 bit ubuntu.

add these three lines to composer.json

```<code>"barryvdh/laravel-snappy": ">=0.4.0",
"h4cc/wkhtmltopdf-i386": "0.12.x",
"h4cc/wkhtmltoimage-i386": "0.12.x"
</code>```

64-bit systems

```<code>"barryvdh/laravel-snappy": ">=0.4.0",
"h4cc/wkhtmltopdf-amd64": "0.12.x",
"h4cc/wkhtmltoimage-amd64": "0.12.x",
</code>```

from your terminal , navigate to your laravel folder and type

composer update

In config/app add these two lines under 'aliases'

'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,

'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

in your terminal type

php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"

go to config/snappy and change your binary path for 'pdf' array to this

'binary'    =>  base_path('/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386'),

and 'image' array to this:

'binary'    =>  base_path('/vendor/h4cc/wkhtmltoimage-i386/bin/wkhtmltoimage-i386'),

To try it out, in your controller, you can do something like:

```<code>public function postPDFPrint() {

        $pdf = \App::make('snappy.pdf.wrapper');
        $pdf->loadHTML('<h1>Test</h1>');
        return $pdf->inline();
    }
</code>```

If you would like to print from a view, load the view and pass in the data like you normally would. I would suggest loading a specific 'view' with print-specific CSS for printing to pdf.

```<code>public function postAdminPrint()
{
        $form = Form::find(1);
        $pdf = \PDF::loadView('form.admin-print'['form'=>$form]);
        return $pdf->inline();
}
</code>```

To Debug "Exit Status Code 127: Something went wrong..." error. First we try to print via command line. Navigate to the root of your laravel installation inside your terminal and type:

```<code>vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64 http://www.google.com test.pdf
</code>```

If it is installed correctly and there are no folder permissions issue then you should see the following lines appearing in your terminal.

```<code>Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
</code>```

A print out of google's home page should appear in ur Laravel root directory. Otherwise, it is your folder permissions causing the error.

If the above works then try to change your binary paths that I wrote initially above to:

```<code>/var/www/html/new/project/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64

/var/www/html/new/project/vendor/h4cc/hkhtmltoimage-amd64/bin/wkhtmltoimage-amd64
</code>```

"/var/www/html" --> my web folder in apache
"/new/project" --> my laravel directory

How to utilize the facade's options:

```<code>// Within your controller class
use PDF;

public function YourControllerFunction(Model $model) {

$pdf = PDF::loadView('path.to.your.file',['model'=>$model])
        ->setPaper('a4')
        ->setOptions([
            'header-html'=>"/var/www/html/{your-laravel-install-folder}/resources/views/header.html", // display a image logo on every page header
            'footer-font-size'=>'8',
            'footer-left'=>'Footer Left Text',
            'footer-center'=>'Footer Center Text',
            'footer-right'=>'Footer Right Text']);

            return $pdf->inline();
      }
</code>```

Your "header.html" file

```<code><!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
            <img style="display:block;" height="100" src="https://dl.dropbox.com/{your-dropbox-image-id}?raw=1">
        </body>
    </html>
</code>```

Reference: https://github.com/barryvdh/laravel-snappy

Title: laravel 5 pdf create, download & print

Body:
using laravel 5.4 on a 32 bit ubuntu.

add these three lines to composer.json

"barryvdh/laravel-snappy": ">=0.4.0",
"h4cc/wkhtmltopdf-i386": "0.12.x",
"h4cc/wkhtmltoimage-i386": "0.12.x"

64-bit systems

"barryvdh/laravel-snappy": ">=0.4.0",
"h4cc/wkhtmltopdf-amd64": "0.12.x",
"h4cc/wkhtmltoimage-amd64": "0.12.x",

from your terminal , navigate to your laravel folder and type

composer update

In config/app add these two lines under 'aliases'

'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class,

'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,

in your terminal type

php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"

go to config/snappy and change your binary path for 'pdf' array to this

'binary'    =>  base_path('/vendor/h4cc/wkhtmltopdf-i386/bin/wkhtmltopdf-i386'),

and 'image' array to this:

'binary'    =>  base_path('/vendor/h4cc/wkhtmltoimage-i386/bin/wkhtmltoimage-i386'),

To try it out, in your controller, you can do something like:

public function postPDFPrint() {

        $pdf = \App::make('snappy.pdf.wrapper');
        $pdf->loadHTML('<h1>Test</h1>');
        return $pdf->inline();
    }

If you would like to print from a view, load the view and pass in the data like you normally would. I would suggest loading a specific 'view' with print-specific CSS for printing to pdf.

public function postAdminPrint()
{
        $form = Form::find(1);
        $pdf = \PDF::loadView('form.admin-print'['form'=>$form]);
        return $pdf->inline();
}

To Debug "Exit Status Code 127: Something went wrong..." error. First we try to print via command line. Navigate to the root of your laravel installation inside your terminal and type:

vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64 http://www.google.com test.pdf

If it is installed correctly and there are no folder permissions issue then you should see the following lines appearing in your terminal.

Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done

A print out of google's home page should appear in ur Laravel root directory. Otherwise, it is your folder permissions causing the error.

If the above works then try to change your binary paths that I wrote initially above to:

/var/www/html/new/project/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64

/var/www/html/new/project/vendor/h4cc/hkhtmltoimage-amd64/bin/wkhtmltoimage-amd64

"/var/www/html" --> my web folder in apache
"/new/project" --> my laravel directory

How to utilize the facade's options:

// Within your controller class
use PDF;

public function YourControllerFunction(Model $model) {

$pdf = PDF::loadView('path.to.your.file',['model'=>$model])
        ->setPaper('a4')
        ->setOptions([
            'header-html'=>"/var/www/html/{your-laravel-install-folder}/resources/views/header.html", // display a image logo on every page header
            'footer-font-size'=>'8',
            'footer-left'=>'Footer Left Text',
            'footer-center'=>'Footer Center Text',
            'footer-right'=>'Footer Right Text']);

            return $pdf->inline();
      }

Your "header.html" file

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
            <img style="display:block;" height="100" src="https://dl.dropbox.com/{your-dropbox-image-id}?raw=1">
        </body>
    </html>

Reference: https://github.com/barryvdh/laravel-snappy


问:
Cygwin diff won't exclude files if a directory is included in the pattern
I need to do a recursive diff using cygwin that needs do exclude all .xml files from certain directories, but not from other directories.  According to the --help option I should be able to do this with with the --exclude=PAT option where PAT is a pattern describing the files I want to exclude from the diff.

If I do this:

```<code>diff -rw --exclude="classes/Services.xml"
</code>```

the diff does not ignore the Services.xml file in the classes directory.  If I do this

```<code>diff -rw --exclude="Services.xml"
</code>```

the diff does ignore the Services.xml file in all directories.

I need to do something like this:

```<code>diff -rw --exclude="*/generated/resources/client/*.xml"
</code>```

to ignore all .xml files in the directory */generated/resources/client/.

Whenever I add path information to the --exclude pattern cygwin does not ignore the file(s) I've specified in the pattern.

Is there some way to make cygwin diff recognize a pattern that identifies certain files in certain directories?  It seems to not be able to handle any directory information at all.

答:
Use find with an approprite expression. Assuming your trees are in tree1/ and tree2/, then

```<code>$ find tree1 -type f ! -path '*classes/Services.xml' |
    while read f; do diff -rw "$f" "tree2${f#tree1}"; done
</code>```

Hmmm, as it stands this misses files in tree2/ that do not exist in tree1/.

Body:
I need to do a recursive diff using cygwin that needs do exclude all .xml files from certain directories, but not from other directories.  According to the --help option I should be able to do this with with the --exclude=PAT option where PAT is a pattern describing the files I want to exclude from the diff.

If I do this:

diff -rw --exclude="classes/Services.xml"

the diff does not ignore the Services.xml file in the classes directory.  If I do this

diff -rw --exclude="Services.xml"

the diff does ignore the Services.xml file in all directories.

I need to do something like this:

diff -rw --exclude="*/generated/resources/client/*.xml"

to ignore all .xml files in the directory */generated/resources/client/.

Whenever I add path information to the --exclude pattern cygwin does not ignore the file(s) I've specified in the pattern.

Is there some way to make cygwin diff recognize a pattern that identifies certain files in certain directories?  It seems to not be able to handle any directory information at all.

Body:
Use find with an approprite expression. Assuming your trees are in tree1/ and tree2/, then

$ find tree1 -type f ! -path '*classes/Services.xml' |
    while read f; do diff -rw "$f" "tree2${f#tree1}"; done

Hmmm, as it stands this misses files in tree2/ that do not exist in tree1/.


问:
Why can't I get the count of enums during compile time?
I have asked How can I get the number of enums as a constant?, and I found out that I cannot get the count of enums during compile time, because C# uses reflection to do so.

I read What is reflection and why is it useful?, so I have a very basic understanding of reflection.

To get the count of enums, I can use Enum.GetNames(typeof(Item.Type)).Length;, and this happens during runtime using reflection.

I don't see any runtime knowledge needed to get the count of enums, because as far as I know, the count of enums cannot be changed during runtime.

Why does C# have to use reflection to get the count of enums? Why can't it do so during compile time?

答:
I don't see any runtime knowledge needed to get the count of enums,
  because as far as I know, the count of enums cannot be changed during
  runtime.

Here is the mistake in your reasoning: Yes, the count of enums cannot be changed during runtime. However, it can be changed between runtime:

```<code>A.dll - version 1
  public enum Foo { A }

A.dll - version 2
  public enum Foo { Bar, Baz }
</code>```

Replace version 1 of A.dll with version 2. The count of enums has changed (and the names of the values as well).

Why does C# have to use reflection to get the count of enums? Why
  can't it do so during compile time?

It could do so. But then you would run into the problem above. The compile-time calculated value could become incorrect.

Body:
I don't see any runtime knowledge needed to get the count of enums,
  because as far as I know, the count of enums cannot be changed during
  runtime.

Here is the mistake in your reasoning: Yes, the count of enums cannot be changed during runtime. However, it can be changed between runtime:

A.dll - version 1
  public enum Foo { A }

A.dll - version 2
  public enum Foo { Bar, Baz }

Replace version 1 of A.dll with version 2. The count of enums has changed (and the names of the values as well).

Why does C# have to use reflection to get the count of enums? Why
  can't it do so during compile time?

It could do so. But then you would run into the problem above. The compile-time calculated value could become incorrect.


问:
Creating partitions
Hei, I am having problem with creating partitions using PL/SQL procedure:

ORA-14019: partition bound element must be one of: string, datetime or
  interval literal, number, or MAXVALUE

It seems like problem is in format of attribute r.partition_date, I already run some tests script and tried different date format, but nothing helped.

Format of column partition_date : 2017-09-01

I am running this procedure:

```<code>    declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where a.PARTITION_NAME =  'PARTITION_20170831'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at (''N'',to_date(' || r.partition_date || ',''yyyy.mm.dd''))
      into (partition ' || r.partition_name || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/
</code>```

Even though this one is working:

```<code> declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where rownum = '1'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at ("N",to_date(''2017-01-29'',''yyyy.mm.dd''))
      into (partition ' || 'PARTITION_20170129' || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/
</code>```

Thank you for advice.

答:
I don't understand the purpose of "N" but I think it should be this:

```<code>v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
  PARTITION_30000101
  at (DATE '''||TO_CHAR(r.partition_date,'yyyy-mm-dd')||''')
  into (partition ' || r.partition_name || ' ,partition
  PARTITION_30000101)';
</code>```

Note, when you use DATE literal then format is fixed YYYY-MM-DD, otherwise use like

```<code>at (TO_DATE('''|| TO_CHAR(r.partition_date,'dd.mm.yyyy') ||''', ''dd.mm.yyyy'')`
</code>```

Title: Creating partitions

Body:
Hei, I am having problem with creating partitions using PL/SQL procedure:

ORA-14019: partition bound element must be one of: string, datetime or
  interval literal, number, or MAXVALUE

It seems like problem is in format of attribute r.partition_date, I already run some tests script and tried different date format, but nothing helped.

Format of column partition_date : 2017-09-01

I am running this procedure:

    declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where a.PARTITION_NAME =  'PARTITION_20170831'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at (''N'',to_date(' || r.partition_date || ',''yyyy.mm.dd''))
      into (partition ' || r.partition_name || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/

Even though this one is working:

 declare
v_new_part varchar2(30);
v_prev_part varchar2(30);
v_sql varchar2(4000);
v_table varchar(30) := 'RL2_OUTDW_CORP_PRISK_REV_B';
begin
for r in (select distinct a.partition_date , a.partition_name from XX a
where rownum = '1'
order by 1)
loop
      v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
      PARTITION_30000101
      at ("N",to_date(''2017-01-29'',''yyyy.mm.dd''))
      into (partition ' || 'PARTITION_20170129' || ' ,partition
      PARTITION_30000101)';

 execute immediate v_sql;
end loop;
end;
/

Thank you for advice.

Body:
I don't understand the purpose of "N" but I think it should be this:

v_sql := 'alter table ' || v_table || ' SPLIT PARTITION
  PARTITION_30000101
  at (DATE '''||TO_CHAR(r.partition_date,'yyyy-mm-dd')||''')
  into (partition ' || r.partition_name || ' ,partition
  PARTITION_30000101)';

Note, when you use DATE literal then format is fixed YYYY-MM-DD, otherwise use like

at (TO_DATE('''|| TO_CHAR(r.partition_date,'dd.mm.yyyy') ||''', ''dd.mm.yyyy'')`


问:
Merge branch with trunk
Using TortoiseSVN, I need to take changes I've done in a branch and then merge them with trunk.

I am the only developer on this project, so I know trunk hasn't changed.  I am learning SVN so that eventually my team can use it.

Basically, I want my trunk to look exactly like the branch.

In pre-svn world, I would just copy the files in my branch folder, delete the files in the trunk folder, and then copy branch into trunk.

In TortoiseSVN, I've tried Reintegrate a branch, Merge a range of revisions, and Merge two different trees.  Nothing seems to actually change trunk.  I've also tried branching on top of the trunk.  This gives me an error, saying that the trunk already exists.

答:
I am using TortoiseSVN 1.9.3, Build 27038.

Follow below steps in order to merge branch into trunk.

1)  Right click on trunk working copy and select the below option.

2)  In case of Branch Merging into trunk select option second as shown below and click next

3)  In the From: field enter the full folder URL of the trunk. This may sound wrong, but remember that the trunk is the start point to which you want to add the branch changes.
In the To: field enter the full folder URL of the feature branch.

4)  Click next and do the test merge

5) If test merge is successful then click on Merge button.

6) Once merge is successful then commit the changes on trunk.

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 4.0

Title: Merge branch with trunk


问:
git ignore file completely
I am using git to organise my code in better way.

I have setup git on localhost and production server

There is a median GitLab to store all commits and branches.

On the server, I have setup two subdomains, one to host master branch on app.example.com and another one for dev branch on dev.example.com

I have initialized and set up the same remote on both subdomains to pull master branch to app and dev branch to dev.

I want some files to be separate in all three places.

Like I have two files in my application database_config.php and app.php

database_config.php file contains the database credentials and since database credentials for localhost, app and dev are different. I need it to be different and not be affected by merge, push and pull.

Similarly, I have app.php through which debug is enabled on localhost and dev but it will always be disabled on app.

although I have included these files in .gitignore file on localhost, it is not pushed to GitLab. When in case of conflict I need to reset HEAD on production which also deletes the both files on production because they does not exists on GitLab repository.

How can I prevent these files from any action of the git and it will always be intact of any event?

答: When you add a file to .gitignore, it must be untracked. Remove it using git rm --cached database_config.php.

Title: git ignore file completely


问:
AspxErrorPath in Custom Error Page
We currently has a page that is used to display a generic error message when errors occur on our website. It has no functionality at all other than displaying a label that mentions there was an error.

Here is my issue, our client has ran a security review and tells us our error page contains phishing due to the URL in the query string, now I don't consider this a problem, but to put an end to the question, I'd like to remove the query string.

My web.config entry is this:

```<code><customErrors mode="On" defaultRedirect="~/DefaultErrorPage.aspx">
</customErrors>
</code>```

When an error occurs, it goes to DefaultErrorPage.aspx?aspxerrorpath=/Website1/LastPage.aspx

How can I prevent this? However, I could just redirect to the page if it contains the query, but I'm more looking for a way to prevent the query string instead of an extra redirection.

答:
You are going to have to take control of the error handling process yourself. One method is get rid of the custom error redirect and use the Application_Error method in global. You can then direct the person, as needed without any query string argument.

Another option is ELMAH, which is designed to avoid the yellow screen of death errors in ASP.NET. You can then tailor a friendly error and not worry about writing error handling code, per se.

A third method is to educate the security team on how ASP.NET works and see if the "security concern" is legitimate (it may be) or not. This does not mean they won't make you do one of the above options anyway, of course.

Title: AspxErrorPath in Custom Error Page

Body:
We currently has a page that is used to display a generic error message when errors occur on our website. It has no functionality at all other than displaying a label that mentions there was an error.

Here is my issue, our client has ran a security review and tells us our error page contains phishing due to the URL in the query string, now I don't consider this a problem, but to put an end to the question, I'd like to remove the query string.

My web.config entry is this:

<customErrors mode="On" defaultRedirect="~/DefaultErrorPage.aspx">
</customErrors>

When an error occurs, it goes to DefaultErrorPage.aspx?aspxerrorpath=/Website1/LastPage.aspx

How can I prevent this? However, I could just redirect to the page if it contains the query, but I'm more looking for a way to prevent the query string instead of an extra redirection.


问:
Opengles How to change black pixels to transparent pixels
My code is

```<code>vec4 textureColor = texture2D(uTextureSampler, vTextureCoord);
if(textureColor.r* 0.299 + textureColor.g * 0.587 + textureColor.b * 0.114 < 0.1) {
    gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
} else {
    gl_FragColor = vec4(textureColor.r, textureColor.g, textureColor.b, textureColor.w);
}
</code>```

My problem is how to judge the pixel is black? How can I do that, should change rgb to hsv?

答:
```<code>        return "precision mediump float; \n"+
            "   varying highp vec2 " + VARYING_TEXTURE_COORD + ";\n" +
            "   \n" +
            "   uniform sampler2D " + TEXTURE_SAMPLER_UNIFORM + ";\n" +
            "   \n" +
            " void main()\n" +
            " {\n" +
            " vec3 keying_color = vec3(0.0, 0.0, 0.0);\n" +
            " float thresh = 0.45; // [0, 1.732]\n" +
            " float slope = 0.1; // [0, 1]\n" +
            " vec3 input_color = texture2D(" + TEXTURE_SAMPLER_UNIFORM + ", " + VARYING_TEXTURE_COORD + ").rgb;\n" +
            " float d = abs(length(abs(keying_color.rgb - input_color.rgb)));\n" +
            " float edge0 = thresh * (1.0 - slope);\n" +
            " float alpha = smoothstep(edge0, thresh, d);\n" +
            " gl_FragColor = vec4(input_color,alpha);\n" +
            " }";
</code>```

In the keying_color variable is stored the actual color we want to replace. It is using classic RGB model, but intensity is not expressed as 0-255 integer. It is a float value in range 0-1. (So 0 = 0, 255 = 0, 122 = 0.478…) In our case, the green color has value (0.647, 0.941, 0.29), but if you are using different video, measure the color yourself.

Note: Make sure you have the right color. Some color measurement software automatically converts colors to slightly different formats, such as AdobeRGB.

So where’s the magic?

We load current pixel color in the input_color, then calculate difference between input and keying color. Based on this difference, alpha value is calculated and used for specific pixel.

You can control how strict the comparison is using the slope and threshold values. It is a bit more complicated, but the most basic rule is: The more threshold you have, the bigger tolerance.

So, we are done, right? Nope.

You can look this link: http://blog.csdn.net/u012847940/article/details/47441923

Body:
My code is

vec4 textureColor = texture2D(uTextureSampler, vTextureCoord);
if(textureColor.r* 0.299 + textureColor.g * 0.587 + textureColor.b * 0.114 < 0.1) {
    gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
} else {
    gl_FragColor = vec4(textureColor.r, textureColor.g, textureColor.b, textureColor.w);
}

My problem is how to judge the pixel is black? How can I do that, should change rgb to hsv?

Body:
        return "precision mediump float; \n"+
            "   varying highp vec2 " + VARYING_TEXTURE_COORD + ";\n" +
            "   \n" +
            "   uniform sampler2D " + TEXTURE_SAMPLER_UNIFORM + ";\n" +
            "   \n" +
            " void main()\n" +
            " {\n" +
            " vec3 keying_color = vec3(0.0, 0.0, 0.0);\n" +
            " float thresh = 0.45; // [0, 1.732]\n" +
            " float slope = 0.1; // [0, 1]\n" +
            " vec3 input_color = texture2D(" + TEXTURE_SAMPLER_UNIFORM + ", " + VARYING_TEXTURE_COORD + ").rgb;\n" +
            " float d = abs(length(abs(keying_color.rgb - input_color.rgb)));\n" +
            " float edge0 = thresh * (1.0 - slope);\n" +
            " float alpha = smoothstep(edge0, thresh, d);\n" +
            " gl_FragColor = vec4(input_color,alpha);\n" +
            " }";

In the keying_color variable is stored the actual color we want to replace. It is using classic RGB model, but intensity is not expressed as 0-255 integer. It is a float value in range 0-1. (So 0 = 0, 255 = 0, 122 = 0.478…) In our case, the green color has value (0.647, 0.941, 0.29), but if you are using different video, measure the color yourself.

Note: Make sure you have the right color. Some color measurement software automatically converts colors to slightly different formats, such as AdobeRGB.

So where’s the magic?

We load current pixel color in the input_color, then calculate difference between input and keying color. Based on this difference, alpha value is calculated and used for specific pixel.

You can control how strict the comparison is using the slope and threshold values. It is a bit more complicated, but the most basic rule is: The more threshold you have, the bigger tolerance.

So, we are done, right? Nope.

You can look this link: http://blog.csdn.net/u012847940/article/details/47441923


问:
Does the nix build daemon keep the build log?
Sometime when running nix-build and nixos-rebuild I found easy-to-fix problems (like deprecated warnings or redundant imports) and I thought "Interesting, I might be able to fix that in my free time".

I know I could redirect the build log to a file but I keep forgetting to do it until I see the warning again.

Question: Does the nix build daemon save the build log somewhere?

答:
You can enable build-cache-failures in your nix.conf and then use a combination of

```<code>nix-store --query-failed-paths
</code>```

and

```<code>nix-store --read-log
</code>```

If the build failure cache was not already enabled, there is probably no (easy) way to recall which builds have failed, unless you have something to grep -R for in /nix/var/log/nix/drvs/.

Body:
You can enable build-cache-failures in your nix.conf and then use a combination of

nix-store --query-failed-paths

and

nix-store --read-log

If the build failure cache was not already enabled, there is probably no (easy) way to recall which builds have failed, unless you have something to grep -R for in /nix/var/log/nix/drvs/.


问:
Pure CSS Collapse Accordion
I have a CSS collapse accordion with just pure CSS, it is working perfect.

I have just 1 issue:
right now if the user click in any label: Label One, Label Two, Label Three, he can't close it clicking in Label  again, each label can just close if the user clicks in the next one

I would like make it possible,

example: the user click in Label One to open, if him click again this label will close and the same will all for all labels.

js fiddle: https://jsfiddle.net/11wunqqz/4/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="wrapper">
  <div class="tab blue">
    <input id="tab-four" type="radio" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-five" type="radio" name="tabs2">
    <label for="tab-five">Label Two</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-six" type="radio" name="tabs2">
    <label for="tab-six">Label Three</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
</div></code>```

答:
It runs perfectly when u change type radio to type checkbox.
https://jsfiddle.net/4xvsn17y/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="wrapper">
  <div class="tab blue">
    <input id="tab-four" type="checkbox" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-five" type="checkbox" name="tabs2">
    <label for="tab-five">Label Two</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-six" type="checkbox" name="tabs2">
    <label for="tab-six">Label Three</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
</div></code>```

Title: Pure CSS Collapse Accordion

Body:
I have a CSS collapse accordion with just pure CSS, it is working perfect.

I have just 1 issue:
right now if the user click in any label: Label One, Label Two, Label Three, he can't close it clicking in Label  again, each label can just close if the user clicks in the next one

I would like make it possible,

example: the user click in Label One to open, if him click again this label will close and the same will all for all labels.

js fiddle: https://jsfiddle.net/11wunqqz/4/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <input id="tab-four" type="radio" name="tabs2">
    Label One

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

    <input id="tab-five" type="radio" name="tabs2">
    Label Two

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

    <input id="tab-six" type="radio" name="tabs2">
    Label Three

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.

Body:
It runs perfectly when u change type radio to type checkbox.
https://jsfiddle.net/4xvsn17y/

/* Acordeon styles */

.tab {
  position: relative;
  margin-bottom: 1px;
  width: 100%;
  color: #fff;
  overflow: hidden;
}

input {
  position: absolute;
  opacity: 0;
  z-index: -1;
}

label {
  position: relative;
  display: block;
  padding: 0 0 0 1em;
  background: #16a085;
  font-weight: bold;
  line-height: 3;
  cursor: pointer;
}

.blue label {
  background: #2980b9;
}

.tab-content {
  max-height: 0;
  overflow: hidden;
  background: #1abc9c;
  -webkit-transition: max-height .35s;
  -o-transition: max-height .35s;
  transition: max-height .35s;
}

.blue .tab-content {
  background: #3498db;
}

.tab-content p {
  margin: 1em;
}

/* :checked */

input:checked ~ .tab-content {
  max-height: 10em;
}

/* Icon */

label::after {
  position: absolute;
  right: 0;
  top: 0;
  display: block;
  width: 3em;
  height: 3em;
  line-height: 3;
  text-align: center;
  -webkit-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
}

input[type=checkbox] + label::after {
  content: "+";
}

input[type=radio] + label::after {
  content: "\25BC";
}

input[type=checkbox]:checked + label::after {
  transform: rotate(315deg);
}

input[type=radio]:checked + label::after {
  transform: rotateX(180deg);
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="wrapper">
  <div class="tab blue">
    <input id="tab-four" type="checkbox" name="tabs2">
    <label for="tab-four">Label One</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-five" type="checkbox" name="tabs2">
    <label for="tab-five">Label Two</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
  <div class="tab blue">
    <input id="tab-six" type="checkbox" name="tabs2">
    <label for="tab-six">Label Three</label>
    <div class="tab-content">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, architecto, explicabo perferendis nostrum, maxime impedit atque odit sunt pariatur illo obcaecati soluta molestias iure facere dolorum adipisci eum? Saepe, itaque.</p>
    </div>
  </div>
</div>


问:
How to execute two functions sequently in python?
How to execute two functions sequently in python?

for example,

there is a python script:

test.py

```<code>#!/usr/bin/python3
import shutil

def copy_folder():
    shutil.copytree('/var/www/project-one', '/var/www/project-two')

def modify_file():
    with open('/var/www/project-two/public/index.php', "r+") as f:
        read_data = f.read()
        f.seek(0, 0)
        f.write(read_data.replace('vendor/autoload.php', '../project-one/vendor/autoload.php'))

def trigger():
    copy_folder() #copy a folder
    modify_file()  # modify a file

if __name__ == "__main__":
    trigger()
</code>```

There are three functions in above script,

copy_folder() copies  folder project-one,and saves it as project-two.

modify_file() modifies a file inproject-two.

trigger() combines the two steps above.

Question：

Executing copy_folder() and modify_file() manually,it is ok. But executing trigger(),there is an error,it looks like modify_file() starts running when copy_folder() is not complete,so how to let them execute sequently?

答:
Your code looks fine. Looks like a race condition, the copy is not finished before modify is triggered. Wait 1-2 s before using time.sleep().

```<code>#!/usr/bin/python3
import shutil
import time

def copy_folder():
    shutil.copytree('/var/www/project-one', '/var/www/project-two')

def modify_file():
    with open('/var/www/project-two/public/index.php', "r+") as f:
        read_data = f.read()
        f.seek(0, 0)
        f.write(read_data.replace('vendor/autoload.php', '../project-one/vendor/autoload.php'))

def trigger():
    copy_folder() #copy a folder
    time.sleep(2)  # Give some time for copy to finish. 2 seconds in this case.
    modify_file()  # modify a file

if __name__ == "__main__":
    trigger()
</code>```

Body:
How to execute two functions sequently in python?

for example,

there is a python script:

test.py

#!/usr/bin/python3
import shutil

def copy_folder():
    shutil.copytree('/var/www/project-one', '/var/www/project-two')

def modify_file():
    with open('/var/www/project-two/public/index.php', "r+") as f:
        read_data = f.read()
        f.seek(0, 0)
        f.write(read_data.replace('vendor/autoload.php', '../project-one/vendor/autoload.php'))

def trigger():
    copy_folder() #copy a folder
    modify_file()  # modify a file

if __name__ == "__main__":
    trigger()

There are three functions in above script,

copy_folder() copies  folder project-one,and saves it as project-two.

modify_file() modifies a file inproject-two.

trigger() combines the two steps above.

Question：

Executing copy_folder() and modify_file() manually,it is ok. But executing trigger(),there is an error,it looks like modify_file() starts running when copy_folder() is not complete,so how to let them execute sequently?

Body:
Your code looks fine. Looks like a race condition, the copy is not finished before modify is triggered. Wait 1-2 s before using time.sleep().

#!/usr/bin/python3
import shutil
import time

def copy_folder():
    shutil.copytree('/var/www/project-one', '/var/www/project-two')

def modify_file():
    with open('/var/www/project-two/public/index.php', "r+") as f:
        read_data = f.read()
        f.seek(0, 0)
        f.write(read_data.replace('vendor/autoload.php', '../project-one/vendor/autoload.php'))

def trigger():
    copy_folder() #copy a folder
    time.sleep(2)  # Give some time for copy to finish. 2 seconds in this case.
    modify_file()  # modify a file

if __name__ == "__main__":
    trigger()


问:
Why is this code correct?
```<code>#include <stdio.h>
void reverseSentence();

int main()
{
  printf("Enter a sentence: ");
  reverseSentence();

  return 0;
}

void reverseSentence()
{
  char c;
  scanf("%c", &c);

  if( c != '\n')
  {
    reverseSentence();
    printf("%c",c);
  }
</code>```

I tried out this code and I know it is correct, but i don't know why the recursion works. It seems a bit non-intuitive. Could someone please shed some light on why it works? Also, what is \n doing exactly?(This is where i think the answer to my question lies). Thanks.

答:
The name reverseSentence is rather bad for recursion.

What happens is that it reads one character and saves it in a local variable.

Then if the character is not a newline (==\n) it will call itself again. This will happen recursively until a newline is entered. After that, it will print its character.

Since at the end you will traverse up through the call-stack, this will call the different instances in reverse order. → the string will be outputted in reverse

Title: Why is this code correct?

Body:
#include <stdio.h>
void reverseSentence();

int main()
{
  printf("Enter a sentence: ");
  reverseSentence();

  return 0;
}

void reverseSentence()
{
  char c;
  scanf("%c", &c);

  if( c != '\n')
  {
    reverseSentence();
    printf("%c",c);
  }

I tried out this code and I know it is correct, but i don't know why the recursion works. It seems a bit non-intuitive. Could someone please shed some light on why it works? Also, what is \n doing exactly?(This is where i think the answer to my question lies). Thanks.


问:
How get all log events in amazon via loop?
Every amazon API has it's own token which you have to set to next request. But with aws log api I got infinity loop:

```<code>public class Some {
    public static void main (String[] args) {
        final GetLogEventsRequest request = new GetLogEventsRequest()
                .withLogGroupName("myGroup")
                .withLogStreamName("myStrean");
        final AWSLogs awsLogs = AWSLogsClientBuilder.defaultClient();
        Collection<OutputLogEvent> result = new ArrayList<>();

        GetLogEventsResult response = null;
        do {
            response = awsLogs.getLogEvents(request);
            result.addAll(response.getEvents());
            request.withNextToken(response.getNextBackwardToken());
        } while (response.getNextBackwardToken() != null);
    }
}
</code>```

From documentation:

nextBackwardToken

The token for the next set of items in the backward direction. The token expires after 24 hours. This token will never be null. If you have reached the end of the stream, it will return the same token you passed in.

So it can not be null like LastEvaluatedKey when you scan dynamodb:

```<code>Map<String, AttributeValue> lastKeyEvaluated = null;
do {
    ScanRequest scanRequest = new ScanRequest()
        .withTableName("ProductCatalog")
        .withLimit(10)
        .withExclusiveStartKey(lastKeyEvaluated);

    ScanResult result = client.scan(scanRequest);
    for (Map<String, AttributeValue> item : result.getItems()){
        printItem(item);
    }
    lastKeyEvaluated = result.getLastEvaluatedKey();
} while (lastKeyEvaluated != null);
</code>```

So and what I should pass to request.withNextToken if we speak about log api??? And if nextBackwardToken (and nextForwardToken too) can not be null - how to detect that I receive the last response from amazon???

答:
The documentation which you've cited is quite straightforward. I think you need something like this:

```<code>    final AWSLogs awsLogs = AWSLogsClientBuilder.defaultClient();
    Collection<OutputLogEvent> result = new ArrayList<>();

    String nextToken = null;
    GetLogEventsResult response;
    do {
        GetLogEventsRequest request = new GetLogEventsRequest()
                .withLogGroupName("myGroup")
                .withLogStreamName("myStrean");
        if (nextToken != null) request = request.withNextToken(nextToken);

        response = awsLogs.getLogEvents(request);
        result.addAll(response.getEvents());

        // check if token is the same
        if (response.getNextForwardToken().equals(nextToken)) break;
        // save new token
        nextToken = response.getNextForwardToken();
    } while (true);
</code>```

So, you simply need to create request each time with the new token, until it becomes equals to the old one.

Body:
Every amazon API has it's own token which you have to set to next request. But with aws log api I got infinity loop:

public class Some {
    public static void main (String[] args) {
        final GetLogEventsRequest request = new GetLogEventsRequest()
                .withLogGroupName("myGroup")
                .withLogStreamName("myStrean");
        final AWSLogs awsLogs = AWSLogsClientBuilder.defaultClient();
        Collection<OutputLogEvent> result = new ArrayList<>();

        GetLogEventsResult response = null;
        do {
            response = awsLogs.getLogEvents(request);
            result.addAll(response.getEvents());
            request.withNextToken(response.getNextBackwardToken());
        } while (response.getNextBackwardToken() != null);
    }
}

From documentation:

nextBackwardToken

The token for the next set of items in the backward direction. The token expires after 24 hours. This token will never be null. If you have reached the end of the stream, it will return the same token you passed in.

So it can not be null like LastEvaluatedKey when you scan dynamodb:

Map<String, AttributeValue> lastKeyEvaluated = null;
do {
    ScanRequest scanRequest = new ScanRequest()
        .withTableName("ProductCatalog")
        .withLimit(10)
        .withExclusiveStartKey(lastKeyEvaluated);

    ScanResult result = client.scan(scanRequest);
    for (Map<String, AttributeValue> item : result.getItems()){
        printItem(item);
    }
    lastKeyEvaluated = result.getLastEvaluatedKey();
} while (lastKeyEvaluated != null);

So and what I should pass to request.withNextToken if we speak about log api??? And if nextBackwardToken (and nextForwardToken too) can not be null - how to detect that I receive the last response from amazon???

Body:
The documentation which you've cited is quite straightforward. I think you need something like this:

    final AWSLogs awsLogs = AWSLogsClientBuilder.defaultClient();
    Collection<OutputLogEvent> result = new ArrayList<>();

    String nextToken = null;
    GetLogEventsResult response;
    do {
        GetLogEventsRequest request = new GetLogEventsRequest()
                .withLogGroupName("myGroup")
                .withLogStreamName("myStrean");
        if (nextToken != null) request = request.withNextToken(nextToken);

        response = awsLogs.getLogEvents(request);
        result.addAll(response.getEvents());

        // check if token is the same
        if (response.getNextForwardToken().equals(nextToken)) break;
        // save new token
        nextToken = response.getNextForwardToken();
    } while (true);

So, you simply need to create request each time with the new token, until it becomes equals to the old one.


问:
Update information as needed
On the page I have a list of HTML-elements, each element has its status:

```<code><ul>
    <li>
        <span class='status'>ok</span>
        <span class='content'>content1</span>
    </li>
    <li>
        <span class='status'>not ok</span>
        <span class='content'>content2</span>
    </li>
    <li>
        <span class='status'>ok</span>
        <span class='content'>content3</span>
    </li>
</ul>
</code>```

This list is very big.

I need to update the status (without reloading the page).

What are the ways to do this?

I wanted to use AJAX. And periodically poll the database and get out status, etc.
What could be more options?

Update1:

I think that the use of Ajax in this way is not very good: the status change very rarely, and a list of objects is large.

答: Without reloading the page? AJAX seems to be current best practice. Or you can use an iframe.</p>

Title: Update information as needed

Body:
On the page I have a list of HTML-elements, each element has its status:

        ok
        content1

        not ok
        content2

        ok
        content3

This list is very big.

I need to update the status (without reloading the page).

What are the ways to do this?

I wanted to use AJAX. And periodically poll the database and get out status, etc.
What could be more options?

Update1:

I think that the use of Ajax in this way is not very good: the status change very rarely, and a list of objects is large.


问:
unpacking values outside a class error
I am trying to read in a csv file data and store the data using a class. My variables are not defined in the file directly, but as an input from the csv file. I  want to read the Line Groundas an input for the class Building_Storey and split the line using the class method  from_st.However I receive this error too many values to unpack (expected 4) and the error message missing 3 required positional arguments if I split the line Ground earlier in the code.it seems that he reads the whole line as one string, and gives the first argument to the whole line. I don't know what is the problem with this code.

Input csv file:

```<code>TABLE;BuildingStorey;
GbxmlID;Name;Level;Internal Height;
F0;GroundFloor;0;3.7
F1;FirstFloor;4;3.7
F2;SecondFloor;16;8
</code>```

The code :

```<code>with open('file.csv', 'r')as fp:
    copy = fp.readlines()
    print(copy)
    l = 0
    for line in copy:
        l = l + 1
        if l == 3:
            if 'GroundFloor' in line:
                Ground = line
                print(Ground)

class Building_Storey:
    def __init__(self, GbxmlID, Name, Level, Internal_Height):

        self.GbxmlID = GbxmlID
        self.Name = Name
        self.Level = Level
        self.Internal_Height = Internal_Height

    @classmethod
    def from_st(cls, Story_st):
        GbxmlID, Name, Level, Internal_Height = Story_st.split(';')
        return cls(GbxmlID, Name, Level, Internal_Height)

Groundfloor = Building_Storey.from_st(Ground)
print(Groundfloor.GbxmlID)
print(Groundfloor.Name)
print(Groundfloor.Level)
print(Groundfloor.Internal_Height)
</code>```

Output should be:

```<code>  F0;GroundFloor;0;3.7;;;;;;;  # the line I want to read
  GroundFloor.GbxmlID = F0
  GroundFloor.Name = GroundFloor
  GroundFloor.Level = 0
  GroundFloor.Internal_Height = 3.7
</code>```

答:
You could skip the first two "header" lines and then read each line in using Python's csv library to automatically split the text into a list of values per row. If the list contains 4 entries, pass the values directly to your class using * to pass each list element as an argument to your class:

```<code>import csv

class Building_Storey:
    def __init__(self, GbxmlID, Name, Level, Internal_Height):
        self.GbxmlID = GbxmlID
        self.Name = Name
        self.Level = Level
        self.Internal_Height = Internal_Height

with open('file.csv', newline='') as f_file:
    csv_file = csv.reader(f_file, delimiter=';')
    header_1 = next(csv_file)
    header_2 = next(csv_file)

    for row in csv_file:
        if len(row) == 4:
            floor = Building_Storey(*row)
            print("ID: {}, Name: {}, Level: {}, Height: {}".format(floor.GbxmlID, floor.Name, floor.Level, floor.Internal_Height))
</code>```

This would display:

ID: F0, Name: GroundFloor, Level: 0, Height: 3.7
ID: F1, Name: FirstFloor, Level: 4, Height: 3.7
ID: F2, Name: SecondFloor, Level: 16, Height: 8
```

Title: unpacking values outside a class error

Body:
I am trying to read in a csv file data and store the data using a class. My variables are not defined in the file directly, but as an input from the csv file. I  want to read the Line Groundas an input for the class Building_Storey and split the line using the class method  from_st.However I receive this error too many values to unpack (expected 4) and the error message missing 3 required positional arguments if I split the line Ground earlier in the code.it seems that he reads the whole line as one string, and gives the first argument to the whole line. I don't know what is the problem with this code.

Input csv file:

TABLE;BuildingStorey;
GbxmlID;Name;Level;Internal Height;
F0;GroundFloor;0;3.7
F1;FirstFloor;4;3.7
F2;SecondFloor;16;8

The code :

with open('file.csv', 'r')as fp:
    copy = fp.readlines()
    print(copy)
    l = 0
    for line in copy:
        l = l + 1
        if l == 3:
            if 'GroundFloor' in line:
                Ground = line
                print(Ground)

class Building_Storey:
    def __init__(self, GbxmlID, Name, Level, Internal_Height):

        self.GbxmlID = GbxmlID
        self.Name = Name
        self.Level = Level
        self.Internal_Height = Internal_Height

    @classmethod
    def from_st(cls, Story_st):
        GbxmlID, Name, Level, Internal_Height = Story_st.split(';')
        return cls(GbxmlID, Name, Level, Internal_Height)

Groundfloor = Building_Storey.from_st(Ground)
print(Groundfloor.GbxmlID)
print(Groundfloor.Name)
print(Groundfloor.Level)
print(Groundfloor.Internal_Height)

Output should be:

  F0;GroundFloor;0;3.7;;;;;;;  # the line I want to read
  GroundFloor.GbxmlID = F0
  GroundFloor.Name = GroundFloor
  GroundFloor.Level = 0
  GroundFloor.Internal_Height = 3.7

Body:
You could skip the first two "header" lines and then read each line in using Python's csv library to automatically split the text into a list of values per row. If the list contains 4 entries, pass the values directly to your class using * to pass each list element as an argument to your class:

import csv

class Building_Storey:
    def __init__(self, GbxmlID, Name, Level, Internal_Height):
        self.GbxmlID = GbxmlID
        self.Name = Name
        self.Level = Level
        self.Internal_Height = Internal_Height

with open('file.csv', newline='') as f_file:
    csv_file = csv.reader(f_file, delimiter=';')
    header_1 = next(csv_file)
    header_2 = next(csv_file)

    for row in csv_file:
        if len(row) == 4:
            floor = Building_Storey(*row)
            print("ID: {}, Name: {}, Level: {}, Height: {}".format(floor.GbxmlID, floor.Name, floor.Level, floor.Internal_Height))

This would display:

ID: F0, Name: GroundFloor, Level: 0, Height: 3.7
ID: F1, Name: FirstFloor, Level: 4, Height: 3.7
ID: F2, Name: SecondFloor, Level: 16, Height: 8


问:
Issue with image upload using Retrofit
I'm using retrofit to upload images on server, image are uploading successfully, but without extension.
Means only image name is uploading to database, extension is not there.
So image became useless for me.
please provide help.
here is my method in interface-></p>

```<code>    @FormUrlEncoded
        @POST("/webservices/AssessorAssetsUpload.php")
        Call<ImageModel> uploadImage(
            @Field("name")String pictype,
            @Field("type")String uploadtype,
            @Field("accesser_id")String asses_id,
            @Field("paper_schedule_id")String paper_id,
            @Field("imagefile")String image
        );

    my activity code->

        String image=imagetoString();

            RetrofitInterface retrofit=ApiClient.getApiClient().create(RetrofitInterface.class);
            Call<ImageModel> call=retrofit.uploadImage(imageName,"image",assessor_id,paperId,image);

            call.enqueue(new Callback<ImageModel>() {
                @Override
                public void onResponse(Call<ImageModel> call, Response<ImageModel> response) {
                    System.out.println(response.body().getStatus()+" "+response.body().getMsg()+" "+response.body().getUrl());

                }
                @Override
                public void onFailure(Call<ImageModel> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    private String imagetoString(){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
    byte[] bytes=stream.toByteArray();
        return Base64.encodeToString(bytes,Base64.DEFAULT);
    }
</code>```

答:
```<code>We use Multipart instead of formurlencoded in case of any multimedia object.

     @Multipart
        @POST("/webservices/AssessorAssetsUpload.php")
        Call<ImageModel> uploadImage(
            @Part("name")RequestBody pictype,
            @Part("type")RequestBody uploadtype,
            @Part("accesser_id")RequestBody asses_id,
            @Part("paper_schedule_id")RequestBody paper_id,
            @Part("imagefile")MultipartBody.Part image
        );

    MultipartBody.Part image=imagetoPart();

            RetrofitInterface retrofit=ApiClient.getApiClient().create(RetrofitInterface.class);
            Call<ImageModel> call=retrofit.uploadImage(
                getTextRequest("imageName"),
                getTextRequest("image"),
                getTextRequest("assessor_id"),
                getTextRequest("paperId"),
                image
                );

            call.enqueue(new Callback<ImageModel>() {
                @Override
                public void onResponse(Call<ImageModel> call, Response<ImageModel> response) {
                    System.out.println(response.body().getStatus()+" "+response.body().getMsg()+" "+response.body().getUrl());

                }
                @Override
                public void onFailure(Call<ImageModel> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    private String imagetoPart(){

        Bitmap bitmap = BitmapFactory.decodeFile("Image Path");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
        byte[] bytes=stream.toByteArray();
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), bytes);
        MultipartBody.Part part = MultipartBody.Part.createFormData("name", "name", reqFile);

        return part;
    }

 private RequestBody getTextRequest(String body) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), body);

        return requestBody;
    }
</code>```

We need to convert the fields into request body and image into a multipart body to send it as a multipart request. This will do your work.

Title: Issue with image upload using Retrofit

Body:
I'm using retrofit to upload images on server, image are uploading successfully, but without extension.
Means only image name is uploading to database, extension is not there.
So image became useless for me.
please provide help.
here is my method in interface->

    @FormUrlEncoded
        @POST("/webservices/AssessorAssetsUpload.php")
        Call<ImageModel> uploadImage(
            @Field("name")String pictype,
            @Field("type")String uploadtype,
            @Field("accesser_id")String asses_id,
            @Field("paper_schedule_id")String paper_id,
            @Field("imagefile")String image
        );

    my activity code->

        String image=imagetoString();

            RetrofitInterface retrofit=ApiClient.getApiClient().create(RetrofitInterface.class);
            Call<ImageModel> call=retrofit.uploadImage(imageName,"image",assessor_id,paperId,image);

            call.enqueue(new Callback<ImageModel>() {
                @Override
                public void onResponse(Call<ImageModel> call, Response<ImageModel> response) {
                    System.out.println(response.body().getStatus()+" "+response.body().getMsg()+" "+response.body().getUrl());

                }
                @Override
                public void onFailure(Call<ImageModel> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    private String imagetoString(){
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
    byte[] bytes=stream.toByteArray();
        return Base64.encodeToString(bytes,Base64.DEFAULT);
    }

Body:
We use Multipart instead of formurlencoded in case of any multimedia object.

     @Multipart
        @POST("/webservices/AssessorAssetsUpload.php")
        Call<ImageModel> uploadImage(
            @Part("name")RequestBody pictype,
            @Part("type")RequestBody uploadtype,
            @Part("accesser_id")RequestBody asses_id,
            @Part("paper_schedule_id")RequestBody paper_id,
            @Part("imagefile")MultipartBody.Part image
        );

    MultipartBody.Part image=imagetoPart();

            RetrofitInterface retrofit=ApiClient.getApiClient().create(RetrofitInterface.class);
            Call<ImageModel> call=retrofit.uploadImage(
                getTextRequest("imageName"),
                getTextRequest("image"),
                getTextRequest("assessor_id"),
                getTextRequest("paperId"),
                image
                );

            call.enqueue(new Callback<ImageModel>() {
                @Override
                public void onResponse(Call<ImageModel> call, Response<ImageModel> response) {
                    System.out.println(response.body().getStatus()+" "+response.body().getMsg()+" "+response.body().getUrl());

                }
                @Override
                public void onFailure(Call<ImageModel> call, Throwable t) {
                    t.printStackTrace();
                }
            });
        }

    private String imagetoPart(){

        Bitmap bitmap = BitmapFactory.decodeFile("Image Path");
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
        byte[] bytes=stream.toByteArray();
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), bytes);
        MultipartBody.Part part = MultipartBody.Part.createFormData("name", "name", reqFile);

        return part;
    }

 private RequestBody getTextRequest(String body) {

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), body);

        return requestBody;
    }

We need to convert the fields into request body and image into a multipart body to send it as a multipart request. This will do your work.