问:
Meteor not returning data from MongoDB
For some reason i can't get data displayed from my Locations collection. No matter what i type i get [object Object] when i write {{myPlaces}} in the HTML. Should i not get a list of the entire content and all fields listed? Can someone explain this, as I get all data from both Meteor.Users and Images. Thank you!

zipCodes.js:

```<code>import { Mongo } from 'meteor/mongo';

export const Locations = new Mongo.Collection('locations');

if (Meteor.isServer) {
  Meteor.publish("locations", function () {
   return Locations.find().cursor;
   });
}

if (Meteor.isServer) {

  Locations.batchInsert(
    [
     {
       "country": "NO",
       "zipcode": 1751,
       "place": "Halden",
       "county": "Ostfold",
       "countyNumber": 1,
       "municipality": "Halden",
       "municipalityNumber": 101,
       "lat": 59.1248,
       "long": 11.3875,
       "num": 4
     },
     {
       "country": "NO",
       "zipcode": 1752,
       "place": "Halden",
       "county": "Ostfold",
       "countyNumber": 1,
       "municipality": "Halden",
       "municipalityNumber": 101,
       "lat": 59.1248,
       "long": 11.3875,
       "num": 4
     },
</code>```

testPage.js

```<code>import './testPage.html';
import { Template } from 'meteor/templating';
import Images from '/lib/config/imagesCollection.js';
import { Locations } from '/imports/api/profiles/zipCodes.js';

Template.testPage.helpers({
  // PROFILE INFORMATION
  user: function() {
    return Meteor.users.find();
  },

  // this = {{#each user}} context
  userEmail: function() {
    return this.emails[0].address;
  },

  userFirstName: function() {
    return this.profile.first_name;
  },

  userTitle: function() {
    return this.profile.work_title;
  },

  userMobile: function() {
    return this.profile.mobile;
  },

  userZip: function() {
    return this.profile.zipcode;
  },

  // PATH TO PROFILE PICTURE
  imageLink: function() {
    return Images.findOne({userId: this._id})['_id'];
  },

  // GEODATA TEST
  myPlaces: function() {
    return Locations.find({});
  },
});
</code>```

答:
Your myPlaces helper returns a cursor - i.e. a function that lets you refer to a list of Locations. You need to iterate over that cursor to display individual documents using {{#each }}. In your html do:

```<code><template name="locations">
  {{#each myPlaces}}
    place: {{place}}
    country: {{country}}
    zipcode: {{zipcode}}
   {{/each}}
</template>
</code>```

Title: Meteor not returning data from MongoDB

Body:
For some reason i can't get data displayed from my Locations collection. No matter what i type i get [object Object] when i write {{myPlaces}} in the HTML. Should i not get a list of the entire content and all fields listed? Can someone explain this, as I get all data from both Meteor.Users and Images. Thank you!

zipCodes.js:

import { Mongo } from 'meteor/mongo';

export const Locations = new Mongo.Collection('locations');

if (Meteor.isServer) {
  Meteor.publish("locations", function () {
   return Locations.find().cursor;
   });
}

if (Meteor.isServer) {

  Locations.batchInsert(
    [
     {
       "country": "NO",
       "zipcode": 1751,
       "place": "Halden",
       "county": "Ostfold",
       "countyNumber": 1,
       "municipality": "Halden",
       "municipalityNumber": 101,
       "lat": 59.1248,
       "long": 11.3875,
       "num": 4
     },
     {
       "country": "NO",
       "zipcode": 1752,
       "place": "Halden",
       "county": "Ostfold",
       "countyNumber": 1,
       "municipality": "Halden",
       "municipalityNumber": 101,
       "lat": 59.1248,
       "long": 11.3875,
       "num": 4
     },

testPage.js

import './testPage.html';
import { Template } from 'meteor/templating';
import Images from '/lib/config/imagesCollection.js';
import { Locations } from '/imports/api/profiles/zipCodes.js';

Template.testPage.helpers({
  // PROFILE INFORMATION
  user: function() {
    return Meteor.users.find();
  },

  // this = {{#each user}} context
  userEmail: function() {
    return this.emails[0].address;
  },

  userFirstName: function() {
    return this.profile.first_name;
  },

  userTitle: function() {
    return this.profile.work_title;
  },

  userMobile: function() {
    return this.profile.mobile;
  },

  userZip: function() {
    return this.profile.zipcode;
  },

  // PATH TO PROFILE PICTURE
  imageLink: function() {
    return Images.findOne({userId: this._id})['_id'];
  },

  // GEODATA TEST
  myPlaces: function() {
    return Locations.find({});
  },
});

Body:
Your myPlaces helper returns a cursor - i.e. a function that lets you refer to a list of Locations. You need to iterate over that cursor to display individual documents using {{#each }}. In your html do:

<template name="locations">
  {{#each myPlaces}}
    place: {{place}}
    country: {{country}}
    zipcode: {{zipcode}}
   {{/each}}
</template>


来源: stackexchange

问:
BigQuery : Scalar Subquery produced more than one - Custom Dimensions
Im trying to get a custom dimension into my one of my unions, but im getting a issue with scalar sub query produced more than one element. I believe the issue lies within this code.  Im trying to migrate across to standard SQL so please give answer in standard SQL.

```<code>SELECT
      d.value
FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
WHERE
      d.index = 65) AS viewID,
</code>```

Overall example of the query

```<code>#standardSQL
SELECT
  date,
  channelGrouping,
  viewID,
  SUM(Revenue) Revenue,
  SUM(Shipping) Shipping,
  SUM(bounces) bounces,
  SUM(transactions) transactions,
  COUNT(date) sessions
FROM (
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    (
    SELECT
      d.value
    FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
    WHERE
      d.index = 65) AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703' )
GROUP BY
  date,
  channelGrouping,
  viewID
</code>```

答:
You can simulate some data in BigQuery to better understand what's going on here.

For instance, this data simulates the hits schema in ga_sessions:

```<code>WITH data AS(
  select ARRAY<STRUCT<hitNumber INT64, customDimensions ARRAY<STRUCT<index INT64, value STRING>> >> [STRUCT(1 as hitNumber, [STRUCT(1 as index, 'val1' as value), STRUCT(2 as index, 'val2' as value), STRUCT(3 as index, 'val3' as value)] as customDimensions), STRUCT(2 as hitNumber, [STRUCT(1 as index, 'val1' as value)] as customDimensions)] hits
)

select * from data
</code>```

Now, if you run your query against this simulated data querying where index = 1, you will get the same error because in two different places the index is 1.

In order for this to work, you would have to bring it as an ARRAY like so:

```<code>SELECT
  array(select custd.value from unnest(hits) hits, unnest(hits.customDimensions) custd where index = 1)
FROM data
</code>```

And you'll see the result:

So in your query you'll have to adapt for either returning this value as an ARRAY or, if for all values where index=65 the value is the same, you can do something like:

```<code>SELECT
  (select custd.value from unnest(hits) hits, unnest(hits.customDimensions) custd where index = 1 limit 1)
FROM data
</code>```

This will bring just one result in the scalar sub-query.

ContentLicense: CC BY-SA 3.0

Body:
Im trying to get a custom dimension into my one of my unions, but im getting a issue with scalar sub query produced more than one element. I believe the issue lies within this code.  Im trying to migrate across to standard SQL so please give answer in standard SQL.

SELECT
      d.value
FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
WHERE
      d.index = 65) AS viewID,

Overall example of the query

#standardSQL
SELECT
  date,
  channelGrouping,
  viewID,
  SUM(Revenue) Revenue,
  SUM(Shipping) Shipping,
  SUM(bounces) bounces,
  SUM(transactions) transactions,
  COUNT(date) sessions
FROM (
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    (
    SELECT
      d.value
    FROM
      UNNEST(hits) AS hits,
      UNNEST(hits.customDimensions) AS d
    WHERE
      d.index = 65) AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703'
  UNION ALL
  SELECT
    date,
    channelGrouping,
    'XXXXXXXXX' AS viewID,
    totals.totaltransactionrevenue / 1e6 Revenue,
    (
    SELECT
      SUM(hits.transaction.transactionshipping) / 1e6
    FROM
      UNNEST(hits) hits) Shipping,
    totals.bounces bounces,
    totals.transactions transactions
  FROM
    `XXXXXXXXX.ga_sessions_*`
  WHERE
    _TABLE_SUFFIX BETWEEN '20170625'
    AND '20170703' )
GROUP BY
  date,
  channelGrouping,
  viewID

Body:
You can simulate some data in BigQuery to better understand what's going on here.

For instance, this data simulates the hits schema in ga_sessions:

WITH data AS(
  select ARRAY<STRUCT<hitNumber INT64, customDimensions ARRAY<STRUCT<index INT64, value STRING>> >> [STRUCT(1 as hitNumber, [STRUCT(1 as index, 'val1' as value), STRUCT(2 as index, 'val2' as value), STRUCT(3 as index, 'val3' as value)] as customDimensions), STRUCT(2 as hitNumber, [STRUCT(1 as index, 'val1' as value)] as customDimensions)] hits
)

select * from data

Now, if you run your query against this simulated data querying where index = 1, you will get the same error because in two different places the index is 1.

In order for this to work, you would have to bring it as an ARRAY like so:

SELECT
  array(select custd.value from unnest(hits) hits, unnest(hits.customDimensions) custd where index = 1)
FROM data

And you'll see the result:

So in your query you'll have to adapt for either returning this value as an ARRAY or, if for all values where index=65 the value is the same, you can do something like:

SELECT
  (select custd.value from unnest(hits) hits, unnest(hits.customDimensions) custd where index = 1 limit 1)
FROM data

This will bring just one result in the scalar sub-query.


问:
Delete subdocuments which meet a criteria
In my collection I've got two arrays with subdocuments. I would like to delete all subdocuments inside of these arrays which meet a certain criteria. This is how my document looks like:

```<code>{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : ISODate("2017-07-04T13:10:11.006Z"),
    "created_at" : ISODate("2017-06-05T18:34:07.150Z"),
    "uploaded_files" : [
        {
            "display_name" : "CoC_Bot.Main.locale (1).pot",
            "file" : ObjectId("595b93b298b07d206c0d6153"),
            "upload_id" : ObjectId("595b93ac98b07d206c0d6152"),
            "created_at" : ISODate("2017-07-04T13:10:11.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562 (1).txt",
            "file" : ObjectId("595b93ac98b07d206c0d6151"),
            "upload_id" : ObjectId("595b93ac98b07d206c0d6152"),
            "created_at" : ISODate("2017-07-04T13:10:04.000Z")
        },
        {
            "display_name" : "CoC_Bot.Main.locale (1).pot",
            "file" : ObjectId("595b93b298b07d206c0d6153"),
            "upload_id" : ObjectId("595b93ac98b07d206c0d6152"),
            "created_at" : ISODate("2017-07-04T13:10:11.000Z")
        }
    ]
}
</code>```

I want to delete all subdocuments from uploaded_files and file_history which match the upload_id x. How can I achieve this?

答:
you can use $pull

```<code>COLLECTION.update(
    {project_id:12}, /* condition */
    {$pull: {file_history:{upload_id: ID}}},
    {multi:true, new: true})
    .exec(function(err, docs){

    });
</code>```

Body:
In my collection I've got two arrays with subdocuments. I would like to delete all subdocuments inside of these arrays which meet a certain criteria. This is how my document looks like:

{
    "_id" : ObjectId("5935a41f12f3fac949a5f925"),
    "project_id" : 13,
    "updated_at" : ISODate("2017-07-04T13:10:11.006Z"),
    "created_at" : ISODate("2017-06-05T18:34:07.150Z"),
    "uploaded_files" : [
        {
            "display_name" : "CoC_Bot.Main.locale (1).pot",
            "file" : ObjectId("595b93b298b07d206c0d6153"),
            "upload_id" : ObjectId("595b93ac98b07d206c0d6152"),
            "created_at" : ISODate("2017-07-04T13:10:11.000Z")
        }
    ],
    "file_history" : [
        {
            "display_name" : "Log_28-6-2017_14-17-53-562 (1).txt",
            "file" : ObjectId("595b93ac98b07d206c0d6151"),
            "upload_id" : ObjectId("595b93ac98b07d206c0d6152"),
            "created_at" : ISODate("2017-07-04T13:10:04.000Z")
        },
        {
            "display_name" : "CoC_Bot.Main.locale (1).pot",
            "file" : ObjectId("595b93b298b07d206c0d6153"),
            "upload_id" : ObjectId("595b93ac98b07d206c0d6152"),
            "created_at" : ISODate("2017-07-04T13:10:11.000Z")
        }
    ]
}

I want to delete all subdocuments from uploaded_files and file_history which match the upload_id x. How can I achieve this?

Body:
you can use $pull

COLLECTION.update(
    {project_id:12}, /* condition */
    {$pull: {file_history:{upload_id: ID}}},
    {multi:true, new: true})
    .exec(function(err, docs){

    });


问:
Make view function in larvael escapes dots from the path
I'm working on Laravel Application and I want to call a view using view function.

The problem is my folders may contain dots like:

```<code>"this.is.folder/file.blade.php"
</code>```

Which of course laravel is going to assume it's

```<code>"this/is/folde/file.blade.php"
</code>```

Which in my case the file doesn't exist!

```<code>$folderName = "this.is.folder";
view($folderName.'/main/file');
</code>```

So How can I solve this problem and make view escapes the dots in my file name!

答:
Edit:

As stated in the comment, i've included the part of the solution - from
 laravel load view from a folder name with actual dot

```<code>$folder = 'this.is.folder';

View::addNamespace($folder, base_path('resources/views')."/{$folder}/");

Route::get('example', function() use ($folder) {
    return view("{$folder}::home");
});
</code>```

Body:
I'm working on Laravel Application and I want to call a view using view function.

The problem is my folders may contain dots like:

"this.is.folder/file.blade.php"

Which of course laravel is going to assume it's

"this/is/folde/file.blade.php"

Which in my case the file doesn't exist!

$folderName = "this.is.folder";
view($folderName.'/main/file');

So How can I solve this problem and make view escapes the dots in my file name!

Body:
Edit:

As stated in the comment, i've included the part of the solution - from
 laravel load view from a folder name with actual dot

$folder = 'this.is.folder';

View::addNamespace($folder, base_path('resources/views')."/{$folder}/");

Route::get('example', function() use ($folder) {
    return view("{$folder}::home");
});


问:
how validation works in mongoose
I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html

It is said that validation occurs before saving document in the database.

And to turn this feature off we have to set option: validateBeforeSave to false.

However I have another decent Node.js tutorial example where they just use .validate as follows:

```<code>      var course = new Course({});

      course.validate(function(err) {
        assert.ok(err);
        assert.equal(err.errors['title'].kind, 'required');

        course.title = 'Introduction to Computer Science';
        assert.equal(course.title, 'Introduction to Computer Science');

        var s = '0123456789';
        course.title = '';
        while (course.title.length < 150) {
          course.title += s;
        }

        course.validate(function(err) {
          assert.ok(err);
          assert.equal(err.errors['title'].kind, 'maxlength');

          ++succeeded;
          done();
        });
      });
</code>```

I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?

答:
In the example code, they are using Async Custom Validator which you would understand better if you check this: http://mongoosejs.com/docs/validation.html#built-in-validators

They are used when standard validation is not enough and this is purely my observation that they are usually used in testing along with some testing framework and assetion library.

Title: how validation works in mongoose

Body:
I was reading documentation of mongoose: http://mongoosejs.com/docs/guide.html

It is said that validation occurs before saving document in the database.

And to turn this feature off we have to set option: validateBeforeSave to false.

However I have another decent Node.js tutorial example where they just use .validate as follows:

      var course = new Course({});

      course.validate(function(err) {
        assert.ok(err);
        assert.equal(err.errors['title'].kind, 'required');

        course.title = 'Introduction to Computer Science';
        assert.equal(course.title, 'Introduction to Computer Science');

        var s = '0123456789';
        course.title = '';
        while (course.title.length < 150) {
          course.title += s;
        }

        course.validate(function(err) {
          assert.ok(err);
          assert.equal(err.errors['title'].kind, 'maxlength');

          ++succeeded;
          done();
        });
      });

I can't understand the underlying reason for using validate without setting validateBeforeSave option to false? Could someone please clarify how the provided code above works?


问:
trying to create submenus
Editing for revision, as you can see the menu and its submenu is hiding behind the banner or picture

Is there something wrong with the code? as it only appears on firefox, all the other web browsers i.e Safari, Chrome, IE and Opera work well

```<code>  <BODY ONSELECTSTART="return false;" BGCOLOR="#FFFFFF" TEXT="#000000">
  <table border="0" align="center" width="800">
  <tr>
  <td align="left" width="200"><a href="index.html"><img
  src="images/logo1.gif" width="135" height="57" border="0"></a></td>
  <td width="399" align="right"><img src="images/medical_innovations.gif"
  width="335" height="60"></td>
  <td align="right" width="187"><div class="body"><b>Tel: 1-905-475-2380<br>
  Toll Free: 1-877-50KOSIM<br  />Fax: 905-475-2303<br  />
  email: <a href="email_sales.php">sales@kosim.ca</a></b></div></td>
  </tr>
  </table>
  <table align="center" width="800" bgcolor="EDF0F7" cellspacing="0"
  cellpadding="0">
  <tr>
  <td width="86" height="25"></td>
  <td width="2"><img src="images/spacer.jpg"></td>
  <td align="center" width="46"><a href="index.html"
  onMouseOver="movr(1);return true;" onMouseOut="mout(1);return true;"
 onClick="return true;"><img name=img1 border=0
 src="images/link_off_home.jpg"></a></td>
 <td width="2"><img src="images/spacer.jpg"></td>
 <td align="center" width="63"><a href="products/index.html"
 onMouseOver="movr(2);return true;" onMouseOut="mout(2);return true;"
  onClick="return true;"><img name=img2 border=0
  src="images/link_off_products.jpg"></a></td>
  <td width="2"><img src="images/spacer.jpg"></td>
  <td align="center" width="66"><a href="about.html"
  onMouseOver="movr(3);return true;" onMouseOut="mout(3);return true;"
  onClick="return true;"><img name=img3 border=0
  src="images/link_off_about.jpg"></a></td>
  <td width="2"><img src="images/spacer.jpg"></td>
  <td align="center" width="99"><a href="events.html"
  onMouseOver="movr(4);return true;" onMouseOut="mout(4);return true;"
  onClick="return true;"><img name=img4 border=0
  src="images/link_off_events.jpg">    </a>     </td>
  <td width="10"><img src="images/spacer.jpg"></td>
  <td align="center" width="111"><a href="customer_service.html"
  onMouseOver="movr(5);return true;" onMouseOut="mout(5);return true;"
  onClick="return true;"><img name=img5 border=0
  src="images/link_off_cs.jpg"></a></td>
  <td width="10"><img src="images/spacer.jpg"></td>
  <td align="center" width="73"><a href="contact_us.html"
  onMouseOver="movr(6);return true;" onMouseOut="mout(6);return true;"
  onClick="return true;"><img name=img6 border=0
  src="images/link_off_contact.jpg"></a></td>
  <td width="90"><img src="images/spacer.jpg"></td>
  <td width="136"></td>
  </tr>
  </table>

  <table align="center" width="800" border="0" cellpadding="0"
  cellspacing="0">
  <tr>
  <td valign="top" bgcolor="EDF0F7">
  <!-- side bar - products -->
  <table width="175" height="494" border="0" align="center" cellpadding="3"
  cellspacing="0" style="border: 1px solid #ADBCDB">
 <tr>
 <td width="167" height="24" align="center" bgcolor="DDDDDD"><font
 face="arial" size="2" color="000000"><b>Products</b></td>
 </tr>
 <tr bgcolor="#EDF0F7" onMouseOver="this.bgColor='FFFFFF';"
 onMouseOut="this.bgColor='#EDF0F7';">
 <td height="23" valign="middle">
 <ul>
<li>
<label for="acu">Acupuncture</label>
<input id="acu" type="checkbox">
  <ul>
  <li><a href="http://kosim.ca/products/needles.html">Needles</a></li>
  <li><a href="http://kosim.ca/products/acu_models.html">Acupuncture Models</a></li>
  <li><a href="http://kosim.ca/products/electro-therapeutic_devices.html">Electro-Therapeutic Devices</a></li>
  <li><a href="http://kosim.ca/products/others.html">Cupping & Tools</a>
 </li>
  <li><a href="http://kosim.ca/products/books.html">Books</a></li>
  </ul>
  </ul>
<ul>
<li>
<label for="ana">Anatomical</label>
<input id="ana" type="checkbox">
<ul>
  <li><a href="products/charts.html">Charts</a>
  <li><a href="products/models_series_1.html">Model 1</a></li>
  <li><a href="products/models_series_2.html">Model 2</a></li>
  <li><a href="products/models_series_3.html">Model 3</a></li>
</ul>
</li>
</ul>
 <ul>
<li>
<label for="Clinical">Clinical Supplies</label>
<input id="Clinical" type="checkbox">
<ul>
<a href="http://kosim.ca/products/clinic_supplies.html">Clinic Supplies</a>
</li>
</ul>
</ul>
<ul>
<li>
 <label for="Diag">Diagnostic Equipment</label>
<input id="Diag" type="checkbox">
<ul>
      <li><a href="http://kosim.ca/products/hand_evaluation.html">Hand
Evaluation</a></li>
      <li><a href="http://kosim.ca/products/rom_measurement.html">Range of
Motion</a></li>
      <li><a href="http://kosim.ca/products/diagnostic_equip.html">Adjusting
& Diagnostic</a></li>
</ul>

<tr bgcolor="#EDF0F7" onMouseOver="this.bgColor='FFFFFF';"
onMouseOut="this.bgColor='#EDF0F7';">
<td height="23" align="center" valign="middle" bgcolor="#D6D6D6"><a
href="monthly_specials.html" target="_blank" class="special" style="text-
decoration:none"><b><em>Monthly Special!</em></b></a></td>
</tr>
<tr></tr>
</table>
<table width="99%">
<tr>
<td height="0" align="left" valign="middle"> </td>
</tr>
<tr>
<td align="center"><br><a href="order_form.php"><img
src="images/howtoorder.jpg"
width="78" height="95" border="0"></a></td>
</tr>
<tr>
<td align="center"><br>

</td>
</tr>
</table></td>

<td width="620" align="center" valign="top">
<!-- body -->

<script src="bookmark.js" type="text/javascript"></script>
<script src='prototype.js' type='text/javascript'></script>
<script src='effects.js' type='text/javascript'></script>
<script src='rotatingbanner.js' type='text/javascript'></script>

<TABLE width="501" cellspacing="1" cellpadding="0" border="0">
<TR>
<TD valign="top"><div id='rotational-banner-container' style='height:
323px;'>
<div id='progress-bar' style='padding-top: 130px; padding-left:0;' >
<center><img src="images/blue-spoke.gif"></center></div>
<div id='rotational-banner' style='display:none;' >
<div><a href="about.html"><img src="images/rotate_banner_1.jpg" width="590"
height="300" border="0"></a></div>
<div><a href="products/chiropractic_tables.html"><img src="images/banner-
CHIROPRACTIC.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/laser_therapy.html"><img src="images/banner-
LASER.jpg"
width="590" height="300" border="0"></a></div>
<div><a href="products/massage_therapy.html"><img src="images/banner-
MASSAGE.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/hi-lo.html"><img src="images/banner-
PHYSIOTHERAPY.jpg"
width="590" height="300" border="0"></a></div>
<div><a href="products/exercise_rehab.html"><img src="images/banner-
EXERCISE.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/clinic_supplies.html"><img src="images/Strength-
Tape_Banner_2.jpg" width="590" height="300" border="0"></a></div>
<div><a href="products/pillows.html#30-5001"><img
src="images/rotate_banner_2.jpg" width="590" height="300" border="0"></a>
</div>
<div><a href="monthly_specials.html"><img src="images/rotate_banner_3.jpg"
width="590" height="300" border="0"></a></div>
</div>
</TD></TR>
</table>
<table>
<tr><td></td></tr>
</code>```

答:
Yes there is a way using css

```<code>li > ul {
    display: none;
}
li:active > ul {
    display: block;
}
</code>```

This would work without using jquery.

Title: trying to create submenus

Body:
Editing for revision, as you can see the menu and its submenu is hiding behind the banner or picture

Is there something wrong with the code? as it only appears on firefox, all the other web browsers i.e Safari, Chrome, IE and Opera work well

Tel: 1-905-475-2380

  Toll Free: 1-877-50KOSIM
Fax: 905-475-2303

  email: sales@kosim.ca

 Products

Acupuncture
<input id="acu" type="checkbox">

Needles

Acupuncture Models

Electro-Therapeutic Devices

Cupping & Tools

Books

Anatomical
<input id="ana" type="checkbox">

Charts

Model 1

Model 2

Model 3

Clinical Supplies
<input id="Clinical" type="checkbox">

Clinic Supplies

 Diagnostic Equipment
<input id="Diag" type="checkbox">

Hand
Evaluation

Range of
Motion

Adjusting
& Diagnostic

Monthly Special!

Body:
Yes there is a way using css

li > ul {
    display: none;
}
li:active > ul {
    display: block;
}

This would work without using jquery.


问:
Unable to save code Espruino NodeMCU
I had been working with Espruino for a bit and it is really a wonderful project. But, I am facing an issue for saving the code onto the flash, so that it can still be run when power is supplied to the board(NodeMCU), instead of the PC COM port. The code works completely fine until it is passed from the terminal. But, if I switch over the power supply it stops working.
Also, I tried the save() and E.on('init',function(){}) but to no avail. It still doesn't create a web server. If someone could help out here it could be great!
Thanks!

```<code>function main() {
  var http = require('http');
  var led = Pin(5);
  http.createServer(function (req, res) {
    var url = req.url;
    res.writeHead(200);
    if(url == "/on") {
      digitalWrite(led, 1);
      res.end("on");
    } else if(url == "/off") {
      digitalWrite(led, 0);
      res.end("off");
    } else {
      res.end('Lol');
    }
  }).listen(80);
}
E.on('init', function(){
  main();
});
</code>```

Here's the code I wish to write to my flash for the IOT project I am working on

答:
After fiddling around with the documentation and crawling the scrambled web for almost a whole day I found out a solution myself. The issue ->

```<code>function main() {
  var wifi = require('Wifi');
  wifi.startAP("testing");
  wifi.save();
  var http = require('http');
  var led = Pin(5);
  return http.createServer(function (req, res) {
    var url = req.url;
    res.writeHead(200);
    if(url == "/on") {
      digitalWrite(led, 1);
      res.end("on");
    } else if(url == "/off") {
      digitalWrite(led, 0);
      res.end("off");
    } else {
      res.end('Lol');
    }
  }).listen(80);
}
function test() {
  console.log('Starting server');
  setTimeout(function() {
    var server = main();
    console.log(server);
  }, 5000);
}
E.on('init', function(){
 test();
});
save();
</code>```

The problem was that the MCU couldnot get enough time to connect to the wifi before the command for http.createServer() is executed. Since, it cannot obtain the ip address for the MCU, thus it is unable to process the http.createServer() command. Hence, a timeout was necessary to process a delay before it's execution.

Title: Unable to save code Espruino NodeMCU

Body:
I had been working with Espruino for a bit and it is really a wonderful project. But, I am facing an issue for saving the code onto the flash, so that it can still be run when power is supplied to the board(NodeMCU), instead of the PC COM port. The code works completely fine until it is passed from the terminal. But, if I switch over the power supply it stops working.
Also, I tried the save() and E.on('init',function(){}) but to no avail. It still doesn't create a web server. If someone could help out here it could be great!
Thanks!

function main() {
  var http = require('http');
  var led = Pin(5);
  http.createServer(function (req, res) {
    var url = req.url;
    res.writeHead(200);
    if(url == "/on") {
      digitalWrite(led, 1);
      res.end("on");
    } else if(url == "/off") {
      digitalWrite(led, 0);
      res.end("off");
    } else {
      res.end('Lol');
    }
  }).listen(80);
}
E.on('init', function(){
  main();
});

Here's the code I wish to write to my flash for the IOT project I am working on

Body:
After fiddling around with the documentation and crawling the scrambled web for almost a whole day I found out a solution myself. The issue ->

function main() {
  var wifi = require('Wifi');
  wifi.startAP("testing");
  wifi.save();
  var http = require('http');
  var led = Pin(5);
  return http.createServer(function (req, res) {
    var url = req.url;
    res.writeHead(200);
    if(url == "/on") {
      digitalWrite(led, 1);
      res.end("on");
    } else if(url == "/off") {
      digitalWrite(led, 0);
      res.end("off");
    } else {
      res.end('Lol');
    }
  }).listen(80);
}
function test() {
  console.log('Starting server');
  setTimeout(function() {
    var server = main();
    console.log(server);
  }, 5000);
}
E.on('init', function(){
 test();
});
save();

The problem was that the MCU couldnot get enough time to connect to the wifi before the command for http.createServer() is executed. Since, it cannot obtain the ip address for the MCU, thus it is unable to process the http.createServer() command. Hence, a timeout was necessary to process a delay before it's execution.


问:
error on storm nimbus daemon
i'm trying to run apache storm on my ubuntu. for this i should run nimbus daemon. the problem is when i type the command storm nimbus
, it gives me an error:

ERROR StatusLogger File not found in file system or classpath:
  /usr/lib/storm/cluster.xml

ERROR StatusLogger Reconfiguration failed: No configuration found for
  'AsyncContext@2503dbd3' at 'null' in 'null'

i found the cluster.xml file from log4j directory and placed it on the storm directory and start nimbus, but this time it stopped without any error with an exception :

expected '', but found BlockMappingStart

does anyone know how to fix it?

答:
The problem was caused by the old configuration of config file: storm/conf/storm.yaml
In version 1.1 of storm, instead of nimbus.host, use nimbus.seeds. </p>

Title: error on storm nimbus daemon


问:
Joining Oracle Table Data with MongoDB Collection
I have a reporting framework to build and generate reports (tabular format reports). As of now I used to write SQL query and it used to fetch data from Oracle. Now I have got an interesting challenge where half of data will come from Oracle and remaining data come from MongoDB based on output from Oracle data. Fetched tabular format data from Oracle will have one additional column which will contain key to fetch data from MongoDB. With this I will have two data set in tabular format one from Oracle data and one from MongoDB. Based on one common column I need to merge both table data and produce one data set to produce report.

I can write logic in java code to merge two tables (say data in 2D array format). But instead of doing this from my own, I am thinking to utilize some RDBMS in-memory data concept. For example, H2 database, where I can create two tables in memory on the fly and execute H2 queries to merge two tables. Or, I believe, there could be something in Oracle too like global temp table etc. Could someone please suggest the better approach to join oracle table data with MongoDB collection.

答:
Another suggestion would be to use apache drill. https://drill.apache.org

You can use a mongo and JDBC drill bits and then you can join oracle tables and mongo collections together.


问:
Error connecting to mysql database.
It might be a duplicate, but i went through all the solution that are suggested in other posts at stackoverflow but cannot find a solution.

```<code> <?php
$PDO= new PDO('mysql:host= 127.0.0.1; dbname = social_network; charset= utf8', 'root', '' );
$PDO-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>
</code>```

The error i am having is as follows:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2019] Unknown character set in C:\xampp\htdocs\social_network\create_account.php:2 Stack trace: #0 C:\xampp\htdocs\social_network\create_account.php(2): PDO->__construct('mysql:host= 127...', 'root', '') #1 {main} thrown in C:\xampp\htdocs\social_network\create_account.php on line 2

I appreciate your quick asnwer.

答:
You have an extra extra space in the DSN which is count as a part of charset name, so it has to be removed.</p>
```<code><?php
$servername = 127.0.0.1;  //localhost
$username = "root";
$password = "";
$dbname = "social_network";
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
</code>```

Title: Error connecting to mysql database.

Body:
It might be a duplicate, but i went through all the solution that are suggested in other posts at stackoverflow but cannot find a solution.

 <?php
$PDO= new PDO('mysql:host= 127.0.0.1; dbname = social_network; charset= utf8', 'root', '' );
$PDO-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

The error i am having is as follows:

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2019] Unknown character set in C:\xampp\htdocs\social_network\create_account.php:2 Stack trace: #0 C:\xampp\htdocs\social_network\create_account.php(2): PDO->__construct('mysql:host= 127...', 'root', '') #1 {main} thrown in C:\xampp\htdocs\social_network\create_account.php on line 2

I appreciate your quick asnwer.

Body:
You have an extra extra space in the DSN which is count as a part of charset name, so it has to be removed.

<?php
$servername = 127.0.0.1;  //localhost
$username = "root";
$password = "";
$dbname = "social_network";
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

ContentLicense: CC BY-SA 4.0


问:
My site is not rendering properly in chrome, Could this happen if Bootstrap and a CSS3 Class conflicted?
I am working on a new page, the domain is quite large and I have never encountered this problem. I have finished my page that shows very well in all internet browsers, except in Chrome, I have cleaned the cache and nothing fixes

Could it be my CSS?

Any experience and / or suggestion?

In the image on the left is EDGE on the right is Chrome

答: If you think your code is error-free and it is the caches you're having trouble with. Then try pressing CTRL+F5 to reload the page. It works for me when the changes in the page are not being applied consistently.


问:
Change font-size of dynamically added elements
I have a  with a fixed width/height to which i'm planning to dynamically add elements to. What im trying is for the font of those added elements to decrease the more there are as there will be a point they wont fit on the parent .

I was able to make the font scale if i scale the browser window...but thats not the plan :)

Is this possible at all, whatever means(css/js/jquery)?

See this jsfiddle example: https://jsfiddle.net/qzt0wkyd/

Sample Code:

.bottom {
  background-color: #fff;
  text-align: center;
  margin: 0px auto;
  padding: 10px 5px 5px 5px;
  margin-top: 5px;
  width: 420px;
  height: 150px;
  border: solid #ff9400;
  border-radius: 10px;
  display: inline-block;
  overflow: hidden;
  box-shadow: inset 0 0 10px #000000;
}

.aside3 {
  color: #FFB894;
  background-color: #666;
  font-size: 1.5em;
  margin-top: -11px;
  margin-left: -8px;
  width: 103%;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  text-shadow: 1px 1px 1px #111, -1px -1px 1px #999, 1px -1px 1px #111, -1px 1px 1px #999;
}

.linksites {
  display: inline-flex;
  float: center;
  text-align: justify;
  font-weight: bold;
  color: orange;
  letter-spacing: .15em;
  font-size: 30px;
  text-decoration: none;
  text-rendering: optimizeLegibility;
  transition: 2s ease;
  -webkit-transition: 2s ease;
  -moz-transition: 2s ease;
  text-shadow: 1px -1px 0 #767676, -1px 2px 1px #737272, -2px 4px 1px #767474
}

.linksites:hover {
  text-decoration: none;
  font-size: 2.5vwx;
  -webkit-transform: scale(1.1, 1.1);
  -moz-transform: scale(1.1, 1.1);
  -ms-transform: scale(1.1, 1.1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="bottom">
  <p class="aside3">CONTACTS</p>
  <div class="bottom-inner">

    <!--ALL DYNAMICALLY INSERTED <a> TAGS COULD BE MORE OR LESS OR ADDED AND REMOVED-->
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6

  </div>
</div></code>```

In that example i have a bunch of links that dont fit in the parent div, how, if possible, if i add more they scale down or if i remove some they scale up all to for the div. (I set the font-size back to fixed px, after i experimented with em,rem and the likes)

Thanks a lot in advance

答:
using jQuery you can dynamically change css values acording to the amount of elements you have doing something like this

```<code>if ($('a.linksites').length>9 && $('a.linksites').length<13) {
    $('.linksites').css('font-size','20px')
}
</code>```

you could set different font sizes for different amounts of linksites by concatenating various if statements like the one above

Body:
I have a  with a fixed width/height to which i'm planning to dynamically add elements to. What im trying is for the font of those added elements to decrease the more there are as there will be a point they wont fit on the parent .

I was able to make the font scale if i scale the browser window...but thats not the plan :)

Is this possible at all, whatever means(css/js/jquery)?

See this jsfiddle example: https://jsfiddle.net/qzt0wkyd/

Sample Code:

.bottom {
  background-color: #fff;
  text-align: center;
  margin: 0px auto;
  padding: 10px 5px 5px 5px;
  margin-top: 5px;
  width: 420px;
  height: 150px;
  border: solid #ff9400;
  border-radius: 10px;
  display: inline-block;
  overflow: hidden;
  box-shadow: inset 0 0 10px #000000;
}

.aside3 {
  color: #FFB894;
  background-color: #666;
  font-size: 1.5em;
  margin-top: -11px;
  margin-left: -8px;
  width: 103%;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  text-shadow: 1px 1px 1px #111, -1px -1px 1px #999, 1px -1px 1px #111, -1px 1px 1px #999;
}

.linksites {
  display: inline-flex;
  float: center;
  text-align: justify;
  font-weight: bold;
  color: orange;
  letter-spacing: .15em;
  font-size: 30px;
  text-decoration: none;
  text-rendering: optimizeLegibility;
  transition: 2s ease;
  -webkit-transition: 2s ease;
  -moz-transition: 2s ease;
  text-shadow: 1px -1px 0 #767676, -1px 2px 1px #737272, -2px 4px 1px #767474
}

.linksites:hover {
  text-decoration: none;
  font-size: 2.5vwx;
  -webkit-transform: scale(1.1, 1.1);
  -moz-transform: scale(1.1, 1.1);
  -ms-transform: scale(1.1, 1.1);
}

CONTACTS

    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6
    Mail1
    Mail2
    Mail3
    Mail4
    Mail5
    Mail6

In that example i have a bunch of links that dont fit in the parent div, how, if possible, if i add more they scale down or if i remove some they scale up all to for the div. (I set the font-size back to fixed px, after i experimented with em,rem and the likes)

Thanks a lot in advance

Body:
using jQuery you can dynamically change css values acording to the amount of elements you have doing something like this

if ($('a.linksites').length>9 && $('a.linksites').length<13) {
    $('.linksites').css('font-size','20px')
}

you could set different font sizes for different amounts of linksites by concatenating various if statements like the one above


问:
Kinesis Firehose to s3: data delivered to wrong hour in s3 path
I'm using Kinesis Firehose to buffer IoT data, and write it to s3.  Firehose writes buffers to s3 in the format s3://bucket.me.com/YYYY/MM/DD/HH

Data that comes in at 10:59a may get buffered by Firehose and not written out until 11:00a (s3://bucket.me.com/2017/03/09/11).

The problem is, when creating partitions for Athena, the partition for hour 10 will not contain all the data for hour 10 because it is in the hour 11 path.

Here is an example that better illustrates:

An IoT sends the following data to Firehose, which at 2a writes it to s3://bucket.me.com/2017/03/24/02/file-0000.  The file contents look like this:

```<code>{"id":1,"dt":"2017-03-24 01:59:40"}
{"id":2,"dt":"2017-03-24 01:59:41"}
{"id":3,"dt":"2017-03-24 01:59:42"}
</code>```

I then create an Athena table:

```<code>CREATE EXTERNAL TABLE sensor_data (
    id string,
    dt timestamp)
PARTITIONED BY (year int, month int, day int, hour int)
ROW FORMAT  serde 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://bucket.me.com/';

ALTER TABLE sensor_data ADD PARTITION (year=2017,month=3,day=24,hour=1) location 's3://bucket.me.com/2017/03/24/01/';
ALTER TABLE sensor_data ADD PARTITION (year=2017,month=3,day=24,hour=2) location 's3://bucket.me.com/2017/03/24/02/';
</code>```

When I run select * from sensor_data where hour = 1, I won't get the 3 records above returned because it will only read from the s3 path defined for partition hour=1 (and the 3 records are really in the hour=2 partition).

How do I avoid this problem?

答:
I think you're going to want to query broader and then refilter

select * from sensor_data
where (hour = 1 or hour = 2)
       and date_trunc('hour', dt.hour) = 1

Body:
I'm using Kinesis Firehose to buffer IoT data, and write it to s3.  Firehose writes buffers to s3 in the format s3://bucket.me.com/YYYY/MM/DD/HH

Data that comes in at 10:59a may get buffered by Firehose and not written out until 11:00a (s3://bucket.me.com/2017/03/09/11).

The problem is, when creating partitions for Athena, the partition for hour 10 will not contain all the data for hour 10 because it is in the hour 11 path.

Here is an example that better illustrates:

An IoT sends the following data to Firehose, which at 2a writes it to s3://bucket.me.com/2017/03/24/02/file-0000.  The file contents look like this:

{"id":1,"dt":"2017-03-24 01:59:40"}
{"id":2,"dt":"2017-03-24 01:59:41"}
{"id":3,"dt":"2017-03-24 01:59:42"}

I then create an Athena table:

CREATE EXTERNAL TABLE sensor_data (
    id string,
    dt timestamp)
PARTITIONED BY (year int, month int, day int, hour int)
ROW FORMAT  serde 'org.apache.hive.hcatalog.data.JsonSerDe'
LOCATION 's3://bucket.me.com/';

ALTER TABLE sensor_data ADD PARTITION (year=2017,month=3,day=24,hour=1) location 's3://bucket.me.com/2017/03/24/01/';
ALTER TABLE sensor_data ADD PARTITION (year=2017,month=3,day=24,hour=2) location 's3://bucket.me.com/2017/03/24/02/';

When I run select * from sensor_data where hour = 1, I won't get the 3 records above returned because it will only read from the s3 path defined for partition hour=1 (and the 3 records are really in the hour=2 partition).

How do I avoid this problem?


问:
Why use RDF instead of XML for the semantic web
I've done a bit of searching around the web about why we use RDF instead of XML for the semantic modeling. I came across this article, but it's still not completely clear to me. i was wondering if someone could just give me a couple of points on why we cannot use XML instead of RDF. From my limited understanding, XML's extensibility just gives us a way to define a document but does not give us any mechanisms to describe the meaning of it. Any examples would be greatly appreciated.

Thank you very much

答:
From my limited understanding, XML's extensibility just gives us a way to define a document but does not give us any mechanisms to describe the meaning of it.

You're correct.  XML describes data but does not do well at describing the relationship between different data elements.

RDF describes the data and the data relationships.  Think of RDF as a textual meta-database.  The article calls RDF a semantic model.

Here's an RDF example:

```<code><?xml version="1.0"?>

<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:cd="http://www.recshop.fake/cd#">

<rdf:Description
    rdf:about="http://www.recshop.fake/cd/Empire Burlesque">
    <cd:artist>Bob Dylan</cd:artist>
    <cd:country>USA</cd:country>
    <cd:company>Columbia</cd:company>
    <cd:price>10.90</cd:price>
    <cd:year>1985</cd:year>
</rdf:Description>

<rdf:Description
    rdf:about="http://www.recshop.fake/cd/Hide your heart">
    <cd:artist>Bonnie Tyler</cd:artist>
    <cd:country>UK</cd:country>
    <cd:company>CBS Records</cd:company>
    <cd:price>9.90</cd:price>
    <cd:year>1988</cd:year>
</rdf:Description>
.
.
.
</rdf:RDF>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
From my limited understanding, XML's extensibility just gives us a way to define a document but does not give us any mechanisms to describe the meaning of it.

You're correct.  XML describes data but does not do well at describing the relationship between different data elements.

RDF describes the data and the data relationships.  Think of RDF as a textual meta-database.  The article calls RDF a semantic model.

Here's an RDF example:

<?xml version="1.0"?>

<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:cd="http://www.recshop.fake/cd#">

<rdf:Description
    rdf:about="http://www.recshop.fake/cd/Empire Burlesque">
    <cd:artist>Bob Dylan</cd:artist>
    <cd:country>USA</cd:country>
    <cd:company>Columbia</cd:company>
    <cd:price>10.90</cd:price>
    <cd:year>1985</cd:year>
</rdf:Description>

<rdf:Description
    rdf:about="http://www.recshop.fake/cd/Hide your heart">
    <cd:artist>Bonnie Tyler</cd:artist>
    <cd:country>UK</cd:country>
    <cd:company>CBS Records</cd:company>
    <cd:price>9.90</cd:price>
    <cd:year>1988</cd:year>
</rdf:Description>
.
.
.
</rdf:RDF>


问:
SSAS Tabular table always shows in Excel
In my SSAS tabular model I have a calendar dimension, and a wave dimension for half-year data only. The data flows to these tables as such:

Fact Table ---> Wave Dim <---> Calendar

No matter what I do I cannot hide the wave table from Excel users. The table shows hidden in Visual Studio, but in Excel it shows the table with no fields in it. I have tried deleting the table and reloading it with no avail. My assumption is that it has to do with the way it's connected to the Calendar dimension, but I can't seem to find anything on my issue. Any help would be much appreciated.

答:
This is a tough one to answer without viewing your model.bim file. Based on your information I have two guesses on what could be the issue, although this may very well not be it:
1) It sounds like you've marked all fields in the Wave table as hidden, but not the Wave table itself. Could this be the reason?
2) Perhaps you are using perspectives, and only hid the Wave table in a perspective rather than in the Model (default perspective)?

The relationships in your model should have no impact on whether a table is displayed in client tools or not.

Feel free to upload your model.bim file if the above does not help.


问:
Passing and using function as constructor argument in Kotlin
How to create a class that takes function as a constructor argument. Then, use this function at some later point in the class.</p>

答:
You can have a property with a function type just like you would with any other type:

```<code>class A(val f: () -> Unit) {

    fun foo() {
        f()
    }

}
</code>```

From here, you can pass that function to the constructor as a method reference:

```<code>fun bar() {
    println("this is bar")
}

val a = A(::bar)
a.foo()             // this is bar
</code>```

Or as a lambda:

```<code>val a = A({ println("this is the lambda") })
</code>```

And you can even do the usual syntactic sugar for lambdas that are the last parameter of a function (although this is getting a little wild):

```<code>val a = A { println("this is the lambda") }
</code>```

Body:
You can have a property with a function type just like you would with any other type:

class A(val f: () -> Unit) {

    fun foo() {
        f()
    }

}

From here, you can pass that function to the constructor as a method reference:

fun bar() {
    println("this is bar")
}

val a = A(::bar)
a.foo()             // this is bar

Or as a lambda:

val a = A({ println("this is the lambda") })

And you can even do the usual syntactic sugar for lambdas that are the last parameter of a function (although this is getting a little wild):

val a = A { println("this is the lambda") }


问:
Implementing Dictionary interface
This is the IEnumerable interface in which adding some words and returning in last two methods.

The idea here is that you have a Dicitionary that will associate each word to a List of words that are synonyms. The AddSynonyms method will take an enumeration of synonyms and begin by creating a list of unique words, in case there are any duplicates. It then goes through each word and checks to see if it has already been added. If it has then it goes through all the synonyms of that word (the words list minus the word) and checks to see if they are in the List associated with that word. If not the synonym is added to the list. If the word is not already in the Dicitionary then it is added along with a List of it's synonyms (again the words list minus the word).

The GetSynonymns method then just returns the List that is associated with the given word. If the word is not in the Thesaurus then an empty enumeration is returned (you could change that to throw an exception if so desired).

The GetWords method simply returns all the keys of the Dicitionary which will be every word that was added.

```<code>summary>
/// Represents a thesaurus.
/// </summary>
public interface IThesaurus
{
/// <summary>
/// Adds the given synonyms to the thesaurus
/// </summary>
/// <param name="synonyms">The synonyms to add.</param>
void AddSynonyms(IEnumerable<string> synonyms);

/// <summary>
/// Gets the synonyms for a given word.
/// </summary>
/// <param name="word">The word the synonyms of which to get.</param>
/// <returns>A <see cref="string"/> with all synonyms for the given word.</returns>
IEnumerable<string> GetSynonyms(string word);

/// <summary>
/// Gets all words from the thesaurus.
/// </summary>
/// <returns>An <see cref="IEnumerable<string>"/> containing
/// all the words in the thesaurus.</returns>
IEnumerable<string> GetWords();
</code>```

}
}

This is how far I have gotten, but  seem stuck at this. The program won't compile properly. I'm unable to call my method with the obj.GetSynonyms();. Ath the bottom of my public thesaurus class public IEnumerable GetWords() { return lookup.Keys(); } } Doesn't work I just can't understand why it will not work. I can't really spot the problem with the code.

```<code>   namespace Thesaurus
 {
    public interface IThesaurus
    {
        IEnumerable<string> AddSynonyms();
        IEnumerable<string> GetSynonyms(string word);

        IEnumerable<string> GetWords();
}

public class Thesaurus : IThesaurus
{
    private Dictionary<string, List<string>> lookup =
        new Dictionary<string, List<string>>();

    public IEnumerable<string> AddSynonyms() //public void AddSynonyms(IEnumerable<string> synonyms)
    {
        var words = AddSynonyms.Distinct().ToList();
        foreach (var word in words)
        {
            var currentWordSynonyms = words.Where(s => s == word);
            if (lookup.ContainsKey(word))
            {
                foreach (var synonym in currentWordSynonyms)
                {
                    if (!lookup[word].Contains(synonym))
                        lookup[word].Add(synonym);
                }
            }
            else
            {
                lookup.Add(word.currentWordSynonyms);
            }

        }
    }

    public IEnumerable<string> GetSynonyms(string word)
    {
        if (lookup.ContainsKey(word))
            return lookup[word];
        return Enumerable.Empty<string>();
        // Or throw an exception.
    }

    public IEnumerable<string> GetWords()
    {
        return lookup.Keys();
    }
}

class MainClass
{

    static void Main()
    {
        // Declare an interface instance.
        IThesaurus obj = new Thesaurus();

        // Call the member.
        obj.AddSynonyms();
        obj.GetSynonyms();
        obj.GetWords();
    }
}
</code>```

}

答:
Got compiler errors out :</p>

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Thesaurus
{

    class MainClass
    {

        static void Main(string[] args)
        {
            // Declare an interface instance.
            IThesaurus obj = new Thesaurus();
            List<string> words = new List<string>();

            // Call the member.
            obj.AddSynonyms(words);
            obj.GetSynonyms(words[0]);
            obj.GetWords();
        }
    }
    //<summary>
    /// Represents a thesaurus.
    /// </summary>
    public interface IThesaurus
    {
        /// <summary>
        /// Adds the given synonyms to the thesaurus
        /// </summary>
        /// <param name="synonyms">The synonyms to add.</param>
        void AddSynonyms(IEnumerable<string> synonyms);

        /// <summary>
        /// Gets the synonyms for a given word.
        /// </summary>
        /// <param name="word">The word the synonyms of which to get.</param>
        /// <returns>A <see cref="string"/> with all synonyms for the given word.</returns>
        IEnumerable<string> GetSynonyms(string word);

        /// <summary>
        /// Gets all words from the thesaurus.
        /// </summary>
        /// <returns>An <see cref="IEnumerable<string>"/> containing
        /// all the words in the thesaurus.</returns>
        IEnumerable<string> GetWords();
    }

    public class Thesaurus : IThesaurus
    {
        private Dictionary<string, List<string>> lookup =
            new Dictionary<string, List<string>>();

        public void AddSynonyms(IEnumerable<string> allWords) //public void AddSynonyms(IEnumerable<string> synonyms)
        {
            var words = allWords.Distinct().ToList();
            foreach (var word in words)
            {
                var currentWordSynonyms = words.Where(s => s == word);
                if (lookup.ContainsKey(word))
                {
                    foreach (var synonym in currentWordSynonyms)
                    {
                        if (!lookup[word].Contains(synonym))
                            lookup[word].Add(synonym);
                    }
                }
                else
                {
                    List<string> newSynonyms =  new List<string>();
                    newSynonyms.AddRange(currentWordSynonyms);
                    lookup.Add(word, newSynonyms);
                }

            }
        }

        public IEnumerable<string> GetSynonyms(string word)
        {
            if (lookup.ContainsKey(word))
                return lookup[word];
            return Enumerable.Empty<string>();
            // Or throw an exception.
        }

        public IEnumerable<string> GetWords()
        {
            return lookup.AsEnumerable().Select(x => x.Key).ToList();
        }
    }

}
</code>```

Title: Implementing Dictionary interface

Body:
This is the IEnumerable interface in which adding some words and returning in last two methods.

The idea here is that you have a Dicitionary that will associate each word to a List of words that are synonyms. The AddSynonyms method will take an enumeration of synonyms and begin by creating a list of unique words, in case there are any duplicates. It then goes through each word and checks to see if it has already been added. If it has then it goes through all the synonyms of that word (the words list minus the word) and checks to see if they are in the List associated with that word. If not the synonym is added to the list. If the word is not already in the Dicitionary then it is added along with a List of it's synonyms (again the words list minus the word).

The GetSynonymns method then just returns the List that is associated with the given word. If the word is not in the Thesaurus then an empty enumeration is returned (you could change that to throw an exception if so desired).

The GetWords method simply returns all the keys of the Dicitionary which will be every word that was added.

summary>
/// Represents a thesaurus.
///
public interface IThesaurus
{
///
/// Adds the given synonyms to the thesaurus
///
/// <param name="synonyms">The synonyms to add.</param>
void AddSynonyms(IEnumerable<string> synonyms);

///
/// Gets the synonyms for a given word.
///
/// <param name="word">The word the synonyms of which to get.</param>
/// <returns>A <see cref="string"/> with all synonyms for the given word.</returns>
IEnumerable<string> GetSynonyms(string word);

///
/// Gets all words from the thesaurus.
///
/// <returns>An <see cref="IEnumerable<string>"/> containing
/// all the words in the thesaurus.</returns>
IEnumerable<string> GetWords();

}
}

This is how far I have gotten, but  seem stuck at this. The program won't compile properly. I'm unable to call my method with the obj.GetSynonyms();. Ath the bottom of my public thesaurus class public IEnumerable GetWords() { return lookup.Keys(); } } Doesn't work I just can't understand why it will not work. I can't really spot the problem with the code.

   namespace Thesaurus
 {
    public interface IThesaurus
    {
        IEnumerable<string> AddSynonyms();
        IEnumerable<string> GetSynonyms(string word);

        IEnumerable<string> GetWords();
}

public class Thesaurus : IThesaurus
{
    private Dictionary<string, List<string>> lookup =
        new Dictionary<string, List<string>>();

    public IEnumerable<string> AddSynonyms() //public void AddSynonyms(IEnumerable<string> synonyms)
    {
        var words = AddSynonyms.Distinct().ToList();
        foreach (var word in words)
        {
            var currentWordSynonyms = words.Where(s => s == word);
            if (lookup.ContainsKey(word))
            {
                foreach (var synonym in currentWordSynonyms)
                {
                    if (!lookup[word].Contains(synonym))
                        lookup[word].Add(synonym);
                }
            }
            else
            {
                lookup.Add(word.currentWordSynonyms);
            }

        }
    }

    public IEnumerable<string> GetSynonyms(string word)
    {
        if (lookup.ContainsKey(word))
            return lookup[word];
        return Enumerable.Empty<string>();
        // Or throw an exception.
    }

    public IEnumerable<string> GetWords()
    {
        return lookup.Keys();
    }
}

class MainClass
{

    static void Main()
    {
        // Declare an interface instance.
        IThesaurus obj = new Thesaurus();

        // Call the member.
        obj.AddSynonyms();
        obj.GetSynonyms();
        obj.GetWords();
    }
}

}

Body:
Got compiler errors out :

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Thesaurus
{

    class MainClass
    {

        static void Main(string[] args)
        {
            // Declare an interface instance.
            IThesaurus obj = new Thesaurus();
            List<string> words = new List<string>();

            // Call the member.
            obj.AddSynonyms(words);
            obj.GetSynonyms(words[0]);
            obj.GetWords();
        }
    }
    //<summary>
    /// Represents a thesaurus.
    /// </summary>
    public interface IThesaurus
    {
        /// <summary>
        /// Adds the given synonyms to the thesaurus
        /// </summary>
        /// <param name="synonyms">The synonyms to add.</param>
        void AddSynonyms(IEnumerable<string> synonyms);

        /// <summary>
        /// Gets the synonyms for a given word.
        /// </summary>
        /// <param name="word">The word the synonyms of which to get.</param>
        /// <returns>A <see cref="string"/> with all synonyms for the given word.</returns>
        IEnumerable<string> GetSynonyms(string word);

        /// <summary>
        /// Gets all words from the thesaurus.
        /// </summary>
        /// <returns>An <see cref="IEnumerable<string>"/> containing
        /// all the words in the thesaurus.</returns>
        IEnumerable<string> GetWords();
    }

    public class Thesaurus : IThesaurus
    {
        private Dictionary<string, List<string>> lookup =
            new Dictionary<string, List<string>>();

        public void AddSynonyms(IEnumerable<string> allWords) //public void AddSynonyms(IEnumerable<string> synonyms)
        {
            var words = allWords.Distinct().ToList();
            foreach (var word in words)
            {
                var currentWordSynonyms = words.Where(s => s == word);
                if (lookup.ContainsKey(word))
                {
                    foreach (var synonym in currentWordSynonyms)
                    {
                        if (!lookup[word].Contains(synonym))
                            lookup[word].Add(synonym);
                    }
                }
                else
                {
                    List<string> newSynonyms =  new List<string>();
                    newSynonyms.AddRange(currentWordSynonyms);
                    lookup.Add(word, newSynonyms);
                }

            }
        }

        public IEnumerable<string> GetSynonyms(string word)
        {
            if (lookup.ContainsKey(word))
                return lookup[word];
            return Enumerable.Empty<string>();
            // Or throw an exception.
        }

        public IEnumerable<string> GetWords()
        {
            return lookup.AsEnumerable().Select(x => x.Key).ToList();
        }
    }

}


问:
Passing argument by void** to function
I'm trying to pass arguments by a function using a void * to give any type of arguments. But for some reasons I don't understand, no data can be read inside of the function.

This is a reproduced behaviour of a company function.
Live on Coliru

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

typedef struct
{
    double d1, d2;
} S;

double doStuff(void ** args)
{
    double * a = (double*)args;

    printf("a[0] = %lf\n", a[0]);
    printf("a[1] = %lf\n", a[1]);

    double r = a[0] + a[1];
    return r;
}

int main(void) {

    S s;
    s.d1 = 10.0;
    s.d2 = 10.0;

    S* ptr = &s;

    void* args[2];
    args[0] = &ptr->d1;
    args[1] = &ptr->d2;

    double d = doStuff(args);

    printf("d = %lf\n", d);

    return 0;
}
</code>```

And it's output

```<code>a[0] = 0.000000
a[1] = 0.000000
d = 0.000000
</code>```

答:
You should change your code to:

```<code>double doStuff(void ** args)
{
    double ** a = (double**)args;

    printf("a[0] = %lf\n", *a[0]);
    printf("a[1] = %lf\n", *a[1]);

    double r = *a[0] + *a[1];
    return r;
}
</code>```

EDIT

The OP asked for a change in main instead of doStuff (which s/he does not own).

Now, as noted by @Eugene Sh, the function doStuff is crippled because it asks for a double pointer argument, but uses as a pointer to double.

The change in main is just pass around a pointer to double, but cast to void** just to make the compiler happy:

```<code>int main(void) {

    S s;
    s.d1 = 10.0;
    s.d2 = 10.0;

    S* ptr = &s;

    double args[2];     // our pointer to double
    args[0] = ptr->d1;
    args[1] = ptr->d2;

    double d = doStuff((void**)args); // cast to void**

    printf("d = %lf\n", d);

    return 0;
}
</code>```

Title: Passing argument by void** to function

Body:
I'm trying to pass arguments by a function using a void * to give any type of arguments. But for some reasons I don't understand, no data can be read inside of the function.

This is a reproduced behaviour of a company function.
Live on Coliru

#include <stdio.h>

typedef struct
{
    double d1, d2;
} S;

double doStuff(void ** args)
{
    double * a = (double*)args;

    printf("a[0] = %lf\n", a[0]);
    printf("a[1] = %lf\n", a[1]);

    double r = a[0] + a[1];
    return r;
}

int main(void) {

    S s;
    s.d1 = 10.0;
    s.d2 = 10.0;

    S* ptr = &s;

    void* args[2];
    args[0] = &ptr->d1;
    args[1] = &ptr->d2;

    double d = doStuff(args);

    printf("d = %lf\n", d);

    return 0;
}

And it's output

a[0] = 0.000000
a[1] = 0.000000
d = 0.000000

Body:
You should change your code to:

double doStuff(void ** args)
{
    double ** a = (double**)args;

    printf("a[0] = %lf\n", *a[0]);
    printf("a[1] = %lf\n", *a[1]);

    double r = *a[0] + *a[1];
    return r;
}

EDIT

The OP asked for a change in main instead of doStuff (which s/he does not own).

Now, as noted by @Eugene Sh, the function doStuff is crippled because it asks for a double pointer argument, but uses as a pointer to double.

The change in main is just pass around a pointer to double, but cast to void** just to make the compiler happy:

int main(void) {

    S s;
    s.d1 = 10.0;
    s.d2 = 10.0;

    S* ptr = &s;

    double args[2];     // our pointer to double
    args[0] = ptr->d1;
    args[1] = ptr->d2;

    double d = doStuff((void**)args); // cast to void**

    printf("d = %lf\n", d);

    return 0;
}


问:
Converting a CGGradient to a CAGradientLayer
I'm using a PaintCode StyleKit to generate a bunch of gradients, but PaintCode exports them as a CGGradient. I wanted to add these gradients a layer. Is it possible to convert a CGGradient to a CAGradientLayer?

答:
This can be important if you have a library of gradients and only occasionally need to use a gradient in one of the two formats.

Yes, it is possible, but requires some math to convert from a regular coordinate system (with x values from 0 to the width and y values from 0 to the height) to the coordinate system used by CAGradientLayer (with x values from 0 to 1 and y values from 0 to 1). And it requires some more math (quite complex) to get the slope right.

The distance from 0 to 1 for x will depend on the width of the original rectangle. And the distance from 0 to 1 for y will depend on the height of the original rectangle. So:

```<code>let convertedStartX = startX/Double(width)
let convertedStartY = startY/Double(height)
let convertedEndX = endX/Double(width)
let convertedEndY = endY/Double(height)

let intermediateStartPoint = CGPoint(x:convertedStartX,y:convertedStartY)
let intermediateEndPoint = CGPoint(x:convertedEndX,y:convertedEndY)
</code>```

This works if your original rectangle was a square. If not, the slope of the line that defines the angle of the gradient will be wrong! To fix this see the excellent answer here: CAGradientLayer diagonal gradient

If you pick up the utility from there, then you can set your final converted start and end points as follows, starting with the already-adjusted point values from above:

```<code>let fixedStartEnd:(CGPoint,CGPoint) = LinearGradientFixer.fixPoints(start: intermediateStartPoint, end: intermediateEndPoint, bounds: CGSize(width:width,height:height))

let myGradientLayer = CAGradientLayer()
myGradientLayer.startPoint = fixedStartEnd.0
myGradientLayer.endPoint = fixedStartEnd.1
</code>```

Here's code for a full Struct that you can use to store gradient data and get back CGGradients or CAGradientLayers as needed:

```<code>import UIKit

struct UniversalGradient {

    //Doubles are more precise than CGFloats for the
    //calculations needed to convert start and end
    //to CAGradientLayers 1...0 format

    var startX: Double
    var startY: Double
    var endX: Double
    var endY: Double

    let options: CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation]

    //for CAGradientLayer
    var colors: [UIColor]
    var locations: [Double]

    //computed conversions
    private var myCGColors: [CGColor] {
        return self.colors .map {color in color.cgColor}
    }

    private var myCGFloatLocations: [CGFloat] {
        return self.locations .map {location in CGFloat(location)}
    }

    //computed properties
    var gradient: CGGradient {
        return CGGradient(colorsSpace: nil, colors: myCGColors as CFArray, locations: myCGFloatLocations)!
    }

    var start: CGPoint {
        return CGPoint(x: startX,y: startY)
    }
    var end: CGPoint {
        return CGPoint(x: endX,y: endY)
    }

    //can't use computed property here
    //since we need details of the specific environment's bounds to be passed in
    //so this will be an instance function

    func gradientLayer(width: CGFloat, height: CGFloat) -> CAGradientLayer {

        //convert location x and y values from full coordinates to 0...1 for start and end
        //this works great for position, but it gets the slope incorrect if the view is not square

        //this is because the gradient is not drawn with the final scale
        //it is drawn while the view is square, and then it gets stretched, changing the angle
        //https://stackoverflow.com/questions/38821631/cagradientlayer-diagonal-gradient

        let convertedStartX = startX/Double(width)
        let convertedStartY = startY/Double(height)
        let convertedEndX = endX/Double(width)
        let convertedEndY = endY/Double(height)

        let intermediateStartPoint = CGPoint(x:convertedStartX,y:convertedStartY)
        let intermediateEndPoint = CGPoint(x:convertedEndX,y:convertedEndY)

        let fixedStartEnd:(CGPoint,CGPoint) = LinearGradientFixer.fixPoints(start: intermediateStartPoint, end: intermediateEndPoint, bounds: CGSize(width:width,height:height))

        let myGradientLayer = CAGradientLayer()
        myGradientLayer.startPoint = fixedStartEnd.0
        myGradientLayer.endPoint = fixedStartEnd.1

        myGradientLayer.locations = self.locations .map {location in NSNumber(value: location)}
        myGradientLayer.colors = self.colors .map {color in color.cgColor}

        return myGradientLayer
    }

}
</code>```

Body:
This can be important if you have a library of gradients and only occasionally need to use a gradient in one of the two formats.

Yes, it is possible, but requires some math to convert from a regular coordinate system (with x values from 0 to the width and y values from 0 to the height) to the coordinate system used by CAGradientLayer (with x values from 0 to 1 and y values from 0 to 1). And it requires some more math (quite complex) to get the slope right.

The distance from 0 to 1 for x will depend on the width of the original rectangle. And the distance from 0 to 1 for y will depend on the height of the original rectangle. So:

let convertedStartX = startX/Double(width)
let convertedStartY = startY/Double(height)
let convertedEndX = endX/Double(width)
let convertedEndY = endY/Double(height)

let intermediateStartPoint = CGPoint(x:convertedStartX,y:convertedStartY)
let intermediateEndPoint = CGPoint(x:convertedEndX,y:convertedEndY)

This works if your original rectangle was a square. If not, the slope of the line that defines the angle of the gradient will be wrong! To fix this see the excellent answer here: CAGradientLayer diagonal gradient

If you pick up the utility from there, then you can set your final converted start and end points as follows, starting with the already-adjusted point values from above:

let fixedStartEnd:(CGPoint,CGPoint) = LinearGradientFixer.fixPoints(start: intermediateStartPoint, end: intermediateEndPoint, bounds: CGSize(width:width,height:height))

let myGradientLayer = CAGradientLayer()
myGradientLayer.startPoint = fixedStartEnd.0
myGradientLayer.endPoint = fixedStartEnd.1

Here's code for a full Struct that you can use to store gradient data and get back CGGradients or CAGradientLayers as needed:

import UIKit

struct UniversalGradient {

    //Doubles are more precise than CGFloats for the
    //calculations needed to convert start and end
    //to CAGradientLayers 1...0 format

    var startX: Double
    var startY: Double
    var endX: Double
    var endY: Double

    let options: CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation]

    //for CAGradientLayer
    var colors: [UIColor]
    var locations: [Double]

    //computed conversions
    private var myCGColors: [CGColor] {
        return self.colors .map {color in color.cgColor}
    }

    private var myCGFloatLocations: [CGFloat] {
        return self.locations .map {location in CGFloat(location)}
    }

    //computed properties
    var gradient: CGGradient {
        return CGGradient(colorsSpace: nil, colors: myCGColors as CFArray, locations: myCGFloatLocations)!
    }

    var start: CGPoint {
        return CGPoint(x: startX,y: startY)
    }
    var end: CGPoint {
        return CGPoint(x: endX,y: endY)
    }

    //can't use computed property here
    //since we need details of the specific environment's bounds to be passed in
    //so this will be an instance function

    func gradientLayer(width: CGFloat, height: CGFloat) -> CAGradientLayer {

        //convert location x and y values from full coordinates to 0...1 for start and end
        //this works great for position, but it gets the slope incorrect if the view is not square

        //this is because the gradient is not drawn with the final scale
        //it is drawn while the view is square, and then it gets stretched, changing the angle
        //https://stackoverflow.com/questions/38821631/cagradientlayer-diagonal-gradient

        let convertedStartX = startX/Double(width)
        let convertedStartY = startY/Double(height)
        let convertedEndX = endX/Double(width)
        let convertedEndY = endY/Double(height)

        let intermediateStartPoint = CGPoint(x:convertedStartX,y:convertedStartY)
        let intermediateEndPoint = CGPoint(x:convertedEndX,y:convertedEndY)

        let fixedStartEnd:(CGPoint,CGPoint) = LinearGradientFixer.fixPoints(start: intermediateStartPoint, end: intermediateEndPoint, bounds: CGSize(width:width,height:height))

        let myGradientLayer = CAGradientLayer()
        myGradientLayer.startPoint = fixedStartEnd.0
        myGradientLayer.endPoint = fixedStartEnd.1

        myGradientLayer.locations = self.locations .map {location in NSNumber(value: location)}
        myGradientLayer.colors = self.colors .map {color in color.cgColor}

        return myGradientLayer
    }

}


问:
How do I access the first key of an ‘associative’ array in JavaScript?
I have a js 'associative' array, with

```<code>array['serial_number'] = 'value'
</code>```

serial_number and value are strings.
e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine.
Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with

```<code>for (var i in sorted)
</code>```

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).

答:
Actually JavaScript doesn't support associative arrays, so you can't loop through it in an implied order (e.g. you can't access it via the indexer property array[0] won't access the first element in your object).  The  syntax is what makes it look like it does, but in reality it doesn't.  So you have no "Order" to your objects.

http://www.hunlock.com/blogs/Mastering_Javascript_Arrays

Javascript does not have, and does not
  support Associative Arrays. However…
  All arrays in Javascript are objects
  and Javascript's object syntax gives a
  basic emulation of an associative
  Array. For this reason the example
  code above will actually work. Be
  warned that this is not a real array
  and it has real pitfals if you try to
  use it. The 'person' element in the
  example becomes part of the Array
  object's properties and methods, just
  like .length, .sort(), .splice(), and
  all the other built-in properties and
  methods.

Body:
I have a js 'associative' array, with

array['serial_number'] = 'value'

serial_number and value are strings.
e.g. array['20910930923'] = '20101102'

I sorted it by value, works fine.
Let's say I get back the object 'sorted';

Now I want to access the first KEY of the 'sorted' array.
How do I do it? I can't think I need an iteration with

for (var i in sorted)

and just stop after ther first one...

thanks

edit: just to clarify, I know that js does not support associative arrays (that's why I put it in high commas in the Title).


问:
Trying to install libsndfile on Ubuntu 16
I've tried running

```<code>sudo apt-get install libsndfile
> E: Unable to locate package libsndfile
</code>```

So then I try

```<code>sudo apt-get install libsndfile1
</code>```

It installs, but where, how?

```<code>find /usr/ -name libsndfile*
> /usr/lib/x86_64-linux-gnu/libsndfile.so.1
> /usr/lib/x86_64-linux-gnu/libsndfile.so.1.0.25
</code>```

At the end of the day my goal is to get the lib to work for ruby, with either:

```<code>gem install sndfile
gem install ruby-audio
</code>```

When I try installing ruby-audio, I get:

```<code>extconf.rb:21:in `<main>':   Can't find libsndfile (http://www.mega-nerd.com/libsndfile/) (RuntimeError)
</code>```

So for some reason the library doesn't install properly.

答:
When you want to compile something against a library you'll need not only the library itself, which is usually one or more .so type files, but the header files that describe how the library works. These are often omitted unless you install the -dev version of the package:

```<code>apt-get install libsndfile-dev
</code>```

This should give the Ruby extconf.rb enough information to compile and link against that library.

Body:
I've tried running

sudo apt-get install libsndfile
> E: Unable to locate package libsndfile

So then I try

sudo apt-get install libsndfile1

It installs, but where, how?

find /usr/ -name libsndfile*
> /usr/lib/x86_64-linux-gnu/libsndfile.so.1
> /usr/lib/x86_64-linux-gnu/libsndfile.so.1.0.25

At the end of the day my goal is to get the lib to work for ruby, with either:

gem install sndfile
gem install ruby-audio

When I try installing ruby-audio, I get:

extconf.rb:21:in `':   Can't find libsndfile (http://www.mega-nerd.com/libsndfile/) (RuntimeError)

So for some reason the library doesn't install properly.

Body:
When you want to compile something against a library you'll need not only the library itself, which is usually one or more .so type files, but the header files that describe how the library works. These are often omitted unless you install the -dev version of the package:

apt-get install libsndfile-dev

This should give the Ruby extconf.rb enough information to compile and link against that library.


问:
Items in linear layout don't fit properly on screen
I am using a linear layout to display image views wrappedh inside a relative layout. I want the image views to appear occupy to the whole width of the screen horizontally with no spaces in between for all screen types.
However, i still get unwanted spaces between the views. I need help on this.</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back_main"
    tools:context="com.example.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        android:layout_alignParentBottom="true">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_audio"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_event"/>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_video" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_more"/>
    </LinearLayout>

</RelativeLayout>
</code>```

答:
Maybe the following Layout do the trick (I modified the code from your question. Modify according your needs)

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back_main"
tools:context="com.example.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:src="@drawable/foo" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:src="@drawable/bar"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:src="@drawable/foobar"/>

</LinearLayout>
</code>```

Depending the images you're using, consider using a "android:scaleType" in the ImageViews.

Body:
I am using a linear layout to display image views wrappedh inside a relative layout. I want the image views to appear occupy to the whole width of the screen horizontally with no spaces in between for all screen types.
However, i still get unwanted spaces between the views. I need help on this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back_main"
    tools:context="com.example.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        android:layout_alignParentBottom="true">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_audio"/>

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_event"/>

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_video" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="56dp"
            android:layout_weight="0.25"
            android:src="@drawable/img_more"/>
    </LinearLayout>

</RelativeLayout>

Body:
Maybe the following Layout do the trick (I modified the code from your question. Modify according your needs)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/back_main"
tools:context="com.example.MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:src="@drawable/foo" />

    <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:src="@drawable/bar"/>

    <ImageView
        android:layout_width="0dp"
        android:layout_height="56dp"
        android:layout_weight="1"
        android:src="@drawable/foobar"/>

</LinearLayout>

Depending the images you're using, consider using a "android:scaleType" in the ImageViews.


问:
How do you replace arbitrary characters with a string in Java?
I'm trying to create a method that replaces an individual character in a string with another string so far, these are my parameters.

public static String replaceAt(String str, int position, String replacement)

It's supposed to look something like this when it runs correctly:

```<code>method         input                          output

replaceAt     "Hello, World", 5, " comma"     Hello comma World
</code>```

This is what I have so far.

```<code>{
   String result = "";

  char character = str.charAt(position);

  str = str.replace(character, replacement);

  result = str;

  return result;
 }
</code>```

but I'm pretty sure I'm messing up the syntax somehow, any pointers on how to proceed?

答:
The biggest problem with using replace, or other solutions that search for regexes, is that we don't know whether the character at that position is the only one in the string.  Suppose the input string is "Hello, world, good morning".  Then your replaceAt would return "Hello comma world comma good morning".  Maybe that's what you really want (it isn't clear), but a method that pretends to be one that "replaces" the character "at" the given "position" with a string, shouldn't do more than that.  (If that's really what you want, I recommend changing the name and the parameters.)

Assuming you want to replace the character at that position, and only the character at that position, I'd recommend using substring instead:

```<code>public static String replaceAt(String str, int position, String replacement) {
    return str.substring(0, position) + replacement + str.substring(position + 1);
}
</code>```

Edit: If you want to handle the case where position == the string length, so that there is no character at that position:

```<code>public static String replaceAt(String str, int position, String replacement) {
    return str.substring(0, position) + replacement + (position == str.length() ? "" : str.substring(position + 1));
}
</code>```

(If position > the string length, the first substring won't work.  Depending on the use case, you can let it throw an exception if this case isn't supposed to happen.  Or you could do this:)

```<code>public static String replaceAt(String str, int position, String replacement) {
    return str.substring(0, Math.min(position, str.length())) + replacement + (position >= str.length() ? "" : str.substring(position + 1));
}
</code>```

Body:
I'm trying to create a method that replaces an individual character in a string with another string so far, these are my parameters.

public static String replaceAt(String str, int position, String replacement)

It's supposed to look something like this when it runs correctly:

method         input                          output

replaceAt     "Hello, World", 5, " comma"     Hello comma World

This is what I have so far.

{
   String result = "";

  char character = str.charAt(position);

  str = str.replace(character, replacement);

  result = str;

  return result;
 }

but I'm pretty sure I'm messing up the syntax somehow, any pointers on how to proceed?

Body:
The biggest problem with using replace, or other solutions that search for regexes, is that we don't know whether the character at that position is the only one in the string.  Suppose the input string is "Hello, world, good morning".  Then your replaceAt would return "Hello comma world comma good morning".  Maybe that's what you really want (it isn't clear), but a method that pretends to be one that "replaces" the character "at" the given "position" with a string, shouldn't do more than that.  (If that's really what you want, I recommend changing the name and the parameters.)

Assuming you want to replace the character at that position, and only the character at that position, I'd recommend using substring instead:

public static String replaceAt(String str, int position, String replacement) {
    return str.substring(0, position) + replacement + str.substring(position + 1);
}

Edit: If you want to handle the case where position == the string length, so that there is no character at that position:

public static String replaceAt(String str, int position, String replacement) {
    return str.substring(0, position) + replacement + (position == str.length() ? "" : str.substring(position + 1));
}

(If position > the string length, the first substring won't work.  Depending on the use case, you can let it throw an exception if this case isn't supposed to happen.  Or you could do this:)

public static String replaceAt(String str, int position, String replacement) {
    return str.substring(0, Math.min(position, str.length())) + replacement + (position >= str.length() ? "" : str.substring(position + 1));
}


答:
If you can use StringBuilder, then you could instantiate one with your input str and then call StringBuilder#replace(int, int, String) like

```<code>public static String replaceAt(String str, int position, String replacement) {
    return new StringBuilder(str).replace(position, position + 1,
            replacement).toString();
}
</code>```

If you can't use that, then you might use String#substring(int, int) and concatenate your output like

```<code>return str.substring(0, position) + replacement + str.substring(position + 1);
</code>```

Note that internally uses StringBuilder to perform the concatenation (at least in recent Java releases), so it is equivalent to

```<code>return new StringBuilder(str.substring(0, position)).append(replacement)
        .append(str.substring(position + 1)).toString();
</code>```

(in very old releases StringBuffer was used).

Title: How do you replace arbitrary characters with a string in Java?

Body:
If you can use StringBuilder, then you could instantiate one with your input str and then call StringBuilder#replace(int, int, String) like

public static String replaceAt(String str, int position, String replacement) {
    return new StringBuilder(str).replace(position, position + 1,
            replacement).toString();
}

If you can't use that, then you might use String#substring(int, int) and concatenate your output like

return str.substring(0, position) + replacement + str.substring(position + 1);

Note that internally uses StringBuilder to perform the concatenation (at least in recent Java releases), so it is equivalent to

return new StringBuilder(str.substring(0, position)).append(replacement)
        .append(str.substring(position + 1)).toString();

(in very old releases StringBuffer was used).


问:
ERROR StatusLogger Reconfiguration failed: No configuration found for '511d50c0' at 'null' in 'null'
I am new to Storm. I installed zookeeper, storm , java im my local machine. Zookeeper is working fine. When I tried to run nimbus using the command storm nimbus, I am getting the following error.

ERROR StatusLogger Unable to access file:///log4j2/cluster.xml
ERROR StatusLogger Reconfiguration failed: No configuration found for '511d50c0' at 'null' in 'null'

I checked the storm.yaml file and its all perfect. Can somebody help me out in solving this.

答:
What is your storm version?

In newer versions,The problem is caused by the old configuration of config file: storm/conf/storm.yaml. In version 1.1 of storm, instead of nimbus.host, use nimbus.seeds.