问:
How to make an async event run continuously?
I am creating a little console app that is just in proof-of-concept stage right now.  The idea is that it will query 3rd party API's for events on their end.  (That part is all working just fine).

When an event arrives, we need to stick the json string for that event into a sqlite db on our side.  At the same time, I need a process running in the same app that is continuously looking for records in the sqlite table, and when it finds one, it handles it.

Here's what I have so far... (again, this is just a proof of concept while I learn the basics of how to set this up)...

```<code>static void Main(string[] args)
{
    var t = CheckEventsAsync();
    while (true)
    {
        System.Threading.Thread.Sleep(5000);
        DataAccess.InsertData("INSERT INTO events(value) VALUES ('this is an event');");
    }
}

static private async Task CheckEventsAsync()
{
    DataTable dt = await DataAccess.LoadDataAsync("SELECT * FROM events");
    foreach (var dr in dt.Rows)
    {
        Console.WriteLine("got an event!");
    }
}
</code>```

The problem is that CheckEventsAsync() only ever fires once, and then when the 5 second timer goes off an a record is added to the table, nothing happens.

Am I going to need to use an EventHandler (with a delegate, etc) to make this work?  Or is it possible w/o doing it that way?

Thanks!

Oh, almost forgot... (this works in that it returns a data table if there is data, and null if not.  But I'm not sure I'm doing  it right for the overall goal)...

```<code>    public static async Task<DataTable> LoadDataAsync(string txtQuery)
    {
        var dataTable = new DataTable();
        var connection = new SQLiteConnection(_source);
        using (connection)
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = txtQuery;
            var task = await command.ExecuteReaderAsync();
            dataTable = new DataTable();
            dataTable.Load(task);
            connection.Close();
        }
        if (dataTable != null & dataTable.Rows.Count > 0)
            return dataTable;
        else
            return null;
    }
</code>```

EDIT

I see from the answers so far that I did a bad job of asking the question.  I need to have two processes running:

The first process will listen for 3rd party events and add them to the sqlite table.  This is simulated with the 5 second timer.  But in reality, there will not be a timer inside a While(true) loop.  It will be a WebSocket Listener.

The second process will watch for records in the database and handle them. So, CheckEventsAsync() needs to be a listener that triggers without the method being called.

The two need to operate within the same app, but independent of each other.

I hope I am making sense?

答:
Use Microsoft's Reactive Framework for this:

```<code>static readonly BlockingCollection<ItemToProcess> _queue = new BlockingCollection<ItemToProcess>(new ConcurrentQueue<ItemToProcess>());

static void Main(string[] args)
{
    IDisposable inserts =
        Observable
            .Interval(TimeSpan.FromSeconds(5.0))
            .Subscribe(_ =>
            {
                _queue.Add(new ItemToProcess() { Value = "value" });
            });

    IDisposable checks =
        new CompositeDisposable(
            Disposable.Create(() => _queue.CompleteAdding()),
            _queue
                .GetConsumingEnumerable()
                .ToObservable(Scheduler.Default)
                .Subscribe(item =>
                {
                    Console.WriteLine(item.Value);
                }));
}
</code>```

This handles all of the threading and makes it easy to close the app. Just call inserts.Dispose() and checks.Dispose() just before exiting.

NuGet "System.Reactive" to get the bits.

Body:
I am creating a little console app that is just in proof-of-concept stage right now.  The idea is that it will query 3rd party API's for events on their end.  (That part is all working just fine).

When an event arrives, we need to stick the json string for that event into a sqlite db on our side.  At the same time, I need a process running in the same app that is continuously looking for records in the sqlite table, and when it finds one, it handles it.

Here's what I have so far... (again, this is just a proof of concept while I learn the basics of how to set this up)...

static void Main(string[] args)
{
    var t = CheckEventsAsync();
    while (true)
    {
        System.Threading.Thread.Sleep(5000);
        DataAccess.InsertData("INSERT INTO events(value) VALUES ('this is an event');");
    }
}

static private async Task CheckEventsAsync()
{
    DataTable dt = await DataAccess.LoadDataAsync("SELECT * FROM events");
    foreach (var dr in dt.Rows)
    {
        Console.WriteLine("got an event!");
    }
}

The problem is that CheckEventsAsync() only ever fires once, and then when the 5 second timer goes off an a record is added to the table, nothing happens.

Am I going to need to use an EventHandler (with a delegate, etc) to make this work?  Or is it possible w/o doing it that way?

Thanks!

Oh, almost forgot... (this works in that it returns a data table if there is data, and null if not.  But I'm not sure I'm doing  it right for the overall goal)...

    public static async Task<DataTable> LoadDataAsync(string txtQuery)
    {
        var dataTable = new DataTable();
        var connection = new SQLiteConnection(_source);
        using (connection)
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = txtQuery;
            var task = await command.ExecuteReaderAsync();
            dataTable = new DataTable();
            dataTable.Load(task);
            connection.Close();
        }
        if (dataTable != null & dataTable.Rows.Count > 0)
            return dataTable;
        else
            return null;
    }

EDIT

I see from the answers so far that I did a bad job of asking the question.  I need to have two processes running:

The first process will listen for 3rd party events and add them to the sqlite table.  This is simulated with the 5 second timer.  But in reality, there will not be a timer inside a While(true) loop.  It will be a WebSocket Listener.

The second process will watch for records in the database and handle them. So, CheckEventsAsync() needs to be a listener that triggers without the method being called.

The two need to operate within the same app, but independent of each other.

I hope I am making sense?

Body:
Use Microsoft's Reactive Framework for this:

static readonly BlockingCollection<ItemToProcess> _queue = new BlockingCollection<ItemToProcess>(new ConcurrentQueue<ItemToProcess>());

static void Main(string[] args)
{
    IDisposable inserts =
        Observable
            .Interval(TimeSpan.FromSeconds(5.0))
            .Subscribe(_ =>
            {
                _queue.Add(new ItemToProcess() { Value = "value" });
            });

    IDisposable checks =
        new CompositeDisposable(
            Disposable.Create(() => _queue.CompleteAdding()),
            _queue
                .GetConsumingEnumerable()
                .ToObservable(Scheduler.Default)
                .Subscribe(item =>
                {
                    Console.WriteLine(item.Value);
                }));
}

This handles all of the threading and makes it easy to close the app. Just call inserts.Dispose() and checks.Dispose() just before exiting.

NuGet "System.Reactive" to get the bits.


来源: stackexchange

问:
HTML label center aligned getting cropped on both sides
I'm seeing a bug that is intermittently reproducible only on iPhone Safari (not on any other mobile or desktop browser not even macbook safari). The code looks like:

```<code><div style="overflow: auto; height: calc(100% - 55px); background-color: cyan;">
   <ul ...><li..></li> <!-- some ul containing li omitted for brevity-->

   <label class="certainClassname" style="font-size: small; font-style: italic; width: 100%; text-align: center; background-color: yellow">
{{"msg" | translate}}
   </label>
</div>
</code>```

In other style sheet I have:

```<code>.certainClassname {
    cursor: pointer;
    word-break: break-all;
}
</code>```

msg = "PKtest!" for my testing though it usually has another value.

The problem is that this label is getting cropped at the edges when the bug is reproduced as below:

This bug is only seen on Safari iPhone and none of the other browsers, and seems to only happen the first time that page is loaded, and not later. It could be related to zooming because even the tiniest pinch-to-zoom on iPhone fixes it and the label text (and yellow) expands fully.

Could someone please help me diagnosing this in CSS above? I've tried to fix using each in css of label but none have worked:

```<code>display: inline;
display: inline-block;
display: block;
padding: 2px 10px 2px 10px;
margin-left: auto;
margin-right: auto;
z-index: 999;
clear: both;
(all these above tested but none fixes this issue seen intermittently and only on iPhone Safari).
</code>```

答: I think you have to set you label around a div with width: 100% a background-color: yellow</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm seeing a bug that is intermittently reproducible only on iPhone Safari (not on any other mobile or desktop browser not even macbook safari). The code looks like:

{{"msg" | translate}}

In other style sheet I have:

.certainClassname {
    cursor: pointer;
    word-break: break-all;
}

msg = "PKtest!" for my testing though it usually has another value.

The problem is that this label is getting cropped at the edges when the bug is reproduced as below:

This bug is only seen on Safari iPhone and none of the other browsers, and seems to only happen the first time that page is loaded, and not later. It could be related to zooming because even the tiniest pinch-to-zoom on iPhone fixes it and the label text (and yellow) expands fully.

Could someone please help me diagnosing this in CSS above? I've tried to fix using each in css of label but none have worked:

display: inline;
display: inline-block;
display: block;
padding: 2px 10px 2px 10px;
margin-left: auto;
margin-right: auto;
z-index: 999;
clear: both;
(all these above tested but none fixes this issue seen intermittently and only on iPhone Safari).


问:
Listing product titles of products added to cart via shortcode in WooCommerce
I am trying to list products that have been added to cart in WooCommerce via shortcode. I have managed to get this far, however it only lists one product with this code. I want to list each product in a different line, preferably with the link back to the product.

Here is my code:

```<code>// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
foreach( $cart as $cart_item ){
return $item_name = $cart_item['data']->get_title();
}
}
add_shortcode( 'bag_products', 'get_cart_products' );
</code>```

Please guide. Thank you.

答:
You can try this,

```<code>// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
 $cart_items = "<table><tr>";
 foreach( $cart as $cart_item ){
   $cart_items .= '<td>'.$cart_item['data']->get_title().'</td>';
 }
 $cart_items .= "</tr></table>";
 return $cart_items;
}
add_shortcode( 'bag_products', 'get_cart_products' );
</code>```

Hope this will helps you.

Body:
I am trying to list products that have been added to cart in WooCommerce via shortcode. I have managed to get this far, however it only lists one product with this code. I want to list each product in a different line, preferably with the link back to the product.

Here is my code:

// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
foreach( $cart as $cart_item ){
return $item_name = $cart_item['data']->get_title();
}
}
add_shortcode( 'bag_products', 'get_cart_products' );

Please guide. Thank you.

Body:
You can try this,

// Add Shortcode [bag_products]
function get_cart_products() {
$cart = WC()->cart->get_cart();
 $cart_items = "<table><tr>";
 foreach( $cart as $cart_item ){
   $cart_items .= '<td>'.$cart_item['data']->get_title().'</td>';
 }
 $cart_items .= "</tr></table>";
 return $cart_items;
}
add_shortcode( 'bag_products', 'get_cart_products' );

Hope this will helps you.


问:
How can I have the text in this accordion be visible when the window is small or on mobile devices?
I have some code that uses HTML, CSS and JS. When you shorten the window or view on a mobile device, the text goes behind the accordian tab below it. How could I make it so the text has a small margin between itself and the tab below when active, and without making the accordions far apart when closed?</p>

```<code><!DOCTYPE html>
<html>
<head>
<style>
button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ccc;
}

button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}
</style>
</head>
<body>

<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<script>
var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + "px";
    }
  }
}
</script>

</body>
</html>
</code>```

答:
There needs to define panel height in resize mode. So I revised the maxHeight of the panel.

Here is the working code for your reference.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = "inherit";
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ccc;
}

button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}</code>```

Accordion with symbols

In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.

<button class="accordion">Section 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">Section 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">Section 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

```

Body:
I have some code that uses HTML, CSS and JS. When you shorten the window or view on a mobile device, the text goes behind the accordian tab below it. How could I make it so the text has a small margin between itself and the tab below when active, and without making the accordions far apart when closed?

<!DOCTYPE html>

Accordion with symbols

In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.

<button class="accordion">Section 1</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">Section 2</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

<button class="accordion">Section 3</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Body:
There needs to define panel height in resize mode. So I revised the maxHeight of the panel.

Here is the working code for your reference.

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle("active");
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight){
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = "inherit";
    }
  }
}

button.accordion {
    background-color: #eee;
    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion.active, button.accordion:hover {
    background-color: #ccc;
}

button.accordion:after {
    content: '\002B';
    color: #777;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}

<h2>Accordion with symbols</h2>
<p>In this example we have added a "plus" sign to each button. When the user clicks on the button, the "plus" sign is replaced with a "minus" sign.</p>
<button class="accordion">Section 1</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 2</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

<button class="accordion">Section 3</button>
<div class="panel">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>


问:
Select column and values where values are greater than 0 in mysql
I have two tables.

```<code>Name: `table1`
name    d1      d2      d3      d4      d5
Tapan   2       0       3       8       0
</code>```

```<code>another table : `table2`
name    c1      c2      c3      c4      c5      c6
Tapan   12      14      0       0       17      0
</code>```

In both tables there are 50+ columns.
How to get a report like:

```<code>name    - Tapan
d1      - 2
d3      - 3
d4      - 8
c1      - 12
c2      - 14
c5      - 17
total   - 56
</code>```

I failed to create the sql query for the report where value>0 and name = 'Tapan'

```<code>SELECT a.*, b.*
FROM table1 a
INNER JOIN table2 b
ON a.name = b.name
</code>```

See the SQL Fiddle

I need to get the report  where column value is greater than 0

答:
IF these are the fixed columns and you need that report for name = Tapan only then you can get the desired results using union all

```<code>select a.name , a.tapan
from(
  select 'd1' as name, d1 as tapan from table1 where name = 'Tapan'
  union all
  select 'd2' as name, d2 as tapan from table1 where name = 'Tapan'
  union all
  select 'd3' as name, d3 as tapan from table1 where name = 'Tapan'
  union all
  select 'd4' as name, d4 as tapan from table1 where name = 'Tapan'
  union all
  select 'd5' as name, d5 as tapan from table1 where name = 'Tapan'
  union all
  select 'c1' as name, c1 as tapan from table2 where name = 'Tapan'
  union all
  select 'c2' as name, c2 as tapan from table2 where name = 'Tapan'
  union all
  select 'c3' as name, c3 as tapan from table2 where name = 'Tapan'
  union all
  select 'c4' as name, c4 as tapan from table2 where name = 'Tapan'
  union all
  select 'c5' as name, c5 as tapan from table2 where name = 'Tapan'
  union all
  select 'c6' as name, c6 as tapan from table2 where name = 'Tapan'
) a
where a.tapan > 0
union all
select 'total', sum(a.d1 +a.d2 +a.d3 +a.d4 +a.d5 + b.c1 + b.c2 + b.c3 + b.c4 + b.c5 + b.c6 )
from table1 a inner join table2 b on a.name = b.name where a.name = 'Tapan'
</code>```

Demo

Edit for restructure

Create 2 tables one for your data and one for data types like c1 , c2 , d1 and so on like

data_types

```<code>    id  title
------  --------
     1  d1
     2  d2
     3  d3
     4  d4
     5  d5
     6  c1
     7  c2
     8  c3
     9  c4
    10  c5
    11  c6
</code>```

data table

```<code>    id  name    type_id  type_value
------  ------  -------  ------------
     1  Tapan         1             2
     2  Tapan         2             0
     3  Tapan         3             3
     4  Tapan         4             8
     5  Tapan         5             0
     6  Tapan         6            12
     7  Tapan         7            14
     8  Tapan         8             0
     9  Tapan         9             0
    10  Tapan        10            17
    11  Tapan        11             0
</code>```

data table will hold the reference of types table as type_id and type_value will store your number related to each name and type and then you can query your required data by using simple join operation

```<code>SELECT b.`title`,a.`type_value` AS Tapan
FROM `data` a
JOIN `data_types` b ON a.`type_id` = b.`id`
WHERE a.`name` = 'Tapan'
AND a.`type_value` > 0
</code>```

Demo

Body:
I have two tables.

Name: `table1`
name    d1      d2      d3      d4      d5
Tapan   2       0       3       8       0

another table : `table2`
name    c1      c2      c3      c4      c5      c6
Tapan   12      14      0       0       17      0

In both tables there are 50+ columns.
How to get a report like:

name    - Tapan
d1      - 2
d3      - 3
d4      - 8
c1      - 12
c2      - 14
c5      - 17
total   - 56

I failed to create the sql query for the report where value>0 and name = 'Tapan'

SELECT a.*, b.*
FROM table1 a
INNER JOIN table2 b
ON a.name = b.name

See the SQL Fiddle

I need to get the report  where column value is greater than 0

Body:
IF these are the fixed columns and you need that report for name = Tapan only then you can get the desired results using union all

select a.name , a.tapan
from(
  select 'd1' as name, d1 as tapan from table1 where name = 'Tapan'
  union all
  select 'd2' as name, d2 as tapan from table1 where name = 'Tapan'
  union all
  select 'd3' as name, d3 as tapan from table1 where name = 'Tapan'
  union all
  select 'd4' as name, d4 as tapan from table1 where name = 'Tapan'
  union all
  select 'd5' as name, d5 as tapan from table1 where name = 'Tapan'
  union all
  select 'c1' as name, c1 as tapan from table2 where name = 'Tapan'
  union all
  select 'c2' as name, c2 as tapan from table2 where name = 'Tapan'
  union all
  select 'c3' as name, c3 as tapan from table2 where name = 'Tapan'
  union all
  select 'c4' as name, c4 as tapan from table2 where name = 'Tapan'
  union all
  select 'c5' as name, c5 as tapan from table2 where name = 'Tapan'
  union all
  select 'c6' as name, c6 as tapan from table2 where name = 'Tapan'
) a
where a.tapan > 0
union all
select 'total', sum(a.d1 +a.d2 +a.d3 +a.d4 +a.d5 + b.c1 + b.c2 + b.c3 + b.c4 + b.c5 + b.c6 )
from table1 a inner join table2 b on a.name = b.name where a.name = 'Tapan'

Demo

Edit for restructure

Create 2 tables one for your data and one for data types like c1 , c2 , d1 and so on like

data_types

    id  title
------  --------
     1  d1
     2  d2
     3  d3
     4  d4
     5  d5
     6  c1
     7  c2
     8  c3
     9  c4
    10  c5
    11  c6

data table

    id  name    type_id  type_value
------  ------  -------  ------------
     1  Tapan         1             2
     2  Tapan         2             0
     3  Tapan         3             3
     4  Tapan         4             8
     5  Tapan         5             0
     6  Tapan         6            12
     7  Tapan         7            14
     8  Tapan         8             0
     9  Tapan         9             0
    10  Tapan        10            17
    11  Tapan        11             0

data table will hold the reference of types table as type_id and type_value will store your number related to each name and type and then you can query your required data by using simple join operation

SELECT b.`title`,a.`type_value` AS Tapan
FROM `data` a
JOIN `data_types` b ON a.`type_id` = b.`id`
WHERE a.`name` = 'Tapan'
AND a.`type_value` > 0

Demo


问:
Issue in signaling to a workerthread from main thread
I have to do OperationA on input files( 1...N), after that I have to do OperationB on operationA completed files.

So in the main thread I iterated through each files( 1...N) and do the operationA. Then pushes the files to a threadsafe queue and continue for next files. A worker thread gets the files from queue and do operationB.
To implement this I used events like the following:

```<code>HANDLE hEvent =CreateEvent(NULL, FALSE/*autoreset*/, FALSE/*nonsignaled*/, "");
for( files 1... N)
{
   1. Operation A
   2. Push file to the queue
   3. SetEvent( hEvent )
}

WorkerThread()
{
   while(1)
   {
      1. WaitforSingleObject( hEvent , INFINITE )
      2. operation B
   }
}
</code>```

What I am expecting is for each SetEvent() the WaitforSingleObject() will be signaled.
But the actual behavior is not.
I.e For the first SetEvent the WaitforSingleObject is signalled.
While the operationB is in progress many SetEvents are triggering from main thread. So the next WaitforSingleObject() should signal with out any delay, since the second SetEvent is already trigerred. But this is not working as expected.

SetEvent

WaitforSingleObject

SetEvent

SetEvent

SetEvent

WaitforSingleObject

SetEvent

SetEvent

WaitforSingleObject

I called 6 setevent for 6 files. But WaitforSingleObject is signaled for only 3.

First of all please let me know am I using the correct synchronization mechanism for the context?

答:
This is producer-consumer problem, and you can do it with semaphores.

Check this link https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem

Your code is inadequate implementation in the link.

With Semaphores the code will run as expected.

Body:
I have to do OperationA on input files( 1...N), after that I have to do OperationB on operationA completed files.

So in the main thread I iterated through each files( 1...N) and do the operationA. Then pushes the files to a threadsafe queue and continue for next files. A worker thread gets the files from queue and do operationB.
To implement this I used events like the following:

HANDLE hEvent =CreateEvent(NULL, FALSE/*autoreset*/, FALSE/*nonsignaled*/, "");
for( files 1... N)
{
   1. Operation A
   2. Push file to the queue
   3. SetEvent( hEvent )
}

WorkerThread()
{
   while(1)
   {
      1. WaitforSingleObject( hEvent , INFINITE )
      2. operation B
   }
}

What I am expecting is for each SetEvent() the WaitforSingleObject() will be signaled.
But the actual behavior is not.
I.e For the first SetEvent the WaitforSingleObject is signalled.
While the operationB is in progress many SetEvents are triggering from main thread. So the next WaitforSingleObject() should signal with out any delay, since the second SetEvent is already trigerred. But this is not working as expected.

SetEvent

WaitforSingleObject

SetEvent

SetEvent

SetEvent

WaitforSingleObject

SetEvent

SetEvent

WaitforSingleObject

I called 6 setevent for 6 files. But WaitforSingleObject is signaled for only 3.

First of all please let me know am I using the correct synchronization mechanism for the context?


问:
how to convert double quoted vectors in df to numpy array?
I have the following csv file.

```<code>index, vector, label
0, "[0,5,7]", class1
0, "[3,8,10]", class2
0, "[3,8,15]", class2
0, "[3,2,1]", class1
</code>```

I would like to parse and get the vector column such as:

```<code>[[0,5,7],[3,8,10],[3,8,15],[3,2,1]]
</code>```

However, whatever I tried, I get an object like:

```<code>['[0,5,7]','[3,8,10]','[3,8,15]','[3,2,1]']
</code>```

It parses the vector as a string instead of array.

I tried to cast it list/np.array but none of them worked. I also tried to apply the following in order to escape quotes:

```<code>replace.replace("'",'')
replace.replace('"','')
</code>```

They did not have any effect at all.

Therefore, I am open your suggestions to try more.

答:
You can combine the csv module and the json module to parse this like:

Code:

```<code>with open('test.csv', 'rU') as f:
    reader = csv.reader(f, skipinitialspace=True)
    header = next(reader)
    column2 = [json.loads(x[1]) for x in reader]
</code>```

Using Pandas:

This can be translated to pandas as:

```<code>df = pd.read_csv('output.csv', skipinitialspace=True,
                 converters={'vector': lambda x: json.loads(x)})
</code>```

Results:

```<code>[[0, 5, 7], [3, 8, 10], [3, 8, 15], [3, 2, 1]]
</code>```

and:

```<code>   index      vector   label
0      0   [0, 5, 7]  class1
1      0  [3, 8, 10]  class2
2      0  [3, 8, 15]  class2
3      0   [3, 2, 1]  class1
</code>```

Body:
I have the following csv file.

index, vector, label
0, "[0,5,7]", class1
0, "[3,8,10]", class2
0, "[3,8,15]", class2
0, "[3,2,1]", class1

I would like to parse and get the vector column such as:

[[0,5,7],[3,8,10],[3,8,15],[3,2,1]]

However, whatever I tried, I get an object like:

['[0,5,7]','[3,8,10]','[3,8,15]','[3,2,1]']

It parses the vector as a string instead of array.

I tried to cast it list/np.array but none of them worked. I also tried to apply the following in order to escape quotes:

replace.replace("'",'')
replace.replace('"','')

They did not have any effect at all.

Therefore, I am open your suggestions to try more.

Body:
You can combine the csv module and the json module to parse this like:

Code:

with open('test.csv', 'rU') as f:
    reader = csv.reader(f, skipinitialspace=True)
    header = next(reader)
    column2 = [json.loads(x[1]) for x in reader]

Using Pandas:

This can be translated to pandas as:

df = pd.read_csv('output.csv', skipinitialspace=True,
                 converters={'vector': lambda x: json.loads(x)})

Results:

[[0, 5, 7], [3, 8, 10], [3, 8, 15], [3, 2, 1]]

and:

   index      vector   label
0      0   [0, 5, 7]  class1
1      0  [3, 8, 10]  class2
2      0  [3, 8, 15]  class2
3      0   [3, 2, 1]  class1


问:
Matrix dot product
Disclaimer: Im a cuda beginner.

```<code>typedef struct
{
    int row_;
    int col_;
    float* element_;
    int step;
}Matrix_t;

#define BLOCK_SIZE 64

__device__ float getElement(const Matrix_t A, int row, int col);
__device__ Matrix_t getSubMat(Matrix_t A, int row, int col);
__device__ void setElement(Matrix_t A, int row, int col, float value);
__global__ void MatrixDot(Matrix_t A, Matrix_t B, float* dot_);
float  Matrix_dot_(float* M_dev_1, float* M_dev_2, int Number_of_cols, int Number_of_rows, int step);
</code>```

the Matrix_t are used to link a cv::cuda::GpuMat to the C interface via the ptr() operator to get the GPU pointer to element.

```<code>__device__ float getElement(const Matrix_t A, int row, int col)
{
    return A.element_[row* A.step + col];
}

__device__ void setElement(Matrix_t A, int row, int col, float value)
{
    A.element_[row*A.step + col] = value;
}
__device__ Matrix_t getSubMat(Matrix_t A, int row, int col)
{
    Matrix_t A_sub;
    A_sub.row_ = BLOCK_SIZE;
    A_sub.col_ = BLOCK_SIZE;
    A_sub.step = A.step;
    A_sub.element_ = &A.element_[A.step * BLOCK_SIZE * row + BLOCK_SIZE * col];

    return A_sub;
}
</code>```

Here is the kernel:

```<code>__global__ void MatrixDot(Matrix_t A, Matrix_t B, float* dot_)
{
    int blockRow = blockIdx.y;
    int blockCol = blockIdx.x;

    float SubDotValue = 0.0f;

    int row = threadIdx.y;
    int col = threadIdx.x;

    for(int m = 0; m < (A.row_ / BLOCK_SIZE); ++m)
    {
        //get subA & subB
        Matrix_t A_sub = getSubMat(A, blockRow, m);
        Matrix_t B_sub = getSubMat(B, blockRow, m);

        //set Asub & Bsub to the  __shared__ memory

        __shared__ float ASub[BLOCK_SIZE][BLOCK_SIZE];
        __shared__ float BSub[BLOCK_SIZE][BLOCK_SIZE];

        ASub[row][col] = getElement(A_sub, row, col);
        BSub[row][col] = getElement(B_sub, row, col);

        //Synchronize before calculations:
        __syncthreads();

        //Get the dot product of the vector Asub[] Bsub[]
        for(int el_ = 0; el_ < BLOCK_SIZE; ++el_)
        {
            SubDotValue += ASub[row][el_] * BSub[row][el_];
        }
        __syncthreads();
    }

    dot_[row] = SubDotValue;

}
</code>```

and the wrapper:

```<code>float  Matrix_dot_(float* M_dev_1,float* M_dev_2, int Number_of_cols, int Number_of_rows, int step)
{

    float retval = 0;
    float* retval_partial;
    float* retval_device;

    Matrix_t A;
    A.col_ = Number_of_cols;
    A.row_ = Number_of_rows;
    A.element_ = M_dev_1;
    A.step = step;
    Matrix_t B;
    B.col_ = Number_of_cols;
    B.row_ = Number_of_rows;
    B.element_ = M_dev_2;
    B.step = step;

    retval_partial = (float*)malloc( B.row_*sizeof(float) );

    cudaError_t err = cudaMalloc( (void**)&retval_device,B.row_/ BLOCK_SIZE *sizeof(float) );
    printf("\n Cuda malloc: %s", cudaGetErrorString(err));
    std::cout<<std::flush;
    dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
    dim3 dimGrid(B.row_ / BLOCK_SIZE, B.col_ / BLOCK_SIZE);

    MatrixDot<<<dimGrid, dimBlock>>>(A, B, retval_device);
    err = cudaThreadSynchronize();
    std::cout<<std::flush;

    printf("\n Cuda kernel run: %s", cudaGetErrorString(err));
    err = cudaMemcpy(retval_partial, retval_device, B.row_ / BLOCK_SIZE* sizeof(float), cudaMemcpyDeviceToHost);
    printf("\n Cuda cudaMemcpy: %s", cudaGetErrorString(err));
    err = cudaFree(retval_device);
    printf("\n Cuda cudaFree: %s", cudaGetErrorString(err));
    for(int i = 0; i<B.row_/ BLOCK_SIZE ; ++i)
    {
        retval+=retval_partial[i];
    }

    free(retval_partial);

    return retval;
}
</code>```

and the main:

```<code>int main(int argc, const char * argv[])
{
    cv::cuda::DeviceInfo devInfo;
    cv::cuda::setDevice(devInfo.deviceID());

    cv::Mat cudatestA = cv::Mat(64*3, 64*3, CV_32FC1, 2);
    cv::Mat cudatestB = cv::Mat(64*3, 64*3, CV_32FC1, 2);

    double tr = (double) cv::getTickCount();
    double res = cudatestA.dot(cudatestB);

    tr = ((double)cv::getTickCount()-tr)/(double)cv::getTickFrequency();

    cv::cuda::GpuMat ctA(cudatestA);
    cv::cuda::GpuMat ctB(cudatestB);

    double tm_ = (double) cv::getTickCount();
    float res_m = 0;

    res_m = Matrix_dot_((float* )ctA.ptr(), (float*)ctB.ptr(), ctA.cols, ctA.rows, ctA.step);
    tm_ = ((double)cv::getTickCount()-tm_)/(double)cv::getTickFrequency();

    printf("\nCPU: %0.4fms, res: %0.4f\nGPU_M: %0.4fms, res: %0.4f\n", tr*1000.0f, res, tm_*1000.0f,res_m);
    return 0;
}
</code>```

I'm currently stuck on various points:

1) it always output 0.

2) it can only work for matrix M*N Multiple of the defined BLOCK_SIZE (64).

for 1) I can't figure where my logic break, I could get the dot product to work on vector without any troubles but the matrix problem induced by the stride between each row prevent me to use the code (code deleted as the site tell me that there is too much code).

答:
Partial answer:

In your kernel you aren't doing the good sum, nor taking the good elements, and your dim seems inverted

```<code>__global__ void MatrixDot(Matrix_t A, Matrix_t B, float* dot_)
{
//int blockRow = blockIdx.y;
//int blockCol = blockIdx.x;
int blockRow = blockIdx.x;
int blockCol = blockIdx.y;

float SubDotValue = 0.0f;

//int row = threadIdx.y;
//int col = threadIdx.x;
int row = threadIdx.x;
int col = threadIdx.y;

for(int m = 0; m < (A.row_ / BLOCK_SIZE); ++m)
    {
        //get subA & subB
        Matrix_t A_sub = getSubMat(A, m, blockCol);//getSubMat(A, blockRow, m)
        Matrix_t B_sub = getSubMat(B, m, blockCol);//getSubMat(B, blockRow, m)

        //set Asub & Bsub to the  __shared__ memory

        __shared__ float ASub[BLOCK_SIZE][BLOCK_SIZE];
        __shared__ float BSub[BLOCK_SIZE][BLOCK_SIZE];

        ASub[row][col] = getElement(A_sub, row, col);
        BSub[row][col] = getElement(B_sub, row, col);

        //Synchronize before calculations:
        __syncthreads();

        //Get the dot product of the vector Asub[] Bsub[]
        for(int el_ = 0; el_ < BLOCK_SIZE; ++el_)
        {
            SubDotValue += ASub[row][el_] * BSub[row][el_];
        }
        __syncthreads();
    }

dot_[blockRow*BLOCK_SIZE + row] = SubDotValue; //dot_[row] = SubDotValue;

}
</code>```

And your wrapper isn't also allocating the size you need:

```<code>cudaError_t err = cudaMalloc( (void**)&retval_device,B.row_/ BLOCK_SIZE *sizeof(float) );
</code>```

should be:

```<code>cudaError_t err = cudaMalloc( (void**)&retval_device,B.row_*sizeof(float) );
</code>```

Note that other allocation related have to change too (Lazy me).

And your call in main need to divide the GpuMat step by the size of one element of the GpuMat

```<code>res_m = Matrix_dot_((float* )ctA.ptr(), (float*)ctB.ptr(), ctA.cols, ctA.rows, ctA.step/ctA.elemsize1());
</code>```

You might also want to change your Matrix_t structure to use const float* instead of float to be able to use:

```<code> GpuMat_.ptr<float>();
</code>```

instead of:

```<code>(float*)GpuMat.ptr();
</code>```

Note that for a matrix of N rows you are starting N^2 threads doing the same thing. I don't have enough knowledge on Cuda to fix that.

Title: Matrix dot product

Body:
Disclaimer: Im a cuda beginner.

typedef struct
{
    int row_;
    int col_;
    float* element_;
    int step;
}Matrix_t;

#define BLOCK_SIZE 64

__device__ float getElement(const Matrix_t A, int row, int col);
__device__ Matrix_t getSubMat(Matrix_t A, int row, int col);
__device__ void setElement(Matrix_t A, int row, int col, float value);
__global__ void MatrixDot(Matrix_t A, Matrix_t B, float* dot_);
float  Matrix_dot_(float* M_dev_1, float* M_dev_2, int Number_of_cols, int Number_of_rows, int step);

the Matrix_t are used to link a cv::cuda::GpuMat to the C interface via the ptr() operator to get the GPU pointer to element.

__device__ float getElement(const Matrix_t A, int row, int col)
{
    return A.element_[row* A.step + col];
}

__device__ void setElement(Matrix_t A, int row, int col, float value)
{
    A.element_[row*A.step + col] = value;
}
__device__ Matrix_t getSubMat(Matrix_t A, int row, int col)
{
    Matrix_t A_sub;
    A_sub.row_ = BLOCK_SIZE;
    A_sub.col_ = BLOCK_SIZE;
    A_sub.step = A.step;
    A_sub.element_ = &A.element_[A.step * BLOCK_SIZE * row + BLOCK_SIZE * col];

    return A_sub;
}

Here is the kernel:

__global__ void MatrixDot(Matrix_t A, Matrix_t B, float* dot_)
{
    int blockRow = blockIdx.y;
    int blockCol = blockIdx.x;

    float SubDotValue = 0.0f;

    int row = threadIdx.y;
    int col = threadIdx.x;

    for(int m = 0; m < (A.row_ / BLOCK_SIZE); ++m)
    {
        //get subA & subB
        Matrix_t A_sub = getSubMat(A, blockRow, m);
        Matrix_t B_sub = getSubMat(B, blockRow, m);

        //set Asub & Bsub to the  __shared__ memory

        __shared__ float ASub[BLOCK_SIZE][BLOCK_SIZE];
        __shared__ float BSub[BLOCK_SIZE][BLOCK_SIZE];

        ASub[row][col] = getElement(A_sub, row, col);
        BSub[row][col] = getElement(B_sub, row, col);

        //Synchronize before calculations:
        __syncthreads();

        //Get the dot product of the vector Asub[] Bsub[]
        for(int el_ = 0; el_ < BLOCK_SIZE; ++el_)
        {
            SubDotValue += ASub[row][el_] * BSub[row][el_];
        }
        __syncthreads();
    }

    dot_[row] = SubDotValue;

}

and the wrapper:

float  Matrix_dot_(float* M_dev_1,float* M_dev_2, int Number_of_cols, int Number_of_rows, int step)
{

    float retval = 0;
    float* retval_partial;
    float* retval_device;

    Matrix_t A;
    A.col_ = Number_of_cols;
    A.row_ = Number_of_rows;
    A.element_ = M_dev_1;
    A.step = step;
    Matrix_t B;
    B.col_ = Number_of_cols;
    B.row_ = Number_of_rows;
    B.element_ = M_dev_2;
    B.step = step;

    retval_partial = (float*)malloc( B.row_*sizeof(float) );

    cudaError_t err = cudaMalloc( (void**)&retval_device,B.row_/ BLOCK_SIZE *sizeof(float) );
    printf("\n Cuda malloc: %s", cudaGetErrorString(err));
    std::cout<<std::flush;
    dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE);
    dim3 dimGrid(B.row_ / BLOCK_SIZE, B.col_ / BLOCK_SIZE);

    MatrixDot<<<dimGrid, dimBlock>>>(A, B, retval_device);
    err = cudaThreadSynchronize();
    std::cout<<std::flush;

    printf("\n Cuda kernel run: %s", cudaGetErrorString(err));
    err = cudaMemcpy(retval_partial, retval_device, B.row_ / BLOCK_SIZE* sizeof(float), cudaMemcpyDeviceToHost);
    printf("\n Cuda cudaMemcpy: %s", cudaGetErrorString(err));
    err = cudaFree(retval_device);
    printf("\n Cuda cudaFree: %s", cudaGetErrorString(err));
    for(int i = 0; i<B.row_/ BLOCK_SIZE ; ++i)
    {
        retval+=retval_partial[i];
    }

    free(retval_partial);

    return retval;
}

and the main:

int main(int argc, const char * argv[])
{
    cv::cuda::DeviceInfo devInfo;
    cv::cuda::setDevice(devInfo.deviceID());

    cv::Mat cudatestA = cv::Mat(64*3, 64*3, CV_32FC1, 2);
    cv::Mat cudatestB = cv::Mat(64*3, 64*3, CV_32FC1, 2);

    double tr = (double) cv::getTickCount();
    double res = cudatestA.dot(cudatestB);

    tr = ((double)cv::getTickCount()-tr)/(double)cv::getTickFrequency();

    cv::cuda::GpuMat ctA(cudatestA);
    cv::cuda::GpuMat ctB(cudatestB);

    double tm_ = (double) cv::getTickCount();
    float res_m = 0;

    res_m = Matrix_dot_((float* )ctA.ptr(), (float*)ctB.ptr(), ctA.cols, ctA.rows, ctA.step);
    tm_ = ((double)cv::getTickCount()-tm_)/(double)cv::getTickFrequency();

    printf("\nCPU: %0.4fms, res: %0.4f\nGPU_M: %0.4fms, res: %0.4f\n", tr*1000.0f, res, tm_*1000.0f,res_m);
    return 0;
}

I'm currently stuck on various points:

1) it always output 0.

2) it can only work for matrix M*N Multiple of the defined BLOCK_SIZE (64).

for 1) I can't figure where my logic break, I could get the dot product to work on vector without any troubles but the matrix problem induced by the stride between each row prevent me to use the code (code deleted as the site tell me that there is too much code).

Body:
Partial answer:

In your kernel you aren't doing the good sum, nor taking the good elements, and your dim seems inverted

__global__ void MatrixDot(Matrix_t A, Matrix_t B, float* dot_)
{
//int blockRow = blockIdx.y;
//int blockCol = blockIdx.x;
int blockRow = blockIdx.x;
int blockCol = blockIdx.y;

float SubDotValue = 0.0f;

//int row = threadIdx.y;
//int col = threadIdx.x;
int row = threadIdx.x;
int col = threadIdx.y;

for(int m = 0; m < (A.row_ / BLOCK_SIZE); ++m)
    {
        //get subA & subB
        Matrix_t A_sub = getSubMat(A, m, blockCol);//getSubMat(A, blockRow, m)
        Matrix_t B_sub = getSubMat(B, m, blockCol);//getSubMat(B, blockRow, m)

        //set Asub & Bsub to the  __shared__ memory

        __shared__ float ASub[BLOCK_SIZE][BLOCK_SIZE];
        __shared__ float BSub[BLOCK_SIZE][BLOCK_SIZE];

        ASub[row][col] = getElement(A_sub, row, col);
        BSub[row][col] = getElement(B_sub, row, col);

        //Synchronize before calculations:
        __syncthreads();

        //Get the dot product of the vector Asub[] Bsub[]
        for(int el_ = 0; el_ < BLOCK_SIZE; ++el_)
        {
            SubDotValue += ASub[row][el_] * BSub[row][el_];
        }
        __syncthreads();
    }

dot_[blockRow*BLOCK_SIZE + row] = SubDotValue; //dot_[row] = SubDotValue;

}

And your wrapper isn't also allocating the size you need:

cudaError_t err = cudaMalloc( (void**)&retval_device,B.row_/ BLOCK_SIZE *sizeof(float) );

should be:

cudaError_t err = cudaMalloc( (void**)&retval_device,B.row_*sizeof(float) );

Note that other allocation related have to change too (Lazy me).

And your call in main need to divide the GpuMat step by the size of one element of the GpuMat

res_m = Matrix_dot_((float* )ctA.ptr(), (float*)ctB.ptr(), ctA.cols, ctA.rows, ctA.step/ctA.elemsize1());

You might also want to change your Matrix_t structure to use const float* instead of float to be able to use:

 GpuMat_.ptr<float>();

instead of:

(float*)GpuMat.ptr();

Note that for a matrix of N rows you are starting N^2 threads doing the same thing. I don't have enough knowledge on Cuda to fix that.


问:
what is the good way to render html contents in angular4?
I have a string of html contents. How to render it in html page without using document.write() in angular 4?

my string looks like:

```<code>`<mark>4.95</mark><mark>Nunavut</mark><mark>Office Furnishings</mark><mark>0.37
 7</mark><mark>"Angle-D Binders with Locking Rings</mark><mark> Label Holders"</mark><mark>Carl Jackson</mark><mark>613</mark><mark>-54.04</mark><mark>7.3</mark><mark>7.72</mark><mark>Nunavut</mark><mark>Binders and Binder Accessories</mark><mark>0.38
 8</mark><mark>"SAFCO Mobile Desk Side File</mark><mark> Wire Frame"</mark><mark>Carl Jackson</mark><mark>613</mark><mark>127.70</mark><mark>42.76</mark><mark>6.22</mark>Nunavut<mark>Storage & Organization</mark><mark>
 9</mark><mark>"SAFCO Commercial Wire Shelving</mark><mark> Black"</mark><mark>Monica Federle</mark><mark>643</mark><mark>-695.26</mark><mark>138.14</mark><mark>35</mark><mark>Nunavut</mark><mark>Storage & Organization</mark><mark>
 10</mark><mark>Xerox 198</mark><mark>Dorothy Badders</mark><mark>678</mark><mark>-226.36</mark><mark>4.98</mark><mark>8.33</mark>
`
</code>```

答:
In your component, say, MyComponent.ts, define your string as an attribute/property:

```<code>public myString = "<mark>...</mark>";
</code>```

Then, in your template, MyComponent.html, set the innerHtml of a div to this string:

```<code><div [innerHtml]="myString"></div>
</code>```

Body:
I have a string of html contents. How to render it in html page without using document.write() in angular 4?

my string looks like:

`4.95NunavutOffice Furnishings0.37
 7"Angle-D Binders with Locking Rings Label Holders"Carl Jackson613-54.047.37.72NunavutBinders and Binder Accessories0.38
 8"SAFCO Mobile Desk Side File Wire Frame"Carl Jackson613127.7042.766.22NunavutStorage & Organization
 9"SAFCO Commercial Wire Shelving Black"Monica Federle643-695.26138.1435NunavutStorage & Organization
 10Xerox 198Dorothy Badders678-226.364.988.33
`

Body:
In your component, say, MyComponent.ts, define your string as an attribute/property:

public myString = "<mark>...</mark>";

Then, in your template, MyComponent.html, set the innerHtml of a div to this string:

<div [innerHtml]="myString"></div>


问:
How to create an initial git repository from multiple versions of the 'same' codebase?
My problem is the following:

I have several directories, kind of 'branches' of the same project with no common root. (Not in the sense of it being ultimately absent, but in the sense that it is lost.)

I need to merge them together to create a single master branch. I know that some versions are derived from other versions, but unfortunately that doesn't mean that they are more advanced than their parents, since many developers just deleted source files they didn't need from their working copies.

How do I properly merge them?

Of course, I could create an empty repository, then add all directories as branches and try to merge them one by one. But is there any better option?

答:
Considering:

the merge would not be a 3-way merge anyway (due to the lack of a proper common ancestor between two branches)

the merge wouldn't even be an automatic one (since developer have deleted sources they don't need, you don't want to do a simple merge, which could in turn delete those same source in the target branch)

the safest course of action is to use a third-party merge tool (WinMerge, kdiff3, BeyondCompare, ...), and carefully merge those folders into one target git repo folder. Pay attention in particular to files absent in the source and present in the target: you probably want to ignore those deletion and keep your target files.


问:
How to print a larger version of the fabricjs canvas?
I'm using the following code to print my canvas and was wondering if it is possible to do something like toDataURL({multiplier: 4})? I plugged it in but can't actually see a different anywhere. Not sure if it's worth having this in or if there's a way to do this.

Thanks in advance!

```<code>function printCanvas() {
var dataUrl = document.getElementById('c').toDataURL(/* data multiplier here? */); //attempt to save base64 string to server using this var
  var windowContent = '<!DOCTYPE html>';
  windowContent += '<html>'
  windowContent += '<head><title>Print canvas</title></head>';
  windowContent += '<body>'
  windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
  windowContent += '</body>';
  windowContent += '</html>';
  var printWin = window.open('', '', 'width=340,height=260');
  printWin.document.open();
  printWin.document.write(windowContent);
}
</code>```

答:
You can try creating a new canvas which is scaled as per your need and draw the original canvas contents there and then use the new canvas's toDataURL() to create the image.

```<code>        var canvas = document.getElementById("c");
        var tempCanvas;
        var tempCanvasCtx;

        function printCanvas() {
            var tempCanvas = document.createElement('canvas');
            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;
            tempCanvasCtx = tempCanvas.getContext("2d");
            tempCanvasCtx.scale(1.5, 1.5);
            tempCanvasCtx.drawImage(canvas, 0, 0);
            var dataUrl = tempCanvas.toDataURL(); //attempt to save base64 string to server using this var
            var windowContent = '<!DOCTYPE html>';
            windowContent += '<html>'
            windowContent += '<head><title>Print canvas</title></head>';
            windowContent += '<body>'
            windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
            windowContent += '</body>';
            windowContent += '</html>';
            var printWin = window.open('', '', 'width=340,height=260');
            printWin.document.open();
            printWin.document.write(windowContent);
        }
</code>```

Body:
I'm using the following code to print my canvas and was wondering if it is possible to do something like toDataURL({multiplier: 4})? I plugged it in but can't actually see a different anywhere. Not sure if it's worth having this in or if there's a way to do this.

Thanks in advance!

function printCanvas() {
var dataUrl = document.getElementById('c').toDataURL(/* data multiplier here? */); //attempt to save base64 string to server using this var
  var windowContent = '<!DOCTYPE html>';
  windowContent += ''
  windowContent += '<title>Print canvas</title>';
  windowContent += ''
  windowContent += '';
  windowContent += '';
  windowContent += '';
  var printWin = window.open('', '', 'width=340,height=260');
  printWin.document.open();
  printWin.document.write(windowContent);
}

Body:
You can try creating a new canvas which is scaled as per your need and draw the original canvas contents there and then use the new canvas's toDataURL() to create the image.

        var canvas = document.getElementById("c");
        var tempCanvas;
        var tempCanvasCtx;

        function printCanvas() {
            var tempCanvas = document.createElement('canvas');
            tempCanvas.width = canvas.width;
            tempCanvas.height = canvas.height;
            tempCanvasCtx = tempCanvas.getContext("2d");
            tempCanvasCtx.scale(1.5, 1.5);
            tempCanvasCtx.drawImage(canvas, 0, 0);
            var dataUrl = tempCanvas.toDataURL(); //attempt to save base64 string to server using this var
            var windowContent = '<!DOCTYPE html>';
            windowContent += '<html>'
            windowContent += '<head><title>Print canvas</title></head>';
            windowContent += '<body>'
            windowContent += '<img src="' + dataUrl + '" onload=window.print();window.close();>';
            windowContent += '</body>';
            windowContent += '</html>';
            var printWin = window.open('', '', 'width=340,height=260');
            printWin.document.open();
            printWin.document.write(windowContent);
        }


问:
Vagrant is not forwarding when I run django runserver on ssh
I created a Vagrant Ubuntu (lucid32) box with Python & Django. My idea is start the VM, log into it with vagrant ssh, and then start Django by running:

```<code>manage.py runserver
</code>```

which defaults to port 8000. The problem is that I can not access the Django server from the host's browser at http://127.0.0.1:8000. What can I do?

答:
First, you need to do port forwarding in Vagrant file.

```<code>config.vm.network "forwarded_port", guest: 8000, host: 8000
</code>```

Then you need to restart/reload your vangrant vm

```<code>vagrant reload
</code>```

Now ssh to your vm and run django server as follows

```<code>python manage.py runserver 0.0.0.0:8000
</code>```

Body:
I created a Vagrant Ubuntu (lucid32) box with Python & Django. My idea is start the VM, log into it with vagrant ssh, and then start Django by running:

manage.py runserver

which defaults to port 8000. The problem is that I can not access the Django server from the host's browser at http://127.0.0.1:8000. What can I do?

Body:
First, you need to do port forwarding in Vagrant file.

config.vm.network "forwarded_port", guest: 8000, host: 8000

Then you need to restart/reload your vangrant vm

vagrant reload

Now ssh to your vm and run django server as follows

python manage.py runserver 0.0.0.0:8000


问:
Unable to launch the IIS Express Web server on specific project in vs 2015

I have created new project and run, it was build successfully after that through an error.

答: I had same issue occured and i fixed this issue by just remove the "applicationhost.config" file from your Project directory -> .vs folder -> config folder -> remove the applicationhost.config and clean & build project and run your project. It will successfully run your project


问:
when we need trim when we don't need in oracle
In Oracle I see, some time 'A  ' = 'A', but some time 'A  ' != 'A', Please see example below you will see detail. I has been try to short the code.

```<code>CREATE TABLE AAA (
    T1 CHAR(3),
    T2 VARCHAR(3),
    T3 VARCHAR(5)
);
insert into AAA
SELECT 'A','A  ', 'A    ' FROM DUAL;
COMMIT;
SELECT * FROM AAA WHERE T1 = 'A'
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A  '
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A    '
UNION ALL
SELECT  * FROM AAA WHERE TRIM(T2) = TRIM('A   ')
UNION ALL
SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;
</code>```

I ask this question because in my db, When I join table A to table B some time we TRIM(A.ID) = TRIM(B.REFID) some time we don't need to do this. When we need TRIM(column)? When 'A  ' = 'A' ? and when 'A  ' != 'A'?

答:
I think the behavior your are seeing when querying your actual table is expected, and the only behavior which might surprise you is in the following query:

```<code>SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;
</code>```

From this Oracle discussion, it appears that what is happening has to do with that 'A', 'A ', etc. are char types and not varchar2 types.  As a result, in order to compare two char values they need to be the same length.  Consider the following CASE expression:

```<code>CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2
</code>```

Here the 'A' literal, which is a char(1), will be promoted to char(8) by padding on the right with spaces.  So when the comparsion actually takes place, both the LHS and RHS are actually the same.  Note that the following CASE expression would not evaluate to the true condition:

```<code>CASE WHEN '  A' = 'A' THEN '1' ELSE '0' END T2
</code>```

This is because the padding would happen to 'A' on the right, so '  A' would be compared against 'A  ', which are not the same.

Follow the link below for a demo which shows that if you use all varchar columns that the original spaces/widths of the inputs are preserved, and the logical comparison of strings is what you would expect.

Demo

Body:
In Oracle I see, some time 'A  ' = 'A', but some time 'A  ' != 'A', Please see example below you will see detail. I has been try to short the code.

CREATE TABLE AAA (
    T1 CHAR(3),
    T2 VARCHAR(3),
    T3 VARCHAR(5)
);
insert into AAA
SELECT 'A','A  ', 'A    ' FROM DUAL;
COMMIT;
SELECT * FROM AAA WHERE T1 = 'A'
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A  '
UNION ALL
SELECT  * FROM AAA WHERE T2 = 'A    '
UNION ALL
SELECT  * FROM AAA WHERE TRIM(T2) = TRIM('A   ')
UNION ALL
SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;

I ask this question because in my db, When I join table A to table B some time we TRIM(A.ID) = TRIM(B.REFID) some time we don't need to do this. When we need TRIM(column)? When 'A  ' = 'A' ? and when 'A  ' != 'A'?

Body:
I think the behavior your are seeing when querying your actual table is expected, and the only behavior which might surprise you is in the following query:

SELECT CASE WHEN 'A' = 'A ' THEN '1' ELSE '0' END T1,
       CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2,
       CASE WHEN 'A ' = 'A ' THEN '1' ELSE '0' END T2
FROM DUAL;

From this Oracle discussion, it appears that what is happening has to do with that 'A', 'A ', etc. are char types and not varchar2 types.  As a result, in order to compare two char values they need to be the same length.  Consider the following CASE expression:

CASE WHEN 'A       ' = 'A' THEN '1' ELSE '0' END T2

Here the 'A' literal, which is a char(1), will be promoted to char(8) by padding on the right with spaces.  So when the comparsion actually takes place, both the LHS and RHS are actually the same.  Note that the following CASE expression would not evaluate to the true condition:

CASE WHEN '  A' = 'A' THEN '1' ELSE '0' END T2

This is because the padding would happen to 'A' on the right, so '  A' would be compared against 'A  ', which are not the same.

Follow the link below for a demo which shows that if you use all varchar columns that the original spaces/widths of the inputs are preserved, and the logical comparison of strings is what you would expect.

Demo


答:
```<code>SELECT a.*, b.*
FROM table1 a
INNER JOIN table2 b
ON (a.name = b.name AND (a.d1>0 AND a.d2>0 AND a.d3>0 AND a.d4>0 AND a.d5>0) AND (b.c1>0 AND b.c2>0 AND b.c3>0 AND b.c4>0 AND b.c5>0))
</code>```

Jusr try this, it will work, but it can be made better as well. I hope this helps.

Title: Select column and values where values are greater than 0 in mysql

Body:
SELECT a.*, b.*
FROM table1 a
INNER JOIN table2 b
ON (a.name = b.name AND (a.d1>0 AND a.d2>0 AND a.d3>0 AND a.d4>0 AND a.d5>0) AND (b.c1>0 AND b.c2>0 AND b.c3>0 AND b.c4>0 AND b.c5>0))

Jusr try this, it will work, but it can be made better as well. I hope this helps.


问:
How do I check the size of different variables in a function?
For a class I have to this simple problem in which I need to check the size of multiple types of variables while using pointers and display it all.
I want my code to look as clean as posible. So I wanted to know if there is something that does it cleaner. I have this code as of now.

```<code>void size (float *p1, int *p2, int*p3, int *p4, double *p5,bool *pc){
    for(int i=1; i <=5; i++){
        cout << "Size of pointer " << i << " is:" << sizeof(p::i)<< endl;
    }

    cout << "Size of control pointer is:" << sizeof(pc)<< endl;
}
</code>```

Is there a way to do it somehow like this, or do I have to explicitely write line by line?

答:
You can use template parameter packs to do this, but it's not clear this is the best choice for whatever problem you're facing.

```<code>#include <iostream>

template<typename T>
void print_size(const T* t) {
  std::cout << sizeof(*t)  << '\n';
}

template<typename T, typename... Args>
void print_size(const T* t, Args... args) {
  std::cout << sizeof(*t)  << '\n';
  print_size(args...);
}

struct MyStruct {
  const char my_char[10];
};

int main() {
  int* int_ptr;
  double* double_ptr;
  MyStruct* my_struct;
  print_size(int_ptr, double_ptr, my_struct);
}
</code>```

Results in the output (on my machine):

```<code>4
8
10
</code>```

Body:
For a class I have to this simple problem in which I need to check the size of multiple types of variables while using pointers and display it all.
I want my code to look as clean as posible. So I wanted to know if there is something that does it cleaner. I have this code as of now.

void size (float *p1, int *p2, int*p3, int *p4, double *p5,bool *pc){
    for(int i=1; i <=5; i++){
        cout << "Size of pointer " << i << " is:" << sizeof(p::i)<< endl;
    }

    cout << "Size of control pointer is:" << sizeof(pc)<< endl;
}

Is there a way to do it somehow like this, or do I have to explicitely write line by line?

Body:
You can use template parameter packs to do this, but it's not clear this is the best choice for whatever problem you're facing.

#include <iostream>

template<typename T>
void print_size(const T* t) {
  std::cout << sizeof(*t)  << '\n';
}

template<typename T, typename... Args>
void print_size(const T* t, Args... args) {
  std::cout << sizeof(*t)  << '\n';
  print_size(args...);
}

struct MyStruct {
  const char my_char[10];
};

int main() {
  int* int_ptr;
  double* double_ptr;
  MyStruct* my_struct;
  print_size(int_ptr, double_ptr, my_struct);
}

Results in the output (on my machine):

4
8
10


问:
Fatal error: SFML/Graphics.hpp: no such file or directory exists
I'm running into problem after problem with SFML, but hopefully it will be worth it in the end.

Here's the error:

fatal error:  SFML/Graphics.hpp : No such file or directory

and the code:

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

int main(){
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "SFML");

while(Window.isOpen()){
    sf::Event Event;
    while(Window.pollEvent(Event)){
        if(Event.type == sf::Event::Closed)
            Window.close();
    }
}
}
</code>```

答:
I'm pretty new to this, but if you followed the tutorial, then you probably set the path for the .hpp files as just /include, but the .hpp files are really in /include/SFML

#include <include/SFML/Graphics.hpp>

Body:
I'm running into problem after problem with SFML, but hopefully it will be worth it in the end.

Here's the error:

fatal error:  SFML/Graphics.hpp : No such file or directory

and the code:

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

int main(){
sf::RenderWindow Window;
Window.create(sf::VideoMode(800, 600), "SFML");

while(Window.isOpen()){
    sf::Event Event;
    while(Window.pollEvent(Event)){
        if(Event.type == sf::Event::Closed)
            Window.close();
    }
}
}


问:
Printing IP address of Nic card to bash using script
currently I am working on a school assignment on Linux using Vim where I have to write a script that displays the user that is currently logged in, the time and date, and list only the IP address of the Nic card. I have everything working except for the IP address part. If anyone could help I would appreciate it greatly.

Edit to include the code I have at the moment.

```<code>#!/bin/bash
Time=$(date)
IP=$(ifconfig ens33)
echo "The following user is currently logged in $USER"
echo ""
echo "The current time is $Time"
echo ""
echo "The IP information is $IP"
</code>```

答:
this line </p>

```<code>IP=$(ifconfig ens33| grep inet | sed 's/ */ /'  | cut -d" " -f3)
</code>```

Body:
currently I am working on a school assignment on Linux using Vim where I have to write a script that displays the user that is currently logged in, the time and date, and list only the IP address of the Nic card. I have everything working except for the IP address part. If anyone could help I would appreciate it greatly.

Edit to include the code I have at the moment.

#!/bin/bash
Time=$(date)
IP=$(ifconfig ens33)
echo "The following user is currently logged in $USER"
echo ""
echo "The current time is $Time"
echo ""
echo "The IP information is $IP"

Body:
this line

IP=$(ifconfig ens33| grep inet | sed 's/ */ /'  | cut -d" " -f3)


问:
How to detect objects on the canvas with click event
Hi I am using a hashmap that allows me to efficiently detect objects in the given coordinates. However it is working perfectly , the problem lies with using the mouse to gather the position of the mouse within the canvas down to the pixel. I have been using the offsetX and offsetY methods for the event to gather some offset but it seems there is an offset I am unaware of and may have something to do with either:

1.using scaling on the canvas , Note: ive tried to fix this by division of the renderscale, this works with everything else so should be fine here.

mouseoffset is not accounting for parts of the page or is missing pixels at a low level (maybe 20) but divided by the render scale thats massive.

3.I am using a cartesian coordinate system to simplify things for the future , so the game map is in cartesian and may have to do with the problem.

I will not be supplying all the code because it is allot of work to go through it all so i will supply the following :

the html/css canvas code

```<code><html lang="en">
<head>
    <meta charset="UTF-8">
    <title> Game</title>
</head>
<body onload="jsEngine = new JsEngine(24, 24, .1); " >

<div class ="wrapper">
    <canvas  id="canvas" width="1920" height="1080"></canvas>
</div>

<style>

    .wrapper {
    position: relative;
    width: auto;
    height: 900px;
    }

    .wrapper   canvas {
       position: absolute;
       left: 90px;
       top: 50px;
       padding-left: 0;
       padding-right: 0;
       margin-left: auto;
       margin-right: auto;
       display: block;
       width: 90%;
       height: 90%;}

   .GUI{
       top: -315px;
       left: -302px;
       position: absolute;
       width: 300px;
       height: 300px;
       background-color: cadetblue;

       opacity: .5;
       word-wrap: break-word;}

    img{
         image-rendering: optimize-contrast;
}
</style>

<div id = GUI class = "GUI"></div>

    <!-- Libraries -->
<script src="../myapi/JSONE.js"></script>
<script src="../myapi/engine/SpacialHash.js"></script>

</body>
</html>
</code>```

2.the javascript click function

```<code>  //Click on objects
let onClick = function(event){
    let canvas_ctx = document.getElementById("canvas").getContext("2d");
let canvasOffsetX = canvas_ctx.canvas.width/2;
let canvasOffsetY = canvas_ctx.canvas.height/2;
let mousePosX = event.clientX;
let mousePosY = event.clientY;

    let mouseX =jsEngine.cameraFocus.x-canvasOffsetX/jsEngine.renderScale+(mousePosX)/jsEngine.renderScale;
    let mouseY = jsEngine.cameraFocus.y+(canvasOffsetY)/jsEngine.renderScale+((-mousePosY)/jsEngine.renderScale);
    console.log("sum to",mouseX,mouseY);

//My hashMap to place the mouse coordinates on the game map
    let clickPosition = hm.find({x:mouseX,y:mouseY,width:1,height:1});

    if(clickPosition.length===1){
        let gameObject = jsEngine.gameObjects[clickPosition[0].range.id];
        //console.log(gameObject.transform.x,gameObject.transform.y,mouseX,mouseY);
        let clickBox = {};
        let picture = gameObject.texture;
        guiCreateClickBox(clickBox,gameObject.id,1200,500,picture);

    }else if(clickPosition.length>1) {
        for (let i = 0; i < clickPosition.length; i++) {
            let gameObject = jsEngine.gameObjects[clickPosition[i].range.id];
            if (gameObject instanceof PlayerShip|| gameObject instanceof Bullet)
                continue;
            let clickBox = {};
            let picture = gameObject.texture;
            guiCreateClickBox(clickBox,gameObject.id,1200,500,picture);

            //console.log(gameObject.transform.x,gameObject.transform.y,mouseX,mouseY)

        }
    }
};

// Listeners
//Click on objects
document.getElementById("canvas").addEventListener("click", onClick);
</code>```

the making of the map and scale :Note: this is done via onPreRender

```<code>function drawBackground(canvas_ctx, renderScale, imageResource) {
let img = imageResource.mapBackground;
let mapWidth = 1000000;
let mapHeight= 1000000;
let zoom = 1;

mapWidth *= renderScale / zoom;
mapHeight *= renderScale / zoom;

// Render the Background
canvas_ctx.fillStyle = canvas_ctx.createPattern(img, 'repeat');
canvas_ctx.scale(zoom, zoom);
canvas_ctx.fillRect(-mapWidth / 2, - mapHeight / 2, mapWidth, mapHeight);

//if (jsEngine.cameraFocus.x > 1000000) {}

canvas_ctx.scale(1/zoom, 1/zoom);
}
</code>```

The rendering method used for playership

```<code>renderGameObject(gameObject) {
let x = gameObject.transform.x * this.renderScale;
let y = -(gameObject.transform.y * this.renderScale);
let rotation = Math.radians(gameObject.transform.rotation);
let width = gameObject.transform.width;
width *= this.renderScale;
let height = gameObject.texture.height;
height *= this.renderScale;

// Render the gameObject
this.canvas_ctx.translate(x, y);
this.canvas_ctx.rotate(rotation);
this.canvas_ctx.drawImage(gameObject.texture, 0, 0, width / this.renderScale, height / this.renderScale,  // Make sure the image is not cropped
    -width/2 ,         // X
    -height/2 ,        // Y
    width, height);     // width and height
this.canvas_ctx.rotate(-rotation);
this.canvas_ctx.translate(-x, -y);

}
</code>```

the issue to solve is to make it so that when you click on any given quadrant of the canvas it will return -+ for top left, -- bottom left , -+ topright, +- bottomright, as well as being applied to the render scale which at the moment is .1 so just divide your mouse and canvas coords like shown above and you should be able to get the same results.

Things to keep in mind :

the jsEngine.cameraFocus is set to the playerships x and y coordinates(which are set to the 0,0 posiiton on the map) (which are also in the middle of the ship)

the top left of the canvas is still 0,0 and ++ is still toward the bottom right so theoretically minusing half the canvas width/height then adding the offsets X and Y. this should be working but at my map coordinate -4000,-4000 i get ~-3620,-3295 and at +4000,+4000 I get 3500,3500. (The reason why the canvas 0,0 is not where the ship is , is to make the ship in the middle of the screen)

If you have questions about anything based on code that needs to be supplied please ask via comment . Please note if you have problems with the format of the code supplied I have nothing to say about it . all I need is the click function working on the canvas model i set up in cartesian format.

ps: jQuery is not a solution its a problem please use vanilla js.

答: I found out why it was off , my canvas has a offset of 90 px and 50 px as well as the main problem that the canvas is only 90% of its origonal size (also in css). If anyone can give me help for how to adjust to these issues please reply in comment . until then I beleieve I have solved my own issue .</p>

Body:
Hi I am using a hashmap that allows me to efficiently detect objects in the given coordinates. However it is working perfectly , the problem lies with using the mouse to gather the position of the mouse within the canvas down to the pixel. I have been using the offsetX and offsetY methods for the event to gather some offset but it seems there is an offset I am unaware of and may have something to do with either:

1.using scaling on the canvas , Note: ive tried to fix this by division of the renderscale, this works with everything else so should be fine here.

mouseoffset is not accounting for parts of the page or is missing pixels at a low level (maybe 20) but divided by the render scale thats massive.

3.I am using a cartesian coordinate system to simplify things for the future , so the game map is in cartesian and may have to do with the problem.

I will not be supplying all the code because it is allot of work to go through it all so i will supply the following :

the html/css canvas code

    <meta charset="UTF-8">
    <title> Game</title>

    <canvas  id="canvas" width="1920" height="1080"></canvas>

2.the javascript click function

  //Click on objects
let onClick = function(event){
    let canvas_ctx = document.getElementById("canvas").getContext("2d");
let canvasOffsetX = canvas_ctx.canvas.width/2;
let canvasOffsetY = canvas_ctx.canvas.height/2;
let mousePosX = event.clientX;
let mousePosY = event.clientY;

    let mouseX =jsEngine.cameraFocus.x-canvasOffsetX/jsEngine.renderScale+(mousePosX)/jsEngine.renderScale;
    let mouseY = jsEngine.cameraFocus.y+(canvasOffsetY)/jsEngine.renderScale+((-mousePosY)/jsEngine.renderScale);
    console.log("sum to",mouseX,mouseY);

//My hashMap to place the mouse coordinates on the game map
    let clickPosition = hm.find({x:mouseX,y:mouseY,width:1,height:1});

    if(clickPosition.length===1){
        let gameObject = jsEngine.gameObjects[clickPosition[0].range.id];
        //console.log(gameObject.transform.x,gameObject.transform.y,mouseX,mouseY);
        let clickBox = {};
        let picture = gameObject.texture;
        guiCreateClickBox(clickBox,gameObject.id,1200,500,picture);

    }else if(clickPosition.length>1) {
        for (let i = 0; i < clickPosition.length; i++) {
            let gameObject = jsEngine.gameObjects[clickPosition[i].range.id];
            if (gameObject instanceof PlayerShip|| gameObject instanceof Bullet)
                continue;
            let clickBox = {};
            let picture = gameObject.texture;
            guiCreateClickBox(clickBox,gameObject.id,1200,500,picture);

            //console.log(gameObject.transform.x,gameObject.transform.y,mouseX,mouseY)

        }
    }
};

// Listeners
//Click on objects
document.getElementById("canvas").addEventListener("click", onClick);

the making of the map and scale :Note: this is done via onPreRender

function drawBackground(canvas_ctx, renderScale, imageResource) {
let img = imageResource.mapBackground;
let mapWidth = 1000000;
let mapHeight= 1000000;
let zoom = 1;

mapWidth *= renderScale / zoom;
mapHeight *= renderScale / zoom;

// Render the Background
canvas_ctx.fillStyle = canvas_ctx.createPattern(img, 'repeat');
canvas_ctx.scale(zoom, zoom);
canvas_ctx.fillRect(-mapWidth / 2, - mapHeight / 2, mapWidth, mapHeight);

//if (jsEngine.cameraFocus.x > 1000000) {}

canvas_ctx.scale(1/zoom, 1/zoom);
}

The rendering method used for playership

renderGameObject(gameObject) {
let x = gameObject.transform.x * this.renderScale;
let y = -(gameObject.transform.y * this.renderScale);
let rotation = Math.radians(gameObject.transform.rotation);
let width = gameObject.transform.width;
width *= this.renderScale;
let height = gameObject.texture.height;
height *= this.renderScale;

// Render the gameObject
this.canvas_ctx.translate(x, y);
this.canvas_ctx.rotate(rotation);
this.canvas_ctx.drawImage(gameObject.texture, 0, 0, width / this.renderScale, height / this.renderScale,  // Make sure the image is not cropped
    -width/2 ,         // X
    -height/2 ,        // Y
    width, height);     // width and height
this.canvas_ctx.rotate(-rotation);
this.canvas_ctx.translate(-x, -y);

}

the issue to solve is to make it so that when you click on any given quadrant of the canvas it will return -+ for top left, -- bottom left , -+ topright, +- bottomright, as well as being applied to the render scale which at the moment is .1 so just divide your mouse and canvas coords like shown above and you should be able to get the same results.

Things to keep in mind :

the jsEngine.cameraFocus is set to the playerships x and y coordinates(which are set to the 0,0 posiiton on the map) (which are also in the middle of the ship)

the top left of the canvas is still 0,0 and ++ is still toward the bottom right so theoretically minusing half the canvas width/height then adding the offsets X and Y. this should be working but at my map coordinate -4000,-4000 i get ~-3620,-3295 and at +4000,+4000 I get 3500,3500. (The reason why the canvas 0,0 is not where the ship is , is to make the ship in the middle of the screen)

If you have questions about anything based on code that needs to be supplied please ask via comment . Please note if you have problems with the format of the code supplied I have nothing to say about it . all I need is the click function working on the canvas model i set up in cartesian format.

ps: jQuery is not a solution its a problem please use vanilla js.


问:
UITableViewCell : UIImageView in ContentView overlaps images in iPhone SDK.
In my iPhone app,  I am using a tableView and have added the imageView as ContentView in my tableViewcell.

At the click of button I am changing the tableView Contents. So every time I click a button it should show the corresponding image in tableViewCell.

Problem:

Suppose I am loading images 1.png, 2.png and 3.png in tableView on click of button A, B and C respectively.

Now let us consider that initially I clicked button A and 1.png appears. Now when I click the button B then 2.png appears but 1.png also remains in background. So basically it overlaps the tableViewCell with a new image.

Troubleshooting I already have done:

1) I tried releasing imageView and setting imageView.image = nil;

2) I tried reloading the table and empty out table before each button click.

3) Even I tried putting the whole code in if(cell==nil) clause of cellForRowAtIndexPath method

答:
Have you tried clearing the cell's contentView? </p>

```<code>for(UIView* subview in [cell.contentView subviews]) {
   [subview removeFromSuperview];
}
</code>```

Body:
Have you tried clearing the cell's contentView?

for(UIView* subview in [cell.contentView subviews]) {
   [subview removeFromSuperview];
}

ContentLicense: CC BY-SA 2.5


问:
iOS 11. UIScrollView in IPhone X shifts when trying to change the orientation of the interface
I have two UIViewController. The first controller is used only in portrait orientation, and it contains the UIScrollView. The second controller is used only in the landscape orientation. When I try to open the second screen from the first one, the UIScrollView content is shifted to -44 by X on the first controller. This behavior exists only for the iPhone X. Does anyone know why this happens?

答:
The problem is solved if I put: </p>

```<code>scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
</code>```

Body:
The problem is solved if I put:

scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;


问:
How to find xpath without firepath into firefox version 57.0
Facing difficulty to find xpath without firepath in new Firefox version 57.0.

In the new Firefox version, firepath is not supported.

Can anyone please suggest a new way for using xpath?

答:
It's not Firefox, but I like to use Google Chrome for this. Press F12, this opens the developer tools. Then click anywhere in the HTML structure and press Ctrl + F or Cmd + F if you're on a Mac.

In the search bar that appears you can search by XPath, Css selectors or strings. So if you type //div/div/form for example, you can immediately check if the XPath works.

You can also right click on an element and choose copy > xpath


问:
WPF Listview overflow
How to stop my listview control from overflowing?

When items get added:

The listview should stop at the red mark.

Desired result:

MainWindow.xaml is a hamburger menu with a menu at left and the views.accounts.xaml at right side.

Views.Accounts.xaml:

```<code>    <UserControl>

<Grid Background="White">
    <!--Define 2 Rows-->
    <Grid.RowDefinitions>
        <RowDefinition Height="48"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

<!--Header-->
<Border Grid.Row="0" Background="#FF444444"...>
<Grid Grid.Row="1" Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>

<!--Options-->
<StackPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"...>

<!--Content area-->
<Grid Grid.Row="1" Grid.Column="0" Margin="0 20 0 0">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <ScrollViewer Grid.Row="0">
            <ListView Style="{StaticResource VirtualisedMetroListView}"
                      MinHeight="250" Name="accountsListView">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Username" DisplayMemberBinding="{Binding username}"/>
                        <GridViewColumn Header="Password" DisplayMemberBinding="{Binding password}"/>
                        <GridViewColumn Header="Email" DisplayMemberBinding="{Binding email}"/>
                        <GridViewColumn Header="Verified" DisplayMemberBinding="{Binding verified}"/>
                    </GridView>
                </ListView.View>
            </ListView>
                </ScrollViewer>
                <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
                <Button Content="Clear" Width="74" Click="clear_Click"/>
                <Button Margin="10 0 0 0" Content="Export" Width="74"/>
            </StackPanel>
            </Grid>
        </Grid>

<!--Settings-->
<Grid Grid.Row="1" Grid.Column="1" Margin="10 10 0 10">

</Grid>
</Grid>
</UserControl>
</code>```

答:
Usually for this kind of a problem there's few reason:

ListView is inside StackPanel

ListView is inside Auto-height Grid Row.

ListView is inside ScrollViewer.

The easiest way to solve this is to remove the StackPanel and the ScrollViewer controls. ListView includes the ScrollViewer built-in, so you don't have to define it manually.

Also make sure that the Grid's RowDefinition is not set to Height="Auto".

So for example:

```<code><!--Content area-->
<Grid Grid.Row="1" Grid.Column="0" Margin="0 20 0 0">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListView Style="{StaticResource VirtualisedMetroListView}" MinHeight="250" Name="accountsListView">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Username" DisplayMemberBinding="{Binding username}"/>
                <GridViewColumn Header="Password" DisplayMemberBinding="{Binding password}"/>
                <GridViewColumn Header="Email" DisplayMemberBinding="{Binding email}"/>
                <GridViewColumn Header="Verified" DisplayMemberBinding="{Binding verified}"/>
            </GridView>
        </ListView.View>
    </ListView>
    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
        <Button Content="Clear" Width="74" Click="clear_Click"/>
        <Button Margin="10 0 0 0" Content="Export" Width="74"/>
    </StackPanel>
</Grid>
</code>```

Also make sure that VirtualisedMetroListView -style doesn't contain anything that could affect the ScrollViewer.

Title: WPF Listview overflow

Body:
How to stop my listview control from overflowing?

When items get added:

The listview should stop at the red mark.

Desired result:

MainWindow.xaml is a hamburger menu with a menu at left and the views.accounts.xaml at right side.

Views.Accounts.xaml:

    <UserControl>

<Grid Background="White">

    <Grid.RowDefinitions>
        <RowDefinition Height="48"/>
        <RowDefinition/>
    </Grid.RowDefinitions>

<Border Grid.Row="0" Background="#FF444444"...>
<Grid Grid.Row="1" Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="250"/>
        </Grid.ColumnDefinitions>

<StackPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"...>

<Grid Grid.Row="1" Grid.Column="0" Margin="0 20 0 0">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>
                <ScrollViewer Grid.Row="0">
            <ListView Style="{StaticResource VirtualisedMetroListView}"
                      MinHeight="250" Name="accountsListView">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Username" DisplayMemberBinding="{Binding username}"/>
                        <GridViewColumn Header="Password" DisplayMemberBinding="{Binding password}"/>
                        <GridViewColumn Header="Email" DisplayMemberBinding="{Binding email}"/>
                        <GridViewColumn Header="Verified" DisplayMemberBinding="{Binding verified}"/>
                    </GridView>
                </ListView.View>
            </ListView>
                </ScrollViewer>
                <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
                <Button Content="Clear" Width="74" Click="clear_Click"/>
                <Button Margin="10 0 0 0" Content="Export" Width="74"/>
            </StackPanel>
            </Grid>
        </Grid>

<Grid Grid.Row="1" Grid.Column="1" Margin="10 10 0 10">

</Grid>
</Grid>
</UserControl>

Body:
Usually for this kind of a problem there's few reason:

ListView is inside StackPanel

ListView is inside Auto-height Grid Row.

ListView is inside ScrollViewer.

The easiest way to solve this is to remove the StackPanel and the ScrollViewer controls. ListView includes the ScrollViewer built-in, so you don't have to define it manually.

Also make sure that the Grid's RowDefinition is not set to Height="Auto".

So for example:

<!--Content area-->
<Grid Grid.Row="1" Grid.Column="0" Margin="0 20 0 0">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <ListView Style="{StaticResource VirtualisedMetroListView}" MinHeight="250" Name="accountsListView">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Username" DisplayMemberBinding="{Binding username}"/>
                <GridViewColumn Header="Password" DisplayMemberBinding="{Binding password}"/>
                <GridViewColumn Header="Email" DisplayMemberBinding="{Binding email}"/>
                <GridViewColumn Header="Verified" DisplayMemberBinding="{Binding verified}"/>
            </GridView>
        </ListView.View>
    </ListView>
    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
        <Button Content="Clear" Width="74" Click="clear_Click"/>
        <Button Margin="10 0 0 0" Content="Export" Width="74"/>
    </StackPanel>
</Grid>

Also make sure that VirtualisedMetroListView -style doesn't contain anything that could affect the ScrollViewer.


问:
Angular2 - Component based architecture
Custom property is used for data binding across components.

```<code>          <section id="main">
              <app-home [dict]="dict">Hello there!</app-home>
          </section>
</code>```

here, dict is a custom property, where app-home is selector of one component used in other component.

The idea of components in Angular2 is to be highly cohesive and loosely coupled.

Why angular2 allow data binding across components?

答:
In your code
 is parent component and <app-home> is child component.

Now in Angular 2 there is no such thing like $rootScope, but sharing data between components is important.

Now there are options available for data sharing between components.
Eg. Shared Services, and Parent-Child relation.

In Parent Child component data sharing we use @Input and @Output.

The example you shared is parent to child data sharing.

[propertyName]="sharedValue" this is the main approach used for Parent to Child component data sharing.

Title: Angular2 - Component based architecture

Body:
Custom property is used for data binding across components.

              <app-home [dict]="dict">Hello there!</app-home>

here, dict is a custom property, where app-home is selector of one component used in other component.

The idea of components in Angular2 is to be highly cohesive and loosely coupled.

Why angular2 allow data binding across components?

Body:
In your code <section> is parent component and <app-home> is child component.

Now in Angular 2 there is no such thing like $rootScope, but sharing data between components is important.

Now there are options available for data sharing between components.
Eg. Shared Services, and Parent-Child relation.

In Parent Child component data sharing we use @Input and @Output.

The example you shared is parent to child data sharing.

[propertyName]="sharedValue" this is the main approach used for Parent to Child component data sharing.


问:
Understanding * (zero or more) operator using re.search()
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

```<code>In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'
</code>```

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

```<code>In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''
</code>```

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

```<code>In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''
</code>```

I have tried the examples in Spyder 3.2.4

答:
You need to use *(0 or more) and +(1 or more) properly to get your desired output

Eg: 1 Matches because you have defined * only for "i", this patter will capture all the "p" or "pi" combination

Eg: 2 If you need to match only "i" you need to use "+" instead of "*".

If you use "*"

```<code>In: re.search(r"pi*g", "piiig!!").group()
</code>```

This will return if you input is ("pig" or "piig" or "pg")

If you use "+"

```<code>In: re.search(r"pi+g", "piiig!!").group()
</code>```

This will return if you input is ("pig" or "piig")

Body:
I am new to python and was going through "Google for Education" python course

Now, the line below confuses me:

* -- 0 or more occurrences of the pattern to its left

(all the examples are in python3)

e.g. 1

In [1]: re.search(r"pi*", "piiig!!").group()
Out[1]: 'piii'

This is fine since, "pi" has 1 occurrance so it is retured

e.g. 2

In [2]: re.search(r"i*", "piiig!!").group()
Out[2]: ''

Why does it not return "i" in fact - from my understanding, it should be returning "iii". But the result is an empty string.

Also, What exactly does "0 or more" mean? I searched on google but everywhere it is mentioned * -- 0 or more. But if there is 0 occurrence of an expression, does that not become true even if it's not there? What is the point of searching then?

I am so confused with this. Can you please help me with explaining this or point me in the right direction.

i hope the right explanation would also resolve my this issue:

In [3]: re.search(r"i?", "piiig!!").group()
Out[3]: ''

I have tried the examples in Spyder 3.2.4

Body:
You need to use *(0 or more) and +(1 or more) properly to get your desired output

Eg: 1 Matches because you have defined * only for "i", this patter will capture all the "p" or "pi" combination

Eg: 2 If you need to match only "i" you need to use "+" instead of "*".

If you use "*"

In: re.search(r"pi*g", "piiig!!").group()

This will return if you input is ("pig" or "piig" or "pg")

If you use "+"

In: re.search(r"pi+g", "piiig!!").group()

This will return if you input is ("pig" or "piig")


问:
Magento bundled item not showing all products
I am trying to add bundled items in Magento but, it does not shows all products.

I am using latest version of Magento, I have 5 products of same type but just two show as bundled item.

I figured out the issue: product with custom option does not shows as bundled items, how can I fix this?

答:
```<code>app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php

 $collection = Mage::getModel('catalog/product')->getCollection()
            ->setStore($this->getStore())
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('price')
            ->addAttributeToSelect('attribute_set_id')
            ->addAttributeToFilter('type_id', array('in' => $this->getAllowedSelectionTypes()))
            ->addStoreFilter();
            //->addFilterByRequiredOptions()
</code>```

Do this changes and all products displayed.

Body:
app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php

 $collection = Mage::getModel('catalog/product')->getCollection()
            ->setStore($this->getStore())
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('price')
            ->addAttributeToSelect('attribute_set_id')
            ->addAttributeToFilter('type_id', array('in' => $this->getAllowedSelectionTypes()))
            ->addStoreFilter();
            //->addFilterByRequiredOptions()

Do this changes and all products displayed.


问:
question number reordering
I have a list of question in my javascript file. Each question has a question number and question description and options. A question can be added anywhere in the list of questions. So if a question is added into the top of all questions, then i need to change the question numbers of all the below ones. How can achieve this. Can i use javascript for this?</p>

答:
Array prototype ( fun! =) ):</p>

```<code>// zero-based insert
Array.prototype.insert = function(index, item) {
    var i = 0, list = [];

    if (this.length == index) {
        list = this;
        list.push(item);
        return list;
    }

    for(; i < this.length; i++) {
        if (index == list.length) {
            list.push(item);
            i--;
        } else {
            list.push(this[i]);
        }
    }

    return list;
};

Array.prototype.print = function (base) {
    base = base || 1;
    for (var i = 0, out = []; i < this.length; i++) {
        out.push((base + i) + '. ' + this[i]);
    }

    return out.join("\n");
};

list = ['when?', 'where?', 'why?'];
list = list.insert(0, 'who?'); // first: ["who?", "when?", "where?", "why?"]
list = list.insert(3, 'how?'); // 4th: ["who?", "when?", "where?", "how?", "why?"]
list = list.insert(list.length, 'last?'); // last: ["who?", "when?", "where?", "how?", "why?", "last?"];

list.print();
/**
"1. who?
 2. when?
 3. where?
 4. how?
 5. why?
 6. last?"
 **/
</code>```

Title: question number reordering

Body:
Array prototype ( fun! =) ):

// zero-based insert
Array.prototype.insert = function(index, item) {
    var i = 0, list = [];

    if (this.length == index) {
        list = this;
        list.push(item);
        return list;
    }

    for(; i < this.length; i++) {
        if (index == list.length) {
            list.push(item);
            i--;
        } else {
            list.push(this[i]);
        }
    }

    return list;
};

Array.prototype.print = function (base) {
    base = base || 1;
    for (var i = 0, out = []; i < this.length; i++) {
        out.push((base + i) + '. ' + this[i]);
    }

    return out.join("\n");
};

list = ['when?', 'where?', 'why?'];
list = list.insert(0, 'who?'); // first: ["who?", "when?", "where?", "why?"]
list = list.insert(3, 'how?'); // 4th: ["who?", "when?", "where?", "how?", "why?"]
list = list.insert(list.length, 'last?'); // last: ["who?", "when?", "where?", "how?", "why?", "last?"];

list.print();
/**
"1. who?
 2. when?
 3. where?
 4. how?
 5. why?
 6. last?"
 **/