问:
Error : NBTSol.Models.ContactDbContext.Persons is inaccessible due to its protection level -C#
i am using entity framework in windowformapplication , when i call "db.Persons.Add()" it doesn't show refernce for Persons and gives the error :

Error : NBTSol.Models.ContactDbContext.Persons is inaccessible due to its protection level
even everything is public,

then why?

Person Model :

```<code> using System;
 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

 namespace NBTSol.Models
 {
   public class Person
   {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long PersonId { get; set; }

    [Required(ErrorMessage = "First Name is Required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is Required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Email is Required")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Gender is Required")]
    public string Gender { get; set; }

    [Required(ErrorMessage = "Address is Required")]
    public string Address { get; set; }

    [Required(ErrorMessage = "City is Required")]
    public string City { get; set; }

    [Required(ErrorMessage = "State is Required")]
    public string State { get; set; }

    [Required(ErrorMessage = "PostalCode is Required")]
    public string PostalCode { get; set; }

    [Required(ErrorMessage = "Country is Required")]
    public string Country { get; set; }

    [Required(ErrorMessage = "Contact Number is Required")]
    public string ContactNumber { get; set; }

    [Required(ErrorMessage = "CNIC is Required")]
    public string CNIC { get; set; }

    public string OrganizationName { get; set; }
    public string Designation { get; set; }
    public string Salary { get; set; }
    public string Description { get; set; }

    public Nullable<bool> IsClient { get; set; }
    public DateTime EntryDateTime { get; set; }
    public Nullable<bool> IsDeleted { get; set; }

 }
}
</code>```

My Context Class :

```<code>      using System;
      using System.Collections.Generic;
      using System.Data.Entity;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;

     namespace NBTSol.Models
     {
     public class ContactDbContext :DbContext
     {
    public ContactDbContext() : base( "name=DefaultConnection") { }

    DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure domain classes using Fluent API here

        base.OnModelCreating(modelBuilder);
    }
   }
  }
</code>```

main form :[here is the error when i try to call "db.Persons.Add()"]

```<code> using NBTSol.Models;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;

 namespace NBTSol
  {
   public partial class Main : Form
   {
    public Main()
    {
        InitializeComponent();
    }

    private void Main_Load(object sender, EventArgs e)
    {
        ContactDbContext db = new ContactDbContext();
        Person person = new Person();
        db.Persons.Add(person);
    }
  }
}
</code>```

答:
Make Person property public in your db context as following and it will work.

```<code>public DbSet<Person> Persons { get; set; }
</code>```

Replace your ContactDbContext class with following code:

```<code>public class ContactDbContext: DbContext {
 public ContactDbContext(): base("name=DefaultConnection") {}

 public DbSet < Person > Persons {
  get;
  set;
 }

 protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  //Configure domain classes using Fluent API here

  //Configure table name
  modelBuilder.Entity<Persons>()
  .ToTable("Persons ");

  base.OnModelCreating(modelBuilder);
 }
}
</code>```

Body:
i am using entity framework in windowformapplication , when i call "db.Persons.Add()" it doesn't show refernce for Persons and gives the error :

Error : NBTSol.Models.ContactDbContext.Persons is inaccessible due to its protection level
even everything is public,

then why?

Person Model :

 using System;
 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

 namespace NBTSol.Models
 {
   public class Person
   {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long PersonId { get; set; }

    [Required(ErrorMessage = "First Name is Required")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name is Required")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Email is Required")]
    public string Email { get; set; }

    [Required(ErrorMessage = "Gender is Required")]
    public string Gender { get; set; }

    [Required(ErrorMessage = "Address is Required")]
    public string Address { get; set; }

    [Required(ErrorMessage = "City is Required")]
    public string City { get; set; }

    [Required(ErrorMessage = "State is Required")]
    public string State { get; set; }

    [Required(ErrorMessage = "PostalCode is Required")]
    public string PostalCode { get; set; }

    [Required(ErrorMessage = "Country is Required")]
    public string Country { get; set; }

    [Required(ErrorMessage = "Contact Number is Required")]
    public string ContactNumber { get; set; }

    [Required(ErrorMessage = "CNIC is Required")]
    public string CNIC { get; set; }

    public string OrganizationName { get; set; }
    public string Designation { get; set; }
    public string Salary { get; set; }
    public string Description { get; set; }

    public Nullable<bool> IsClient { get; set; }
    public DateTime EntryDateTime { get; set; }
    public Nullable<bool> IsDeleted { get; set; }

 }
}

My Context Class :

      using System;
      using System.Collections.Generic;
      using System.Data.Entity;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;

     namespace NBTSol.Models
     {
     public class ContactDbContext :DbContext
     {
    public ContactDbContext() : base( "name=DefaultConnection") { }

    DbSet<Person> Persons { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Configure domain classes using Fluent API here

        base.OnModelCreating(modelBuilder);
    }
   }
  }

main form :[here is the error when i try to call "db.Persons.Add()"]

 using NBTSol.Models;
 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.Windows.Forms;

 namespace NBTSol
  {
   public partial class Main : Form
   {
    public Main()
    {
        InitializeComponent();
    }

    private void Main_Load(object sender, EventArgs e)
    {
        ContactDbContext db = new ContactDbContext();
        Person person = new Person();
        db.Persons.Add(person);
    }
  }
}

Body:
Make Person property public in your db context as following and it will work.

public DbSet<Person> Persons { get; set; }

Replace your ContactDbContext class with following code:

public class ContactDbContext: DbContext {
 public ContactDbContext(): base("name=DefaultConnection") {}

 public DbSet < Person > Persons {
  get;
  set;
 }

 protected override void OnModelCreating(DbModelBuilder modelBuilder) {
  //Configure domain classes using Fluent API here

  //Configure table name
  modelBuilder.Entity<Persons>()
  .ToTable("Persons ");

  base.OnModelCreating(modelBuilder);
 }
}


来源: stackexchange

问:
Algorithm to sum/stack values from a time series graph where data points don't match on time
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?

I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the series don't match up, and i really don't want to resort to duplicating values into time bins.

So, given these 2 series:

```<code>S1: (1;100) (5;100) (10;100)
S2: (4;150) (5;100) (18;150)
</code>```

When added together, should result in:

```<code>ST: (1;100) (4;250) (5;200) (10;200) (18;250)
</code>```

Logic:

```<code>x=1 s1=100, s2=None, sum=100
x=4 s1=100, s2=150, sum=250 (note s1 value from previous value)
x=5 s1=100, s2=100, sum=200
x=10 s1=100, s2=100, sum=200
x=18 s1=100, s2=150, sum=250
</code>```

My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.

Any ideas would be appreciated!

答:
One possible approach:

Format all series' element into
tuples (x, y, series id), e.g. (4,
150, 1) and add them to a tuple list, and sort it by x ascending.

Declare a list with length equals to number of series to maintain "last seen" value for each series.

Iterate through each element tuple of list in step (1), and:

3.1 Update the "last seen" list according to series id in tuple

3.2 When x of previously iterated tuple doesn't match with x of current tuple, sum all element of "last seen" list and add the result to final list.

Now with my dirty test:

```<code>>>>
S1 = ((1, 100), (5, 100), (10, 100))
S2 = ((4, 150), (5, 100), (18, 150))
>>> all = []
>>> for s in S1: all.append((s[0], s[1], 0))
...
>>> for s in S2: all.appned((s[0], s[1], 1))
...
>>> all
[(1, 100, 0), (5, 100, 0), (10, 100, 0), (4, 150, 1), (5, 100, 1), (18, 150, 1)]
>>> all.sort()
>>> all
[(1, 100, 0), (4, 150, 1), (5, 100, 0), (5, 100, 1), (10, 100, 0), (18, 150, 1)]
>>> last_val = [0]*2
>>> last_x = all[0][0]
>>> final = []
>>> for e in all:
...     if e[0] != last_x:
...             final.append((last_x, sum(last_val)))
...     last_val[e[2]] = e[1]
...     last_x = e[0]
...
>>> final.append((last_x, sum(last_val)))
>>> final
[(1, 100), (4, 250), (5, 200), (10, 200), (18, 250)]
>>>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a graphing/analysis problem i can't quite get my head around. I can do a brute force, but its too slow, maybe someone has a better idea, or knows or a speedy library for python?

I have 2+ time series data sets (x,y) that i want to aggregate (and subsequently plot). The issue is that the x values across the series don't match up, and i really don't want to resort to duplicating values into time bins.

So, given these 2 series:

S1: (1;100) (5;100) (10;100)
S2: (4;150) (5;100) (18;150)

When added together, should result in:

ST: (1;100) (4;250) (5;200) (10;200) (18;250)

Logic:

x=1 s1=100, s2=None, sum=100
x=4 s1=100, s2=150, sum=250 (note s1 value from previous value)
x=5 s1=100, s2=100, sum=200
x=10 s1=100, s2=100, sum=200
x=18 s1=100, s2=150, sum=250

My current thinking is to iterate a sorted list of keys(x), keep the previous value for each series, and query each set if it has a new y for the x.

Any ideas would be appreciated!

Body:
One possible approach:

Format all series' element into
tuples (x, y, series id), e.g. (4,
150, 1) and add them to a tuple list, and sort it by x ascending.

Declare a list with length equals to number of series to maintain "last seen" value for each series.

Iterate through each element tuple of list in step (1), and:

3.1 Update the "last seen" list according to series id in tuple

3.2 When x of previously iterated tuple doesn't match with x of current tuple, sum all element of "last seen" list and add the result to final list.

Now with my dirty test:

>>>
S1 = ((1, 100), (5, 100), (10, 100))
S2 = ((4, 150), (5, 100), (18, 150))
>>> all = []
>>> for s in S1: all.append((s[0], s[1], 0))
...
>>> for s in S2: all.appned((s[0], s[1], 1))
...
>>> all
[(1, 100, 0), (5, 100, 0), (10, 100, 0), (4, 150, 1), (5, 100, 1), (18, 150, 1)]
>>> all.sort()
>>> all
[(1, 100, 0), (4, 150, 1), (5, 100, 0), (5, 100, 1), (10, 100, 0), (18, 150, 1)]
>>> last_val = [0]*2
>>> last_x = all[0][0]
>>> final = []
>>> for e in all:
...     if e[0] != last_x:
...             final.append((last_x, sum(last_val)))
...     last_val[e[2]] = e[1]
...     last_x = e[0]
...
>>> final.append((last_x, sum(last_val)))
>>> final
[(1, 100), (4, 250), (5, 200), (10, 200), (18, 250)]
>>>


问:
Convert string to List<string> in one line?
I have a string:

```<code>var names = "Brian,Joe,Chris";
</code>```

Is there a way to convert this to a List<string> delimited by , in one line?

答:
If you already have a list and want to add values from a delimited string, you can use AddRange or InsertRange. For example:

```<code>existingList.AddRange(names.Split(','));
</code>```

Body:
I have a string:

var names = "Brian,Joe,Chris";

Is there a way to convert this to a List<string> delimited by , in one line?

Body:
If you already have a list and want to add values from a delimited string, you can use AddRange or InsertRange. For example:

existingList.AddRange(names.Split(','));

ContentLicense: CC BY-SA 3.0


问:
Why is this python loop containing consecutive duplicate items breaking?
I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST) and discard any adjacent opposite directions (NORTH and SOUTH, EAST and WEST) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']. Why is my code doing this, and how can I fix it to handle consecutive duplicates?

```<code>def dirReduc(arr):
  for direction in arr[:-1]:
    try:
      gotdata = arr[arr.index(direction)+1]
    except IndexError:
      gotdata = 'null'
    except ValueError:
      gotdata = 'null'
    if gotdata is 'null':
      if arr == dirReduc(arr):
        return arr
      else:
        return dirReduc(arr)
    elif cancel_pair(direction, arr[arr.index(direction)+1]):
      del arr[arr.index(direction):arr.index(direction)+2]
  return arr

def cancel_pair(dir1, dir2):
  if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
    return True
  elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
    return True
  return False
</code>```

答:
```<code>opp = {}
opp['NORTH'] = 'SOUTH'
opp['EAST'] = 'WEST'
opp['SOUTH'] = 'NORTH'
opp['WEST'] = 'EAST'

def red(lst):
  i = 0
  j = 1
  while j< len(lst):
    if(opp[lst[i]] == lst[j]):
      lst[i] = 0
      lst[j] = 0
      lst = [x for x in lst if x != 0]
      i =0
      j =1
    else:
      i+=1
      j+=1

  print(i,j)
</code>```

this is a cleaner way to do it, I store the opposite directions and then iterate over the list making a new copy every time i 'pop' opposite elements.

keep in mind that the input list will be modified by this code so you might want to pass a copy of the input list if needed.

Body:
I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST) and discard any adjacent opposite directions (NORTH and SOUTH, EAST and WEST) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']. Why is my code doing this, and how can I fix it to handle consecutive duplicates?

def dirReduc(arr):
  for direction in arr[:-1]:
    try:
      gotdata = arr[arr.index(direction)+1]
    except IndexError:
      gotdata = 'null'
    except ValueError:
      gotdata = 'null'
    if gotdata is 'null':
      if arr == dirReduc(arr):
        return arr
      else:
        return dirReduc(arr)
    elif cancel_pair(direction, arr[arr.index(direction)+1]):
      del arr[arr.index(direction):arr.index(direction)+2]
  return arr

def cancel_pair(dir1, dir2):
  if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
    return True
  elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
    return True
  return False

Body:
opp = {}
opp['NORTH'] = 'SOUTH'
opp['EAST'] = 'WEST'
opp['SOUTH'] = 'NORTH'
opp['WEST'] = 'EAST'

def red(lst):
  i = 0
  j = 1
  while j< len(lst):
    if(opp[lst[i]] == lst[j]):
      lst[i] = 0
      lst[j] = 0
      lst = [x for x in lst if x != 0]
      i =0
      j =1
    else:
      i+=1
      j+=1

  print(i,j)

this is a cleaner way to do it, I store the opposite directions and then iterate over the list making a new copy every time i 'pop' opposite elements.

keep in mind that the input list will be modified by this code so you might want to pass a copy of the input list if needed.


问:
Get line-height of p tag
I want to figure out the line-height of a
 tag within a div.

var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
heightLabel.innerHTML = myp.style.lineHeight + " is the height.";```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div>
      <p id=myp>People assume I'm a boiler ready to explode, <br>but I actually have very low blood pressure, <br>which is shocking to people.</p>
    </div>

    <h3 id="heightLabel"></h3></code>```

However, as seen in the code above, if the line-height of the p tag is not explicitly assigned then using .style.lineHeight returns an empty string.

Is there any way to get the height of a line in a
 tag if it hasn't been assigned? I'd like to get it in px at the end.

答:
Instead of .style property, you need to getComputedStyle() of your p element

```<code>var elementStyle = window.getComputedStyle(*DOM element*);
</code>```

After that you can simply use elementStyle.getPropertyValue(*style-property*) prop.

Btw. you can check computed style under your console (firefox screenshot):

See working example:

var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
var mypStyle = window.getComputedStyle(myp);
heightLabel.innerHTML = mypStyle.getPropertyValue('line-height') + " is the line height.";

// console.log(mypStyle.getPropertyValue('line-height')); // output 20px
// console.log(typeof mypStyle.getPropertyValue('line-height')); // string

// Using parseFloat we convert string into value
// Examples:
// parseFloat('20px') // 20, typeof number
// parseFloat('22.5rem') // 22.5 typeof number
// If you are sure, your string will always contain intenger value use parseInt() instead
// DOES not work cross-browser
// Chrome return line-height normal, firefox '20px'
// var getNumberValue = parseFloat(mypStyle.getPropertyValue('line-height')); // 20, typeof string

console.log(getLineHeight(myp));

// https://stackoverflow.com/questions/4392868/javascript-find-divs-line-height-not-css-property-but-actual-line-height?noredirect=1&lq=1
function getLineHeight(element){
   var temp = document.createElement(element.nodeName);
   temp.setAttribute("style","margin:0px;padding:0px;font-family:"+element.style.fontFamily+";font-size:"+element.style.fontSize);
   temp.innerHTML = "test";
   temp = element.parentNode.appendChild(temp);
   var ret = temp.clientHeight;
   temp.parentNode.removeChild(temp);
   return ret;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
      <p id=myp>People assume I'm a boiler ready to explode, <br>but I actually have very low blood pressure, <br>which is shocking to people.</p>
    </div>

    <h3 id="heightLabel"></h3></code>```

Title: Get line-height of p tag

Body:
I want to figure out the line-height of a
 tag within a div.

var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
heightLabel.innerHTML = myp.style.lineHeight + " is the height.";

People assume I'm a boiler ready to explode,
but I actually have very low blood pressure,
which is shocking to people.

However, as seen in the code above, if the line-height of the p tag is not explicitly assigned then using .style.lineHeight returns an empty string.

Is there any way to get the height of a line in a
 tag if it hasn't been assigned? I'd like to get it in px at the end.

Body:
Instead of .style property, you need to getComputedStyle() of your p element

var elementStyle = window.getComputedStyle(*DOM element*);

After that you can simply use elementStyle.getPropertyValue(*style-property*) prop.

Btw. you can check computed style under your console (firefox screenshot):

See working example:

var myp = document.getElementById('myp');
var heightLabel = document.getElementById('heightLabel');
var mypStyle = window.getComputedStyle(myp);
heightLabel.innerHTML = mypStyle.getPropertyValue('line-height') + " is the line height.";

// console.log(mypStyle.getPropertyValue('line-height')); // output 20px
// console.log(typeof mypStyle.getPropertyValue('line-height')); // string

// Using parseFloat we convert string into value
// Examples:
// parseFloat('20px') // 20, typeof number
// parseFloat('22.5rem') // 22.5 typeof number
// If you are sure, your string will always contain intenger value use parseInt() instead
// DOES not work cross-browser
// Chrome return line-height normal, firefox '20px'
// var getNumberValue = parseFloat(mypStyle.getPropertyValue('line-height')); // 20, typeof string

console.log(getLineHeight(myp));

// https://stackoverflow.com/questions/4392868/javascript-find-divs-line-height-not-css-property-but-actual-line-height?noredirect=1&lq=1
function getLineHeight(element){
   var temp = document.createElement(element.nodeName);
   temp.setAttribute("style","margin:0px;padding:0px;font-family:"+element.style.fontFamily+";font-size:"+element.style.fontSize);
   temp.innerHTML = "test";
   temp = element.parentNode.appendChild(temp);
   var ret = temp.clientHeight;
   temp.parentNode.removeChild(temp);
   return ret;
}

<div>
      <p id=myp>People assume I'm a boiler ready to explode, <br>but I actually have very low blood pressure, <br>which is shocking to people.</p>
    </div>

    <h3 id="heightLabel"></h3>


问:
print on dot matrix printer in .net
anyone can please tell me the code how to print documents on dot matrix printer in C# windows application.</p>

答:
How is this different from printing on inkjet or laser printer?

MSDN: Printing Overview

Preview and Print from Your Windows Forms App with the .NET Printing Namespace

OwnerDisplayName: Vikram

LastEditorDisplayName: Gamecat

Title: print on dot matrix printer in .net

OwnerDisplayName: aku


问:
Jquery dynamic text effect / class problem
I have a html file containing a table with some rows n columns. each row contain a button, which has some functions. First, it has to submit the data in a row to a php file, which is not printing anything. Then the button have to change its text and text in column 5 of its corresponding row. The change text effect of button is working well. But the change text effect of column 5 is buggy. Only the text of column5 in first row is changing, no matter which button you click.. Can anyone fix the problem for me??

Thanks in advance :)

blasteralfred

```<code><head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<style>
.style1 {
    background-color: #c3d9ff;
    font-family:arial,sans-serif;
}
.style2 {
    text-align: center;
    font-weight: bold;
}
.style3 {
    background-color: #FFFFFF;
    font-family:arial,sans-serif;
    text-align: center;
    font-weight: bold;
}
body {
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:15px;
background-color: ;
}
.delete_button {
font-weight:bold;
float:right;
}
</style>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function()
{
    $(".delete_button").click(function()
    {
    var id = $(this).attr("id");
    var dataString = 'id='+ id ;
    var parent = $(this).parent().parent();
    $.ajax({
        type: "POST",
        url: "del.php",
        data: dataString,
        cache: false,
        success: function()
        {
            if(id % 2)
            {
                parent.fadeOut('fast', function() {$(this).fadeOut();$(this).fadeIn();});
            }
            else
            {
                parent.fadeOut('fast', function()   {$(this).fadeOut();$(this).fadeIn();});
            }
        }
    });
    return false;
    }
);});
$(document).ready(function() {
  $('.delete_button').click(function() {
    $(this).text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
    $("#clickme2").text($("#clickme2").text() == 'Inactive' ? 'Active' : 'Inactive');
    return false;
});
});
</script>
</head>
<body>
<table style="width: 90%" align="center" class="style1">
<tr>
        <td colspan="7" class="style2">MANAGER</td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">column1</td>
        <td class="style3" style="width: 139px">column2</td>
        <td class="style3" style="width: 139px">column3</td>
        <td class="style3" style="width: 139px">column4</td>
        <td class="style3" style="width: 139px">column5</td>
        <td class="style3" style="width: 144px">column6</td>
        <td class="style3" style="">Action</td>
    </tr>
        <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
    <tr>
        <td class="style3" style="width: 139px">msg1</td>
        <td class="style3" style="width: 139px">msg2</td>
        <td class="style3" style="width: 139px">msg3</td>
        <td class="style3" style="width: 139px">msg4</td>
        <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
        <td class="style3" style="width: 144px">msg6</td>
        <td  style="width: ">
            <button class="delete_button" style="width:80px;height:">Activate</button>
        </td>
    </tr>
</table>
</body>
</code>```

答:
you have got error in you javascript

```<code>$(document).ready(function() {
$('.delete_button').click(function() {
    $(this).text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
    $("#clickme2").text($("#clickme2").text() == 'Inactive' ? 'Active' : 'Inactive');/*you are giving same id to all rows in 5 th column and selecting it*/
    return false;
    });
});
</code>```

You should remove id from here

```<code> <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>
</code>```

and change your javascript to

then in youjavascript

```<code>    $(document).ready(function() {
$('.delete_button').click(function() {
    $(this).text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
        $(this).closest("td").prev().prev().text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
    return false;
    });
});
</code>```

but i am not sure about ajax request

Body:
I have a html file containing a table with some rows n columns. each row contain a button, which has some functions. First, it has to submit the data in a row to a php file, which is not printing anything. Then the button have to change its text and text in column 5 of its corresponding row. The change text effect of button is working well. But the change text effect of column 5 is buggy. Only the text of column5 in first row is changing, no matter which button you click.. Can anyone fix the problem for me??

Thanks in advance :)

blasteralfred

<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

        MANAGER

        column1
        column2
        column3
        column4
        column5
        column6
        Action

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

        msg1
        msg2
        msg3
        msg4
        Inactive
        msg6

            <button class="delete_button" style="width:80px;height:">Activate</button>

Body:
you have got error in you javascript

$(document).ready(function() {
$('.delete_button').click(function() {
    $(this).text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
    $("#clickme2").text($("#clickme2").text() == 'Inactive' ? 'Active' : 'Inactive');/*you are giving same id to all rows in 5 th column and selecting it*/
    return false;
    });
});

You should remove id from here

 <td div id="clickme2" class="style3" style="width: 139px">Inactive</td>

and change your javascript to

then in youjavascript

    $(document).ready(function() {
$('.delete_button').click(function() {
    $(this).text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
        $(this).closest("td").prev().prev().text($(this).text() == 'Inactivate' ? 'Activate' : 'Inactivate');
    return false;
    });
});

but i am not sure about ajax request


问:
Pandas filling missing dates and values within group
I've a data frame that looks like the following

```<code>x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})
</code>```

What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in 0 for the val column. So the desired output is

```<code>            dt user  val
0   2016-01-01    a    1
1   2016-01-02    a   33
2   2016-01-03    a    0
3   2016-01-04    a    0
4   2016-01-05    a    0
5   2016-01-06    a    0
6   2016-01-01    b    0
7   2016-01-02    b    0
8   2016-01-03    b    0
9   2016-01-04    b    0
10  2016-01-05    b    2
11  2016-01-06    b    1
</code>```

I've tried the solution mentioned here and here but they aren't what I'm after.
Any pointers much appreciated.

Body:
I've a data frame that looks like the following

x = pd.DataFrame({'user': ['a','a','b','b'], 'dt': ['2016-01-01','2016-01-02', '2016-01-05','2016-01-06'], 'val': [1,33,2,1]})

What I would like to be able to do is find the minimum and maximum date within the date column and expand that column to have all the dates there while simultaneously filling in 0 for the val column. So the desired output is

            dt user  val
0   2016-01-01    a    1
1   2016-01-02    a   33
2   2016-01-03    a    0
3   2016-01-04    a    0
4   2016-01-05    a    0
5   2016-01-06    a    0
6   2016-01-01    b    0
7   2016-01-02    b    0
8   2016-01-03    b    0
9   2016-01-04    b    0
10  2016-01-05    b    2
11  2016-01-06    b    1

I've tried the solution mentioned here and here but they aren't what I'm after.
Any pointers much appreciated.

Body:
Initial Dataframe:

            dt  user    val
0   2016-01-01     a      1
1   2016-01-02     a     33
2   2016-01-05     b      2
3   2016-01-06     b      1

First, convert the dates to datetime:

x['dt'] = pd.to_datetime(x['dt'])

Then, generate the dates and unique users:

dates = x.set_index('dt').resample('D').asfreq().index

>> DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04',
               '2016-01-05', '2016-01-06'],
              dtype='datetime64[ns]', name='dt', freq='D')

users = x['user'].unique()

>> array(['a', 'b'], dtype=object)

This will allow you to create a MultiIndex:

idx = pd.MultiIndex.from_product((dates, users), names=['dt', 'user'])

>> MultiIndex(levels=[[2016-01-01 00:00:00, 2016-01-02 00:00:00, 2016-01-03 00:00:00, 2016-01-04 00:00:00, 2016-01-05 00:00:00, 2016-01-06 00:00:00], ['a', 'b']],
           labels=[[0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5], [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1]],
           names=['dt', 'user'])

You can use that to reindex your DataFrame:

x.set_index(['dt', 'user']).reindex(idx, fill_value=0).reset_index()
Out:
           dt user  val
0  2016-01-01    a    1
1  2016-01-01    b    0
2  2016-01-02    a   33
3  2016-01-02    b    0
4  2016-01-03    a    0
5  2016-01-03    b    0
6  2016-01-04    a    0
7  2016-01-04    b    0
8  2016-01-05    a    0
9  2016-01-05    b    2
10 2016-01-06    a    0
11 2016-01-06    b    1

which then can be sorted by users:

x.set_index(['dt', 'user']).reindex(idx, fill_value=0).reset_index().sort_values(by='user')
Out:
           dt user  val
0  2016-01-01    a    1
2  2016-01-02    a   33
4  2016-01-03    a    0
6  2016-01-04    a    0
8  2016-01-05    a    0
10 2016-01-06    a    0
1  2016-01-01    b    0
3  2016-01-02    b    0
5  2016-01-03    b    0
7  2016-01-04    b    0
9  2016-01-05    b    2
11 2016-01-06    b    1

ContentLicense: CC BY-SA 4.0


问:
c# testing async task - test case ignores await - NullReferenceException
I'm using NUnit, Shouldly and Entity Framework in-memory SQLite database for integration tests and got stuck on two of my test cases that doesn't execute any database calls, (no await executed).

Controller:

```<code>[HttpPost("DeleteOrganisations")]
public async Task<IActionResult> DeleteOrganisations([FromBody] DeleteOrganisationsModel model)
{
    //Test case 2 fails here
    if (model == null || !ModelState.IsValid)
    {
        return Ok(new GenericResultModel(_localizer["An_unexpected_error_has_occurred_Please_try_again"]));
    }

    List<OrganisationModel> organisations = (await _organisationService.GetOrganisations(model.OrganisationIds)).ToList();

    //Test case 3 fails here
    if (organisations == null || organisations.Count == 0)
    {
        return Ok(new GenericResultModel(_localizer["Could_not_find_organisations"]));
    }

    StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);

    if (status == null)
    {
        return Ok(new GenericResultModel(_localizer["Could_not_find_status"]));
    }

    foreach (OrganisationModel organisation in organisations)
    {
        organisation.StatusId = status.Id;
    }

    List<OrganisationModel> updatedOrganisations = (await _organisationService.UpdateOrganisations(organisations)).ToList();

    if (updatedOrganisations == null || updatedOrganisations.Count == 0)
    {
        return Ok(new GenericResultModel(_localizer["Could_not_remove_organisations"]));
    }

    if (updatedOrganisations.Count == 1)
    {
        return Ok(new GenericResultModel { Id = updatedOrganisations[0].Id });
    }

    return Ok(new GenericResultModel { Count = updatedOrganisations.Count });
}
</code>```

Test:

```<code>[TestFixture]
public class DeleteOrganisations : TestBase
{
    private OrganisationController _organisationController;

    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        //Controller
        _organisationController = new OrganisationController(null, Mapper, OrganisationService, StatusService, AuthenticationService);

        //Object Mother
        ObjectMother.InsertTestData();
    }

    public static IEnumerable TestCases
    {
        get
        {
            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = new List<int>() { 1 } }, 0, 1).SetName("DeleteOrganisations_Should_Delete_Data_When_OrganisationId_Exist");

            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = null }, 0, 0).SetName("DeleteOrganisations_Should_Not_Delete_Data_When_Null");
            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = new List<int>() { 2 } }, 0, 0).SetName("DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist");
        }
    }

    [Test, TestCaseSource(nameof(TestCases))]
    public async Task Test(DeleteOrganisationsModel model, int removedOrganisationCountBefore, int removedOrganisationCountAfter)
    {
        //Before
        int resultBefore = Database.Organisation.Include(o => o.Status).Count(o => o.Status.Name == StatusEnum.Status.Removed.ToString());

        resultBefore.ShouldBe(removedOrganisationCountBefore);

        //Delete
        await _organisationController.DeleteOrganisations(model);

        //After
        int resultAfter = Database.Organisation.Include(o => o.Status).Count(o => o.Status.Name == StatusEnum.Status.Removed.ToString());

        resultAfter.ShouldBe(removedOrganisationCountAfter);
    }
}
</code>```

Test case 1 passes because

```<code>StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);
</code>```

is called and the result is awaited.

Test case 2 and 3 fails because there's never an await in the function, (if statement).

Message: System.NullReferenceException : Object reference not set to
  an instance of an object.

I can probably create another test for results that doesn't execute any await statements and skip the async Task for the new test function, but then I would get the message saying:

Because this call is not awaited, execution of the current method
  continues before the call is completed. Consider applying the 'await'
  operator to the result of the call.

The test would probably pass but I dont like the idea of two tests plus the syntax error.

What would you do?

Edit

Exception:

```<code>Message: System.NullReferenceException : Object reference not set to an instance of an object.
</code>```

StackTrace:

```<code>Test Name:  DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist
Test FullName:  MyProject.Test.Api.Administration.Organisation.DeleteOrganisations.DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist
Test Source:    C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProject.Test\Api\Administration\Organisation\DeleteOrganisations.cs : line 42
Test Outcome:   Failed
Test Duration:  0:00:02.48

Result StackTrace:  at MyProject.Api.Controllers.Administration.OrganisationController.<DeleteOrganisations>d__8.MoveNext() in C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProject.Api\Controllers\Administration\OrganisationController.cs:line 114
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.Test.Api.Administration.Organisation.DeleteOrganisations.<Test>d__4.MoveNext() in C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProjectTest\Api\Administration\Organisation\DeleteOrganisations.cs:line 49
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult)
   at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.
</code>```

答:
Facepalm - I forgot to inject the localizer class in the testbase. Sorry folks my bad.

This line right here:

```<code>if (organisations == null || organisations.Count == 0)
{
    return Ok(new GenericResultModel(_localizer["Could_not_find_organisations"]));
}
</code>```

Body:
I'm using NUnit, Shouldly and Entity Framework in-memory SQLite database for integration tests and got stuck on two of my test cases that doesn't execute any database calls, (no await executed).

Controller:

[HttpPost("DeleteOrganisations")]
public async Task<IActionResult> DeleteOrganisations([FromBody] DeleteOrganisationsModel model)
{
    //Test case 2 fails here
    if (model == null || !ModelState.IsValid)
    {
        return Ok(new GenericResultModel(_localizer["An_unexpected_error_has_occurred_Please_try_again"]));
    }

    List<OrganisationModel> organisations = (await _organisationService.GetOrganisations(model.OrganisationIds)).ToList();

    //Test case 3 fails here
    if (organisations == null || organisations.Count == 0)
    {
        return Ok(new GenericResultModel(_localizer["Could_not_find_organisations"]));
    }

    StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);

    if (status == null)
    {
        return Ok(new GenericResultModel(_localizer["Could_not_find_status"]));
    }

    foreach (OrganisationModel organisation in organisations)
    {
        organisation.StatusId = status.Id;
    }

    List<OrganisationModel> updatedOrganisations = (await _organisationService.UpdateOrganisations(organisations)).ToList();

    if (updatedOrganisations == null || updatedOrganisations.Count == 0)
    {
        return Ok(new GenericResultModel(_localizer["Could_not_remove_organisations"]));
    }

    if (updatedOrganisations.Count == 1)
    {
        return Ok(new GenericResultModel { Id = updatedOrganisations[0].Id });
    }

    return Ok(new GenericResultModel { Count = updatedOrganisations.Count });
}

Test:

[TestFixture]
public class DeleteOrganisations : TestBase
{
    private OrganisationController _organisationController;

    [OneTimeSetUp]
    public void OneTimeSetUp()
    {
        //Controller
        _organisationController = new OrganisationController(null, Mapper, OrganisationService, StatusService, AuthenticationService);

        //Object Mother
        ObjectMother.InsertTestData();
    }

    public static IEnumerable TestCases
    {
        get
        {
            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = new List<int>() { 1 } }, 0, 1).SetName("DeleteOrganisations_Should_Delete_Data_When_OrganisationId_Exist");

            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = null }, 0, 0).SetName("DeleteOrganisations_Should_Not_Delete_Data_When_Null");
            yield return new TestCaseData(new DeleteOrganisationsModel { OrganisationIds = new List<int>() { 2 } }, 0, 0).SetName("DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist");
        }
    }

    [Test, TestCaseSource(nameof(TestCases))]
    public async Task Test(DeleteOrganisationsModel model, int removedOrganisationCountBefore, int removedOrganisationCountAfter)
    {
        //Before
        int resultBefore = Database.Organisation.Include(o => o.Status).Count(o => o.Status.Name == StatusEnum.Status.Removed.ToString());

        resultBefore.ShouldBe(removedOrganisationCountBefore);

        //Delete
        await _organisationController.DeleteOrganisations(model);

        //After
        int resultAfter = Database.Organisation.Include(o => o.Status).Count(o => o.Status.Name == StatusEnum.Status.Removed.ToString());

        resultAfter.ShouldBe(removedOrganisationCountAfter);
    }
}

Test case 1 passes because

StatusModel status = await _statusService.GetStatus(StatusTypeEnum.StatusType.Organisation, StatusEnum.Status.Removed);

is called and the result is awaited.

Test case 2 and 3 fails because there's never an await in the function, (if statement).

Message: System.NullReferenceException : Object reference not set to
  an instance of an object.

I can probably create another test for results that doesn't execute any await statements and skip the async Task for the new test function, but then I would get the message saying:

Because this call is not awaited, execution of the current method
  continues before the call is completed. Consider applying the 'await'
  operator to the result of the call.

The test would probably pass but I dont like the idea of two tests plus the syntax error.

What would you do?

Edit

Exception:

Message: System.NullReferenceException : Object reference not set to an instance of an object.

StackTrace:

Test Name:  DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist
Test FullName:  MyProject.Test.Api.Administration.Organisation.DeleteOrganisations.DeleteOrganisations_Should_Not_Delete_Data_When_OrganisationId_Not_Exist
Test Source:    C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProject.Test\Api\Administration\Organisation\DeleteOrganisations.cs : line 42
Test Outcome:   Failed
Test Duration:  0:00:02.48

Result StackTrace:  at MyProject.Api.Controllers.Administration.OrganisationController.<DeleteOrganisations>d__8.MoveNext() in C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProject.Api\Controllers\Administration\OrganisationController.cs:line 114
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.Test.Api.Administration.Organisation.DeleteOrganisations.<Test>d__4.MoveNext() in C:\Users\User\Documents\Visual Studio 2017\Projects\MyProject\MyProjectTest\Api\Administration\Organisation\DeleteOrganisations.cs:line 49
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult)
   at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)
Result Message: System.NullReferenceException : Object reference not set to an instance of an object.

Body:
Facepalm - I forgot to inject the localizer class in the testbase. Sorry folks my bad.

This line right here:

if (organisations == null || organisations.Count == 0)
{
    return Ok(new GenericResultModel(_localizer["Could_not_find_organisations"]));
}


答:
There are a lot of mistakes in this function.  The most important two local mistakes are:

arr.index(direction) will always find the first instance of direction in arr, even after you've gone on to the next one

you have del arr[x:y] in the middle of a loop over arr, which will have unpredictable results.1

But also, I don't think your algorithm does what it's supposed to do.  I would write this like this:

```<code>import re
_rcd_removals = re.compile(
    r"\b(?:SOUTH NORTH|NORTH SOUTH|WEST EAST|EAST WEST)\b")

def remove_cancelling_directions(dirs):
    """DIRS is a list of uppercase cardinal directions as strings
       (NORTH, SOUTH, EAST, WEST).  Remove pairs of elements that
       cancel each others' motion, e.g. NORTH immediately followed
       by SOUTH.  Modifies DIRS in place and returns nothing."""

    dirs[:] = _rcd_removals.sub("", " ".join(dirs)).split()
</code>```

Regexes are great at sliding-window edits to sequences of words.  Working on this as an array is going to be a lot finickier.

If you need to collapse pairs that are only visible after other pairs have been collapsed (e.g. WEST SOUTH NORTH EAST should become the empty list), then you should iterate to a fixed point:

```<code>import re
_rcd_removals = re.compile(
    r"\b(?:SOUTH NORTH|NORTH SOUTH|WEST EAST|EAST WEST)\b")
_rcd_fixwhite = re.compile(" {2,}")

def remove_cancelling_directions_repeatedly(dirs):
    ds = " ".join(dirs)
    prev_ds = None
    while prev_ds != ds:
        prev_ds = ds
        ds = _rcd_removals.sub("", ds)
        ds = _rcd_fixwhite.sub(" ", ds)
   dirs[:] = ds.split()
</code>```

1 Can anyone point me at official Python documentation stating that the effect of mutating a list while iterating over it is unpredictable? I know that it is, but I can't find an official rule.  (The spec for list goes out of its way to point out that mutating a list while sorting it has undefined behavior.)

Title: Why is this python loop containing consecutive duplicate items breaking?

Body:
There are a lot of mistakes in this function.  The most important two local mistakes are:

arr.index(direction) will always find the first instance of direction in arr, even after you've gone on to the next one

you have del arr[x:y] in the middle of a loop over arr, which will have unpredictable results.1

But also, I don't think your algorithm does what it's supposed to do.  I would write this like this:

import re
_rcd_removals = re.compile(
    r"\b(?:SOUTH NORTH|NORTH SOUTH|WEST EAST|EAST WEST)\b")

def remove_cancelling_directions(dirs):
    """DIRS is a list of uppercase cardinal directions as strings
       (NORTH, SOUTH, EAST, WEST).  Remove pairs of elements that
       cancel each others' motion, e.g. NORTH immediately followed
       by SOUTH.  Modifies DIRS in place and returns nothing."""

    dirs[:] = _rcd_removals.sub("", " ".join(dirs)).split()

Regexes are great at sliding-window edits to sequences of words.  Working on this as an array is going to be a lot finickier.

If you need to collapse pairs that are only visible after other pairs have been collapsed (e.g. WEST SOUTH NORTH EAST should become the empty list), then you should iterate to a fixed point:

import re
_rcd_removals = re.compile(
    r"\b(?:SOUTH NORTH|NORTH SOUTH|WEST EAST|EAST WEST)\b")
_rcd_fixwhite = re.compile(" {2,}")

def remove_cancelling_directions_repeatedly(dirs):
    ds = " ".join(dirs)
    prev_ds = None
    while prev_ds != ds:
        prev_ds = ds
        ds = _rcd_removals.sub("", ds)
        ds = _rcd_fixwhite.sub(" ", ds)
   dirs[:] = ds.split()

1 Can anyone point me at official Python documentation stating that the effect of mutating a list while iterating over it is unpredictable? I know that it is, but I can't find an official rule.  (The spec for list goes out of its way to point out that mutating a list while sorting it has undefined behavior.)


问:
Apply a loop to a data frame
I'm trying to apply the function RE.Johnson from the Johnson package to a whole data frame df that contains 157 observations of 16 variables and i'd like to loop trough all the dataframe instead of doing it manually.
I've tried the following code but it doesn't work.

```<code>lapply(df[1:16], function(x) RE.Johnson(x))
</code>```

I know it might seem easy for you guys but I'm juste starting with R.
Thanks

EDIT

R provides me the answer Error in RE.ADT(xsl[, i]) : object 'p' not found and the data are not transformed.
And here is a summary of the data:

```<code>data.frame':    157 obs. of  16 variables:
$ X         : num  786988 781045 777589 775266 786843 ...
$ Y         : num  486608 488691 490089 489293 488068 ...
$ Z         : num  182 128 191 80 131 ...
$ pH        : num  7.93 7.69 7.49 7.66 7.92 7.08 7.24 7.19 7.44 7.37 ...
$ CE        : num  0.775 3.284 3.745 4.072 0.95 ...
$ Nitrate   : int  21 14 18 83 30 42 47 101 85 15 ...
$ NP        : num  19.6 43.6 31.7 18.6 31.7 ...
$ Cl        : num  1.9 21.3 2.56 21.5 3.2 ...
$ HCO3      : num  6.65 4.85 4.4 7.72 4.1 ...
$ CO3       : num  0 0 0 0 0.0736 ...
$ Ca        : num  4.12 7.52 3.48 7.58 4.8 10 4.4 4.6 4.2 7.4 ...
$ Mg        : num  3.94 8.92 2.34 7.1 2.5 ...
$ K         : num  0.1442 0.0759 0.0709 0.3691 0.07 ...
$ Na        : num  2.41 34.55 2.51 44.01 2.1 ...
$ SO4       : num  1.45 23.6 1.2 26.66 2 ...
$ Residu_sec: num  0.496 2.102 2.397 2.606 0.608 ...
</code>```

答:
The problem is when the function try to perform the Anderson-Darling test to a vector of equals values. If you do this, you will get the error:

```<code>require(Johnson)
x = rep(1,n=100)
RE.ADT(x)
</code>```

So, to solve this problem you could check it in the IF session inside the function RE.Johnson:

```<code>    if (xsb.valida[1, i] == 0 & any(xsb[, i]!=xsb[1, i])){
        xsb.adtest[1, i] <- (RE.ADT(xsb[, i])$p)
    }else{
        xsb.adtest[1, i] <- 0
    }
    if (xsl.valida[1, i] == 0 & any(xsl[, i]!=xsl[1, i])) {
        xsl.adtest[1, i] <- (RE.ADT(xsl[, i])$p)
    }else{
        xsl.adtest[1, i] <- 0
    }
    if (xsu.valida[1, i] == 0 & any(xsu[, i]!=xsu[1, i])) {
        xsu.adtest[1, i] <- (RE.ADT(xsu[, i])$p)
    }else{
        xsu.adtest[1, i] <- 0
    }
</code>```

Title: Apply a loop to a data frame

Body:
I'm trying to apply the function RE.Johnson from the Johnson package to a whole data frame df that contains 157 observations of 16 variables and i'd like to loop trough all the dataframe instead of doing it manually.
I've tried the following code but it doesn't work.

lapply(df[1:16], function(x) RE.Johnson(x))

I know it might seem easy for you guys but I'm juste starting with R.
Thanks

EDIT

R provides me the answer Error in RE.ADT(xsl[, i]) : object 'p' not found and the data are not transformed.
And here is a summary of the data:

data.frame':    157 obs. of  16 variables:
$ X         : num  786988 781045 777589 775266 786843 ...
$ Y         : num  486608 488691 490089 489293 488068 ...
$ Z         : num  182 128 191 80 131 ...
$ pH        : num  7.93 7.69 7.49 7.66 7.92 7.08 7.24 7.19 7.44 7.37 ...
$ CE        : num  0.775 3.284 3.745 4.072 0.95 ...
$ Nitrate   : int  21 14 18 83 30 42 47 101 85 15 ...
$ NP        : num  19.6 43.6 31.7 18.6 31.7 ...
$ Cl        : num  1.9 21.3 2.56 21.5 3.2 ...
$ HCO3      : num  6.65 4.85 4.4 7.72 4.1 ...
$ CO3       : num  0 0 0 0 0.0736 ...
$ Ca        : num  4.12 7.52 3.48 7.58 4.8 10 4.4 4.6 4.2 7.4 ...
$ Mg        : num  3.94 8.92 2.34 7.1 2.5 ...
$ K         : num  0.1442 0.0759 0.0709 0.3691 0.07 ...
$ Na        : num  2.41 34.55 2.51 44.01 2.1 ...
$ SO4       : num  1.45 23.6 1.2 26.66 2 ...
$ Residu_sec: num  0.496 2.102 2.397 2.606 0.608 ...

Body:
The problem is when the function try to perform the Anderson-Darling test to a vector of equals values. If you do this, you will get the error:

require(Johnson)
x = rep(1,n=100)
RE.ADT(x)

So, to solve this problem you could check it in the IF session inside the function RE.Johnson:

    if (xsb.valida[1, i] == 0 & any(xsb[, i]!=xsb[1, i])){
        xsb.adtest[1, i] <- (RE.ADT(xsb[, i])$p)
    }else{
        xsb.adtest[1, i] <- 0
    }
    if (xsl.valida[1, i] == 0 & any(xsl[, i]!=xsl[1, i])) {
        xsl.adtest[1, i] <- (RE.ADT(xsl[, i])$p)
    }else{
        xsl.adtest[1, i] <- 0
    }
    if (xsu.valida[1, i] == 0 & any(xsu[, i]!=xsu[1, i])) {
        xsu.adtest[1, i] <- (RE.ADT(xsu[, i])$p)
    }else{
        xsu.adtest[1, i] <- 0
    }


问:
Toggling sync and async behavior in .NET web API
I've been asked to implement something like this:

```<code>public async Task<IHttpActionResult> Get(bool sync)
{
    if(sync)
    {
        ...sync behavior
    } else
    {
        ...async behavior
    }
}
</code>```

Now, I understand the basics of sync/async behavior and threading, and am worried about things that might go wrong (async code running synchronously, thread-blocking,returning an arbitrary Task to match the method signature being generally sloppy, etc...), but not enough to say for certain that this code is a bad idea. So, my question: Is this always bad practice, or are there cases where it can be okay?

答:
Async methods will run synchronously until they reach an await. If the await is waiting for a result, the control is given back.

So there is nothing wrong with your code, as long as the async path uses an await.

But it is important to note, that is an async method has not to wait for any long running operation, it will be executed synchronously! So even if you use an await, there is no guarantee that the control is given back.

Body:
I've been asked to implement something like this:

public async Task<IHttpActionResult> Get(bool sync)
{
    if(sync)
    {
        ...sync behavior
    } else
    {
        ...async behavior
    }
}

Now, I understand the basics of sync/async behavior and threading, and am worried about things that might go wrong (async code running synchronously, thread-blocking,returning an arbitrary Task to match the method signature being generally sloppy, etc...), but not enough to say for certain that this code is a bad idea. So, my question: Is this always bad practice, or are there cases where it can be okay?


问:
D3 Adding dots to dynamic line chart
I have a scrolling line chart that is being updated in realtime as data comes in. Here is the js fiddle for the line chart. https://jsfiddle.net/eLu98a6L/

What I would like to do is replace the line with a dot graph, so each point that comes in would create a dot, and the scrolling feature is maintained.This is the type of chart I would like to create dow jones dot graph and ultimately I would like to remove the line underneath.

This is the code I have used to try and add dots to my graph.

```<code>g.append("g")
.selectAll("dot")
.data(4)
.enter("circle")
.attr("cx", "2")
.attr("cy", "2");
</code>```

So far I haven't had any success. I'm very new to d3, so any help is appreciated. Thanks!

答:
Based on your code an approach for this can be :

```<code>var circleArea = g.append('g'); /* added this to hold all dots in a group */
function tick() {

  // Push a new data point onto the back.
  data.push(random());
  // Redraw the line.

  /* hide the line as you don't need it any more
  d3.select(this)
      .attr("d", line)
      .attr("transform", null);
  */

  circleArea.selectAll('circle').remove(); // this makes sure your out of box dots will be remove.

  /* this add dots based on data */
  circleArea.selectAll('circle')
    .data(data)
    .enter()
         .append('circle')
         .attr('r',3)  // radius of dots
         .attr('fill','black') // color of dots
         .attr('transform',function(d,i){ return 'translate('+x(i)+','+y(d)+')';});

  /* here we can animate dots to translate to left for 500ms */
  circleArea.selectAll('circle').transition().duration(500)
    .ease(d3.easeLinear)
    .attr('transform',function(d,i){
         if(x(i )<=0) {   // this makes sure dots are remove on x=0
              d3.select(this).remove();
         }
         return 'translate('+x(i-1)+','+y(d)+')';
    });

   /* here is rest of your code */
  // Slide it to the left.
  d3.active(this)
      .attr("transform", "translate(" + x(-1) + ",0)")
      .transition()
      .on("start", tick);
  // Pop the old data point off the front.
  data.shift();
}
</code>```

See it in action : https://codepen.io/FaridNaderi/pen/weERBj

hope it helps :)

Title: D3 Adding dots to dynamic line chart

Body:
I have a scrolling line chart that is being updated in realtime as data comes in. Here is the js fiddle for the line chart. https://jsfiddle.net/eLu98a6L/

What I would like to do is replace the line with a dot graph, so each point that comes in would create a dot, and the scrolling feature is maintained.This is the type of chart I would like to create dow jones dot graph and ultimately I would like to remove the line underneath.

This is the code I have used to try and add dots to my graph.

g.append("g")
.selectAll("dot")
.data(4)
.enter("circle")
.attr("cx", "2")
.attr("cy", "2");

So far I haven't had any success. I'm very new to d3, so any help is appreciated. Thanks!

Body:
Based on your code an approach for this can be :

var circleArea = g.append('g'); /* added this to hold all dots in a group */
function tick() {

  // Push a new data point onto the back.
  data.push(random());
  // Redraw the line.

  /* hide the line as you don't need it any more
  d3.select(this)
      .attr("d", line)
      .attr("transform", null);
  */

  circleArea.selectAll('circle').remove(); // this makes sure your out of box dots will be remove.

  /* this add dots based on data */
  circleArea.selectAll('circle')
    .data(data)
    .enter()
         .append('circle')
         .attr('r',3)  // radius of dots
         .attr('fill','black') // color of dots
         .attr('transform',function(d,i){ return 'translate('+x(i)+','+y(d)+')';});

  /* here we can animate dots to translate to left for 500ms */
  circleArea.selectAll('circle').transition().duration(500)
    .ease(d3.easeLinear)
    .attr('transform',function(d,i){
         if(x(i )<=0) {   // this makes sure dots are remove on x=0
              d3.select(this).remove();
         }
         return 'translate('+x(i-1)+','+y(d)+')';
    });

   /* here is rest of your code */
  // Slide it to the left.
  d3.active(this)
      .attr("transform", "translate(" + x(-1) + ",0)")
      .transition()
      .on("start", tick);
  // Pop the old data point off the front.
  data.shift();
}

See it in action : https://codepen.io/FaridNaderi/pen/weERBj

hope it helps :)


问:
How to decode unicode-encoded JSON in PHP with Zend\Json\Json::decode(...)?
I'm writing a client for an API...

```<code>use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();
</code>```

... and get a unicode encoded JSON like this:

```<code>...{"id":"7","title":"\u0438\u043b\u043b\u044e\u0441\u0442\u0440\u0430\u0446\u0438\u0438","short_name":"\u0418\u041b\u041b\u042e\u0421\u0422\u0420\u0410\u0426\u0418\u0418"...
</code>```

First I tried to decode it with json_decode(...). But I didn't find any appropriate method to do this in PHP (without suspect regex based approaches).

Now I'm trying it with Zend\Json\Json::decode(...) and getting following error:

```<code>/var/www/path/to/project/vendor/zendframework/zend-json/src/Json.php:243
Decoding failed: Syntax error
</code>```

How to get a unicode-encoded JSON decoded with Zend\Json?

EDIT

Just notices, that the JSON is broken. It is separated to two parts. The string starts with 1f9e, then the first part, then the string \u043, then the second content part, then 0.

```<code>1f9e <-- What is it?
{"_li...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0
</code>```

答:
As soon as I see this json doesn't seem to be broken. Please consider the next code lines:

```<code>$data = '{"id":"7","title":"\u0438\u043b\u043b\u044e\u0441\u0442\u0440\u0430\u0446\u0438\u0438","short_name":"\u0418\u041b\u041b\u042e\u0421\u0422\u0420\u0410\u0426\u0418\u0418"}';

$json = json_decode($data);

header('Content-Type: text/html; charset=utf-8');
echo $json->title;
echo "<br/>";
echo $json->short_name;
</code>```

the result is:

```<code>иллюстрации
ИЛЛЮСТРАЦИИ
</code>```

Body:
I'm writing a client for an API...

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();

... and get a unicode encoded JSON like this:

...{"id":"7","title":"\u0438\u043b\u043b\u044e\u0441\u0442\u0440\u0430\u0446\u0438\u0438","short_name":"\u0418\u041b\u041b\u042e\u0421\u0422\u0420\u0410\u0426\u0418\u0418"...

First I tried to decode it with json_decode(...). But I didn't find any appropriate method to do this in PHP (without suspect regex based approaches).

Now I'm trying it with Zend\Json\Json::decode(...) and getting following error:

/var/www/path/to/project/vendor/zendframework/zend-json/src/Json.php:243
Decoding failed: Syntax error

How to get a unicode-encoded JSON decoded with Zend\Json?

EDIT

Just notices, that the JSON is broken. It is separated to two parts. The string starts with 1f9e, then the first part, then the string \u043, then the second content part, then 0.

1f9e <-- What is it?
{"_li...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0

Body:
As soon as I see this json doesn't seem to be broken. Please consider the next code lines:

$data = '{"id":"7","title":"\u0438\u043b\u043b\u044e\u0441\u0442\u0440\u0430\u0446\u0438\u0438","short_name":"\u0418\u041b\u041b\u042e\u0421\u0422\u0420\u0410\u0426\u0418\u0418"}';

$json = json_decode($data);

header('Content-Type: text/html; charset=utf-8');
echo $json->title;
echo "<br/>";
echo $json->short_name;

the result is:

иллюстрации
ИЛЛЮСТРАЦИИ


问:
Python pyautogui window handle
Using pyautogui is there a way to get a handle to a window so that I can ensure that a click is performed on that window only? In other words, if my window isn't in focus, then the click does not occur. Additionally, if my window isn't in focus then I bring it into focus and then perform the actions.

The way to identify a window could be an ID, window title etc similar to this https://autohotkey.com/docs/commands/WinGet.htm

Is there any other Python module that supports this kind of functionality?

答:
PyAutoGui itself says, in its documentation's FAQ section,

Q: Can PyAutoGUI figure out where windows are or which windows are visible? Can it focus, maximize, minimize windows? Can it read the window titles?

A: Unfortunately not, but these are the next features planned for PyAutoGUI. This functionality is being implemented in a Python package named PyGetWindow, which will be included in PyAutoGUI when complete.

Now, if you go on over to PyGetWindow's repo, you'll see there's no code there yet, but there is a random_notes.txt file, with this pointer:

Finding window titles on Windows:

http://stackoverflow.com/questions/37501191/how-to-get-windows-window-names-with-ctypes-in-python

which has some interesting information.  (I haven't tried it yet.)

Title: Python pyautogui window handle


问:
How to delete the first 2 lines from string in C#?
I have a string like the following:

```<code>string myString = @"This is the first line

This is the third line as the 2nd is empty
The string continues

Anso so on ...
...
..
.";
</code>```

I know that I can split this into an array, delete the first 2 elements and then rebuild my string from that array but I'm looking for something much more simple.

答:
```<code>myString = String.Join("\n", myString.Split('\n').Skip(2));
</code>```

Here's @maccettura's fiddle of that code with your string literal.

To break that down:

Split on newlines, return a sequence of segments -- the segments are lines, since we split on newline:

```<code>myString.Split('\n')
</code>```

Skip the first two segments, return the rest of the a sequence

```<code>.Skip(2)
</code>```

And rejoin the shorter sequence with newlines:

```<code>String.Join("\n", ...
</code>```

This is just what you were contemplating doing in a loop, but with Skip(), it can be expressed as a readable one-liner.

Lastly, here's @user1242967 's version of the Split() call, which will handle \r\n newlines:

```<code>myString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)
</code>```

Body:
I have a string like the following:

string myString = @"This is the first line

This is the third line as the 2nd is empty
The string continues

Anso so on ...
...
..
.";

I know that I can split this into an array, delete the first 2 elements and then rebuild my string from that array but I'm looking for something much more simple.

Body:
myString = String.Join("\n", myString.Split('\n').Skip(2));

Here's @maccettura's fiddle of that code with your string literal.

To break that down:

Split on newlines, return a sequence of segments -- the segments are lines, since we split on newline:

myString.Split('\n')

Skip the first two segments, return the rest of the a sequence

.Skip(2)

And rejoin the shorter sequence with newlines:

String.Join("\n", ...

This is just what you were contemplating doing in a loop, but with Skip(), it can be expressed as a readable one-liner.

Lastly, here's @user1242967 's version of the Split() call, which will handle \r\n newlines:

myString.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None)


问:
Is there a way to install java on Oracle 11g XE?
I am using the database Oracle 11g Express Edition (XE) and when I try to create a java source object it returns me an error:

ORA-29538: Java not installed

The source code is simple:

```<code>create or replace and compile java source named hello AS
  public class Hello {
    public static String hello() { return "Hello!"; }
  };
</code>```

I found at Oracle's documentation that Oracle XE does not include Java.

Does anybody know if it is possible to "install" Java on it ?

答:
And if you have the full licensed version of Oracle, and need to install the JVM in Oracle, you can invoke as sysdba:

```<code> @?/javavm/install/initjvm.sql
</code>```

and you may also need to run

```<code> @?/rdbms/admin/catjava.sql
</code>```

The website https://itkbs.wordpress.com/2014/02/15/how-to-install-java-in-oracle-database-ora-29538/ taught me the first part; I still had errors with a Java class schedFileWatcherJava not found, which the second script fixed.

You can verify if Java is installed with this query from that website:

```<code>select comp_name, version, status from dba_registry;
</code>```

which will list JServer JAVA Virtual Machine as part of the results if Java is installed.

Body:
I am using the database Oracle 11g Express Edition (XE) and when I try to create a java source object it returns me an error:

ORA-29538: Java not installed

The source code is simple:

create or replace and compile java source named hello AS
  public class Hello {
    public static String hello() { return "Hello!"; }
  };

I found at Oracle's documentation that Oracle XE does not include Java.

Does anybody know if it is possible to "install" Java on it ?

Body:
And if you have the full licensed version of Oracle, and need to install the JVM in Oracle, you can invoke as sysdba:

 @?/javavm/install/initjvm.sql

and you may also need to run

 @?/rdbms/admin/catjava.sql

The website https://itkbs.wordpress.com/2014/02/15/how-to-install-java-in-oracle-database-ora-29538/ taught me the first part; I still had errors with a Java class schedFileWatcherJava not found, which the second script fixed.

You can verify if Java is installed with this query from that website:

select comp_name, version, status from dba_registry;

which will list JServer JAVA Virtual Machine as part of the results if Java is installed.


问:
Custom Calculator with Spree
I have some problem to create a custom calculator. I follow the instructions here:

http://guides.spreecommerce.org/developer/calculators.html.

I have my calculator inside spree/calculator:

```<code>class CustomCalculator < Spree::Calculator
  def self.description
    # Human readable description of the calculator
  end

  def compute(object=nil)
    p "Test"
    10.0
    # Returns the value after performing the required calculation
  end
end
</code>```

and in spree.rb I added:

```<code>config = Rails.application.config
config.spree.calculators.tax_rates << CustomCalculator
</code>```

but when I run the server, I receive this server:

```<code>config/initializers/spree.rb:24:in `<top (required)>': uninitialized constant CustomCalculator (NameError)
</code>```

I already looked around and tries different ways to create my custom calculator... but nothing was right.

I'm using Spree 3.1.

答:
Create a file with class_name in models/spree/calculators folder

    module Spree
      class Calculator::CustomCalculator < Calculator
        def self.description
          # Human readable description of the calculator
        end

        def compute(object=nil)
          p "Test"
          10.0
          # Returns the value after performing the required calculation
        end
      end
    end
```

In spree.rb add Rails.application.config.spree.calculators.tax_rates << Spree::Calculator::CustomCalculator

Title: Custom Calculator with Spree

Body:
I have some problem to create a custom calculator. I follow the instructions here:

http://guides.spreecommerce.org/developer/calculators.html.

I have my calculator inside spree/calculator:

class CustomCalculator < Spree::Calculator
  def self.description
    # Human readable description of the calculator
  end

  def compute(object=nil)
    p "Test"
    10.0
    # Returns the value after performing the required calculation
  end
end

and in spree.rb I added:

config = Rails.application.config
config.spree.calculators.tax_rates << CustomCalculator

but when I run the server, I receive this server:

config/initializers/spree.rb:24:in `<top (required)>': uninitialized constant CustomCalculator (NameError)

I already looked around and tries different ways to create my custom calculator... but nothing was right.

I'm using Spree 3.1.

Body:
Create a file with class_name in models/spree/calculators folder

    module Spree
      class Calculator::CustomCalculator < Calculator
        def self.description
          # Human readable description of the calculator
        end

        def compute(object=nil)
          p "Test"
          10.0
          # Returns the value after performing the required calculation
        end
      end
    end

In spree.rb add Rails.application.config.spree.calculators.tax_rates << Spree::Calculator::CustomCalculator


问:
Change style of a EnhancedGrid line on "onRowClick" event
I want to change a color of grid line but without selecting it. It means I cannot use onStyleRow event as it reacts only for 'selected', 'odd' or 'over' event.

Any ideas?

thx

答: I found an updateRowStyles(idxRow) function, but no idea how to use it (how to pass syles etc.) and not sure if it will solve my problem</p>


问:
No 'Access-Control-Allow-Origin' is present on requested resource
I am having a weird issue where my client side request is telling me I have no 'Access-Control-Allow-Origin' present when making an HTTP POST request to a java servlet I have hosted and live. I have made sure to add the necessary headers in my response to clear up CORS requests issues but it does not seem to be recognizing the headers.

Here is my angular $http.post request I am making from the client side:

```<code>var parameter = JSON.stringify(details);
            var req = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: parameter
            }

            $http.post(localurl, req).
              then(function(response) {

              });
</code>```

Here is the error I am getting from chrome:

```<code>Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.
</code>```

Here is the beginning of my java servlet doPost function:

```<code> @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) {
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        res.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
</code>```

I have been searching various stackoverflow questions and those response headers I am setting in my servlet should clear up the CORS requests issues but it does not seem to be recognizing the response headers I am setting at the beginning of the doPost function. Any and all help is very appreciated. Thanks in advance.

答:
The problem is on your back-end, if yours is nodejs, should be like this way to allow Access-Control-Allow-Origin: </p>

```<code>app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
</code>```

Body:
I am having a weird issue where my client side request is telling me I have no 'Access-Control-Allow-Origin' present when making an HTTP POST request to a java servlet I have hosted and live. I have made sure to add the necessary headers in my response to clear up CORS requests issues but it does not seem to be recognizing the headers.

Here is my angular $http.post request I am making from the client side:

var parameter = JSON.stringify(details);
            var req = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                data: parameter
            }

            $http.post(localurl, req).
              then(function(response) {

              });

Here is the error I am getting from chrome:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.

Here is the beginning of my java servlet doPost function:

 @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) {
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        res.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");

I have been searching various stackoverflow questions and those response headers I am setting in my servlet should clear up the CORS requests issues but it does not seem to be recognizing the response headers I am setting at the beginning of the doPost function. Any and all help is very appreciated. Thanks in advance.

Body:
The problem is on your back-end, if yours is nodejs, should be like this way to allow Access-Control-Allow-Origin:

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});


问:
MySQL query splitting unexpectedly in Bash Script
I am having issues and not understanding what the underlying cause is.

I have a table that has these three fields:

```<code>______________________________________________
|   cid    |    order_id    |    TxRefNum    |
----------------------------------------------
</code>```

I am making a simple call in my bash script (there is literally no other code to start with)

```<code>#!/bin/bash

mysql --login-path=main-data -e "SELECT
    cid,
    order_id,
    TxRefNum
FROM database.orders_temp" |

while read this that other; do

    echo "$this  ||  $that  ||  $other"
done
</code>```

I would expect to see the following:

```<code>__________________________________________________________
|    29    |    F0VIc - CHATEAU ROOFIN    |   5555555    |
----------------------------------------------------------
</code>```

Instead my script is splitting the string $that into two different strings ..  The echo is actually:

```<code>___________________________________________________
|    29    |    F0VIc    |    - CHATEAU ROOFIN    |
---------------------------------------------------
</code>```

Do I have to set a delimiter when setting my variables in my while loop??  I am truly stumped!!

答:
Getting output from the mysql command formatted in an intelligent way is problematic. In your case bash is interpreting the  as a delimiter. You need to split a different way. I was able to get this working. You'll note the | in the query as well at the IFS line at the tope

```<code>#!/bin/bash

IFS='|' # set the delimiter
mysql --login-path=main-data -e "SELECT
    29 as cid, '|',
    'F0VIc - CHATEAU ROOFIN' as order_id,
    '|',
    5555555 as TxRefNum
FROM dual" |
while read this that other; do
    echo "$this  ||  $that  ||  $other"
done
</code>```

Body:
I am having issues and not understanding what the underlying cause is.

I have a table that has these three fields:

______________________________________________
|   cid    |    order_id    |    TxRefNum    |
----------------------------------------------

I am making a simple call in my bash script (there is literally no other code to start with)

#!/bin/bash

mysql --login-path=main-data -e "SELECT
    cid,
    order_id,
    TxRefNum
FROM database.orders_temp" |

while read this that other; do

    echo "$this  ||  $that  ||  $other"
done

I would expect to see the following:

__________________________________________________________
|    29    |    F0VIc - CHATEAU ROOFIN    |   5555555    |
----------------------------------------------------------

Instead my script is splitting the string $that into two different strings ..  The echo is actually:

___________________________________________________
|    29    |    F0VIc    |    - CHATEAU ROOFIN    |
---------------------------------------------------

Do I have to set a delimiter when setting my variables in my while loop??  I am truly stumped!!

Body:
Getting output from the mysql command formatted in an intelligent way is problematic. In your case bash is interpreting the  as a delimiter. You need to split a different way. I was able to get this working. You'll note the | in the query as well at the IFS line at the tope

#!/bin/bash

IFS='|' # set the delimiter
mysql --login-path=main-data -e "SELECT
    29 as cid, '|',
    'F0VIc - CHATEAU ROOFIN' as order_id,
    '|',
    5555555 as TxRefNum
FROM dual" |
while read this that other; do
    echo "$this  ||  $that  ||  $other"
done


问:
JSR-330 @Scope and Spring Don't Match
The java doc for the JSR-330 Scope annotation states "uses the instance for one injection, and then forgets it" implying that the instance is of scope prototype and the Singleton annotation is intended to create the singleton that is the default behavior with spring.  So the question is, Why, when I use the Named annotation rather than the Spring Component annotation does Spring not follow the JSR guidelines and scope the bean as prototype?  It seems to me like it should.

I would like to keep the spring dependencies consolidated to a single module and use JSR-330 everywhere else so If needed I can easily switch later.

答:
So this is how I made what I want work:

```<code>/**
 * JSR-330 assumes the default scope is prototype, however Spring IOC defaults to singleton scope.
 * This annotation is used to force the JSR-330 standard on the spring application.
 *
 * This is done by registering this annotation with the spring bean factory post processor.
 * ```
 *
 * public class PrototypeBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
 *
 *   public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
 *      for (String beanName : factory.getBeanDefinitionNames()) {
 *          if (factory.findAnnotationOnBean(beanName, Prototype.class) != null) {
 *              BeanDefinition beanDef = factory.getBeanDefinition(beanName);
 *              beanDef.setScope("prototype");
 *          }
 *      }
 *   }
 * }
 *
 * ```
 *
 * @see javax.inject.Scope @Scope
 */
@Scope
@Documented
@Retention(RUNTIME)
public @interface Prototype {}
</code>```

I put this annotation in my core jar and then let the spring-boot app module do the work of processing the annotation.

It works well for me but I am happy to hear any other suggestions.

Title: JSR-330 @Scope and Spring Don't Match

Body:
So this is how I made what I want work:

/**
 * JSR-330 assumes the default scope is prototype, however Spring IOC defaults to singleton scope.
 * This annotation is used to force the JSR-330 standard on the spring application.
 *
 * This is done by registering this annotation with the spring bean factory post processor.
 * <pre>
 * <code>
 * public class PrototypeBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
 *
 *   public void postProcessBeanFactory(ConfigurableListableBeanFactory factory) throws BeansException {
 *      for (String beanName : factory.getBeanDefinitionNames()) {
 *          if (factory.findAnnotationOnBean(beanName, Prototype.class) != null) {
 *              BeanDefinition beanDef = factory.getBeanDefinition(beanName);
 *              beanDef.setScope("prototype");
 *          }
 *      }
 *   }
 * }
 * </code>
 * </pre>
 *
 * @see javax.inject.Scope @Scope
 */
@Scope
@Documented
@Retention(RUNTIME)
public @interface Prototype {}

I put this annotation in my core jar and then let the spring-boot app module do the work of processing the annotation.

It works well for me but I am happy to hear any other suggestions.


问:
How can i remove “addDisposableTo” when i used RxSwift
when i use RxSwift, i must write many many addDisposableTo, how can i remove it?</p>

```<code>usernameTextField.rx.text.orEmpty
            .bindTo(viewModel.username)
            .addDisposableTo(disposeBag)

    passwordTextField.rx.text.orEmpty
        .bindTo(viewModel.password)
        .addDisposableTo(disposeBag)

    repeatPasswordTextField.rx.text.orEmpty
        .bindTo(viewModel.repeatPassword)
        .addDisposableTo(disposeBag)
</code>```

答:
I have created a code snippet in XCode for the subscription code and so its very handy that I don't have to type it in every time

I'm afraid since the dispose bag is a property that you tie to the object that is subscribing there is not much you can save in terms of boiler plate code.

May be you could write a convinience wrapper but still is it worth it? In my opinion XCode snippets works just fine

Body:
when i use RxSwift, i must write many many addDisposableTo, how can i remove it?

usernameTextField.rx.text.orEmpty
            .bindTo(viewModel.username)
            .addDisposableTo(disposeBag)

    passwordTextField.rx.text.orEmpty
        .bindTo(viewModel.password)
        .addDisposableTo(disposeBag)

    repeatPasswordTextField.rx.text.orEmpty
        .bindTo(viewModel.repeatPassword)
        .addDisposableTo(disposeBag)


问:
Update table column using sum()
I am trying to do two thing with my SQL code. I want it to copy data from another column (hours) , that’s located in another table (works- table), and place it into a new column (numHours) in a different table (Employee- table). However, I want it to use the sum of the hours worked for each employee id (eid) and then place that sum into the new column.

This is what I wrote, but two things are wrong. When I execute just the select statement every employee id has the same number of hours worked. When I run the whole statement I get this error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

```<code>UPDATE Employee
SET numHours= (SELECT sum(w.hours) AS totalHours From works w, Employee e WHERE
numHours IS NULL AND e.eid = w.eid Group by w.eid);
</code>```

These are my tables

```<code>CREATE TABLE Employee(
eid INT,
ename VARCHAR(30),
age INT,
salary INT,

CONSTRAINT Pk_key_eid PRIMARY KEY (eid)
);

CREATE TABLE Department(
did INT,
dname VARCHAR(30),
budget int,
managerid INT,

CONSTRAINT Validate_managerid CHECK(managerid < 1000),
CONSTRAINT Pk_key_did PRIMARY KEY (did)
);

CREATE TABLE Works(
eid INT,
did INT,
hours INT,

CONSTRAINT fk_key_eid FOREIGN KEY (eid) REFERENCES Employee (eid) ON DELETE CASCADE,
CONSTRAINT fk_key_Did  FOREIGN KEY (did) REFERENCES Department (did) ON DELETE CASCADE
);
</code>```

How would I properly code this?

答:
I believe you want this:

```<code>UPDATE Employee
    SET numHours= (SELECT sum(w.hours) From works w WHERE employee.eid = w.eid)
    WHERE numHours IS NULL;
</code>```

Notes:

The condition on numHours belongs in the UPDATE, not the subquery.

You want a correlated query, not a full join (and don't use commas in the FROM clause ever!).

There is no need for a column alias in the subquery.

There is no need for GROUP BY in the subquery.

Title: Update table column using sum()

Body:
I am trying to do two thing with my SQL code. I want it to copy data from another column (hours) , that’s located in another table (works- table), and place it into a new column (numHours) in a different table (Employee- table). However, I want it to use the sum of the hours worked for each employee id (eid) and then place that sum into the new column.

This is what I wrote, but two things are wrong. When I execute just the select statement every employee id has the same number of hours worked. When I run the whole statement I get this error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

UPDATE Employee
SET numHours= (SELECT sum(w.hours) AS totalHours From works w, Employee e WHERE
numHours IS NULL AND e.eid = w.eid Group by w.eid);

These are my tables

CREATE TABLE Employee(
eid INT,
ename VARCHAR(30),
age INT,
salary INT,

CONSTRAINT Pk_key_eid PRIMARY KEY (eid)
);

CREATE TABLE Department(
did INT,
dname VARCHAR(30),
budget int,
managerid INT,

CONSTRAINT Validate_managerid CHECK(managerid < 1000),
CONSTRAINT Pk_key_did PRIMARY KEY (did)
);

CREATE TABLE Works(
eid INT,
did INT,
hours INT,

CONSTRAINT fk_key_eid FOREIGN KEY (eid) REFERENCES Employee (eid) ON DELETE CASCADE,
CONSTRAINT fk_key_Did  FOREIGN KEY (did) REFERENCES Department (did) ON DELETE CASCADE
);

How would I properly code this?

Body:
I believe you want this:

UPDATE Employee
    SET numHours= (SELECT sum(w.hours) From works w WHERE employee.eid = w.eid)
    WHERE numHours IS NULL;

Notes:

The condition on numHours belongs in the UPDATE, not the subquery.

You want a correlated query, not a full join (and don't use commas in the FROM clause ever!).

There is no need for a column alias in the subquery.

There is no need for GROUP BY in the subquery.


问:
Java scsi access
I'd like to port a Linux C program to Java. This program controls a camera which is connected to the PC with a USB cable. The C code uses Linux SCSI Generic (sg).

Sample code from the C program:

```<code>#include <linux/../scsi/sg.h>

...

static int scsi_write(int sg_fd, uint8_t *cmd, uint32_t cmdLen,
               uint8_t *buf, uint32_t bufLen) {

    sg_io_hdr_t io;
    int r;

    memset(&io, 0, sizeof(io));

    io.interface_id = 'S';
    io.cmd_len = cmdLen;

    ...
    r = ioctl(sg_fd, SG_IO, &io);
    ...
}
</code>```

Is there a way to port this program to Java? I was searching for a cross-platform SCSI library written for Java, but found none. I was also searching for a JNI over SCSI/sg, also no luck.

答: You may have more luck with a Java based USB library, like an implementation of JSR080 (javax.usb). You can find the reference implementation here, but only the Linux implementation is kind of production ready.</p>

Title: Java scsi access

Body:
I'd like to port a Linux C program to Java. This program controls a camera which is connected to the PC with a USB cable. The C code uses Linux SCSI Generic (sg).

Sample code from the C program:

#include <linux/../scsi/sg.h>

...

static int scsi_write(int sg_fd, uint8_t *cmd, uint32_t cmdLen,
               uint8_t *buf, uint32_t bufLen) {

    sg_io_hdr_t io;
    int r;

    memset(&io, 0, sizeof(io));

    io.interface_id = 'S';
    io.cmd_len = cmdLen;

    ...
    r = ioctl(sg_fd, SG_IO, &io);
    ...
}

Is there a way to port this program to Java? I was searching for a cross-platform SCSI library written for Java, but found none. I was also searching for a JNI over SCSI/sg, also no luck.


问:
Disable past date code in jquery is not working?
I link the jquery file in my page that can simply show datepicker but the function that have code of disabling past date is not working. When i code for displaying specific date is also not working. feedback will be high appreciated.</p>

```<code><script>
   $("#datepicker").datepicker();

   $(document).ready(function(){
        $("#datepicker").datepicker({
            minDate: -0
        });
    });
</script>
</code>```

答:
You can set minDate: 0

```<code><script>
   $(document).ready(function(){
        $("#datepicker").datepicker({
            minDate: 0
        });
    });
</script>
</code>```

Body:
You can set minDate: 0

<script>
   $(document).ready(function(){
        $("#datepicker").datepicker({
            minDate: 0
        });
    });
</script>