问:
Function and Triggers in Oracle
how to do the equivalent code in ORACLE

The code is made for Postgresql.

```<code> CREATE FUNCTION emp_stamp() RETURNS trigger AS emp_stamp
    BEGIN
        -- BODY

    END;
$emp_stamp$ LANGUAGE plpgsql;

CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
    FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
</code>```

答:
I don't know Postresql. If you could explain what this piece of code does, it might be easier to assist.  Meanwhile, see if this example helps.

Function accepts employee's EMPNO and returns its MAX salary from the salaries table (doesn't make much sense, but that replaces your --body comment).

```<code>create or replace function emp_stamp (par_empno in emp.empno%type)
  return emp.sal%type
is
  retval emp.sal%type;
begin
  select max(sal)
    into retval
    from salaries
    where empno = par_empno;

  return retval;
end;
/
</code>```

Trigger calls that function and sets employee's emp.sal column to value returned by the function.

```<code>create or replace trigger trg_emp_stamp
  before insert or update on emp
  for each row
begin
  :new.sal := emp_stamp(:new.empno);
end;
/
</code>```

Title: Function and Triggers in Oracle

Body:
how to do the equivalent code in ORACLE

The code is made for Postgresql.

 CREATE FUNCTION emp_stamp() RETURNS trigger AS emp_stamp
    BEGIN
        -- BODY

    END;
$emp_stamp$ LANGUAGE plpgsql;

CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
    FOR EACH ROW EXECUTE PROCEDURE emp_stamp();

Body:
I don't know Postresql. If you could explain what this piece of code does, it might be easier to assist.  Meanwhile, see if this example helps.

Function accepts employee's EMPNO and returns its MAX salary from the salaries table (doesn't make much sense, but that replaces your --body comment).

create or replace function emp_stamp (par_empno in emp.empno%type)
  return emp.sal%type
is
  retval emp.sal%type;
begin
  select max(sal)
    into retval
    from salaries
    where empno = par_empno;

  return retval;
end;
/

Trigger calls that function and sets employee's emp.sal column to value returned by the function.

create or replace trigger trg_emp_stamp
  before insert or update on emp
  for each row
begin
  :new.sal := emp_stamp(:new.empno);
end;
/


来源: stackexchange

问:
Hibernate search lucene : Updating index document by removing a child entity makes children entity as orphan in index document
This is how my entity is configured

```<code>@Entity
@Indexed
public class Book{

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "book")
    @IndexedEmbedded
    private FrontPage frontPage;

...//other data
}
</code>```

```<code>@Entity
public class FrontPage{

    @OneToOne(cascade = {}, fetch = FetchType.EAGER, targetEntity = Book.class)
    @JoinColumn(name = "book_id", nullable = false)
    @ContainedIn
    private Book book;

...//other data

}
</code>```

This is how my integration test looks

```<code>@Test
public void testMerge_RemoveFrontPage() {
    insertDataSet("dataset.xml");

    Book book = getEntityManager().find(Book.class, 2000L);
    //this book instance already have data

    book.setFrontPage(null);

    dao.merge(book);

    //verify after commit
    //In database the FrontPage entity reference is removed

}
</code>```

By looking at the database, the FrontPage entity is removed but in Book index still, I can see the FrontPage data.

the same thing happens if I tried to replace the FrontPage data like this and in the Book index now I can see two FrontPage data.

```<code>book.setFrontPage(new FrontPage);
</code>```

By debugging, FullTextIndexEventListener logs below warnings in logs, not sure if this makes sense but I have a suspect that could be a cause.

org.hibernate.search.event.impl.FullTextIndexEventListener:250 - HSEARCH000024: Unable to reindex entity on collection change, id cannot be extracted: com.x.x.x.FrontPage

Not sure whats going wrong here or is this expected behaviour?

Hibernate versions that I use are,

hibernate-search-elasticsearch, hibernate-search-orm = 5.11.4.Final

答:
Indexing is near-real-time in the Elasticsearch backend by default, meaning changes take some time to be visible in search queries. By default, it only takes one second.

You can request a refresh after every indexed document by setting the property hibernate.search.default.elasticsearch.refresh_after_write to true. If you do that, that changes will be visible immediately after a transaction commit. However, this will lead to poor performance, so I wouldn't recommend it in production: just use that for tests.

From the documentation:

Whether to perform an explicit refresh after a set of operations has
  been executed against a specific index (true or false)

```<code>hibernate.search.default.elasticsearch.refresh_after_write false (default)
</code>```

This is useful in unit tests to ensure that a write is visible by a query immediately without delay. This keeps unit tests simpler. You
  should not rely on the synchronous behaviour for your production code
  except in rare cases as Elasticsearch is optimised for asynchronous
  writes: leave at false for optimal performance.

ContentLicense: CC BY-SA 4.0

Body:
This is how my entity is configured

@Entity
@Indexed
public class Book{

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "book")
    @IndexedEmbedded
    private FrontPage frontPage;

...//other data
}

@Entity
public class FrontPage{

    @OneToOne(cascade = {}, fetch = FetchType.EAGER, targetEntity = Book.class)
    @JoinColumn(name = "book_id", nullable = false)
    @ContainedIn
    private Book book;

...//other data

}

This is how my integration test looks

@Test
public void testMerge_RemoveFrontPage() {
    insertDataSet("dataset.xml");

    Book book = getEntityManager().find(Book.class, 2000L);
    //this book instance already have data

    book.setFrontPage(null);

    dao.merge(book);

    //verify after commit
    //In database the FrontPage entity reference is removed

}

By looking at the database, the FrontPage entity is removed but in Book index still, I can see the FrontPage data.

the same thing happens if I tried to replace the FrontPage data like this and in the Book index now I can see two FrontPage data.

book.setFrontPage(new FrontPage);

By debugging, FullTextIndexEventListener logs below warnings in logs, not sure if this makes sense but I have a suspect that could be a cause.

org.hibernate.search.event.impl.FullTextIndexEventListener:250 - HSEARCH000024: Unable to reindex entity on collection change, id cannot be extracted: com.x.x.x.FrontPage

Not sure whats going wrong here or is this expected behaviour?

Hibernate versions that I use are,

hibernate-search-elasticsearch, hibernate-search-orm = 5.11.4.Final

Body:
Indexing is near-real-time in the Elasticsearch backend by default, meaning changes take some time to be visible in search queries. By default, it only takes one second.

You can request a refresh after every indexed document by setting the property hibernate.search.default.elasticsearch.refresh_after_write to true. If you do that, that changes will be visible immediately after a transaction commit. However, this will lead to poor performance, so I wouldn't recommend it in production: just use that for tests.

From the documentation:

Whether to perform an explicit refresh after a set of operations has
  been executed against a specific index (true or false)

hibernate.search.default.elasticsearch.refresh_after_write false (default)

This is useful in unit tests to ensure that a write is visible by a query immediately without delay. This keeps unit tests simpler. You
  should not rely on the synchronous behaviour for your production code
  except in rare cases as Elasticsearch is optimised for asynchronous
  writes: leave at false for optimal performance.


问:
Using frame through code for a queue
So I have a program that runs a simulation

When you select the model, it opens a screen which lets you select "Run the Model", which opens another screen in which you can press the start button

I want to make a queue so that the user could select multiple models and the program would run through these screens without user input

So, I'm calling a frame like this:

```<code>ProgForm := TProgressForm.Create(Self, FModItem);
Self.Visible := False;
try
 ProgForm.ShowModal;
</code>```

Now, I can get the program to run by adding a line at the end of Create to run the simulation, but the problem is that it doesn't show the frame until the end of the simulation (since the Create constructor isn't finished until the run function I called is finished)

I'm not sure what to do, since if I don't add anything in the Create function I'm calling, there doesn't seem to be any other way to call any function automatically, but if I do something in Create, the frame isn't displayed until Create is finished

Thanks

答:
I suggest reading:

http://delphi.about.com/od/formsdialogs/a/delphiformlife.htm

You can use the form's OnShow event to do stuff before the form is fully drawn on the screen.

OnActivate is usually the best place to do stuff when the form is drawn.

BTW

you say Frame, but in your code it says TProgressForm so I'm guessing you mean Form with a Frame inside.

ContentLicense: CC BY-SA 3.0

Title: Using frame through code for a queue

Body:
So I have a program that runs a simulation

When you select the model, it opens a screen which lets you select "Run the Model", which opens another screen in which you can press the start button

I want to make a queue so that the user could select multiple models and the program would run through these screens without user input

So, I'm calling a frame like this:

ProgForm := TProgressForm.Create(Self, FModItem);
Self.Visible := False;
try
 ProgForm.ShowModal;

Now, I can get the program to run by adding a line at the end of Create to run the simulation, but the problem is that it doesn't show the frame until the end of the simulation (since the Create constructor isn't finished until the run function I called is finished)

I'm not sure what to do, since if I don't add anything in the Create function I'm calling, there doesn't seem to be any other way to call any function automatically, but if I do something in Create, the frame isn't displayed until Create is finished

Thanks


问:
Problem when using extension in a XML Schema
I need to create a XML schema which extends simple types, so I could add an attribute for later use in my code (this attribute won't be used in the generated XML). It must be an extension since I have to estabilish some restrictions to these types.

Problem: msg_1 and msg_2 must have some elements with the same name and it's causing an error.

Error: cos-element-consistent: Error for type '#AnonType_msg'. Multiple elements with name 'Code', with different types, appear in the model group.

I'm aware that making these element names different would solve the problem, but they must be the same, unfortunatelly.

Here's the code:

```<code><xsd:element name="msg">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:group ref="header"/>
            <xsd:choice>
                <xsd:group ref="msg_1"/>
                <xsd:group ref="msg_2"/>
            </xsd:choice>
        </xsd:sequence>
        <xsd:attribute name="IdMsg" type="IdM" use="required"/>
    </xsd:complexType>
</xsd:element>

<xsd:group id="M39" name="msg_1">
    <xsd:sequence>
        <xsd:element name="Code">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="Code">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
        <xsd:element name="ID">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="ID">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
   </xsd:sequence>
</xsd:group>
<xsd:group id="M40" name="msg_2">
    <xsd:sequence>
        <xsd:element name="Code">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="Code">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
        <xsd:element name="ID">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="ID">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
    </xsd:sequence>
</xsd:group>

<xsd:simpleType name="IdM">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="29"/>
        <xsd:maxInclusive value="42"/>
    </xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="ID">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="0"/>
        <xsd:maxInclusive value="255"/>
    </xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="Code">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="0"/>
        <xsd:maxInclusive value="13"/>
    </xsd:restriction>
</xsd:simpleType>
<xsd:group id="M2" name="header">
    <xsd:sequence>
        <xsd:element fixed="2" name="Version" type="xsd:unsignedInt"/>
        <xsd:element name="Timer" type="xsd:unsignedLong"/>
    </xsd:sequence>
</xsd:group>
</code>```

Is there any workaround?

Update:
Assertions are not the case. Basically, I have two different messages(groups) sharing some parameters(child elements).

I guess that namespaces could do the trick, but I'm trying to avoid it, since it's preferrable to have only 1 .xsd file.

I get the part about ambiguity and etc, but it doesn't answer why the code that follows validates just fine. Here's the code:

```<code><xsd:element name="msg">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:group ref="header"/>
            <xsd:choice>
                <xsd:group ref="msg_1"/>
                <xsd:group ref="msg_2"/>
            </xsd:choice>
        </xsd:sequence>
        <xsd:attribute name="IdMsg" type="IdM" use="required"/>
    </xsd:complexType>
</xsd:element>

<xsd:group id="M39" name="msg_1">
    <xsd:sequence>
        <xsd:element name="anything" type="code"/>
        <xsd:element name="something_else" type="code"/>
   </xsd:sequence>
</xsd:group>
<xsd:group id="M40" name="msg_2">
    <xsd:sequence>
        <xsd:element name="nothing" type="code"/>
        <xsd:element name="something_else" type="code"/>
    </xsd:sequence>
</xsd:group>

<xsd:simpleType name="code">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="0"/>
    </xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="IdM">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="29"/>
        <xsd:maxInclusive value="42"/>
    </xsd:restriction>
</xsd:simpleType>

<xsd:group id="M2" name="header">
    <xsd:sequence>
        <xsd:element fixed="2" name="Version" type="xsd:unsignedInt"/>
        <xsd:element name="Timer" type="xsd:unsignedLong"/>
    </xsd:sequence>
</xsd:group>
</code>```

Curiously, it works even with 2 elements sharing the same name (something_else). If the elements named "anything" and "nothing" are taken out of msg_1 and msg_2, the issue about ambiguity returns. Is there any explanation about it? I see no reason for this behavior, so I must be missing something.

PS: The code here is just an example, and I know the 2 groups are exactly the same. I made the code to ilustrate the problem. In my application the groups are different even though they share some elements.

答:
XSD is designed so that when a particular element is encountered by the validator, the validator knows without ambiguity where to find the rules for that element, based solely on its name (and the type of the containing element). Your schema clearly violates that rule: when a Code is encountered, there are two possible definitions and it won't know which one to choose.

If you're trying to write an XSD for an existing class of XML documents where the rules are context-sensitive, then you may be able to express the constraints in a different way, for example using XSD 1.1 assertions, or using Schematron.

Body:
I need to create a XML schema which extends simple types, so I could add an attribute for later use in my code (this attribute won't be used in the generated XML). It must be an extension since I have to estabilish some restrictions to these types.

Problem: msg_1 and msg_2 must have some elements with the same name and it's causing an error.

Error: cos-element-consistent: Error for type '#AnonType_msg'. Multiple elements with name 'Code', with different types, appear in the model group.

I'm aware that making these element names different would solve the problem, but they must be the same, unfortunatelly.

Here's the code:

<xsd:element name="msg">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:group ref="header"/>
            <xsd:choice>
                <xsd:group ref="msg_1"/>
                <xsd:group ref="msg_2"/>
            </xsd:choice>
        </xsd:sequence>
        <xsd:attribute name="IdMsg" type="IdM" use="required"/>
    </xsd:complexType>
</xsd:element>

<xsd:group id="M39" name="msg_1">
    <xsd:sequence>
        <xsd:element name="Code">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="Code">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
        <xsd:element name="ID">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="ID">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
   </xsd:sequence>
</xsd:group>
<xsd:group id="M40" name="msg_2">
    <xsd:sequence>
        <xsd:element name="Code">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="Code">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
        <xsd:element name="ID">
            <xsd:complexType>
                <xsd:simpleContent>
                    <xsd:extension base="ID">
                        <xsd:attribute name="compact" use="prohibited"/>
                    </xsd:extension>
                </xsd:simpleContent>
            </xsd:complexType>
        </xsd:element>
    </xsd:sequence>
</xsd:group>

<xsd:simpleType name="IdM">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="29"/>
        <xsd:maxInclusive value="42"/>
    </xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="ID">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="0"/>
        <xsd:maxInclusive value="255"/>
    </xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="Code">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="0"/>
        <xsd:maxInclusive value="13"/>
    </xsd:restriction>
</xsd:simpleType>
<xsd:group id="M2" name="header">
    <xsd:sequence>
        <xsd:element fixed="2" name="Version" type="xsd:unsignedInt"/>
        <xsd:element name="Timer" type="xsd:unsignedLong"/>
    </xsd:sequence>
</xsd:group>

Is there any workaround?

Update:
Assertions are not the case. Basically, I have two different messages(groups) sharing some parameters(child elements).

I guess that namespaces could do the trick, but I'm trying to avoid it, since it's preferrable to have only 1 .xsd file.

I get the part about ambiguity and etc, but it doesn't answer why the code that follows validates just fine. Here's the code:

<xsd:element name="msg">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:group ref="header"/>
            <xsd:choice>
                <xsd:group ref="msg_1"/>
                <xsd:group ref="msg_2"/>
            </xsd:choice>
        </xsd:sequence>
        <xsd:attribute name="IdMsg" type="IdM" use="required"/>
    </xsd:complexType>
</xsd:element>

<xsd:group id="M39" name="msg_1">
    <xsd:sequence>
        <xsd:element name="anything" type="code"/>
        <xsd:element name="something_else" type="code"/>
   </xsd:sequence>
</xsd:group>
<xsd:group id="M40" name="msg_2">
    <xsd:sequence>
        <xsd:element name="nothing" type="code"/>
        <xsd:element name="something_else" type="code"/>
    </xsd:sequence>
</xsd:group>

<xsd:simpleType name="code">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="0"/>
    </xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="IdM">
    <xsd:restriction base="xsd:unsignedByte">
        <xsd:minInclusive value="29"/>
        <xsd:maxInclusive value="42"/>
    </xsd:restriction>
</xsd:simpleType>

<xsd:group id="M2" name="header">
    <xsd:sequence>
        <xsd:element fixed="2" name="Version" type="xsd:unsignedInt"/>
        <xsd:element name="Timer" type="xsd:unsignedLong"/>
    </xsd:sequence>
</xsd:group>

Curiously, it works even with 2 elements sharing the same name (something_else). If the elements named "anything" and "nothing" are taken out of msg_1 and msg_2, the issue about ambiguity returns. Is there any explanation about it? I see no reason for this behavior, so I must be missing something.

PS: The code here is just an example, and I know the 2 groups are exactly the same. I made the code to ilustrate the problem. In my application the groups are different even though they share some elements.


问:
SwiftKuery, KituraStencil compilation problem with resultSet.forEach()
I'm a complete beginner at swift development and I can't get the following code to compile:

```<code>import Kitura
import KituraStencil
import SwiftKuery
import SwiftKuerySQLite
[...]
resultSet.forEach() { row, error in
    guard let row = row else {
        guard let _ = error else {
            // Processed all results
            try response.render("themes.stencil", with: themes, forKey: "themes")
        }
        // Handle error
        return
    }

    /* build 'themes' object */
    [...]
}
[...]
</code>```

Get this error:
 error: contextual closure type '([Any?]?, Error?, () -> Void) -> Void' expects 3 arguments, but 2 were used in closure body
            resultSet.forEach() { row, error in

So I tried the following:

```<code>import Kitura
import KituraStencil
import SwiftKuery
import SwiftKuerySQLite
[...]
resultSet.forEach() { row, error, dummy in
    guard let row = row else {
        guard let _ = error else {
            // Processed all results
            try response.render("themes.stencil", with: themes, forKey: "themes")
        }
        // Handle error
        return
    }

    /* build 'themes' object */
    [...]
}
[...]
</code>```

And then I get this error:
error: contextual closure type '([Any?]?, Error?) -> Void' expects 2 arguments, but 3 were used in closure body
            resultSet.forEach() { row, error, dummy in

In both case if I replace try response.render("themes.stencil", with: themes, forKey: "themes") with return there is no compilation error

What am I doing wrong?

答:
Finally fixed the problem this way (unhandled exception):</p>

```<code>[...]
resultSet.forEach() { row, error, dummy in
    guard let row = row else {
        guard let _ = error else {
            // Processed all results
            do {
                try response.render("themes.stencil", with: themes, forKey: "themes")
            }
            catch { }
        }
        // Handle error
        return
    }

    /* build 'themes' object */
    [...]
}
[...]
</code>```

Body:
I'm a complete beginner at swift development and I can't get the following code to compile:

import Kitura
import KituraStencil
import SwiftKuery
import SwiftKuerySQLite
[...]
resultSet.forEach() { row, error in
    guard let row = row else {
        guard let _ = error else {
            // Processed all results
            try response.render("themes.stencil", with: themes, forKey: "themes")
        }
        // Handle error
        return
    }

    /* build 'themes' object */
    [...]
}
[...]

Get this error:
 error: contextual closure type '([Any?]?, Error?, () -> Void) -> Void' expects 3 arguments, but 2 were used in closure body
            resultSet.forEach() { row, error in

So I tried the following:

import Kitura
import KituraStencil
import SwiftKuery
import SwiftKuerySQLite
[...]
resultSet.forEach() { row, error, dummy in
    guard let row = row else {
        guard let _ = error else {
            // Processed all results
            try response.render("themes.stencil", with: themes, forKey: "themes")
        }
        // Handle error
        return
    }

    /* build 'themes' object */
    [...]
}
[...]

And then I get this error:
error: contextual closure type '([Any?]?, Error?) -> Void' expects 2 arguments, but 3 were used in closure body
            resultSet.forEach() { row, error, dummy in

In both case if I replace try response.render("themes.stencil", with: themes, forKey: "themes") with return there is no compilation error

What am I doing wrong?

Body:
Finally fixed the problem this way (unhandled exception):

[...]
resultSet.forEach() { row, error, dummy in
    guard let row = row else {
        guard let _ = error else {
            // Processed all results
            do {
                try response.render("themes.stencil", with: themes, forKey: "themes")
            }
            catch { }
        }
        // Handle error
        return
    }

    /* build 'themes' object */
    [...]
}
[...]


问:
Puppet - Duplicate declaration for Registry_key
I have a manifest file to add registry keys and values based on facts (works fine).

```<code>       registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
          ensure => present,
        }

        registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
         ensure => present,
         type   => dword,
         data   => $test_key_value,
       }
</code>```

I want to add a second file to remove these if required but when i do i get an error

"Duplicate declaration: Registry_key[HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate] is already declared"

Not sure how to get around this - if at all? Any advice appreciated. Obviously a puppet novice...

Thanks

答:
If you want to solve this problem, you would probably use custom or external facts, something like this:

$ensure = $facts['include_windows_update_keys']

registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
  ensure => $ensure,
}

registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
  ensure => $ensure,
  type   => dword,
  data   => $test_key_value,
}
```

As you have discovered, declaring the same resource more than once but with different attributes is not allowed in Puppet.

There is more on custom facts here in the docs.

Body:
I have a manifest file to add registry keys and values based on facts (works fine).

       registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
          ensure => present,
        }

        registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
         ensure => present,
         type   => dword,
         data   => $test_key_value,
       }

I want to add a second file to remove these if required but when i do i get an error

"Duplicate declaration: Registry_key[HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate] is already declared"

Not sure how to get around this - if at all? Any advice appreciated. Obviously a puppet novice...

Thanks

Body:
If you want to solve this problem, you would probably use custom or external facts, something like this:

$ensure = $facts['include_windows_update_keys']

registry_key { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate':
  ensure => $ensure,
}

registry_value { 'HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\TestKey':
  ensure => $ensure,
  type   => dword,
  data   => $test_key_value,
}

As you have discovered, declaring the same resource more than once but with different attributes is not allowed in Puppet.

There is more on custom facts here in the docs.


问:
How to mock Base64 in Android?
I am writing a Unit test for a class that uses android.util.Base64 and I get this error:

```<code>java.lang.RuntimeException: Method encode in android.util.Base64 not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.util.Base64.encode(Base64.java)
</code>```

This is the code using the encode() method:

```<code>ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// [write some data to the stream]
byte[] base64Bytes = Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
</code>```

Now I understand that I can't use Android library classes in my Unit tests. But how do I correctly mock Base64 so I can write a correct Unit test for my class?

答:
I'm late but maybe that will help somebody.
For JUnit you can mock up the class without any third party lib. Just create a file Base64.java inside app/src/test/java/android/util with contents:

```<code>package android.util;

public class Base64 {

    public static String encodeToString(byte[] input, int flags) {
        return java.util.Base64.getEncoder().encodeToString(input);
    }

    public static byte[] decode(String str, int flags) {
        return java.util.Base64.getDecoder().decode(str);
    }

    // add other methods if required...
}
</code>```

Title: How to mock Base64 in Android?

Body:
I am writing a Unit test for a class that uses android.util.Base64 and I get this error:

java.lang.RuntimeException: Method encode in android.util.Base64 not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.util.Base64.encode(Base64.java)

This is the code using the encode() method:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// [write some data to the stream]
byte[] base64Bytes = Base64.encode(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

Now I understand that I can't use Android library classes in my Unit tests. But how do I correctly mock Base64 so I can write a correct Unit test for my class?

Body:
I'm late but maybe that will help somebody.
For JUnit you can mock up the class without any third party lib. Just create a file Base64.java inside app/src/test/java/android/util with contents:

package android.util;

public class Base64 {

    public static String encodeToString(byte[] input, int flags) {
        return java.util.Base64.getEncoder().encodeToString(input);
    }

    public static byte[] decode(String str, int flags) {
        return java.util.Base64.getDecoder().decode(str);
    }

    // add other methods if required...
}


问:
Django, exclude from main list, but viewable from django filter
I'm trying to add an archive section to my site, though when I say archive, I mean just not visible in the main list view that is the home page, the site is small and the projects are just small amounts of text so space and optimization are never going to be needed. I use django-filter to search through projects by department(Area in my code), and "Archive" is down as one of the departments. I've tried using exclude in the queryset, but of course that just removes any projects with area="Archive" completely so that the "Archive" section is empty. How can I get archived projects removed from the main list view but searchable via the filter.

View:

```<code>def project_list_view(request):
    project_list = Project.objects.annotate(
        display_date = models.Case(
            models.When(models.Q(staff_trials__isnull=True) | models.Q(timeline_switch=False), then=models.F('launch')),
            models.When(models.Q(staff_trials__isnull=False) & models.Q(timeline_switch=True), then=models.F('staff_trials')),
            output_field=models.DateField(),
        )
    ).exclude(area='1').order_by('-slip', 'display_date')

    project_filter = ProjectFilter(request.GET, queryset=project_list)
    return render(
        request,
        'project_portal/project_list.html',
        {'filter': project_filter}
        )
</code>```

filter:

```<code>class ProjectFilter(django_filters.FilterSet):

    class Meta:
        model = Project
        fields = ['area', 'user']
</code>```

For clarity, Area has it's own Model with a foreign key to the Project model, and the departments are just entries in the database. The above code kind of does what I want, but as mentioned before makes archived projects not accessible in any way, whereas I want them to show if "Archive" is picked from the search dropdown.

答:
One possible solution is add exclude to your queryset only if area filter not equal to archived:

```<code>def project_list_view(request):
    project_list = Project.objects.annotate(
        display_date = models.Case(
            models.When(models.Q(staff_trials__isnull=True) | models.Q(timeline_switch=False), then=models.F('launch')),
            models.When(models.Q(staff_trials__isnull=False) & models.Q(timeline_switch=True), then=models.F('staff_trials')),
            output_field=models.DateField(),
        )
    ).order_by('-slip', 'display_date')

    if request.GET.get('area') != '1':
        project_list = project_list.exclude(area='1')

    project_filter = ProjectFilter(request.GET, queryset=project_list)
    return render(
        request,
        'project_portal/project_list.html',
        {'filter': project_filter}
        )
</code>```

Body:
I'm trying to add an archive section to my site, though when I say archive, I mean just not visible in the main list view that is the home page, the site is small and the projects are just small amounts of text so space and optimization are never going to be needed. I use django-filter to search through projects by department(Area in my code), and "Archive" is down as one of the departments. I've tried using exclude in the queryset, but of course that just removes any projects with area="Archive" completely so that the "Archive" section is empty. How can I get archived projects removed from the main list view but searchable via the filter.

View:

def project_list_view(request):
    project_list = Project.objects.annotate(
        display_date = models.Case(
            models.When(models.Q(staff_trials__isnull=True) | models.Q(timeline_switch=False), then=models.F('launch')),
            models.When(models.Q(staff_trials__isnull=False) & models.Q(timeline_switch=True), then=models.F('staff_trials')),
            output_field=models.DateField(),
        )
    ).exclude(area='1').order_by('-slip', 'display_date')

    project_filter = ProjectFilter(request.GET, queryset=project_list)
    return render(
        request,
        'project_portal/project_list.html',
        {'filter': project_filter}
        )

filter:

class ProjectFilter(django_filters.FilterSet):

    class Meta:
        model = Project
        fields = ['area', 'user']

For clarity, Area has it's own Model with a foreign key to the Project model, and the departments are just entries in the database. The above code kind of does what I want, but as mentioned before makes archived projects not accessible in any way, whereas I want them to show if "Archive" is picked from the search dropdown.

Body:
One possible solution is add exclude to your queryset only if area filter not equal to archived:

def project_list_view(request):
    project_list = Project.objects.annotate(
        display_date = models.Case(
            models.When(models.Q(staff_trials__isnull=True) | models.Q(timeline_switch=False), then=models.F('launch')),
            models.When(models.Q(staff_trials__isnull=False) & models.Q(timeline_switch=True), then=models.F('staff_trials')),
            output_field=models.DateField(),
        )
    ).order_by('-slip', 'display_date')

    if request.GET.get('area') != '1':
        project_list = project_list.exclude(area='1')

    project_filter = ProjectFilter(request.GET, queryset=project_list)
    return render(
        request,
        'project_portal/project_list.html',
        {'filter': project_filter}
        )


问:
How to parse EDIfact file containing multiple items using EDI.Net?
I am using EDI.Net from indice-co and i have a EDI file that contains multiple items, when i use the EdiGrammer.NewEdiFact and read the file using stream and deserialize it I get only 1 item from the file, the top most; how do i read the file using stream and deserialize it to a list?

Code Example:

```<code> var editFactParser = EdiGrammar.NewEdiFact();

        var interchange = default(EdiModel.Interchange);
        using (
            var stream = File.Open("E:\\SomePath\\20191121020103.00000091.EDI", FileMode.Open,
                FileAccess.Read))
        {
            interchange = new EdiSerializer().Deserialize<EdiModel.Interchange>(new StreamReader(stream),
                editFactParser );
        }
</code>```

EdiFact File Content

```<code>UNA:+.? 'UNB+UNOA:2+DHLEUAPGW+CENTIRO+191030:1347+203516'UNH+240179+IFTSTA:D:01B:UN'BGM+77+9690108+9'DTM+9:201910301347:203'NAD+CZ+9690108'CNI+1+1032173'LOC+5+AMS::87'LOC+8+AMS::87'STS++PU+:::SHIPMENT PICKUP'RFF+CN:1297617'DTM+11:20191030:102'DTM+7:201910301329:203'GID++1'PCI+18'GIN+BN+10321732'UNT+15+240179'UNH+240180+IFTSTA:D:01B:UN'BGM+77+9690108+9'DTM+9:201910301347:203'NAD+CZ+96901083'CNI+1+2598018'LOC+5+ORY::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:116775116'DTM+11:20191029:102'DTM+7:201910301336:203'GID++1'PCI+18'GIN+BN+2598018043'CNI+2+4911357323'LOC+5+CDG::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:1286700'DTM+11:20191029:102'DTM+7:201910301339:203'GID++1'PCI+18'GIN+BN+49113573'CNI+3+4911401'LOC+5+CDG::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:129007'DTM+11:20191029:102'DTM+7:201910301337:203'GID++1'PCI+18'GIN+BN+49114019'CNI+4+6194460'LOC+5+BRU::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:127214241'DTM+11:20191029:102'DTM+7:201910301339:203'GID++1'PCI+18'GIN+BN+6194460856'CNI+5+7525715'LOC+5+ORY::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:ECONOCOM'DTM+11:20191029:102'DTM+7:201910301336:203'GID++1'PCI+18'GIN+BN+75257154'CNI+6+752571'LOC+5+ORY::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:ECONOCOM'DTM+11:20191029:102'DTM+7:201910301339:203'GID++1'PCI+18'GIN+BN+7525715'UNT+65+240180'UNZ+2+203516'
</code>```

答: sorry for the late reply, I was able to solve it, it was an issue how with how I was accessing the segments and what data I was trying to get back, after some more trial and error I was able to figure it out, I currently do not have access to the code and will try and post it back here when I get to it. Thank you.</p>

Body:
I am using EDI.Net from indice-co and i have a EDI file that contains multiple items, when i use the EdiGrammer.NewEdiFact and read the file using stream and deserialize it I get only 1 item from the file, the top most; how do i read the file using stream and deserialize it to a list?

Code Example:

 var editFactParser = EdiGrammar.NewEdiFact();

        var interchange = default(EdiModel.Interchange);
        using (
            var stream = File.Open("E:\\SomePath\\20191121020103.00000091.EDI", FileMode.Open,
                FileAccess.Read))
        {
            interchange = new EdiSerializer().Deserialize<EdiModel.Interchange>(new StreamReader(stream),
                editFactParser );
        }

EdiFact File Content

UNA:+.? 'UNB+UNOA:2+DHLEUAPGW+CENTIRO+191030:1347+203516'UNH+240179+IFTSTA:D:01B:UN'BGM+77+9690108+9'DTM+9:201910301347:203'NAD+CZ+9690108'CNI+1+1032173'LOC+5+AMS::87'LOC+8+AMS::87'STS++PU+:::SHIPMENT PICKUP'RFF+CN:1297617'DTM+11:20191030:102'DTM+7:201910301329:203'GID++1'PCI+18'GIN+BN+10321732'UNT+15+240179'UNH+240180+IFTSTA:D:01B:UN'BGM+77+9690108+9'DTM+9:201910301347:203'NAD+CZ+96901083'CNI+1+2598018'LOC+5+ORY::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:116775116'DTM+11:20191029:102'DTM+7:201910301336:203'GID++1'PCI+18'GIN+BN+2598018043'CNI+2+4911357323'LOC+5+CDG::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:1286700'DTM+11:20191029:102'DTM+7:201910301339:203'GID++1'PCI+18'GIN+BN+49113573'CNI+3+4911401'LOC+5+CDG::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:129007'DTM+11:20191029:102'DTM+7:201910301337:203'GID++1'PCI+18'GIN+BN+49114019'CNI+4+6194460'LOC+5+BRU::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:127214241'DTM+11:20191029:102'DTM+7:201910301339:203'GID++1'PCI+18'GIN+BN+6194460856'CNI+5+7525715'LOC+5+ORY::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:ECONOCOM'DTM+11:20191029:102'DTM+7:201910301336:203'GID++1'PCI+18'GIN+BN+75257154'CNI+6+752571'LOC+5+ORY::87'LOC+8+AMS::87'STS++PL+:::PROCESSED AT LOCATION'RFF+CN:ECONOCOM'DTM+11:20191029:102'DTM+7:201910301339:203'GID++1'PCI+18'GIN+BN+7525715'UNT+65+240180'UNZ+2+203516'


问:
SQL syntax near WHERE?
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?</p>

```<code>protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}
</code>```

答:
That is incorrect INSERT syntax. Correct INSERT syntax is:

```<code>INSERT INTO tableName (columnList) VALUES (valueList)
</code>```

columnList and valueList must have same count of items and values must be of type expected by columns.

or

```<code>INSERT INTO tableName (columnList)
SELECT columnList2
FROM tableName2
WHERE conditionsFromTable2
</code>```

columnList and columnList2 must have same count of items of same types. You can use any complicated select joined over multiple tables with condition applied on data from these tables.

Title: SQL syntax near WHERE?

Body:
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?

protected void BtnSubmit_Click(object sender, EventArgs e)
{
    string x = Request.QueryString["SubId"];
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
    string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
    using (SqlConnection sqlConn = new SqlConnection(connectionString))
    {
        sqlConn.Open();
        using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
        {
            comCmd.ExecuteNonQuery();
        }
    }
}

Body:
That is incorrect INSERT syntax. Correct INSERT syntax is:

INSERT INTO tableName (columnList) VALUES (valueList)

columnList and valueList must have same count of items and values must be of type expected by columns.

or

INSERT INTO tableName (columnList)
SELECT columnList2
FROM tableName2
WHERE conditionsFromTable2

columnList and columnList2 must have same count of items of same types. You can use any complicated select joined over multiple tables with condition applied on data from these tables.


问:
Expanding column values as key and values in DataFrame
I have a DataFrame like:

```<code>df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B':['d', 'e', 'f'], 'C':[1,2,3], 'D':[4,5,6]})

A   B   C   D
a   d   1   4
b   e   2   5
c   f   3   6
</code>```

I have to expand columns C and D treating A and B as keys. The output should look like:

```<code>A   B   key val
a   d   C   1
a   d   D   4
b   e   C   2
b   e   D   5
c   f   C   3
c   f   D   6
</code>```

I have coded this as:

```<code>df_new = pd.DataFrame()
list_to_expand = ['C', 'D']
for index, row in df.iterrows():
    for l in list_to_expand:
        df_new = df_new.append(
             pd.DataFrame({'A': row['A'],'B': row['B'], 'key': l, 'val': row[l]},
             index=[0]))
</code>```

I need to optimize my code in a vectorized format but couldn't find any function. Please note that the list of columns can increase i.e. ['C', 'D', 'E'...]. I am using python3 and pandas.

答:
You want DataFrame.melt:

```<code>df.melt(id_vars=['A', 'B'], var_name='key', value_name='val')

   A  B key  val
0  a  d   C    1
1  b  e   C    2
2  c  f   C    3
3  a  d   D    4
4  b  e   D    5
5  c  f   D    6
</code>```

Body:
I have a DataFrame like:

df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B':['d', 'e', 'f'], 'C':[1,2,3], 'D':[4,5,6]})

A   B   C   D
a   d   1   4
b   e   2   5
c   f   3   6

I have to expand columns C and D treating A and B as keys. The output should look like:

A   B   key val
a   d   C   1
a   d   D   4
b   e   C   2
b   e   D   5
c   f   C   3
c   f   D   6

I have coded this as:

df_new = pd.DataFrame()
list_to_expand = ['C', 'D']
for index, row in df.iterrows():
    for l in list_to_expand:
        df_new = df_new.append(
             pd.DataFrame({'A': row['A'],'B': row['B'], 'key': l, 'val': row[l]},
             index=[0]))

I need to optimize my code in a vectorized format but couldn't find any function. Please note that the list of columns can increase i.e. ['C', 'D', 'E'...]. I am using python3 and pandas.

Body:
You want DataFrame.melt:

df.melt(id_vars=['A', 'B'], var_name='key', value_name='val')

   A  B key  val
0  a  d   C    1
1  b  e   C    2
2  c  f   C    3
3  a  d   D    4
4  b  e   D    5
5  c  f   D    6


问:
Bamboo Deploy via Bastion Host
How can I configure a Bamboo Deployment Task to use a SSH Bastion (jump) host to connect to the target deployment server to run a script?

I've tried configuring a .ssh/config file on the bamboo server. It works from the command line but it is ignored by Bamboo.

答:
I think this can be worked around by defining the host in your .ssh/config and using -J option there. In Bamboo use the alias that is defined in .ssh/config. Behind the scenes it's just SSH commands and will probably pick up the alias

I did not test this.

Title: Bamboo Deploy via Bastion Host


问:
How to change a variable UITextView after clicking the button?
I create UITextView with a random tag and text, but it is created with one variable, is it possible to update the variable after creation UITextView (by clicking the add button)? Maybe add a random number to it, for example newText1, newText2.. etc.

So that the next UITextView is already created with a new variable?

P.S Sorry, if the question is silly, I just recently started to study Swift

```<code>@IBOutlet weak var addTextButton: UIButton!
@IBOutlet weak var StoriesView: UIView!

var newText = UITextView()

override func viewDidLoad() {
        super.viewDidLoad()
}

@IBAction func addTextButton(_ sender: Any) {

        let maxNumber = 10000
        let i = Int(arc4random_uniform(UInt32(maxNumber)))

        newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
         self.StoriesView.addSubview(newText)

         newText.font = UIFont(name: "Verdana", size: 11)
         newText.text = "TAP TO EDIT #\(i)"
         newText.sizeToFit()
         newText.textColor = UIColor.black
         newText.backgroundColor = UIColor.clear
         newText.tag = i

         newText.isEditable = true
         newText.isSelectable = true
         newText.isUserInteractionEnabled = true
         newText.allowsEditingTextAttributes = true
         newText.translatesAutoresizingMaskIntoConstraints = true

         newText.enablesReturnKeyAutomatically = true

         newText.delegate = self
       }
</code>```

UPD:

```<code>let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        fontToolbar.barStyle = .default
        fontToolbar.items = [
            UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
             UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
             UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
        UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
        fontToolbar.sizeToFit()
        newText.inputAccessoryView = fontToolbar
</code>```

in the toolBar above the keyboard I have buttons, here we change the color

```<code>@objc func redColor() {
        newText.textColor = UIColor.red}

    @objc func blueColor() {
        newText.textColor = UIColor.blue}

    @objc func greenColor() {
        newText.textColor = UIColor.green}
</code>```

So the color changes only in the newly created UITextView

答:
On click of button, create a new texView and assign it a tag value. Once it is added, update the value of i to +1, so that every textView added has a new tag value.

```<code>var i = 1
var newText = UITextView()

@IBAction func addTextButton(_ sender: Any) {

    newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
     self.StoriesView.addSubview(newText)

    newText.font = UIFont(name: "Verdana", size: 11)
    newText.text = "TAP TO EDIT #\(i)"
    newText.sizeToFit()
    newText.textColor = UIColor.black
    newText.backgroundColor = UIColor.clear
    newText.tag = i

    newText.isEditable = true
    newText.isSelectable = true
    newText.isUserInteractionEnabled = true
    newText.allowsEditingTextAttributes = true
    newText.translatesAutoresizingMaskIntoConstraints = true

    newText.enablesReturnKeyAutomatically = true

    newText.delegate = self
    //increment i
    i+=1
}
</code>```

then you can access your textField via tag values like this:

```<code>if let textView = self.StoriesView.viewWithTag(i) as? UITextView {
     // textView.text = "change it"
}
</code>```

UPDATE:

Add textView Delegate method, and once a textView starts editing, change the newText value to the currently editing textView

```<code>class ViewController : UIViewController, UITextViewDelegate {

    func textViewDidBeginEditing(_ textView: UITextView) {
        newText = textView
    }
}
</code>```

Body:
I create UITextView with a random tag and text, but it is created with one variable, is it possible to update the variable after creation UITextView (by clicking the add button)? Maybe add a random number to it, for example newText1, newText2.. etc.

So that the next UITextView is already created with a new variable?

P.S Sorry, if the question is silly, I just recently started to study Swift

@IBOutlet weak var addTextButton: UIButton!
@IBOutlet weak var StoriesView: UIView!

var newText = UITextView()

override func viewDidLoad() {
        super.viewDidLoad()
}

@IBAction func addTextButton(_ sender: Any) {

        let maxNumber = 10000
        let i = Int(arc4random_uniform(UInt32(maxNumber)))

        newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
         self.StoriesView.addSubview(newText)

         newText.font = UIFont(name: "Verdana", size: 11)
         newText.text = "TAP TO EDIT #\(i)"
         newText.sizeToFit()
         newText.textColor = UIColor.black
         newText.backgroundColor = UIColor.clear
         newText.tag = i

         newText.isEditable = true
         newText.isSelectable = true
         newText.isUserInteractionEnabled = true
         newText.allowsEditingTextAttributes = true
         newText.translatesAutoresizingMaskIntoConstraints = true

         newText.enablesReturnKeyAutomatically = true

         newText.delegate = self
       }

UPD:

let fontToolbar = UIToolbar(frame:CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50))
        fontToolbar.barStyle = .default
        fontToolbar.items = [
            UIBarButtonItem(title: "Green", style: .plain, target: self, action: #selector(greenColor)),
             UIBarButtonItem(title: "Blue", style: .plain, target: self, action: #selector(blueColor)),
             UIBarButtonItem(title: "Red", style: .plain, target: self, action: #selector(redColor)),
        UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
        UIBarButtonItem(title: "Close Keyboard", style: .plain, target: self, action: #selector(dismissKeyboard))]
        fontToolbar.sizeToFit()
        newText.inputAccessoryView = fontToolbar

in the toolBar above the keyboard I have buttons, here we change the color

@objc func redColor() {
        newText.textColor = UIColor.red}

    @objc func blueColor() {
        newText.textColor = UIColor.blue}

    @objc func greenColor() {
        newText.textColor = UIColor.green}

So the color changes only in the newly created UITextView

Body:
On click of button, create a new texView and assign it a tag value. Once it is added, update the value of i to +1, so that every textView added has a new tag value.

var i = 1
var newText = UITextView()

@IBAction func addTextButton(_ sender: Any) {

    newText = UITextView(frame: CGRect(x: self.StoriesView.frame.origin.x + 40, y: self.StoriesView.frame.origin.y + 40, width: 380, height: 80))
     self.StoriesView.addSubview(newText)

    newText.font = UIFont(name: "Verdana", size: 11)
    newText.text = "TAP TO EDIT #\(i)"
    newText.sizeToFit()
    newText.textColor = UIColor.black
    newText.backgroundColor = UIColor.clear
    newText.tag = i

    newText.isEditable = true
    newText.isSelectable = true
    newText.isUserInteractionEnabled = true
    newText.allowsEditingTextAttributes = true
    newText.translatesAutoresizingMaskIntoConstraints = true

    newText.enablesReturnKeyAutomatically = true

    newText.delegate = self
    //increment i
    i+=1
}

then you can access your textField via tag values like this:

if let textView = self.StoriesView.viewWithTag(i) as? UITextView {
     // textView.text = "change it"
}

UPDATE:

Add textView Delegate method, and once a textView starts editing, change the newText value to the currently editing textView

class ViewController : UIViewController, UITextViewDelegate {

    func textViewDidBeginEditing(_ textView: UITextView) {
        newText = textView
    }
}


问:
Form an numpy array from indices and fill with zeroes
I have a nympy array a = np.array([483, 39, 18, 999, 20, 48]

I have an array of indices indices = np.array([2, 3])

I would like to have all the indices of the array and fill the rest of the indices with 0 so I get as a result :

np.array([0, 0, 18, 999, 0, 0])

Thank you for your answer.

答:
What about using list comprehension?</p>

```<code>a = np.array([n if i in indices else 0 for i, n in enumerate(a)])

print(a) #array([  0,   0,  18, 999,   0,   0])
</code>```

Body:
What about using list comprehension?

a = np.array([n if i in indices else 0 for i, n in enumerate(a)])

print(a) #array([  0,   0,  18, 999,   0,   0])


问:
Remove duplicates from rows in mydataset
Im having a CSV file which contain 436 columns and 14k rows.
The format of the data inside the cells is string.
For the example it looks like this:

```<code>A,A,A,B,B,C,C,,,,,
D,F,D,F,D,F,H,,,,,
</code>```

My goal is to get every row with its unique values only. Like that:

```<code>A,B,C,,,,,,,,
D,F,H,,,,,,,,
</code>```

The file is on csv/txt file. I can use Jupyter notebook( with Python3 or any other code you guys will provide). But this is my enviorment of work. Any help would be amazing!
I also uploaded the csv as a Dataframe to the notebook. What you guys suggest?

答:
First you have to read your csv file into a numpy array. Then for each row, I'd do something like:

```<code>import numpy as np
s='A,A,A,B,B,C,C'
f=s.split(',')
np.unique(np.array(f))
</code>```

which prints array(['A', 'B', 'C'], dtype='|S1').

Body:
Im having a CSV file which contain 436 columns and 14k rows.
The format of the data inside the cells is string.
For the example it looks like this:

A,A,A,B,B,C,C,,,,,
D,F,D,F,D,F,H,,,,,

My goal is to get every row with its unique values only. Like that:

A,B,C,,,,,,,,
D,F,H,,,,,,,,

The file is on csv/txt file. I can use Jupyter notebook( with Python3 or any other code you guys will provide). But this is my enviorment of work. Any help would be amazing!
I also uploaded the csv as a Dataframe to the notebook. What you guys suggest?

Body:
First you have to read your csv file into a numpy array. Then for each row, I'd do something like:

import numpy as np
s='A,A,A,B,B,C,C'
f=s.split(',')
np.unique(np.array(f))

which prints array(['A', 'B', 'C'], dtype='|S1').


问:
Display message when some or all checkboxes aren't checked
I have this page that has multiple checkboxes and when clicked, an element appears.

I have this stripped down version to show it simply:

```<code><!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

Checkbox 1: <input type="checkbox" id="check1"  onclick="box1()"><br>
Checkbox 2: <input type="checkbox" id="check2"  onclick="box2()">

<p id="fill">No boxes are checked</p>

<p id="text" style="display:none">Checkbox1 is CHECKED!</p>
<p id="text2" style="display:none">Checkbox2 is CHECKED!</p>

<script>
function box1() {
  var checkBox = document.getElementById("check1");
  var text = document.getElementById("text");
  var fill = document.getElementById("fill");
  if (checkBox.checked == true){
      text.style.display = "block";
      fill.style.display = "none";
  } else {
      text.style.display = "none";
      fill.style.display = "block";
  }
}
</script>
<script>
function box2() {
  var checkBox = document.getElementById("check2");
  var text = document.getElementById("text2");
  var fill = document.getElementById("fill");
  if (checkBox.checked == true){
    text.style.display = "block";
    fill.style.display = "none";
  } else {
     text.style.display = "none";
     fill.style.display = "block";
  }
 }
</script>

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

My problem is that the text shows even a box is checked as shown in the image. How can I do this effectively? thanks!

答:
I'd add the same listener to both checkboxes, and have that listener check the state of both. Then, if both are not checked, display the fill:

const isCheckeds = document.querySelectorAll('.is-checked');
const fill = document.querySelector('#fill');
function validate() {
  let anyChecked = false;
  document.querySelectorAll('input').forEach((checkbox, i) => {
    if (checkbox.checked) {
      anyChecked = true;
    }
    isCheckeds[i].style.display = checkbox.checked ? 'block' : 'none';
  });
  fill.style.display = anyChecked ? 'none' : 'block';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Display some text when the checkbox is checked:</p>

Checkbox 1: <input type="checkbox" onclick="validate()"><br>
Checkbox 2: <input type="checkbox" onclick="validate()">

<p id="fill">No boxes are checked</p>

<p class="is-checked" style="display:none">Checkbox1 is CHECKED!</p>
<p class="is-checked" style="display:none">Checkbox2 is CHECKED!</p></code>```

Note that inline handlers should be avoided. Strongly consider attaching them properly with Javascript instead. You could also consider using a change listener instead of a click listener (for better accessablity), and you could surround the inputs in a  to make them more clickable:

const isCheckeds = document.querySelectorAll('.is-checked');
const fill = document.querySelector('#fill');
const checkboxes = document.querySelectorAll('input');
function validate() {
  let anyChecked = false;
  checkboxes.forEach((checkbox, i) => {
    if (checkbox.checked) {
      anyChecked = true;
    }
    isCheckeds[i].style.display = checkbox.checked ? 'block' : 'none';
  });
  fill.style.display = anyChecked ? 'none' : 'block';
}
for (const checkbox of checkboxes) {
  checkbox.addEventListener('change', validate);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Display some text when the checkbox is checked:</p>

<label>Checkbox 1: <input type="checkbox"></label><br>
<label>Checkbox 2: <input type="checkbox"></label>

<p id="fill">No boxes are checked</p>

<p class="is-checked" style="display:none">Checkbox1 is CHECKED!</p>
<p class="is-checked" style="display:none">Checkbox2 is CHECKED!</p></code>```

Body:
I have this page that has multiple checkboxes and when clicked, an element appears.

I have this stripped down version to show it simply:

<!DOCTYPE html>

Display some text when the checkbox is checked:

Checkbox 1: <input type="checkbox" id="check1"  onclick="box1()">

Checkbox 2: <input type="checkbox" id="check2"  onclick="box2()">

No boxes are checked

Checkbox1 is CHECKED!

Checkbox2 is CHECKED!

My problem is that the text shows even a box is checked as shown in the image. How can I do this effectively? thanks!

Body:
I'd add the same listener to both checkboxes, and have that listener check the state of both. Then, if both are not checked, display the fill:

const isCheckeds = document.querySelectorAll('.is-checked');
const fill = document.querySelector('#fill');
function validate() {
  let anyChecked = false;
  document.querySelectorAll('input').forEach((checkbox, i) => {
    if (checkbox.checked) {
      anyChecked = true;
    }
    isCheckeds[i].style.display = checkbox.checked ? 'block' : 'none';
  });
  fill.style.display = anyChecked ? 'none' : 'block';
}

<p>Display some text when the checkbox is checked:</p>

Checkbox 1: <input type="checkbox" onclick="validate()"><br>
Checkbox 2: <input type="checkbox" onclick="validate()">

<p id="fill">No boxes are checked</p>

<p class="is-checked" style="display:none">Checkbox1 is CHECKED!</p>
<p class="is-checked" style="display:none">Checkbox2 is CHECKED!</p>

Note that inline handlers should be avoided. Strongly consider attaching them properly with Javascript instead. You could also consider using a change listener instead of a click listener (for better accessablity), and you could surround the inputs in a <label> to make them more clickable:

const isCheckeds = document.querySelectorAll('.is-checked');
const fill = document.querySelector('#fill');
const checkboxes = document.querySelectorAll('input');
function validate() {
  let anyChecked = false;
  checkboxes.forEach((checkbox, i) => {
    if (checkbox.checked) {
      anyChecked = true;
    }
    isCheckeds[i].style.display = checkbox.checked ? 'block' : 'none';
  });
  fill.style.display = anyChecked ? 'none' : 'block';
}
for (const checkbox of checkboxes) {
  checkbox.addEventListener('change', validate);
}

<p>Display some text when the checkbox is checked:</p>

<label>Checkbox 1: <input type="checkbox"></label><br>
<label>Checkbox 2: <input type="checkbox"></label>

<p id="fill">No boxes are checked</p>

<p class="is-checked" style="display:none">Checkbox1 is CHECKED!</p>
<p class="is-checked" style="display:none">Checkbox2 is CHECKED!</p>


问:
JSON Array parsing where key is missing in the key-value pair
I am trying to parse a JSON Array which looks something like this

"data":["data1","data2","data3"]

If I write JSONArray arr = obj1.getJSONArray("data");, this will provide me with the JSON array but since the key name from key-value pair is missing, how will I retrieve "data1", "data2" and "data3"?

答:
JSON arrays allows for non json children. In this case, the children are of String value:

```<code>for(int i=0;i<arr.length();i++) {
    String value = arr.getString(i);
}
</code>```

My syntax might be inaccurate

Body:
JSON arrays allows for non json children. In this case, the children are of String value:

for(int i=0;i<arr.length();i++) {
    String value = arr.getString(i);
}

My syntax might be inaccurate


问:
Selenium Element not Visible Exception : Despite Using Correct XPATH and Putting Breakpoint to Wait for Element to Be Displayed in HTML
$x("//input[contains(@id,'default-column')]") - returns 10 elements

```<code>public List<WebElementFacade> defaultFieldsCheckBox;
</code>```

$x("(//input[contains(@id,'default-column')])[1]") - returns 1 element

```<code>public WebElementFacade firstFieldsCheckBox;
</code>```

"Customize Click" Opens List Of Check-boxes

Check Boxes are Displayed in View after "Customize Click"

I even put a breakpoint after "Customize Click" to ensure the Check-boxes are displayed (see image)

mpAuthPage.firstFieldsCheckBox.isDisplayed()
throws ElementNotVisibleException: Element not available

mpAuthPage.defaultFieldsCheckBox.size()
throws NoSuchElementException: Element not Visible

firstFieldsCheckBox can be found by XPATH and is clearly displayed in HTML

defaultFieldsCheckBox.size() should return 10 instead of error Element not
Visible

Any Ideas as to my issue ??

Checkbox Display In HTML

Image Of HTML Added

答:
The Question was answered by scilence - Thank you !!

Thanks scilence this worked and this is the solution !

WebElement input = mpAuthPage.defaultFieldsCheckBox.get(i).findElement(By.xpath("preceding::input[1]"));

String isChecked = input.getAttribute("checked");

System.out.println("Checkbox " + getText(mpAuthPage.defaultFieldsCheckBox.get(i)) + " Is Checked  " + isChecked);

Body:
$x("//input[contains(@id,'default-column')]") - returns 10 elements

public List<WebElementFacade> defaultFieldsCheckBox;

$x("(//input[contains(@id,'default-column')])[1]") - returns 1 element

public WebElementFacade firstFieldsCheckBox;

"Customize Click" Opens List Of Check-boxes

Check Boxes are Displayed in View after "Customize Click"

I even put a breakpoint after "Customize Click" to ensure the Check-boxes are displayed (see image)

mpAuthPage.firstFieldsCheckBox.isDisplayed()
throws ElementNotVisibleException: Element not available

mpAuthPage.defaultFieldsCheckBox.size()
throws NoSuchElementException: Element not Visible

firstFieldsCheckBox can be found by XPATH and is clearly displayed in HTML

defaultFieldsCheckBox.size() should return 10 instead of error Element not
Visible

Any Ideas as to my issue ??

Checkbox Display In HTML

Image Of HTML Added


问:
Does using channel encryption (https) make hashing the secret key redundant?
I'm designing a web service that clients connect to in order to retrieve some private data. Each client has a unique ID and a secret key (generated by the server) that are sent as parameters to the web service in order to authenticate itself. In addition, all communications are done over HTTPS.

I'm also planning to use HMAC-SHA256, in order to avoid sending the secret key over the wire.

However, I'm wondering whether this is strictly necessary. Since HTTPS gives me a secure channel between client and server, why would I really mind sending the secret key over that channel?

The only reason I managed to come up with is that an unknowledgeable developer might add a service in the future and not reject non-HTTPS connections, so hashing the secret key is a sort of insurance against the realities of corporate software development, an extra line of defense if you will.

Am I missing something more significant? Is this a real vulnerability that some attack vector could take advantage of?

答:
An attacker installs a fake trusted certificate into a browser and hijacks the session.

A link to your site is sent, but the redirection to SSL is intercepted and a non-SSL session commences.

There are others, but the story is this: SSL is complicated and often attacked in inventive ways. If your connection is secure, then the hashing has little value compared to the complexity in code for humans and the cost in cpu time. However, if the SSL session is compromised, then you've still saved your key. Much as we hash passwords in databases despite the fact that nobody undesirable should have access, hashing your key despite SSL would be wise.


问:
How to update MySQL query with multiple where and set using or clause
```<code>Update table
set col = replace(col, 'value1','') where col like '%value1%'
or set col = replace(col, 'value2','') where col like '%value2%'
or set col = replace(col, 'value3','') where col like'%value3%';
</code>```

答:
You could use a case expression:

```<code>update table set col = case
    when col like '%value1%' then replace(col, 'value1', '')
    when col like '%value2%' then replace(col, 'value2', '')
    when col like '%value3%' then replace(col, 'value3', '')
    else col
end
</code>```

You could also phrase this query as follows - this is almost equivalent to the above query, excepted if col contains, for example, both 'value1' and 'value2' (in which case both would be replace, while the first query would replace 'col1'):

```<code>update table set col =
    replace(
        replace(
            replace(col, 'value1', ''),
            'value2', ''
        ),
        'value3', ''
    )
</code>```

Also, you might want to filter the dataset before updating it, especially if your table has a large number of rows. You can do this by adding a where clause to the query:

```<code>where col like '%value1%' or col like '%value2%' or col like '%value3%'
</code>```

Body:
You could use a case expression:

update table set col = case
    when col like '%value1%' then replace(col, 'value1', '')
    when col like '%value2%' then replace(col, 'value2', '')
    when col like '%value3%' then replace(col, 'value3', '')
    else col
end

You could also phrase this query as follows - this is almost equivalent to the above query, excepted if col contains, for example, both 'value1' and 'value2' (in which case both would be replace, while the first query would replace 'col1'):

update table set col =
    replace(
        replace(
            replace(col, 'value1', ''),
            'value2', ''
        ),
        'value3', ''
    )

Also, you might want to filter the dataset before updating it, especially if your table has a large number of rows. You can do this by adding a where clause to the query:

where col like '%value1%' or col like '%value2%' or col like '%value3%'


问:
Postgres copy to TSV file with header
I have a function like so -

```<code>CREATE
OR REPLACE FUNCTION ind (bucket text) RETURNS table (
    middle character varying (100),
    last character varying (100)
) AS $body$ BEGIN return query
select
  fname as first,
  lname as last
from all_records
; END;
$body$ LANGUAGE PLPGSQL;
</code>```

How do I output the results of select ind ('Mob') into a tsv file?

I want the output to look like this -

```<code>first   last
MARY    KATHERINE
</code>```

答:
Postgres doesn't allow copy with header for tsv for some reason.

If you're using a linux based system you can do it with a script like this:

```<code>#create file with tab delimited column list (use \t between each column name)
echo -e "user_id\temail" > user_output.tsv

#now you can append the results of your query to that file by copying to STDOUT
psql -h your_host_name -d your_database_name -c "\copy (SELECT user_id, email FROM my_user_table) to STDOUT;" >> user_output.tsv
</code>```

Alternatively, if your script is long and you don't want to pass it in with -c command you can use the same approach from a .sql file, use "--quiet" to avoid notices being passed into your file

```<code>psql --quiet -h your_host_name -d your_database_name -f your_sql_file.sql >> user_output.tsv
</code>```

Title: Postgres copy to TSV file with header

Body:
I have a function like so -

CREATE
OR REPLACE FUNCTION ind (bucket text) RETURNS table (
    middle character varying (100),
    last character varying (100)
) AS $body$ BEGIN return query
select
  fname as first,
  lname as last
from all_records
; END;
$body$ LANGUAGE PLPGSQL;

How do I output the results of select ind ('Mob') into a tsv file?

I want the output to look like this -

first   last
MARY    KATHERINE

Body:
Postgres doesn't allow copy with header for tsv for some reason.

If you're using a linux based system you can do it with a script like this:

#create file with tab delimited column list (use \t between each column name)
echo -e "user_id\temail" > user_output.tsv

#now you can append the results of your query to that file by copying to STDOUT
psql -h your_host_name -d your_database_name -c "\copy (SELECT user_id, email FROM my_user_table) to STDOUT;" >> user_output.tsv

Alternatively, if your script is long and you don't want to pass it in with -c command you can use the same approach from a .sql file, use "--quiet" to avoid notices being passed into your file

psql --quiet -h your_host_name -d your_database_name -f your_sql_file.sql >> user_output.tsv


问:
Unsupported Media Type 415 Error on Angular 7
I made an admin panel using Angular 7 and I checked admin access. I am tring to upload from Pc to panel/database .I confused about what I should use for it. And also, when I try to upload image from pc to admin panel on Angular side(I used fileuploader library).I get error which is called Unsupported Media Type 415 .How can I upload image or file to database(I mean image will be shown on admin panel) from PC?</p>

答:
It is solved when adding [FromForm] to front of model which I get from [HttpPost] function at .Net Core </p>

<p>(ıf we dont write the code which is up , it will expect application/JSON )</p>

Body:
It is solved when adding [FromForm] to front of model which I get from [HttpPost] function at .Net Core

(ıf we dont write the code which is up , it will expect application/JSON )


问:
PHP & MYSQL: Convert rows and columns to json objects
I'm trying to get all of the rows and columns of a MYSQL table to be objects in an array so I can retrieve them via javascript.

Here's what I've got so far:

```<code><?PHP
include '../sql.php';
$c = mysql_connect('localhost', $user, $pw) or die('Unable to connect to MySQL');
$s = mysql_select_db('mydb') or die('Could not select database');
$q = mysql_query('SELECT * FROM mytable') or die(mysql_error());
$a = array();

$cl = mysql_num_fields($q);
for($i = 1; $i < $cl; $i++){
    while($r = mysql_fetch_assoc($q)){
        foreach($r as $k => $v){
            $a[] = //something;
        }
    }
}

echo json_encode($a);
mysql_close($c);
?>
</code>```

The object at the end should look something like this:

```<code>[
    {id: 1, name: 'bob', status: 'sleeping'},
    {id: 2, name: 'james', status: 'partying'},
    {id: 3, name: 'eric', status: 'reading'}
]
</code>```

答:
For mysqli json response in PHP</p>

```<code>$link = mysqli_connect($servername, "$username", "$password", "$db_name", $port);
if (!$link)
{die("MySQL connect ERROR:  " . mysqli_connect_error());}

$query = "SELECT * FROM mytable";
$result = mysqli_query($link,$query);
echo json_encode(mysqli_fetch_all($result,MYSQLI_ASSOC));
@mysql_close($link);
</code>```

Body:
I'm trying to get all of the rows and columns of a MYSQL table to be objects in an array so I can retrieve them via javascript.

Here's what I've got so far:

<?PHP
include '../sql.php';
$c = mysql_connect('localhost', $user, $pw) or die('Unable to connect to MySQL');
$s = mysql_select_db('mydb') or die('Could not select database');
$q = mysql_query('SELECT * FROM mytable') or die(mysql_error());
$a = array();

$cl = mysql_num_fields($q);
for($i = 1; $i < $cl; $i++){
    while($r = mysql_fetch_assoc($q)){
        foreach($r as $k => $v){
            $a[] = //something;
        }
    }
}

echo json_encode($a);
mysql_close($c);
?>

The object at the end should look something like this:

[
    {id: 1, name: 'bob', status: 'sleeping'},
    {id: 2, name: 'james', status: 'partying'},
    {id: 3, name: 'eric', status: 'reading'}
]

Body:
For mysqli json response in PHP

$link = mysqli_connect($servername, "$username", "$password", "$db_name", $port);
if (!$link)
{die("MySQL connect ERROR:  " . mysqli_connect_error());}

$query = "SELECT * FROM mytable";
$result = mysqli_query($link,$query);
echo json_encode(mysqli_fetch_all($result,MYSQLI_ASSOC));
@mysql_close($link);


问:
Combine Thread Results with openmp
I have some problems combining the processing results I recieve from several Threads. And I'm not sure, if I use openmp correctly. The below code extract shows the openmp portion of my code.

Parameters:

thread private:

it: map iterator (timestamp, userkey)

ite: map iterator ((timestamp,userkey)/int amount)

thread_result_map: typedef map < userkey(str),timestamp(str) >

when, who: matching regex (timestamp, userkey)

shared among threads:

log: char array

size: log.size()

identifier, timestamp, userkey: boost::regex patterns

combined_result_map: typedef map < thread_result_map, hits(int) >

```<code>#pragma omp parallel shared(log, size, identifier, timestamp, userkey) private(it, ite, str_time, str_key, vec_str_result, i, id, str_current, when, who, thread_result_map)
    {
#pragma omp for
    for (i = 0 ; i < size ; i++){
            str_current.push_back(log[i]);
        if (log[i] == '\n') {
            if (boost::regex_search(str_current, identifier)){
                boost::regex_search(str_current, when, timestamp);
                str_time = when[0];
                boost::regex_search(str_current, who, userkey);
                str_key = who[0];
                thread_result_map.insert(make_pair(str_time, str_key));
                }
                str_current = ""; //reset temp string
            }
        }
#pragma omp critical
        {
        for (it=thread_result_map.begin(); it!=thread_result_map.end(); it++) {
                id = omp_get_thread_num();
            cout << thread_result_map[it->first] <<
                           thread_result_map[it->second];
            cout << "tID_" << id << " reducing" << endl;
            }
        }
    }
</code>```

As you can see every thread has his own partition of the char array, it parses line by line from the array and if the current string is identified by "identifier", the timestamp and userkey are added to the thread's private result map (string/string).

Now after the loop I have several thread's private result maps. The combined_result_map is a map inside a map. The key is the combination of key/value of the threads result and the value is the amount of occurences of this combination.

I'm parsing only a portion of the timestamp so when in 1 hour the same userkey appears multiple times the hit counter will be increased.

The result should look something like this:

```<code>TIME(MMM/DD/HH/);USERKEY;HITS
May/25/13;SOMEKEY124345;3
</code>```

So I have no problems combining hit amounts in the critical section (which I removed) by specifying combined+=results.

But how can I combine my result maps the same way? I know I have to iterate through threads maps, but when I put a "cout" inside the loop for testing every thread calls it only once.

A test run on my local syslog gives me the following output when I set all the regex to "error" (to make sure every identified line will have a userkey and a timestamp with the same name):

Pattern for parsing Access String:

```<code>error   Pattern for parsing Timestamp:
error   Pattern for parsing Userkey:
error

 *** Parsing File /var/log/syslog

errortID_0 reducing errortID_1
reducing errortID_2 reducing
errortID_3 reducing

 *** Ok!   ________________   hits :
418   worktime: 0.0253871s
</code>```

(The calculated hits come from thread private counters, that I removed in the code above)

So every of my 4 threads does a single cout and leaves the loop, although all together should have 418 hits. So what do I do wrong? How do I iterate through my results from inside my openmp area?

答:
Found the problem myself, sorry for asking stupid questions.

I was trying to add the same key multiple times, that's why map size didn't increase and every thread looped only once.

Edit:

If anybody is interested in the solution how to combine thread results, this is how I did it. perhaps you see anything that could be improved.

I just changed the local threads result map to a vector of pairs(str,str).

This is the full working openmp code section. Pehaps it's useful for anyone:

```<code>#pragma omp parallel shared(log, size, identifier, timestamp, userkey) private(it, ite, str_time, str_key, i, id, str_current, when, who, local_res)
    {
#pragma omp for
        for (i = 0 ; i < size ; i++){

            str_current.push_back(log[i]);

            if (log[i] == '\n') {   // if char is newline character
                if (boost::regex_search(str_current, identifier)){  // if current line is access string
                    boost::regex_search(str_current, when, timestamp);  // get timestamp from string
                    str_time = when[0];
                    boost::regex_search(str_current, who, userkey); // get userkey from string
                    str_key = who[0];
                    local_res.push_back((make_pair(str_time, str_key)));    // append key-value-pair(timestamp/userkey)
                    id = omp_get_thread_num();
                    //cout << "tID_" << id << " - adding pair - my local result map size is now: " << local_res.size() << endl;
                }
                str_current = "";
            }
        }

#pragma omp critical
        {
            id = omp_get_thread_num();
            hits += local_res.size();
            cout << "tID_" << id << " had HITS: " << local_res.size() << endl;
            for (i = 0; i < local_res.size(); i++) {
                acc_key = local_res[i].second;
                acc_time = local_res[i].first;
                if(m_KeyDatesHits.count(acc_key) == 0) { // if there are no items for this key yet, make a new entry
                    m_KeyDatesHits.insert(make_pair(acc_key, str_int_MapType()));
                }
                if (m_KeyDatesHits[acc_key].count(acc_time) == 0) { // "acc_time" is a key value, if it doesn't exist yet, add it and set "1" as value
                    m_KeyDatesHits[acc_key].insert(make_pair(acc_time, 1 ));
                    it = m_KeyDatesHits.begin(); // iterator for userkeys/maps
                    ite = m_KeyDatesHits[acc_key].begin(); // iterator for  times/clicks
                } else m_KeyDatesHits[acc_key][acc_time]++; // if userkey already exist and timestamp already exists, count hits +1 for it

            }
        }
    }
</code>```

I did some tests and it's really running fast.

Using 4 Threads this searches a 150MB LogFile for access events, parses a custom user key and date from every event and combines the results in under 4 seconds.

At the End it creates a export list. This is the program output:

HELLO, welcome to LogMap 0.1!

C++/OpenMP Memory Map Parsing Engine

  __________________   Number of processors available = 4

  Number of threads =              4

Pattern for parsing Access String:

  GET /_openbooknow/key/   Pattern for

  parsing Timestamp: \d{2}/\w{3}/\d{4}

  Pattern for parsing Userkey:

  [a-zA-Z0-9]{20,32}

* Parsing File

  /home/c0d31n/Desktop/access_log-test.txt

HITS: 169147 HITS: 169146 HITS: 169146

  HITS: 169147

* Ok!   ________   hits :

  676586   worktime: 4.03816s

* new export file created: "./test.csv"

root@c0d3b0x:~/workspace/OpenBookMap/Release#

  cat test.csv

  "1nDh0gV6eE3MzK0517aE6VIU0";"28/Mar/2011";"18813"

  "215VIU1wBN2O2Fmd63MVmv6QTZy";"28/Mar/2011";"6272"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"18/Mar/2011";"18816"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"21/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"22/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"23/Mar/2011";"18816"

  "9E1608JFGk2GZQ4ppe1Grtv2";"28/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"17/Mar/2011";"18029"

  "pachCsiog05bpK0kDA3K2lhEY";"18/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"21/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"22/Mar/2011";"6272"

  "pachCsiog05bpK0kDA3K2lhEY";"23/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"28/Mar/2011";"501760"

  "1nDh0gV6eE3MzK0517aE6VIU0";"28/Mar/2011";"18813"

  "215VIU1wBN2O2Fmd63MVmv6QTZy";"28/Mar/2011";"6272"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"18/Mar/2011";"18816"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"21/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"22/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"23/Mar/2011";"18816"

  "9E1608JFGk2GZQ4ppe1Grtv2";"28/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"17/Mar/2011";"18029"

  "pachCsiog05bpK0kDA3K2lhEY";"18/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"21/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"22/Mar/2011";"6272"

  "pachCsiog05bpK0kDA3K2lhEY";"23/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"28/Mar/2011";"501760"

Title: Combine Thread Results with openmp

Body:
I have some problems combining the processing results I recieve from several Threads. And I'm not sure, if I use openmp correctly. The below code extract shows the openmp portion of my code.

Parameters:

thread private:

it: map iterator (timestamp, userkey)

ite: map iterator ((timestamp,userkey)/int amount)

thread_result_map: typedef map < userkey(str),timestamp(str) >

when, who: matching regex (timestamp, userkey)

shared among threads:

log: char array

size: log.size()

identifier, timestamp, userkey: boost::regex patterns

combined_result_map: typedef map < thread_result_map, hits(int) >

#pragma omp parallel shared(log, size, identifier, timestamp, userkey) private(it, ite, str_time, str_key, vec_str_result, i, id, str_current, when, who, thread_result_map)
    {
#pragma omp for
    for (i = 0 ; i < size ; i++){
            str_current.push_back(log[i]);
        if (log[i] == '\n') {
            if (boost::regex_search(str_current, identifier)){
                boost::regex_search(str_current, when, timestamp);
                str_time = when[0];
                boost::regex_search(str_current, who, userkey);
                str_key = who[0];
                thread_result_map.insert(make_pair(str_time, str_key));
                }
                str_current = ""; //reset temp string
            }
        }
#pragma omp critical
        {
        for (it=thread_result_map.begin(); it!=thread_result_map.end(); it++) {
                id = omp_get_thread_num();
            cout << thread_result_map[it->first] <<
                           thread_result_map[it->second];
            cout << "tID_" << id << " reducing" << endl;
            }
        }
    }

As you can see every thread has his own partition of the char array, it parses line by line from the array and if the current string is identified by "identifier", the timestamp and userkey are added to the thread's private result map (string/string).

Now after the loop I have several thread's private result maps. The combined_result_map is a map inside a map. The key is the combination of key/value of the threads result and the value is the amount of occurences of this combination.

I'm parsing only a portion of the timestamp so when in 1 hour the same userkey appears multiple times the hit counter will be increased.

The result should look something like this:

TIME(MMM/DD/HH/);USERKEY;HITS
May/25/13;SOMEKEY124345;3

So I have no problems combining hit amounts in the critical section (which I removed) by specifying combined+=results.

But how can I combine my result maps the same way? I know I have to iterate through threads maps, but when I put a "cout" inside the loop for testing every thread calls it only once.

A test run on my local syslog gives me the following output when I set all the regex to "error" (to make sure every identified line will have a userkey and a timestamp with the same name):

Pattern for parsing Access String:

error   Pattern for parsing Timestamp:
error   Pattern for parsing Userkey:
error

 *** Parsing File /var/log/syslog

errortID_0 reducing errortID_1
reducing errortID_2 reducing
errortID_3 reducing

 *** Ok!   ________________   hits :
418   worktime: 0.0253871s

(The calculated hits come from thread private counters, that I removed in the code above)

So every of my 4 threads does a single cout and leaves the loop, although all together should have 418 hits. So what do I do wrong? How do I iterate through my results from inside my openmp area?

Body:
Found the problem myself, sorry for asking stupid questions.

I was trying to add the same key multiple times, that's why map size didn't increase and every thread looped only once.

Edit:

If anybody is interested in the solution how to combine thread results, this is how I did it. perhaps you see anything that could be improved.

I just changed the local threads result map to a vector of pairs(str,str).

This is the full working openmp code section. Pehaps it's useful for anyone:

#pragma omp parallel shared(log, size, identifier, timestamp, userkey) private(it, ite, str_time, str_key, i, id, str_current, when, who, local_res)
    {
#pragma omp for
        for (i = 0 ; i < size ; i++){

            str_current.push_back(log[i]);

            if (log[i] == '\n') {   // if char is newline character
                if (boost::regex_search(str_current, identifier)){  // if current line is access string
                    boost::regex_search(str_current, when, timestamp);  // get timestamp from string
                    str_time = when[0];
                    boost::regex_search(str_current, who, userkey); // get userkey from string
                    str_key = who[0];
                    local_res.push_back((make_pair(str_time, str_key)));    // append key-value-pair(timestamp/userkey)
                    id = omp_get_thread_num();
                    //cout << "tID_" << id << " - adding pair - my local result map size is now: " << local_res.size() << endl;
                }
                str_current = "";
            }
        }

#pragma omp critical
        {
            id = omp_get_thread_num();
            hits += local_res.size();
            cout << "tID_" << id << " had HITS: " << local_res.size() << endl;
            for (i = 0; i < local_res.size(); i++) {
                acc_key = local_res[i].second;
                acc_time = local_res[i].first;
                if(m_KeyDatesHits.count(acc_key) == 0) { // if there are no items for this key yet, make a new entry
                    m_KeyDatesHits.insert(make_pair(acc_key, str_int_MapType()));
                }
                if (m_KeyDatesHits[acc_key].count(acc_time) == 0) { // "acc_time" is a key value, if it doesn't exist yet, add it and set "1" as value
                    m_KeyDatesHits[acc_key].insert(make_pair(acc_time, 1 ));
                    it = m_KeyDatesHits.begin(); // iterator for userkeys/maps
                    ite = m_KeyDatesHits[acc_key].begin(); // iterator for  times/clicks
                } else m_KeyDatesHits[acc_key][acc_time]++; // if userkey already exist and timestamp already exists, count hits +1 for it

            }
        }
    }

I did some tests and it's really running fast.

Using 4 Threads this searches a 150MB LogFile for access events, parses a custom user key and date from every event and combines the results in under 4 seconds.

At the End it creates a export list. This is the program output:

HELLO, welcome to LogMap 0.1!

C++/OpenMP Memory Map Parsing Engine

  __________________   Number of processors available = 4

  Number of threads =              4

Pattern for parsing Access String:

  GET /_openbooknow/key/   Pattern for

  parsing Timestamp: \d{2}/\w{3}/\d{4}

  Pattern for parsing Userkey:

  [a-zA-Z0-9]{20,32}

* Parsing File

  /home/c0d31n/Desktop/access_log-test.txt

HITS: 169147 HITS: 169146 HITS: 169146

  HITS: 169147

* Ok!   ________   hits :

  676586   worktime: 4.03816s

* new export file created: "./test.csv"

root@c0d3b0x:~/workspace/OpenBookMap/Release#

  cat test.csv

  "1nDh0gV6eE3MzK0517aE6VIU0";"28/Mar/2011";"18813"

  "215VIU1wBN2O2Fmd63MVmv6QTZy";"28/Mar/2011";"6272"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"18/Mar/2011";"18816"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"21/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"22/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"23/Mar/2011";"18816"

  "9E1608JFGk2GZQ4ppe1Grtv2";"28/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"17/Mar/2011";"18029"

  "pachCsiog05bpK0kDA3K2lhEY";"18/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"21/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"22/Mar/2011";"6272"

  "pachCsiog05bpK0kDA3K2lhEY";"23/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"28/Mar/2011";"501760"

  "1nDh0gV6eE3MzK0517aE6VIU0";"28/Mar/2011";"18813"

  "215VIU1wBN2O2Fmd63MVmv6QTZy";"28/Mar/2011";"6272"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"18/Mar/2011";"18816"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"21/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"22/Mar/2011";"12544"

  "36Pu0A2Wly3uYeIPZ4YPAuBy";"23/Mar/2011";"18816"

  "9E1608JFGk2GZQ4ppe1Grtv2";"28/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"17/Mar/2011";"18029"

  "pachCsiog05bpK0kDA3K2lhEY";"18/Mar/2011";"12544"

  "pachCsiog05bpK0kDA3K2lhEY";"21/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"22/Mar/2011";"6272"

  "pachCsiog05bpK0kDA3K2lhEY";"23/Mar/2011";"18816"

  "pachCsiog05bpK0kDA3K2lhEY";"28/Mar/2011";"501760"


问:
how the camera moves whenever the location of Android Google Map changes
I am a beginner of android and java.

I am using the Android Google Map API.

mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 18), 1000, null);

Pressing a button using [animateCamera] implements the function of moving the camera to its current position.

I want the camera to keep up with my position.

[Thread] tried applying [animateCamera] using [sleep], but the Google Map stops.

How do I apply it in Android?

答:
check this code to first check location permission and then get current location and move camera in current location

```<code>LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            LatLng latLngOfMyLocation = new LatLng(location.getLatitude(), location.getLongitude());
            builder.include(latlng);
            map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 8));

            return;
        }
</code>```

Body:
check this code to first check location permission and then get current location and move camera in current location

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            LatLngBounds.Builder builder = new LatLngBounds.Builder();
            Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            LatLng latLngOfMyLocation = new LatLng(location.getLatitude(), location.getLongitude());
            builder.include(latlng);
            map.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 8));

            return;
        }


答:
Javascript is not necessary for this task: with your markup structure you could use CSS only

:checked ~ p, #cb1, #cb2 {
  display: none;
}

#check1:checked ~ #cb1,
#check2:checked ~ #cb2 { display: block; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Display some text when the checkbox is checked:</p>

Checkbox 1: <input type="checkbox" id="check1"><br>
Checkbox 2: <input type="checkbox" id="check2">

<p id="cb0">No boxes are checked</p>
<p id="cb1">Checkbox1 is checked</p>
<p id="cb2">Checkbox2 is checked!</p></code>```

Title: Display message when some or all checkboxes aren't checked

Body:
Javascript is not necessary for this task: with your markup structure you could use CSS only

:checked ~ p, #cb1, #cb2 {
  display: none;
}

#check1:checked ~ #cb1,
#check2:checked ~ #cb2 { display: block; }

<p>Display some text when the checkbox is checked:</p>

Checkbox 1: <input type="checkbox" id="check1"><br>
Checkbox 2: <input type="checkbox" id="check2">

<p id="cb0">No boxes are checked</p>
<p id="cb1">Checkbox1 is checked</p>
<p id="cb2">Checkbox2 is checked!</p>