问:
How can I set up different footers for TableSections when using a Custom TableView Renderer
I am using a renderer to allow me to set a custom footer in my TableView. The renderer works but I would like to have the capability to set up different footers for the different table sections. For example one footer for table section 0 and another for table section 1, all the way up to table section 5.

Here's the XAML that I am using:

```<code>           <!-- <local:ExtFooterTableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">-->
                <TableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
                <TableSection Title="Cards1">
                    <ViewCell Height="50">
                        <Label Text="Hello1" />
                    </ViewCell>
                    <ViewCell Height="50">
                        <Label Text="Hello2" />
                    </ViewCell>
                </TableSection>
                <TableSection Title="Cards2">
                    <TextCell Height="50" Text="Hello"></TextCell>
                </TableSection>

                </TableSection>
        <!--    </local:ExtFooterTableView>-->
            </TableView>
</code>```

and here is the C# class and renderer:

```<code>public class ExtFooterTableView : TableView
{
    public ExtFooterTableView()
    {
    }
}
</code>```

and:

```<code>   using System;
using Japanese;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtFooterTableView), typeof(Japanese.iOS.ExtFooterTableViewRenderer))]
namespace Japanese.iOS
{
    public class ExtFooterTableViewRenderer : TableViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
                return;

            var tableView = Control as UITableView;
            var formsTableView = Element as TableView;
            tableView.WeakDelegate = new CustomFooterTableViewModelRenderer(formsTableView);
        }

        private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
        {
            public CustomFooterTableViewModelRenderer(TableView model) : base(model)
            {
            }

            public override UIView GetViewForFooter(UITableView tableView, nint section)
            {
                Debug.WriteLine("xx");
                if (section == 0)
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "abc",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
                else
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "def",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
            }

        }
    }
}
</code>```

The code works but I would like to find out how I can set up a different footer text for different sections in the XAML. Something like this:

From what I see it looks like the code is partly there TitleForFooter(tableView, section) but I am not sure how to use it and how I could set it up. Note that I am not really looking for a view model solution.  I would be happy to be simply able to specify the section footer text as part of the TableView XAML.

I'd appreciate if anyone could give me some advice on this.

答:
It is very simple. you need to add the bindable property for pass value from XAML to CustomRenderer in CustomControl like this:

Customer TableView

```<code>public class ExtFooterTableView : TableView
{
    public ExtFooterTableView()
    {
    }
}
</code>```

Xaml control code

```<code><local:ExtFooterTableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
</code>```

Renderer class

```<code>using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using yournamespace;
using System.ComponentModel;

[assembly: ExportRenderer(typeof(ExtFooterTableView), typeof(FooterTableViewRenderer))]
namespace yournamespace
{
    public class FooterTableViewRenderer : TableViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
        {
            base.OnElementChanged(e);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            var view = (ExtFooterTableView)Element;

            if (e.PropertyName == ExtFooterTableView.IntentProperty.PropertyName)
            {
                string intent = view.Intent;
                // Do your stuff for intent property
            }

            if (e.PropertyName == ExtFooterTableView.HasUnevenRowsProperty.PropertyName)
            {
                bool hasUnevenRows = view.HasUnevenRows;
                // Do yout stuff for HasUnevenRow
            }
        }

    }
}
</code>```

Body:
I am using a renderer to allow me to set a custom footer in my TableView. The renderer works but I would like to have the capability to set up different footers for the different table sections. For example one footer for table section 0 and another for table section 1, all the way up to table section 5.

Here's the XAML that I am using:

                <TableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">
                <TableSection Title="Cards1">
                    <ViewCell Height="50">

                    </ViewCell>
                    <ViewCell Height="50">

                    </ViewCell>
                </TableSection>
                <TableSection Title="Cards2">
                    <TextCell Height="50" Text="Hello"></TextCell>
                </TableSection>

                </TableSection>

            </TableView>

and here is the C# class and renderer:

public class ExtFooterTableView : TableView
{
    public ExtFooterTableView()
    {
    }
}

and:

   using System;
using Japanese;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtFooterTableView), typeof(Japanese.iOS.ExtFooterTableViewRenderer))]
namespace Japanese.iOS
{
    public class ExtFooterTableViewRenderer : TableViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
                return;

            var tableView = Control as UITableView;
            var formsTableView = Element as TableView;
            tableView.WeakDelegate = new CustomFooterTableViewModelRenderer(formsTableView);
        }

        private class CustomFooterTableViewModelRenderer : TableViewModelRenderer
        {
            public CustomFooterTableViewModelRenderer(TableView model) : base(model)
            {
            }

            public override UIView GetViewForFooter(UITableView tableView, nint section)
            {
                Debug.WriteLine("xx");
                if (section == 0)
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "abc",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
                else
                {
                    return new UILabel()
                    {
                        // Text = TitleForFooter(tableView, section), // or use some other text here
                        Text = "def",
                        TextAlignment = UITextAlignment.Left
                        // TextAlignment = NSTextAlignment.NSTextAlignmentJustified
                    };
                }
            }

        }
    }
}

The code works but I would like to find out how I can set up a different footer text for different sections in the XAML. Something like this:

From what I see it looks like the code is partly there TitleForFooter(tableView, section) but I am not sure how to use it and how I could set it up. Note that I am not really looking for a view model solution.  I would be happy to be simply able to specify the section footer text as part of the TableView XAML.

I'd appreciate if anyone could give me some advice on this.

Body:
It is very simple. you need to add the bindable property for pass value from XAML to CustomRenderer in CustomControl like this:

Customer TableView

public class ExtFooterTableView : TableView
{
    public ExtFooterTableView()
    {
    }
}

Xaml control code

<local:ExtFooterTableView x:Name="tableView" Intent="Settings" HasUnevenRows="True">

Renderer class

using System;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
using yournamespace;
using System.ComponentModel;

[assembly: ExportRenderer(typeof(ExtFooterTableView), typeof(FooterTableViewRenderer))]
namespace yournamespace
{
    public class FooterTableViewRenderer : TableViewRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<TableView> e)
        {
            base.OnElementChanged(e);
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            var view = (ExtFooterTableView)Element;

            if (e.PropertyName == ExtFooterTableView.IntentProperty.PropertyName)
            {
                string intent = view.Intent;
                // Do your stuff for intent property
            }

            if (e.PropertyName == ExtFooterTableView.HasUnevenRowsProperty.PropertyName)
            {
                bool hasUnevenRows = view.HasUnevenRows;
                // Do yout stuff for HasUnevenRow
            }
        }

    }
}


来源: stackexchange

问:
How to append textbox value to the nearest span?
I'm using jQuery datatables and want to apply calculation on it, it is hard to do so i want to append value of textbox to invisible span. How can i do this? with this following code it is only working on 1 textbox of same id i want to apply on all textbox of same id.

$('td').each(function() {
  $("input").keyup(function() {
    var txtvalue = $('#curr_sales').val();
    $("#curr").closest('span').text(txtvalue);
    console.log(txtvalue);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span id="curr"></span></td>
<td><input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span id="curr"></span></td>
<td><input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required><span id="curr"></span></td>
</tr></table></code>```

答:
I highly recommend you read Decoupling Your HTML, CSS, and JavaScript.

I would completely rewrite (example below).  Targeting Ids is problematic because you can only have a single html element with and id, which makes jQuery non-reusable.  Targeting span also makes the jQuery code fragile, because someone else comes along and changes the span to a div and jQuery stops working.

$(document).ready(function() {
  $(".js-populate-target").on('keyup change', function() {
    var txtvalue = $(this).val();
    var selector = $(this).data('populate-target');
    $(this).closest('.js-populate-container').find(selector).text(txtvalue);
    console.log(txtvalue);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <table>
    <tr>
      <td class="js-populate-container">
        <input type="number" size="5" name="curr_sales" placeholder="Current Sales" required class="curr_sales js-populate-target" data-populate-target=".js-populator">
        <span class="js-populator"></span>
      </td>
      <td class="js-populate-container">
        <input type="number" size="5" name="curr_sales" placeholder="Current Sales" required class="curr_sales js-populate-target" data-populate-target=".js-populator">
        <span class="js-populator"></span>
      </td>
      <td class="js-populate-container">
        <input type="number" size="5" name="curr_sales" placeholder="Current Sales" required class="curr_sales js-populate-target"  data-populate-target=".js-blah">
        <span class="js-blah"></span>
      </td>
    </tr>
  </table></code>```

By putting the target in a data field, you can now specific specifically which elements get targeted per item.

ContentLicense: CC BY-SA 3.0

Body:
I'm using jQuery datatables and want to apply calculation on it, it is hard to do so i want to append value of textbox to invisible span. How can i do this? with this following code it is only working on 1 textbox of same id i want to apply on all textbox of same id.

$('td').each(function() {
  $("input").keyup(function() {
    var txtvalue = $('#curr_sales').val();
    $("#curr").closest('span').text(txtvalue);
    console.log(txtvalue);
  });
});

<input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required>
<input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required>
<input type="number" id="curr_sales" size="5" name="curr_sales" placeholder="Current Sales" required>

Body:
I highly recommend you read Decoupling Your HTML, CSS, and JavaScript.

I would completely rewrite (example below).  Targeting Ids is problematic because you can only have a single html element with and id, which makes jQuery non-reusable.  Targeting span also makes the jQuery code fragile, because someone else comes along and changes the span to a div and jQuery stops working.

$(document).ready(function() {
  $(".js-populate-target").on('keyup change', function() {
    var txtvalue = $(this).val();
    var selector = $(this).data('populate-target');
    $(this).closest('.js-populate-container').find(selector).text(txtvalue);
    console.log(txtvalue);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <table>
    <tr>
      <td class="js-populate-container">
        <input type="number" size="5" name="curr_sales" placeholder="Current Sales" required class="curr_sales js-populate-target" data-populate-target=".js-populator">
        <span class="js-populator"></span>
      </td>
      <td class="js-populate-container">
        <input type="number" size="5" name="curr_sales" placeholder="Current Sales" required class="curr_sales js-populate-target" data-populate-target=".js-populator">
        <span class="js-populator"></span>
      </td>
      <td class="js-populate-container">
        <input type="number" size="5" name="curr_sales" placeholder="Current Sales" required class="curr_sales js-populate-target"  data-populate-target=".js-blah">
        <span class="js-blah"></span>
      </td>
    </tr>
  </table>

By putting the target in a data field, you can now specific specifically which elements get targeted per item.


问:
Modify HTML tags in a *ngFor loop based on a variable in Angular 4
I'm working in Angular 4 and I would like to modify the html tags based on a variable in my *ngFor loop. This is the code that I'm trying to build:</p>

```<code><mat-card-content *ngFor="let question of questionGroup.profileQuestion class="mat-elevation-z2">

  <!-- I would like to do something like this in a *ngIF and isQASideBySide
       is a boolean value -->
  <div class="container" *ngIf="questions.isQASideBySide THEN fxLayout.xs='row' ELSE fxLayout.xs='column'" fxLayoutGap.xs="0" fxLayoutGap="10px">

      <div fxFlex="50%" fxFlexOrder="1" style="padding:10px">
         <p>
           {{ question.profileQuestionText }}
         </p>
      </div>

      <div fxFlex="50%" fxFlexOrder="1" style="padding:10px" >
         <!-- INPUT CONTROLS ....-->
      </div>
  </div>
</mat-card-content>
</code>```

答:
MODIFIED CODE

It worked here is the OP's final code (moved from the question itself):

```<code><mat-card-content *ngFor="let question of questionGroup.profileQuestion class="mat-elevation-z2">
  <div class="container" [fxLayout]="question.isQASideBySide ? 'row' : 'column'" fxLayoutGap.xs="0" fxLayoutGap="10px">

      <div [fxFlex]="question.isQASideBySide ? '50%' : '100%'" fxFlexOrder="1" style="padding:10px">
         <p>
           {{ question.profileQuestionText }}
         </p>
      </div>

      <div fxFlex="50%" fxFlexOrder="1" style="padding:10px" >
         <!-- INPUT CONTROLS ....-->
      </div>
  </div>
</mat-card-content>
</code>```

Body:
I'm working in Angular 4 and I would like to modify the html tags based on a variable in my *ngFor loop. This is the code that I'm trying to build:

<mat-card-content *ngFor="let question of questionGroup.profileQuestion class="mat-elevation-z2">

           {{ question.profileQuestionText }}

</mat-card-content>

Body:
MODIFIED CODE

It worked here is the OP's final code (moved from the question itself):

<mat-card-content *ngFor="let question of questionGroup.profileQuestion class="mat-elevation-z2">
  <div class="container" [fxLayout]="question.isQASideBySide ? 'row' : 'column'" fxLayoutGap.xs="0" fxLayoutGap="10px">

      <div [fxFlex]="question.isQASideBySide ? '50%' : '100%'" fxFlexOrder="1" style="padding:10px">
         <p>
           {{ question.profileQuestionText }}
         </p>
      </div>

      <div fxFlex="50%" fxFlexOrder="1" style="padding:10px" >
         <!-- INPUT CONTROLS ....-->
      </div>
  </div>
</mat-card-content>


问:
SQL Query: Select most recent entry for each distinct field value?
i have this table POSITION:

```<code>CREATE TABLE `position` (
  `idposition` bigint(20) NOT NULL AUTO_INCREMENT,
  `latitude` varchar(45) DEFAULT NULL,
  `longitude` varchar(45) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `fk_email` varchar(100) DEFAULT NULL,
</code>```

with this population:

```<code>idposition  latitude    longitude   timestamp              fk_email
        1   39.49333    -0.33667    2010-12-10 17:15:39     david@test.es
         4  39.47333    -0.36167    2010-12-11 09:58:47     ronald@test.es
         5  39.50333    -0.34267    2010-12-10 21:11:10     david@test.es
        10  39.44333    -0.41667    2010-12-12 18:17:26     fanny@test.es
        11  39.45199    -0.31967    2010-12-12 21:01:18     victor@test.es
        12  39.52133    -0.36167    2010-12-12 17:43:11     carlos@test.es
        13  39.43199    -0.31967    2010-12-14 15:45:25     victor@test.es
        14  39.41199    -0.34567    2010-12-14 20:46:09     victor@test.es
        15  39.43433    -0.41667    2010-12-14 17:29:39     maria@test.es
        16  39.44133    -0.42667    2010-12-12 19:17:33     maria@test.es
        17  39.50333    -0.35667    2010-12-13 16:36:22     angel@test.es
        196     39.46454    -0.38978    0000-00-00 00:00:00     fanny@test.es
        271     33.63883    -0.45024    2010-12-17 11:36:45     fanny@test.es
        273     39.46680    -0.39452    2010-12-20 00:00:00     fanny@test.es
        441     39.44133    -0.41467    2010-12-15 17:45:13     carlos@test.es
        5326    39.47316    -0.38351    2011-01-18 18:09:56     pablo@upv.es
</code>```

ok, i want to make  SQL Query, that returns to me THE LAST (NEWEST) POSITION OF EACH FK_EMAIL, i mean, for each fk_email, the position with the last (newest) timestamp, only one position (te last) for each email.

it is possible to do it? can someone help me with the query? is too munch hard for me

答:
```<code>SELECT
      p.idposition,
      p.atitude,
      p.longitude,
      p.timestamp,
      p.fk_email

FROM
      position p
      INNER JOIN (select
              fk_email,
              max(timestamp) timestamp
                 FROM    POSITION
                 GROUP BY  fk_email) lastPos
      ON p.fk_email = lastPos.fk_email and p.timeStamp = lastpos.timestamp
</code>```

The one potential problem with this is that if the same timestamp is recorded for the same fk_email you will get both results. If there was a unique constraint on the combination of these two columns you won't have to worry about that though.

update
From the comments

but one question more, the only
  possibility to be returned two rows
  per email is to have the seame
  timestamp in two rows for the same
  email? how can i evade that

As I said before adding a unique constraint on the two fields so it doesn't happen is the easiest. But lets assume you can't do that and lets also assume that the timestamp is the same. you'll need to pick an arbitrary row as "the correct one".

Assuming that IdPosition is unique you could do this

```<code>SELECT
     p.idposition,
      p.atitude,
      p.longitude,
      p.timestamp,
      p.fk_email
  FROM
   position p
    INNER JOIN (SELECT
                    max(p.idposition) idposition
              FROM
                    position p
                    INNER JOIN (select
                            fk_email,
                            max(timestamp) timestamp
                               FROM    POSITION
                               GROUP BY  fk_email) lastPos
                    ON p.fk_email = lastPos.fk_email and p.timeStamp = lastpos.timestamp
              GROUP BY
                     fk_email) lastpos
              on p.idposition = lastpos.idposition
</code>```

Body:
i have this table POSITION:

CREATE TABLE `position` (
  `idposition` bigint(20) NOT NULL AUTO_INCREMENT,
  `latitude` varchar(45) DEFAULT NULL,
  `longitude` varchar(45) DEFAULT NULL,
  `timestamp` datetime DEFAULT NULL,
  `fk_email` varchar(100) DEFAULT NULL,

with this population:

idposition  latitude    longitude   timestamp              fk_email
        1   39.49333    -0.33667    2010-12-10 17:15:39     david@test.es
         4  39.47333    -0.36167    2010-12-11 09:58:47     ronald@test.es
         5  39.50333    -0.34267    2010-12-10 21:11:10     david@test.es
        10  39.44333    -0.41667    2010-12-12 18:17:26     fanny@test.es
        11  39.45199    -0.31967    2010-12-12 21:01:18     victor@test.es
        12  39.52133    -0.36167    2010-12-12 17:43:11     carlos@test.es
        13  39.43199    -0.31967    2010-12-14 15:45:25     victor@test.es
        14  39.41199    -0.34567    2010-12-14 20:46:09     victor@test.es
        15  39.43433    -0.41667    2010-12-14 17:29:39     maria@test.es
        16  39.44133    -0.42667    2010-12-12 19:17:33     maria@test.es
        17  39.50333    -0.35667    2010-12-13 16:36:22     angel@test.es
        196     39.46454    -0.38978    0000-00-00 00:00:00     fanny@test.es
        271     33.63883    -0.45024    2010-12-17 11:36:45     fanny@test.es
        273     39.46680    -0.39452    2010-12-20 00:00:00     fanny@test.es
        441     39.44133    -0.41467    2010-12-15 17:45:13     carlos@test.es
        5326    39.47316    -0.38351    2011-01-18 18:09:56     pablo@upv.es

ok, i want to make  SQL Query, that returns to me THE LAST (NEWEST) POSITION OF EACH FK_EMAIL, i mean, for each fk_email, the position with the last (newest) timestamp, only one position (te last) for each email.

it is possible to do it? can someone help me with the query? is too munch hard for me

Body:
SELECT
      p.idposition,
      p.atitude,
      p.longitude,
      p.timestamp,
      p.fk_email

FROM
      position p
      INNER JOIN (select
              fk_email,
              max(timestamp) timestamp
                 FROM    POSITION
                 GROUP BY  fk_email) lastPos
      ON p.fk_email = lastPos.fk_email and p.timeStamp = lastpos.timestamp

The one potential problem with this is that if the same timestamp is recorded for the same fk_email you will get both results. If there was a unique constraint on the combination of these two columns you won't have to worry about that though.

update
From the comments

but one question more, the only
  possibility to be returned two rows
  per email is to have the seame
  timestamp in two rows for the same
  email? how can i evade that

As I said before adding a unique constraint on the two fields so it doesn't happen is the easiest. But lets assume you can't do that and lets also assume that the timestamp is the same. you'll need to pick an arbitrary row as "the correct one".

Assuming that IdPosition is unique you could do this

SELECT
     p.idposition,
      p.atitude,
      p.longitude,
      p.timestamp,
      p.fk_email
  FROM
   position p
    INNER JOIN (SELECT
                    max(p.idposition) idposition
              FROM
                    position p
                    INNER JOIN (select
                            fk_email,
                            max(timestamp) timestamp
                               FROM    POSITION
                               GROUP BY  fk_email) lastPos
                    ON p.fk_email = lastPos.fk_email and p.timeStamp = lastpos.timestamp
              GROUP BY
                     fk_email) lastpos
              on p.idposition = lastpos.idposition

ContentLicense: CC BY-SA 2.5


问:
How to create a MS Dynamics CRM app
I would like to create a Visual Studio project to my Dynamics site.
I'm using .NET and Javascript. My target is create a component (html + javascript/angular/...) and add this component into my dynamics page layout (or somewhere in dynamic site to see my UI).

My project has Back-end as well which using web API and get Dynamics CRM metadata by Client Object Model and send result to the component.
I finished my backend API and client HTML component. But I don't know how to install my app and show my component into my Dynamic site.

Could anyone share me some tutorials or demos related this?

答:
To get you started... the general way to add things into CRM is via unmanaged or managed Solutions: https://msdn.microsoft.com/en-us/library/gg334576.aspx.

The solution that contains everything is called the Default Solution. You can get to it by going to Settings > Customizations > Customize the System.

You can put your JavaScript code into one or more web resources. Then add them to a form and register them on the OnLoad, OnSave, or individual field OnChange events.

C# code goes in as a Plugin Assembly or a Custom Workflow Assembly. To register those, use the Plugin Registration Tool, which is available in the SDK.
Once your plugins are registered, you can add them to a solution and port them to other systems.

Title: How to create a MS Dynamics CRM app


问:
How To Parse JSON Object Array with Jackson Into DTO In SpringBoot
I am currently building an application that uses RestTemplate to structure API requests to the Alpha Vantage API. Here is a sample response excluding unnecessary metadata:

```<code>{
  "Time Series (Daily)": {
    "2017-11-10": {
      "1. open": "83.7900",
      "2. high": "84.1000",
      "3. low": "83.2300",
      "4. close": "83.8700",
      "5. volume": "19340435"
    },
    "2017-11-09": {
      "1. open": "84.1100",
      "2. high": "84.2700",
      "3. low": "82.9000",
      "4. close": "84.0900",
      "5. volume": "20924172"
    },
    "2017-11-08": {
      "1. open": "84.1400",
      "2. high": "84.6100",
      "3. low": "83.8300",
      "4. close": "84.5600",
      "5. volume": "18034170"
    },
    "2017-11-07": {
      "1. open": "84.7700",
      "2. high": "84.9000",
      "3. low": "83.9300",
      "4. close": "84.2700",
      "5. volume": "17152583"
    },
    "2017-11-06": {
      "1. open": "84.2000",
      "2. high": "84.7000",
      "3. low": "84.0800",
      "4. close": "84.4700",
      "5. volume": "19039847"
    },
    "2017-11-03": {
      "1. open": "84.0800",
      "2. high": "84.5400",
      "3. low": "83.4000",
      "4. close": "84.1400",
      "5. volume": "17569120"
    }
  }
}
</code>```

I am building out my Data Transfer Object layer and it consists as such:

Top Layer:

```<code>public class Stock extends Dto{

    @JsonProperty("Time Series (Daily)")
    private TimeSeries timeSeries;

    public TimeSeries getTimeSeries() {
        return timeSeries;
    }

    public void setTimeSeries(TimeSeries timeSeries) {
        this.timeSeries = timeSeries;
    }
}
</code>```

Middle Layer:

```<code>public class TimeSeries extends Dto{

    private List<Day> days;

    public List<Day> getDays() {
        return days;
    }

    public void setDays(List<Day> days) {
        this.days = days;
    }
}
</code>```

Final Layer (where data pans out):

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
public class Day extends Dto{

    @JsonProperty("1. open")
    private double open;

    @JsonProperty("2. high")
    private double high;

    @JsonProperty("3. low")
    private double low;

    @JsonProperty("4. close")
    private double close;

    @JsonProperty("5. volume")
    private double volume;

    public double getOpen() {
        return open;
    }

    public void setOpen(double open) {
        this.open = open;
    }

    public double getHigh() {
        return high;
    }

    public void setHigh(double high) {
        this.high = high;
    }

    public double getLow() {
        return low;
    }

    public void setLow(double low) {
        this.low = low;
    }

    public double getClose() {
        return close;
    }

    public void setClose(double close) {
        this.close = close;
    }

    public double getVolume() {
        return volume;
    }

    public void setVolume(double volume) {
        this.volume = volume;
    }
}
</code>```

What Happens When I Run My Application:
When I run the application the top layer (Stock.java) gets populated with a Time Series object but then the next layer (TimeSeries.java) does not contain an array of (Day.java) objects as I expect and it is null. I have tried:

```<code>@JSONProperty("2017-11-10")
private Day day;
</code>```

And that does work and bridges the gap in the middle layer to the final layer and data comes through fine...but that's not what I'm after.

What I Expected To Happen/Want To Happen:
I am trying to get an array of all of the dates (in TimeSeries.java) in the List of days but it won't work and I believe it is because the JSON response doesn't give them as an array of JavaScript objects but rather as an actual key and pair so I can't just make a list of them but have to directly drill down to the final object...which isn't what I want.

Threads I Have Read Regarding This Topic

Parse JSON array with resttemplate

Parsing JSON with Jackson

Parsing JSON with Jackson Java

Unable to consume JSON array using Spring RestTemplate

How to use query parameter represented as JSON with Spring RestTemplate?

How to deserialize an array of objects using Jackson or any other api?

desrialize JSON with child array using Jackson annotations?

Jackson Mapping List of String or simple String

Where should I get the object to represent what is passed (Json) in a RESTful api

If anyone knows how I can get that middle step to work and actually store the objects in the key "Time Series (Daily)" as Days then access their values that'd be awesome.

NOTE: Also if you are going to down-vote this please comment why you have done so below. I have researched this for the past 5 hours so I believe I've done due diligence to be able to ask here and I've been as thorough as possible...c'mon.

答:
You don't have Json array in your json. You actually have json object with multiple fields, so your java data structure should be represented with Map and not List. If your want to keep current classes structure, then you should understand, that you loose the date part of timeseries. And i don't think you want this.

Option 1. Use HashMap<String, Day> timeSeries

```<code>public class Stock {

    @JsonProperty("Time Series (Daily)")
    private HashMap<String, Day> timeSeries;

    public HashMap<String, Day> getTimeSeries() {
        return timeSeries;
    }

    public void setTimeSeries(HashMap<String, Day> timeSeries) {
        this.timeSeries = timeSeries;
    }
}
</code>```

Option 2. Change TimeSeries code

```<code>public class TimeSeries {

    // TreeMap because it preserves sorting order
    @JsonIgnore
    private Map<String, Day> days = new TreeMap<>();

    @JsonAnySetter
    public void setDays(String time, Day value){
        days.put(time,value);
    }

    @JsonAnyGetter
    public Map<String, Day> getData() {
        return days;
    }

    // add getDays() if you need only values
    // and if you need list, can use new ArrayList(days.values())
    @JsonIgnore
    public Collection<Day> getDays(){
        return days.values();
    }
}
</code>```

Body:
I am currently building an application that uses RestTemplate to structure API requests to the Alpha Vantage API. Here is a sample response excluding unnecessary metadata:

{
  "Time Series (Daily)": {
    "2017-11-10": {
      "1. open": "83.7900",
      "2. high": "84.1000",
      "3. low": "83.2300",
      "4. close": "83.8700",
      "5. volume": "19340435"
    },
    "2017-11-09": {
      "1. open": "84.1100",
      "2. high": "84.2700",
      "3. low": "82.9000",
      "4. close": "84.0900",
      "5. volume": "20924172"
    },
    "2017-11-08": {
      "1. open": "84.1400",
      "2. high": "84.6100",
      "3. low": "83.8300",
      "4. close": "84.5600",
      "5. volume": "18034170"
    },
    "2017-11-07": {
      "1. open": "84.7700",
      "2. high": "84.9000",
      "3. low": "83.9300",
      "4. close": "84.2700",
      "5. volume": "17152583"
    },
    "2017-11-06": {
      "1. open": "84.2000",
      "2. high": "84.7000",
      "3. low": "84.0800",
      "4. close": "84.4700",
      "5. volume": "19039847"
    },
    "2017-11-03": {
      "1. open": "84.0800",
      "2. high": "84.5400",
      "3. low": "83.4000",
      "4. close": "84.1400",
      "5. volume": "17569120"
    }
  }
}

I am building out my Data Transfer Object layer and it consists as such:

Top Layer:

public class Stock extends Dto{

    @JsonProperty("Time Series (Daily)")
    private TimeSeries timeSeries;

    public TimeSeries getTimeSeries() {
        return timeSeries;
    }

    public void setTimeSeries(TimeSeries timeSeries) {
        this.timeSeries = timeSeries;
    }
}

Middle Layer:

public class TimeSeries extends Dto{

    private List<Day> days;

    public List<Day> getDays() {
        return days;
    }

    public void setDays(List<Day> days) {
        this.days = days;
    }
}

Final Layer (where data pans out):

@JsonIgnoreProperties(ignoreUnknown = true)
public class Day extends Dto{

    @JsonProperty("1. open")
    private double open;

    @JsonProperty("2. high")
    private double high;

    @JsonProperty("3. low")
    private double low;

    @JsonProperty("4. close")
    private double close;

    @JsonProperty("5. volume")
    private double volume;

    public double getOpen() {
        return open;
    }

    public void setOpen(double open) {
        this.open = open;
    }

    public double getHigh() {
        return high;
    }

    public void setHigh(double high) {
        this.high = high;
    }

    public double getLow() {
        return low;
    }

    public void setLow(double low) {
        this.low = low;
    }

    public double getClose() {
        return close;
    }

    public void setClose(double close) {
        this.close = close;
    }

    public double getVolume() {
        return volume;
    }

    public void setVolume(double volume) {
        this.volume = volume;
    }
}

What Happens When I Run My Application:
When I run the application the top layer (Stock.java) gets populated with a Time Series object but then the next layer (TimeSeries.java) does not contain an array of (Day.java) objects as I expect and it is null. I have tried:

@JSONProperty("2017-11-10")
private Day day;

And that does work and bridges the gap in the middle layer to the final layer and data comes through fine...but that's not what I'm after.

What I Expected To Happen/Want To Happen:
I am trying to get an array of all of the dates (in TimeSeries.java) in the List of days but it won't work and I believe it is because the JSON response doesn't give them as an array of JavaScript objects but rather as an actual key and pair so I can't just make a list of them but have to directly drill down to the final object...which isn't what I want.

Threads I Have Read Regarding This Topic

Parse JSON array with resttemplate

Parsing JSON with Jackson

Parsing JSON with Jackson Java

Unable to consume JSON array using Spring RestTemplate

How to use query parameter represented as JSON with Spring RestTemplate?

How to deserialize an array of objects using Jackson or any other api?

desrialize JSON with child array using Jackson annotations?

Jackson Mapping List of String or simple String

Where should I get the object to represent what is passed (Json) in a RESTful api

If anyone knows how I can get that middle step to work and actually store the objects in the key "Time Series (Daily)" as Days then access their values that'd be awesome.

NOTE: Also if you are going to down-vote this please comment why you have done so below. I have researched this for the past 5 hours so I believe I've done due diligence to be able to ask here and I've been as thorough as possible...c'mon.

Body:
You don't have Json array in your json. You actually have json object with multiple fields, so your java data structure should be represented with Map and not List. If your want to keep current classes structure, then you should understand, that you loose the date part of timeseries. And i don't think you want this.

Option 1. Use HashMap<String, Day> timeSeries

public class Stock {

    @JsonProperty("Time Series (Daily)")
    private HashMap<String, Day> timeSeries;

    public HashMap<String, Day> getTimeSeries() {
        return timeSeries;
    }

    public void setTimeSeries(HashMap<String, Day> timeSeries) {
        this.timeSeries = timeSeries;
    }
}

Option 2. Change TimeSeries code

public class TimeSeries {

    // TreeMap because it preserves sorting order
    @JsonIgnore
    private Map<String, Day> days = new TreeMap<>();

    @JsonAnySetter
    public void setDays(String time, Day value){
        days.put(time,value);
    }

    @JsonAnyGetter
    public Map<String, Day> getData() {
        return days;
    }

    // add getDays() if you need only values
    // and if you need list, can use new ArrayList(days.values())
    @JsonIgnore
    public Collection<Day> getDays(){
        return days.values();
    }
}


问:
Create dense matrix from sparse matrix efficently (numpy/scipy but NO sklearn)
I have a sparse.txt that looks like this:

```<code># first column is label 0 or 1
# rest of the data is sparse data
# maximum value in the data is 4, so the future dense matrix will
# have 1+4 = 5 elements in a row
# file: sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 2:1 3:1 4:1
</code>```

The required dense.txt is this:

```<code># required file: dense.txt
1 1 1 1 0
0 1 0 0 1
1 0 1 1 1
</code>```

Without using scipy coo_matrix it did it in a simple way like this:

```<code>def create_dense(fsparse, fdense,fvocab):
    # number of lines in vocab
    lvocab = sum(1 for line in open(fvocab))

    # create dense file
    with open(fsparse) as fi, open(fdense,'w') as fo:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]

            row = [0]* (lvocab+1)
            row[0] = label

            # use listcomps
            row = [ 1 if i in indices else row[i] for i in range(len(row))]

            l = " ".join(map(str,row)) + "\n"
            fo.write(l)

            print('Writing dense matrix line: ', i+1)
</code>```

Question
How can we directly get label and data from sparse data without first creating dense matrix and using NUMPY /Scipy preferably??

Question:
How can we read the sparse data using numpy.fromregex ?

My attempt is:

```<code>def read_file(fsparse):
    regex = r'([0-1]\s)([0-9]):(1\s)*([0-9]:1)' + r'\s*\n'
    data = np.fromregex(fsparse,regex,dtype=str)

    print(data,file=open('dense.txt','w'))
</code>```

It did not work!

Related links:

Parsing colon separated sparse data with pandas and numpy

答:
Tweaking your code to create the dense array directly, rather via file:

```<code>fsparse = 'stack47266965.txt'

def create_dense(fsparse, fdense, lvocab):
    alist = []
    with open(fsparse) as fi:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]

            row = [0]* (lvocab+1)
            row[0] = label

            # use listcomps
            row = [ 1 if i in indices else row[i] for i in range(len(row))]
            alist.append(row)
    return alist

alist = create_dense(fsparse, fdense, 4)
print(alist)
import numpy as np
arr = np.array(alist)
from scipy import sparse
M = sparse.coo_matrix(arr)
print(M)
print(M.A)
</code>```

produces

```<code>0926:~/mypy$ python3 stack47266965.py
[[1, 1, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 1, 1]]
  (0, 0)    1
  (0, 1)    1
  (0, 2)    1
  (0, 3)    1
  (1, 1)    1
  (1, 4)    1
  (2, 0)    1
  (2, 2)    1
  (2, 3)    1
  (2, 4)    1
[[1 1 1 1 0]
 [0 1 0 0 1]
 [1 0 1 1 1]]
</code>```

If you want to skip the dense arr, you need to generate the equivalent of the M.row,M.col, and M.data attributes (order doesn't matter)

```<code>[0 0 0 0 1 1 2 2 2 2]
[0 1 2 3 1 4 0 2 3 4]
[1 1 1 1 1 1 1 1 1 1]
</code>```

I don't use regex much so I won't try to fix that.  I assume you want to convert

```<code> '1 1:1 2:1 3:1'
</code>```

into

```<code> ['1' '1' '2' '2' '1' '3' '1']
</code>```

But that just gets you to the words/label stage.

A direct to sparse:

```<code>def create_sparse(fsparse, lvocab):

    row, col, data = [],[],[]
    with open(fsparse) as fi:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            row.append(i); col.append(0); data.append(label)

            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]
            for j in indices:   # quick-n-dirty version
                row.append(i); col.append(j); data.append(1)
    return row, col, data

r,c,d = create_sparse(fsparse, 4)
print(r,c,d)
M = sparse.coo_matrix((d,(r,c)))
print(M)
print(M.A)
</code>```

producing

```<code>[0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2] [0, 1, 2, 3, 0, 1, 4, 0, 2, 3, 4] [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1]
....
</code>```

The only thing that's different is the one data item with value 0.  sparse will take care of that.

Body:
I have a sparse.txt that looks like this:

# first column is label 0 or 1
# rest of the data is sparse data
# maximum value in the data is 4, so the future dense matrix will
# have 1+4 = 5 elements in a row
# file: sparse.txt
1 1:1 2:1 3:1
0 1:1 4:1
1 2:1 3:1 4:1

The required dense.txt is this:

# required file: dense.txt
1 1 1 1 0
0 1 0 0 1
1 0 1 1 1

Without using scipy coo_matrix it did it in a simple way like this:

def create_dense(fsparse, fdense,fvocab):
    # number of lines in vocab
    lvocab = sum(1 for line in open(fvocab))

    # create dense file
    with open(fsparse) as fi, open(fdense,'w') as fo:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]

            row = [0]* (lvocab+1)
            row[0] = label

            # use listcomps
            row = [ 1 if i in indices else row[i] for i in range(len(row))]

            l = " ".join(map(str,row)) + "\n"
            fo.write(l)

            print('Writing dense matrix line: ', i+1)

Question
How can we directly get label and data from sparse data without first creating dense matrix and using NUMPY /Scipy preferably??

Question:
How can we read the sparse data using numpy.fromregex ?

My attempt is:

def read_file(fsparse):
    regex = r'([0-1]\s)([0-9]):(1\s)*([0-9]:1)' + r'\s*\n'
    data = np.fromregex(fsparse,regex,dtype=str)

    print(data,file=open('dense.txt','w'))

It did not work!

Related links:

Parsing colon separated sparse data with pandas and numpy

Body:
Tweaking your code to create the dense array directly, rather via file:

fsparse = 'stack47266965.txt'

def create_dense(fsparse, fdense, lvocab):
    alist = []
    with open(fsparse) as fi:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]

            row = [0]* (lvocab+1)
            row[0] = label

            # use listcomps
            row = [ 1 if i in indices else row[i] for i in range(len(row))]
            alist.append(row)
    return alist

alist = create_dense(fsparse, fdense, 4)
print(alist)
import numpy as np
arr = np.array(alist)
from scipy import sparse
M = sparse.coo_matrix(arr)
print(M)
print(M.A)

produces

0926:~/mypy$ python3 stack47266965.py
[[1, 1, 1, 1, 0], [0, 1, 0, 0, 1], [1, 0, 1, 1, 1]]
  (0, 0)    1
  (0, 1)    1
  (0, 2)    1
  (0, 3)    1
  (1, 1)    1
  (1, 4)    1
  (2, 0)    1
  (2, 2)    1
  (2, 3)    1
  (2, 4)    1
[[1 1 1 1 0]
 [0 1 0 0 1]
 [1 0 1 1 1]]

If you want to skip the dense arr, you need to generate the equivalent of the M.row,M.col, and M.data attributes (order doesn't matter)

[0 0 0 0 1 1 2 2 2 2]
[0 1 2 3 1 4 0 2 3 4]
[1 1 1 1 1 1 1 1 1 1]

I don't use regex much so I won't try to fix that.  I assume you want to convert

 '1 1:1 2:1 3:1'

into

 ['1' '1' '2' '2' '1' '3' '1']

But that just gets you to the words/label stage.

A direct to sparse:

def create_sparse(fsparse, lvocab):

    row, col, data = [],[],[]
    with open(fsparse) as fi:
        for i, line in enumerate(fi):
            words = line.strip('\n').split(':')
            words = " ".join(words).split()

            label = int(words[0])
            row.append(i); col.append(0); data.append(label)

            indices = [int(w) for (i,w) in enumerate(words) if int(i)%2]
            for j in indices:   # quick-n-dirty version
                row.append(i); col.append(j); data.append(1)
    return row, col, data

r,c,d = create_sparse(fsparse, 4)
print(r,c,d)
M = sparse.coo_matrix((d,(r,c)))
print(M)
print(M.A)

producing

[0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2] [0, 1, 2, 3, 0, 1, 4, 0, 2, 3, 4] [1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1]
....

The only thing that's different is the one data item with value 0.  sparse will take care of that.


问:
Can I make a function in python treat undefined names as strings?
Say I have this code

```<code>def shut_down(s):
  if s=='yes':
    return "Shutting down"
  else: return "whatever dude I don't even care"
</code>```

Is there a way for it to accept a variable (not a string) and treat it as a string? In short, is foo(undefined), possible?

I tried both

```<code>def shut_down(s):
  s=str(s)
</code>```

and

```<code>def shut_down(str(s)):
</code>```

but it doesn't work. (When I enter shut_down(yes) I get the error yes is not defined. It does work when I enter shut_down('yes'), but that's not the question.

Thanks!

答:
No, it isn't possible. If you want to enter a string, do so, use shut_down('yes'), with the quotes.

You might also prefer to write the next

```<code>def shut_down():
  s=input("Shut down? ").lower()
  if s=='yes':
    return "Shutting down"
  else: return "whatever dude I don't even care"
</code>```

Body:
Say I have this code

def shut_down(s):
  if s=='yes':
    return "Shutting down"
  else: return "whatever dude I don't even care"

Is there a way for it to accept a variable (not a string) and treat it as a string? In short, is foo(undefined), possible?

I tried both

def shut_down(s):
  s=str(s)

and

def shut_down(str(s)):

but it doesn't work. (When I enter shut_down(yes) I get the error yes is not defined. It does work when I enter shut_down('yes'), but that's not the question.

Thanks!

Body:
No, it isn't possible. If you want to enter a string, do so, use shut_down('yes'), with the quotes.

You might also prefer to write the next

def shut_down():
  s=input("Shut down? ").lower()
  if s=='yes':
    return "Shutting down"
  else: return "whatever dude I don't even care"


问:
No local JVM's were detected, not even the jvm running this instance of java mission control
I'm new at Java, and I've just recently installed it and set the environmental variables.

But when I try to compile something, it says:

```<code>javac: file not found: BoleanTest.java
Usage: javac <options> <source files>
use -help for a list of possible options
</code>```

And when I open JVM it says:

No local JVM's were detected, not even the jvm running this instance of java mission control.

Help please, thank you.

(A photo of the error as shown on the screen)

答: In terminal you are in C:\Program Files... and your file is created at C:\Users\.... You are obviously missing your paths here

Body:
I'm new at Java, and I've just recently installed it and set the environmental variables.

But when I try to compile something, it says:

javac: file not found: BoleanTest.java
Usage: javac <options> <source files>
use -help for a list of possible options

And when I open JVM it says:

No local JVM's were detected, not even the jvm running this instance of java mission control.

Help please, thank you.

(A photo of the error as shown on the screen)


问:
Calling the same ColdFusion component from different templates
In a.cfm I have:

```<code><CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Functiion_1(userid)>
</code>```

In the next few templates, c.cfm, I need to call a different function within Ver_Users.cfc I can do:

```<code><CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Function_2(userid)>
</code>```

If I need to call the same cfc again from yet another template down the road and I keep doing this I think it is very awkward and repetitive? the purpose of using .cfc is so that I can reuse or call the functions by just doing:

```<code> <CFSET VerObj,Function_1()> or calling Function_2
</code>```

from anywhere without keep instantiating the cfc am I correct? is there any example on how to accomplish This?

答:
Instantiating a component has a very small performance penalty. It is not false to re-instantiate it in different templates.

If you really want to cut away these few nanoseconds an bytes of memory you can instantiate the component one time at the onApplicationStart() event im your Application.cfc and store it in the application scope.

```<code><cfset application.verUser = new cfcomponents.VerFold.Ver_Users()>
</code>```

And then call the functions in your cfm like:

```<code><cfset application.verUser.Function_1()>
</code>```

Body:
In a.cfm I have:

<CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Functiion_1(userid)>

In the next few templates, c.cfm, I need to call a different function within Ver_Users.cfc I can do:

<CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Function_2(userid)>

If I need to call the same cfc again from yet another template down the road and I keep doing this I think it is very awkward and repetitive? the purpose of using .cfc is so that I can reuse or call the functions by just doing:

 <CFSET VerObj,Function_1()> or calling Function_2

from anywhere without keep instantiating the cfc am I correct? is there any example on how to accomplish This?

Body:
Instantiating a component has a very small performance penalty. It is not false to re-instantiate it in different templates.

If you really want to cut away these few nanoseconds an bytes of memory you can instantiate the component one time at the onApplicationStart() event im your Application.cfc and store it in the application scope.

<cfset application.verUser = new cfcomponents.VerFold.Ver_Users()>

And then call the functions in your cfm like:

<cfset application.verUser.Function_1()>


问:
Location is required in JavaFX with gradle
I'm getting

java.lang.NullPointerException: Location is required.

when I run my program after assembling using gradle with javafx plugin. If I run it from IntelliJ Idea, everything is all right. The Java source files and .fxml are locate in some package.

build.gradle

```<code>apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'idea'
apply from: 'javafx.plugin'

javafx {
    javaRuntime = 'C:\\Program Files\\Java\\jdk1.7.0_45'

    appID 'FXMLExample'
    appName 'fxml example application'
    mainClass 'local.hz.FXMLExample'
}

task "create-dirs" {
    sourceSets*.java.srcDirs*.each {it.mkdirs()}
    sourceSets*.resources.srcDirs*.each {it.mkdirs()}
}
</code>```

fxml_example.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<GridPane fx:controller="local.hz.FXMLExampleController"
      xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<padding><Insets top="25" right="25" bottom="10" left="25"/></padding>
<gridLinesVisible>true</gridLinesVisible>

<Text text="Welcome"
      GridPane.columnIndex="0" GridPane.rowIndex="0"
      GridPane.columnSpan="2"/>

<Label text="User Name:"
      GridPane.columnIndex="0" GridPane.rowIndex="1"/>

<TextField
      GridPane.columnIndex="1" GridPane.rowIndex="1"/>

<Label text="Password:"
      GridPane.columnIndex="0" GridPane.rowIndex="2"/>

<PasswordField fx:id="passwordField"
               GridPane.columnIndex="1" GridPane.rowIndex="2"/>

<HBox spacing="10" alignment="bottom_right"
      GridPane.columnIndex="1" GridPane.rowIndex="4">
    <Button text="Sign In"
            onAction="#handleSubmitButtonAction"/>
</HBox>

<Text fx:id="actiontarget"
      GridPane.columnIndex="1" GridPane.rowIndex="6"/>
</GridPane>
</code>```

FXMLExample.java

```<code>package local.hz;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FXMLExample extends Application {
@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));

    Scene scene = new Scene(root,300,275);

    stage.setTitle("FXML WELCOME!!");
    stage.setScene(scene);
    stage.show();
}

public static  void main(String[] arguments) {
    launch(arguments);
}
}
</code>```

答:
Actually, loading a resource with Gradle might be different from using your IDE resource system. </p>

<p>It is better to use the ClassLoader : </p>

```<code>URL myFxmlURL = ClassLoader.getSystemResource("fxml_example.fxml");
FXMLLoader loader = new FXMLLoader(sampleUrl);

Parent root = loader.load(myFxmlURL);
</code>```

Body:
I'm getting

java.lang.NullPointerException: Location is required.

when I run my program after assembling using gradle with javafx plugin. If I run it from IntelliJ Idea, everything is all right. The Java source files and .fxml are locate in some package.

build.gradle

apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'idea'
apply from: 'javafx.plugin'

javafx {
    javaRuntime = 'C:\\Program Files\\Java\\jdk1.7.0_45'

    appID 'FXMLExample'
    appName 'fxml example application'
    mainClass 'local.hz.FXMLExample'
}

task "create-dirs" {
    sourceSets*.java.srcDirs*.each {it.mkdirs()}
    sourceSets*.resources.srcDirs*.each {it.mkdirs()}
}

fxml_example.fxml

<?xml version="1.0" encoding="UTF-8"?>
<?import java.net.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<GridPane fx:controller="local.hz.FXMLExampleController"
      xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="10" vgap="10">
<padding><Insets top="25" right="25" bottom="10" left="25"/></padding>
<gridLinesVisible>true</gridLinesVisible>

<Text text="Welcome"
      GridPane.columnIndex="0" GridPane.rowIndex="0"
      GridPane.columnSpan="2"/>

<TextField
      GridPane.columnIndex="1" GridPane.rowIndex="1"/>

<PasswordField fx:id="passwordField"
               GridPane.columnIndex="1" GridPane.rowIndex="2"/>

<HBox spacing="10" alignment="bottom_right"
      GridPane.columnIndex="1" GridPane.rowIndex="4">
    <Button text="Sign In"
            onAction="#handleSubmitButtonAction"/>
</HBox>

<Text fx:id="actiontarget"
      GridPane.columnIndex="1" GridPane.rowIndex="6"/>
</GridPane>

FXMLExample.java

package local.hz;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class FXMLExample extends Application {
@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));

    Scene scene = new Scene(root,300,275);

    stage.setTitle("FXML WELCOME!!");
    stage.setScene(scene);
    stage.show();
}

public static  void main(String[] arguments) {
    launch(arguments);
}
}

Body:
Actually, loading a resource with Gradle might be different from using your IDE resource system.

It is better to use the ClassLoader :

URL myFxmlURL = ClassLoader.getSystemResource("fxml_example.fxml");
FXMLLoader loader = new FXMLLoader(sampleUrl);

Parent root = loader.load(myFxmlURL);


问:
Qt5: How do I make the window scroll instead of expand as rows are added to QFormLayout? (Python 3)
I have a window set up like this:

```<code>vbox = QVBoxLayout()
groupBox = QGroupBox()
formLayout = QFormLayout()
groupBox.setLayout(formLayout)
vbox.addWidget(groupBox)
</code>```

I also have two buttons that add rows and remove rows from formLayout.

When I add too many rows such that they cannot fit in the defined window, the window expands vertically. When rows are deleted, the window remains at the expanded size.

I instead want to have the area scroll such that the new rows are only visible within the defined window size, and such that the window does not expand unless the user expands it manually. How can I add a scrolling feature to this and prevent the window from expanding?

答:
I've figured it out. You can use QScrollArea(), as below:

```<code>vbox = QVBoxLayout()
groupBox = QGroupBox()
formLayout = QFormLayout()
groupBox.setLayout(formLayout)
scroll_area = QScrollArea()
scroll_area.setWidgetResizeable(True)
scroll_area.setWidget(groupBox)
vbox.addWidget(scroll_area)
</code>```

This creates a window that doesn't change its size, but rather automatically adds a scroll bar when more rows are added to formLayout.

Body:
I have a window set up like this:

vbox = QVBoxLayout()
groupBox = QGroupBox()
formLayout = QFormLayout()
groupBox.setLayout(formLayout)
vbox.addWidget(groupBox)

I also have two buttons that add rows and remove rows from formLayout.

When I add too many rows such that they cannot fit in the defined window, the window expands vertically. When rows are deleted, the window remains at the expanded size.

I instead want to have the area scroll such that the new rows are only visible within the defined window size, and such that the window does not expand unless the user expands it manually. How can I add a scrolling feature to this and prevent the window from expanding?

Body:
I've figured it out. You can use QScrollArea(), as below:

vbox = QVBoxLayout()
groupBox = QGroupBox()
formLayout = QFormLayout()
groupBox.setLayout(formLayout)
scroll_area = QScrollArea()
scroll_area.setWidgetResizeable(True)
scroll_area.setWidget(groupBox)
vbox.addWidget(scroll_area)

This creates a window that doesn't change its size, but rather automatically adds a scroll bar when more rows are added to formLayout.


问:
select tabbar item programmatically and show the indicator image
I am using UITabBar, not UITabBarController. Whenever user clicks on any tab, I am able to see the underlined image.

```<code>public override func viewDidLoad() {
    super.viewDidLoad()
    UITabBar.appearance().selectionIndicatorImage = getImageWithColorPosition(color: UIColor.darkGray, size: CGSize(width:presenterView.frame.size.width/2, height:49), lineSize: CGSize(width:presenterView.frame.size.width/2, height:2))
}
</code>```

//getImageWithColorPosition is for adding underlined image below UITabBarItem

```<code>func getImageWithColorPosition(color: UIColor, size: CGSize, lineSize: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    let rectLine = CGRect(x: 0, y: size.height-lineSize.height, width: lineSize.width, height: lineSize.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    UIColor.clear.setFill()
    UIRectFill(rect)
    color.setFill()
    UIRectFill(rectLine)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    openItem1()
}

public func  tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if (item.tag == 0) {
        openItem1()
    } else {
        openItem2()
    }
}
</code>```

However, when user clicks on any of the tab items then only underlined image is displayed. I want to select a default tab when user lands on the screen for the first time. As I am doing it programmatically, the underline image doesn't show up. I read couple of stack overflow posts which say that selection on UITabBar can not be triggered programmatically.

Is there any other way to go about it?

答:
If I understand the question correctly, you want to programmatically select a tab on your UITabBar, when the user opens the app. You can do this inside the AppDelegate, for example in didFinishLaunchingWithOptions

In my project I jump to tabs in my tabbar controller depending on events like certain notifications. Inside the AppDelegate I use the following code to programmatically select a tab:

```<code>if let tabbarController = self.window?.rootViewController as? UITabBarController {
    tabbarController.selectedIndex = 0
}
</code>```

Per default the selected item will be the one with index 0 if the app was launched from a cold start and the last opened tab, if the app was in was previously launched and is held in the app switcher.

Hope this is what you are looking for.

Body:
I am using UITabBar, not UITabBarController. Whenever user clicks on any tab, I am able to see the underlined image.

public override func viewDidLoad() {
    super.viewDidLoad()
    UITabBar.appearance().selectionIndicatorImage = getImageWithColorPosition(color: UIColor.darkGray, size: CGSize(width:presenterView.frame.size.width/2, height:49), lineSize: CGSize(width:presenterView.frame.size.width/2, height:2))
}

//getImageWithColorPosition is for adding underlined image below UITabBarItem

func getImageWithColorPosition(color: UIColor, size: CGSize, lineSize: CGSize) -> UIImage {
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    let rectLine = CGRect(x: 0, y: size.height-lineSize.height, width: lineSize.width, height: lineSize.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    UIColor.clear.setFill()
    UIRectFill(rect)
    color.setFill()
    UIRectFill(rectLine)
    let image = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return image
}

public override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    openItem1()
}

public func  tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if (item.tag == 0) {
        openItem1()
    } else {
        openItem2()
    }
}

However, when user clicks on any of the tab items then only underlined image is displayed. I want to select a default tab when user lands on the screen for the first time. As I am doing it programmatically, the underline image doesn't show up. I read couple of stack overflow posts which say that selection on UITabBar can not be triggered programmatically.

Is there any other way to go about it?

Body:
If I understand the question correctly, you want to programmatically select a tab on your UITabBar, when the user opens the app. You can do this inside the AppDelegate, for example in didFinishLaunchingWithOptions

In my project I jump to tabs in my tabbar controller depending on events like certain notifications. Inside the AppDelegate I use the following code to programmatically select a tab:

if let tabbarController = self.window?.rootViewController as? UITabBarController {
    tabbarController.selectedIndex = 0
}

Per default the selected item will be the one with index 0 if the app was launched from a cold start and the last opened tab, if the app was in was previously launched and is held in the app switcher.

Hope this is what you are looking for.


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
Maybe not much better, but how about</p>

```<code>results = ['first', 'second', 'third', 'fourth',
           'fifth', 'sixth', 'seventh', 'eighth']
name = results[((not a) << 2) + ((not b) << 1) + (not c)]
</code>```

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
Maybe not much better, but how about

results = ['first', 'second', 'third', 'fourth',
           'fifth', 'sixth', 'seventh', 'eighth']
name = results[((not a) << 2) + ((not b) << 1) + (not c)]


问:
website to activate my python scraper using c# and possibly a raspberry pi
I am interested in making a website that activates a python script. I am most familiar with c# but I have a python scraping script I would like to use that currently runs well on my raspberry pi.

My question is:

How do I make a C# asp.net website that activates the python script? what is the best approach? should i just forget c# all together and use something like django to host the site?

答: Considering how easy that is with something like django, I would go that route. Unless you're a C# wizard (I am most certainly not) or need it for something else. </p>


问:
How convert varchar2 to number(15,4) with arithmetic operations in Oracle
I have a table with VARCHAR2 datatypes and have to create view by casting varchar to number(15,4).But Varchar2 column contains data like [100 10/50], so the expected decimail value is 100.2.
Table

```<code>CREATE table test1
(
  id Varchar2(50)  ,
  Least Varchar(50));
</code>```

View:VW_test1

```<code>CREATE VIEW VW_test1
    AS
        (SELECT
id,
CAST(Least as Number(15,4))
 FROM test1).
</code>```

Can some one tell how to do this conversion.

答:
I suggest you to do the following. Create a function to do the conversion.

```<code>CREATE OR REPLACE FUNCTION fn_convert_op ( v_string VARCHAR2 )
        RETURN NUMBER
IS
        v_op  VARCHAR2(50);
        v_num NUMBER(15,4);
BEGIN
        v_op := TRANSLATE ( v_string,' []', '+');
        EXECUTE IMMEDIATE 'SELECT '||
        v_op                       ||
        ' FROM DUAL' INTO v_num ;
        RETURN v_num;
END;
/
</code>```

Then create your view using the converted values from the function.

```<code>CREATE VIEW vw_test1 AS
    ( SELECT
        id,
        CAST(fn_convert_op(least) AS NUMBER(15,4) ) least
      FROM
        test1
    );
</code>```

It is recommended that you re-design your table structure to contain proper data.

Body:
I have a table with VARCHAR2 datatypes and have to create view by casting varchar to number(15,4).But Varchar2 column contains data like [100 10/50], so the expected decimail value is 100.2.
Table

CREATE table test1
(
  id Varchar2(50)  ,
  Least Varchar(50));

View:VW_test1

CREATE VIEW VW_test1
    AS
        (SELECT
id,
CAST(Least as Number(15,4))
 FROM test1).

Can some one tell how to do this conversion.

Body:
I suggest you to do the following. Create a function to do the conversion.

CREATE OR REPLACE FUNCTION fn_convert_op ( v_string VARCHAR2 )
        RETURN NUMBER
IS
        v_op  VARCHAR2(50);
        v_num NUMBER(15,4);
BEGIN
        v_op := TRANSLATE ( v_string,' []', '+');
        EXECUTE IMMEDIATE 'SELECT '||
        v_op                       ||
        ' FROM DUAL' INTO v_num ;
        RETURN v_num;
END;
/

Then create your view using the converted values from the function.

CREATE VIEW vw_test1 AS
    ( SELECT
        id,
        CAST(fn_convert_op(least) AS NUMBER(15,4) ) least
      FROM
        test1
    );

It is recommended that you re-design your table structure to contain proper data.


问:
Find the position inside this Yii 2 query
I have this following Yii 2 query

```<code>$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();
</code>```

So imagine this query was an array. Everything found by this query has an "id" attribute.

Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.

Currently, I'm using this code.

```<code>foreach ($find as $t) {
    $arr[] = $t->id;

    if ($t->id == $id) {
        break;
    }
}

$key = count($arr);

return $key;
</code>```

However, this code is vany wayow on a 100k+ result query.

Is there anyway to speed this up?

答:
To get array from query in YII, you can use queryAll();

```<code>$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->queryAll();
</code>```

OR, another way to convert the object into an array is:

```<code>$find = json_decode(json_encode($find), true);  // to convert all data into array.
</code>```

And once you get results in array, you can implement the actual code for your requirement as given below.

You can use array_search() function to get index of your value.

```<code>$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);
</code>```

The array_search() function search an array for a value and returns the key.

ContentLicense: CC BY-SA 4.0

Body:
I have this following Yii 2 query

$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();

So imagine this query was an array. Everything found by this query has an "id" attribute.

Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.

Currently, I'm using this code.

foreach ($find as $t) {
    $arr[] = $t->id;

    if ($t->id == $id) {
        break;
    }
}

$key = count($arr);

return $key;

However, this code is vany wayow on a 100k+ result query.

Is there anyway to speed this up?

Body:
To get array from query in YII, you can use queryAll();

$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->queryAll();

OR, another way to convert the object into an array is:

$find = json_decode(json_encode($find), true);  // to convert all data into array.

And once you get results in array, you can implement the actual code for your requirement as given below.

You can use array_search() function to get index of your value.

$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a);

The array_search() function search an array for a value and returns the key.


问:
Checking odd/even numbers and changing outputs on number size
I have a couple of problems to solve for an assignment, and am a bit stuck.
The question is to write a program that gets the user to input an odd number (check it's odd), then print an upside down pyramid of stars based on the size of the input.

For example, if you enter 5, it comes up with

```<code>*****
 ***
  *
</code>```

My problem is therefore two-fold.

1) How do I check if it's even or odd? I tried if number/2 == int in the hope that it might do something, and the internet tells me to do if number%2==0, but that doesn't work.

2) How do I change the asterisks in the middle of each line?

Any help with either problem is greatly appreciated.

答:
```<code>def main():
    n = float(input('odd:'))
    while n % 2 == 0:
        #if n % 2 == 1: No need for these lines as if it were true the while loop would not have been entered.
            #break not required as the while condition will break loop
        n = float(input('odd:'))

    for i in range(int((n+1)/2)):
        print(' '*i+'*'*int((n-2*i))+' '*i)

main()
</code>```

#1st part ensures that it is an odd number that was entered.2nd part does the printing of triangular

Body:
I have a couple of problems to solve for an assignment, and am a bit stuck.
The question is to write a program that gets the user to input an odd number (check it's odd), then print an upside down pyramid of stars based on the size of the input.

For example, if you enter 5, it comes up with

*****
 ***
  *

My problem is therefore two-fold.

1) How do I check if it's even or odd? I tried if number/2 == int in the hope that it might do something, and the internet tells me to do if number%2==0, but that doesn't work.

2) How do I change the asterisks in the middle of each line?

Any help with either problem is greatly appreciated.

Body:
def main():
    n = float(input('odd:'))
    while n % 2 == 0:
        #if n % 2 == 1: No need for these lines as if it were true the while loop would not have been entered.
            #break not required as the while condition will break loop
        n = float(input('odd:'))

    for i in range(int((n+1)/2)):
        print(' '*i+'*'*int((n-2*i))+' '*i)

main()

#1st part ensures that it is an odd number that was entered.2nd part does the printing of triangular


问:
Drupal: sync users accounts between 2 different Drupal websites
I've a Drupal A website with users accounts running on server A and with domain A.

Now, I need to build a Drupal B website on server B and domain B, and when someone register on Drupal B, he is automatically registered on Drupal A.

In other terms, I need so sync the users accounts.
Can i easily make it ?

thanks

答:
Take a look at the following projects/documentation:

http://drupal.org/project/bakery with documentation at http://drupal.org/node/567410 for single sign-on on sites on the same domain (example.com, subsite.example.com, subsite2.example.com)

http://drupal.org/node/22267 sharing database tables across Drupal sites, which is what Andrew was going for

http://drupal.org/project/domain splits up a single "site" into domains

http://drupal.org/project/sso Single Sign-On

Is it possible to share users between a Drupal 6.x and Open Atrium database, based on organic groups or CiviCRM smart groups? similar question on Stack Overflow


问:
Awk getline takes progressively more time
Have a (G|M)awk script that is used to redistribute lines from source files into different files based on content. An example is sharding a set of source data into separate dated files based on a row timestamp.

Its fast enough until I need to add a csv header row. The source data comes in unordered, so I have considered using if (getline < (fname) < 0) { print cols > fname } to create each destination file with the header line on first touch.

I know that this test for each row of the source data can be expensive, but it appears that as the destination files are created, each getline test takes longer, as the rate of source files processed slows. The slowdown is the performance issue.

This process is also run under GNU Parallel, so a system -f test does not work hanging on the system call.

Suggestions on how to address performance while creating files with a header? Looking to keep this script in Awk as there is other logic already in place.

As an example of the task, I have logs from multiple hosts that need to be combined into files based on the date of the log entry:

```<code>date, time, measure
2017-01-01, 00:00, 10
2017-01-01, 01:00, 20
2017-01-03, 00:05, 30
2017-01-02, 02:10, 40
2017-01-03, 00:00, 50
</code>```

The result of this script would be 3 files based on the date column:

Filename: 20170101.log

```<code>date, time, measure
2017-01-01, 00:00, 10
2017-01-01, 01:00, 20
</code>```

Filename: 20170102.log

```<code>date, time, measure
2017-01-02, 02:10, 40
</code>```

Filename: 20170103.log

```<code>date, time, measure
2017-01-03, 00:05, 30
2017-01-03, 00:00, 50
</code>```

Running this log recombination is fast and simple until the need to include the column header came into play. It seems that as the destination files grow the getline operation takes longer each call. Other examples have shown the use of system calls to test -f for the existence of the file, but this too is an expensive operation and seems to hang under GNU Parallel.

答:
It turns out my issue was an issue with record separators.

The source files use RS="\r\n" (set in the BEGIN block), but the destination files use "\n" as a separator since they are simply printed and this is on Linux. This was causing getline to not see lines, so as the destination files grew so did the time for getline - it was reading the whole file.

My rather inelegant solution is:

```<code>RS="\n"
if (getline < (fname) < 0) { print cols > fname }
RS="\r\n"
</code>```

Body:
Have a (G|M)awk script that is used to redistribute lines from source files into different files based on content. An example is sharding a set of source data into separate dated files based on a row timestamp.

Its fast enough until I need to add a csv header row. The source data comes in unordered, so I have considered using if (getline < (fname) < 0) { print cols > fname } to create each destination file with the header line on first touch.

I know that this test for each row of the source data can be expensive, but it appears that as the destination files are created, each getline test takes longer, as the rate of source files processed slows. The slowdown is the performance issue.

This process is also run under GNU Parallel, so a system -f test does not work hanging on the system call.

Suggestions on how to address performance while creating files with a header? Looking to keep this script in Awk as there is other logic already in place.

As an example of the task, I have logs from multiple hosts that need to be combined into files based on the date of the log entry:

date, time, measure
2017-01-01, 00:00, 10
2017-01-01, 01:00, 20
2017-01-03, 00:05, 30
2017-01-02, 02:10, 40
2017-01-03, 00:00, 50

The result of this script would be 3 files based on the date column:

Filename: 20170101.log

date, time, measure
2017-01-01, 00:00, 10
2017-01-01, 01:00, 20

Filename: 20170102.log

date, time, measure
2017-01-02, 02:10, 40

Filename: 20170103.log

date, time, measure
2017-01-03, 00:05, 30
2017-01-03, 00:00, 50

Running this log recombination is fast and simple until the need to include the column header came into play. It seems that as the destination files grow the getline operation takes longer each call. Other examples have shown the use of system calls to test -f for the existence of the file, but this too is an expensive operation and seems to hang under GNU Parallel.

Body:
It turns out my issue was an issue with record separators.

The source files use RS="\r\n" (set in the BEGIN block), but the destination files use "\n" as a separator since they are simply printed and this is on Linux. This was causing getline to not see lines, so as the destination files grew so did the time for getline - it was reading the whole file.

My rather inelegant solution is:

RS="\n"
if (getline < (fname) < 0) { print cols > fname }
RS="\r\n"


问:
Top 1 & Top 1 1 ( Expr1000 1 ) typical output
```<code>SELECT TOP 1 * FROM Customers;
</code>```

This gives me all customer details of first row

```<code>( customerid, customer name etc..,)
</code>```

```<code>SELECT TOP 1 1 FROM Customers;
</code>```

I got o/p as

```<code>  Expr1000
 ------------
     1
</code>```

But I genuinely don't understand above output, and I searched for it but couldn't get the clear understanding of it.

答:
When you

```<code>SELECT 1
</code>```

it will show just one row of 1.  When you

```<code>SELECT 1 FROM Customers
</code>```

it will give you the number of rows that there in Customers.  So when you

```<code>SELECT TOP 1 1 FROM Customers
</code>```

it will give you only the first row of 1 as if you did

```<code>SELECT TOP 1 * FROM Customers
</code>```

Body:
SELECT TOP 1 * FROM Customers;

This gives me all customer details of first row

( customerid, customer name etc..,)

SELECT TOP 1 1 FROM Customers;

I got o/p as

  Expr1000
 ------------
     1

But I genuinely don't understand above output, and I searched for it but couldn't get the clear understanding of it.

Body:
When you

SELECT 1

it will show just one row of 1.  When you

SELECT 1 FROM Customers

it will give you the number of rows that there in Customers.  So when you

SELECT TOP 1 1 FROM Customers

it will give you only the first row of 1 as if you did

SELECT TOP 1 * FROM Customers


问:
Program to find largest and second largest number in array
I have searched many websites for this question. They are doing it by some different approach.
This code is just not giving output if I input first element of array as largest i.e. a[0].
I think some minor change is required.
can anyone please tell me?

```<code>#include <stdio.h>

int main() {
    int a[10], n;
    int largest1, largest2, i;

    printf("enter number of elements you want in array");
    scanf("%d", &n);
    printf("enter elements");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    largest1 = a[0];
    for (i = 0; i < n; i++) {
        if (a[i] > largest1) {
            largest1 = a[i];
        }
    }
    largest2 = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] > largest2 && a[i] < largest1)
            largest2 = a[i];
    }
    printf("First and second largest number is %d and %d ", largest1, largest2);
}
</code>```

答:
Find your second largest number without using any String function:

```<code>int array[];//Input array
int firstLargest, secondLargest;
int minNumber = -1;//whatever smallest you want to add here
/*There should be more than two elements*/
if (array_size < 2)
{
    printf("Array is too small");
    return;
}

firstLargest = secondLargest = minNumber;
for (index = 0; index < array_size ; ++index)
{
    //Largest number check
    if (array[index] > first)
    {
        secondLargest = firstLargest;
        firstLargest = array[index];
    }

    //It may not larger than first but can be larger than second number
    else if (array[index] > secondLargest && array[index] != firstLargest)
{
        secondLargest = array[index];
}

//Finally you got your answer
if (secondLargest == minNumber)
{
    printf("No Second largest number");
}
else
{
    printf("Second Largest Number is %d", secondLargest);
}
</code>```

Body:
I have searched many websites for this question. They are doing it by some different approach.
This code is just not giving output if I input first element of array as largest i.e. a[0].
I think some minor change is required.
can anyone please tell me?

#include <stdio.h>

int main() {
    int a[10], n;
    int largest1, largest2, i;

    printf("enter number of elements you want in array");
    scanf("%d", &n);
    printf("enter elements");
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    largest1 = a[0];
    for (i = 0; i < n; i++) {
        if (a[i] > largest1) {
            largest1 = a[i];
        }
    }
    largest2 = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] > largest2 && a[i] < largest1)
            largest2 = a[i];
    }
    printf("First and second largest number is %d and %d ", largest1, largest2);
}

Body:
Find your second largest number without using any String function:

int array[];//Input array
int firstLargest, secondLargest;
int minNumber = -1;//whatever smallest you want to add here
/*There should be more than two elements*/
if (array_size < 2)
{
    printf("Array is too small");
    return;
}

firstLargest = secondLargest = minNumber;
for (index = 0; index < array_size ; ++index)
{
    //Largest number check
    if (array[index] > first)
    {
        secondLargest = firstLargest;
        firstLargest = array[index];
    }

    //It may not larger than first but can be larger than second number
    else if (array[index] > secondLargest && array[index] != firstLargest)
{
        secondLargest = array[index];
}

//Finally you got your answer
if (secondLargest == minNumber)
{
    printf("No Second largest number");
}
else
{
    printf("Second Largest Number is %d", secondLargest);
}


问:
is there a faster way to write similar test cases for Django views?
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

```<code>from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])
</code>```

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

答:
I guess what you want is "parameterized tests", standard unittest could do this with parameterized package:

```<code>import unittest
from parameterized import parameterized

class SomeModelApiTests(unittest.TestCase):

    @parameterized.expand([
        ('case1', 'm1', 'f1', 'nf1'),
        ('case1', 'm2', 'f2', 'nf2'),
    ])
    def test_update_with_only_1_field(self, dummy_subtest_name, model_name, field_name, new_field_value):
        print(model_name, field_name, new_field_value)
</code>```

will yields:

```<code>test_update_with_only_1_field_0_case1 (t.SomeModelApiTests) ... m1 f1 nf1
ok
test_update_with_only_1_field_1_case1 (t.SomeModelApiTests) ... m2 f2 nf2
ok
</code>```

pytest testing framework has better support builtin on parameterized tests, worth looking at.

Body:
Basically, I realize that I am writing the same test case (test_update_with_only_1_field) for a similar URL for multiple models

from django.test import RequestFactory, TestCase
class BaseApiTest(TestCase):
def setUp(self):
    superuser = User.objects.create_superuser('test', 'test@api.com', 'testpassword')
    self.factory = RequestFactory()
    self.user = superuser
    self.client.login(username=superuser.username, password='testpassword')

class SomeModelApiTests(base_tests.BaseApiTest):
def test_update_with_only_1_field(self):
    """
    Tests for update only 1 field

    GIVEN the following shape and related are valid
    WHEN we update only with just 1 field
    THEN we expect the update to be successful
    """
    shape_data = {
        'name': 'test shape',
        'name_en': 'test shape en',
        'name_zh_hans': 'test shape zh hans',
        'serial_number': 'test shape serial number',
        'model_name': {
            'some_field': '123'
        }
    }

    data = json.dumps(shape_data)
    response = self.client.post(reverse('shape-list-create'), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    some_model = response.data['some_model']
    new_some_field = '12345'

    data = json.dumps({'some_field': new_some_field, 'id': response.data['some_model']['id']})
    response = self.client.put(reverse('some-model', args=[some_model['id']]), data, 'application/json')
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    self.assertEqual(new_some_field, response.data['some_field'])

I need to do this for more than 10 times. Which I have already done so.

the only difference each time, is the following phrases "some_model", "some-model", and "some_field"

I was wondering if there's a faster way to do this.

I can think abstractly two ways:

create a template in a text editor that somehow can generate the final test case which I then copy and paste. I am using sublime text 3 though I am okay to switch to another text editor

There's a way I can write slightly more code in the form of converting this test case into a behavior class that the individual test class can call. aka composition.

Which one makes more sense or there's a different way to do this?

Please note that BaseApi class is also inherited by other test class that do NOT have that repetitive test case method.

Body:
I guess what you want is "parameterized tests", standard unittest could do this with parameterized package:

import unittest
from parameterized import parameterized

class SomeModelApiTests(unittest.TestCase):

    @parameterized.expand([
        ('case1', 'm1', 'f1', 'nf1'),
        ('case1', 'm2', 'f2', 'nf2'),
    ])
    def test_update_with_only_1_field(self, dummy_subtest_name, model_name, field_name, new_field_value):
        print(model_name, field_name, new_field_value)

will yields:

test_update_with_only_1_field_0_case1 (t.SomeModelApiTests) ... m1 f1 nf1
ok
test_update_with_only_1_field_1_case1 (t.SomeModelApiTests) ... m2 f2 nf2
ok

pytest testing framework has better support builtin on parameterized tests, worth looking at.