问:
plugin override Joomla MVC not working
Hellow !

I must use Joomla for a website and I need to override an MVC component (com_contact) to add a field to the contact form. The problem is, I followed this tutorial :

https://docs.joomla.org/How_to_override_the_component_mvc_from_the_Joomla!_core/fr

I installed the plugin, rewrote needed files and place them where the tutorial says to place them, but it doesn't work, the plugin is not overidden.

Could someone help me with this please ?

------EDIT---------

I gave up the first tutorial and am now trying to follow this one :
https://docs.joomla.org/J3.x:Creating_a_Plugin_for_Joomla/fr

but my plugin dosen't work. Here is the code of the plugin:

```<code>/**
 * Prepare form and add my field.
 *
 * @param   JForm  $form  The form to be altered.
 * @param   mixed  $data  The associated data for the form.
 *
 * @return  boolean
 *
 * @since   <your version>
 */

function onContentPrepareForm($form, $data)
{

    $app = JFactory::getApplication();
    $option = $app->input->get('option');

    switch ($option) {

        case 'com_contact': {
            if ($app->isAdmin()) {
                JForm::addFormPath(__DIR__ . '/forms');
                $form->loadFile('item', false);
            }
            return true;
        }

    }
    return true;
}
}
?>
</code>```

the contact.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<form>
<fields name="params">
    <fieldset name="params" label="PLG_CONTENT_EXAMPLE_FIELDSET_LABEL">
        <field
                name="contact_emaillabel2"
                type="text"
                label="PLG_CONTENT_EXAMPLE_CONTACT_EMAILLABEL2"
        />
        <field
                name="contact_email2"
                type="text"
                label="PLG_CONTENT_EXAMPLE_CONTACT_EMAIL2"
                filter="email"
        />
    </fieldset>
</fields>
</form>
</code>```

install xml file :

```<code><?xml version="1.0" encoding="utf-8"?>
<extension version="3.2" type="plugin" group="override">
<name>test</name>
<author>Laurine</author>
<creationDate>June 2016</creationDate>
<copyright>Copyright (C) Page Graphique, tous droits réservés</copyright>
<authorEmail>Laurine@page-graphique.fr</authorEmail>
<version>3.2</version>
<description>Plugin pour surcharger les composants MVC</description>
<files>
    <filename>plgoverridetest.php</filename>
</files>
<config>
</config>
</extension>
</code>```

arborescence :

```<code>- <Joomla>/.../plugins/override
    plgoverridetest.php
    install.xml
    - forms
        contact.xml
</code>```

答:
In order to override the contact form, you need to create a 'content' plugin, your plugin above is 'override' so it will not be fired by the contact component.

Also, in your code  $form->loadFile('item', false); is wrong because the xml file you're trying to load is 'contact.xml' so your code should be $form->loadFile('contact', false);.

I've just completed the development of a plugin that adds many fields such as phone, website, company, file upload, newsletter and includes switching off the default fields if need be. It also sends the information to HubSpot if you use their CRM.

Now the thing is in order to use these extra fields you need to create a 'contact' plugin that's fired when the form is submitted and triggered with the plugin trigger 'onSubmitContact($data)', I've created a 'custom reply' plugin for this purpose.

You need to remember when using a custom reply plugin you must select the 'Custom Reply' option on the contact options in the admin component.

Also, the plugins I've created work on a per form basis rather than having the same fields on multiple forms you can modify each form independently.

Title: plugin override Joomla MVC not working

Body:
Hellow !

I must use Joomla for a website and I need to override an MVC component (com_contact) to add a field to the contact form. The problem is, I followed this tutorial :

https://docs.joomla.org/How_to_override_the_component_mvc_from_the_Joomla!_core/fr

I installed the plugin, rewrote needed files and place them where the tutorial says to place them, but it doesn't work, the plugin is not overidden.

Could someone help me with this please ?

------EDIT---------

I gave up the first tutorial and am now trying to follow this one :
https://docs.joomla.org/J3.x:Creating_a_Plugin_for_Joomla/fr

but my plugin dosen't work. Here is the code of the plugin:

/**
 * Prepare form and add my field.
 *
 * @param   JForm  $form  The form to be altered.
 * @param   mixed  $data  The associated data for the form.
 *
 * @return  boolean
 *
 * @since   <your version>
 */

function onContentPrepareForm($form, $data)
{

    $app = JFactory::getApplication();
    $option = $app->input->get('option');

    switch ($option) {

        case 'com_contact': {
            if ($app->isAdmin()) {
                JForm::addFormPath(__DIR__ . '/forms');
                $form->loadFile('item', false);
            }
            return true;
        }

    }
    return true;
}
}
?>

the contact.xml

<?xml version="1.0" encoding="UTF-8"?>
<form>
<fields name="params">
    <fieldset name="params" label="PLG_CONTENT_EXAMPLE_FIELDSET_LABEL">
        <field
                name="contact_emaillabel2"
                type="text"
                label="PLG_CONTENT_EXAMPLE_CONTACT_EMAILLABEL2"
        />
        <field
                name="contact_email2"
                type="text"
                label="PLG_CONTENT_EXAMPLE_CONTACT_EMAIL2"
                filter="email"
        />
    </fieldset>
</fields>
</form>

install xml file :

<?xml version="1.0" encoding="utf-8"?>
<extension version="3.2" type="plugin" group="override">
<name>test</name>
<author>Laurine</author>
<creationDate>June 2016</creationDate>
<copyright>Copyright (C) Page Graphique, tous droits réservés</copyright>
<authorEmail>Laurine@page-graphique.fr</authorEmail>
<version>3.2</version>
<description>Plugin pour surcharger les composants MVC</description>
<files>
    <filename>plgoverridetest.php</filename>
</files>
<config>
</config>
</extension>

arborescence :

- <Joomla>/.../plugins/override
    plgoverridetest.php
    install.xml
    - forms
        contact.xml


来源: stackexchange

问:
React Native - How to change data in js file using text input
My android app is loading string data from a js file that is looking like this:

```<code>module.exports = {
DATA: {
  firstdata: 'data',
  seconddata: 'data2'},
};
</code>```

What I want to do, is change content of this file using text input with

```<code> onChangeText={(text) => data.DATA.firstdata.setState({text})}
</code>```

But it tells me that "undefined is not a function".

These are my first attempts with text inputs. Any help will be appreciated :)

答:
it seems you are trying to implement different concepts. You are trying to change js file using setState function, which is a function provided by react to change data in local component state. So, in your case, data.DATA.firstdata should be just a string, that doesn't know what setState function is. But, according to an error, it seems you are not even importing this DATA variable.

What you can do is set this data to your local state when component is mounted, and then mutate this local state with setState function.

```<code>...
import { DATA } from './path/to/the/file'

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            firstdata: DATA.firstdata,
            seconddata: DATA.seconddata,
        };
    }
    render() {
        return (
            ...

           <TextInput onChangeText={(text) => this.setState({firstdata: text})}>
        )
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My android app is loading string data from a js file that is looking like this:

module.exports = {
DATA: {
  firstdata: 'data',
  seconddata: 'data2'},
};

What I want to do, is change content of this file using text input with

 onChangeText={(text) => data.DATA.firstdata.setState({text})}

But it tells me that "undefined is not a function".

These are my first attempts with text inputs. Any help will be appreciated :)

Body:
it seems you are trying to implement different concepts. You are trying to change js file using setState function, which is a function provided by react to change data in local component state. So, in your case, data.DATA.firstdata should be just a string, that doesn't know what setState function is. But, according to an error, it seems you are not even importing this DATA variable.

What you can do is set this data to your local state when component is mounted, and then mutate this local state with setState function.

...
import { DATA } from './path/to/the/file'

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = {
            firstdata: DATA.firstdata,
            seconddata: DATA.seconddata,
        };
    }
    render() {
        return (
            ...

           <TextInput onChangeText={(text) => this.setState({firstdata: text})}>
        )
    }
}


问:
How to use different version dependencies for each JAR
I have a maven project A that uses some Java library B, which is dependency stated in POM. That library uses some other library C that uses library D. The problem arises in compiling where both A and C are using that library D but different versions. It looks like this:

```<code>A ----- B
|       |
D(v1)   C
        |
        D(v2)
</code>```

A can not change its dependency to D(v2), but also if I exclude D(v2) in A's POM:

```<code><dependency>
    <groupId>...</groupId>
    <artifactId> C </artifactId>
    <exclusions>
        <exclusion>
            <groupId>...</groupId>
            <artifactId> D </artifactId>
            <version> v2 </version>
        </exclusion>
    </exclusions>
</dependency>
</code>```

I will get compilation error that some class MissingClass is not resolved in class C. The most annoying thing is that only D(v2) has that Missing Class.

I am not somewhat skilled with Maven so is there some way to make Maven is using D(v1) dependency in A's case, and D(v2) in B's case?

答:
This is more a problem of Java classpath.
Could your scenario work if you run things via cmd line, without Maven? (i.e. run your app, and manually specify your classpath).

If the answer is yes, then you probably can do it in Maven; but my understanding from your description is that no, you couldn't run via cmd line.

Body:
I have a maven project A that uses some Java library B, which is dependency stated in POM. That library uses some other library C that uses library D. The problem arises in compiling where both A and C are using that library D but different versions. It looks like this:

A ----- B
|       |
D(v1)   C
        |
        D(v2)

A can not change its dependency to D(v2), but also if I exclude D(v2) in A's POM:

<dependency>
    <groupId>...</groupId>
    <artifactId> C </artifactId>
    <exclusions>
        <exclusion>
            <groupId>...</groupId>
            <artifactId> D </artifactId>
            <version> v2 </version>
        </exclusion>
    </exclusions>
</dependency>

I will get compilation error that some class MissingClass is not resolved in class C. The most annoying thing is that only D(v2) has that Missing Class.

I am not somewhat skilled with Maven so is there some way to make Maven is using D(v1) dependency in A's case, and D(v2) in B's case?


问:
How do I open a dialog as soon as an application is initialized?
I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

```<code>public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}
</code>```

and:

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

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}
</code>```

How do I do this?

答: Try doing it from the Loaded event of your windows.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}

and:

public MainWindow()
{
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}

How do I do this?


问:
Setting format of DateTime - how do I keep the value in DateTime format?
I have a DateTime being created in the format dd/MM/yyyy HH:mm:ss.  I am writing code that interacts with a third-party SOAP library that requires a DateTime variable, in the format yyyy-MM-dd HH:mm:ss.

How do I change the way the information is stored in the DateTime variable, for the purpose of the call to the third-party SOAP library, i.e. no system-wide changes to dates?

I have investigated CultureInfo, which is mildly confusing and possibly too permanent a solution; the only time I need the DateTime changing is for an instance of this single call.

As an explanation, the library has a function GetOrders(DateTime startDate, DateTime endDate, TradingRoleCodeType roleType, OrderStatusCodeType statusType). When attempting to perform the function with DateTimes as created, it generates an error "Sorry, the end date was missing, invalid, or before the start date.  must be in YYYY-MM-DD or YYYY-MM-DD HH:MI:SS format, and after the start date.". Given the format that is passed in as dd/MM/yyyy HH:mm:ss, I'd think this may be the problem.

答:
You don't need to change how it's stored, as already mentioned above.
You need to format is as a string according to ISO8601, which is what your SOAP service expects datetime parameter to be.

Check How to parse and generate DateTime objects in ISO 8601 format
and

Given a DateTime object, how do I get an ISO 8601 date in string format?


问:
Deleting layers with gradient properly
I have UICollectionViewCell with UIView called gradientView that is used as a background for labels on it.

This UIView needs to have gradient - it is light and almost transparent at the top of cell and becomes slightly darker in the bottom of the cell (simple linear gradient).

So I created func called addGradient that takes UIView and adds layer with gradient to it.

```<code>  func addGradient(view : UIView){

    view.backgroundColor = .clear

    let color1 = somecolor1.cgColor
    let color2 = somecolor2.cgColor

    let gradient:CAGradientLayer = CAGradientLayer()
        gradient.frame.size = view.frame.size
        gradient.colors = [color1, color2]

    view.layer.addSublayer(gradient)
}
</code>```

Inside cellForItemAt I call addGradient(cell.gradientView) and the gradient is shown. But I have 2 problems:

1) each cell becomes darker and darker - it seems that layers are added one over another and I don't want it

2) sometimes this gradients are slighly misplaced - I also think that is because I don't delete this layers properly

So how and where I should clear sublayers and maybe my method of adding this gradient inside cellForItemAt is not right?

答:
just a guess on number 1 without seeing more of your code: change frame to bounds</p>

```<code> func addGradient(view : UIView){

    view.backgroundColor = .clear

    let color1 = somecolor1.cgColor
    let color2 = somecolor2.cgColor

    let gradient:CAGradientLayer = CAGradientLayer()
        gradient.frame.size = view.bounds.size
        gradient.colors = [color1, color2]

    view.layer.addSublayer(gradient)
}
</code>```

Title: Deleting layers with gradient properly

Body:
I have UICollectionViewCell with UIView called gradientView that is used as a background for labels on it.

This UIView needs to have gradient - it is light and almost transparent at the top of cell and becomes slightly darker in the bottom of the cell (simple linear gradient).

So I created func called addGradient that takes UIView and adds layer with gradient to it.

  func addGradient(view : UIView){

    view.backgroundColor = .clear

    let color1 = somecolor1.cgColor
    let color2 = somecolor2.cgColor

    let gradient:CAGradientLayer = CAGradientLayer()
        gradient.frame.size = view.frame.size
        gradient.colors = [color1, color2]

    view.layer.addSublayer(gradient)
}

Inside cellForItemAt I call addGradient(cell.gradientView) and the gradient is shown. But I have 2 problems:

1) each cell becomes darker and darker - it seems that layers are added one over another and I don't want it

2) sometimes this gradients are slighly misplaced - I also think that is because I don't delete this layers properly

So how and where I should clear sublayers and maybe my method of adding this gradient inside cellForItemAt is not right?

Body:
just a guess on number 1 without seeing more of your code: change frame to bounds

 func addGradient(view : UIView){

    view.backgroundColor = .clear

    let color1 = somecolor1.cgColor
    let color2 = somecolor2.cgColor

    let gradient:CAGradientLayer = CAGradientLayer()
        gradient.frame.size = view.bounds.size
        gradient.colors = [color1, color2]

    view.layer.addSublayer(gradient)
}


问:
How to have a list of random numbers by ensuring all of them at least once used?
I am trying to have a list of numbers from 1 to 10 with many occurrences, therefore I began with using the following code:

```<code>list(range(1,11))
</code>```

However, it only gives every number only once. I need to have an output in double size, half of it having the arbitrarily ordered numbers and half should have random numbers in the given range like following:

```<code>[1,2,3,4,5,6,7,8,9,10,3,4,2,7,5,7,5,2,8,9]
</code>```

My approach was:

1) Making a random list

```<code>a = random.randint(0,9)
</code>```

2) Combining with the output of range

```<code>b = list(range(1,11))
result = a+b
</code>```

Is it possible to have it in other way?

答:
What's wrong with:

```<code>import random

your_array = list(range(1, 11)) + random.sample(range(1, 11), 10)
#  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 7, 8, 2, 1, 9, 5, 10, 6, 4]
</code>```

On a second read... If you want repeats in your second part you can do it as:

```<code>your_array = list(range(1, 11)) + [random.randrange(1, 11) for _ in range(10)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 8, 1, 5, 1, 10, 5, 2, 10]
</code>```

Body:
I am trying to have a list of numbers from 1 to 10 with many occurrences, therefore I began with using the following code:

list(range(1,11))

However, it only gives every number only once. I need to have an output in double size, half of it having the arbitrarily ordered numbers and half should have random numbers in the given range like following:

[1,2,3,4,5,6,7,8,9,10,3,4,2,7,5,7,5,2,8,9]

My approach was:

1) Making a random list

a = random.randint(0,9)

2) Combining with the output of range

b = list(range(1,11))
result = a+b

Is it possible to have it in other way?

Body:
What's wrong with:

import random

your_array = list(range(1, 11)) + random.sample(range(1, 11), 10)
#  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 7, 8, 2, 1, 9, 5, 10, 6, 4]

On a second read... If you want repeats in your second part you can do it as:

your_array = list(range(1, 11)) + [random.randrange(1, 11) for _ in range(10)]
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 5, 4, 8, 1, 5, 1, 10, 5, 2, 10]


问:
Allow contributors to add limited number of a node
I want to allow my contributors to add a limited number of a node in Edit Mode. Here's what I have right now in my definitions.cnd:

```<code>[jnt:parent] > jnt:content, jmix:basicContent, mix:title
 - intro (string, richtext)
 + * (jnt:child)
</code>```

This allows contributors to add as many node child they want. I want to limit that number to 2. I tried + 2 (jnt:child) but that didn't change a thing.

How to achieve my goal?

答:
That is not possible in cnd.  Here is a link to the source docs: https://jackrabbit.apache.org/jcr/node-type-notation.html  It's either one or many.

The way I have controled that in the past is to use logic to in the ui to remove the option of adding additional nodes, and logic in the backing handlers to discard any attempts to add nodes.

Body:
I want to allow my contributors to add a limited number of a node in Edit Mode. Here's what I have right now in my definitions.cnd:

[jnt:parent] > jnt:content, jmix:basicContent, mix:title
 - intro (string, richtext)
 + * (jnt:child)

This allows contributors to add as many node child they want. I want to limit that number to 2. I tried + 2 (jnt:child) but that didn't change a thing.

How to achieve my goal?


问:
How is clickView used properly?
I'm trying to write a simple test app to run in JUnit. I've been having trouble getting clickView to click on the proper view. Below is some sample code that can be used on SkeletonActivity sample app that comes with the SDK.

```<code>    public class SkeletonInstrumentation extends ActivityInstrumentationTestCase2<Activity>{

 private Activity act;
 private  Button bClear;
 private  Button bBack;
 private  EditText eMain;

 public SkeletonInstrumentation(){
  super("com.example.android.skeletonapp", Activity.class);

 }

 public void setUp() {

  String app = this.getInstrumentation().getTargetContext().getPackageName();
  this.setActivityInitialTouchMode(true);
  act = this.launchActivity(app, SkeletonActivity.class, Bundle.EMPTY);

  bClear = (Button) act.findViewById(R.id.clear);
  bBack = (Button) act.findViewById(R.id.back);
  eMain = (EditText) act.findViewById(R.id.editor);

 }

 public void testClick()
 {

  TouchUtils.clickView(this, bClear);

 }

 public void testSendKeys()
 {

  act.runOnUiThread(
    new Runnable(){
     public void run(){
      bClear.clearFocus();
      eMain.requestFocus();
     }
    }
   );

  this.sendKeys("A B C D E F G ENTER");
 }

}
</code>```

testClick runs, but clicks on the main EditText view that has focus when the Activity starts and ends up bringing up the on-screen keyboard. I want it to click on the 'Clear' button below the EditText. Can someone tell me what's wrong here?

答: The use of clickView here is correct. The problem was in the AndroidManifest.xml. Min and Target SDK must be set for it to work properly. </p>

Title: How is clickView used properly?

Body:
I'm trying to write a simple test app to run in JUnit. I've been having trouble getting clickView to click on the proper view. Below is some sample code that can be used on SkeletonActivity sample app that comes with the SDK.

    public class SkeletonInstrumentation extends ActivityInstrumentationTestCase2<Activity>{

 private Activity act;
 private  Button bClear;
 private  Button bBack;
 private  EditText eMain;

 public SkeletonInstrumentation(){
  super("com.example.android.skeletonapp", Activity.class);

 }

 public void setUp() {

  String app = this.getInstrumentation().getTargetContext().getPackageName();
  this.setActivityInitialTouchMode(true);
  act = this.launchActivity(app, SkeletonActivity.class, Bundle.EMPTY);

  bClear = (Button) act.findViewById(R.id.clear);
  bBack = (Button) act.findViewById(R.id.back);
  eMain = (EditText) act.findViewById(R.id.editor);

 }

 public void testClick()
 {

  TouchUtils.clickView(this, bClear);

 }

 public void testSendKeys()
 {

  act.runOnUiThread(
    new Runnable(){
     public void run(){
      bClear.clearFocus();
      eMain.requestFocus();
     }
    }
   );

  this.sendKeys("A B C D E F G ENTER");
 }

}

testClick runs, but clicks on the main EditText view that has focus when the Activity starts and ends up bringing up the on-screen keyboard. I want it to click on the 'Clear' button below the EditText. Can someone tell me what's wrong here?


问:
Appending a JSON file
I'm working in JAVASCRIPT and I am trying to append a JSON file. The top of the file looks like this ...

```<code>doUpdate(
{
  "response": {
  "version":"0.1",
.
.
.
);
</code>```

I want to the top of the file to look like this and then to add the appropriate } at the end

```<code>doUpdate(
{
"data": {
  "response": {
  "version":"0.1",
.
.
.
.
}
);
</code>```

I know this is kind of weird but I have a theory and I am working on an issue.

答:
You would need to take several steps to modify the object inside the function call. The bare-basic, dumbest, error-prone way is:

```<code>fs = require('fs');
fs.readFile('myfile.js', 'utf8', function (str) {
  str = str.replace(/^doUpdate\(|\)$/g, ''); // modify this for newlines and semicolon
  obj = JSON.parse(str);
  obj['newContent'] = 'foo';
  obj['moreContent'] = 'bar';
  str = 'doUpdate(' + JSON.stringify(obj) + ')'; // or stringify(obj, null, 2) for pretty-print
  console.log(str);
  // or fs.writeFile('myfile.js', str);
});
</code>```

A more robust way would be parsing and building an AST using Esprima, then grabbing the object, and rebuilding the output js.

Title: Appending a JSON file

Body:
I'm working in JAVASCRIPT and I am trying to append a JSON file. The top of the file looks like this ...

doUpdate(
{
  "response": {
  "version":"0.1",
.
.
.
);

I want to the top of the file to look like this and then to add the appropriate } at the end

doUpdate(
{
"data": {
  "response": {
  "version":"0.1",
.
.
.
.
}
);

I know this is kind of weird but I have a theory and I am working on an issue.

Body:
You would need to take several steps to modify the object inside the function call. The bare-basic, dumbest, error-prone way is:

fs = require('fs');
fs.readFile('myfile.js', 'utf8', function (str) {
  str = str.replace(/^doUpdate\(|\)$/g, ''); // modify this for newlines and semicolon
  obj = JSON.parse(str);
  obj['newContent'] = 'foo';
  obj['moreContent'] = 'bar';
  str = 'doUpdate(' + JSON.stringify(obj) + ')'; // or stringify(obj, null, 2) for pretty-print
  console.log(str);
  // or fs.writeFile('myfile.js', str);
});

A more robust way would be parsing and building an AST using Esprima, then grabbing the object, and rebuilding the output js.


答:
Use the random built-in.

```<code>import random

my_list = list(range(1,11))
for i in range(10):
    my_list.append(random.randint(0, 10))

print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, 5, 10, 8, 6, 10, 6, 5, 6, 6]
</code>```

Title: How to have a list of random numbers by ensuring all of them at least once used?

Body:
Use the random built-in.

import random

my_list = list(range(1,11))
for i in range(10):
    my_list.append(random.randint(0, 10))

print(my_list)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 6, 5, 10, 8, 6, 10, 6, 5, 6, 6]


问:
Keyboard height giving 0 on first load - Swift
I am trying to move the view up when the keyboard appears, using the following code:

```<code>func keyboardWillShow(notification: NSNotification) {
if let keyboardSize: CGSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {

            if self.view.frame.origin.y == 0{
                print("Keyboard height is: \(keyboardSize.height)")

                let keyboardHeight = keyboardSize.height - (self.tabBarController?.tabBar.frame.height)!
                self.view.frame.origin.y -= (keyboardHeight)
                print("Keyboard height is: \(keyboardSize.height)")

        }
    }
}
</code>```

The first time this function is called once the app has been opened, keyboard height is populated as 0, meaning the view drops by the height of the tabBar. When I reload the view, it works perfectly from then on.

It seems like I am not getting the keyboard height until the keyboard is actually opened, which is too late for the first run of the function.

Any idea what the issue is? Please let me know if you want any more details.

答: Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey and see if that helps.

Body:
I am trying to move the view up when the keyboard appears, using the following code:

func keyboardWillShow(notification: NSNotification) {
if let keyboardSize: CGSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {

            if self.view.frame.origin.y == 0{
                print("Keyboard height is: \(keyboardSize.height)")

                let keyboardHeight = keyboardSize.height - (self.tabBarController?.tabBar.frame.height)!
                self.view.frame.origin.y -= (keyboardHeight)
                print("Keyboard height is: \(keyboardSize.height)")

        }
    }
}

The first time this function is called once the app has been opened, keyboard height is populated as 0, meaning the view drops by the height of the tabBar. When I reload the view, it works perfectly from then on.

It seems like I am not getting the keyboard height until the keyboard is actually opened, which is too late for the first run of the function.

Any idea what the issue is? Please let me know if you want any more details.


问:
Developer Portal ID in xcodebuild
My Apple Developer Account is on multiple teams and that is causing a problem in regards to getting the xcodebuild to run.

Here is the command that I am running.

xcodebuild -workspace <name>.xcworkspace -scheme "<my scheme>"

And the error that I am getting is...

Error Domain=IDECapabilitiesErrorDomain Code=1 "The operation requires a selected developer portal team."

I have tried setting the DEVELOPMENT_TEAM and CODE_SIGN_IDENTITY variables manually, but to no avail. I have also attempted to use the fastlane (with match, sigh, and cert) but that did not work as well. I was wondering if anyone knew a workaround for this situation. By the way, I am running this on Jenkins.

答:
It sounds like you don't have a provision profile selected in the project that you're trying to build, or perhaps don't have a team selected in one of your targets.

Open the project in Xcode and go into the build settings for the project. Make sure that you've got a developer profile selected for both the debug and release cases. Then select each of the build targets in the project and make sure that you've got a team, provision profile, and developer certificate selected. (If you've turned on automatic signing, you just need to select the team, and Xcode will take care of the others.)

Those settings are saved in the project file and will remain in effect when you build with xcodebuild.

Title: Developer Portal ID in xcodebuild


问:
How to scrape non-standard HTML with Nokogiri
How can I unpack a non-standard HTML:

```<code><body>
    <div class="open">
        <div style='style'>Raw name 1</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
        <div style='style'>Raw name 5</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
    </div>
</body>
</code>```

I want to get a result similar to:

```<code>['Raw name 1', Text_1, Text_2, Text_3, Text_4, Text_5]
...
['Raw name 5', Text_1, Text_2, Text_3, Text_4, Text_5]
</code>```

I tried to do something on this example How to parse a HTML table with Nokogiri?, but nothing happened.

Is it possible to obtain information that I want from such HTML?

答:
If I understand correctly this might work for you

```<code>require 'nokogiri'
body = <<-BODY
<body>
    <div class="open">
        <div style='style'>Raw name 1</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
        <div style='style'>Raw name 5</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
    </div>
</body>
BODY

doc = Nokogiri::HTML(body)
doc.xpath('//body/div').children.each_with_object({}) do |node,obj|
    text = node.text.strip
    obj[text] = [] if node.name == 'div'
    obj[obj.keys.last] << text if node.name == 'p'
end
#=> {"Raw name 1"=>["Text_1", "Text_2", "Text_3", "Text_4", "Text_5"],
#     "Raw name 5"=>["Text_1", "Text_2", "Text_3", "Text_4", "Text_5"]}
</code>```

Steps:

This follows the xpath to the first div (doc.xpath('//body/div'))

Then passes each child (.children) of that div to the block along with an object (.each_with_object({}) do |node,obj|) in this case as an accumulator.

It then adds a key for each div tag and assigns it to an empty array(obj[text] = [] if node.name == 'div').

It populates the last key with the following p tags (obj[obj.keys.last] << text if node.name == 'p')

The result is a Hash where the keys are the divs and the value is an Array of the following p tags text until it gets to the next div.

Body:
How can I unpack a non-standard HTML:

Raw name 1

Text_1

Text_2

Text_3

Text_4

Text_5

Raw name 5

Text_1

Text_2

Text_3

Text_4

Text_5

I want to get a result similar to:

['Raw name 1', Text_1, Text_2, Text_3, Text_4, Text_5]
...
['Raw name 5', Text_1, Text_2, Text_3, Text_4, Text_5]

I tried to do something on this example How to parse a HTML table with Nokogiri?, but nothing happened.

Is it possible to obtain information that I want from such HTML?

Body:
If I understand correctly this might work for you

require 'nokogiri'
body = <<-BODY
<body>
    <div class="open">
        <div style='style'>Raw name 1</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
        <div style='style'>Raw name 5</div>
        <p>Text_1</p>
        <p>Text_2</p>
        <p>Text_3</p>
        <p>Text_4</p>
        <p>Text_5</p>
    </div>
</body>
BODY

doc = Nokogiri::HTML(body)
doc.xpath('//body/div').children.each_with_object({}) do |node,obj|
    text = node.text.strip
    obj[text] = [] if node.name == 'div'
    obj[obj.keys.last] << text if node.name == 'p'
end
#=> {"Raw name 1"=>["Text_1", "Text_2", "Text_3", "Text_4", "Text_5"],
#     "Raw name 5"=>["Text_1", "Text_2", "Text_3", "Text_4", "Text_5"]}

Steps:

This follows the xpath to the first div (doc.xpath('//body/div'))

Then passes each child (.children) of that div to the block along with an object (.each_with_object({}) do |node,obj|) in this case as an accumulator.

It then adds a key for each div tag and assigns it to an empty array(obj[text] = [] if node.name == 'div').

It populates the last key with the following p tags (obj[obj.keys.last] << text if node.name == 'p')

The result is a Hash where the keys are the divs and the value is an Array of the following p tags text until it gets to the next div.


问:
Node.js install keeps rolling back install right near the end
Working on Windows 7 on a work computer that's been handled by many users before me. npm and node seems to have been installed in the past, particularly through other software downloads, but nothing is organized and I'm afraid to delete things because...well, it's a work computer and I'm liable to destroy something. Anyways, I've been trying to load node.js but it keeps rolling back. I've tried eliminating the option 'online documentation shortcuts' which was suggested in a similar questions in question, but no luck. Right near the end it starts to roll back.

I can't figure out where to get an error log so I can be more specific.

Any suggestions?

答:
Have you try with installing node via NVM?

NVM is a Node Version Manager, it allows you to install multiple versions
of node in separated environments

Here is the link!


问:
Set, get text and value in listitem view in Android
I have listview collection that show id and name in Android. I following example from this resource site.

But actually that example only display name. I wish similar like checkboxlist in ASP.NET that contain property text and value. So the text to show name and value store id. When user select one item, I could retrieve id by viewtext.

My question is how do I set id and name in same viewtext item? I wish could pass the id to another layout.

I know that possible using multi viewtext then set invisible of viewtext using map. How that could be waste memory.

答: Views have an associated tag Object map, which could contain your id http://developer.android.com/reference/android/view/View.html#getTag%28int%29</p>


问:
Websocketpp: Address already in use
I am using websocketpp to run a websocket server. However, when I close the application and start it again, I get the error:

```<code>[info] asio listen error: system:98 (Address already in use)
</code>```

It seems like I have to set reuse_address in the asio socket. I have not found any documentation how to do it.

How can I let the websocket server reuse the address?

答:
According to this help page it looks like there is a set_reuse_addr() function exposed, this may help?

Synopsis:

```<code>void set_reuse_addr (bool value)
</code>```

Specifies whether or not to use the SO_REUSEADDR TCP socket option.
  What this flag does depends on your operating system.

Please consult operating system documentation for more details. There
  may be security consequences to enabling this option.

New values affect future calls to listen only so set this value prior
  to calling listen.

The default is false.

Title: Websocketpp: Address already in use

Body:
I am using websocketpp to run a websocket server. However, when I close the application and start it again, I get the error:

[info] asio listen error: system:98 (Address already in use)

It seems like I have to set reuse_address in the asio socket. I have not found any documentation how to do it.

How can I let the websocket server reuse the address?

Body:
According to this help page it looks like there is a set_reuse_addr() function exposed, this may help?

Synopsis:

void set_reuse_addr (bool value)

Specifies whether or not to use the SO_REUSEADDR TCP socket option.
  What this flag does depends on your operating system.

Please consult operating system documentation for more details. There
  may be security consequences to enabling this option.

New values affect future calls to listen only so set this value prior
  to calling listen.

The default is false.

ContentLicense: CC BY-SA 4.0


问:
How to configure webpack multicompiler for a nested application?
Having webpack config like so:

```<code>module.exports = [
  {
    entry: { main: './main/app.js' },
    module: [...]
  }, {
    entry: { sub: './sub/app.js' },
    module: [...]
  }
]
</code>```

And main/app.js like so:

```<code>import('./foo'); // all files inside ./main should be handled by first config
import('../sub/bar');  // all files inside ./sub should be handled by second config
</code>```

I'd like to configure webpack so that each config object handles only files in that app's directory. Which means that even though I include files from sub app inside main app, I'd like for all the loaders to only apply to files imported from main app and let sub app files be handled by sub app config.

I've looked through multiple webpack issues and docs, but there doesn't seem to be a solution for this. I hope that perhaps somebody could shine the light how to achieve that.

Using include/exclude does not solve the issue - these will only prevent loaders to being applied to given files, but the main app will still attempt to load them and throw errors that no loader exists for given files.

noParse or webpackIgnorePlugin are also not an option, since sub app is a fully fledged app, which will do other file imports etc. and noParse would break these imports.

Edit: On a higher level, what I'm trying to do is to have one main application that loads multiple sub apps dynamically into the window (using dynamic import()).

Each sub app should have its own webpack config and only that config should be responsible for applying correct loaders. Main app should only serve a the navigation that allows loading the sub apps dynamically, without knowing what loaders they might need.

答:
By default when we run webpack it loads webpack.config.js however we can use webpack multiple config files  depding upon app structure.

webpack --config="webpack.app1.config.js"

webpack --config="webpack.app2.config.js"

Also we can multiple entries.

```<code>entry: {
        app: [
        './src/app.js', //main javascript file
        './src/app.scss', //main scss file
        ],
        vendor:['jquery']

    },
</code>```

Then in modules rules you can exclude certain folder depeding upon structure. but it is recommended to create seprate webpack config files for different app structures.

Body:
Having webpack config like so:

module.exports = [
  {
    entry: { main: './main/app.js' },
    module: [...]
  }, {
    entry: { sub: './sub/app.js' },
    module: [...]
  }
]

And main/app.js like so:

import('./foo'); // all files inside ./main should be handled by first config
import('../sub/bar');  // all files inside ./sub should be handled by second config

I'd like to configure webpack so that each config object handles only files in that app's directory. Which means that even though I include files from sub app inside main app, I'd like for all the loaders to only apply to files imported from main app and let sub app files be handled by sub app config.

I've looked through multiple webpack issues and docs, but there doesn't seem to be a solution for this. I hope that perhaps somebody could shine the light how to achieve that.

Using include/exclude does not solve the issue - these will only prevent loaders to being applied to given files, but the main app will still attempt to load them and throw errors that no loader exists for given files.

noParse or webpackIgnorePlugin are also not an option, since sub app is a fully fledged app, which will do other file imports etc. and noParse would break these imports.

Edit: On a higher level, what I'm trying to do is to have one main application that loads multiple sub apps dynamically into the window (using dynamic import()).

Each sub app should have its own webpack config and only that config should be responsible for applying correct loaders. Main app should only serve a the navigation that allows loading the sub apps dynamically, without knowing what loaders they might need.

Body:
By default when we run webpack it loads webpack.config.js however we can use webpack multiple config files  depding upon app structure.

webpack --config="webpack.app1.config.js"

webpack --config="webpack.app2.config.js"

Also we can multiple entries.

entry: {
        app: [
        './src/app.js', //main javascript file
        './src/app.scss', //main scss file
        ],
        vendor:['jquery']

    },

Then in modules rules you can exclude certain folder depeding upon structure. but it is recommended to create seprate webpack config files for different app structures.


问:
How to Create Extension Form View in Python Side?
I am trying to create dynamic view ,  so i want to create views in python side . But when i try to save the view the "arch_base" field is not set . Can someone tell me what's the problem ? Here is my function</p>

```<code>@api.onchange('field_id')
def create_validation_button(self):
    model = self.field_id.model_id.model
    model_view = self.env['ir.ui.view'].search([("model", "=", model), ('type', "=", "form")])
    arch = '<xpath expr="//header" postition="inside"><button string="Add Followers" type="object" name="add_project_followers" /></xpath>'
    if model_view:
        self.view_id = None
        self.env['ir.ui.view'].search(
            [("model", "=", model), ('name', "=", 'validation.' + model_view.name)]).unlink()
        view_data = {'name': 'validation.' + model_view.name, 'type': 'form', 'model': model, 'priority': 1,
                     'inherit_id': model_view.id,
                     'mode': 'extension',
                     'arch_base': arch.encode('utf-8')}
        view = self.env["ir.ui.view"].create(view_data)
        self.view_id = view
</code>```

答:
the field name is arch not arch_base so the set will be :

```<code>view_data = {'name': 'validation.' + model_view.name, 'type': 'form', 'model': model, 'priority': 1,
                     'inherit_id': model_view.id,
                     'mode': 'extension',
                     'arch': arch.encode('utf-8')}
</code>```

Thanks to

Peter Alabaster
  https://www.odoo.com/fr_FR/forum/aide-1/question/how-to-create-extension-form-view-in-python-side-119479

Body:
I am trying to create dynamic view ,  so i want to create views in python side . But when i try to save the view the "arch_base" field is not set . Can someone tell me what's the problem ? Here is my function

@api.onchange('field_id')
def create_validation_button(self):
    model = self.field_id.model_id.model
    model_view = self.env['ir.ui.view'].search([("model", "=", model), ('type', "=", "form")])
    arch = '<xpath expr="//header" postition="inside"><button string="Add Followers" type="object" name="add_project_followers" /></xpath>'
    if model_view:
        self.view_id = None
        self.env['ir.ui.view'].search(
            [("model", "=", model), ('name', "=", 'validation.' + model_view.name)]).unlink()
        view_data = {'name': 'validation.' + model_view.name, 'type': 'form', 'model': model, 'priority': 1,
                     'inherit_id': model_view.id,
                     'mode': 'extension',
                     'arch_base': arch.encode('utf-8')}
        view = self.env["ir.ui.view"].create(view_data)
        self.view_id = view

Body:
the field name is arch not arch_base so the set will be :

view_data = {'name': 'validation.' + model_view.name, 'type': 'form', 'model': model, 'priority': 1,
                     'inherit_id': model_view.id,
                     'mode': 'extension',
                     'arch': arch.encode('utf-8')}

Thanks to

Peter Alabaster
  https://www.odoo.com/fr_FR/forum/aide-1/question/how-to-create-extension-form-view-in-python-side-119479


答:
```<code>import random

l = [x for x in range(11)] + [random.randint(0, 10) for x in range(11)]
</code>```

edit
If you would like the 2nd half of list to only contain elements from the first half, but in a random order

```<code>a = [x for x in range(11)]
b = a[:]
random.shuffle(b)
a.extend(b)

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 7, 4, 10, 1, 5, 9, 3, 0, 6, 2, 8]
</code>```

Body:
import random

l = [x for x in range(11)] + [random.randint(0, 10) for x in range(11)]

edit
If you would like the 2nd half of list to only contain elements from the first half, but in a random order

a = [x for x in range(11)]
b = a[:]
random.shuffle(b)
a.extend(b)

>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 7, 4, 10, 1, 5, 9, 3, 0, 6, 2, 8]


答:
I am using this

first

```<code>var iskeyboard : Bool = false;
</code>```

for show

```<code>  func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        if (!iskeyboard)
        {
            self.view.frame.origin.y -= keyboardSize.height
        }
        iskeyboard = true

    }
}
</code>```

for hide

```<code>  func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        if (iskeyboard)
        {
            self.view.frame.origin.y += keyboardSize.height
        }
         iskeyboard = false
    }
}
</code>```

Title: Keyboard height giving 0 on first load - Swift

Body:
I am using this

first

var iskeyboard : Bool = false;

for show

  func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        if (!iskeyboard)
        {
            self.view.frame.origin.y -= keyboardSize.height
        }
        iskeyboard = true

    }
}

for hide

  func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

        if (iskeyboard)
        {
            self.view.frame.origin.y += keyboardSize.height
        }
         iskeyboard = false
    }
}


问:
Null Pointer Exception Error message
I cannot seem to find why I am getting this error message. I thought I have already instantiated my array in my main.

Exception in thread "main" java.lang.NullPointerException

```<code>public class A1ArrayList<E> {
    private E[] e;
    private int capacity = 0;

    public A1ArrayList(){
    }

    public int size(){
        return e.length;
    }

    public boolean add(E addElement){
        e[capacity] = addElement;
        capacity = capacity + 1;

        return true;
    }

    public static void main(String[] arg){
        A1ArrayList<Object> e = new A1ArrayList<Object>();
        e.size();

    }
</code>```

答: Your Array e is null. Therefore you get a Nullpointer Exception. </p>

Title: Null Pointer Exception Error message

Body:
I cannot seem to find why I am getting this error message. I thought I have already instantiated my array in my main.

Exception in thread "main" java.lang.NullPointerException

public class A1ArrayList<E> {
    private E[] e;
    private int capacity = 0;

    public A1ArrayList(){
    }

    public int size(){
        return e.length;
    }

    public boolean add(E addElement){
        e[capacity] = addElement;
        capacity = capacity + 1;

        return true;
    }

    public static void main(String[] arg){
        A1ArrayList<Object> e = new A1ArrayList<Object>();
        e.size();

    }


问:
Excel VBA how to populate values from different sheets
I have a sheet that I want to be able to transport cell values being double-clicked by users to another sheet/form called JE.

Example: user clicks on cell F10 in sheet JE, that takes the user to a different sheet (containing a macro), once the user is at that sheet, I want the user to be able to double-click any cell in the A column and the cell value being clicked, fills cell F10 back in sheet JE. So, after being navigated to a macro/different sheet, If the user double clicks on cell A7 and the value "123ABC" is in A7, I would like "123ABC" to populate cell F10 in sheet JE. Similarly, if the user clicks cell F25 on sheet JE, and still chooses to double-click A7 in a different sheet, I would like the value "123ABC" to fill F25 in sheet JE. I would also like the cell in column F to turn to a no-fill background once a value is present in the cell.

The issue I am having now is that my code is set up in such a way that no matter which row the user is using on sheet JE, the values in column A of the macros are only filling the first cell in column F(F7) Whereas, I want the value being double-clicked on in the macro to fill in the F column cell that is active, not the first cell in the F column. Also, when double-clicked, the values in column A of the macros, are not changing the background color of the red cell in column F to a no fill, white background.

This code is the code associated with sheet JE (The main form users are filling out)

```<code>Option Explicit
Public sourceRange As Range

Private Sub Worksheet_Change(ByVal Target As Range)
'  If Not Intersect(Target, Range("C7:D446")) Is Nothing Then
      Dim c As Range: Set c = Range("D7:D446")
'     For Each c In Target
 For Each c In c.Cells
          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20ONLC", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select
      Next c
' End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing ' Set it to nothing to avoid too long remembering
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target ' Remember source cell
      'Cancel = True
      Select Case Target.Offset(0, -2).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
End If

End Sub
</code>```

This is the code that lies in all of the macro sheets which the user is brought to when clicking on the cells in the F column in Sheet JE.

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Set JE.sourceRange = Target.Value
If Target.Column = 1 Then
   If Not JE.sourceRange Is Nothing Then
        JE.sourceRange.Value = ActiveCell.Value
        Cells(c.Row, "F").Interior.ColorIndex = 0

End If
End If
End Sub
</code>```

I am also having trouble getting values for the C column to populate multiple rows. For example, if I already have a value in C7 and want to add a value being clicked on in a sheet to the C column as well, If i click on a value, it will overwrite the value in C7 rather than populating cell C8. Here is the code I have for that sheet:

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Target.Column = 1 Then
'Sheet2.Range("F" & Target.Row & ":F" & Target.Row).Value = ActiveCell.Value
Sheet2.sourceRange.Value = ActiveCell.Value
Worksheets("JE").Activate
'Sheet2.Activate

'Cells(c.Row, "F").Interior.ColorIndex = 3
Cancel = True
End If
End Sub
</code>```

答:
You need to store somwhere original Range active before user switch to different worksheet. Then you will be able to write there value.

How to do it:

1) Add public variable on worksheet JE (just after line Option Explicit)

```<code>Public sourceRange As Range
</code>```

2) In event Worksheet_SelectionChange on worksheet JE add just after first if code to set variable to current Range - please also notice first line with setting variable to Nothing - it is required to avoid remembering last range forever:

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing ' Set it to nothing to avoid too long remembering
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target ' Remember source cell
      'Cancel = True
</code>```

3) Now it is easy - just use variable in double click event on other sheet:

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Target.Column = 1 Then
    If Not JE.sourceRange Is Nothing Then
        JE.sourceRange.Value = ActiveCell.Value
    End If
</code>```

Please note rest of code should stay like it is - for clarity I put only fragments where you need to change something.

Body:
I have a sheet that I want to be able to transport cell values being double-clicked by users to another sheet/form called JE.

Example: user clicks on cell F10 in sheet JE, that takes the user to a different sheet (containing a macro), once the user is at that sheet, I want the user to be able to double-click any cell in the A column and the cell value being clicked, fills cell F10 back in sheet JE. So, after being navigated to a macro/different sheet, If the user double clicks on cell A7 and the value "123ABC" is in A7, I would like "123ABC" to populate cell F10 in sheet JE. Similarly, if the user clicks cell F25 on sheet JE, and still chooses to double-click A7 in a different sheet, I would like the value "123ABC" to fill F25 in sheet JE. I would also like the cell in column F to turn to a no-fill background once a value is present in the cell.

The issue I am having now is that my code is set up in such a way that no matter which row the user is using on sheet JE, the values in column A of the macros are only filling the first cell in column F(F7) Whereas, I want the value being double-clicked on in the macro to fill in the F column cell that is active, not the first cell in the F column. Also, when double-clicked, the values in column A of the macros, are not changing the background color of the red cell in column F to a no fill, white background.

This code is the code associated with sheet JE (The main form users are filling out)

Option Explicit
Public sourceRange As Range

Private Sub Worksheet_Change(ByVal Target As Range)
'  If Not Intersect(Target, Range("C7:D446")) Is Nothing Then
      Dim c As Range: Set c = Range("D7:D446")
'     For Each c In Target
 For Each c In c.Cells
          Select Case c.Value
              Case "1000GP", "1000MM", "19FEST", "20IEDU", "20ONLC", "20PART", "20PRDV", "20SPPR", "22DANC", "22LFLC", "22MEDA", "530CCH", "60POUBL", "74GA01", "74GA17", "74GA99", "78REDV"
                  Cells(c.Row, "F").Interior.ColorIndex = 3
              Case Else
                 Cells(c.Row, "F").Interior.ColorIndex = 0
          End Select
      Next c
' End If

End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing ' Set it to nothing to avoid too long remembering
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target ' Remember source cell
      'Cancel = True
      Select Case Target.Offset(0, -2).Value2
        Case "1000GP": gotoref1
        Case "1000MM": gotoref2
        Case "19FEST": gotoref3
        Case "20IEDU": gotoref4
        Case "20ONLC": gotoref5
        Case "20PART": gotoref6
        Case "20PRDV": gotoref7
        Case "20SPPR": gotoref8
        Case "22DANC": gotoref9
        Case "22LFLC": gotoref10
        Case "22MEDA": gotoref11
        Case "530CCH": gotoref12
        Case "60PUBL": gotoref13
        Case "74GA01": gotoref14
        Case "74GA17": gotoref15
        Case "74GA99": gotoref16
        Case "78REDV": gotoref17
      End Select
End If

End Sub

This is the code that lies in all of the macro sheets which the user is brought to when clicking on the cells in the F column in Sheet JE.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Set JE.sourceRange = Target.Value
If Target.Column = 1 Then
   If Not JE.sourceRange Is Nothing Then
        JE.sourceRange.Value = ActiveCell.Value
        Cells(c.Row, "F").Interior.ColorIndex = 0

End If
End If
End Sub

I am also having trouble getting values for the C column to populate multiple rows. For example, if I already have a value in C7 and want to add a value being clicked on in a sheet to the C column as well, If i click on a value, it will overwrite the value in C7 rather than populating cell C8. Here is the code I have for that sheet:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Target.Column = 1 Then
'Sheet2.Range("F" & Target.Row & ":F" & Target.Row).Value = ActiveCell.Value
Sheet2.sourceRange.Value = ActiveCell.Value
Worksheets("JE").Activate
'Sheet2.Activate

'Cells(c.Row, "F").Interior.ColorIndex = 3
Cancel = True
End If
End Sub

Body:
You need to store somwhere original Range active before user switch to different worksheet. Then you will be able to write there value.

How to do it:

1) Add public variable on worksheet JE (just after line Option Explicit)

Public sourceRange As Range

2) In event Worksheet_SelectionChange on worksheet JE add just after first if code to set variable to current Range - please also notice first line with setting variable to Nothing - it is required to avoid remembering last range forever:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Set sourceRange = Nothing ' Set it to nothing to avoid too long remembering
  If Target.Column = 6 And Target.Cells.Count = 1 And Target.Interior.ColorIndex = 3 Then
      Set sourceRange = Target ' Remember source cell
      'Cancel = True

3) Now it is easy - just use variable in double click event on other sheet:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Target.Column = 1 Then
    If Not JE.sourceRange Is Nothing Then
        JE.sourceRange.Value = ActiveCell.Value
    End If

Please note rest of code should stay like it is - for clarity I put only fragments where you need to change something.


问:
Combining Either and Pair monads with transformers
I haven't used monad transformers before but I think it's what I need in my case. Here's some sample code below:

```<code>Prelude> (+) <$> Right 2 <*> Right 3
Right 5

Prelude> (+) <$> (['a'],2) <*> (['b'],3)
("ab",5)
</code>```

But I want to combine these two behaviours like so:

```<code>Prelude> (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)
</code>```

Naturally this fails to compile as numeric addition is not defined on (String, Int).

The Monad transformers Haskell wiki page suggests I need to use a transformer for the inner monad, which is in this case a pair, but searching for PairT on Hayoo! or Hoogle didn't reveal anything relevant.

Do I have to implement this transformer myself, or is there something on Hackage I've missed, or am I just misunderstanding how this should be done?

Note:

The actual outer monad I'm using isn't Either, it's a custom monad I've detailed in this question, which however is quite similar to Either.

答:
In the example, we are combining actions in an "applicative" way, meaning that each action does not depend on the returning value of a previous action.

Turns out that Applicatives compose better than Monads: instead of needing a different "transformer" type for each Applicative, we can use a common Compose newtype to create a composite effect for any two Applicatives:

```<code>ghci> import Data.Functor.Compose
ghci> getCompose $ (+) <$> Compose (Right ("a",2)) <*> Compose (Right ("b",3))
Right ("ab",5)
</code>```

The effects of the "outermost" Applicative (Either in this case) have priority.

There is some noise in the wrapping/unwrapping of the newtype. If we want to avoid the newtype noise and the operators, we could also modify chi's answer and do something like

```<code>liftA2 (liftA2 (+)) (Right ("a",2)) (Right ("b",3))
</code>```

The "outer" liftA2 works on the Either, the "inner" liftA2 works on (,) String.

Body:
I haven't used monad transformers before but I think it's what I need in my case. Here's some sample code below:

Prelude> (+) <$> Right 2 <*> Right 3
Right 5

Prelude> (+) <$> (['a'],2) <*> (['b'],3)
("ab",5)

But I want to combine these two behaviours like so:

Prelude> (+) <$> Right ("a",2) <*> Right ("b",3)
Right ("ab",5)

Naturally this fails to compile as numeric addition is not defined on (String, Int).

The Monad transformers Haskell wiki page suggests I need to use a transformer for the inner monad, which is in this case a pair, but searching for PairT on Hayoo! or Hoogle didn't reveal anything relevant.

Do I have to implement this transformer myself, or is there something on Hackage I've missed, or am I just misunderstanding how this should be done?

Note:

The actual outer monad I'm using isn't Either, it's a custom monad I've detailed in this question, which however is quite similar to Either.

Body:
In the example, we are combining actions in an "applicative" way, meaning that each action does not depend on the returning value of a previous action.

Turns out that Applicatives compose better than Monads: instead of needing a different "transformer" type for each Applicative, we can use a common Compose newtype to create a composite effect for any two Applicatives:

ghci> import Data.Functor.Compose
ghci> getCompose $ (+) <$> Compose (Right ("a",2)) <*> Compose (Right ("b",3))
Right ("ab",5)

The effects of the "outermost" Applicative (Either in this case) have priority.

There is some noise in the wrapping/unwrapping of the newtype. If we want to avoid the newtype noise and the operators, we could also modify chi's answer and do something like

liftA2 (liftA2 (+)) (Right ("a",2)) (Right ("b",3))

The "outer" liftA2 works on the Either, the "inner" liftA2 works on (,) String.


问:
Restructuring data.frame to long format converts my numerics to NA's?

Problem

I have the following table in R which shows one row per salary:

```<code>> df
  employee employment start_date  end_date salary
1      Ian          1  28Jul2010 28Jul2011  20000
2     Rose          1  28Jul2011 28Jul2012  30000
3     Rose          2  28Jul2012 28Jul2013  31000
</code>```

and I would like to transform it into the following structure which shows one row per employee:

```<code>> df2
  employee start_date_employement_1 end_date_employment_1 salary_employement_1 start_date_employement_2 end_date_employment_2 salary_employement_2
1      Ian                28Jul2010             28Jul2011                20000                     <NA>                  <NA>                   NA
2     Rose                28Jul2011             28Jul2012                30000                28Jul2012             28Jul2013                31000
</code>```

Unfortunately I can't see how to do this and would appreciate some help.

Note: The R code to create the tables above are at the end of this post.

My failed approach

This is a data restructuring problem and so I imagine that the reshape/reshape2 packages are the way forward.

I can run the basic melt and cast examples but can't see how to apply it to my specific problem. When I tried, my salary values disapeared and I'm not sure why (seems to be interpreting my salaries as factors instead of numerics?):

```<code>library(reshape2)
library(dplyr)
> melt(df, id.vars = c("employee", "employment")) %>%
    arrange(employee, employment)
  employee employment   variable     value
1      Ian          1 start_date 28Jul2010
2      Ian          1   end_date 28Jul2011
3      Ian          1     salary      <NA>
4     Rose          1 start_date 28Jul2011
5     Rose          1   end_date 28Jul2012
6     Rose          1     salary      <NA>
7     Rose          2 start_date 28Jul2012
8     Rose          2   end_date 28Jul2013
9     Rose          2     salary      <NA>
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = c(20000L, 30000L, 31000L)) :
  invalid factor level, NA generated
</code>```

However, if the above did work, then I'd do this:

```<code>melt(df, id.vars = c("employee", "employment")) %>%
  arrange(employee, employment) %>%
  mutate(variable = paste(variable, employment, sep="_")) %>%
  select(employee, variable, value) %>%
  cast()

  employee end_date_1 end_date_2 salary_1 salary_2 start_date_1 start_date_2
1      Ian  28Jul2011       <NA>     <NA>     <NA>    28Jul2010         <NA>
2     Rose  28Jul2012  28Jul2013     <NA>     <NA>    28Jul2011    28Jul2012
</code>```

Which is almost what I want except for the NA's and the ordering of the columns.

Data

```<code>df <-
  structure(list(employee = c("Ian", "Rose", "Rose"),
               employment = c(1L, 1L, 2L),
               start_date = c("28Jul2010", "28Jul2011", "28Jul2012"),
               end_date = c("28Jul2011", "28Jul2012", "28Jul2013"),
               salary = c(20000.00, 30000.00, 31000.00)),
          .Names = c("employee", "employment", "start_date", "end_date", "salary"),
          sorted = c("employee", "employment"), class = c("data.frame"), row.names = c(NA, -3L))

df2 <-
  structure(list(employee = c("Ian", "Rose"), start_date_employement_1 = c("28Jul2010", "28Jul2011"),
                 end_date_employment_1 = c("28Jul2011", "28Jul2012"),
                 salary_employement_1 = c(20000L, 30000L),
                 start_date_employement_2 = c(NA, "28Jul2012"),
                 end_date_employment_2 = c(NA, "28Jul2013"),
                 salary_employement_2 = c(NA, 31000L)),
            .Names = c("employee", "start_date_employement_1", "end_date_employment_1", "salary_employement_1", "start_date_employement_2", "end_date_employment_2", "salary_employement_2"),
            class = "data.frame", row.names = c(NA, -2L))
</code>```

答:
You are meant to use dcast to reshape data frame from long to wide; The reshape2::dcast doesn't seem to support multi value.var columns. You might use reshape from baseR:

```<code>reshape(df, direction = "wide", idvar = "employee", timevar = "employment")

#  employee start_date.1 end_date.1 salary.1 start_date.2 end_date.2 salary.2
#1      Ian    28Jul2010  28Jul2011    20000         <NA>       <NA>       NA
#2     Rose    28Jul2011  28Jul2012    30000    28Jul2012  28Jul2013    31000
</code>```

Or use data.table::dcast:

```<code>library(data.table)
dcast(setDT(df), employee ~ employment, value.var = c("start_date", "end_date", "salary"))
#   employee start_date_1 start_date_2 end_date_1 end_date_2 salary_1 salary_2
#1:      Ian    28Jul2010           NA  28Jul2011         NA    20000       NA
#2:     Rose    28Jul2011    28Jul2012  28Jul2012  28Jul2013    30000    31000
</code>```

Body:
Problem

I have the following table in R which shows one row per salary:

> df
  employee employment start_date  end_date salary
1      Ian          1  28Jul2010 28Jul2011  20000
2     Rose          1  28Jul2011 28Jul2012  30000
3     Rose          2  28Jul2012 28Jul2013  31000

and I would like to transform it into the following structure which shows one row per employee:

> df2
  employee start_date_employement_1 end_date_employment_1 salary_employement_1 start_date_employement_2 end_date_employment_2 salary_employement_2
1      Ian                28Jul2010             28Jul2011                20000                     <NA>                  <NA>                   NA
2     Rose                28Jul2011             28Jul2012                30000                28Jul2012             28Jul2013                31000

Unfortunately I can't see how to do this and would appreciate some help.

Note: The R code to create the tables above are at the end of this post.

My failed approach

This is a data restructuring problem and so I imagine that the reshape/reshape2 packages are the way forward.

I can run the basic melt and cast examples but can't see how to apply it to my specific problem. When I tried, my salary values disapeared and I'm not sure why (seems to be interpreting my salaries as factors instead of numerics?):

library(reshape2)
library(dplyr)
> melt(df, id.vars = c("employee", "employment")) %>%
    arrange(employee, employment)
  employee employment   variable     value
1      Ian          1 start_date 28Jul2010
2      Ian          1   end_date 28Jul2011
3      Ian          1     salary      <NA>
4     Rose          1 start_date 28Jul2011
5     Rose          1   end_date 28Jul2012
6     Rose          1     salary      <NA>
7     Rose          2 start_date 28Jul2012
8     Rose          2   end_date 28Jul2013
9     Rose          2     salary      <NA>
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = c(20000L, 30000L, 31000L)) :
  invalid factor level, NA generated

However, if the above did work, then I'd do this:

melt(df, id.vars = c("employee", "employment")) %>%
  arrange(employee, employment) %>%
  mutate(variable = paste(variable, employment, sep="_")) %>%
  select(employee, variable, value) %>%
  cast()

  employee end_date_1 end_date_2 salary_1 salary_2 start_date_1 start_date_2
1      Ian  28Jul2011       <NA>     <NA>     <NA>    28Jul2010         <NA>
2     Rose  28Jul2012  28Jul2013     <NA>     <NA>    28Jul2011    28Jul2012

Which is almost what I want except for the NA's and the ordering of the columns.

Data

df <-
  structure(list(employee = c("Ian", "Rose", "Rose"),
               employment = c(1L, 1L, 2L),
               start_date = c("28Jul2010", "28Jul2011", "28Jul2012"),
               end_date = c("28Jul2011", "28Jul2012", "28Jul2013"),
               salary = c(20000.00, 30000.00, 31000.00)),
          .Names = c("employee", "employment", "start_date", "end_date", "salary"),
          sorted = c("employee", "employment"), class = c("data.frame"), row.names = c(NA, -3L))

df2 <-
  structure(list(employee = c("Ian", "Rose"), start_date_employement_1 = c("28Jul2010", "28Jul2011"),
                 end_date_employment_1 = c("28Jul2011", "28Jul2012"),
                 salary_employement_1 = c(20000L, 30000L),
                 start_date_employement_2 = c(NA, "28Jul2012"),
                 end_date_employment_2 = c(NA, "28Jul2013"),
                 salary_employement_2 = c(NA, 31000L)),
            .Names = c("employee", "start_date_employement_1", "end_date_employment_1", "salary_employement_1", "start_date_employement_2", "end_date_employment_2", "salary_employement_2"),
            class = "data.frame", row.names = c(NA, -2L))

Body:
You are meant to use dcast to reshape data frame from long to wide; The reshape2::dcast doesn't seem to support multi value.var columns. You might use reshape from baseR:

reshape(df, direction = "wide", idvar = "employee", timevar = "employment")

#  employee start_date.1 end_date.1 salary.1 start_date.2 end_date.2 salary.2
#1      Ian    28Jul2010  28Jul2011    20000         <NA>       <NA>       NA
#2     Rose    28Jul2011  28Jul2012    30000    28Jul2012  28Jul2013    31000

Or use data.table::dcast:

library(data.table)
dcast(setDT(df), employee ~ employment, value.var = c("start_date", "end_date", "salary"))
#   employee start_date_1 start_date_2 end_date_1 end_date_2 salary_1 salary_2
#1:      Ian    28Jul2010           NA  28Jul2011         NA    20000       NA
#2:     Rose    28Jul2011    28Jul2012  28Jul2012  28Jul2013    30000    31000


答:
You can test that all the col3 values are the same for a given col1 value a simple group by and having query:

```<code>select col1
from t
group by col1
having min(col3) = max(col3);
</code>```

I don't see what col2 has to do with the question.

Title: Matching All the Columns Have the Same Value

Body:
I have a data set as follows:

Col1 | COl2  | Col3
--------------------
A    | Jan-1 |   1
-------------------
A    | Jan-2 |   2
-------------------
A    | Jan-3 |   2
-------------------
A    | Jan-4 |   3
-------------------
B    | Jan-1 |   1
-------------------
B    | Jan-2 |   1
-------------------
B    | Jan-3 |   1
-------------------
B    | Jan-4 |   1
-------------------

I want to select all the Col1 entities that have the same Col3 value for entire date range available in Col2.

Would you be able to help me with this. Thanks.

Body:
You can test that all the col3 values are the same for a given col1 value a simple group by and having query:

select col1
from t
group by col1
having min(col3) = max(col3);

I don't see what col2 has to do with the question.


问:
How to convert Nifti file to Numpy array?
I have 3D array in Nifti file (.ii.gz) and I want to save it as a 3D numpy array. I used Nibabel to convert Numpy to Nifti1. Can I do the opposite?</p>

答:
From nipy

```<code>import numpy as np
import nibabel as nib

img = nib.load(example_filename)

a = np.array(img.dataobj)
</code>```

Body:
From nipy

import numpy as np
import nibabel as nib

img = nib.load(example_filename)

a = np.array(img.dataobj)


问:
How to pass a two dimensional list/array between groovy scripts in soap ui?
Problem statement: We need a way to pass a two dimensional list (or array) from one groovy script to other scripts ( to assert values from multiple DB2 tables in other scripts].

Some Background:
Step1: Based on our input xml payload we are capturing the list of nodes (and child elements) in a two dimensional list [][]. [Done]
Step2: Now we want to use the values from each of this list to assert with respect to values in DB2 tables [Also done, however keeping both step1 and step2 in same groovy script].

What we want is to to be able to pass the 2dimensional list from step1 in step2. Specially important since we have multiple tables and we dont want to either add all table steps in one big groovy script Or to duplicate step1 code in each Db2 validataion script.

We read about setting each element value from list at test case level and then reconstructing the array back but we are hesitating to use that method due to (varying &) huge size of list elements (in thousands). Question is: Are there any clean ways to achieve this?

Thanks!

答:
You can use context

That's real working Groovy Script steps.

step1:

```<code>def array = ['Kyiv', 'Boryspil', 'Kharkiv', "L'Viv", "Odesa"]
context.setProperty('cities', array)
log.info( 'script1: '+array )
</code>```

step2:

```<code>def array = context.getProperty('cities')
log.info( 'script2: '+array )
assert array.size()>0
</code>```

Note:

If you run just one step, then there will be absolutely
  independent context.

But if you run the whole testcase then there will be context shared
  for the whole testcase.

You can use Run from here context menu in your test case window to run from exact step.

Body:
You can use context

That's real working Groovy Script steps.

step1:

def array = ['Kyiv', 'Boryspil', 'Kharkiv', "L'Viv", "Odesa"]
context.setProperty('cities', array)
log.info( 'script1: '+array )

step2:

def array = context.getProperty('cities')
log.info( 'script2: '+array )
assert array.size()>0

Note:

If you run just one step, then there will be absolutely
  independent context.

But if you run the whole testcase then there will be context shared
  for the whole testcase.

You can use Run from here context menu in your test case window to run from exact step.


问:
How to register root logins in phpmyadmin
My IT teacher asked me to help him with maintaining school site's remote server, and he wanted me to write a script to register who (ip addr) and when, logged in by root account, because he suspected that someone undesirable logs into the server. And there I've spotted the problem, generally site stands on phpmyadmin, I am pythonist and meant that I've never used phpmyadmin to manage websites. I would not take this task but I thought about SO society.
Referring to foregoing issue, have you any idea how I can do it? Thanks in advance.</p>

答:
Simplest solution is
a) Change the root password.
b) Create a new set of users.
c) Just track who does what and identify the undesirable.
d) Block the user after it is done.

Ofcourse, if you still want to track ipaddress of root users, here is, the option.This query works for active logins only.
Use this query to track every login and write a db trigger to store the host in a file or another table.

```<code>select host from information_schema.processlist;
</code>```

Hope this helps.

Body:
Simplest solution is
a) Change the root password.
b) Create a new set of users.
c) Just track who does what and identify the undesirable.
d) Block the user after it is done.

Ofcourse, if you still want to track ipaddress of root users, here is, the option.This query works for active logins only.
Use this query to track every login and write a db trigger to store the host in a file or another table.

select host from information_schema.processlist;

Hope this helps.


问:
How can I parse a selected table from webpage with Python BeautifulSoup
I wish to parse the results table from a local sport event (the page basically just contain a table), but when I try with the script below I just get the "menu", not the actual result list. What am I missing? </p>

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd

site = "https://rittresultater.no/nb/sb_tid/923?pv2=11027&pv1=U"
html = urlopen(site)
soup = BeautifulSoup(html, "lxml") #BeautifulSoup(urlopen(html, "lxml"))

table = soup.select("table")
df = pd.read_html(str(table))[0]
print.df
</code>```

答:
This is happening because there are two
s on that page. You can either query on the class name of the table you want (in this case .table-condensed) using the class_ parameter of the find() function, or you can just grab the second table in the list of all tables using the find_all() function.

Solution 1:

```<code>table = soup.find('table', class_='table-condensed')
print(table)
</code>```

Solution 2:

```<code>tables = soup.find_all('table')
print(tables[1])
</code>```

Body:
I wish to parse the results table from a local sport event (the page basically just contain a table), but when I try with the script below I just get the "menu", not the actual result list. What am I missing?

from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd

site = "https://rittresultater.no/nb/sb_tid/923?pv2=11027&pv1=U"
html = urlopen(site)
soup = BeautifulSoup(html, "lxml") #BeautifulSoup(urlopen(html, "lxml"))

table = soup.select("table")
df = pd.read_html(str(table))[0]
print.df

Body:
This is happening because there are two <table>s on that page. You can either query on the class name of the table you want (in this case .table-condensed) using the class_ parameter of the find() function, or you can just grab the second table in the list of all tables using the find_all() function.

Solution 1:

table = soup.find('table', class_='table-condensed')
print(table)

Solution 2:

tables = soup.find_all('table')
print(tables[1])


问:
How to pass edit an object that is part of the state and return that edited object back?
I have one obj like so:

```<code>Object{}
</code>```

This object has other objects inside of it, but are marked by keys, like so:

```<code>Object{1: Object, 2: Object, 3: Object}
</code>```

I want to be able to select one of those objects or edit by having only the value of the key. So lets say object 1 is an object that has

```<code>1: Object {
   title: "yay Im a title",
   description: "yay Im a desc",
   quantity: 1
   }
</code>```

I want to be able to get back a value like 1 and be able to take that certain object with the key of 1 out and update the quantity by 1 each time the function or whatever is called. If this doesn't make since please let me know.

This is with a project I am working with in react/redux.

I will post each relevant code:

action:

```<code> export function updateCart(_id, unit) {
  return {
    type: "UPDATE_CART",
    _id: _id,
    unit: unit
  }
}
</code>```

reducer:

```<code>case "UPDATE_CART":
    let foundBook = _.get(state, action._id);
    //Stuck here, want to update quantity by one and return the item
    break;
</code>```

component in which is calling action:

```<code>import React , { Component } from 'react';
import {connect} from 'react-redux';
import {addToCart, updateCart} from '../../actions/cartActions';

class BookItem extends Component {

  handleCart() {
    const book = {
      _id: this.props._id,
      title: this.props.title,
      description: this.props.description,
      price: this.props.price,
      quantity: 1
    }
    if(Object.keys(this.props.cart).length > 0) {
      let _id = this.props._id;

      let cartIndex = _id in this.props.cart;
      if(!cartIndex) {
        this.props.addToCart(book);
      } else {
        this.props.updateCart(_id, 1);
      }

    } else {
      this.props.addToCart(book);
    }
  }

  render() {
    return (
      <div className="well">
        <div className="row">
          <div className="col-xs-12">
            <h6>{this.props.title}</h6>
            <p>{this.props.description}</p>
            <h6>{this.props.price}</h6>
            <button onClick={this.handleCart.bind(this)} className="btn btn-primary">Buy now</button>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
 return {
   cart: state.cart
 }
}

export default connect(mapStateToProps, {addToCart, updateCart})(BookItem);
</code>```

Hopefully this didn't make this to confusing now, but as request I posted what I am working on to hopefully help.

答:
A very basic approach might be to create a function that will take an object, key, and optional function as parameters.  If a function is provided as the third parameter it would be evaluated against the child object with the given key, if located.  The child object, if located, is returned.

The use of hasOwnProperty allows location of child objects that belong to the parent object alone, and not inherited from the prototype.

```<code>function extract(obj, key,fn) {
    if (obj === null || typeof obj !== 'object' ||
        key === null || !obj.hasOwnProperty(key) || typeof obj[key] !== 'object' ||
        obj[key] === null)
        return null;

    if (typeof fn === 'function' && fn !== null)
        fn(obj[key]);

    return obj[key];
}
</code>```

Body:
I have one obj like so:

Object{}

This object has other objects inside of it, but are marked by keys, like so:

Object{1: Object, 2: Object, 3: Object}

I want to be able to select one of those objects or edit by having only the value of the key. So lets say object 1 is an object that has

1: Object {
   title: "yay Im a title",
   description: "yay Im a desc",
   quantity: 1
   }

I want to be able to get back a value like 1 and be able to take that certain object with the key of 1 out and update the quantity by 1 each time the function or whatever is called. If this doesn't make since please let me know.

This is with a project I am working with in react/redux.

I will post each relevant code:

action:

 export function updateCart(_id, unit) {
  return {
    type: "UPDATE_CART",
    _id: _id,
    unit: unit
  }
}

reducer:

case "UPDATE_CART":
    let foundBook = _.get(state, action._id);
    //Stuck here, want to update quantity by one and return the item
    break;

component in which is calling action:

import React , { Component } from 'react';
import {connect} from 'react-redux';
import {addToCart, updateCart} from '../../actions/cartActions';

class BookItem extends Component {

  handleCart() {
    const book = {
      _id: this.props._id,
      title: this.props.title,
      description: this.props.description,
      price: this.props.price,
      quantity: 1
    }
    if(Object.keys(this.props.cart).length > 0) {
      let _id = this.props._id;

      let cartIndex = _id in this.props.cart;
      if(!cartIndex) {
        this.props.addToCart(book);
      } else {
        this.props.updateCart(_id, 1);
      }

    } else {
      this.props.addToCart(book);
    }
  }

  render() {
    return (

{this.props.title}

{this.props.description}

{this.props.price}

            <button onClick={this.handleCart.bind(this)} className="btn btn-primary">Buy now</button>

    );
  }
}

function mapStateToProps(state) {
 return {
   cart: state.cart
 }
}

export default connect(mapStateToProps, {addToCart, updateCart})(BookItem);

Hopefully this didn't make this to confusing now, but as request I posted what I am working on to hopefully help.

Body:
A very basic approach might be to create a function that will take an object, key, and optional function as parameters.  If a function is provided as the third parameter it would be evaluated against the child object with the given key, if located.  The child object, if located, is returned.

The use of hasOwnProperty allows location of child objects that belong to the parent object alone, and not inherited from the prototype.

function extract(obj, key,fn) {
    if (obj === null || typeof obj !== 'object' ||
        key === null || !obj.hasOwnProperty(key) || typeof obj[key] !== 'object' ||
        obj[key] === null)
        return null;

    if (typeof fn === 'function' && fn !== null)
        fn(obj[key]);

    return obj[key];
}


问:
How to use hex color value in SSRS
When I set custom color to some form in Expressions window, the formula looks like
#117be0
or
="#117be0"

So, the question is, how to get string color hex value from dataset that contains the same value?
Something like this
=First(Fields!my_color.Value, "color_dataset")

答:
Well, you kind of answered your own question. Yes, FIRST() will return the first value in the colors dataset. To make this more meaningful, you are going to want to used the LOOKUP function.

LOOKUP(Fields!Local_Dataset_Value.Value, Fields!Color_Dataset_Value.Value, Fields!my_color.Value, "color_dataset")

Lookup will check the value of the Local_Dataset_Value field in your current table dataset, and find a match for that value in the "color_dataset" dataset's Color_Dataset_Value field. When it finds a match, then your color will return.

To explain further, given datasets:

Dataset1

Name | Age | Etc

........................

Joe  |  30 | Whatever

and

color_dataset

Color_Name | my_color

.....................

Joe  | Blue

then:

LOOKUP(Fields!Name.Value, Fields!Color_Name.Value, Fields!my_color.Value, "color_dataset")

Would return:

"Blue"

Title: How to use hex color value in SSRS


问:
Using jQuery to limit the number of list elements
I have a list element containing a number of between 20-30 events. I only want to show 5 of those, and have a «More» link I can click to watch the the next five. It doesn't matter if the five next events are appended.

Can't find a jQuery script that actually does this, or am I just blind? I don't want to use carousel plugins or anything like that.

答:
I wrote a hideMaxListItems plugin that may be what you were looking for. You can set the maximum number of list items, animation speed for the slide animation, and expand/collapse button HTML. The slide animation is done sequentially per list item, to give a smooth animation.

http://www.joshuawinn.com/maximum-list-items-jquery-hide-after-x-number-bullets/


问:
find the value not present in the column earlier
I am looking to find the latest scanids which doesn't have an errorid present from the previous scan.

```<code>scanid  | errorid | date                |state
--------|---------|---------------------|-----
   1    |    1    | 2016-01-01 00:00:00 | 9
   1    |    2    | 2016-01-01 00:00:00 | 9
   2    |    1    | 2016-01-02 00:00:00 | 9
</code>```

For the example above, I want to display below row as result:

```<code>scanid  | errorid | date                |state
--------|---------|---------------------|-----
   2    |    2    | 2016-01-02 00:00:00 | 10
</code>```

So, errorid 2 is not repeated with scanid 2, also I need to change the state of this row to 10 for the errorid 2 which is not part of the latest scan.

I have tried using NOT IN and EXISTS but not getting expected record.

I am using PostgreSQL as my database.

答:
To find the highest and second highest scan IDs rank them with DENSE_RANK. Then use a NOT EXISTS clause to get the last scan records that have no match in the previous scan.

```<code>with ranked as
(
  select
    scanid, errorid, date, state, dense_rank() over(order by scanid desc) as rnk
  from scans
)
select scanid, errorid, date, state + 1
from ranked lastscan
where rnk = 1
and not exists
(
  select *
  from ranked prevscan
  where prevscan.rnk = 2
  and prevscan.errorid = lastscan.errorid
);
</code>```

Body:
I am looking to find the latest scanids which doesn't have an errorid present from the previous scan.

scanid  | errorid | date                |state
--------|---------|---------------------|-----
   1    |    1    | 2016-01-01 00:00:00 | 9
   1    |    2    | 2016-01-01 00:00:00 | 9
   2    |    1    | 2016-01-02 00:00:00 | 9

For the example above, I want to display below row as result:

scanid  | errorid | date                |state
--------|---------|---------------------|-----
   2    |    2    | 2016-01-02 00:00:00 | 10

So, errorid 2 is not repeated with scanid 2, also I need to change the state of this row to 10 for the errorid 2 which is not part of the latest scan.

I have tried using NOT IN and EXISTS but not getting expected record.

I am using PostgreSQL as my database.

Body:
To find the highest and second highest scan IDs rank them with DENSE_RANK. Then use a NOT EXISTS clause to get the last scan records that have no match in the previous scan.

with ranked as
(
  select
    scanid, errorid, date, state, dense_rank() over(order by scanid desc) as rnk
  from scans
)
select scanid, errorid, date, state + 1
from ranked lastscan
where rnk = 1
and not exists
(
  select *
  from ranked prevscan
  where prevscan.rnk = 2
  and prevscan.errorid = lastscan.errorid
);


问:
How do I choose a node for Jenkins in Jenkinsfile using condition?
I am trying go get Jenkins to choose a node from a condition.

```<code>timestamps {
  def triggers=""
  if (isMasterBuild()) {
    node ('node.a'){
        runMaster(triggers)
    }
  } else {
    node ('node.b'){
        runBranch(triggers)
    }
  }
...
</code>```

But I just get an error.

```<code>15:13:14 Required context class hudson.FilePath is missing
15:13:14 Perhaps you forgot to surround the code with a step that provides this, such as: dockerNode,node
</code>```

What is the correct way to do this?

答: I figured it out.  It happened to be that I had an 'sh' command before the if statement and outside of a node block.  Once I moved that line into one of the node blocks, it started to work again.</p>

Body:
I am trying go get Jenkins to choose a node from a condition.

timestamps {
  def triggers=""
  if (isMasterBuild()) {
    node ('node.a'){
        runMaster(triggers)
    }
  } else {
    node ('node.b'){
        runBranch(triggers)
    }
  }
...

But I just get an error.

15:13:14 Required context class hudson.FilePath is missing
15:13:14 Perhaps you forgot to surround the code with a step that provides this, such as: dockerNode,node

What is the correct way to do this?


问:
set.seed publishing model in R
Do you include set.seed() as part of the final model when you are ready to distribute/expose your model to the real word? Do you only use set.seed() for validation during training and validation?

Once you decide on your method, parameters, etc., do you run the model without setting the seed and that is the model you launch? Or do you pick the seed that performed the best during validation?

Thanks!

答: I doubt different seeds give that variant results unless you have parameters that involve random sampling of features or observations. Still i believe you answered your own question. To reproduce the Exact result you would need to include the seed value as well with your final model. It is not of really great significance however, so you dont need to really worry about it too much.</p>

Title: set.seed publishing model in R