问:
Definition of Type in .NET
This question gives me curiosity... When you want to define a type you must say GetType(Type) ex.: GetType(string), but ain't String a type itself?

Why do you need to use GetType in those situations? And, if the reason is because it is expecting a Type 'Type'... why isn't the conversion implicit... I mean, all the data is there...

答:
string is type, int is type and Type is type and they are not the same. but about why there is no implicit conversion it's not recommended by MSDN:

By eliminating unnecessary casts,
  implicit conversions can improve
  source code readability. However,
  because implicit conversions can occur
  without the programmer's specifying
  them, care must be taken to prevent
  unpleasant surprises. In general,
  implicit conversion operators should
  never throw exceptions and never lose
  information so that they can be used
  safely without the programmer's
  awareness. If a conversion operator
  cannot meet those criteria, it should
  be marked explicit.

Take attention to :

never lose information so that they
  can be used safely without the
  programmer's awareness

Title: Definition of Type in .NET


来源: stackexchange

问:
Date display in handsontable
Here is what I have (the relevant part of it).

Handsontable options:

```<code>data: [[new Date(2013,5,26,17,00,00),24.7025,null,29.018950276,19.7746530531,null,null,null,null,null,null,55,110,165,220], ...

columns: [{type:'date', dateFormat: 'mm/dd/yy'},{type: 'numeric',format: '0,0.00'}, ...
</code>```

Result as shown in the handsontable date cell:

```<code>Wed Jun 26 2013 17:00:00 GMT+0200 (Romance Daylight Time)
</code>```

I would like to show it as "dd-MM-yyyy HH:mm", but I haven't found a way to do so... the display seems to always stick to the default date format, as shown above.

答:
It's 4 years later and I've found the answer in the Handsontable documentation. I thought I would share anyway...

```<code>hot = new Handsontable(container, {
    data: getDataFromSomewhere(),
    colHeaders: ['SomeText', 'SomeDate'],
    columns: [
      {
        // 1st cell is simple text, no special options here
      },
      {
        type: 'date',
        dateFormat: 'MM/DD/YYYY',
        correctFormat: true,
        defaultDate: '01/01/1900'
      }
    ]
});
</code>```

The downside of this is that you need to use three extra libraries:

/dist/moment/moment.js

/dist/pikaday/pikaday.js

/dist/pikaday/css/pikaday.css

And it automatically adds a daypicker (which is not what I wanted anyway... I need to have HH:mm as well).

ContentLicense: CC BY-SA 3.0

Title: Date display in handsontable

Body:
Here is what I have (the relevant part of it).

Handsontable options:

data: [[new Date(2013,5,26,17,00,00),24.7025,null,29.018950276,19.7746530531,null,null,null,null,null,null,55,110,165,220], ...

columns: [{type:'date', dateFormat: 'mm/dd/yy'},{type: 'numeric',format: '0,0.00'}, ...

Result as shown in the handsontable date cell:

Wed Jun 26 2013 17:00:00 GMT+0200 (Romance Daylight Time)

I would like to show it as "dd-MM-yyyy HH:mm", but I haven't found a way to do so... the display seems to always stick to the default date format, as shown above.

Body:
It's 4 years later and I've found the answer in the Handsontable documentation. I thought I would share anyway...

hot = new Handsontable(container, {
    data: getDataFromSomewhere(),
    colHeaders: ['SomeText', 'SomeDate'],
    columns: [
      {
        // 1st cell is simple text, no special options here
      },
      {
        type: 'date',
        dateFormat: 'MM/DD/YYYY',
        correctFormat: true,
        defaultDate: '01/01/1900'
      }
    ]
});

The downside of this is that you need to use three extra libraries:

/dist/moment/moment.js

/dist/pikaday/pikaday.js

/dist/pikaday/css/pikaday.css

And it automatically adds a daypicker (which is not what I wanted anyway... I need to have HH:mm as well).


问:
How to separate code into classes for swing jframe application
I'm developing a Java application with Swing that has a JFrame with buttons and a JTable. It also reads and write files.

So far, I've created different classes for each input/output files.  DefaultTable model, Table and the class that does the user input validation.

My main class is still about 1000 lines. It includes the JFrame definition (buttons, fields labels etc) the table cell renders/ editors and the actual code.

This will be a stand alone application and none of the code will be reused or shared.

Should I worry about the size of my main class and try to move the frame and table code to their respective classes ? Or is the size of the main class acceptable.  What's the best practice in this case? Most of the examples I find are for very simple applications where everything is in the same class.

Thanks for any input
link to source code of main class

答:
The answer is definitely: Yes, you should reduce your Main class. Classes of 1000 lines are very large and will become hard to handle in further developement of your project. A good guideline for reducing your class is grouping code by responsibility. Here is a basic refactoring scheme i often use:

Try to find blocks of code that can be described to do a specific task/responsibility, for instance a couple lines of code that handle file input.

Isolate blocks of code for a specific task/responsibility in their own method for that task.

Finally, group together functions with responsibilities that relate to each other. Then create a new class that will become the handler or expert for this responsibility. Move the functions to their respective responsibility class.

In general, if you think of adding new code to an existing, first think "Can I create a class that does what I want my program to do?" instead of implementing it in an already existing class, method. If you find that the code fits nicely whithin the responsibility of a class you already have, you should implement it in that class, otherwise it can't do any harm to create a new class for the purpose of the code. For more information, read about Design Patterns, GRASP concepts and Refactoring.


问:
My php script isn't visible in the browser
I just started PHP I got my XAMMP server up and running and now I made my first html test page and added one line of PHP script but it isn't showing in my browser.

```<code>    <!DOCTYPE html>
<html lang="nl">
<head>
    <title>Mijn php-script</title>
</head>
<body>
    <?php
    phpinfo();
    ?>
</body>
</html>
</code>```

It does however shows the title I gave it, can anybody tell me why the rest isn't showing? it should show the info version page of my PHP.

答: You need to save your file as .PHP and not as .HTML in order to be able to run this. Also, you need to fix the HTML closing tag in the end, as you are closing the HEAD again.</p>

Body:
I just started PHP I got my XAMMP server up and running and now I made my first html test page and added one line of PHP script but it isn't showing in my browser.

    <!DOCTYPE html>

    <title>Mijn php-script</title>

    <?php
    phpinfo();
    ?>

It does however shows the title I gave it, can anybody tell me why the rest isn't showing? it should show the info version page of my PHP.


问:
Passing data to node backed
I do not know whats going on here and tried to fix it for a few hours now.

I have a simple post

So I am posting the data to

http://localhost:8080/api/data

now in my root folder I have node file index.js I am trying to retrieve the posted values

```<code>  // grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/data', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});
</code>```

However when I start the node server and navigate to either

http://localhost:8080/

or

http://localhost:8080/api/data

I simple get : Cannot Get

What am I doing wrong ?

答:
```<code>// POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/data', function(req, res) {
  // ...
});
</code>```

However when I start the node server and navigate to either http://localhost:8080/ or http://localhost:8080/api/data I simple get : Cannot Get

When you navigate to some URL your browser uses the GET method, not POST - however your request handler uses the POST method, not GET - which means that your API doesn't support the GET method for that route and that't what you see here.

If you want to test it with your browser you would either need to create an HTML form with the correct method or use a tool like Postman or cUrl:

https://www.getpostman.com/

https://curl.haxx.se/

Title: Passing data to node backed

Body:
I do not know whats going on here and tried to fix it for a few hours now.

I have a simple post

So I am posting the data to

http://localhost:8080/api/data

now in my root folder I have node file index.js I am trying to retrieve the posted values

  // grab the packages we need
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;

// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);

var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

// POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/data', function(req, res) {
    var user_id = req.body.id;
    var token = req.body.token;
    var geo = req.body.geo;

    res.send(user_id + ' ' + token + ' ' + geo);
});

However when I start the node server and navigate to either

http://localhost:8080/

or

http://localhost:8080/api/data

I simple get : Cannot Get

What am I doing wrong ?

Body:
// POST http://localhost:8080/api/users
// parameters sent with
app.post('/api/data', function(req, res) {
  // ...
});

However when I start the node server and navigate to either http://localhost:8080/ or http://localhost:8080/api/data I simple get : Cannot Get

When you navigate to some URL your browser uses the GET method, not POST - however your request handler uses the POST method, not GET - which means that your API doesn't support the GET method for that route and that't what you see here.

If you want to test it with your browser you would either need to create an HTML form with the correct method or use a tool like Postman or cUrl:

https://www.getpostman.com/

https://curl.haxx.se/


问:
Can linear complexity O(20n) dominate polynomial complexity O(n^2/3)?
Graph for an algorithm with a complexity of O(n^2/3) (polynomial complexity):

Graph for an algorithm with a complexity of O(20n) (linear complexity):

Order of Dominance for different complexity:

O(1) < O(logn) < O(n) < O(nlogn) < O(n^2) < O(2^n) < O(n!)

Problem:
If I were to defined a order of dominance between the two algorithms above n^2/3 and 20n, I am confused as to which one will come first.

According to the order of dominance for different complexity, I see that polynomial complexity dominates linear complexity.

Order 1:

O(n^2/3) < O(20n)

But from the graphs, we can see that for O(20n), the growth rate of the number of operations over the number of elements is greater than O(n^2/3).

Order 2:

O(20n) < O(n^2/3)

I need some clarification as to which order among Order 1 or Order 2 is correct.

答:
O(n^b) ⊆ O(n^a) if b <= a

O(20*n) = O(n) = O(n^1)

O(n^(2/3)) ⊆ O(n^1)

A few words about polynomial time complexity

An algorithm is said to be solvable in polynomial time if the number of steps required to complete the algorithm for a given input is O(n^k) for some nonnegative integer k, where n is the complexity of the input.

Thus, algorithms with O(20*n) and O(n^(2/3)) time complexity both have polynomial time complexity. 'Linear complexity' is just a subcase of a polynomial.


问:
Regular expression - delimiter problem in PHP
I'm trying to extract src attributes from: [attname src="http://example.org"] somecontent [attname src="http://www.example.com"]

What I have now:

preg_match_all('#attname src=".*[^"]#', $buffer, $bufferarr);

However it doesn't work - there's no stop after second ", what results in: attname src="http://example.org"] somecontent [attname src="http://www.example.com

答:
```<code>preg_match_all('#attname src="([^"]*)"#', $buffer, $bufferarr);
</code>```

ContentLicense: CC BY-SA 2.5


问:
connect and insert into Cassandra using perl
I want to know how to connect to Cassandra using Perl, and insert, select, update etc.

I tried this

```<code>my $dbh = DBI->connect(
    "dbi:Cassandra:host=localhost;keyspace=nomkeyspace",
    "root",
    '',
    { RaiseError => 1 }
);

my $rows = $dbh->selectall_arratref( "SELECT id, nom" );

for my $row ( @$rows ) {
    print( "ok" );
}

$dbh->do( "insert into resultat (ip, nom) values (?,?)" );

$dbh->disconnect;
</code>```

but it's give me this error

Can't locate DBD/Cassandra.pm in @INC (you may need to install the DBD::Cassandra module)

thanks

答:
You have to install the reqired perl module DBD::Cassandra

You can do this with perl -MCPAN -e install "DBD::Cassandra"

Body:
I want to know how to connect to Cassandra using Perl, and insert, select, update etc.

I tried this

my $dbh = DBI->connect(
    "dbi:Cassandra:host=localhost;keyspace=nomkeyspace",
    "root",
    '',
    { RaiseError => 1 }
);

my $rows = $dbh->selectall_arratref( "SELECT id, nom" );

for my $row ( @$rows ) {
    print( "ok" );
}

$dbh->do( "insert into resultat (ip, nom) values (?,?)" );

$dbh->disconnect;

but it's give me this error

Can't locate DBD/Cassandra.pm in @INC (you may need to install the DBD::Cassandra module)

thanks


问:
the xml database keeps being created
at this part I am trying to create a new database to put my info in

the problem is that every time I close the program and reopen it creats a new database I'd like to prevent that from happening

is there is a way to check if XML already exist and if yes  how to read from XML without using the Dataset deceleration line and if no what to do on it

```<code>public Form1()
{
    InitializeComponent();
}

DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataRow dr;
private void Form1_Load(object sender, EventArgs e)
{
    dt.TableName = "Employees";
    dt.Columns.Add("Name");
    dt.Columns.Add("E-Mail");
    dt.Columns.Add("Age");
    dt.Columns.Add("WorkHours");
    dt.Columns.Add("Gender");
    dt.Columns.Add("JobTitle");
    //ba3ml tabel be el  klam da
    ds.Tables.Add(dt);
}

private void button4_Click(object sender, EventArgs e)
{
    dr = ds.Tables["Employees"].NewRow();
    dr["Name"] = textBox1.Text;
    dr["E-Mail"] = textBox2.Text;
    dr["Age"] = textBox4.Text;
    dr["WorkHours"] = textBox5.Text;
    dr["Gender"] = textBox6.Text;
    dr["JobTitle"] = textBox3.Text;
    ds.Tables["Employees"].Rows.Add(dr);

    using (var sw = new StreamWriter("Data.xml"))
    {
        ds.WriteXml(sw);
        sw.Close();
    }
}
</code>```

答:
First of all I suggest you make use of the XDocument or XmlDocument class, both of which are documented on the MSDN website.

The way I have always validated the existence of an xml database is by using System.IO.File.Exists(pathToXml). To use this, however, you do need to first save your xml file. You can do this with either class mentioned above.

Reading from / writing to the xml using XDocument or XmlDocument is also fairly easy and documentation on this can be found on the MSDN website.

XDocument: https://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument(v=vs.110).aspx
XmlDocument: https://msdn.microsoft.com/en-us/library/system.xml.xmldocument%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

Title: the xml database keeps being created

Body:
at this part I am trying to create a new database to put my info in

the problem is that every time I close the program and reopen it creats a new database I'd like to prevent that from happening

is there is a way to check if XML already exist and if yes  how to read from XML without using the Dataset deceleration line and if no what to do on it

public Form1()
{
    InitializeComponent();
}

DataSet ds = new DataSet();
DataTable dt = new DataTable();
DataRow dr;
private void Form1_Load(object sender, EventArgs e)
{
    dt.TableName = "Employees";
    dt.Columns.Add("Name");
    dt.Columns.Add("E-Mail");
    dt.Columns.Add("Age");
    dt.Columns.Add("WorkHours");
    dt.Columns.Add("Gender");
    dt.Columns.Add("JobTitle");
    //ba3ml tabel be el  klam da
    ds.Tables.Add(dt);
}

private void button4_Click(object sender, EventArgs e)
{
    dr = ds.Tables["Employees"].NewRow();
    dr["Name"] = textBox1.Text;
    dr["E-Mail"] = textBox2.Text;
    dr["Age"] = textBox4.Text;
    dr["WorkHours"] = textBox5.Text;
    dr["Gender"] = textBox6.Text;
    dr["JobTitle"] = textBox3.Text;
    ds.Tables["Employees"].Rows.Add(dr);

    using (var sw = new StreamWriter("Data.xml"))
    {
        ds.WriteXml(sw);
        sw.Close();
    }
}


问:
Unable to find tbl child nodes in MS Word doc using xpath or $node->children()
I have a project where I am attempting to take a docx file then unzip it, then run through the document.xml file using xpath in order find all table elements. then within each table element run through and identify specific tables using the tblCaption (Table Caption obviously) attribute and then run through the table and find table cells. Then I will change background color of cells by changing the w:fill value using a string replace. We're doing it like this because we want to manually enter tables into Word and then change the table without having to dynamically generate tables using a library like PHPDocx or otherwise. I have so far used SimpleXML with xpath to find all tables in the doc, loop through them and test for the existence and value of the tblCaption node. If there is a match I will then assign bg color to each cell using the cell text to id the cell node. I can find all the tables using xpath. I have attempted to find child nodes of each table using both $tblNode->children() and $xpath:

```<code>    $xml =    simplexml_load_file(APPPATH.TEMPLATE_UPLOAD_PATH.'xmltest/word/document.xml');

    $namespaces = $xml->getDocNamespaces(true);
    foreach ($namespaces as $prefix => $ns) {
        $prefix = $prefix  == '' ? 'default' : $prefix;
        $xml->registerXPathNamespace($prefix, $ns);
    }

    $nodes = $xml->xpath("/w:document/w:body//w:tbl");

    foreach($nodes as $node) {
        $children = $node->xpath("/w:tblCaption");
        echo count($children) . '<br />';
        //$children = $node->children();
        //echo count($children) . '<br />';
    }
</code>```

I would eventually like to use:
 $children = $node->xpath("/w:tblCaption[@val='whatever']"); to return a tblCaption node only if it exists and has a specific value.

At the moment there are zero child nodes for each tbl node being returned.

Any ideas?

答: I've ditched this all together and I'm using the OpenTBS plugin for changing table appearance in Word. It's much more powerful than trying to mess around with xml elements yourself. I haven't tried the above idea. Buy thanks anway. </p>

Body:
I have a project where I am attempting to take a docx file then unzip it, then run through the document.xml file using xpath in order find all table elements. then within each table element run through and identify specific tables using the tblCaption (Table Caption obviously) attribute and then run through the table and find table cells. Then I will change background color of cells by changing the w:fill value using a string replace. We're doing it like this because we want to manually enter tables into Word and then change the table without having to dynamically generate tables using a library like PHPDocx or otherwise. I have so far used SimpleXML with xpath to find all tables in the doc, loop through them and test for the existence and value of the tblCaption node. If there is a match I will then assign bg color to each cell using the cell text to id the cell node. I can find all the tables using xpath. I have attempted to find child nodes of each table using both $tblNode->children() and $xpath:

    $xml =    simplexml_load_file(APPPATH.TEMPLATE_UPLOAD_PATH.'xmltest/word/document.xml');

    $namespaces = $xml->getDocNamespaces(true);
    foreach ($namespaces as $prefix => $ns) {
        $prefix = $prefix  == '' ? 'default' : $prefix;
        $xml->registerXPathNamespace($prefix, $ns);
    }

    $nodes = $xml->xpath("/w:document/w:body//w:tbl");

    foreach($nodes as $node) {
        $children = $node->xpath("/w:tblCaption");
        echo count($children) . '
';
        //$children = $node->children();
        //echo count($children) . '
';
    }

I would eventually like to use:
 $children = $node->xpath("/w:tblCaption[@val='whatever']"); to return a tblCaption node only if it exists and has a specific value.

At the moment there are zero child nodes for each tbl node being returned.

Any ideas?


问:
Pandas DataFrame output as ASCII ^A or Unicode SOH delimited file
Finished my processing of a DataFrame and now I want to export it. Normally I export it as a plain CSV and there isn't a problem. Today I am asked to export the file with a ASCII ^A or the equivalent Unicode SOH delimiter. I will be frank this is the first time I have ever had to deal with ASCII/Unicode delimiters. Can you guys offer me some guidance/help as to how to go about this in pandas/python? I would really appreciate it. Thanks in advance for your help.

答:
In Python you can convert any number to a character using chr().  For your example I think you want chr(1) which is ASCII SOH.  You can then pass this as the separator:

```<code>df.to_csv('foo.txt', sep=chr(1))
</code>```

Once you see what chr(1) produces (\x01), you may realize you can also write it this way:

```<code>df.to_csv('foo.txt', sep='\1')
</code>```

The ASCII table, of course, is here: http://www.asciitable.com/

^A is ASCII SOH according to this: http://academic.evergreen.edu/projects/biophysics/technotes/program/ascii_ctrl.htm - there is no Python escape code for it though.  curses.ascii.SOH is close, but it's actually just the constant 1 so pretty useless - you'd be better off just writing SOH = '\1' in your program.

Body:
In Python you can convert any number to a character using chr().  For your example I think you want chr(1) which is ASCII SOH.  You can then pass this as the separator:

df.to_csv('foo.txt', sep=chr(1))

Once you see what chr(1) produces (\x01), you may realize you can also write it this way:

df.to_csv('foo.txt', sep='\1')

The ASCII table, of course, is here: http://www.asciitable.com/

^A is ASCII SOH according to this: http://academic.evergreen.edu/projects/biophysics/technotes/program/ascii_ctrl.htm - there is no Python escape code for it though.  curses.ascii.SOH is close, but it's actually just the constant 1 so pretty useless - you'd be better off just writing SOH = '\1' in your program.


问:
How to take the actionscript from an as3 package and use it in .fla
This morning i stumbled upon this source code for a miner game : http://www.emanueleferonato.com/2010/10/22/create-a-flash-game-like-gold-miner-as3-version/

The problem is that I never used packages and classes before ( I only worked with as2 ) .

I need the code from the AS files to be in the timeline AS but cant figure out a way to have it there and working .

If anybody knows how please tell me .

I tried copy/pasting the code , removing the package,class and private text and it still doesn't work .

Any help is apreciated.

Chris

答:
You simply need to put all this packages in their own file and name the file after the class name, for instance the Main class should be saved as Main.as.

After you've saved each class in its own .as file , take all these files and copy them in the same folder as your fla. The reason for this is that the packages don't specify a path ( something like com.example for instance ) , so they need to be at the same directory level as your fla.

Finally , just use the Main class as your Document Class, here's a tutorial ,
there are plenty of examples on the web anyway...

http://www.heaveninteractive.com/2008/03/04/introduction-to-the-document-class-in-actionscript-30-tutorial/

Test your swf...


问:
How to get the selected text from an embedded pdf in a web page?
Here's an example of a pdf document from which I need to extract the user's selection http://www.ada.gov/hospcombrprt.pdf . If we look in the page source we will see smth like:

```<code><html>
  <body marginwidth="0" marginheight="0" style="background-color: rgb(38,38,38)">
     <embed width="100%" height="100%" name="plugin"
     src="http://www.ada.gov/hospcombrprt.pdf" type="application/pdf">
  </body>
</html>
</code>```

How can we get a user's selection from this embedded pdf?

I found a post about extracting the whole text from a pdf doc here and a similar to mine post here where it's written that there are no such possibilities.

But there should be some way out. Probably it's possible to extract the whole text and then somehow determine what's been selected? Or determine the selection through the mouse cursor position on the mouse-down and up events? Would appreciate any ideas.

答:
I too wanted a way to get selected text from a pdf on the webpage and I came across pdftron, which is not a native method of course. You can get selected text from a pdf using pdftron's webviewer using the following method: </p>

```<code>var selectedText = myWebViewer.getInstance().docViewer.getSelectedText();
</code>```

Body:
Here's an example of a pdf document from which I need to extract the user's selection http://www.ada.gov/hospcombrprt.pdf . If we look in the page source we will see smth like:

     <embed width="100%" height="100%" name="plugin"
     src="http://www.ada.gov/hospcombrprt.pdf" type="application/pdf">

How can we get a user's selection from this embedded pdf?

I found a post about extracting the whole text from a pdf doc here and a similar to mine post here where it's written that there are no such possibilities.

But there should be some way out. Probably it's possible to extract the whole text and then somehow determine what's been selected? Or determine the selection through the mouse cursor position on the mouse-down and up events? Would appreciate any ideas.

Body:
I too wanted a way to get selected text from a pdf on the webpage and I came across pdftron, which is not a native method of course. You can get selected text from a pdf using pdftron's webviewer using the following method:

var selectedText = myWebViewer.getInstance().docViewer.getSelectedText();


问:
jQuery get the location of an element relative to window
Given an HTML DOM ID, how to get an element's position relative to the window in JavaScript/JQuery?  This is not the same as relative to the document nor offset parent since the element may be inside an iframe or some other elements.  I need to get the screen location of the element's rectangle (as in position and dimension) as it is currently being displayed.  Negative values are acceptable if the element is currently off-screen (have been scrolled off).

This is for an iPad (WebKit / WebView) application.  Whenever the user taps on a special link in an UIWebView, I am supposed to open a popover view that displays further information about the link.  The popover view needs to display an arrow that points back to the part of the screen that invokes it.

答:
TL;DR

```<code>headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe
</code>```

.getBoundingClientRect() appears to be universal.  .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

Body:
TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal.  .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.


问:
Pandas: Adding 0 to a long integer representing a date
I am trying to import a csv into panda. This csv contains a data column as follow (for instance):

20170607155749330: (Year/Month/Day/Hour/Minute/Second/decisecond/centisecond/millisecond). So there are 17 numbers representing the date.

Issue I have is that for this particular dataset is that some row have dates at a different precision, for instance:
2017060715581995 : here there are only 16 numbers since the millisecond is missing.

What I want to do is simple: converting every date for every row in a way that I would end up with 17 digit, by adding a 0 when one of them is missing.

Here is the function I wrote for this:

```<code>def convert_value(val):
   return ('{:0<17}'.format(val))
</code>```

So I try to apply it to every row by just creating a new column such as:

```<code>file_temp['Time_Transformed'] = file_temp.apply( lambda x: convert_value(x["TIME"]) , axis =1)
</code>```

And I am facing two issues:

Firstly, the newly created column is not of integer but of object type;

Secondly, it just does not work, 0 is not added to shorter date.

I tried various other approaches by converting the original data to string but they are not working either.

Body:
I am trying to import a csv into panda. This csv contains a data column as follow (for instance):

20170607155749330: (Year/Month/Day/Hour/Minute/Second/decisecond/centisecond/millisecond). So there are 17 numbers representing the date.

Issue I have is that for this particular dataset is that some row have dates at a different precision, for instance:
2017060715581995 : here there are only 16 numbers since the millisecond is missing.

What I want to do is simple: converting every date for every row in a way that I would end up with 17 digit, by adding a 0 when one of them is missing.

Here is the function I wrote for this:

def convert_value(val):
   return ('{:0<17}'.format(val))

So I try to apply it to every row by just creating a new column such as:

file_temp['Time_Transformed'] = file_temp.apply( lambda x: convert_value(x["TIME"]) , axis =1)

And I am facing two issues:

Firstly, the newly created column is not of integer but of object type;

Secondly, it just does not work, 0 is not added to shorter date.

I tried various other approaches by converting the original data to string but they are not working either.

Body:
I think you need astype with str.ljust:

df = pd.DataFrame({'A':[20170607155749330,20170607155749]})

df['new'] = df['A'].astype(str).str.ljust(17, '0').astype('int64')
print (df)
                   A                new
0  20170607155749330  20170607155749330
1     20170607155749  20170607155749000

And for datetime:

df['date'] = pd.to_datetime(df['A'].astype(str).str.ljust(17, '0'), format='%Y%m%d%M%S%f')
print (df)
                   A                       date
0  20170607155749330 2017-06-07 00:15:57.493300
1     20170607155749 2017-06-07 00:15:57.490000

is same as:

df['date'] = pd.to_datetime(df['A'], format='%Y%m%d%M%S%f')
print (df)
                   A                       date
0  20170607155749330 2017-06-07 00:15:57.493300
1     20170607155749 2017-06-07 00:15:57.490000


问:
On logout invalidate flask-JWT
I have generated Flask-JWT token for user authentication, but on logout i want to invalidate token. Now it's allowing to access route after logout.</p>

```<code>@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
    user = current_user
    user.authenticated = False
    db.session.commit()
    logout_user()
    return jsonify({'success': True})
</code>```

答:
Check flask-jwt-extended. It has support for blacklisting tokens built in to the extension (and is still actively supported, unlike flask jwt which has been abandoned).

https://flask-jwt-extended.readthedocs.io/en/stable/blacklist_and_token_revoking/

Title: On logout invalidate flask-JWT

Body:
I have generated Flask-JWT token for user authentication, but on logout i want to invalidate token. Now it's allowing to access route after logout.

@app.route('/logout', methods=['POST'])
@jwt_required
def logout():
    user = current_user
    user.authenticated = False
    db.session.commit()
    logout_user()
    return jsonify({'success': True})

ContentLicense: CC BY-SA 4.0


问:
How do i improve my code to load images from remote server more effiecintly without UI lag?
The adapter provides data for a listview. But when you scroll up and down, it shows old images and takes a couple of seconds to finish loading the images. This is true when you open the view for the first time.</p>

```<code>public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask(imageurl);
        task.execute(imagelink);

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView img;

        ImageAsyncTask(ImageView img) {
            this.img = img;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {
            this.img.setImageBitmap(data);

        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

}
</code>```

答:
User Picasso best way to display image even you can set default image when image is loading see below example..

```<code>Picasso.with(context).load(imageUrl).placeholder(R.drawable.default_image).into(imageView);
</code>```

compile 'com.squareup.picasso:picasso:2.4.0' just add into build.gradle

Body:
The adapter provides data for a listview. But when you scroll up and down, it shows old images and takes a couple of seconds to finish loading the images. This is true when you open the view for the first time.

public class BooksAdapter extends ArrayAdapter<Books> {

    public BooksAdapter(Activity context, ArrayList<Books> word) {
        super(context, 0, word);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        Books currentbook = getItem(position);

        TextView bookView = (TextView) listItemView.findViewById(R.id.bookTittle);
        String booktitle = currentbook.getBookName();
        bookView.setText(booktitle);

        TextView authorView = (TextView) listItemView.findViewById(R.id.authorname);
        String authorname = currentbook.getAuthorName();
        authorView.setText(authorname);

        ImageView imageurl = (ImageView) listItemView.findViewById(R.id.imageView);
        String imagelink = currentbook.getImageLink();

        ImageAsyncTask task = new ImageAsyncTask(imageurl);
        task.execute(imagelink);

        return listItemView;

    }

    private class ImageAsyncTask extends AsyncTask<String, Void, Bitmap> {

        private ImageView img;

        ImageAsyncTask(ImageView img) {
            this.img = img;
        }

        @Override
        protected Bitmap doInBackground(String... urls) {

            URL url = null;
            Bitmap bmp = null;

            try {
                url = new URL(urls[0]);
            } catch (MalformedURLException e) {
                Log.e(LOG_TAG, "Error with creating URL ", e);
            }
            try {
                bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            } catch (IOException e) {
                Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
            }

            return bmp;

        }

        @Override
        protected void onPostExecute(Bitmap data) {
            this.img.setImageBitmap(data);

        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }

    }

}

Body:
User Picasso best way to display image even you can set default image when image is loading see below example..

Picasso.with(context).load(imageUrl).placeholder(R.drawable.default_image).into(imageView);

compile 'com.squareup.picasso:picasso:2.4.0' just add into build.gradle


问:
a very simple query is not working PHP
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

```<code>  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>
</code>```

答:
The basic debugging steps are 1. adding

```<code>if (!$result) echo "Error: ".mysql_error();
</code>```

to see any errors from the SQL query and 2. outputting

```<code>echo "Query: $query";
</code>```

to see what the variables contain. One of these will point you to the problem.

Also, your query is vulnerable to SQL injection. You should add a

```<code>$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );
</code>```

after fetching the values from the POST array.

Title: a very simple query is not working PHP

Body:
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S

here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!

  <?php

 $email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];

$connection = mysql_connect('localhost','root','') ;

$db_selected = mysql_select_db("lab5" , $connection) ;

$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
    while($row=mysql_fetch_array($result))
    {
        echo $row['name'];
    }
mysql_close($connection);
?>

Body:
The basic debugging steps are 1. adding

if (!$result) echo "Error: ".mysql_error();

to see any errors from the SQL query and 2. outputting

echo "Query: $query";

to see what the variables contain. One of these will point you to the problem.

Also, your query is vulnerable to SQL injection. You should add a

$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );

after fetching the values from the POST array.


问:
WebStorm debugging create-react-native-app
What should I set in Run Debug Configuration in WebStorm to debug a app created by create-react-native-app?

I'm at a loss on how to debug since it doesn't use ~/.node_modules/lib/node_modules/react-native-cli but a custom module called react-native-scripts to start the compiling:

package.json:

```<code> "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "test": "node node_modules/jest/bin/jest.js --watch",
    "menu": "adb shell input keyevent 82"
  },
</code>```

答:
I dont think you can do this, at least not in an easy way, and why would you wan't to do it anyway?

React Native ships with great debugging capabilities "out of the box" via Chrome Developer Tools.
Here you can debug code, both running on emulators, and even better on a real device.
See here for details: https://facebook.github.io/react-native/docs/debugging.html

Body:
What should I set in Run Debug Configuration in WebStorm to debug a app created by create-react-native-app?

I'm at a loss on how to debug since it doesn't use ~/.node_modules/lib/node_modules/react-native-cli but a custom module called react-native-scripts to start the compiling:

package.json:

 "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "test": "node node_modules/jest/bin/jest.js --watch",
    "menu": "adb shell input keyevent 82"
  },


答:
Simple OUTER APPLY should do the thing:

```<code>SELECT  c.id,
        c.[status],
        c.[Modified_date] as [start_date],
        COALESCE(t.[Modified_date],'99-99-9999') as end_date --or ISNULL
FROM YourTable c
OUTER APPLY (
    SELECT TOP 1 [Modified_date]
    FROM YourTable
    WHERE ID = c.ID AND [Modified_date] > c.[Modified_date]
    ) as t
</code>```

Output:

```<code>id          status  start_date end_date
----------- ------- ---------- ----------
1           active  20-10-2016 09-11-2016
1           removed 09-11-2016 99-99-9999
2           active  21-10-2016 11-01-2017
2           removed 11-01-2017 99-99-9999
</code>```

Or using LEAD (starting from SQL Server 2012):

```<code>SELECT  id,
        [status],
        [Modified_date] as [start_date],
        LEAD([Modified_date],1,'99-99-9999') OVER (PARTITION BY Id ORDER BY [Modified_date] DESC) as end_date
FROM YourTable
</code>```

Title: Create start and end date from single date column

Body:
Input:

Id |Status  |Modified_date
-----------------------------------------
1  |active  |20-10-2016
1  |removed |09-11-2016
2  |active  |21-10-2016
2  |removed |11-01-2017

I would like to add start date and end date as new columns and the output should look like

ID       | status   | start_Date  | end_date
-----------------------------------------
1/1/1900 | active   | 20-10-2016  |9/11/2016
1/1/1900 | removed  | 9/11/2016   |99-99-9999
1/2/1900 | active   | 21-10-2016  |11/1/2017
1/2/1900 | removed  | 11/1/2017   |99-99-9999

Please let me know how this is possible

Body:
Simple OUTER APPLY should do the thing:

SELECT  c.id,
        c.[status],
        c.[Modified_date] as [start_date],
        COALESCE(t.[Modified_date],'99-99-9999') as end_date --or ISNULL
FROM YourTable c
OUTER APPLY (
    SELECT TOP 1 [Modified_date]
    FROM YourTable
    WHERE ID = c.ID AND [Modified_date] > c.[Modified_date]
    ) as t

Output:

id          status  start_date end_date
----------- ------- ---------- ----------
1           active  20-10-2016 09-11-2016
1           removed 09-11-2016 99-99-9999
2           active  21-10-2016 11-01-2017
2           removed 11-01-2017 99-99-9999

Or using LEAD (starting from SQL Server 2012):

SELECT  id,
        [status],
        [Modified_date] as [start_date],
        LEAD([Modified_date],1,'99-99-9999') OVER (PARTITION BY Id ORDER BY [Modified_date] DESC) as end_date
FROM YourTable


问:
How to hide the backing field from the rest of the class
Is there any way to enforce the rest of my class to access the property setter rather than the backing field? Consider the following clumsy code:

```<code>public class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    public void OhDearWhatWasIThinking()
    {
        _somethingWorthProtecting = "Shooting myself in the foot here, aren't I?";
    }
}
</code>```

As far as I know, C# does not provide any mechanism to prevent the class developer from making this mistake. (Auto-properties are clearly not an option in this situation.) Is there a design pattern or practice that can help safeguard against such inadvertant end-arounds?

答:
you can move that logic to an abstract base class:

```<code>public abstract class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    //.....
}
</code>```

then you can be sure no one will instantiate this class, and derived classes will not be able to access the private field.

```<code>public class BrittleDerived : Brittle
{
     public void DoSomething()
     {
        // cannot access _somethingWorthProtecting;
     }
}
</code>```

Body:
Is there any way to enforce the rest of my class to access the property setter rather than the backing field? Consider the following clumsy code:

public class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    public void OhDearWhatWasIThinking()
    {
        _somethingWorthProtecting = "Shooting myself in the foot here, aren't I?";
    }
}

As far as I know, C# does not provide any mechanism to prevent the class developer from making this mistake. (Auto-properties are clearly not an option in this situation.) Is there a design pattern or practice that can help safeguard against such inadvertant end-arounds?

Body:
you can move that logic to an abstract base class:

public abstract class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    //.....
}

then you can be sure no one will instantiate this class, and derived classes will not be able to access the private field.

public class BrittleDerived : Brittle
{
     public void DoSomething()
     {
        // cannot access _somethingWorthProtecting;
     }
}


问:
How to perform backup with Azure App Service
I tried backing up Azure App Service according to the following URL.

However, if you press the backup button on the App Service menu, the next screen will be displayed and you will not be able to proceed.

Backup Not Configured, Configure you backup by setting up a storage account, schedule and select databases to be backed up for safe keeping and disaster recovery.

I tried the App Service Plan with Standard and Premium.
I also created Azure Storage Account.
I have created a new App Service in several regions.

However, both of them got the same result.
Does anyone know the procedure?

Best regards.

答: The "Configure" option appeared for me after I tried logging into the Azure portal in private/incognito mode. I'd also recommend clearing out your cache for good measure. Hope that helps.</p>


问:
ng-repeat : custom filter to show all rows of the same user if one validate condition
I have a ng-repeat that loops over a list of proposed actions by a user. There can be one to many action per user. If one of these proposed actions validates a condition (a location), then all proposed action of this users should be displayed.

Said more abstractly, how to display all rows having a certain property, when one of these row has another property that validates a condition ?

I know I can provide a custom function as filter for the ng-repeat but so far all approaches I came up with implied to loop over the whole list for each item tested. Maybe I can rely instead on some more performant builtin feature of angular, hence this question.

答:
Instead of doing expensive computation in the filter function for ng-repeat, I choose to to intercept and enrich the data upfront. This can be done in the controller once the promise is resolved, or better as an interceptor in the service.

In my specific case I added a new field "allLocations" to each items. Once this is done the filter function can test each row normally, i.e by testing it own attributes, without to have to loop over all items.

Even though there isn't many people who will ever read this, that is how I solved it.


问:
Using a regex in Java
I need to build a regular expression for all nonempty sequences of letters other than : file, for,from.

So I should end up getting all the values from my text input excluding the above 3 words.

Is this a correct way to represent it?

```<code>^(?:(?!file|for|from).)*$
</code>```

Also I was trying to use this regex pattern in my java program and assumed it should work. But it does not.

My sample code is as follows:

```<code>Pattern p = Pattern.compile("^(?:(?!file|for|from).)*$");

// Split input with the pattern

String[] result =

         p.split("file is not there from for this time for this test");

for (int i=0; i<result.length; i++)

    System.out.println(result[i]);
</code>```

Is there an error in my regex or is there some error with the way I am using regex in java?

Please advise.

Thank you.

答:
There is obscurity in the question.
Do you want to extract all the words of a string that aren’t one of (file,for,from) ?
Or do you want to match the strings that don’t include any of these words ?
’for’ is refused , but what about ’affordable’ : accepted or refused ?

As far as I understand the question, I propose, to catch words not being ’file’,’for’ or ’from’, in a chain, the following RE chain:

'\b(?!file|for|from)\w+'

Title: Using a regex in Java

Body:
I need to build a regular expression for all nonempty sequences of letters other than : file, for,from.

So I should end up getting all the values from my text input excluding the above 3 words.

Is this a correct way to represent it?

^(?:(?!file|for|from).)*$

Also I was trying to use this regex pattern in my java program and assumed it should work. But it does not.

My sample code is as follows:

Pattern p = Pattern.compile("^(?:(?!file|for|from).)*$");

// Split input with the pattern

String[] result =

         p.split("file is not there from for this time for this test");

for (int i=0; i<result.length; i++)

    System.out.println(result[i]);

Is there an error in my regex or is there some error with the way I am using regex in java?

Please advise.

Thank you.


问:
Spring Roo 2.0.0.RC1 - Problems when change contextPath
clinic example

I have change the contextPath in application.properties:

```<code>server.contextPath=/tierklinik
</code>```

When I start the application now the url is http://localhost:8080/tierklinik, but when I will add something new (create) then I get error side and the URL is not correct.

Url after save:

```<code>http://localhost:8080/tierklinik/tierklinik/pets/
</code>```

I have a normal spring boot application and the contextPath change work.

答:
This is a known problem in the Spring Roo 2.0.0.RC1 applications.

Check the <form> element of your create.html and edit.html files. You could see that the action attribute of the form is defined like this:

```<code>data-th-action="@{${collectionLink.to('create').with('item', item.id)}}"
</code>```

Removing the @{ and the final } you should obtain the following value for the action attribute:

```<code>data-th-action="${collectionLink.to('create').with('item', item.id)}"
</code>```

The problem is that the @ includes the contextPath in the URL, but the collectionLink and the itemLink includes it too.

If you want to apply this change to all your HTML views, you could update the .ftl files instead the .html files installing the templates with the command web mvc templates setup --type THYMELEAF and updating them. After this update, opening the Spring Roo shell again, all your .html files will be regenerated removing the @ from the action attribute.

Hope it helps,

Regards,

Body:
clinic example

I have change the contextPath in application.properties:

server.contextPath=/tierklinik

When I start the application now the url is http://localhost:8080/tierklinik, but when I will add something new (create) then I get error side and the URL is not correct.

Url after save:

http://localhost:8080/tierklinik/tierklinik/pets/

I have a normal spring boot application and the contextPath change work.

Body:
This is a known problem in the Spring Roo 2.0.0.RC1 applications.

Check the <form> element of your create.html and edit.html files. You could see that the action attribute of the form is defined like this:

data-th-action="@{${collectionLink.to('create').with('item', item.id)}}"

Removing the @{ and the final } you should obtain the following value for the action attribute:

data-th-action="${collectionLink.to('create').with('item', item.id)}"

The problem is that the @ includes the contextPath in the URL, but the collectionLink and the itemLink includes it too.

If you want to apply this change to all your HTML views, you could update the .ftl files instead the .html files installing the templates with the command web mvc templates setup --type THYMELEAF and updating them. After this update, opening the Spring Roo shell again, all your .html files will be regenerated removing the @ from the action attribute.

Hope it helps,

Regards,


问:
pick item from list at random, each has different chance
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

```<code>this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};
</code>```

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

```<code>this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];
</code>```

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.

答:
You can do something like this.

Creating an array with the same value multiple times gives it a higher chance of being selected.

var resources = [{
    type: 'empty',
    chance: 30
  },
  {
    type: 'nitrogen',
    chance: 10
  },
  {
    type: 'silicon',
    chance: 20
  },
  {
    type: 'cobalt',
    chance: 30
  },
  {
    type: 'magnesium',
    chance: 10
  }
];

function GetRandom(list) {
  var array = [];
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var chance = item.chance / 10;
    for (var j = 0; j < chance; j++) {
      array.push(item.type);
    }
  }
  var idx = Math.floor(Math.random() * array.length);
  return array[idx];

}

console.log(GetRandom(resources))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I wanted to write a simple function that allows to roll random item from list, i did it with this code:

this.resources = [false, 'nitrogen', 'silicon', 'cobalt', 'magnesium'];

this.assign_resource = function() {
    var index = tools.rnd(0, this.resources.length - 1);
    return this.resources[index];
};

But it doesn't play well, so i wanted to change it to different system that allows a list of items (including empty one) and it picks one at random but each one has different chance (for example this one has 10%, this one has 20%). Maybe someone could help me with this kind of function.

Edited -----

for example this could be new list:

this.resources = [
    { type: 'empty', chance: 30 },
    { type: 'nitrogen', chance: 10 },
    { type: 'silicon', chance: 20 },
    { type: 'cobalt', chance: 30 },
    { type: 'magnesium', chance: 10 }
];

How to use it now to make it happen properly?

Edited 2 -----

I am trying to figure out well done programming solution using math rather then simply duplicating items in array, answers presented in this topic are just work arounds to a problem.

Body:
You can do something like this.

Creating an array with the same value multiple times gives it a higher chance of being selected.

var resources = [{
    type: 'empty',
    chance: 30
  },
  {
    type: 'nitrogen',
    chance: 10
  },
  {
    type: 'silicon',
    chance: 20
  },
  {
    type: 'cobalt',
    chance: 30
  },
  {
    type: 'magnesium',
    chance: 10
  }
];

function GetRandom(list) {
  var array = [];
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var chance = item.chance / 10;
    for (var j = 0; j < chance; j++) {
      array.push(item.type);
    }
  }
  var idx = Math.floor(Math.random() * array.length);
  return array[idx];

}

console.log(GetRandom(resources))

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to properly post data using begin/end GetRequestStream and callbacks
I'm trying to post a piece of data but it seems to be getting caught and hangs (but not throwing an error).

```<code> internal IAsyncResult RequestGet<TPostType>(Action<string> callback, string path, TPostType value)
    {
        var http = (HttpWebRequest)WebRequest.Create(Connection.GetUri(path).Uri);
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";

        var parsedContent = JsonConvert.SerializeObject(value);
        var encoding = new ASCIIEncoding();
        var bytes = encoding.GetBytes(parsedContent);

        return http.BeginGetRequestStream(ar =>
        {
            try
            {
                var stream = http.EndGetRequestStream(ar);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                http.BeginGetResponse(body =>
                {
// its around here that it hangs.
                    var response = http.EndGetResponse(ar);

                    var s = response.GetResponseStream();

                    ReadStream(callback, s);

                }, null);
            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;

                using (Stream respStream = errResp.GetResponseStream())
                {
                    Console.WriteLine(new StreamReader(respStream).ReadToEnd());
                }
            }
        }, null);
    }
</code>```

There were a few times when it didn't hang but told me that the request body was missing, however I didn't make any progress beyond that. Could someone please inform me as to what I'm doing wrong?

The ReadStream method works for GET requests, but for context:

```<code>private static IAsyncResult ReadStream(Action<string> callback, Stream stream)
    {
        var buffer = new byte[5000];

        var asyncResult = stream.BeginRead(buffer, 0, 5000, ar2 =>
        {
            try
            {
                callback(Encoding.UTF8.GetString(buffer, 0, 5000));
            }
            catch (Exception ex)
            {
                // do better error handling
                Console.WriteLine("exception reading stream");
                Console.WriteLine(ex);
            }
        }, null);

        return asyncResult;
    }
</code>```

For more context on how its being used:

```<code> public IAsyncResult BeginGetChainPart(Action<BlockData.BlockList> callback, int height)
    {
        var asyncResult = new HttpConnector(Connection).RequestGet(body =>
        {
            callback(JsonConvert.DeserializeObject<BlockData.BlockList>(body));
        }, "/local/chain/blocks-after", new BlockData.BlockHeight { Height = height });

        return asyncResult;
    }
</code>```

答:
found the solution, posting in case anyone comes across the same issue:</p>

```<code>        internal IAsyncResult RequestGet<TPostType>(Action<string> callback, string path, TPostType value)
    {
        var http = (HttpWebRequest)WebRequest.Create(Connection.GetUri(path).Uri);
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";

        var parsedContent = JsonConvert.SerializeObject(value);
        var encoding = new ASCIIEncoding();
        var bytes = encoding.GetBytes(parsedContent);

        return http.BeginGetRequestStream(ar => {
            try
            {
                var stream = http.EndGetRequestStream(ar);

                stream.Write(bytes, 0, bytes.Length);

                stream.Close();

                var response = http.GetResponse();

                var responseStream = response.GetResponseStream();

                ReadStream(callback, responseStream);

            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;

                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);

                    string text = reader.ReadToEnd();

                    Console.WriteLine(text);
                }
            }
        }, null);
    }
</code>```

Body:
I'm trying to post a piece of data but it seems to be getting caught and hangs (but not throwing an error).

 internal IAsyncResult RequestGet<TPostType>(Action<string> callback, string path, TPostType value)
    {
        var http = (HttpWebRequest)WebRequest.Create(Connection.GetUri(path).Uri);
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";

        var parsedContent = JsonConvert.SerializeObject(value);
        var encoding = new ASCIIEncoding();
        var bytes = encoding.GetBytes(parsedContent);

        return http.BeginGetRequestStream(ar =>
        {
            try
            {
                var stream = http.EndGetRequestStream(ar);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                http.BeginGetResponse(body =>
                {
// its around here that it hangs.
                    var response = http.EndGetResponse(ar);

                    var s = response.GetResponseStream();

                    ReadStream(callback, s);

                }, null);
            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;

                using (Stream respStream = errResp.GetResponseStream())
                {
                    Console.WriteLine(new StreamReader(respStream).ReadToEnd());
                }
            }
        }, null);
    }

There were a few times when it didn't hang but told me that the request body was missing, however I didn't make any progress beyond that. Could someone please inform me as to what I'm doing wrong?

The ReadStream method works for GET requests, but for context:

private static IAsyncResult ReadStream(Action<string> callback, Stream stream)
    {
        var buffer = new byte[5000];

        var asyncResult = stream.BeginRead(buffer, 0, 5000, ar2 =>
        {
            try
            {
                callback(Encoding.UTF8.GetString(buffer, 0, 5000));
            }
            catch (Exception ex)
            {
                // do better error handling
                Console.WriteLine("exception reading stream");
                Console.WriteLine(ex);
            }
        }, null);

        return asyncResult;
    }

For more context on how its being used:

 public IAsyncResult BeginGetChainPart(Action<BlockData.BlockList> callback, int height)
    {
        var asyncResult = new HttpConnector(Connection).RequestGet(body =>
        {
            callback(JsonConvert.DeserializeObject<BlockData.BlockList>(body));
        }, "/local/chain/blocks-after", new BlockData.BlockHeight { Height = height });

        return asyncResult;
    }

Body:
found the solution, posting in case anyone comes across the same issue:

        internal IAsyncResult RequestGet<TPostType>(Action<string> callback, string path, TPostType value)
    {
        var http = (HttpWebRequest)WebRequest.Create(Connection.GetUri(path).Uri);
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";

        var parsedContent = JsonConvert.SerializeObject(value);
        var encoding = new ASCIIEncoding();
        var bytes = encoding.GetBytes(parsedContent);

        return http.BeginGetRequestStream(ar => {
            try
            {
                var stream = http.EndGetRequestStream(ar);

                stream.Write(bytes, 0, bytes.Length);

                stream.Close();

                var response = http.GetResponse();

                var responseStream = response.GetResponseStream();

                ReadStream(callback, responseStream);

            }
            catch (WebException webex)
            {
                WebResponse errResp = webex.Response;

                using (Stream respStream = errResp.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(respStream);

                    string text = reader.ReadToEnd();

                    Console.WriteLine(text);
                }
            }
        }, null);
    }


问:
regular expression to delete entire content of file if string matches
I am trying to find a regular expression which would allow me to delete entire content of a file if a particular string matches.

As an example, my file contents are:

```<code>This is the first line
Here is password=SECRET second line
Here is third line
</code>```

I am doing search for string with pattern password= and when that match happens, ALL lines should be removed from the above file.

Below command does remove the entire line matching the pattern but I can't figure out a regular expression for removing the entire content:

```<code>cat test.txt | sed 's|^.*password=.*||'
</code>```

I understand sed works line by line and unless I use additional options in sed, I probably do not have a way to delete the entire content.

The reason I am only interested in regular expression is that I am using another tool which uses regular expression as an input to perform transformations. I use sed here as an example to illustrate what I understand so far.

答:
Note that this answer is based on OP's comments on his answer where he discloses that he is only using sed to test his regex and that his final solution uses BFG. This tool uses Java regexes so testing the solution with sed makes little sense, which is why my solution doesn't match the tags of the question.

The documentation of the tool you use is lackluster, I couldn't find if there was a way to specify a regex flag separated from the regex itself.

If you find such a way, you should aim to specify the use of Pattern.DOTALL, which will make . match linefeeds.

If you don't, you can specify the use of the DOTALL mode from inside the regex pattern by using its shorthand (?s), which will apply to the rest of the pattern :

```<code>(?s)^.*password=.*"
</code>```

I've tested it on ideone, feel free to adapt the code to make sure it works for you.

You won't be able to test this with sed ; the line-by-line problem could be avoided by loading the whole file in the pattern space (which would be a bad idea in itself), but (GNU?) sed only accepts BRE and ERE regexs, which do not implement a DOTALL flag.

To test it on individual files regex101 will do, to test it on a whole git repo I'd just clone it and run the target tool rather than a substitute command.

Body:
I am trying to find a regular expression which would allow me to delete entire content of a file if a particular string matches.

As an example, my file contents are:

This is the first line
Here is password=SECRET second line
Here is third line

I am doing search for string with pattern password= and when that match happens, ALL lines should be removed from the above file.

Below command does remove the entire line matching the pattern but I can't figure out a regular expression for removing the entire content:

cat test.txt | sed 's|^.*password=.*||'

I understand sed works line by line and unless I use additional options in sed, I probably do not have a way to delete the entire content.

The reason I am only interested in regular expression is that I am using another tool which uses regular expression as an input to perform transformations. I use sed here as an example to illustrate what I understand so far.

Body:
Note that this answer is based on OP's comments on his answer where he discloses that he is only using sed to test his regex and that his final solution uses BFG. This tool uses Java regexes so testing the solution with sed makes little sense, which is why my solution doesn't match the tags of the question.

The documentation of the tool you use is lackluster, I couldn't find if there was a way to specify a regex flag separated from the regex itself.

If you find such a way, you should aim to specify the use of Pattern.DOTALL, which will make . match linefeeds.

If you don't, you can specify the use of the DOTALL mode from inside the regex pattern by using its shorthand (?s), which will apply to the rest of the pattern :

(?s)^.*password=.*"

I've tested it on ideone, feel free to adapt the code to make sure it works for you.

You won't be able to test this with sed ; the line-by-line problem could be avoided by loading the whole file in the pattern space (which would be a bad idea in itself), but (GNU?) sed only accepts BRE and ERE regexs, which do not implement a DOTALL flag.

To test it on individual files regex101 will do, to test it on a whole git repo I'd just clone it and run the target tool rather than a substitute command.


问:
Tiles being drawn in the wrong location
I've finally managed to get my tiles drawn on the screen somewhat in a correct way. Although the location is a bit off and I can't seem to figure out why...

I'm using SFML for drawing.

Tile.hpp:

```<code>#ifndef TILE_HPP
#define TILE_HPP

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

#include "textureManager.hpp"

class Tile {
public:
    Tile();
    Tile(sf::Vector2i coord, int biome);
    ~Tile();

    sf::Vector2i getCoord() const { return coord; };
    int getBiome() const { return biome; };

    void setCoord(sf::Vector2i coord) { this->coord = coord; };
    void setBiome(int biome) { this->biome = biome; };

    void draw(int x, int y, sf::RenderWindow* rw);
    void update(sf::Texture& texture);

private:
    sf::Vector2i coord;
    int biome;

    sf::Sprite sprite;
};

#endif
</code>```

Tile.cpp

```<code>#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

#include "textureManager.hpp"
#include "tile.hpp"

Tile::Tile()
{}

Tile::Tile(sf::Vector2i coord, int biome) {
    this->biome = biome;
    this->coord = coord;
}

Tile::~Tile(){}

void Tile::draw(int x, int y, sf::RenderWindow* rw)
{
    sprite.setPosition(x, y);
    rw->draw(sprite);
}

void Tile::update(sf::Texture& texture)
{
    switch (biome)
    {
        // Not important here
    }
}
</code>```

Now the more relevant part: the drawing

```<code>void StatePlay::draw(const float dt)
{
    game->window.setView(view);
    game->window.clear(sf::Color::Black);

    sf::Vector2f offset = camera.getLocation();
    int newX = (offset.x / map.getTileSize()) - (map.chunkSize / 2);
    int newY = (offset.y / map.getTileSize()) - (map.chunkSize / 2);

    for (int x = 0; x < map.chunkSize; x++)
    {
        for (int y = 0; y < map.chunkSize; y++)
            {
                Tile tile = map.getTile(newX + x, newY + y);
                tile.draw((newX + x) * map.getTileSize(), (newY + y) * map.getTileSize(), &game->window);
            }
        }

    return;
}

StatePlay::StatePlay(Game* game)
{
    this->game = game;
    sf::Vector2f pos = sf::Vector2f(game->window.getSize()); // 1366x768
    view.setSize(pos);
    pos *= 0.5f; // 688x384
    view.setCenter(pos);

    // Initialize map
    map.init(game->gameTime, game->textureManager.getImage("tileset.png"));

    float w     = (float) map.getWidth(); // 500
    float h     = (float) map.getHeight(); // 500
    w           *= 0.5f; // 250
    h           *= 0.5f; // 250
    w           *= map.getTileSize(); // 250 * 32 = 8000
    h           *= map.getTileSize(); // 250 * 32 = 8000
    // Move camera
    // Uses view::move from sfml to move the view with w and h
    // Also sets camera private to w and h values, return with camera::getLocation()
    camera.setLocation(&view, sf::Vector2f(w, h));
}
</code>```

The result is that I only see the ~10 tiles squared, in the bottom left corner of my screen, covering about 3/4.

The correct tiles are chosen, but the draw location is wrong... It should draw the center of 64x64 (x 32px each) tiles, as much as fit on the screen.

答:
I have fixed the problem. It was a very stupid mistake...

At first without drawing anything, it is normal to center the view on 0.5f * sf::View::getSize() to get the view centered in your window. So the center was already at half of my window size. When using Camera::setLocation(), I used the sf::View::move() to move the view accordingly. So when trying to center it on the map, it added the x and y correctly, but also half of my window size. This resulted in having an offset which was incorrect. Substracting or leaving those values out has fixed this stupid problem.

Thank you for the help.

Title: Tiles being drawn in the wrong location

Body:
I've finally managed to get my tiles drawn on the screen somewhat in a correct way. Although the location is a bit off and I can't seem to figure out why...

I'm using SFML for drawing.

Tile.hpp:

#ifndef TILE_HPP
#define TILE_HPP

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

#include "textureManager.hpp"

class Tile {
public:
    Tile();
    Tile(sf::Vector2i coord, int biome);
    ~Tile();

    sf::Vector2i getCoord() const { return coord; };
    int getBiome() const { return biome; };

    void setCoord(sf::Vector2i coord) { this->coord = coord; };
    void setBiome(int biome) { this->biome = biome; };

    void draw(int x, int y, sf::RenderWindow* rw);
    void update(sf::Texture& texture);

private:
    sf::Vector2i coord;
    int biome;

    sf::Sprite sprite;
};

#endif

Tile.cpp

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

#include "textureManager.hpp"
#include "tile.hpp"

Tile::Tile()
{}

Tile::Tile(sf::Vector2i coord, int biome) {
    this->biome = biome;
    this->coord = coord;
}

Tile::~Tile(){}

void Tile::draw(int x, int y, sf::RenderWindow* rw)
{
    sprite.setPosition(x, y);
    rw->draw(sprite);
}

void Tile::update(sf::Texture& texture)
{
    switch (biome)
    {
        // Not important here
    }
}

Now the more relevant part: the drawing

void StatePlay::draw(const float dt)
{
    game->window.setView(view);
    game->window.clear(sf::Color::Black);

    sf::Vector2f offset = camera.getLocation();
    int newX = (offset.x / map.getTileSize()) - (map.chunkSize / 2);
    int newY = (offset.y / map.getTileSize()) - (map.chunkSize / 2);

    for (int x = 0; x < map.chunkSize; x++)
    {
        for (int y = 0; y < map.chunkSize; y++)
            {
                Tile tile = map.getTile(newX + x, newY + y);
                tile.draw((newX + x) * map.getTileSize(), (newY + y) * map.getTileSize(), &game->window);
            }
        }

    return;
}

StatePlay::StatePlay(Game* game)
{
    this->game = game;
    sf::Vector2f pos = sf::Vector2f(game->window.getSize()); // 1366x768
    view.setSize(pos);
    pos *= 0.5f; // 688x384
    view.setCenter(pos);

    // Initialize map
    map.init(game->gameTime, game->textureManager.getImage("tileset.png"));

    float w     = (float) map.getWidth(); // 500
    float h     = (float) map.getHeight(); // 500
    w           *= 0.5f; // 250
    h           *= 0.5f; // 250
    w           *= map.getTileSize(); // 250 * 32 = 8000
    h           *= map.getTileSize(); // 250 * 32 = 8000
    // Move camera
    // Uses view::move from sfml to move the view with w and h
    // Also sets camera private to w and h values, return with camera::getLocation()
    camera.setLocation(&view, sf::Vector2f(w, h));
}

The result is that I only see the ~10 tiles squared, in the bottom left corner of my screen, covering about 3/4.

The correct tiles are chosen, but the draw location is wrong... It should draw the center of 64x64 (x 32px each) tiles, as much as fit on the screen.


问:
Telegram : How to Broadcast Message
We are planning to integrate Telegram with our project. The requirement is that when some event occurs, send a notification to a set of users. I have already created a test bot with telegram. My question is, is it possible to do it with bot ie sending a message to group of users. Or are there any other method to accomplish this.

We are using PHP for our project.

答:
Message can't send to multiple chat, even send one message pre request, there have rate limit.

You should try channel instead of private message, it support unlimited subscriber, and can post by any administrators (both human and bot).

Title: Telegram : How to Broadcast Message


问:
Bundling data files with PyInstaller (--onefile)
I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with --onefile.

If I do --onedir it works all works very well.
When I use --onefile, it can't find the referenced additional files (when running the compiled EXE). It finds the DLLs and everything else fine, just not the two images.

I've looked in the temp-dir generated when running the EXE (\Temp\_MEI95642\ for example) and the files are indeed in there. When I drop the EXE in that temp-directory it finds them. Very perplexing.

This is what I've added to the .spec file

```<code>a.datas += [('images/icon.ico', 'D:\\[workspace]\\App\\src\\images\\icon.ico',  'DATA'),
('images/loaderani.gif','D:\\[workspace]\\App\\src\\images\\loaderani.gif','DATA')]
</code>```

I should add that I have tried not putting them in subfolders as well, didn't make a difference.

Edit: Marked newer answer as correct due to PyInstaller update.

答:
Perhaps i missed a step or did something wrong but the methods which are above, didn't bundle data files with PyInstaller into one exe file. Let me share the steps what i have done.

step:Write one of the above methods into your py file with importing sys and os modules. I tried both of them. The last one is:

```<code>def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)
</code>```

step: Write, pyi-makespec file.py, to the console, to create a file.spec file.

step: Open, file.spec with Notepad++ to add the data files like below:

```<code>a = Analysis(['C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.py'],
             pathex=['C:\\Users\\TCK\\Desktop\\Projeler'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
#Add the file like the below example
a.datas += [('Converter-GUI.ico', 'C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico', 'DATA')]
pyz = PYZ(a.pure, a.zipped_data,
     cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='Converter-GUI',
          debug=False,
          strip=False,
          upx=True,
          #Turn the console option False if you don't want to see the console while executing the program.
          console=False,
          #Add an icon to the program.
          icon='C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico')

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='Converter-GUI')
</code>```

step: I followed the above steps, then saved the spec file. At last opened the console and write, pyinstaller file.spec (in my case, file=Converter-GUI).

Conclusion: There's still more than one file in the dist folder.

Note: I'm using Python 3.5.

EDIT: Finally it works with Jonathan Reinhart's method.

step: Add the below codes to your python file with importing sys and os.

```<code>def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)
</code>```

step: Call the above function with adding the path of your file:

```<code>image_path = resource_path("Converter-GUI.ico")
</code>```

step: Write the above variable that call the function to where your codes need the path. In my case it's:

```<code>    self.window.iconbitmap(image_path)
</code>```

step: Open the console in the same directory of your python file, write the codes like below:

```<code>    pyinstaller --onefile your_file.py
</code>```

step: Open the .spec file of the python file and append the a.datas array and add the icon to the exe class, which was given above before the edit in 3'rd step.

step: Save and exit the path file. Go to your folder which include the spec and py file. Open again the console window and type the below command:

```<code>    pyinstaller your_file.spec
</code>```

After the 6. step your one file is ready to use.

Body:
I'm trying to build a one-file EXE with PyInstaller which is to include an image and an icon. I cannot for the life of me get it to work with --onefile.

If I do --onedir it works all works very well.
When I use --onefile, it can't find the referenced additional files (when running the compiled EXE). It finds the DLLs and everything else fine, just not the two images.

I've looked in the temp-dir generated when running the EXE (\Temp\_MEI95642\ for example) and the files are indeed in there. When I drop the EXE in that temp-directory it finds them. Very perplexing.

This is what I've added to the .spec file

a.datas += [('images/icon.ico', 'D:\\[workspace]\\App\\src\\images\\icon.ico',  'DATA'),
('images/loaderani.gif','D:\\[workspace]\\App\\src\\images\\loaderani.gif','DATA')]

I should add that I have tried not putting them in subfolders as well, didn't make a difference.

Edit: Marked newer answer as correct due to PyInstaller update.

Body:
Perhaps i missed a step or did something wrong but the methods which are above, didn't bundle data files with PyInstaller into one exe file. Let me share the steps what i have done.

step:Write one of the above methods into your py file with importing sys and os modules. I tried both of them. The last one is:

def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

step: Write, pyi-makespec file.py, to the console, to create a file.spec file.

step: Open, file.spec with Notepad++ to add the data files like below:

a = Analysis(['C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.py'],
             pathex=['C:\\Users\\TCK\\Desktop\\Projeler'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
#Add the file like the below example
a.datas += [('Converter-GUI.ico', 'C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico', 'DATA')]
pyz = PYZ(a.pure, a.zipped_data,
     cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          exclude_binaries=True,
          name='Converter-GUI',
          debug=False,
          strip=False,
          upx=True,
          #Turn the console option False if you don't want to see the console while executing the program.
          console=False,
          #Add an icon to the program.
          icon='C:\\Users\\TCK\\Desktop\\Projeler\\Converter-GUI.ico')

coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='Converter-GUI')

step: I followed the above steps, then saved the spec file. At last opened the console and write, pyinstaller file.spec (in my case, file=Converter-GUI).

Conclusion: There's still more than one file in the dist folder.

Note: I'm using Python 3.5.

EDIT: Finally it works with Jonathan Reinhart's method.

step: Add the below codes to your python file with importing sys and os.

def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

step: Call the above function with adding the path of your file:

image_path = resource_path("Converter-GUI.ico")

step: Write the above variable that call the function to where your codes need the path. In my case it's:

    self.window.iconbitmap(image_path)

step: Open the console in the same directory of your python file, write the codes like below:

    pyinstaller --onefile your_file.py

step: Open the .spec file of the python file and append the a.datas array and add the icon to the exe class, which was given above before the edit in 3'rd step.

step: Save and exit the path file. Go to your folder which include the spec and py file. Open again the console window and type the below command:

    pyinstaller your_file.spec

After the 6. step your one file is ready to use.


问:
sample spawned processes is alive and exit code
I have bash script that runs a long running process that prints a lot of stuff to stdout. I made the script print the process output only after it finished and only if it failed.

My problem is that some CI require some stdout prints every X minutes and the process sometimes take a lot more than those X minutes.

I'm trying to think of bash solution that would:

run the process and keep the stdout aside.

while the process is running, print "." to stdout every X seconds - to signal that the script is still running.

After the process is done, will be able to get its exit code and recat accordingly.

Here's is what I started writing:

```<code>run_process > output.txt 2>&1 & my_pid=$!
exited=0
while [ ${exited} -eq 0 ]
do
  timeout wait 5s ${my_pid};exit_code=$?;exited=1
  echo .
done
</code>```

clearly, that doesn't work since timeout cannot get a series of commands.
Do you have other solutions?

答:
Try this:

```<code>run_process > output.txt 2>&1 & my_pid=$!
while ps -p $my_pid > /dev/null; do
  echo -n .
  sleep 5
done
</code>```

Get exit value from wait:

```<code>wait $mypid
echo $?
</code>```

Body:
I have bash script that runs a long running process that prints a lot of stuff to stdout. I made the script print the process output only after it finished and only if it failed.

My problem is that some CI require some stdout prints every X minutes and the process sometimes take a lot more than those X minutes.

I'm trying to think of bash solution that would:

run the process and keep the stdout aside.

while the process is running, print "." to stdout every X seconds - to signal that the script is still running.

After the process is done, will be able to get its exit code and recat accordingly.

Here's is what I started writing:

run_process > output.txt 2>&1 & my_pid=$!
exited=0
while [ ${exited} -eq 0 ]
do
  timeout wait 5s ${my_pid};exit_code=$?;exited=1
  echo .
done

clearly, that doesn't work since timeout cannot get a series of commands.
Do you have other solutions?

Body:
Try this:

run_process > output.txt 2>&1 & my_pid=$!
while ps -p $my_pid > /dev/null; do
  echo -n .
  sleep 5
done

Get exit value from wait:

wait $mypid
echo $?


问:
How to handle default values for a DateTime type in Doctrine2 SELECT query?
I have the following Doctrine2 entity:

```<code><?php

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
/**
 * @ORM\Entity
 */
class Account
{
    use TimestampableEntity;

    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(type="integer", unique=true, nullable=false)
     */
    private $id;
}
</code>```

As you can see I am using Gedmo Timestampable with the Trait provided by the bundle. It's working fine.

The problem happen when I fetch the data and the column updated_at is coming as NULL 0000-00-00 00:00:00. For such case the DateTime object is translated into an invalid date as shown below:

```<code>array (
  'RowId' => 26944,
  'synchflag' => 1,
  'updatedAt' =>
  DateTime::__set_state(array(
     'date' => '-0001-11-30 00:00:00.000000',
     'timezone_type' => 3,
     'timezone' => 'UTC',
  )),
)
</code>```

I did check docs but there isn't anything helpful (or at least I didn't found it if you do let me know)

What is the right way to deal with this?

EDIT:

Maybe the right question here should be: if updated_at is coming as 0000-00-00 00:00:00 how do I turn it into NOW()? As you may notice the getUpdatedAt() return a DateTime based on the fetched data. Is there any event for SELECT statement?

答:
As the problem is that the database already have those invalid values, you can create your own doctrine datetime type to make the conversion to null when reading that invalid value from the database:

```<code><?php
namespace AppBundle\Doctrine\DBAL;

use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class MyDateTimeType extends DateTimeType
{

   public function convertToPHPValue($value, AbstractPlatform $platform)
   {
       if (null === $value || $value instanceof \DateTime) {
           return $value;
       }

       if ('0000-00-00 00:00:00' === $value) {
          return null;
       }

       return parent::convertToPHPValue($value, $platform);
   }
}
</code>```

And register this custom type in doctrine configuration:

```<code>doctrine:
   dbal:
       types:
           datetime: AppBundle\Doctrine\DBAL\MyDateTimeType
</code>```

Note: you can enhanced this code using regexp and/or datetime validity checking instead of a simple comparison

Body:
I have the following Doctrine2 entity:

<?php

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
/**
 * @ORM\Entity
 */
class Account
{
    use TimestampableEntity;

    /**
     * @var integer
     *
     * @ORM\Id
     * @ORM\Column(type="integer", unique=true, nullable=false)
     */
    private $id;
}

As you can see I am using Gedmo Timestampable with the Trait provided by the bundle. It's working fine.

The problem happen when I fetch the data and the column updated_at is coming as NULL 0000-00-00 00:00:00. For such case the DateTime object is translated into an invalid date as shown below:

array (
  'RowId' => 26944,
  'synchflag' => 1,
  'updatedAt' =>
  DateTime::__set_state(array(
     'date' => '-0001-11-30 00:00:00.000000',
     'timezone_type' => 3,
     'timezone' => 'UTC',
  )),
)

I did check docs but there isn't anything helpful (or at least I didn't found it if you do let me know)

What is the right way to deal with this?

EDIT:

Maybe the right question here should be: if updated_at is coming as 0000-00-00 00:00:00 how do I turn it into NOW()? As you may notice the getUpdatedAt() return a DateTime based on the fetched data. Is there any event for SELECT statement?

Body:
As the problem is that the database already have those invalid values, you can create your own doctrine datetime type to make the conversion to null when reading that invalid value from the database:

<?php
namespace AppBundle\Doctrine\DBAL;

use DateTimeZone;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\ConversionException;
use Doctrine\DBAL\Types\DateTimeType;

class MyDateTimeType extends DateTimeType
{

   public function convertToPHPValue($value, AbstractPlatform $platform)
   {
       if (null === $value || $value instanceof \DateTime) {
           return $value;
       }

       if ('0000-00-00 00:00:00' === $value) {
          return null;
       }

       return parent::convertToPHPValue($value, $platform);
   }
}

And register this custom type in doctrine configuration:

doctrine:
   dbal:
       types:
           datetime: AppBundle\Doctrine\DBAL\MyDateTimeType

Note: you can enhanced this code using regexp and/or datetime validity checking instead of a simple comparison