问:
Reference Xml file from csv column and then add a corresponding column to the xml files
I have a situation where there is 10 000 XML files, and then a csv file that has more information for each of those xml files. I need a powershell script to reference the filename from the csv file, and add information from one of the columns next to it to XML file that is referencing.

I have no idea how to accomplish this.

答:
We can load an XML file easily in PowerShell.  Imagine an XML file called Data.xml that looks like this:

```<code><--.\Data.xml-->
<?xml version="1.0" encoding="utf-8"?>
<Data version="2.0">
  <Roles>
    <Role Name="ManagementServer" Value="NewManagementServer" />
    <Role Name="ADServer" Value="NewADServer" />
    <Role Name="ADServer" Value="NewADServer" />
  </Roles>
  <SQL>
    <Instance Server="NewSQLServer" Instance="MSSQLSERVER" Version="SQL Server 2012">
      <Variable Name="SQLAdmin" Value="Domain\NewSQlAdmin" />
      <Variable Name="SQLUser" Value="domain\sqluser" />
    </Instance>
  </SQL>
</AllContacts>
</Data>
</code>```

We can load the file in PowerShell with these commands.

```<code>$file = (get-content .\data.xml) -as [XML]
</code>```

We can then view the XML file as an object, or even select nodes like so:

```<code>#Display some particular sub-nodes
$file.Data.Roles.Role

Name             Value
----             -----
ManagementServer NewManagementServer
ADServer         NewADServer
ADServer         NewADServer
</code>```

We can add nodes too!

```<code>#Create a new XML element
$newRole = $xml.CreateElement("Role")

#set the values
$newRole.SetAttribute("Name","MyNewElement")
$newRole.SetAttribute("Value","MyNewValue")

#add it to the collection
$file.Data.roles.AppendChild($newRole)

#save it
$file.Save('c:\temp.data.xml')
</code>```

I haven't touched on how to pull the info from a .csv file yet, but I can update once you provide additional information.

Body:
We can load an XML file easily in PowerShell.  Imagine an XML file called Data.xml that looks like this:

<--.\Data.xml-->
<?xml version="1.0" encoding="utf-8"?>
<Data version="2.0">
  <Roles>
    <Role Name="ManagementServer" Value="NewManagementServer" />
    <Role Name="ADServer" Value="NewADServer" />
    <Role Name="ADServer" Value="NewADServer" />
  </Roles>
  <SQL>
    <Instance Server="NewSQLServer" Instance="MSSQLSERVER" Version="SQL Server 2012">
      <Variable Name="SQLAdmin" Value="Domain\NewSQlAdmin" />
      <Variable Name="SQLUser" Value="domain\sqluser" />
    </Instance>
  </SQL>
</AllContacts>
</Data>

We can load the file in PowerShell with these commands.

$file = (get-content .\data.xml) -as [XML]

We can then view the XML file as an object, or even select nodes like so:

#Display some particular sub-nodes
$file.Data.Roles.Role

Name             Value
----             -----
ManagementServer NewManagementServer
ADServer         NewADServer
ADServer         NewADServer

We can add nodes too!

#Create a new XML element
$newRole = $xml.CreateElement("Role")

#set the values
$newRole.SetAttribute("Name","MyNewElement")
$newRole.SetAttribute("Value","MyNewValue")

#add it to the collection
$file.Data.roles.AppendChild($newRole)

#save it
$file.Save('c:\temp.data.xml')

I haven't touched on how to pull the info from a .csv file yet, but I can update once you provide additional information.


来源: stackexchange

问:
SELECTing Related Rows Based on a Single Row Match
I have the following table running on Postgres SQL 9.5:

```<code>+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
|10 | 4567890    | abc123-ab   |
|11 | 4567890    | gex890-aj   |
|12 | 4567890    | ghi567-ef   |
+---+------------+-------------+
</code>```

I am looking for the rows for each trans_id based on a LIKE query, like this:

```<code>SELECT * FROM table
WHERE message LIKE '%def-234%'
</code>```

This, of course, returns just three rows, the three that match my pattern in the message column. What I am looking for, instead, is all the rows matching that trans_id in groups of messages that match. That is, if a single row matches the pattern, get all the rows with the trans_id of that matching row.

That is, the results would be:

```<code>+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
+---+------------+-------------+
</code>```

Notice rows 10, 11, and 12 were not SELECTed because there was not one of them that matched the %def-234% pattern.

I have tried (and failed) to write a sub-query to get the all the related rows when a single message matches a pattern:

```<code>SELECT sub.*
    FROM (
        SELECT DISTINCT trans_id FROM table WHERE message LIKE '%def-234%'
    ) sub
WHERE table.trans_id = sub.trans_id
</code>```

I could easily do this with two queries, but the first query to get a list of matching trans_ids to include in a WHERE trans_id IN (<huge list of trans_ids>) clause would be very large, and would not be a very inefficient way of doing this, and I believe there exists a way to do it with a single query.

Thank you!

答:
Try this:

```<code>SELECT ID, trans_id, message
FROM (
   SELECT ID, trans_id, message,
          COUNT(*) FILTER (WHERE message LIKE '%def234%')
                   OVER (PARTITION BY trans_id)  AS pattern_cnt
   FROM mytable) AS t
WHERE pattern_cnt >= 1
</code>```

Using a FILTER clause in the windowed version of COUNT function we can get the number of records matching the predefined pattern within each trans_id slice. The outer query uses this count to filter out irrelevant slices.

Demo here

ContentLicense: CC BY-SA 3.0

Body:
I have the following table running on Postgres SQL 9.5:

+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
|10 | 4567890    | abc123-ab   |
|11 | 4567890    | gex890-aj   |
|12 | 4567890    | ghi567-ef   |
+---+------------+-------------+

I am looking for the rows for each trans_id based on a LIKE query, like this:

SELECT * FROM table
WHERE message LIKE '%def-234%'

This, of course, returns just three rows, the three that match my pattern in the message column. What I am looking for, instead, is all the rows matching that trans_id in groups of messages that match. That is, if a single row matches the pattern, get all the rows with the trans_id of that matching row.

That is, the results would be:

+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
+---+------------+-------------+

Notice rows 10, 11, and 12 were not SELECTed because there was not one of them that matched the %def-234% pattern.

I have tried (and failed) to write a sub-query to get the all the related rows when a single message matches a pattern:

SELECT sub.*
    FROM (
        SELECT DISTINCT trans_id FROM table WHERE message LIKE '%def-234%'
    ) sub
WHERE table.trans_id = sub.trans_id

I could easily do this with two queries, but the first query to get a list of matching trans_ids to include in a WHERE trans_id IN (<huge list of trans_ids>) clause would be very large, and would not be a very inefficient way of doing this, and I believe there exists a way to do it with a single query.

Thank you!

Body:
Try this:

SELECT ID, trans_id, message
FROM (
   SELECT ID, trans_id, message,
          COUNT(*) FILTER (WHERE message LIKE '%def234%')
                   OVER (PARTITION BY trans_id)  AS pattern_cnt
   FROM mytable) AS t
WHERE pattern_cnt >= 1

Using a FILTER clause in the windowed version of COUNT function we can get the number of records matching the predefined pattern within each trans_id slice. The outer query uses this count to filter out irrelevant slices.

Demo here


问:
Vertical lines to points in scatter plot
Suppose I have a set of points x and a set of corresponding data y. I now plot these in a scatter plot, plt.scatter(x,y). The figure I get contains some x axis tick generated by matplotlib. Is there a way I can attain the automatic ticking, but to add vertical lines from the x-axis to the point in the scatter and label them?

答:
Well, there is a stem method, much easier to use:

```<code>import matplotlib.pyplot as plt
import numpy as np

x, y = np.random.random((2, 20))

fig, ax = plt.subplots()
ax.stem(x, y, markerfmt=' ')
plt.show()
</code>```

If you want bullets on the top of lines, just remove markerfmt.

Body:
Well, there is a stem method, much easier to use:

import matplotlib.pyplot as plt
import numpy as np

x, y = np.random.random((2, 20))

fig, ax = plt.subplots()
ax.stem(x, y, markerfmt=' ')
plt.show()

If you want bullets on the top of lines, just remove markerfmt.


问:
How to obtain this ref to declaring class from Dojo gridx detailProvider (Dod module)
Using the Dojo framework.

I have a 2 nested grid. Grid 1 uses a Dod with a detailprovider to load details on demand when one clicks a expand icon. When pressed this opens a nested grid. I need to track changes made in both grids. In the declaring class I've got an array that keeps track on changes made. The problem is that I can't access the array from a detailprovider. Since I've to conform to the protocol which gridx later invokes. What can I do to obtain a ref to the declaring class

```<code>var myDeclaringClass = declare([_WidgetBase,_TemplatedMixin,_WidgetsInTemplateMixin], {
    array: [],

    initGrid: function(){
        var grid = new Grid({
            store: store,
            structure: columns,
            modules: [ {
                  moduleClass: Dod,
                  showExpando: true,
                  detailProvider: this.myDetailProvider
            }]
        });

        // .... grid.placeAt() .. grid.startup()
    },

    myDetailProvider: function(parentGrid, rowId, detailNode, rendered) {
        // construct Nested Grid ...

        // How to obtain this reference here?
        // to access this.array?

        rendered.callback();
        return rendered;
    }
    retrun myDeclaring;
}
</code>```

EDIT:
I have also tried with a static var like:

```<code>statics: { array: [] }
</code>```

But here I will stille need a instance ref to access it.

答:
Try something like this</p>

```<code> var myDeclaringClass = declare([_WidgetBase,_TemplatedMixin,_WidgetsInTemplateMixin], {
        array: [],
var globalref : this,//here i'm assigning 'this' i.e. class level ref to the variable

        initGrid: function(){
            var grid = new Grid({
                store: store,
                structure: columns,
                modules: [ {
                      moduleClass: Dod,
                      showExpando: true,
                      detailProvider: this.myDetailProvider
                }]
            });

            // .... grid.placeAt() .. grid.startup()
        },

        myDetailProvider: function(parentGrid, rowId, detailNode, rendered) {
            // construct Nested Grid ...

            // How to obtain this reference here?
            // to access this.array?
    globalref.array//should give you access to the array
            rendered.callback();
            return rendered;
        }
        retrun myDeclaring;
    }
</code>```

Body:
Using the Dojo framework.

I have a 2 nested grid. Grid 1 uses a Dod with a detailprovider to load details on demand when one clicks a expand icon. When pressed this opens a nested grid. I need to track changes made in both grids. In the declaring class I've got an array that keeps track on changes made. The problem is that I can't access the array from a detailprovider. Since I've to conform to the protocol which gridx later invokes. What can I do to obtain a ref to the declaring class

var myDeclaringClass = declare([_WidgetBase,_TemplatedMixin,_WidgetsInTemplateMixin], {
    array: [],

    initGrid: function(){
        var grid = new Grid({
            store: store,
            structure: columns,
            modules: [ {
                  moduleClass: Dod,
                  showExpando: true,
                  detailProvider: this.myDetailProvider
            }]
        });

        // .... grid.placeAt() .. grid.startup()
    },

    myDetailProvider: function(parentGrid, rowId, detailNode, rendered) {
        // construct Nested Grid ...

        // How to obtain this reference here?
        // to access this.array?

        rendered.callback();
        return rendered;
    }
    retrun myDeclaring;
}

EDIT:
I have also tried with a static var like:

statics: { array: [] }

But here I will stille need a instance ref to access it.

Body:
Try something like this

 var myDeclaringClass = declare([_WidgetBase,_TemplatedMixin,_WidgetsInTemplateMixin], {
        array: [],
var globalref : this,//here i'm assigning 'this' i.e. class level ref to the variable

        initGrid: function(){
            var grid = new Grid({
                store: store,
                structure: columns,
                modules: [ {
                      moduleClass: Dod,
                      showExpando: true,
                      detailProvider: this.myDetailProvider
                }]
            });

            // .... grid.placeAt() .. grid.startup()
        },

        myDetailProvider: function(parentGrid, rowId, detailNode, rendered) {
            // construct Nested Grid ...

            // How to obtain this reference here?
            // to access this.array?
    globalref.array//should give you access to the array
            rendered.callback();
            return rendered;
        }
        retrun myDeclaring;
    }


问:
How to display ripple animation on google map in Android?
I'm trying to set ripple animation on google map using specific Lat-Lng, please see this which exactly describes what I wants, I referred above link but unable to set animation on google map.

What I tried so far is-

My xml code:

```<code><com.test.custom.RippleBackground
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/rippleLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        app:rb_color="#0099CC"
        app:rb_duration="5000"
        app:rb_radius="32dp"
        app:rb_rippleAmount="4"
        app:rb_scale="6" >

        <ImageView
            android:id="@+id/imgMapProfile"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_centerInParent="true"
            android:src="@drawable/ic_profile_active" />
    </com.test.custom.RippleBackground>
</code>```

My Java code to place ripple on google map:

```<code> LatLng currentAddressLatLong;
                        currentAddressLatLong = new LatLng(gps.getLatitude(), gps.getLongitude());

                    RippleBackground rippleLayout=(RippleBackground)findViewById(R.id.rippleLayout);
                    rippleLayout.setVisibility(View.VISIBLE);
                    ImageView imgMapProfile=(ImageView)findViewById(R.id.imgMapProfile);

                    Bitmap markerUserBitmap = Comman.createDrawableFromView(NearByActivity.this, rippleLayout);
                    googleMap.addMarker(new MarkerOptions().position(currentAddressLatLong).icon(BitmapDescriptorFactory.fromBitmap(markerUserBitmap)));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentAddressLatLong));
                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(11));

                    rippleLayout.startRippleAnimation();

     // Convert a view to bitmap function
            public static Bitmap createDrawableFromView(Context context, View view)
            {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
                view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
                view.buildDrawingCache();
                Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

                Canvas canvas = new Canvas(bitmap);
                view.draw(canvas);

                return bitmap;
            }
</code>```

But the bitmap is not getting animate. please help. thanks a lot.

答:
Thanks to yeldos I just modfiy his code for adding a fade out effect at the end of the animation.

Add this line inside the overlay function

```<code>groundOverlay.setTransparency(animatedFraction);
</code>```

Just below

```<code>groundOverlay.setDimensions(i);
</code>```

Body:
I'm trying to set ripple animation on google map using specific Lat-Lng, please see this which exactly describes what I wants, I referred above link but unable to set animation on google map.

What I tried so far is-

My xml code:

<com.test.custom.RippleBackground
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/rippleLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        app:rb_color="#0099CC"
        app:rb_duration="5000"
        app:rb_radius="32dp"
        app:rb_rippleAmount="4"
        app:rb_scale="6" >

        <ImageView
            android:id="@+id/imgMapProfile"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_centerInParent="true"
            android:src="@drawable/ic_profile_active" />
    </com.test.custom.RippleBackground>

My Java code to place ripple on google map:

 LatLng currentAddressLatLong;
                        currentAddressLatLong = new LatLng(gps.getLatitude(), gps.getLongitude());

                    RippleBackground rippleLayout=(RippleBackground)findViewById(R.id.rippleLayout);
                    rippleLayout.setVisibility(View.VISIBLE);
                    ImageView imgMapProfile=(ImageView)findViewById(R.id.imgMapProfile);

                    Bitmap markerUserBitmap = Comman.createDrawableFromView(NearByActivity.this, rippleLayout);
                    googleMap.addMarker(new MarkerOptions().position(currentAddressLatLong).icon(BitmapDescriptorFactory.fromBitmap(markerUserBitmap)));
                    googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentAddressLatLong));
                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(11));

                    rippleLayout.startRippleAnimation();

     // Convert a view to bitmap function
            public static Bitmap createDrawableFromView(Context context, View view)
            {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                ((Activity)context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
                view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
                view.buildDrawingCache();
                Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

                Canvas canvas = new Canvas(bitmap);
                view.draw(canvas);

                return bitmap;
            }

But the bitmap is not getting animate. please help. thanks a lot.

Body:
Thanks to yeldos I just modfiy his code for adding a fade out effect at the end of the animation.

Add this line inside the overlay function

groundOverlay.setTransparency(animatedFraction);

Just below

groundOverlay.setDimensions(i);


问:
query ElasticSearch from JQuery (or Angular) : No Living connections
I'm starting with ES and at first time I just would like to make a simple test to ping my ES local instance, which is running, through JQuery or Angular.

I've made my own test using JQuery or I also followed this example : https://github.com/spalger/elasticsearch-angular-example

But I always get the same error : No Living connections.

I also tried through Java but there it works, I can query my ES local instance.

Thank you in advance for your ideas !

I'm using ES 2.4.6 but have the same issue with 5.6.2

答:
I saw you didn't specify the schema on your host. Try adding http:// to it.  It worked for me once I added that and used a server with CORS configured.

```<code>ExampleApp.service('client', function (esFactory) {
  return esFactory({
    host: 'http://localhost:9200',
    apiVersion: '2.3',
    log: 'trace'
  });
});
</code>```

It could also be that your ES server requires authentication.  Can you browse to the ES server without credentials?

Body:
I saw you didn't specify the schema on your host. Try adding http:// to it.  It worked for me once I added that and used a server with CORS configured.

ExampleApp.service('client', function (esFactory) {
  return esFactory({
    host: 'http://localhost:9200',
    apiVersion: '2.3',
    log: 'trace'
  });
});

It could also be that your ES server requires authentication.  Can you browse to the ES server without credentials?


问:
Am I babying the platform/hardware?
I can't tell if I'm being respectful and courteous to the user or if I'm unnecessarily handicapping the utility of my app in the name of treating the phone like a china doll.

I have a successful app in the Android Market. One main functionality is that it records sports stats from a game the user is scoring. The current level of detail is fairly basic: a row for each player and a field for each basic stat. However, I could conceivably dramatically increase the detail and level of usefulness of the app if I recorded additional information, blowing this up to numerous relational tables and conceivably thousands upon thousands of records.

My question is, is this a responsible thing to do? Up to this point, I've shied away from it, thinking that "it's just a phone" and "it's just SQLite", but I've never really looked at whether that's a legitimate reason to hold back on doing things that I wouldn't give a second thought to doing on a web or desktop app.

So with that, how much data (very quantifiable, I know) is it reasonable to expect a phone app to do in regards to storing and sifting through database records?

EDIT:
To be clear, I'm not simply talking about adding more fields as I know the impact of that is trivial. I'm talking about going from the level of detail of "This player has 5 singles and 3 homers" to storing information about each pitch that comprised each at-bat that lead to 5 singles and three homers. Obviously this will call for additional tables and conceivably a great many records.

答: Sounds like SQLite will do just fine for what you need. I wouldn't hesitate to push it's limits. It's a very well implemented product and should be able to handle what you describe. If you get to the point where your application is handling larger volumes of data (more than 100-200MB), you might want to consider Berkeley DB. Berkeley DB supports the SQLite3 API and provides additional data management capabilities that provide better performance, scalability and reliability than native SQLite, especially when dealing with larger data sets. - Dave</p>

ContentLicense: CC BY-SA 2.5

Title: Am I babying the platform/hardware?


问:
Resolve "Apple Mach-O Linker (ld) Error" with Ionic 3 and FCM
I build an Ionic 3 app and I try to use FCM to have push notifications.

I works in android. But when I try to deploy project on iOS I have this error : Apple Mach-O Linker (ld) Error.

I tried to remove and add iOS platform in my project but nothing better.

I open my project with .xcworkspace file, and I haven't Pod, I don't need it with Fcm. So this solution doesn't works for me ...
https://github.com/phonegap/phonegap-plugin-push/issues/1518

My Ionic Info :

```<code>cli packages: (/Users/ox/Documents/Mobile/ox/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 2.1.0
    Cordova Platforms  : ios 4.5.3
    Ionic Framework    : ionic-angular 3.6.1

System:

    ios-deploy : 1.9.2
    ios-sim    : 5.0.13
    Node       : v6.11.3
    npm        : 3.10.10
    OS         : macOS Sierra
    Xcode      : Xcode 9.1 Build version 9B55
</code>```

Any idea please ?

答:
I had this problem with Ionic1, it was related to CocoaPods used by FCM, OneSignal and others.

On your platform/ios/:

Try to start xcode from the .xcworkspace file. This should resolve the problem. At least resolved on other Ionic versions.

Body:
I build an Ionic 3 app and I try to use FCM to have push notifications.

I works in android. But when I try to deploy project on iOS I have this error : Apple Mach-O Linker (ld) Error.

I tried to remove and add iOS platform in my project but nothing better.

I open my project with .xcworkspace file, and I haven't Pod, I don't need it with Fcm. So this solution doesn't works for me ...
https://github.com/phonegap/phonegap-plugin-push/issues/1518

My Ionic Info :

cli packages: (/Users/ox/Documents/Mobile/ox/node_modules)

    @ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 2.1.0
    Cordova Platforms  : ios 4.5.3
    Ionic Framework    : ionic-angular 3.6.1

System:

    ios-deploy : 1.9.2
    ios-sim    : 5.0.13
    Node       : v6.11.3
    npm        : 3.10.10
    OS         : macOS Sierra
    Xcode      : Xcode 9.1 Build version 9B55

Any idea please ?


问:
how to check exist relation in eloquent query?
I am using the laravel polymorphic relation.

cartable model:

```<code>public function  objectable()
{
    return $this->morphTo();
}
</code>```

instructions model:

```<code>public function cartable()
{
    return $this->morphMany('PTA_OIMS\Cartable', 'objectable');
}
</code>```

reports model:

```<code>public function reports()
{
    return $this->morphMany('PTA_OIMS\Cartable', 'objectable');
}
</code>```

My instruction table has extra related table called instruction_logs.

But in the reports table, this relationship does not exist.
When my object is report this query has error. Because the reports.report_logs does not exist.

```<code>$data = Cartable::where('id', '=', $cartableID)
    ->with('objectable')
    ->with('objectable.objectable_logs.attachment') //line error
    ->with('box.position')
    ->with('box.assign.staff')
    ->first();

return $data;
</code>```

How to handle query if objectable_logs did not exist skip the line error?

答:
```<code>$data = Cartable::with([
    'objectable',
    'objectable.objectable_logs.attachment',
    'box.position',
    'box.assign.staff'
])->find($cartableID);

return $data;
</code>```

if attachment is a column in objectable_logs table, it should be like:

```<code>$data = Cartable::with([
    'objectable',
    'objectable.objectable_logs:objectable_id,attachment',
    'box.position',
    'box.assign.staff'
])->find($cartableID);

return $data;
</code>```

Body:
I am using the laravel polymorphic relation.

cartable model:

public function  objectable()
{
    return $this->morphTo();
}

instructions model:

public function cartable()
{
    return $this->morphMany('PTA_OIMS\Cartable', 'objectable');
}

reports model:

public function reports()
{
    return $this->morphMany('PTA_OIMS\Cartable', 'objectable');
}

My instruction table has extra related table called instruction_logs.

But in the reports table, this relationship does not exist.
When my object is report this query has error. Because the reports.report_logs does not exist.

$data = Cartable::where('id', '=', $cartableID)
    ->with('objectable')
    ->with('objectable.objectable_logs.attachment') //line error
    ->with('box.position')
    ->with('box.assign.staff')
    ->first();

return $data;

How to handle query if objectable_logs did not exist skip the line error?

Body:
$data = Cartable::with([
    'objectable',
    'objectable.objectable_logs.attachment',
    'box.position',
    'box.assign.staff'
])->find($cartableID);

return $data;

if attachment is a column in objectable_logs table, it should be like:

$data = Cartable::with([
    'objectable',
    'objectable.objectable_logs:objectable_id,attachment',
    'box.position',
    'box.assign.staff'
])->find($cartableID);

return $data;


问:
Export multiple sheets in a single PDF
Just wondering how I would be able to export a PDF file to contain multiple sheets, but not all in the workbook. I've been only been able to send single sheets as separate PDF attachments. Any insight on this would be great.</p>

```<code>  var url = ss.getUrl(); //gets url
  url = url.replace(/edit/,'');

  var url_ext = 'export?exportFormat=pdf&format=pdf' +
  '&size=letter' +
  '&portrait=false' +
  '&fitw=true' +
  '&sheetnames=false&printtitle=false' +
  '&pagenumbers=true&gridlines=false' +
  '&fzr=true' +
  '&gid=GID'

  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url + url_ext, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });
      var blob = response.getBlob().setName(sheet.getName() + '.pdf');
</code>```

答:
A guide has been written about this in this blog post by Andrew Roberts, the source code from that post is as follows:</p>

```<code>function convertSpreadsheetToPdf(email, spreadsheetId, sheetName, pdfName) {

  var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();
  spreadsheetId = spreadsheetId ? spreadsheetId : spreadsheet.getId()
  var sheetId = sheetName ? spreadsheet.getSheetByName(sheetName).getSheetId() : null;
  var pdfName = pdfName ? pdfName : spreadsheet.getName();
  var parents = DriveApp.getFileById(spreadsheetId).getParents();
  var folder = parents.hasNext() ? parents.next() : DriveApp.getRootFolder();
  var url_base = spreadsheet.getUrl().replace(/edit$/,'');

  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf

      // Print either the entire Spreadsheet or the specified sheet if optSheetId is provided
      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
      // following parameters are optional...
      + '&size=letter'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw=true'        // fit to width, false for actual size
      + '&sheetnames=false&printtitle=false&pagenumbers=false'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
    }
  }

  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  folder.createFile(blob);

  if (email) {

    var mailOptions = {
      attachments:blob
    }

    MailApp.sendEmail(
      email,
      "Here is a file named " + pdfName,
      "Please let me know if you have any questions or comments.",
      mailOptions);
  }

} // convertSpreadsheetToPdf()

function test() {

  var TEST_EMAIL = 'your email address'

  // Create a PDF containing all the tabs in the active spreadsheet, name it
  // after the spreadsheet, and email it
  convertSpreadsheetToPdf(TEST_EMAIL)

  // Create a PDF containing all the tabs in the spreadsheet specified, name it
  // after the spreadsheet, and email it
  convertSpreadsheetToPdf(TEST_EMAIL, '1r9INcnsyvSQmeduJWVYAvznOOYei9jeAjsy0acA3G1k')

  // Create a PDF just containing the tab 'Sheet2' in the active spreadsheet, specify a name, and email it
  convertSpreadsheetToPdf(TEST_EMAIL, null, 'Sheet2', 'PDF 3')
}
</code>```

Title: Export multiple sheets in a single PDF

Body:
Just wondering how I would be able to export a PDF file to contain multiple sheets, but not all in the workbook. I've been only been able to send single sheets as separate PDF attachments. Any insight on this would be great.

  var url = ss.getUrl(); //gets url
  url = url.replace(/edit/,'');

  var url_ext = 'export?exportFormat=pdf&format=pdf' +
  '&size=letter' +
  '&portrait=false' +
  '&fitw=true' +
  '&sheetnames=false&printtitle=false' +
  '&pagenumbers=true&gridlines=false' +
  '&fzr=true' +
  '&gid=GID'

  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url + url_ext, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });
      var blob = response.getBlob().setName(sheet.getName() + '.pdf');

Body:
A guide has been written about this in this blog post by Andrew Roberts, the source code from that post is as follows:

function convertSpreadsheetToPdf(email, spreadsheetId, sheetName, pdfName) {

  var spreadsheet = spreadsheetId ? SpreadsheetApp.openById(spreadsheetId) : SpreadsheetApp.getActiveSpreadsheet();
  spreadsheetId = spreadsheetId ? spreadsheetId : spreadsheet.getId()
  var sheetId = sheetName ? spreadsheet.getSheetByName(sheetName).getSheetId() : null;
  var pdfName = pdfName ? pdfName : spreadsheet.getName();
  var parents = DriveApp.getFileById(spreadsheetId).getParents();
  var folder = parents.hasNext() ? parents.next() : DriveApp.getRootFolder();
  var url_base = spreadsheet.getUrl().replace(/edit$/,'');

  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf

      // Print either the entire Spreadsheet or the specified sheet if optSheetId is provided
      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
      // following parameters are optional...
      + '&size=letter'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw=true'        // fit to width, false for actual size
      + '&sheetnames=false&printtitle=false&pagenumbers=false'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
    }
  }

  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  folder.createFile(blob);

  if (email) {

    var mailOptions = {
      attachments:blob
    }

    MailApp.sendEmail(
      email,
      "Here is a file named " + pdfName,
      "Please let me know if you have any questions or comments.",
      mailOptions);
  }

} // convertSpreadsheetToPdf()

function test() {

  var TEST_EMAIL = 'your email address'

  // Create a PDF containing all the tabs in the active spreadsheet, name it
  // after the spreadsheet, and email it
  convertSpreadsheetToPdf(TEST_EMAIL)

  // Create a PDF containing all the tabs in the spreadsheet specified, name it
  // after the spreadsheet, and email it
  convertSpreadsheetToPdf(TEST_EMAIL, '1r9INcnsyvSQmeduJWVYAvznOOYei9jeAjsy0acA3G1k')

  // Create a PDF just containing the tab 'Sheet2' in the active spreadsheet, specify a name, and email it
  convertSpreadsheetToPdf(TEST_EMAIL, null, 'Sheet2', 'PDF 3')
}


问:
How to find the midPoint of arc in SVG with javascript
I want to the mid point of arc in svg.. Can any one tell formula to find the midbpoint of arc.,</p>

答:
The answer to that question is not straightforward.  That's because in SVG arcs can be an elliptical arc. For example, what would you say is the midpoint on the following arc?

<svg width="200" height="200" viewBox="0 0 100 100">
  <path fill="none" stroke="black" stroke-width="2"
        d="M 20,75 A 21,50, 45, 1 1, 60,75"/>
</svg>```
</div>
</div>
</p>

<p>Anyway, without getting into complicated formulae, the simplest method is probably to take advantage of SVG's <code>pointAtLength()</code> method.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myarc = document.getElementById("myarc");

// Get the length of the path
var pathLen = myarc.getTotalLength();

// How far along the path to we want the position?
var pathDistance = pathLen * 0.5;

// Get the X,Y position
var midpoint = myarc.getPointAtLength(pathDistance)

// For fun, let's add a dot at that position to mark it.
var svg = myarc.ownerSVGElement;
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", midpoint.x);
circle.setAttribute("cy", midpoint.y);
circle.setAttribute("r", "5");
circle.setAttribute("fill", "red");
svg.appendChild(circle);</code>```

<svg width="200" height="200" viewBox="0 0 100 100">
  <path id="myarc" fill="none" stroke="black" stroke-width="2"
        d="M 20,75 A 21,50, 45, 1 1, 60,75"/>
</svg>```

Body:
The answer to that question is not straightforward.  That's because in SVG arcs can be an elliptical arc. For example, what would you say is the midpoint on the following arc?

<svg width="200" height="200" viewBox="0 0 100 100">
  <path fill="none" stroke="black" stroke-width="2"
        d="M 20,75 A 21,50, 45, 1 1, 60,75"/>
</svg>

Anyway, without getting into complicated formulae, the simplest method is probably to take advantage of SVG's pointAtLength() method.

var myarc = document.getElementById("myarc");

// Get the length of the path
var pathLen = myarc.getTotalLength();

// How far along the path to we want the position?
var pathDistance = pathLen * 0.5;

// Get the X,Y position
var midpoint = myarc.getPointAtLength(pathDistance)

// For fun, let's add a dot at that position to mark it.
var svg = myarc.ownerSVGElement;
var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
circle.setAttribute("cx", midpoint.x);
circle.setAttribute("cy", midpoint.y);
circle.setAttribute("r", "5");
circle.setAttribute("fill", "red");
svg.appendChild(circle);

<svg width="200" height="200" viewBox="0 0 100 100">
  <path id="myarc" fill="none" stroke="black" stroke-width="2"
        d="M 20,75 A 21,50, 45, 1 1, 60,75"/>
</svg>


问:
Copy database from one server to another using c#
I'm trying to create a windows application that copies a database from one server to another using the Transfer object
but end up having "The Integration Services component is not installed or you do not have permission to use it" error.
both servers have enterprise edition of sql server 2005 and the integration services component installed, the connection logins have full permissions as well. I really don't know what goes wrong here

```<code>            Server backFromServer = new Server(@"xx.xx.xx.xx");
            Server backToServer = new Server(@"xx.xx.xx.xx");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "username";
            backFromServer.ConnectionContext.Password = "password";

            backToServer.ConnectionContext.LoginSecure = false;
            backToServer.ConnectionContext.Login = "username";
            backToServer.ConnectionContext.Password = "password";

            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["databasesource"];

            Database backToDb = new Database();
            backToDb = backToServer.Databases["databasedest"];

            EventLog.WriteEntry(eventLogSource,"Loading databases successful!", EventLogEntryType.Information);

            Transfer dataTransfer = new Transfer(backFromDb);
            dataTransfer.CopyAllTables = true;
            dataTransfer.CopyAllObjects = false;
            dataTransfer.CopyData = true;
            dataTransfer.CopyAllUserDefinedDataTypes = true;
            dataTransfer.CopyAllStoredProcedures = false;

            dataTransfer.DropDestinationObjectsFirst = true;

            dataTransfer.Options.WithDependencies = false;

            dataTransfer.DestinationServer = backToServer.Name;
            dataTransfer.DestinationDatabase = backToDb.Name;
            dataTransfer.DestinationLoginSecure = false;
            dataTransfer.DestinationLogin = "username";
            dataTransfer.DestinationPassword = "password";

            EventLog.WriteEntry(eventLogSource,"Transfer configuration successful, starting to transfer!", EventLogEntryType.Information);

            dataTransfer.TransferData();//here causes the error

            EventLog.WriteEntry(eventLogSource, "Transfer successful!", EventLogEntryType.Information);
</code>```

I managed to find a solution
so the app does this:
step 1. backup the database into a .bak file by using the Backup class

```<code> Server backFromServer = new Server(@"server");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "un";
            backFromServer.ConnectionContext.Password = "psd";
            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["dbname"];

            Backup bkpDatabase = new Backup();
            bkpDatabase.Action = BackupActionType.Database;
            bkpDatabase.Database = backFromDb.Name;
            bkpDatabase.Incremental = false;
            bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;
            bkpDatabase.Initialize = true;

            BackupDeviceItem bkpDevice = new BackupDeviceItem(@"c:\backup.bak", DeviceType.File);

            bkpDatabase.Devices.Add(bkpDevice);
            bkpDatabase.SqlBackup(backFromServer);

            EventLog.WriteEntry(eventLogSource, "Create database backup file successful!", EventLogEntryType.Information);
</code>```

step 2. Since the file is in the source server, download the file.
step 3. restore the database by using t-sql.
step 4. fire up a scheduled task that runs the app on daily basis.
  here is the t-sql script:
USE master
ALTER DATABASE [DBName] SET Single_User WITH Rollback Immediate
RESTORE DATABASE [DBName] FROM DISK = N'filepath' WITH REPLACE, FILE = 1,  NOUNLOAD,  STATS = 10
ALTER DATABASE [DBName] SET Multi_User

答: Create a sql job that does the, well, the job by doing backup & restore, log shipping, SQL Replication, etc. Doesn't sound like a problem you want to solve through an app running daily but a sql job instead, which will be more reliable, get monitoring, diagnostics for free, not to mention that you will need to run your app with high privileges, which is in itself a bad practice and a call for trouble.</p>

Body:
I'm trying to create a windows application that copies a database from one server to another using the Transfer object
but end up having "The Integration Services component is not installed or you do not have permission to use it" error.
both servers have enterprise edition of sql server 2005 and the integration services component installed, the connection logins have full permissions as well. I really don't know what goes wrong here

            Server backFromServer = new Server(@"xx.xx.xx.xx");
            Server backToServer = new Server(@"xx.xx.xx.xx");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "username";
            backFromServer.ConnectionContext.Password = "password";

            backToServer.ConnectionContext.LoginSecure = false;
            backToServer.ConnectionContext.Login = "username";
            backToServer.ConnectionContext.Password = "password";

            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["databasesource"];

            Database backToDb = new Database();
            backToDb = backToServer.Databases["databasedest"];

            EventLog.WriteEntry(eventLogSource,"Loading databases successful!", EventLogEntryType.Information);

            Transfer dataTransfer = new Transfer(backFromDb);
            dataTransfer.CopyAllTables = true;
            dataTransfer.CopyAllObjects = false;
            dataTransfer.CopyData = true;
            dataTransfer.CopyAllUserDefinedDataTypes = true;
            dataTransfer.CopyAllStoredProcedures = false;

            dataTransfer.DropDestinationObjectsFirst = true;

            dataTransfer.Options.WithDependencies = false;

            dataTransfer.DestinationServer = backToServer.Name;
            dataTransfer.DestinationDatabase = backToDb.Name;
            dataTransfer.DestinationLoginSecure = false;
            dataTransfer.DestinationLogin = "username";
            dataTransfer.DestinationPassword = "password";

            EventLog.WriteEntry(eventLogSource,"Transfer configuration successful, starting to transfer!", EventLogEntryType.Information);

            dataTransfer.TransferData();//here causes the error

            EventLog.WriteEntry(eventLogSource, "Transfer successful!", EventLogEntryType.Information);

I managed to find a solution
so the app does this:
step 1. backup the database into a .bak file by using the Backup class

 Server backFromServer = new Server(@"server");
            backFromServer.ConnectionContext.LoginSecure = false;
            backFromServer.ConnectionContext.Login = "un";
            backFromServer.ConnectionContext.Password = "psd";
            Database backFromDb = new Database();
            backFromDb = backFromServer.Databases["dbname"];

            Backup bkpDatabase = new Backup();
            bkpDatabase.Action = BackupActionType.Database;
            bkpDatabase.Database = backFromDb.Name;
            bkpDatabase.Incremental = false;
            bkpDatabase.LogTruncation = BackupTruncateLogType.Truncate;
            bkpDatabase.Initialize = true;

            BackupDeviceItem bkpDevice = new BackupDeviceItem(@"c:\backup.bak", DeviceType.File);

            bkpDatabase.Devices.Add(bkpDevice);
            bkpDatabase.SqlBackup(backFromServer);

            EventLog.WriteEntry(eventLogSource, "Create database backup file successful!", EventLogEntryType.Information);

step 2. Since the file is in the source server, download the file.
step 3. restore the database by using t-sql.
step 4. fire up a scheduled task that runs the app on daily basis.
  here is the t-sql script:
USE master
ALTER DATABASE [DBName] SET Single_User WITH Rollback Immediate
RESTORE DATABASE [DBName] FROM DISK = N'filepath' WITH REPLACE, FILE = 1,  NOUNLOAD,  STATS = 10
ALTER DATABASE [DBName] SET Multi_User


问:
How to use Calculate Function in PowerPivot
I am new to PowerPivot and tried to use Calculation(). However, no matter I change, it always showing Error.
I had sum the Total Sales, just want to calculate the sales for Peak time. Therefore, my formula is as following:

```<code>Peak:=Calculate([Total Sales],[Period]="Peak")
</code>```

Could you please let me know why it shows error? Do I miss something?
Many thanks

答:
If the error message is along the following for a calculated measure

Calculation error in measure 'Table1'[Test]: The value for 'period'
  cannot be determined. Either 'period' doesn't exist, or there is no
  current row for a column named 'period'.

It would be due to not referencing the column name in the table you are filtering against.

```<code>Test:=CALCULATE( [Total Sales], Table1[period] = "Peak")
</code>```

Body:
I am new to PowerPivot and tried to use Calculation(). However, no matter I change, it always showing Error.
I had sum the Total Sales, just want to calculate the sales for Peak time. Therefore, my formula is as following:

Peak:=Calculate([Total Sales],[Period]="Peak")

Could you please let me know why it shows error? Do I miss something?
Many thanks

Body:
If the error message is along the following for a calculated measure

Calculation error in measure 'Table1'[Test]: The value for 'period'
  cannot be determined. Either 'period' doesn't exist, or there is no
  current row for a column named 'period'.

It would be due to not referencing the column name in the table you are filtering against.

Test:=CALCULATE( [Total Sales], Table1[period] = "Peak")


问:
How to resolve inconsistent annotation in Django?
I have the following 2 lines of

```<code>CategoryContext = Somemodel.objects.values('title__categories__category').distinct()
CategoryContextSum = CategoryContext.annotate(Total_Revenue=Sum('revenue')).order_by('-Total_Revenue')
CategoryContextAvg = CategoryContext.annotate(Average_Revenue=Avg('revenue')).order_by('-Average_Revenue')
</code>```

The avg query yields a querylist of objects where the category comes first, followed by the revenue. So basically:

```<code><QuerySet [{'title__categories__category':'Category', 'Average_Revenue':Decimal('100'),}, {'title__categories__category':'Category2':'Average_Revenue':Decimal('120'), }]>
</code>```

The sum query on the other hand yields the revenue followed by the category, so basically:

```<code><QuerySet [{'Total_Revenue':Decimal('100'), 'title__categories__category':'Category'}, {'Total_Revenue':Decimal('120'), 'title__categories__category':'Category2'}]>
</code>```

Now I have tried flipping the queries around and changing the variable names so far, but I cannot seem to figure out why in the heck these 2 statements are behaving so differently. Does anybody know what could influence annotation behavior in Django?

Edit:
In case you are wondering why I need to understand this: I am passing the queryset to a method that turns it into data for generating a barchart and the first object in the dataset must be the identifier of the value. I could make it so that it inverts the whole process by checking whether this indeed is the case and ivnerting otherwise, but it seems to me that this shouldnt be necessary

答:
This has little or nothing to do with annotate. Dictionaries in Python have no conventional sense of ordering (at least not until Python 3.6), and keys can be ordered differently across different queryset results.

And this constitutes little or not problem since you'll be access required values by key and not serially (as with sequences):

```<code>for obj_dct in your_qs:
    print(obj_dct[some_key])
</code>```

If your plot function takes dicts, no need to worry about ordering.

Body:
I have the following 2 lines of

CategoryContext = Somemodel.objects.values('title__categories__category').distinct()
CategoryContextSum = CategoryContext.annotate(Total_Revenue=Sum('revenue')).order_by('-Total_Revenue')
CategoryContextAvg = CategoryContext.annotate(Average_Revenue=Avg('revenue')).order_by('-Average_Revenue')

The avg query yields a querylist of objects where the category comes first, followed by the revenue. So basically:

<QuerySet [{'title__categories__category':'Category', 'Average_Revenue':Decimal('100'),}, {'title__categories__category':'Category2':'Average_Revenue':Decimal('120'), }]>

The sum query on the other hand yields the revenue followed by the category, so basically:

<QuerySet [{'Total_Revenue':Decimal('100'), 'title__categories__category':'Category'}, {'Total_Revenue':Decimal('120'), 'title__categories__category':'Category2'}]>

Now I have tried flipping the queries around and changing the variable names so far, but I cannot seem to figure out why in the heck these 2 statements are behaving so differently. Does anybody know what could influence annotation behavior in Django?

Edit:
In case you are wondering why I need to understand this: I am passing the queryset to a method that turns it into data for generating a barchart and the first object in the dataset must be the identifier of the value. I could make it so that it inverts the whole process by checking whether this indeed is the case and ivnerting otherwise, but it seems to me that this shouldnt be necessary

Body:
This has little or nothing to do with annotate. Dictionaries in Python have no conventional sense of ordering (at least not until Python 3.6), and keys can be ordered differently across different queryset results.

And this constitutes little or not problem since you'll be access required values by key and not serially (as with sequences):

for obj_dct in your_qs:
    print(obj_dct[some_key])

If your plot function takes dicts, no need to worry about ordering.


问:
Nested class has unstable name. Fix with @objc with strange param
We have some code where a class is nested in an extension. After opening the project in Xcode 9, we get the 'Nested class has unstable name' warning.
When using Xcode auto-fix, it generate an @objc with some (generated?) param.

For example:

```<code>struct Something {
}

extension Something {

    @objc(_TtCV16MyProject9Something4Some) class Some: NSObject, NSCoding {

        required init?(coder aDecoder: NSCoder) {

        }

        func encode(with aCoder: NSCoder) {

        }

    }
}
</code>```

All this compiles. But what the heck is this _TtCV16MyProject9Something4Some?

It seems to be unique because if we use the same one in two places, it will not compile (some generic project level compiler error).

If I replace the _TtCV16MyProject9Something4Some with anything else (say @objc(Something)), the project compiles fine, but that does not shad any more light really.

One important question, is the param randomly generated or is it an actual link to a real bridging name?

答:
But what the heck is this _TtCV16MyProject9Something4Some?

It's the (Swift 3) mangled name for Something.Some. And as you haven't specified a custom name by which to expose the class to Objective-C, it is also the name by which the Obj-C runtime sees the class (as Obj-C has no concept of nested classes).

Therefore it's also the name that is encoded into an NSCoding archive of an instance of that class (allowing the instance to be re-constructed on decoding; the Obj-C runtime will be queried for the class that goes by that name).

The reason why you're getting this error is because name mangling for nested classes changed between Swift 3 and 4 – and may well change again in the future (until Swift is ABI stable at least). Therefore to allow archives encoded with Swift 3 mangled names to be decoded in Swift 4 and above, the compiler is suggesting you expose the class to Obj-C with the Swift 3 mangled name.

If you don't need to provide this backwards compatibility for Swift 3, then you can go ahead and expose the nested class to Obj-C with your own stable name (to ensure future mangling changes don't affect archive decoding). In this case, I would recommend something like @objc(Something_Some).

Body:
We have some code where a class is nested in an extension. After opening the project in Xcode 9, we get the 'Nested class has unstable name' warning.
When using Xcode auto-fix, it generate an @objc with some (generated?) param.

For example:

struct Something {
}

extension Something {

    @objc(_TtCV16MyProject9Something4Some) class Some: NSObject, NSCoding {

        required init?(coder aDecoder: NSCoder) {

        }

        func encode(with aCoder: NSCoder) {

        }

    }
}

All this compiles. But what the heck is this _TtCV16MyProject9Something4Some?

It seems to be unique because if we use the same one in two places, it will not compile (some generic project level compiler error).

If I replace the _TtCV16MyProject9Something4Some with anything else (say @objc(Something)), the project compiles fine, but that does not shad any more light really.

One important question, is the param randomly generated or is it an actual link to a real bridging name?


问:
Should I test (duplicate) data, or only the behavior?
From the design perspective, I am wondering should I test the data, especially if it's a generally known data (not something very configurable) - this can apply to things like popular file extensions, special IP addresses etc.

Suppose we have a emergency phone number classifier:

```<code>public class ContactClassifier {

    public final static String EMERGENCY_PHONE_NUMBER = "911";

    public boolean isEmergencyNumber(String number) {
        return number.equals(EMERGENCY_PHONE_NUMBER);
    }
}
</code>```

Should I test it this way ("911" duplication):

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

or (test if properly recognized "configured" number):

```<code>@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}
</code>```

or inject "911" in the constructor,which looks the most reasonable for me, but even if I do so - should I wrote a test for the "application glue" if the component was instantiated with proper value? If someone can do a typo in data (code), then I see no reasons someone can do a typo in tests case (I bet such data would be copy-paste)

答:
External constants as such have a problem. The import disappears and the constant is added to the class' constant pool. Hence when in the future the constant is changed in the original class, the compiler does not see a dependency between the .class files, and leaves the old constant value in the test class.

So you would need a clean build.

Furthermore tests should be short, clear to read and fast to write. Tests deal with concrete cases of data. Abstractions are counter-productive, and may even lead to errors in the test themselves. Constants (like a speed limit) should be etched in stone, should be literals. Value properties like the maximum velocity of a car brand can stem from some kind of table lookup.

Of course repeated values could be placed in local constants. Prevents typos, easy - as local - abstraction, clarifies the semantic meaning of a value.

However as cases in general will use constants maybe twice or three times (positive and negative test), I would go for bare constants.

Body:
From the design perspective, I am wondering should I test the data, especially if it's a generally known data (not something very configurable) - this can apply to things like popular file extensions, special IP addresses etc.

Suppose we have a emergency phone number classifier:

public class ContactClassifier {

    public final static String EMERGENCY_PHONE_NUMBER = "911";

    public boolean isEmergencyNumber(String number) {
        return number.equals(EMERGENCY_PHONE_NUMBER);
    }
}

Should I test it this way ("911" duplication):

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber("911"));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

or (test if properly recognized "configured" number):

@Test
public testClassifier() {
    assertTrue(contactClassifier.isEmergencyNumber(ContactClassifier.EMERGENCY_PHONE_NUMBER));
    assertFalse(contactClassifier.isEmergencyNumber("111-other-222"));
}

or inject "911" in the constructor,which looks the most reasonable for me, but even if I do so - should I wrote a test for the "application glue" if the component was instantiated with proper value? If someone can do a typo in data (code), then I see no reasons someone can do a typo in tests case (I bet such data would be copy-paste)


答:
This will do the job I think :

```<code>WITH sub AS (
    SELECT trans_id
      FROM table
     WHERE message LIKE '%def-234%'
)
SELECT *
  FROM table JOIN sub USING (trans_id);
</code>```

Hope this help.

Title: SELECTing Related Rows Based on a Single Row Match

Body:
I have the following table running on Postgres SQL 9.5:

+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
|10 | 4567890    | abc123-ab   |
|11 | 4567890    | gex890-aj   |
|12 | 4567890    | ghi567-ef   |
+---+------------+-------------+

I am looking for the rows for each trans_id based on a LIKE query, like this:

SELECT * FROM table
WHERE message LIKE '%def-234%'

This, of course, returns just three rows, the three that match my pattern in the message column. What I am looking for, instead, is all the rows matching that trans_id in groups of messages that match. That is, if a single row matches the pattern, get all the rows with the trans_id of that matching row.

That is, the results would be:

+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
+---+------------+-------------+

Notice rows 10, 11, and 12 were not SELECTed because there was not one of them that matched the %def-234% pattern.

I have tried (and failed) to write a sub-query to get the all the related rows when a single message matches a pattern:

SELECT sub.*
    FROM (
        SELECT DISTINCT trans_id FROM table WHERE message LIKE '%def-234%'
    ) sub
WHERE table.trans_id = sub.trans_id

I could easily do this with two queries, but the first query to get a list of matching trans_ids to include in a WHERE trans_id IN (<huge list of trans_ids>) clause would be very large, and would not be a very inefficient way of doing this, and I believe there exists a way to do it with a single query.

Thank you!

Body:
This will do the job I think :

WITH sub AS (
    SELECT trans_id
      FROM table
     WHERE message LIKE '%def-234%'
)
SELECT *
  FROM table JOIN sub USING (trans_id);

Hope this help.


问:
Working with decimals in Ruby on Rails 3
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

```<code>def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end
</code>```

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

答:
What you're doing is called integer division, which discards any remainder, as it wouldn't be expressible in integers, e.g.:

```<code>1 / 3 # == 0
</code>```

As other respondents have mentioned, you can force a floating point division. You need to force the first argument to be a float (1 here) by calling .to_f. The second argument will automatically be coerced into a float, i.e.:

```<code>1.to_f / 3 # ~ 0.3333...
</code>```

Note that once you move to floating point numbers, the result, generally speaking, is no longer exact. This is why I put ~ 0.333.

The precise details are more involved. In binary floating point arithmetic, which is common in today's microprocessors, powers of 2 are still exact, I believe. But the integer 3, for example, is not longer represented exactly, but only within the precision of the floating point representation (typically 1E-16 or thereabouts for "double" precision).

Long story short, here is a rule of thumb: If you're dealing with money values, where precision matters (ever been noticed a 1 cent discrepancy on a phone bill?) don't store computed results, and don't store values in floating points. Instead use integer or decimal data types (which internally store strings). Compute floating point results only for display and on demand, if possible. Avoid adding large and small values together once they're floats, and avoid chained computations in floats. Rework your algebra to avoid divisions until the end. Ruby also supports a Rational data type which represents fractions exactly and may be useful.

These issues fall under the science of "floating point error propagation" which is where you can look up more information if you need.

Body:
I'm trying to calculate the average net price of a product. I have, in my Product model :total_sold and :total_net_revenue. Doing straight division in the method seems to always result in 0. I resorted to using BigDecimal as I figured that was the problem ... but with my latest iteration of the code below, I'm still getting zero when the answer comes out to a decimal.

def avg_price
  BigDecimal(total_sold.to_s) / (BigDecimal(total_net_revenue.to_s) / 100)
end

Net revenue is in cents, which is why I divide by 100. Can someone point out what I'm doing wrong or should do?

Body:
What you're doing is called integer division, which discards any remainder, as it wouldn't be expressible in integers, e.g.:

1 / 3 # == 0

As other respondents have mentioned, you can force a floating point division. You need to force the first argument to be a float (1 here) by calling .to_f. The second argument will automatically be coerced into a float, i.e.:

1.to_f / 3 # ~ 0.3333...

Note that once you move to floating point numbers, the result, generally speaking, is no longer exact. This is why I put ~ 0.333.

The precise details are more involved. In binary floating point arithmetic, which is common in today's microprocessors, powers of 2 are still exact, I believe. But the integer 3, for example, is not longer represented exactly, but only within the precision of the floating point representation (typically 1E-16 or thereabouts for "double" precision).

Long story short, here is a rule of thumb: If you're dealing with money values, where precision matters (ever been noticed a 1 cent discrepancy on a phone bill?) don't store computed results, and don't store values in floating points. Instead use integer or decimal data types (which internally store strings). Compute floating point results only for display and on demand, if possible. Avoid adding large and small values together once they're floats, and avoid chained computations in floats. Rework your algebra to avoid divisions until the end. Ruby also supports a Rational data type which represents fractions exactly and may be useful.

These issues fall under the science of "floating point error propagation" which is where you can look up more information if you need.


问:
Private IBOutlets Swift
I know that our IBOutlets should be private, but for example if I have IBOutlets in TableViewCell, how should I access them from another ViewController? Here is the example why I'm asking this kind of question:

```<code>class BookTableViewCell: UITableViewCell {

    @IBOutlet weak private var bookTitle: UILabel!

}
</code>```

if I assign to the IBOutlet that it should be private, I got an error in another ViewController while I'm accessing the cell property: 'bookTitle' is inaccessible due to 'private' protection level

答:
I haven't come across making IBOutlets private to be common, for cells at least. If you want to do so, provide a configure method within your cell that is not private, which you can pass values to, that you want to assign to your outlets. The function within your cell could look like this:

```<code>func configure(with bookTitle: String) {
    bookTitle.text = bookTitle
}
</code>```

EDIT: Such a function can be useful for the future, when you change your cell and add new outlets. You can then add parameters to your configure function to handle those. You will get compiler errors everywhere, where you use that function, which allows you to setup your cell correctly wherever you use it. That is helpful in a big project that reuses cells in different places.

Title: Private IBOutlets Swift

Body:
I know that our IBOutlets should be private, but for example if I have IBOutlets in TableViewCell, how should I access them from another ViewController? Here is the example why I'm asking this kind of question:

class BookTableViewCell: UITableViewCell {

    @IBOutlet weak private var bookTitle: UILabel!

}

if I assign to the IBOutlet that it should be private, I got an error in another ViewController while I'm accessing the cell property: 'bookTitle' is inaccessible due to 'private' protection level

Body:
I haven't come across making IBOutlets private to be common, for cells at least. If you want to do so, provide a configure method within your cell that is not private, which you can pass values to, that you want to assign to your outlets. The function within your cell could look like this:

func configure(with bookTitle: String) {
    bookTitle.text = bookTitle
}

EDIT: Such a function can be useful for the future, when you change your cell and add new outlets. You can then add parameters to your configure function to handle those. You will get compiler errors everywhere, where you use that function, which allows you to setup your cell correctly wherever you use it. That is helpful in a big project that reuses cells in different places.


问:
Bootstraptable isn't making the table interactive
I'm trying to make a fancy table using the extended bootstrap table code from here:
https://github.com/wenzhixin/bootstrap-table

It's a very popular project but the table isn't interactive in any way and I don't know why.
What is strange is that the bootstraptable Js puts the data into a html-table:

```<code> $(function () {
        $('#datatable').bootstrapTable({
            striped: true,
            pagination: true,
            showColumns: true,
            showToggle: true,
            showExport: true,
            sortable: true,
            paginationVAlign: 'both',
            pageSize: 25,
            pageList: [10, 25, 50, 100, 'ALL'],
            columns: [{'field': 'Name', 'title': 'Name'}, {'field': 'Age', 'title': 'Age'}],  // here is where we use the column content from our Django View
            data: [{"Name":"Alex","Age":10},{"Name":"Bob","Age":12},{"Name":"Clarke","Age":13}] // here is where we use the data content from our Django View. we escape the content with the safe tag so the raw JSON isn't shown.
        });
    });
</code>```

So the fact that a table is produced in the HTML should mean that the bootstrapTable code is running. But none of the fancy features (pagination, sorting) work.

Working example:
https://jsfiddle.net/wouterr5/b4huLLt8/1/

答:
I believe the issue you're having is that you simply forgot to include Bootstrap's CSS.  You have its JavaScript component but without the CSS included all of the styles fail to get applied.

https://jsfiddle.net/9whpma70/

$(function () {
  $('#datatable').bootstrapTable({
    striped: true,
    pagination: true,
    showColumns: true,
    showToggle: true,
    showExport: true,
    sortable: true,
    paginationVAlign: 'both',
    pageSize: 25,
    pageList: [10, 25, 50, 100, 'ALL'],
    columns: [{'field': 'Name', 'title': 'Name'}, {'field': 'Age', 'title': 'Age'}],  // here is where we use the column content from our Django View
    data: [{"Name":"Alex","Age":10},{"Name":"Bob","Age":12},{"Name":"Clarke","Age":13}] // here is where we use the data content from our Django View. we escape the content with the safe tag so the raw JSON isn't shown.
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.js"></script>

<table id="datatable"></table></code>```

Body:
I'm trying to make a fancy table using the extended bootstrap table code from here:
https://github.com/wenzhixin/bootstrap-table

It's a very popular project but the table isn't interactive in any way and I don't know why.
What is strange is that the bootstraptable Js puts the data into a html-table:

 $(function () {
        $('#datatable').bootstrapTable({
            striped: true,
            pagination: true,
            showColumns: true,
            showToggle: true,
            showExport: true,
            sortable: true,
            paginationVAlign: 'both',
            pageSize: 25,
            pageList: [10, 25, 50, 100, 'ALL'],
            columns: [{'field': 'Name', 'title': 'Name'}, {'field': 'Age', 'title': 'Age'}],  // here is where we use the column content from our Django View
            data: [{"Name":"Alex","Age":10},{"Name":"Bob","Age":12},{"Name":"Clarke","Age":13}] // here is where we use the data content from our Django View. we escape the content with the safe tag so the raw JSON isn't shown.
        });
    });

So the fact that a table is produced in the HTML should mean that the bootstrapTable code is running. But none of the fancy features (pagination, sorting) work.

Working example:
https://jsfiddle.net/wouterr5/b4huLLt8/1/

Body:
I believe the issue you're having is that you simply forgot to include Bootstrap's CSS.  You have its JavaScript component but without the CSS included all of the styles fail to get applied.

https://jsfiddle.net/9whpma70/

$(function () {
  $('#datatable').bootstrapTable({
    striped: true,
    pagination: true,
    showColumns: true,
    showToggle: true,
    showExport: true,
    sortable: true,
    paginationVAlign: 'both',
    pageSize: 25,
    pageList: [10, 25, 50, 100, 'ALL'],
    columns: [{'field': 'Name', 'title': 'Name'}, {'field': 'Age', 'title': 'Age'}],  // here is where we use the column content from our Django View
    data: [{"Name":"Alex","Age":10},{"Name":"Bob","Age":12},{"Name":"Clarke","Age":13}] // here is where we use the data content from our Django View. we escape the content with the safe tag so the raw JSON isn't shown.
  });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.js"></script>

<table id="datatable"></table>


问:
Function doesn't output "STRING"
```<code><?php
function remove_char(string $s):string
    {
        settype($s, 'string');
        $pieces = str_split($s);
        unset($pieces[0]);
        $numb = count($pieces);
        unset($pieces[$numb - 1]);
        echo implode("", $pieces);
    }

    $lotsp = "lotsp";`enter code here`
    remove_char($lotsp);
?>
</code>```

The function 'remove_char()' supposed to bring 'String' type of output. However it is outputting anything other than string.

Error: FATAL ERROR Uncaught TypeError: Return value of remove_char() must be of the type string, none returned in /home4/phptest/public_html/code.php70(5) : enter code here

I don't know where is the problem. Any help is greatly appreciated. Thanks

答:
You are declaring that remove_char() should return a string but you are not returning anything.

Remove :string from your function declaration:

```<code>function remove_char(string $s)
{
    settype($s, 'string');
    $pieces = str_split($s);
    unset($pieces[0]);
    $numb = count($pieces);
    unset($pieces[$numb - 1]);
    echo implode("", $pieces);
}
</code>```

Now you should be able to echo from within the function.

See this answer about the difference between echo and return.

Title: Function doesn't output "STRING"

Body:
<?php
function remove_char(string $s):string
    {
        settype($s, 'string');
        $pieces = str_split($s);
        unset($pieces[0]);
        $numb = count($pieces);
        unset($pieces[$numb - 1]);
        echo implode("", $pieces);
    }

    $lotsp = "lotsp";`enter code here`
    remove_char($lotsp);
?>

The function 'remove_char()' supposed to bring 'String' type of output. However it is outputting anything other than string.

Error: FATAL ERROR Uncaught TypeError: Return value of remove_char() must be of the type string, none returned in /home4/phptest/public_html/code.php70(5) : enter code here

I don't know where is the problem. Any help is greatly appreciated. Thanks

Body:
You are declaring that remove_char() should return a string but you are not returning anything.

Remove :string from your function declaration:

function remove_char(string $s)
{
    settype($s, 'string');
    $pieces = str_split($s);
    unset($pieces[0]);
    $numb = count($pieces);
    unset($pieces[$numb - 1]);
    echo implode("", $pieces);
}

Now you should be able to echo from within the function.

See this answer about the difference between echo and return.


问:
Use variable value from .gs file in custom HTML sidebar
I have a google sheet where I have scripted a custom sidebar.

Within the sidebar, I want to display the value of column I within the active row.

I've managed to work out the script to store the variable 'I' when the sidebar is opened:

```<code>var hotelName = ""

function openSidebar() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showSidebar(html);
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var column=9;
hotelName = s.getRange(row, column).getValue();
Logger.log(hotelName);
}
</code>```

However I now need this to appear in an empty DIV element in my sidebar. How do I export this variable?

UPDATE:

That works great. I've now added as well a button to the sidebar to refresh and what I want that to do is to update the script so that if the user has changed rows, the new hotel name will show. At the moment I've added this HTML:

```<code> <div id="footer">

 <div><?= hotel ?></div>

 <p><i class="fa fa-refresh" aria-hidden="true" id="testing"></i></p>

 </div>
</code>```

And this JQuery to the index file:

```<code>$("#testing").on('click', function buttonClick() {
google.script.run.buttonClick();
});
</code>```

And for the function I just copied the original function:

```<code>function buttonClick() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var column=9;
var hotelName = s.getRange(row, column).getValue();

// get the html template after retrieving the values
var html_template = HtmlService.createTemplateFromFile('index');

// set the value for the index.html `hotel` placeholder/scriptlet
html_template.hotel = hotelName;

// evaluate the template
var sidebar_html = html_template.evaluate();

SpreadsheetApp.getUi().showSidebar(sidebar_html);

Logger.log(hotelName);
}
</code>```

However, really I want the value of the cell to update asynchronously so that the sidebar doesn't re-load, just the hotel name...

Would this be possible??

答:
Use Scriptlets with createTemplateFromFile() and evaluate(). Then use the printing scriptlets in the html file and set their value in your openSidebar()

```<code>function openSidebar() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getSheetByName("Contract Registry Document");
  var row=s.getActiveCell().getRow();
  var column=9;
  var hotelName = s.getRange(row, column).getValue();

  // get the html template after retrieving the values
  var html_template = HtmlService.createTemplateFromFile('index');

  // set the value for the index.html `hotel` placeholder/scriptlet
  html_template.hotel = hotelName;

  // evaluate the template
  var sidebar_html = html_template.evaluate();

  SpreadsheetApp.getUi().showSidebar(sidebar_html);

  Logger.log(hotelName);
}
</code>```

index.html

```<code><html>
  <body>
    <p>The hotel name is: <?= hotel ?></p>
  </body>
</html>
</code>```

Body:
I have a google sheet where I have scripted a custom sidebar.

Within the sidebar, I want to display the value of column I within the active row.

I've managed to work out the script to store the variable 'I' when the sidebar is opened:

var hotelName = ""

function openSidebar() {
var html = HtmlService.createHtmlOutputFromFile('index');
SpreadsheetApp.getUi().showSidebar(html);
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var column=9;
hotelName = s.getRange(row, column).getValue();
Logger.log(hotelName);
}

However I now need this to appear in an empty DIV element in my sidebar. How do I export this variable?

UPDATE:

That works great. I've now added as well a button to the sidebar to refresh and what I want that to do is to update the script so that if the user has changed rows, the new hotel name will show. At the moment I've added this HTML:

<?= hotel ?>

And this JQuery to the index file:

$("#testing").on('click', function buttonClick() {
google.script.run.buttonClick();
});

And for the function I just copied the original function:

function buttonClick() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName("Contract Registry Document");
var row=s.getActiveCell().getRow();
var column=9;
var hotelName = s.getRange(row, column).getValue();

// get the html template after retrieving the values
var html_template = HtmlService.createTemplateFromFile('index');

// set the value for the index.html `hotel` placeholder/scriptlet
html_template.hotel = hotelName;

// evaluate the template
var sidebar_html = html_template.evaluate();

SpreadsheetApp.getUi().showSidebar(sidebar_html);

Logger.log(hotelName);
}

However, really I want the value of the cell to update asynchronously so that the sidebar doesn't re-load, just the hotel name...

Would this be possible??

Body:
Use Scriptlets with createTemplateFromFile() and evaluate(). Then use the printing scriptlets in the html file and set their value in your openSidebar()

function openSidebar() {
  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var s=ss.getSheetByName("Contract Registry Document");
  var row=s.getActiveCell().getRow();
  var column=9;
  var hotelName = s.getRange(row, column).getValue();

  // get the html template after retrieving the values
  var html_template = HtmlService.createTemplateFromFile('index');

  // set the value for the index.html `hotel` placeholder/scriptlet
  html_template.hotel = hotelName;

  // evaluate the template
  var sidebar_html = html_template.evaluate();

  SpreadsheetApp.getUi().showSidebar(sidebar_html);

  Logger.log(hotelName);
}

index.html

<html>
  <body>
    <p>The hotel name is: <?= hotel ?></p>
  </body>
</html>


问:
How to get name value from SelectList in mvc
I want to get the name value not ID value from SelectList in mvc.

Here is my code

Controller

```<code>var occupationList = new SelectList(new[]
{
    new { ID = 1, Name = "Student" },
    new { ID = 2, Name = "House Wife" },
    new { ID = 3, Name = "Business Man" },
    new { ID = 4, Name = "Service Man" },
},
"ID", "Name", 1);
ViewData["occupationList"] = occupationList;
return View();
</code>```

View

```<code>@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {@class="control-label", style="width:250px;" })
</code>```

Now, when I select the item from dropdownlist at that time it shows the selected item but it store the ID value in the database.

For ex : I select the Student Name value from the dropdownlist and save it. Now, in database it store the 1 value.

But I dont want to store the ID value i.e. 1. I want to store the Name value i.e. Student in database.

Thank You.

答:
When you submit the form, the selected option's value attribute is send from the browser to the server for that select element. If you want to send the name instead of the numeric id, you should set the data value field of the SelectList to be the name instead of Id

```<code>var occupationList = new SelectList(new[]
    {
        new { ID = 1, Name = "Student" },
        new { ID = 2, Name = "House Wife" },
        new { ID = 3, Name = "Business Man" },
        new { ID = 4, Name = "Service Man" },
    },
    "Name", "Name", "Student");
ViewData["occupationList"] = occupationList;
</code>```

Your view code will be same

```<code>@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList,
                                    new {@class="control-label", style="width:250px;" })
</code>```

This will render the markup for SELECT element with value and text set to the same field.

```<code><select id="Occupation" name="Occupation">
   <option value="Student" selected="selected">Student</option>
   <option value="House Wife">House Wife</option>
   <option value="Business Man">Business Man</option>
   <option value="Service Man">Service Man</option>
</select>
</code>```

As i mentioned earlier, now when you submit the form ,the string value will be submitted instead of the numeric Id. That means you need to make adjustments to your server side code to receive the string value and save it ( probably need to update the db schema as well to store the string value instead of numeric value)

Body:
I want to get the name value not ID value from SelectList in mvc.

Here is my code

Controller

var occupationList = new SelectList(new[]
{
    new { ID = 1, Name = "Student" },
    new { ID = 2, Name = "House Wife" },
    new { ID = 3, Name = "Business Man" },
    new { ID = 4, Name = "Service Man" },
},
"ID", "Name", 1);
ViewData["occupationList"] = occupationList;
return View();

View

@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {@class="control-label", style="width:250px;" })

Now, when I select the item from dropdownlist at that time it shows the selected item but it store the ID value in the database.

For ex : I select the Student Name value from the dropdownlist and save it. Now, in database it store the 1 value.

But I dont want to store the ID value i.e. 1. I want to store the Name value i.e. Student in database.

Thank You.

Body:
When you submit the form, the selected option's value attribute is send from the browser to the server for that select element. If you want to send the name instead of the numeric id, you should set the data value field of the SelectList to be the name instead of Id

var occupationList = new SelectList(new[]
    {
        new { ID = 1, Name = "Student" },
        new { ID = 2, Name = "House Wife" },
        new { ID = 3, Name = "Business Man" },
        new { ID = 4, Name = "Service Man" },
    },
    "Name", "Name", "Student");
ViewData["occupationList"] = occupationList;

Your view code will be same

@Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList,
                                    new {@class="control-label", style="width:250px;" })

This will render the markup for SELECT element with value and text set to the same field.

<select id="Occupation" name="Occupation">
   <option value="Student" selected="selected">Student</option>
   <option value="House Wife">House Wife</option>
   <option value="Business Man">Business Man</option>
   <option value="Service Man">Service Man</option>
</select>

As i mentioned earlier, now when you submit the form ,the string value will be submitted instead of the numeric Id. That means you need to make adjustments to your server side code to receive the string value and save it ( probably need to update the db schema as well to store the string value instead of numeric value)


问:
radio button with custom background image turns black in internet explorer
I need to render radiobuttons on my site with specific background-images:
not checked
, checked

I solved this problem by adding the following styles for radiobutton elements:

```<code>{
  width: 20px;
  height: 20px;
  -webkit-appearance: none;
  background-image: url(/Images/notChackedRadioButton.png);
  background-repeat: no-repeat;
}
</code>```

Everything was fine, but when i open my site in Internet Explorer I see that all radiobuttons became black.
Seems like IE adds its own image above my background image, but I don't have any idea how to solve this. Please, any suggestions will be helpful.

答:
Not knowing the rest of your code here is an example of a way you can do it. Works in IE 11 and IE Edge. Found on codepen for rest of the example - https://codepen.io/tutsplus/pen/bgqYJz

input[type="radio"] {
  display:none;
}

input[type="radio"] + label span {
  display:inline-block;
  width:19px;
  height:19px;
  margin:-2px 10px 0 0;
  vertical-align:middle;
  background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/check_radio_sheet.png) -38px top no-repeat;
  cursor:pointer;
}

input[type="radio"]:checked + label span {
  background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/check_radio_sheet.png) -57px top no-repeat;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <input type="radio" id="r1" name="rr" />
      <label for="r1"><span></span>Radio Button 1</label>
      <p>
      <input type="radio" id="r2" name="rr" />
      <label for="r2"><span></span>Radio Button 2</label></code>```

Body:
I need to render radiobuttons on my site with specific background-images:
not checked
, checked

I solved this problem by adding the following styles for radiobutton elements:

{
  width: 20px;
  height: 20px;
  -webkit-appearance: none;
  background-image: url(/Images/notChackedRadioButton.png);
  background-repeat: no-repeat;
}

Everything was fine, but when i open my site in Internet Explorer I see that all radiobuttons became black.
Seems like IE adds its own image above my background image, but I don't have any idea how to solve this. Please, any suggestions will be helpful.

Body:
Not knowing the rest of your code here is an example of a way you can do it. Works in IE 11 and IE Edge. Found on codepen for rest of the example - https://codepen.io/tutsplus/pen/bgqYJz

input[type="radio"] {
  display:none;
}

input[type="radio"] + label span {
  display:inline-block;
  width:19px;
  height:19px;
  margin:-2px 10px 0 0;
  vertical-align:middle;
  background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/check_radio_sheet.png) -38px top no-repeat;
  cursor:pointer;
}

input[type="radio"]:checked + label span {
  background:url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/210284/check_radio_sheet.png) -57px top no-repeat;
}

      <input type="radio" id="r1" name="rr" />
      <label for="r1"><span></span>Radio Button 1</label>
      <p>
      <input type="radio" id="r2" name="rr" />
      <label for="r2"><span></span>Radio Button 2</label>


问:
Eclipse: How to find the type of the variable in Expressions window?
Eclipse includes a window named "Expressions" that allows showing the content of expressions/variables. My problem is that I can't see the Type/Class expressions window.

Do you know how I can use the Expressions window to see the type of the result of the expressions?

答: In the view menu of the Expressions view select Layout > Select Columns... and check Declared Type or/and Actual Type:


问:
Error in clearecase wile checking out a file
I have an issue with ClearCase I was trying to check out a file from the dir by using ct co -nc file name, but I am getting the following error:

```<code>cleartool: Error: branch type "test1" not found in VOB "/dir/file" and no global type definition can be found.
cleartool: Error: Unable to create branch requested by -mkbranch option in config spec.
cleartool: Error: Unable to check out "file".
</code>```

But when I was trying to check out another file from dir I am able to do them. I am only getting the problem to check out that file.

Can anyone help me how can I overcome this error?

答:
Looks like "test1" branch type does not exist in the vob.

Create a branch using ct mkbrtype. Run the following command form the folder where file is present

ct mkbrtype -nc test1

As the error is occurring only for one file, the config spec should have selection rule only for that file. Can check this using
ct catcs

Note:- When adding a branch rule in config spec, Always check the brtype exists with that name.

Body:
I have an issue with ClearCase I was trying to check out a file from the dir by using ct co -nc file name, but I am getting the following error:

cleartool: Error: branch type "test1" not found in VOB "/dir/file" and no global type definition can be found.
cleartool: Error: Unable to create branch requested by -mkbranch option in config spec.
cleartool: Error: Unable to check out "file".

But when I was trying to check out another file from dir I am able to do them. I am only getting the problem to check out that file.

Can anyone help me how can I overcome this error?