问:
export entire excel sheet to sql table with VBA
having issue sending entire sheet to sql table. I have tried 2 different ways as shown below. both work in different ways. Ultimately I am struggling with exporting multiple rows of data to sql DB

this 1st way I can import multiple rows to sql table successfully with one click of the button, only problem is that the StartTime and FinishTime come to sql table as 00:00:00 even if I enter a normal time in excel

```<code>Sub Button1_Click()
  Dim conn As New ADODB.Connection
  Dim iRowNo As Integer
  Dim sEventDate, sID, sDeptCode, sOpCode, sStartTime, sFinishTime, sUnits  As String

  With Sheets("Sheet1")
    'Open a connection to SQL Server
    conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=PTW;Integrated Security=SSPI;"
    'Skip the header row
    iRowNo = 2
    'Loop until empty cell in FirstName
    Do Until .Cells(iRowNo, 1) = ""
    sEventDate = .Cells(iRowNo, 1)
    sID = .Cells(iRowNo, 2)
    sDeptCode = .Cells(iRowNo, 3)
    sOpCode = .Cells(iRowNo, 4)
    sStartTime = .Cells(iRowNo, 5).Text
    sFinishTime = .Cells(iRowNo, 6).Text
    sUnits = .Cells(iRowNo, 7)
    'Generate and execute sql statement to import the excel rows to SQL Server table
    conn.Execute "insert into dbo.TimeLog (EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', cast('" & dStartTime & "' as datetime), cast('" & dFinishTime & "' as datetime), '" & sUnits & "')"

    iRowNo = iRowNo + 1

    Loop

    MsgBox "Data Successfully Exported."
    conn.Close
    Set conn = Nothing
  End With
End Sub
</code>```

this 2nd way works and sends the StartTime and FinishTime exactly as it is in excel table, but it only allows me to send one row to sql table at a time

```<code>Sub Button1_Click()
  Dim conn As ADODB.Connection
  Dim cmd As ADODB.Command
  Dim strSQL As String

  strSQL = "INSERT INTO dbo.TimeLog" & _
     "(EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) " & _
     "VALUES (?,?,?,?,?,?,?)"

Set conn = New ADODB.Connection
  conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=PTW;Integrated Security=SSPI;"

iRowNo = 1

Set cmd = New ADODB.Command

  cmd.ActiveConnection = conn
  cmd.CommandType = adCmdText
  cmd.CommandText = strSQL

With Sheets("Sheet1")
  'Loop until empty cell in FirstName
   Do Until .Cells(iRowNo, 1) = ""

  cmd.Parameters.Append _
    cmd.CreateParameter("pEventDate", adVarChar, adParamInput, 8, .Cells(iRowNo, 1))
  cmd.Parameters.Append _
    cmd.CreateParameter("pID", adInteger, adParamInput, , .Cells(iRowNo, 2))
  cmd.Parameters.Append _
    cmd.CreateParameter("pDeptCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 3))
  cmd.Parameters.Append _
    cmd.CreateParameter("pOpCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 4))
  cmd.Parameters.Append _
    cmd.CreateParameter("pStartTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 5))
  cmd.Parameters.Append _
    cmd.CreateParameter("pFinishTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 6))
  cmd.Parameters.Append _
    cmd.CreateParameter("pUnits", adInteger, adParamInput, , .Cells(iRowNo, 7))

  cmd.Execute

  iRowNo = iRowNo + 1
  Loop

  MsgBox "Data Successfully Exported"

End With

  conn.Close
  Set conn = Nothing
End Sub
</code>```

答:
you must cast the value. In mssql, yourt time value is recognized as string.

cast('8:00:00' as datetime)

```<code>conn.Execute "insert into dbo.TimeLog (EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', cast('" & dStartTime & "' as datetime), cast('" & dFinishTime & "' as datetime), '" & sUnits & "')"
</code>```

Body:
having issue sending entire sheet to sql table. I have tried 2 different ways as shown below. both work in different ways. Ultimately I am struggling with exporting multiple rows of data to sql DB

this 1st way I can import multiple rows to sql table successfully with one click of the button, only problem is that the StartTime and FinishTime come to sql table as 00:00:00 even if I enter a normal time in excel

Sub Button1_Click()
  Dim conn As New ADODB.Connection
  Dim iRowNo As Integer
  Dim sEventDate, sID, sDeptCode, sOpCode, sStartTime, sFinishTime, sUnits  As String

  With Sheets("Sheet1")
    'Open a connection to SQL Server
    conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=PTW;Integrated Security=SSPI;"
    'Skip the header row
    iRowNo = 2
    'Loop until empty cell in FirstName
    Do Until .Cells(iRowNo, 1) = ""
    sEventDate = .Cells(iRowNo, 1)
    sID = .Cells(iRowNo, 2)
    sDeptCode = .Cells(iRowNo, 3)
    sOpCode = .Cells(iRowNo, 4)
    sStartTime = .Cells(iRowNo, 5).Text
    sFinishTime = .Cells(iRowNo, 6).Text
    sUnits = .Cells(iRowNo, 7)
    'Generate and execute sql statement to import the excel rows to SQL Server table
    conn.Execute "insert into dbo.TimeLog (EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', cast('" & dStartTime & "' as datetime), cast('" & dFinishTime & "' as datetime), '" & sUnits & "')"

    iRowNo = iRowNo + 1

    Loop

    MsgBox "Data Successfully Exported."
    conn.Close
    Set conn = Nothing
  End With
End Sub

this 2nd way works and sends the StartTime and FinishTime exactly as it is in excel table, but it only allows me to send one row to sql table at a time

Sub Button1_Click()
  Dim conn As ADODB.Connection
  Dim cmd As ADODB.Command
  Dim strSQL As String

  strSQL = "INSERT INTO dbo.TimeLog" & _
     "(EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) " & _
     "VALUES (?,?,?,?,?,?,?)"

Set conn = New ADODB.Connection
  conn.Open "Provider=SQLOLEDB;Data Source=db\db1;Initial Catalog=PTW;Integrated Security=SSPI;"

iRowNo = 1

Set cmd = New ADODB.Command

  cmd.ActiveConnection = conn
  cmd.CommandType = adCmdText
  cmd.CommandText = strSQL

With Sheets("Sheet1")
  'Loop until empty cell in FirstName
   Do Until .Cells(iRowNo, 1) = ""

  cmd.Parameters.Append _
    cmd.CreateParameter("pEventDate", adVarChar, adParamInput, 8, .Cells(iRowNo, 1))
  cmd.Parameters.Append _
    cmd.CreateParameter("pID", adInteger, adParamInput, , .Cells(iRowNo, 2))
  cmd.Parameters.Append _
    cmd.CreateParameter("pDeptCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 3))
  cmd.Parameters.Append _
    cmd.CreateParameter("pOpCode", adVarChar, adParamInput, 2, .Cells(iRowNo, 4))
  cmd.Parameters.Append _
    cmd.CreateParameter("pStartTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 5))
  cmd.Parameters.Append _
    cmd.CreateParameter("pFinishTime", adDBTime, adParamInput, 0, .Cells(iRowNo, 6))
  cmd.Parameters.Append _
    cmd.CreateParameter("pUnits", adInteger, adParamInput, , .Cells(iRowNo, 7))

  cmd.Execute

  iRowNo = iRowNo + 1
  Loop

  MsgBox "Data Successfully Exported"

End With

  conn.Close
  Set conn = Nothing
End Sub

Body:
you must cast the value. In mssql, yourt time value is recognized as string.

cast('8:00:00' as datetime)

conn.Execute "insert into dbo.TimeLog (EventDate, ID, DeptCode, Opcode, StartTime, FinishTime, Units) values ('" & sEventDate & "', '" & sID & "', '" & sDeptCode & "', '" & sOpCode & "', cast('" & dStartTime & "' as datetime), cast('" & dFinishTime & "' as datetime), '" & sUnits & "')"


来源: stackexchange

问:
SeekBar on Navigation Drawer
I'm trying to use the seekbar in the navigation drawer. What's my mistake? In the application without the navigation drawer there is no problem. Thank you.

```<code>public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

    TextView textView;
    SeekBar seekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    seekBar = (SeekBar) findViewById(R.id.seekbar);
    textView = (TextView) findViewById(R.id.txtView);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            textView.setText(String.valueOf(progress));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
</code>```

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
</code>```

答:
I suppose your Seek bar is in Header View of Navigation Drawer in That Case You may :

```<code>        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View header = navigationView.getHeaderView(0);
        profile_name = (TextView) header.findViewById(R.id.profile_name);
        profile_email = (TextView) header.findViewById(R.id.profile_email);
        profile_image = (ImageView) header.findViewById(R.id.imageView);
        setNavigationHeader();
</code>```

You need to get the view of Header first and then find your Seek bar in it

If your view is not in header then this won't work.

You need to create your own Custom Navigation Drawer

ContentLicense: CC BY-SA 3.0

Title: SeekBar on Navigation Drawer

Body:
I'm trying to use the seekbar in the navigation drawer. What's my mistake? In the application without the navigation drawer there is no problem. Thank you.

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {

    TextView textView;
    SeekBar seekBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    seekBar = (SeekBar) findViewById(R.id.seekbar);
    textView = (TextView) findViewById(R.id.txtView);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            textView.setText(String.valueOf(progress));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference

Body:
I suppose your Seek bar is in Header View of Navigation Drawer in That Case You may :

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        View header = navigationView.getHeaderView(0);
        profile_name = (TextView) header.findViewById(R.id.profile_name);
        profile_email = (TextView) header.findViewById(R.id.profile_email);
        profile_image = (ImageView) header.findViewById(R.id.imageView);
        setNavigationHeader();

You need to get the view of Header first and then find your Seek bar in it

If your view is not in header then this won't work.

You need to create your own Custom Navigation Drawer


问:
Why width: 0 doesn't work
In @media screen and (max-width: 700px), I set aside {width: 0}, but it doesn't disappear. After resizing, the window remains as null space with width: 52px, why is this happening, and how can I fix it?

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    opacity: 0;
    width: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
    <div class="wrapper">
      <header>HEADER</header>
      <main>
        <section>SECTION</section>
        <aside>ASIDE</aside>
      </main>
      <footer>FOOTER</footer>
    </div>
  </body>
</html></code>```

答:
If you don't want to use display: none you can add this:

```<code>@media screen and (max-width: 700px) {
  aside {
    opacity: 0;
    width: 0;
    border: none;
    font-size: 0;
  }
}
</code>```

Title: Why width: 0 doesn't work

Body:
In @media screen and (max-width: 700px), I set aside {width: 0}, but it doesn't disappear. After resizing, the window remains as null space with width: 52px, why is this happening, and how can I fix it?

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    opacity: 0;
    width: 0;
  }
}

      HEADER

SECTION

        ASIDE

      FOOTER

Body:
If you don't want to use display: none you can add this:

@media screen and (max-width: 700px) {
  aside {
    opacity: 0;
    width: 0;
    border: none;
    font-size: 0;
  }
}


问:
What is the difference between componentWillMount and componentDidMount in ReactJS?
I looked at Facebook's documentation at (React.Component)  and it mentions how componentWillMount is invoked on the client/server whereas componentDidMount is invoked only on the client. What does componentWillMount do to the server?

答:
As per the documentation ( https://facebook.github.io/react/docs/react-component.html )

Methods prefixed with will are called right before something happens
and

Methods prefixed with did are called right after something happens.

ContentLicense: CC BY-SA 4.0


问:
Movie DB - storage of Actors / actress / Tags?
Creating a movie db and I dont like the idea of giving each actor/actress and also each tag its own row as if there are 10 million moives total, each has a cast of atleast 20-30 people we will have 200-300 million rows in the table.

And it gets more complex with tags which can be unlimited per movie. So how to best store these 3 items? Ideally these can be modeled as a Many to Many but still it will have hundreds of millions of rows. Any better suggestions on storing these? I am using MySQL.

I would dump it all in a textfile but I need to link actors between movies and do some analytics also and allow users to rate actors find movies by tag, etc so need to use a DB.

答:
10 million movies w/ 20 to 30 cast members each (although the number sound higher than real life) will invariably lead to 200-300 million associations.  If you're storing your data in a relational database, each association will naturally be one row in a table linking movies to actors.  Each row will be very small (two columns - movie PK and actor PK; possibly an extra surrogate key column); the bulk of the data will be stored in the movies and actors table.

Any other solution (in an SQL database) will store the same amount of data in a less optimal format.

ContentLicense: CC BY-SA 2.5


问:
Disallow Twitter Bootstrap modal window from closing
I am creating a modal window using Twitter Bootstrap. The default behavior is if you click outside the modal area, the modal will automatically close. I would like to disable that -- i.e. not close the modal window when clicking outside the modal.

Can someone share jQuery code to do this?

答:
```<code><button type="button" class="btn btn-info btn-md" id="myBtn3">Static
Modal</button>

<!-- Modal -->
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">×</button>
      <h4 class="modal-title">Static Backdrop</h4>
    </div>
    <div class="modal-body">
      <p>You cannot click outside of this modal to close it.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-
      dismiss="modal">Close</button>
    </div>
   </div>
  </div>
</div>
   <script>
    $("#myBtn3").click(function(){
     $("#myModal3").modal({backdrop: "static"});
    });
   });
  </script>
</code>```


问:
Rewriting in simple theorem proof
I wrote a definition of group in Idris:

```<code>data Group: Type -> Type where
    Unit: (x: t) -> Group t
    (*): Group t -> Group t -> Group t
    Inv: Group t -> Group t
postulate
    assoc: (a : Group t) -> (b : Group t) -> (c : Group t) -> ((a*b)*c = a*(b*c))
postulate
    neutralL: (x: t) -> (a : Group t) -> a * Unit x = a
postulate
    neutralR: (x: t) -> (a : Group t) -> Unit x * a = a
postulate
    invUnitL: (x: t) -> (a : Group t) -> a * (Inv a) = Unit x
postulate
    invUnitR: (x: t) -> (a : Group t) -> (Inv a) * a = Unit x
</code>```

Then I proved a couple of simple propositions:

```<code>cong : (a : Group t) -> (b : Group t) -> (c: Group t) -> a = b -> a*c = b*c
cong a b c post = rewrite post in Refl

neutralL1: (x: t) -> (a : Group t) -> a = a * Unit x
neutralL1 x a = rewrite neutralL x a in Refl

neutralR1: (x: t) -> (a : Group t) -> a = Unit x * a
neutralR1 x a = rewrite neutralR x a in Refl
</code>```

However, I have a problem with proving that there is only one unit element:

```<code>singleUnit : (x: t) -> (y: t) -> (Unit x = Unit y)
</code>```

I tried various expressions using a general idea, that Unit x = (by neutralL1 y (Unit x)) = Unit x * Unit y = (by neutralR x (Unit y)) = Unit y, but with no success:

```<code>singleUnit x y = rewrite neutralL1 y (Unit x) in neutralR x (Unit y)
singleUnit x y = rewrite neutralL1 y (Unit x) in rewrite neutralR x (Unit y) in Refl
singleUnit x y = rewrite neutralR x (Unit y) in neutralL1 y (Unit x)
singleUnit x y = rewrite neutralR x (Unit y) in rewrite neutralL1 y (Unit x) in Refl
</code>```

How can I prove this?
I have a feeling, that the problem here is related to substitution of complex expressions, like Unit x * Unit y.

答:
Your group definition is structured in a way that would make sense if it was an interface. I have rewritten it as follows, keeping your original variable and function names as much as possible:

```<code>%default total

interface Group t where
  Unit: t
  (*): t -> t -> t
  Inv: t -> t

  assoc: (a : t) -> (b : t) -> (c : t) -> ((a*b)*c = a*(b*c))
  neutralL: (x: t) -> (a : t) -> a * Unit = a
  neutralR: (x: t) -> (a : t) -> Unit * a = a
  invUnitL: (x: t) -> (a : t) -> a * (Inv a) = Unit
  invUnitR: (x: t) -> (a : t) -> (Inv a) * a = Unit

cong : Group t => (a : t) -> (b : t) -> (c: t) -> a = b -> a*c = b*c
cong a b c post = rewrite post in Refl

neutralL1: Group t => (x: t) -> (a : t) -> a = a * Unit
neutralL1 x a = rewrite neutralL x a in Refl

neutralR1: Group t => (x: t) -> (a : t) -> a = Unit * a
neutralR1 x a = rewrite neutralR x a in Refl

is_left_unit : Group t => (x : t) -> Type
is_left_unit x = (y : t) -> x * y = y

only_one_left_unit : Group t => (x : t) -> is_left_unit x -> x = Unit
only_one_left_unit x is_left_unit_x =
  let x_times_unit_is_unit = is_left_unit_x Unit in
  let x_times_unit_is_x = neutralL Unit x in
    trans (sym x_times_unit_is_x) x_times_unit_is_unit

is_right_unit : Group t => (x : t) -> Type
is_right_unit x = (y : t) -> y * x = y

only_one_right_unit : Group t => (x : t) -> is_right_unit x -> x = Unit
only_one_right_unit x is_right_unit_x =
  let unit_times_x_is_unit = is_right_unit_x Unit in
  let unit_times_x_is_x = neutralR Unit x in
    trans (sym unit_times_x_is_x) unit_times_x_is_unit
</code>```

You'll notice that the type t actually is the group type, and Unit is a value rather than a function with one parameter. I have defined separate functions is_left_unit and is_right_unit representing the notions of being a left or right unit respectively.

To be sure all this makes sense we would want to define some actual concrete group, supplying implementations for Unit, * and Inv, and additionally supplying implementations for assoc, neutralL, neutralR, invUnitL and invUnitR which represent proof obligations.

Title: Rewriting in simple theorem proof

Body:
I wrote a definition of group in Idris:

data Group: Type -> Type where
    Unit: (x: t) -> Group t
    (*): Group t -> Group t -> Group t
    Inv: Group t -> Group t
postulate
    assoc: (a : Group t) -> (b : Group t) -> (c : Group t) -> ((a*b)*c = a*(b*c))
postulate
    neutralL: (x: t) -> (a : Group t) -> a * Unit x = a
postulate
    neutralR: (x: t) -> (a : Group t) -> Unit x * a = a
postulate
    invUnitL: (x: t) -> (a : Group t) -> a * (Inv a) = Unit x
postulate
    invUnitR: (x: t) -> (a : Group t) -> (Inv a) * a = Unit x

Then I proved a couple of simple propositions:

cong : (a : Group t) -> (b : Group t) -> (c: Group t) -> a = b -> a*c = b*c
cong a b c post = rewrite post in Refl

neutralL1: (x: t) -> (a : Group t) -> a = a * Unit x
neutralL1 x a = rewrite neutralL x a in Refl

neutralR1: (x: t) -> (a : Group t) -> a = Unit x * a
neutralR1 x a = rewrite neutralR x a in Refl

However, I have a problem with proving that there is only one unit element:

singleUnit : (x: t) -> (y: t) -> (Unit x = Unit y)

I tried various expressions using a general idea, that Unit x = (by neutralL1 y (Unit x)) = Unit x * Unit y = (by neutralR x (Unit y)) = Unit y, but with no success:

singleUnit x y = rewrite neutralL1 y (Unit x) in neutralR x (Unit y)
singleUnit x y = rewrite neutralL1 y (Unit x) in rewrite neutralR x (Unit y) in Refl
singleUnit x y = rewrite neutralR x (Unit y) in neutralL1 y (Unit x)
singleUnit x y = rewrite neutralR x (Unit y) in rewrite neutralL1 y (Unit x) in Refl

How can I prove this?
I have a feeling, that the problem here is related to substitution of complex expressions, like Unit x * Unit y.

Body:
Your group definition is structured in a way that would make sense if it was an interface. I have rewritten it as follows, keeping your original variable and function names as much as possible:

%default total

interface Group t where
  Unit: t
  (*): t -> t -> t
  Inv: t -> t

  assoc: (a : t) -> (b : t) -> (c : t) -> ((a*b)*c = a*(b*c))
  neutralL: (x: t) -> (a : t) -> a * Unit = a
  neutralR: (x: t) -> (a : t) -> Unit * a = a
  invUnitL: (x: t) -> (a : t) -> a * (Inv a) = Unit
  invUnitR: (x: t) -> (a : t) -> (Inv a) * a = Unit

cong : Group t => (a : t) -> (b : t) -> (c: t) -> a = b -> a*c = b*c
cong a b c post = rewrite post in Refl

neutralL1: Group t => (x: t) -> (a : t) -> a = a * Unit
neutralL1 x a = rewrite neutralL x a in Refl

neutralR1: Group t => (x: t) -> (a : t) -> a = Unit * a
neutralR1 x a = rewrite neutralR x a in Refl

is_left_unit : Group t => (x : t) -> Type
is_left_unit x = (y : t) -> x * y = y

only_one_left_unit : Group t => (x : t) -> is_left_unit x -> x = Unit
only_one_left_unit x is_left_unit_x =
  let x_times_unit_is_unit = is_left_unit_x Unit in
  let x_times_unit_is_x = neutralL Unit x in
    trans (sym x_times_unit_is_x) x_times_unit_is_unit

is_right_unit : Group t => (x : t) -> Type
is_right_unit x = (y : t) -> y * x = y

only_one_right_unit : Group t => (x : t) -> is_right_unit x -> x = Unit
only_one_right_unit x is_right_unit_x =
  let unit_times_x_is_unit = is_right_unit_x Unit in
  let unit_times_x_is_x = neutralR Unit x in
    trans (sym unit_times_x_is_x) unit_times_x_is_unit

You'll notice that the type t actually is the group type, and Unit is a value rather than a function with one parameter. I have defined separate functions is_left_unit and is_right_unit representing the notions of being a left or right unit respectively.

To be sure all this makes sense we would want to define some actual concrete group, supplying implementations for Unit, * and Inv, and additionally supplying implementations for assoc, neutralL, neutralR, invUnitL and invUnitR which represent proof obligations.


问:
Why does ManualResetEventSlim.Wait appear not to block for the full wait time?
So I am using System.Threading.ManualResetEventSlim in my code and I happened to notice that sometimes when I call Wait(TimeSpan) the time spent waiting is significantly less than the time specified.

Here is a unit test that demonstrates my situation

```<code>using System;
using System.Diagnostics;
using NUnit.Framework;

namespace DB
{
    [TestFixture]
    public class ManualResetEventSlimTests
    {
        [Test]
        [Repeat(100)]
        public void TestThatWait_ShouldBlockForAtLeastAsLongAsTheWaitTimeout_IfNotSignalled()
        {
            TimeSpan waitTime = TimeSpan.FromMilliseconds(250);
            using (var waiter = new System.Threading.ManualResetEventSlim(false))
            {
                var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                waiter.Wait(waitTime);
                Assert.That(stopwatch.Elapsed, Is.GreaterThanOrEqualTo(waitTime));
            }
        }
    }
}
</code>```

This test will pass most of the time but when repeated 100 times there is always at least 1 failure because the time measured by the stopwatch is less than the specified wait TimeSpan. A typical failure is

Expected: greater than or equal to 00:00:00.2500000
   But was:  00:00:00.2497514

My first thought was that the stopwatch was not accurate enough but that appears not to be the case; the Stopwatch.Frequency = 3507511, which means that it should be accurate to something like 285ns per tick i.e. much, much less than the discrepancy of 0.25ms (assuming that it can accurately count ticks).

The fact that it waits a few fractions of a ms less than I expected does not have any impact on my particular program but I was curious and my Google-foo did not uncover anything relevant. So I put it to the SO community to see if someone has a reasonable explanation.

答:
ManualResetEventSlim ultimately uses Environment.TickCount (see http://referencesource.microsoft.com/#mscorlib/system/threading/ManualResetEventSlim.cs,8a17ba6e95765ed8 and http://referencesource.microsoft.com/#mscorlib/system/threading/SpinWait.cs,9212529427afb371) . The docs state:

Note that, because it is derived from the system timer, the resolution
  of the TickCount property is limited to the resolution of the system
  timer, which is typically in the range of 10 to 16 milliseconds

As such, Stopwatch is likely being more accurate / precise than ManualResetEventSlim.

Body:
So I am using System.Threading.ManualResetEventSlim in my code and I happened to notice that sometimes when I call Wait(TimeSpan) the time spent waiting is significantly less than the time specified.

Here is a unit test that demonstrates my situation

using System;
using System.Diagnostics;
using NUnit.Framework;

namespace DB
{
    [TestFixture]
    public class ManualResetEventSlimTests
    {
        [Test]
        [Repeat(100)]
        public void TestThatWait_ShouldBlockForAtLeastAsLongAsTheWaitTimeout_IfNotSignalled()
        {
            TimeSpan waitTime = TimeSpan.FromMilliseconds(250);
            using (var waiter = new System.Threading.ManualResetEventSlim(false))
            {
                var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                waiter.Wait(waitTime);
                Assert.That(stopwatch.Elapsed, Is.GreaterThanOrEqualTo(waitTime));
            }
        }
    }
}

This test will pass most of the time but when repeated 100 times there is always at least 1 failure because the time measured by the stopwatch is less than the specified wait TimeSpan. A typical failure is

Expected: greater than or equal to 00:00:00.2500000
   But was:  00:00:00.2497514

My first thought was that the stopwatch was not accurate enough but that appears not to be the case; the Stopwatch.Frequency = 3507511, which means that it should be accurate to something like 285ns per tick i.e. much, much less than the discrepancy of 0.25ms (assuming that it can accurately count ticks).

The fact that it waits a few fractions of a ms less than I expected does not have any impact on my particular program but I was curious and my Google-foo did not uncover anything relevant. So I put it to the SO community to see if someone has a reasonable explanation.


答:
As far as I understand, you want to calculate confidence for every row in your DataFrame. For this purpose, please use UDF, instead of lit. Lit function inserts the same data into every row.

Here is example of UDF:

```<code>val df = spark.sparkContext.parallelize(Seq(1,2,3,4)).toDF("first")
import org.apache.spark.sql.functions.udf
val func = udf((i1: Int) => i1 + 3)
df.withColumn("sum", func(df("first"))).show
</code>```

Title: Calculating confidence interval in Spark scala

Body:
I have the following dataframe:

+---------------+-----------+-------------+-----+----+----+--------------------+-------------------+------+--------------------+-------+-------+--------------------+
|   time_stamp_0|sender_ip_1|receiver_ip_2|count|rank|  xi|                  pi|                  r|attack|             myvalue|max_int|min_int|                 int|
+---------------+-----------+-------------+-----+----+----+--------------------+-------------------+------+--------------------+-------+-------+--------------------+
|12:18:52.702936|   10.0.0.1|     10.0.0.4|11139|   1|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:53.702976|   10.0.0.1|     10.0.0.4|11139|   2|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.702873|   10.0.0.1|     10.0.0.4|11139|   3|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:55.702825|   10.0.0.1|     10.0.0.4|11139|   4|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:56.703021|   10.0.0.1|     10.0.0.4|11139|   5|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:57.703786|   10.0.0.1|     10.0.0.4|11139|   6|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:58.706354|   10.0.0.1|     10.0.0.4|11139|   7|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:59.705885|   10.0.0.1|     10.0.0.4|11139|   8|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:14.703371|   10.0.0.1|     10.0.0.4|11139|   9|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:15.702891|   10.0.0.1|     10.0.0.4|11139|  10|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:16.703450|   10.0.0.1|     10.0.0.4|11139|  11|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:17.703087|   10.0.0.1|     10.0.0.4|11139|  12|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:18.704467|   10.0.0.1|     10.0.0.4|11139|  13|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:19.703472|   10.0.0.1|     10.0.0.4|11139|  14|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:20:20.703268|   10.0.0.1|     10.0.0.4|11139|  15|  15| 0.00134661998384056|0.49609480204686235|     0|0.008901370242045487|11139.0|11139.0|[11139.000, 11139...|
|12:18:52.995718|   10.0.0.5|     10.0.0.1|11139|   1|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:53.995478|   10.0.0.5|     10.0.0.1|11139|   2|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.995653|   10.0.0.5|     10.0.0.1|11139|   3|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:55.995978|   10.0.0.5|     10.0.0.1|11139|   4|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:56.994984|   10.0.0.5|     10.0.0.1|11139|   5|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:57.995190|   10.0.0.5|     10.0.0.1|11139|   6|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:58.994970|   10.0.0.5|     10.0.0.1|11139|   7|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:14.995142|   10.0.0.5|     10.0.0.1|11139|   8|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:15.995244|   10.0.0.5|     10.0.0.1|11139|   9|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:16.995481|   10.0.0.5|     10.0.0.1|11139|  10|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:17.995213|   10.0.0.5|     10.0.0.1|11139|  11|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:18.994985|   10.0.0.5|     10.0.0.1|11139|  12|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:19.994872|   10.0.0.5|     10.0.0.1|11139|  13|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:20.994932|   10.0.0.5|     10.0.0.1|11139|  14|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:52.995744|   10.0.0.1|     10.0.0.5|11139|   1|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:53.995496|   10.0.0.1|     10.0.0.5|11139|   2|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.995665|   10.0.0.1|     10.0.0.5|11139|   3|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:55.995986|   10.0.0.1|     10.0.0.5|11139|   4|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:56.994999|   10.0.0.1|     10.0.0.5|11139|   5|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:57.995204|   10.0.0.1|     10.0.0.5|11139|   6|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:58.995057|   10.0.0.1|     10.0.0.5|11139|   7|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:14.995169|   10.0.0.1|     10.0.0.5|11139|   8|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:15.995261|   10.0.0.1|     10.0.0.5|11139|   9|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:16.995499|   10.0.0.1|     10.0.0.5|11139|  10|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:17.995220|   10.0.0.1|     10.0.0.5|11139|  11|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:18.994997|   10.0.0.1|     10.0.0.5|11139|  12|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:19.994891|   10.0.0.1|     10.0.0.5|11139|  13|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:20:20.994951|   10.0.0.1|     10.0.0.5|11139|  14|  14|0.001256845318251...|0.49609480204686235|     0|0.008394658926763537|11139.0|11139.0|[11139.000, 11139...|
|12:18:52.811535|   10.0.0.1|     10.0.0.2|11139|   1|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:53.812029|   10.0.0.1|     10.0.0.2|11139|   2|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.480070|   10.0.0.1|     10.0.0.2|11139|   3|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.481196|   10.0.0.1|     10.0.0.2|11139|   4|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.483532|   10.0.0.1|     10.0.0.2|11139|   5|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.485713|   10.0.0.1|     10.0.0.2|11139|   6|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.487091|   10.0.0.1|     10.0.0.2|11139|   7|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|
|12:18:54.488272|   10.0.0.1|     10.0.0.2|11139|   8|5526| 0.49609480204686235|0.49609480204686235|     0|   0.347756620851195|11139.0|11139.0|[11139.000, 11139...|

I need to calculate the confidence interval, min confidence interval and max confidence interval(About confidence interval computation: http://www.statisticshowto.com/how-to-find-a-confidence-interval/) for "myvalue" column. I used the following code:

 val cntInterval = final_add_count_rank_xi_pi_r_attack_antropy.select("myvalue").rdd.countApprox(timeout = 1000L,confidence = 0.95)
    val (lowCnt,highCnt) = (cntInterval.getFinalValue().low, cntInterval.getFinalValue().high)

    //Add the confidencial interval to df
    val final_integration_df=final_add_count_rank_xi_pi_r_attack_antropy.withColumn("max_int", lit(highCnt))
    .withColumn("min_int", lit(lowCnt))
    .withColumn("int", lit(cntInterval.getFinalValue().toString()))

    //Data becomes clean
    final_integration_df.show(100)

However my problem is that, confidence interval is 11139.0 for all three values(confidence interval, min confidence interval and max confidence interval) in my dataframe which is equal to number of connection between "10.0.0.1" and "10.0.0.2"! (count column in dataframe)
Can you help me how to fix it? thanks

Body:
As far as I understand, you want to calculate confidence for every row in your DataFrame. For this purpose, please use UDF, instead of lit. Lit function inserts the same data into every row.

Here is example of UDF:

val df = spark.sparkContext.parallelize(Seq(1,2,3,4)).toDF("first")
import org.apache.spark.sql.functions.udf
val func = udf((i1: Int) => i1 + 3)
df.withColumn("sum", func(df("first"))).show


问:
all time conserv same bytes in python
I wouldlike to have same digit/bytes all time (8 bytes)

Example : My first number have 5 decimals after comma : 95.12345 so 8 bytes
          If this number is now 100.12345, I have got 9 bytes. Is it possible to delete the last number to conserv all time 8 bytes like this :

```<code>         100.12345 ===> 100.1234
         1000.1234 ===> 1000.123
</code>```

Thanks for your help !

Title: all time conserv same bytes in python

Body:
I wouldlike to have same digit/bytes all time (8 bytes)

Example : My first number have 5 decimals after comma : 95.12345 so 8 bytes
          If this number is now 100.12345, I have got 9 bytes. Is it possible to delete the last number to conserv all time 8 bytes like this :

         100.12345 ===> 100.1234
         1000.1234 ===> 1000.123

Thanks for your help !

Body:
d = 100.12345
print(d, str(d)[:8], sep=' => ')

100.12345 => 100.1234

But 1 digit is not 1 byte, it's true only for string.


问:
Rewrite URL in web.config
Right now my site is working like that whenever i hit my root site link mysite.com i get mysite.com/public and sub pages are being accessed as mysite.com/public/login.
I want to remove "public" from all URL's.

Here is my web.config (using Laravel's original)

```<code><configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Imported Rule 1" stopProcessing="true">
          <match url="^(.*)/$" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Redirect" redirectType="Permanent" url="/{R:1}" />
        </rule>
        <rule name="Imported Rule 2" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
</code>```

答: You need to set your webserver up so that the /public folder is the site root. If you have to prefix every URL with /public, that means it is currently pointed at the app root.</p>

Title: Rewrite URL in web.config

Body:
Right now my site is working like that whenever i hit my root site link mysite.com i get mysite.com/public and sub pages are being accessed as mysite.com/public/login.
I want to remove "public" from all URL's.

Here is my web.config (using Laravel's original)

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Imported Rule 1" stopProcessing="true">
          <match url="^(.*)/$" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Redirect" redirectType="Permanent" url="/{R:1}" />
        </rule>
        <rule name="Imported Rule 2" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>


问:
Ignore git log cross-branch duplicates
If I perform git log -g, for instance, the results will include many commits containing the same content (for example, commits with the same diff but cherry picked to different branches). How can I have git log only show one of those commits and ignore others with duplicate diff content?

答:
I think you need the --cherry-pick option. In my test:

```<code> git log -g --format="%h %s %b"
 3301841 improve readme (cherry picked from commit ...)
 731e382 test
 613e970 improve readme
</code>```

With --cherry-pick, I only get the 3301841.

--cherry-pick Omit any commit that introduces the same change as another commit on the “other side” when the set of commits are limited with symmetric difference.

Title: Ignore git log cross-branch duplicates

Body:
I think you need the --cherry-pick option. In my test:

 git log -g --format="%h %s %b"
 3301841 improve readme (cherry picked from commit ...)
 731e382 test
 613e970 improve readme

With --cherry-pick, I only get the 3301841.

--cherry-pick Omit any commit that introduces the same change as another commit on the “other side” when the set of commits are limited with symmetric difference.


问:
Help inserting db query results to a CSV file
I have a table that contains information pointing to files stored on a file server.  I'm trying to write a powershell script to verify that each record in the table has a physical file associated with it on the server, if it does not write to the CSV file.  I'm not having much luck wit the csv portion and was hoping you could help?

Here is what I have so far (please let me know if there are better ways to do this, Im brand new to powershell).  I only want to add records to the csv if the test-path fails to find the file in question.

```<code>[Reflection.Assembly]::LoadFile("C:\ora10g\odp.net\bin\2.x\Oracle.DataAccess.dll")
$connectionString = "Data Source=XXXXXX;User Id=XXXX;Password=XXXXXXXX;"
$connection = New-Object Oracle.DataAccess.Client.OracleConnection($connectionString)
$connection.Open()
$queryString = "SELECT Key, Sequence, Type, File FROM FileTable WHERE Type IN (2, 5)"

$command = new-Object Oracle.DataAccess.Client.OracleCommand($queryString, $connection)
$mediaObjRS = $command.ExecuteReader()

# Loop through recordset
while ($mediaObjRS.read()) {

   # Assign variables from recordset.
   $objectKey = $mediaObjRS.GetString(0)
   $objectSeq = $mediaObjRS.GetDecimal(1)
   $objectType = $mediaObjRS.GetDecimal(2)
   $objectFileName = $mediaObjRS.GetString(3)

        # Check if file exists based on filetype.
        if($objectType -eq 2){
            # Type 2 = OLE
            $fileLocation = "\\fileserver\D$\files\" + $objectFileName
        }elseif($objectType -eq 5){
             # Type 5 = FILE
             $fileLocation = $objectFileName
        }
        $fileExists = Test-Path $fileLocation
        if($fileExists -eq $False){
                #Write to output file
                $objectKey | Export-Csv missingfiles.csv
                $objectSeq | Export-Csv missingfiles.csv
                $objectType | Export-Csv missingfiles.csv
                $objectFileName | Export-Csv missingfiles.csv
        }
}

$connection.Close()
</code>```

答:
Each time you write to the missingfiles.cs you clobber the previous one. Plus this cmdlet is oriented towards saving objects where each property represents one of the comma separated values.

The simplest way to do this is to manually write (append) to the csv file:

```<code>if(!$fileExists) {
    #Write to output file
    "`"$objectKey`",`"$objectSeq`",`"$objectType`",`"$objectFileName`" >> foo.csv
}
</code>```

The "slick" PowerShell way to do it would be to create an object for each file and then put those in an array and when you're done, export that array of object to a CSV file e.g.:

```<code>$files = @() # Initialize array outside loop
...
if (!$fileExists) {
    $obj = new-object -psobject -prop @{
               Key = $objectKey
               Seq = $objectSeq
               Type = $objectType
               FileName = $objectFileName
           }
    $files += obj
}
...
# outside of loop, export array of objects to csv
$files | Export-Csv missingfiles.csv
</code>```

Body:
I have a table that contains information pointing to files stored on a file server.  I'm trying to write a powershell script to verify that each record in the table has a physical file associated with it on the server, if it does not write to the CSV file.  I'm not having much luck wit the csv portion and was hoping you could help?

Here is what I have so far (please let me know if there are better ways to do this, Im brand new to powershell).  I only want to add records to the csv if the test-path fails to find the file in question.

[Reflection.Assembly]::LoadFile("C:\ora10g\odp.net\bin\2.x\Oracle.DataAccess.dll")
$connectionString = "Data Source=XXXXXX;User Id=XXXX;Password=XXXXXXXX;"
$connection = New-Object Oracle.DataAccess.Client.OracleConnection($connectionString)
$connection.Open()
$queryString = "SELECT Key, Sequence, Type, File FROM FileTable WHERE Type IN (2, 5)"

$command = new-Object Oracle.DataAccess.Client.OracleCommand($queryString, $connection)
$mediaObjRS = $command.ExecuteReader()

# Loop through recordset
while ($mediaObjRS.read()) {

   # Assign variables from recordset.
   $objectKey = $mediaObjRS.GetString(0)
   $objectSeq = $mediaObjRS.GetDecimal(1)
   $objectType = $mediaObjRS.GetDecimal(2)
   $objectFileName = $mediaObjRS.GetString(3)

        # Check if file exists based on filetype.
        if($objectType -eq 2){
            # Type 2 = OLE
            $fileLocation = "\\fileserver\D$\files\" + $objectFileName
        }elseif($objectType -eq 5){
             # Type 5 = FILE
             $fileLocation = $objectFileName
        }
        $fileExists = Test-Path $fileLocation
        if($fileExists -eq $False){
                #Write to output file
                $objectKey | Export-Csv missingfiles.csv
                $objectSeq | Export-Csv missingfiles.csv
                $objectType | Export-Csv missingfiles.csv
                $objectFileName | Export-Csv missingfiles.csv
        }
}

$connection.Close()

Body:
Each time you write to the missingfiles.cs you clobber the previous one. Plus this cmdlet is oriented towards saving objects where each property represents one of the comma separated values.

The simplest way to do this is to manually write (append) to the csv file:

if(!$fileExists) {
    #Write to output file
    "`"$objectKey`",`"$objectSeq`",`"$objectType`",`"$objectFileName`" >> foo.csv
}

The "slick" PowerShell way to do it would be to create an object for each file and then put those in an array and when you're done, export that array of object to a CSV file e.g.:

$files = @() # Initialize array outside loop
...
if (!$fileExists) {
    $obj = new-object -psobject -prop @{
               Key = $objectKey
               Seq = $objectSeq
               Type = $objectType
               FileName = $objectFileName
           }
    $files += obj
}
...
# outside of loop, export array of objects to csv
$files | Export-Csv missingfiles.csv


问:
Modelsim "Failed to map the library" error
I have written this simple code. But when i try to simulate it using Modelsim, it shows the an error saying library cannot be mapped. How do i sort it?

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity p1 is
    Port ( a : in  STD_LOGIC;
           b : in  STD_LOGIC;
           c : out  STD_LOGIC);
end p1;

architecture Behavioral of p1 is

begin

c <= a or b;

end Behavioral;
</code>```

This is the error:

ERROR: Failed to map the library

答:
probably you changed directory, and library work is not created there, although a mapping exists in your modelsim.ini.

Type in transcript:

```<code>vlib work
</code>```

To create the library work.

edit: if the mapping is also missing (i.e. the above solution does not solve this) add the following command:

```<code>vmap work work
</code>```

P.s. Stupid thing is: modelsim should not default to a library named "work", as "work" is a reserved keyword (meaning 'the current library'). But ignore that, as that has been an issue/bug for tens of years now...

Body:
I have written this simple code. But when i try to simulate it using Modelsim, it shows the an error saying library cannot be mapped. How do i sort it?

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

entity p1 is
    Port ( a : in  STD_LOGIC;
           b : in  STD_LOGIC;
           c : out  STD_LOGIC);
end p1;

architecture Behavioral of p1 is

begin

c <= a or b;

end Behavioral;

This is the error:

ERROR: Failed to map the library

Body:
probably you changed directory, and library work is not created there, although a mapping exists in your modelsim.ini.

Type in transcript:

vlib work

To create the library work.

edit: if the mapping is also missing (i.e. the above solution does not solve this) add the following command:

vmap work work

P.s. Stupid thing is: modelsim should not default to a library named "work", as "work" is a reserved keyword (meaning 'the current library'). But ignore that, as that has been an issue/bug for tens of years now...


问:
UICollectionView highlighted cell with shadow
I have UICollectionView in which the centre cell will be highlighted as shown below image.

i have used following code to make shadow around the center cell.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell : STSuggestStyleCell = collectionView.dequeueReusableCell(for: indexPath)

    if indexPath.row == 4{

        cell.imageProfile.layer.cornerRadius = 2.0
        cell.imageProfile.layer.borderWidth = 1.0;
        cell.imageProfile.layer.borderColor = UIColor.clear.cgColor
        cell.imageProfile.layer.masksToBounds = true;

        cell.imageProfile.layer.shadowColor = UIColor.lightGray.cgColor;
        cell.imageProfile.layer.shadowOffset = CGSize(width: 2.0, height: 2.0);
        cell.imageProfile.layer.shadowRadius = 2.0;
        cell.imageProfile.layer.shadowOpacity = 2.0;
        cell.imageProfile.layer.masksToBounds = false;
        cell.imageProfile.layer.shadowPath = UIBezierPath(roundedRect: cell.imageProfile.bounds, cornerRadius: cell.imageProfile.layer.cornerRadius).cgPath

                    cell.imageProfile.backgroundColor = UIColor.white

    }

    return cell
}
</code>```

But it is not working properly.

Can anyone tell me how to achieve the above design using UICollectionView?

答:
Maybe you need to create two different cell. because of its reuse feature. </p>

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.row == 4{
        let cell : STSuggestStyleCell = collectionView.dequeueReusableCell(for: indexPath)
        cell.imageProfile.layer.cornerRadius = 2.0
        cell.imageProfile.layer.borderWidth = 1.0;
        cell.imageProfile.layer.borderColor = UIColor.clear.cgColor
        cell.imageProfile.layer.masksToBounds = true;

        cell.imageProfile.layer.shadowColor = UIColor.lightGray.cgColor;
        cell.imageProfile.layer.shadowOffset = CGSize(width: 2.0, height: 2.0);
        cell.imageProfile.layer.shadowRadius = 2.0;
        cell.imageProfile.layer.shadowOpacity = 2.0;
        cell.imageProfile.layer.masksToBounds = false;
        cell.imageProfile.layer.shadowPath = UIBezierPath(roundedRect: cell.imageProfile.bounds, cornerRadius: cell.imageProfile.layer.cornerRadius).cgPath

        cell.imageProfile.backgroundColor = UIColor.white
        return cell
    }else{
        let cell : STSuggestNomalCell = collectionView.dequeueReusableCell(for: indexPath)
        return cell
    }
}
</code>```

Body:
I have UICollectionView in which the centre cell will be highlighted as shown below image.

i have used following code to make shadow around the center cell.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell : STSuggestStyleCell = collectionView.dequeueReusableCell(for: indexPath)

    if indexPath.row == 4{

        cell.imageProfile.layer.cornerRadius = 2.0
        cell.imageProfile.layer.borderWidth = 1.0;
        cell.imageProfile.layer.borderColor = UIColor.clear.cgColor
        cell.imageProfile.layer.masksToBounds = true;

        cell.imageProfile.layer.shadowColor = UIColor.lightGray.cgColor;
        cell.imageProfile.layer.shadowOffset = CGSize(width: 2.0, height: 2.0);
        cell.imageProfile.layer.shadowRadius = 2.0;
        cell.imageProfile.layer.shadowOpacity = 2.0;
        cell.imageProfile.layer.masksToBounds = false;
        cell.imageProfile.layer.shadowPath = UIBezierPath(roundedRect: cell.imageProfile.bounds, cornerRadius: cell.imageProfile.layer.cornerRadius).cgPath

                    cell.imageProfile.backgroundColor = UIColor.white

    }

    return cell
}

But it is not working properly.

Can anyone tell me how to achieve the above design using UICollectionView?

Body:
Maybe you need to create two different cell. because of its reuse feature.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if indexPath.row == 4{
        let cell : STSuggestStyleCell = collectionView.dequeueReusableCell(for: indexPath)
        cell.imageProfile.layer.cornerRadius = 2.0
        cell.imageProfile.layer.borderWidth = 1.0;
        cell.imageProfile.layer.borderColor = UIColor.clear.cgColor
        cell.imageProfile.layer.masksToBounds = true;

        cell.imageProfile.layer.shadowColor = UIColor.lightGray.cgColor;
        cell.imageProfile.layer.shadowOffset = CGSize(width: 2.0, height: 2.0);
        cell.imageProfile.layer.shadowRadius = 2.0;
        cell.imageProfile.layer.shadowOpacity = 2.0;
        cell.imageProfile.layer.masksToBounds = false;
        cell.imageProfile.layer.shadowPath = UIBezierPath(roundedRect: cell.imageProfile.bounds, cornerRadius: cell.imageProfile.layer.cornerRadius).cgPath

        cell.imageProfile.backgroundColor = UIColor.white
        return cell
    }else{
        let cell : STSuggestNomalCell = collectionView.dequeueReusableCell(for: indexPath)
        return cell
    }
}


答:
Because it has a property of display: table-cell which will force it to behave like a table.

You can just add display: block in your current code.

Alternatively, replace the code with a single display: none will do the trick.

Or, with a rather weird styling, see below.

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    display: none;

    /* OR */

    display: table-cell;
    border: none;
    opacity: 0;
    width: 0;
    font-size: 0;

    /* OR */

    display: block;
    opacity: 0;
    width: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <body>
    <div class="wrapper">
      <header>HEADER</header>
      <main>
        <section>SECTION</section>
        <aside>ASIDE</aside>
      </main>
      <footer>FOOTER</footer>
    </div>
  </body>
</html></code>```

Title: Why width: 0 doesn't work

Body:
In @media screen and (max-width: 700px), I set aside {width: 0}, but it doesn't disappear. After resizing, the window remains as null space with width: 52px, why is this happening, and how can I fix it?

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    opacity: 0;
    width: 0;
  }
}

      HEADER

SECTION

        ASIDE

      FOOTER

Body:
Because it has a property of display: table-cell which will force it to behave like a table.

You can just add display: block in your current code.

Alternatively, replace the code with a single display: none will do the trick.

Or, with a rather weird styling, see below.

* {
  margin:0;
  padding:0;
}

html, body {
  height: 100%;
}

body {
  background-color: #eee;
}

.wrapper {
  height: 100%;
  display: table;
  width: 100%;
  text-align: center;
  border-collapse: collapse;
}

header {
  box-sizing: border-box;
  display: table-row;
  height: 50px;
  background-color: #eee;
  border-bottom: 1px solid black;
}

main {
  height: 100%;
  display: table;
  width: 800px;
  margin: 0 auto;
  background-color: #fff;
}

section {
  display: table-cell;
}

aside {
  display: table-cell;
  box-sizing: border-box;
  border-left: 1px solid black;
  width: 300px;

  /*__transition*/
  opacity: 1;
  transition: all .25s;
}

footer {
  box-sizing: border-box;
  border-top: 1px solid black;
  display: table-row;
  height: 50px;
  background-color: #eee;
}

@media screen and (max-width: 800px) {

  main {
    width: 100%;
  }
}

@media screen and (max-width: 700px) {

  section {
    width: 100%;
  }

  aside {
    display: none;

    /* OR */

    display: table-cell;
    border: none;
    opacity: 0;
    width: 0;
    font-size: 0;

    /* OR */

    display: block;
    opacity: 0;
    width: 0;
  }
}

<html>
  <body>
    <div class="wrapper">
      <header>HEADER</header>
      <main>
        <section>SECTION</section>
        <aside>ASIDE</aside>
      </main>
      <footer>FOOTER</footer>
    </div>
  </body>
</html>


问:
Logging In: Background Details
What happens when you log into a website?

I know cookies are stored and some info (what info?) gets sent to the server...but maybe some more detail?

答:
That's a pretty general question.  What you're doing, over all, is establishing some kind of credentials with the site itself.  If we take the simple version, you enter a user name and a password; that means you identify yourself to the website, and then show it a secret you and the website share that no one else knows (we hope).  That establishes you as authentically the person with that user name, and so we say you have authenticated yourself.

Once you've done so, there are some design decisions the website designer has to make.  most people don't want to log in for every page, so the web site wants to store a little information, a credential, on your end.  This means that it can tell it's still you.  Often, as you say, that's a "cookie", which is nothing more that a tiny text file named with the web site's URL.  This file is stored by the browser.

On many web sites, like for banking, you also want to guarantee that the data being exchanged can't be intercepted by a third party.  If so, you establish a secure connection using a protocol known as SSL or TLS.  What this adds to the basic connection is an exchange of information that establishes a session key.  This session key is then used to encrypt the communications.  This usually happens before you exchange the user name and password, so that your password is never visible to a malicious third party either.

Under the covers, when you establish a secure connection, the web site sends your browser a block of formatted data called an x509 certificate.  This is another form of authentication; the certificate will have been signed by an issuer (the certificate authority or "CA") and the browser can use stored data about the CA's to ensure that the certificate is authentic.

OwnerDisplayName: koldfyre

Title: Logging In: Background Details

LastEditorDisplayName: Jens Roland

OwnerDisplayName: Charlie Martin


问:
Looking for some Java good practice advice regarding distributed applications and message passing
Some background information. This is a distributed application with multiples nodes. A 'communication' thread sends and receives all messages sent between these nodes. This cannot be changed.

A 'doStuff' thread asks the 'communication' thread to send a message to a node. It then needs to wait for a response from the other node. The 'communication' thread will receive this response message. It then needs to deliver this message to the correct 'doStuff' thread.

I am unsure what sort of information needs to be stored at the node or within the message to ensure that the correct thread always receives the response message.

Looking for some advice upon how to achieve this. Thanks for reading :)

答: Is using JMS an option at all?  If so, you might find that more practical than doing "roll your own."  Asynchronous message passing, in general, is a solved problem.  If JMS is an option, look at TopicRequestor and/or QueueRequestor in particular.</p>


问:
How to do I send a message to a queue in Azure from an Azure function using python?
I am using an azure function that has a time trigger and I am trying to communication with a data base to return a list of dictionaries, I am trying to send each dictionary as a string (queue message) to a queue, I was going to do this with an output binder but could not figure out how to, so I am using the azure module. Problem is every message I send goes into a poison queue for some reason, and I cannot figure out why, here is a code snippet of what I have in my Azure function.

```<code>import os
import platform
import WorkWithDatabase
#import base64
from azure.storage.queue import QueueService
acc='...ACCOUNT NAME'
key='...KEY'

#Connect to QueueService
queue_service = QueueService(account_name=acc, account_key=key)

#Pull missing data from the database,
#Call a function in another script to do this

missingList=WorkWithDatabase.ListRequests()

for item in missingList:
    queue_service.put_message('taskqueue', str(item))
</code>```

Also Is there a way I can use the database as a resource in an azure function with python??

答:
For using these python packages, such as pyodbc or pymssql to connect Azure SQL Database, you need to install a custom version of Python on Azure Function, then to install pip for the custom verion of Python to install these package as you want.

So the steps as below.

Follow the document Using a custom version of Python to install a custom Python runtime in the path site\tools of Kudu via access the url https://<your function name>.scm.azurewebsites.net/DebugConsole.

After custom python installation, to download a get-pip.py file to the path site\tool of custom Python, then to install pip tool via command python get-pip.py.

Then, you can install these packages via Scripts/pip.exe install <package-names>.

Then, you can import these packages to write your code in your Azure Function on Azure portal.

Body:
I am using an azure function that has a time trigger and I am trying to communication with a data base to return a list of dictionaries, I am trying to send each dictionary as a string (queue message) to a queue, I was going to do this with an output binder but could not figure out how to, so I am using the azure module. Problem is every message I send goes into a poison queue for some reason, and I cannot figure out why, here is a code snippet of what I have in my Azure function.

import os
import platform
import WorkWithDatabase
#import base64
from azure.storage.queue import QueueService
acc='...ACCOUNT NAME'
key='...KEY'

#Connect to QueueService
queue_service = QueueService(account_name=acc, account_key=key)

#Pull missing data from the database,
#Call a function in another script to do this

missingList=WorkWithDatabase.ListRequests()

for item in missingList:
    queue_service.put_message('taskqueue', str(item))

Also Is there a way I can use the database as a resource in an azure function with python??


问:
binding knockout bindings to an MVC razor model
I have the following in knockout

```<code>     <select multiple="multiple" height="5" data-bind="options:allItems,
 selectedOptions:selectedItems"> </select>
</code>```

The above generates a list of all the items in the "observableArray" in the knockout script.

I need to somehow bind this, almost as if it were an @html.etc element in razor.

For example, I have the following

```<code>     @using (Html.BeginForm("SubmitFull", "ENCOUNTER", null))

         {

        @Html.HiddenFor(model => model.Name)
      @Html.ValidationSummary(true)
      <fieldset>
         <legend>ENCOUNTER</legend>
         <div class="editor-label">
            @Html.LabelFor(model => model.Date)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Date)
            @Html.ValidationMessageFor(model => model.Date)
        </div>
</code>```

So when I click the button at the bottom of my page, the model that I defined at the top of the view

```<code>     @model MVC_MONGODB.Models.PATIENT.Patient
</code>```

will be loaded up now with a "Date" property and a "Name" property.

I need to also load up with model with the values from the knockout observableArray.  I have never done this before, I'm not sure what the best way to do it is, or even any possible way, I'm not even 100% sure it's possible.

http://knockoutmvc.com/ seems like a promising reference.

Using "ValueUpdate" seems like a possibility or maybe a (input type="hidden") element somewhere..

I want to basically have the textbox from the knockout code I mentioned at the top of this question, to act as if it was actually inside

```<code> @Html.TextAreaFor(model => model.ChiefComplaintsStr, 5, 100, new {
  HtmlAttributes = new { } })
</code>```

答:
you can set the knockout related attributes using the HtmlAttributes of the controls like...

```<code>@Html.HiddenFor(model => model.ChiefComplaintsStr, htmlAttributes: new { @data_bind = "put knockout binding here"})
</code>```

Body:
I have the following in knockout

     <select multiple="multiple" height="5" data-bind="options:allItems,
 selectedOptions:selectedItems"> </select>

The above generates a list of all the items in the "observableArray" in the knockout script.

I need to somehow bind this, almost as if it were an @html.etc element in razor.

For example, I have the following

     @using (Html.BeginForm("SubmitFull", "ENCOUNTER", null))

         {

        @Html.HiddenFor(model => model.Name)
      @Html.ValidationSummary(true)
      <fieldset>
         <legend>ENCOUNTER</legend>

            @Html.LabelFor(model => model.Date)

            @Html.EditorFor(model => model.Date)
            @Html.ValidationMessageFor(model => model.Date)

So when I click the button at the bottom of my page, the model that I defined at the top of the view

     @model MVC_MONGODB.Models.PATIENT.Patient

will be loaded up now with a "Date" property and a "Name" property.

I need to also load up with model with the values from the knockout observableArray.  I have never done this before, I'm not sure what the best way to do it is, or even any possible way, I'm not even 100% sure it's possible.

http://knockoutmvc.com/ seems like a promising reference.

Using "ValueUpdate" seems like a possibility or maybe a (input type="hidden") element somewhere..

I want to basically have the textbox from the knockout code I mentioned at the top of this question, to act as if it was actually inside

 @Html.TextAreaFor(model => model.ChiefComplaintsStr, 5, 100, new {
  HtmlAttributes = new { } })

Body:
you can set the knockout related attributes using the HtmlAttributes of the controls like...

@Html.HiddenFor(model => model.ChiefComplaintsStr, htmlAttributes: new { @data_bind = "put knockout binding here"})


问:
Birt cascading parameter with search box instead of combo box
I am new to BIRT reporting. I have following requirement

I want to load list of customer in BIRT parameter selection window. I have more than 3000++ customers to load. Hence our team came to a conclusion , to give a searchable text box in parameter window and once user type few character of customer name and press search button/hit enter, Then it will load the filtered set of customer matching with the name as a cascading drop down below the search box.

How I can do this in BIRT report?

Thank you

答: Use cascading parameters with a filter by some group... location, first letter in their name. See an example here - http://download.eclipse.org/birt/downloads/examples/reports/2.1/cascade/cascade.rptdesign</p>


问:
Angular2 bool scoping issue
I'm trying to make a Basic Select in Angular2 with angular-cli v1.0.0 and angular 2.4.10, but the problem is that the isOpen variable doesn't toggle when selecting an option, thus closing the menu.

```<code>BasicSelect.ts
@Component({
  selector: 'basic-select',
  templateUrl: './basic-select.component.html',
  styleUrls: ['./basic-select.component.less']
})
export class BasicSelect implements OnInit, OnDestroy {
  // Input is populated from an outside component after an http call
  @Input()
  selectOptions:Array<any>;
  //
  @Input()
  selectedOption:BehaviorSubject<any>;

  public isOpen:boolean;

  public constructor() {
    this.isOpen = false;
  }
  //THIS WORKS
  public toggleDropdown():void {
    this.isOpen = !this.isOpen;
  }
  //THIS DOESN'T WORK
  public selectOption(opt):void {
    this.isOpen = false;
    this.selectedOption.next(opt);
  }
}

BasicSelect.html
<div class="dropdown_container" (click)="toggleDropdown()" [ngClass]="{ 'show': isOpen }">
  <dl>
    <dt><span>{{selection}}</span></dt>
  </dl>
  <ul class="dropdown_items">
    <li *ngFor="let option of selectOptions" (click)="selectOption(option)">
      <span>{{option}}</span>
    </li>
  </ul>
</div>
</code>```

The problem is that if I click the dropdown container, works like a charm, but when actually selecting an option, the isOpen change is not seen by the component.

答:
Do this:

```<code>public selectOption(event, opt):void {
    event.stopPropagation()
    this.isOpen = false;
    this.selectedOption.next(opt);
  }
</code>```

This is because, when you click on li element, you are triggering two click functions. One is on the li and second is on outer div. So, event.stopPropagation() will stop propagation of click event. There by only one click is triggered.

Read about it more here

Hope it helps. :-)

Title: Angular2 bool scoping issue

Body:
I'm trying to make a Basic Select in Angular2 with angular-cli v1.0.0 and angular 2.4.10, but the problem is that the isOpen variable doesn't toggle when selecting an option, thus closing the menu.

BasicSelect.ts
@Component({
  selector: 'basic-select',
  templateUrl: './basic-select.component.html',
  styleUrls: ['./basic-select.component.less']
})
export class BasicSelect implements OnInit, OnDestroy {
  // Input is populated from an outside component after an http call
  @Input()
  selectOptions:Array<any>;
  //
  @Input()
  selectedOption:BehaviorSubject<any>;

  public isOpen:boolean;

  public constructor() {
    this.isOpen = false;
  }
  //THIS WORKS
  public toggleDropdown():void {
    this.isOpen = !this.isOpen;
  }
  //THIS DOESN'T WORK
  public selectOption(opt):void {
    this.isOpen = false;
    this.selectedOption.next(opt);
  }
}

BasicSelect.html

{{selection}}

      {{option}}

The problem is that if I click the dropdown container, works like a charm, but when actually selecting an option, the isOpen change is not seen by the component.

Body:
Do this:

public selectOption(event, opt):void {
    event.stopPropagation()
    this.isOpen = false;
    this.selectedOption.next(opt);
  }

This is because, when you click on li element, you are triggering two click functions. One is on the li and second is on outer div. So, event.stopPropagation() will stop propagation of click event. There by only one click is triggered.

Read about it more here

Hope it helps. :-)


问:
Disable guest checkout spree
Is there any way to disable the functionality which allows guests to make orders in spree? I searched around but couldn't seem to see anything, also no settings in the admin panel.

Is there any proper way to do this or will I have to go through the code and rip stuff out?

答:
Use the allow_guest_checkout preference to change the default setting with checkout.

You can set this preference false to disable guest checkout in spree.
Hope this helps.

Title: Disable guest checkout spree


问:
Tomcat cluster with inconsistent static resources
Suppose there's a java webapp that let users upload image files, it simply stores those images on the tomcat server's filesystem, and will serve them as static resources upon further requesting. Now this application needs to be scaled out and deployed in a large cluster of tomcat servers sitting behind an apache server with mod_jk as load-balancer.

Since the uploaded images lie on the filesystem, they won't be available on the rest of tomcat servers other than the one on which the upload event occurs. If one user comes in, uploads an image,and after a while requests the image again, his request may be unfortunately routed to another server due to the round-robin load balancing policy, so he won't see his image!

Is there any conventional way to deal with this sort of problem? or should i re-design the upload system by utilizing a back-end database?

答:
One way is with a shared filesystem. Of course, thats not always possible. The other way is to hold everything in the database. Because of synchronization, this is the way I would suggest.
For content I would recommend to use jackrabbit. A good introduction to clustering and jackrabbit is here: http://wiki.apache.org/jackrabbit/Clustering</p>


问:
Mysql query insert from another table
When using the query below I'm inserting product_id and I also want to set field category_id = 4 for all inserted product_ids. Here's my code to insert products.

```<code>INSERT INTO lc_products_to_categories
( product_id)
SELECT product_id
FROM lc_products_info
where name like '%awesome product%'
</code>```

How to update category_id with single query?

答:
```<code>INSERT INTO lc_products_to_categories
( product_id, category_id)
SELECT product_id, 4
FROM lc_products_info
where name like '%awesome product%'
</code>```

Title: Mysql query insert from another table

Body:
When using the query below I'm inserting product_id and I also want to set field category_id = 4 for all inserted product_ids. Here's my code to insert products.

INSERT INTO lc_products_to_categories
( product_id)
SELECT product_id
FROM lc_products_info
where name like '%awesome product%'

How to update category_id with single query?


问:
Is it possible to create new type variable without struct?
Here is what i got but when i check type it displays "struct MyVarName"

```<code>#include <iostream>
#include <typeinfo>
typedef struct { char text[15];} MyVarName;
int  g = 0;
int main(void) {
    MyVarName a = { "super" };
    std::cout << typeid(a).name() << '\n';
    std::cout << typeid(g).name() << '\n';
return 0;
}
</code>```

Is it possible to define your own variable type and then use it as any other variable?

Print, assign new value.. etc.

答:
The result of std::type_info::name() is implementation-defined and could be anything, including a mangled name, the empty string, or a recipe for lasagna.

For example, GCC gives:

```<code>9MyVarName
i
</code>```

Apparently yours is taking a C-like approach and calling it struct MyVarName, which is what you'd have to write to reference the type in C.

Simply don't rely on it for this kind of thing. C++ does not pretend to have meaningful reflection.

Besides that, there is nothing wrong with your code. You did define a new type. There are ways to introduce new types that don't require the creation of a class type (i.e. with struct or class), but these all involve aliasing existing types with typedef or using, and are thus limited. They won't allow you to create a complex type like std::string.

Body:
Here is what i got but when i check type it displays "struct MyVarName"

#include <iostream>
#include <typeinfo>
typedef struct { char text[15];} MyVarName;
int  g = 0;
int main(void) {
    MyVarName a = { "super" };
    std::cout << typeid(a).name() << '\n';
    std::cout << typeid(g).name() << '\n';
return 0;
}

Is it possible to define your own variable type and then use it as any other variable?

Print, assign new value.. etc.

Body:
The result of std::type_info::name() is implementation-defined and could be anything, including a mangled name, the empty string, or a recipe for lasagna.

For example, GCC gives:

9MyVarName
i

Apparently yours is taking a C-like approach and calling it struct MyVarName, which is what you'd have to write to reference the type in C.

Simply don't rely on it for this kind of thing. C++ does not pretend to have meaningful reflection.

Besides that, there is nothing wrong with your code. You did define a new type. There are ways to introduce new types that don't require the creation of a class type (i.e. with struct or class), but these all involve aliasing existing types with typedef or using, and are thus limited. They won't allow you to create a complex type like std::string.


问:
How to add a woocommerce product to the custom Product_type using php code?
A WooCommerce product is getting created easily but the product is getting added to the product_type:simple. I want to add the product to the "custom product_type:test"

```<code>static function createTicket($postId, $productDetails) {
$id = wp_insert_post(array(
    'post_type' => 'product',
    'post_title' => $productDetails['title'],
    'post_content' => $productDetails['description'],
    'post_status' => get_post_status($postId),
        'max_value' => 1,
));
update_post_meta($id, '_price', $productDetails['price']);
update_post_meta($id, '_regular_price', $productDetails['price']);
update_post_meta($id, '_wpws_testID', $postId);
update_post_meta($id, '_sold_individually', "yes");
wp_set_object_terms( $id, 'test', 'product_type' );
return $id;
}
</code>```

I have added

wp_set_object_terms( $id, 'test', 'product_type' );

But nothing works

答:
Used product_type_selector hook

```<code>// add a product type
add_filter( 'product_type_selector', 'add_custom_product_type' );
function add_custom_product_type( $types ){
    $types[ 'test_custom_product_type' ] = __( 'test Product' );
    return $types;
}
</code>```

Edit

Please check below links it help you more on this

http://jeroensormani.com/adding-a-custom-woocommerce-product-type/

https://wisdmlabs.com/blog/create-product-type-custom-settings-woocommerce/

Edit

Above code for older version of WooCommerce

Used this code for save product with custom product type. it working with WooCommerce 3.*
Check this for more information https://gist.github.com/stirtingale/753ac6ddb076bd551c3261007c9c63a5

```<code>function register_simple_rental_product_type() {
    class WC_Product_Simple_Rental extends WC_Product {

        public function __construct( $product ) {
            $this->product_type = 'simple_rental';
            parent::__construct( $product );
        }
    }
}
add_action( 'init', 'register_simple_rental_product_type' );
function add_simple_rental_product( $types ){
    // Key should be exactly the same as in the class
    $types[ 'simple_rental' ] = __( 'Simple Rental' );
    return $types;
}
add_filter( 'product_type_selector', 'add_simple_rental_product' );
</code>```

Body:
A WooCommerce product is getting created easily but the product is getting added to the product_type:simple. I want to add the product to the "custom product_type:test"

static function createTicket($postId, $productDetails) {
$id = wp_insert_post(array(
    'post_type' => 'product',
    'post_title' => $productDetails['title'],
    'post_content' => $productDetails['description'],
    'post_status' => get_post_status($postId),
        'max_value' => 1,
));
update_post_meta($id, '_price', $productDetails['price']);
update_post_meta($id, '_regular_price', $productDetails['price']);
update_post_meta($id, '_wpws_testID', $postId);
update_post_meta($id, '_sold_individually', "yes");
wp_set_object_terms( $id, 'test', 'product_type' );
return $id;
}

I have added

wp_set_object_terms( $id, 'test', 'product_type' );

But nothing works

Body:
Used product_type_selector hook

// add a product type
add_filter( 'product_type_selector', 'add_custom_product_type' );
function add_custom_product_type( $types ){
    $types[ 'test_custom_product_type' ] = __( 'test Product' );
    return $types;
}

Edit

Please check below links it help you more on this

http://jeroensormani.com/adding-a-custom-woocommerce-product-type/

https://wisdmlabs.com/blog/create-product-type-custom-settings-woocommerce/

Edit

Above code for older version of WooCommerce

Used this code for save product with custom product type. it working with WooCommerce 3.*
Check this for more information https://gist.github.com/stirtingale/753ac6ddb076bd551c3261007c9c63a5

function register_simple_rental_product_type() {
    class WC_Product_Simple_Rental extends WC_Product {

        public function __construct( $product ) {
            $this->product_type = 'simple_rental';
            parent::__construct( $product );
        }
    }
}
add_action( 'init', 'register_simple_rental_product_type' );
function add_simple_rental_product( $types ){
    // Key should be exactly the same as in the class
    $types[ 'simple_rental' ] = __( 'Simple Rental' );
    return $types;
}
add_filter( 'product_type_selector', 'add_simple_rental_product' );


问:
Unload Modal after data processed in datatable
I show modal while processing data in my datatable, however i can't figure out how to hide the modal after the process is done.
I checked and tried all events of datatable with no sucess

```<code> $(document).ready(function () {

            var x = $('#datatab').DataTable({
               .....
     });

    $('#datatab').on('processing.dt', function (e, settings) {
                alert("processing");
                $('#myPleaseWait').modal('show'); // Here i show the modal
            });
            // I tried the following events but non worked
            $('#datatab').on('draw.dt', function () {
                alert("draw");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('stateLoaded.dt', function () {
                alert("stateLoaded");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('initComplete', function () {
                alert("initComplete");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('stateLoadParams.dt', function () {
                alert("stateLoadParams");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('xhr.dt', function () {
                alert("xhr");
                $('#myPleaseWait').modal('hide');
            });
</code>```

The model remains open, how can i hide it after the processing is done?

Thank you

答:
Here is what worked for me</p>

```<code>var x = $('#datatab').DataTable({
            "bServerSide": true,
            "ajax": {
                "beforeSend":AjaxBegin,
                "type": "POST",
                "url": '/Totto/GetZScgData',
                "contentType": 'application/json; charset=utf-8',
                'data': function(data) { return data = JSON.stringify(data); },
                'complete': AjaxComplete
            },

function AjaxBegin() {
    $('#myPleaseWait').modal('show');

}
function AjaxComplete() {
    $('#myPleaseWait').modal('hide');

}
</code>```

Body:
I show modal while processing data in my datatable, however i can't figure out how to hide the modal after the process is done.
I checked and tried all events of datatable with no sucess

 $(document).ready(function () {

            var x = $('#datatab').DataTable({
               .....
     });

    $('#datatab').on('processing.dt', function (e, settings) {
                alert("processing");
                $('#myPleaseWait').modal('show'); // Here i show the modal
            });
            // I tried the following events but non worked
            $('#datatab').on('draw.dt', function () {
                alert("draw");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('stateLoaded.dt', function () {
                alert("stateLoaded");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('initComplete', function () {
                alert("initComplete");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('stateLoadParams.dt', function () {
                alert("stateLoadParams");
                $('#myPleaseWait').modal('hide');
            });

            $('#datatab').on('xhr.dt', function () {
                alert("xhr");
                $('#myPleaseWait').modal('hide');
            });

The model remains open, how can i hide it after the processing is done?

Thank you

Body:
Here is what worked for me

var x = $('#datatab').DataTable({
            "bServerSide": true,
            "ajax": {
                "beforeSend":AjaxBegin,
                "type": "POST",
                "url": '/Totto/GetZScgData',
                "contentType": 'application/json; charset=utf-8',
                'data': function(data) { return data = JSON.stringify(data); },
                'complete': AjaxComplete
            },

function AjaxBegin() {
    $('#myPleaseWait').modal('show');

}
function AjaxComplete() {
    $('#myPleaseWait').modal('hide');

}


问:
Mongoexport strict json load in Spark
I have a process that exports data from a mongodb using mongoexport.
As the documentation mentions all json  output is in Strict mode

This means data will look like this:

```<code>"{amount":{"$numberLong":"3"},"count":{"$numberLong":"245"}}
</code>```

Where as my Scala case class is defined as:

```<code>case class MongoData(amount: Long, count: Long)
</code>```

Reading the data will of course fail like this:

```<code>spark
      .read
      .json(inputPath)
      .as[MongoData]
</code>```

Is there a way to either export from mongo without the strict mode or to import the json in Scala without manually restructuring each field to the appropriate structure?

答:
I'm now using this as solution. but it feels somewhat hacky.</p>

```<code>case class DataFrameExtended(dataFrame: DataFrame) {

   def undoMongoStrict(): DataFrame = {
    val numberLongType = StructType(List(StructField("$numberLong", StringType, true)))

    def restructure(fields: Array[StructField], nesting: List[String] = Nil): List[Column] = {
      fields.flatMap(field => {
        val fieldPath = nesting :+ field.name
        val fieldPathStr = fieldPath.mkString(".")
        field.dataType match {
          case dt: StructType if dt == numberLongType =>
            Some(col(s"$fieldPathStr.$$numberLong").cast(LongType).as(field.name))
          case dt: StructType =>
            Some(struct(restructure(dt.fields, fieldPath): _*).as(field.name))
          case _ => Some(col(fieldPathStr).as(field.name))
          //              case dt:ArrayType => //@todo handle other DataTypes Array??
        }
      })
    }.toList

    dataFrame.select(restructure(dataFrame.schema.fields): _*)
  }
}

implicit def dataFrameExtended(df: DataFrame): DataFrameExtended = {
  DataFrameExtended(df)
}

spark
  .read
  .json(inputPath)
  .undoMongoStrict()
</code>```

Title: Mongoexport strict json load in Spark

Body:
I have a process that exports data from a mongodb using mongoexport.
As the documentation mentions all json  output is in Strict mode

This means data will look like this:

"{amount":{"$numberLong":"3"},"count":{"$numberLong":"245"}}

Where as my Scala case class is defined as:

case class MongoData(amount: Long, count: Long)

Reading the data will of course fail like this:

spark
      .read
      .json(inputPath)
      .as[MongoData]

Is there a way to either export from mongo without the strict mode or to import the json in Scala without manually restructuring each field to the appropriate structure?

Body:
I'm now using this as solution. but it feels somewhat hacky.

case class DataFrameExtended(dataFrame: DataFrame) {

   def undoMongoStrict(): DataFrame = {
    val numberLongType = StructType(List(StructField("$numberLong", StringType, true)))

    def restructure(fields: Array[StructField], nesting: List[String] = Nil): List[Column] = {
      fields.flatMap(field => {
        val fieldPath = nesting :+ field.name
        val fieldPathStr = fieldPath.mkString(".")
        field.dataType match {
          case dt: StructType if dt == numberLongType =>
            Some(col(s"$fieldPathStr.$$numberLong").cast(LongType).as(field.name))
          case dt: StructType =>
            Some(struct(restructure(dt.fields, fieldPath): _*).as(field.name))
          case _ => Some(col(fieldPathStr).as(field.name))
          //              case dt:ArrayType => //@todo handle other DataTypes Array??
        }
      })
    }.toList

    dataFrame.select(restructure(dataFrame.schema.fields): _*)
  }
}

implicit def dataFrameExtended(df: DataFrame): DataFrameExtended = {
  DataFrameExtended(df)
}

spark
  .read
  .json(inputPath)
  .undoMongoStrict()


问:
How to close admob inersitial after click on it
I use AdMob Interstitials in my Android app in a simple way, just something like in example from

https://developers.google.com/mobile-ads-sdk/docs/admob/advanced?hl=no-NO&csw=1#android

This code works correct. But there is one extra thing I wanna do - close AdMob banner after user clicks it. I mean, when user comes back to my app from page opened with click, there is still AdMob banner on screen, but I wanna see my app's screen.

I do not see the close method or something about it in the class InterstitialAd.

Is there simple way to solve it?

答:
By keeping
onHistory="true" for activity android:name="com.google.ads.AdActivity" in manifest worked for me.</p>


问:
How to access Elasticsearch remotely from Kibana Dashboard?
In simple terms, think of trying visualize your data via Kibana from any computer, but once you get to the Kibana dashboard you see 0 hits/results.

I currently have Elasticsearch on a Linux machine with no GUI (simply changing to a GUI is not allowed).

I'm trying to access my indexes using Kibana (Internet Explorer on a Windows machine).

I also have Kibana running on the Linux machine (./kibana), you can't access the Kibana machine via IP/domain unless you start the (./kibana).

But I don't know which ELK files to configure, and what to configure.

答:
Kibana Dashboards are used to visualize the pre-configred charts, maps, time series etc.

You can not use them to do the administrative operations to your elastic search instance.

Although Kibana does have Dev Tools that you can use to query Elastic search and do mappings etc. To list all the indexes, the query to write in Dev Tools will be GET /_cat/indices?v

However, if you are looking for a GUI based tool to monitor and manage the clusters, nodes etc of Elastic Search, then you can opt for Monitoring that comes with the X-Pack