问:
Getting confused using weightSum
First of all this is a layout of a fragment that contains a TextView ,View and a ListView.The View which is a gray line do not appear.

I want to get in the top the TextView and below it the gray line then the ListView.

I knew that the layout_weight < weigthSum but when using it like that I get the ListView too much in the bottom so I tried it = 165 and got a better result but still not getting the gray line

This is the xml for the layout where I have set the weightSum=100 and the layout_weight of the relative layout that contains the textView and the ImageView =165 .

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="100">
    <!--android:weightSum="100"-->
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="165"
        android:id="@+id/first_relative_accueil_fragment">
        <!--165-->
        <!--android:layout_weight="160"-->
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/accueil_toolbar_text"
            android:text="Accueil"
            android:textSize="20dp"
            android:paddingLeft="16dp"
            android:paddingTop="16dp"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@android:color/darker_gray" />

    </RelativeLayout>
    <ListView
        android:id="@+id/accueil_fragment_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

答:
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/accueil_toolbar_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:text="Accueil"
        android:textSize="20dp" />

    <View
        android:id="@+id/separator"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@android:color/darker_gray" />

    <ListView
        android:id="@+id/accueil_fragment_list"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>
</LinearLayout>
</code>```

This should serve your purpose. One needs to be a bit careful using the height definition, layout_weight, weight_sum values. (the parent-child layouts' relationships should be taken care of while defining the values).

PS: Using of unnecessary layouts is a bad practice and
  makes the UI rendering slow, so try to use simpler layouts & less of
  nesting. :)

Title: Getting confused using weightSum

Body:
First of all this is a layout of a fragment that contains a TextView ,View and a ListView.The View which is a gray line do not appear.

I want to get in the top the TextView and below it the gray line then the ListView.

I knew that the layout_weight < weigthSum but when using it like that I get the ListView too much in the bottom so I tried it = 165 and got a better result but still not getting the gray line

This is the xml for the layout where I have set the weightSum=100 and the layout_weight of the relative layout that contains the textView and the ImageView =165 .

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="100">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="165"
        android:id="@+id/first_relative_accueil_fragment">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/accueil_toolbar_text"
            android:text="Accueil"
            android:textSize="20dp"
            android:paddingLeft="16dp"
            android:paddingTop="16dp"/>
        <View
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@android:color/darker_gray" />

    </RelativeLayout>
    <ListView
        android:id="@+id/accueil_fragment_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

Body:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/accueil_toolbar_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        android:text="Accueil"
        android:textSize="20dp" />

    <View
        android:id="@+id/separator"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@android:color/darker_gray" />

    <ListView
        android:id="@+id/accueil_fragment_list"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>
</LinearLayout>

This should serve your purpose. One needs to be a bit careful using the height definition, layout_weight, weight_sum values. (the parent-child layouts' relationships should be taken care of while defining the values).

PS: Using of unnecessary layouts is a bad practice and
  makes the UI rendering slow, so try to use simpler layouts & less of
  nesting. :)


来源: stackexchange

问:
Angular http get no response from api
I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the  details of the object):

```<code>  0
 id "1"
 name   "Company-A21"
 address    "Gany-A11"
</code>```

If I want to see RAW data I get this:

```<code>[{"id":"1","name":"Company-A21","address":"Gany-A11"}]
</code>```

On the "other side" I am running apache2 and this HTML file:

```<code>    <!doctype html>
<html >
    <head>
        <title>Hello AngularJS</title>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="Hello">
            <p>The ID is {{company.id}}</p>
            <p>The content is {{company.name}}</p>
        </div>
    </body>
</html>
</code>```

And the hello.js:

```<code>angular.module('demo', [])
.controller('Hello', function($scope, $http){

    $http.get('http://localhost:4567/api/v1/companies/2').
    then(function(response) {
            $scope.company = response.data;
    });
 });
</code>```

Why I can not see response?
I just started to practice Angular and I stuck here...

答:
Your data is an array of objects so you'd output it like: {{company[0].id}}

You probably followed an example using ng-repeat which would look something like this:

```<code><div ng-repeat="company in companies">
   <p>The ID is {{company.id}}</p>
    <p>The content is {{company.name}}</p>
 </div>
</code>```

https://jsfiddle.net/ojzdxpt1/21/

ContentLicense: CC BY-SA 3.0

Title: Angular http get no response from api

Body:
I am trying to get any information with Angular from the local api that I have created in Ruby, Sinatra platform. I am sure that the api is running on the port 4567 since I can see the data if i access m it directly through web interface. When I do that I see this (just next to the number 0 there is like a small arrow so it is possible to minimize the  details of the object):

  0
 id "1"
 name   "Company-A21"
 address    "Gany-A11"

If I want to see RAW data I get this:

[{"id":"1","name":"Company-A21","address":"Gany-A11"}]

On the "other side" I am running apache2 and this HTML file:

    <!doctype html>

        <title>Hello AngularJS</title>

The ID is {{company.id}}

The content is {{company.name}}

And the hello.js:

angular.module('demo', [])
.controller('Hello', function($scope, $http){

    $http.get('http://localhost:4567/api/v1/companies/2').
    then(function(response) {
            $scope.company = response.data;
    });
 });

Why I can not see response?
I just started to practice Angular and I stuck here...

Body:
Your data is an array of objects so you'd output it like: {{company[0].id}}

You probably followed an example using ng-repeat which would look something like this:

<div ng-repeat="company in companies">
   <p>The ID is {{company.id}}</p>
    <p>The content is {{company.name}}</p>
 </div>

https://jsfiddle.net/ojzdxpt1/21/


问:
Disable and enable jQuery context menu
I use

```<code>$('#test').unbind('click');
</code>```

to remove the click event on the #test item. How do I make the item clickable again?

Actually I have a table. On click event a context menu appears. But if there are no entries the menu has to be disabled. So I use unbind above. Since the context menu is generated by a plugin I do not know how to make it clickable again.

Any ideas?

Update: this is how the context menu is set up

```<code> $('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
      'sms': function(t) {},
      'delete': function(t) {}
    }
 });
</code>```

Since I am still not sure how to solve my problem I will describe it a little more. I use the lightweight context-menu plugin in jQuery to display context menus.

```<code>#contacts tbody tr
</code>```

are the table rows and myMenu1 is the context menu that appears on tr click.

On my page I have a table. Each row has its own context menu, well always the same but function(t) referes always to the clicked row.

Well, the table may be empty so I want to disable the context menu. I believe there are may ways to do that. One is to unbind the click event, this does not work for me.

I hope anyone has an idea.

答:
Take a look at this question Rebind DOM Event with jQuery

Josiah's solution is preferable but if you really wanted to unbind the click event entirely I believe you could do this:

```<code>var storedClick = $('#test').data('events').click[0].handler;
$('#test').unbind('click');
$('#test').bind('click', storedClick);
</code>```

Remember that data('events').click is an array so you would need to store the handler for every member of the array.

ContentLicense: CC BY-SA 2.5

Title: Disable and enable jQuery context menu

Body:
I use

$('#test').unbind('click');

to remove the click event on the #test item. How do I make the item clickable again?

Actually I have a table. On click event a context menu appears. But if there are no entries the menu has to be disabled. So I use unbind above. Since the context menu is generated by a plugin I do not know how to make it clickable again.

Any ideas?

Update: this is how the context menu is set up

 $('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
      'sms': function(t) {},
      'delete': function(t) {}
    }
 });

Since I am still not sure how to solve my problem I will describe it a little more. I use the lightweight context-menu plugin in jQuery to display context menus.

#contacts tbody tr

are the table rows and myMenu1 is the context menu that appears on tr click.

On my page I have a table. Each row has its own context menu, well always the same but function(t) referes always to the clicked row.

Well, the table may be empty so I want to disable the context menu. I believe there are may ways to do that. One is to unbind the click event, this does not work for me.

I hope anyone has an idea.

Body:
Take a look at this question Rebind DOM Event with jQuery

Josiah's solution is preferable but if you really wanted to unbind the click event entirely I believe you could do this:

var storedClick = $('#test').data('events').click[0].handler;
$('#test').unbind('click');
$('#test').bind('click', storedClick);

Remember that data('events').click is an array so you would need to store the handler for every member of the array.


问:
Apache Drill | How to configure Spill on disk
I doing R&D on Apache drill by querying on 20 million data on 8GB RAM with MySQL and Mongo data source and getting out of memory exception.

Then,tried to configure Spill on disk by following configuration in drill-override.conf.

```<code>drill.exec: {
 cluster-id: "APDCluster1",
 zk.connect: "192.168.1.16:2181",
 spill: {
  directories: ["/data/enliven/installations/ApacheD/drill/spill"],
  fs: "file:///"
 }
 sort: {
  external: {
   batch.size: 4000,
   spill: {
    batch.size: 4000,
    group.size: 100,
    threshold: 200,
    directories: ["/data/enliven/installations/ApacheD/drill/spill"],
    fs: "file:///"
   }
  }
 },
 hashagg: {
  spill: {
   directories: ["/data/enliven/installations/ApacheD/drill/spill"],
   fs: "file:///"
  }
 }
}
</code>```

Still am getting same out of memory exception .

Any one can help me on this.

答:
The drill-override.conf settings you have is correct (though no need to specify the operator specific settings. The drill.exec.spill.* is common to all spilling operators. The operator specific ones (like drill.exec.hashagg.spill.fs) would be deprecated in the future).

The planner.memory.max_query_memory_per_node is an important setting. Ideally should be set to a size close to the size of the direct memory, divided by the number of concurrent query streams used. The default setting is 2GB, which is often too small.

Spilling enabled is not a panacea for all memory issues. Need to check the specific detail (examine the stack trace in the log) to find out which operator failed. Some possibilities:

Hash Join does not yet support spilling. If need to join a large data set, better disable (alter session set `planner.enable_hashjoin` = false;) so merge-join will be used instead.

The External Sort has a new version ("managed") that handles memory better. To enable using the managed version instead set the configuration of "drill.exec.sort.external.disable_managed" to false. (This would become the default setting in Drill 1.12).

The Hash Aggregate spill support is a new feature (Drill 1.12 may work better). Options here: Either disable (alter session set `planner.enable_hashagg` = false;), or try and increase  "exec.hashagg.min_batches_per_partition" to a higher value (4 or 5).

The TopN operator (used when the query has both ORDER BY and LIMIT clauses) had some memory issues (fixed in 1.12). This can be fixed by setting in the configuration override of  "purge.threshold : 10" under drill.exec.sort .

Body:
I doing R&D on Apache drill by querying on 20 million data on 8GB RAM with MySQL and Mongo data source and getting out of memory exception.

Then,tried to configure Spill on disk by following configuration in drill-override.conf.

drill.exec: {
 cluster-id: "APDCluster1",
 zk.connect: "192.168.1.16:2181",
 spill: {
  directories: ["/data/enliven/installations/ApacheD/drill/spill"],
  fs: "file:///"
 }
 sort: {
  external: {
   batch.size: 4000,
   spill: {
    batch.size: 4000,
    group.size: 100,
    threshold: 200,
    directories: ["/data/enliven/installations/ApacheD/drill/spill"],
    fs: "file:///"
   }
  }
 },
 hashagg: {
  spill: {
   directories: ["/data/enliven/installations/ApacheD/drill/spill"],
   fs: "file:///"
  }
 }
}

Still am getting same out of memory exception .

Any one can help me on this.


问:
which aws instance types need subnet id specified?
Cloud formation says:

The specified instance type can only be used in a VPC. A subnet ID or
  network interface ID is required to carry out the request. Launching
  EC2 instance failed.

Which instance types do not need a subnet ID or network interface ID?

答:
So if you have an older AWS account, you may still have access to EC2 "Classic", which means it is possible to launch an instance without needing a VPC.  Only accounts created before Dec. 2013 support EC2 Classic.

However, not every instance type supports being launched into EC2 Classic - in fact, most of the newer instance types can only be launched into a VPC.

The full list is here, but the M/C/R4 families plus T2s, are VPC only.


问:
Changing a CSS Animation using jQuery
I've got the following keyframe animation,

```<code>@-webkit-keyframes rotate {
  from {
    -webkit-transform: rotateY(0);
    -moz-transform: rotateY(0);
    transform: rotateY(0);
  }

  to {
    -webkit-transform: rotateX(2160deg);
    -moz-transform: rotateX(2160deg);
    transform: rotateX(2160deg);
   }
}
</code>```

Now under a certain condition, I'd like to change the to {} part of this animation, and then the rotation.

I'd like to achieve this using .css (?). How would I do this without using multiple animation, but just change the CSS instead?

Title: Changing a CSS Animation using jQuery

Body:
I've got the following keyframe animation,

@-webkit-keyframes rotate {
  from {
    -webkit-transform: rotateY(0);
    -moz-transform: rotateY(0);
    transform: rotateY(0);
  }

  to {
    -webkit-transform: rotateX(2160deg);
    -moz-transform: rotateX(2160deg);
    transform: rotateX(2160deg);
   }
}

Now under a certain condition, I'd like to change the to {} part of this animation, and then the rotation.

I'd like to achieve this using .css (?). How would I do this without using multiple animation, but just change the CSS instead?

Body:
.css doesn't support -webkit-keyframes that way.  However, you can generate a new WebKit keyframe on the fly by appending a style tag.  In this code I used JavaScript's multi-line quote character ` (lowercase tilde).

If you want to be able to animate anything via CSS transitions:

var uniqueRotate = 0;

$('#test').click(function () {
  var amountToRotate = Math.floor(180 * Math.random()) + 'deg',
      myRotateId = 'rotate' + uniqueRotate++;
  $('<style>')
    .text(`
    @-webkit-keyframes ` + myRotateId + ` {
      from {
        -webkit-transform: rotateY(0);
        -moz-transform: rotateY(0);
        transform: rotateY(0);
      }

      to {
        -webkit-transform: rotateX(` + amountToRotate + `);
        -moz-transform: rotateX(` + amountToRotate + `);
        transform: rotateX(` + amountToRotate + `);
       }
    }
    `)
    .appendTo(document.body);
  $(this).css('animation', '1s ease-out 0s 1 ' + myRotateId);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<div id='test'>Testing cool stuff! Please click me!</div>

If you only ever want to change transform:

var uniqueRotate = 0;

$('#test').click(function () {
  var amountToRotate = 180 * Math.random(),
      animationTime = 2*1000,
      updatePerMs = 20,
      iterations = 0; // every 20 ms we update our timer
  var myTimer = setInterval(function () {
    iterations++;
    var ratio = (updatePerMs*iterations) / animationTime,
        current = Math.floor(ratio * amountToRotate);
    if (ratio > 1) {
      clearInterval(myTimer);
      return;
    }
    $(this).css({
      '-webkit-transform': 'rotateX(' + current + 'deg)',
      '-moz-transform': 'rotateX(' + current + 'deg)',
      'transform': 'rotateX(' + current + 'deg)'
    });
  }.bind(this), updatePerMs);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>
<div id='test'>Testing cool stuff! Please click me!</div>


问:
Draw QFrame around QPushButton PyQt5
I am unable to get a QFrame to completely surround a QPushButton Like a Border. It only frames the top and left side of the button. I was wondering what I'm doing wrong with the frame.</p>

```<code>import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class main(QWidget):
    def __init__(self):
        super().__init__()
        layout1 = QVBoxLayout()
        btn1 = QPushButton("Test")

        frame = QFrame(btn1)
        frame.setGeometry(btn1.geometry())
        frame.setFrameShape(QFrame.Box)
        frame.setFrameShadow(QFrame.Plain)
        frame.setLineWidth(4)

        layout1.addWidget(btn1)
        self.setLayout(layout1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = main()
    window.show()
    sys.exit(app.exec_())
</code>```

答:
The problem is caused because the QFrame does not change the size, instead QPushButton does. In my solution I have resized every time the size is changed in the QPushButton

```<code>class FrameButton(QPushButton):
    def __init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)
        self.frame = QFrame(self)
        self.frame.setFrameShape(QFrame.Box)
        self.frame.setFrameShadow(QFrame.Plain)
        self.frame.setLineWidth(4)

    def resizeEvent(self, event):
        self.frame.resize(self.size())
        QWidget.resizeEvent(self, event)

class main(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout(self)
        layout.addWidget(FrameButton("Test"))
</code>```

Title: Draw QFrame around QPushButton PyQt5

Body:
I am unable to get a QFrame to completely surround a QPushButton Like a Border. It only frames the top and left side of the button. I was wondering what I'm doing wrong with the frame.

import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class main(QWidget):
    def __init__(self):
        super().__init__()
        layout1 = QVBoxLayout()
        btn1 = QPushButton("Test")

        frame = QFrame(btn1)
        frame.setGeometry(btn1.geometry())
        frame.setFrameShape(QFrame.Box)
        frame.setFrameShadow(QFrame.Plain)
        frame.setLineWidth(4)

        layout1.addWidget(btn1)
        self.setLayout(layout1)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = main()
    window.show()
    sys.exit(app.exec_())

Body:
The problem is caused because the QFrame does not change the size, instead QPushButton does. In my solution I have resized every time the size is changed in the QPushButton

class FrameButton(QPushButton):
    def __init__(self, *args, **kwargs):
        QPushButton.__init__(self, *args, **kwargs)
        self.frame = QFrame(self)
        self.frame.setFrameShape(QFrame.Box)
        self.frame.setFrameShadow(QFrame.Plain)
        self.frame.setLineWidth(4)

    def resizeEvent(self, event):
        self.frame.resize(self.size())
        QWidget.resizeEvent(self, event)

class main(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout(self)
        layout.addWidget(FrameButton("Test"))


问:
Access Configuration from a View in ASP.NET Core
How can I access IConfiguration in an MVC View in ASP.NET Core 1.1?

Ex. _Layout.cshtml

```<code><link href="@Configuration["MyConfigEntry"]/css/site.min.css>
</code>```

答:
@inject it into the view (if that's really what you want to do).

Additional documentation: Options provided by a view model or with direct view injection

ContentLicense: CC BY-SA 4.0

Body:
How can I access IConfiguration in an MVC View in ASP.NET Core 1.1?

Ex. _Layout.cshtml

<link href="@Configuration["MyConfigEntry"]/css/site.min.css>


问:
cast problem from class to interface
```<code>Assembly assembly = Assembly.LoadFrom("Logic\\bin\\Debug\\Logic.dll");
            Type queryManagerType = assembly.GetType("Logic." + HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
            var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);

public interface ISearchQueryManager
    {
        IList<Advertisements> ApplyQueries(string searchQuery, int page, int pageSize, string orderBy, out int count);
    }

public class SlovenianSearchQueryManager : ISearchQueryManager
    {
...
}
</code>```

but i get

Unable to cast object of type 'Logic.SlovenianSearchQueryManager' to type 'Logic.ISearchQueryManager'.

EDIT: whole stacktrace

System.InvalidCastException was
  unhandled by user code

  Message="Unable to cast object of type
  'Logic.SlovenianSearchQueryManager' to
  type 'Logic.ISearchQueryManager'."

  Source="ViaMura.Web.Module"

  StackTrace:
         at ViaMura.Web.Module.WebController.GetAdvertismentsByRawQuery(String
  rawQuery, Int32 page, Int32 pageSize,
  String orderBy, Int32& count) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\WebController.cs:line
  32
         at ViaMura.Web.Module.Views.SearchResultsPresenter.OnResultsLoad(Int32
  page, Int32 pageSize, String orderBy)
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\Views\SearchResultsPresenter.cs:line
  43
         at ViaMura.Web.SearchResults.SearchAdvertisments()
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  155
         at ViaMura.Web.SearchResults.Page_Load(Object
  sender, EventArgs e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  149
         at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
         at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e)
         at System.Web.UI.Control.OnLoad(EventArgs
  e)
         at ViaMura.Web.App_Code.PageControllers.BasePage.OnLoad(EventArgs
  e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\App_Code\PageControllers\BasePage.cs:line 89
         at System.Web.UI.Control.LoadRecursive()
         at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint)

  InnerException:

EDIT2:

```<code>string a1 = typeof (ISearchQueryManager).Assembly.Location;
string a2 = typeof(SlovenianSearchQueryManager).Assembly.Location
</code>```

give me the same result:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary
  ASP.NET
  Files\root\5438a399\53975f83\assembly\dl3\0f9540b5\15407fe2_5db7cb01\Logic.DLL

but

```<code>string a3 = queryManagerType.Assembly.Location;
</code>```

gives me different path:

D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\bin\Debug\WebCrawler.Logic.dll

答:
Can you try printing out the interfaces from the object created before casting it(Type.GetInterfaces() ).? that might give you an idea of what interfaces are exposed and you are getting what you think you are getting..
or using Activator.CreateInstance(String, String) variation and pass the Assembly name as well. </p>

Title: cast problem from class to interface

Body:
Assembly assembly = Assembly.LoadFrom("Logic\\bin\\Debug\\Logic.dll");
            Type queryManagerType = assembly.GetType("Logic." + HttpContext.Current.Session["lang_name"] + "SearchQueryManager");
            var queryManager = (ISearchQueryManager)Activator.CreateInstance(queryManagerType);

public interface ISearchQueryManager
    {
        IList<Advertisements> ApplyQueries(string searchQuery, int page, int pageSize, string orderBy, out int count);
    }

public class SlovenianSearchQueryManager : ISearchQueryManager
    {
...
}

but i get

Unable to cast object of type 'Logic.SlovenianSearchQueryManager' to type 'Logic.ISearchQueryManager'.

EDIT: whole stacktrace

System.InvalidCastException was
  unhandled by user code

  Message="Unable to cast object of type
  'Logic.SlovenianSearchQueryManager' to
  type 'Logic.ISearchQueryManager'."

  Source="ViaMura.Web.Module"

  StackTrace:
         at ViaMura.Web.Module.WebController.GetAdvertismentsByRawQuery(String
  rawQuery, Int32 page, Int32 pageSize,
  String orderBy, Int32& count) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\WebController.cs:line
  32
         at ViaMura.Web.Module.Views.SearchResultsPresenter.OnResultsLoad(Int32
  page, Int32 pageSize, String orderBy)
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web.Module\Views\SearchResultsPresenter.cs:line
  43
         at ViaMura.Web.SearchResults.SearchAdvertisments()
  in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  155
         at ViaMura.Web.SearchResults.Page_Load(Object
  sender, EventArgs e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\SearchResults.aspx.cs:line
  149
         at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
         at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e)
         at System.Web.UI.Control.OnLoad(EventArgs
  e)
         at ViaMura.Web.App_Code.PageControllers.BasePage.OnLoad(EventArgs
  e) in
  D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\App_Code\PageControllers\BasePage.cs:line 89
         at System.Web.UI.Control.LoadRecursive()
         at System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint)

  InnerException:

EDIT2:

string a1 = typeof (ISearchQueryManager).Assembly.Location;
string a2 = typeof(SlovenianSearchQueryManager).Assembly.Location

give me the same result:

C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary
  ASP.NET
  Files\root\5438a399\53975f83\assembly\dl3\0f9540b5\15407fe2_5db7cb01\Logic.DLL

but

string a3 = queryManagerType.Assembly.Location;

gives me different path:

D:\PROJEKTI\crawler\WebCrawlerSuite\WebCrawler.Logic\bin\Debug\WebCrawler.Logic.dll


问:
Classic ASP: Multiple ASPSESSIONID in cookies
I have a problem with a classic asp page and I just cannot solve it since 3 days.

The page is working with Sessions - sometimes it happens that the ASPSESSIONID cookie is set twice in the Request.ServerVariables("HTTP_COOKIE"). This causes the ASP-Page to jump between the two Sessions when the page is refreshed.

I have written an Test page which outputs the current SessionId, the Server Software and the HTTP_COOKIE value.

Sample Output:

Session ID: 308542840

Session Timeout: 20 minutes

Server Software: Microsoft-IIS/6.0

HTTP_COOKIE: ASPSESSIONIDQCBATRAD=MBHHDGCBGGBJBMAEGLDAJLGF; ASPSESSIONIDQCCDTTCB=PGHPDGCBPLKALGGKIPOFIGDM

Why are there two ASPSESSIONIDs?
When I refresh the page then it randomly outputs one of the two Session IDs.

Here is a screencast which shows the problem in IE9:
http://prinz-alexander.at/asp_test.avi

This error often occurs in ie8 and ie9.

Just do the following to recreate the Problem:

Completely close IE8 or IE9

Start IE8 or IE9 and open http://www.pfiffikus.at/pfiffikus/tests/

Immediatly after the page is loaded refresh the page mutiple times

If you repeat this steps then randomly (not always) the HTTP_COOKIE is populated with two different ASPSESSIONIDs.

The asp test file is only outputing the mentiod values, nothing else is happening in the source code.

This is the code of the asp test file:

```<code><% If trim(Session("test_val")) = "" Then
     Dim my_num
     Randomize
     number = Int((rnd*1000))+1
     Session("test_val") = number
   End If
%>

<b>Session ID:</b>
<% response.write(Session.SessionId) %><br /><br />

<b>Session("test_val"):</b>
<% response.write(Session("test_val")) %><br /><br />

<b>Session Timeout:</b>
<% response.write(Session.Timeout) %> minutes<br /><br />

<b>Server Software:</b>
<% response.write(Request.ServerVariables("SERVER_SOFTWARE")) %><br /> <br />

<b>HTTP_COOKIE:</b> <% response.write(Request.ServerVariables("HTTP_COOKIE")) %>
</code>```

How can i avoid multiple ASPSESSIONIds in cookies?

Thanks for any help!

答:
Maybe later but could be useful as there is no accepted answer.

In application pool, at recycling options, check if you do not
recycle your application too soon or you will ended with an
ASPSESSIONIDXXXXXXX for each new application you respawn.

There are several recycling conditions.
I set "minimum number of requests" to 1 by mistake and got
an ASPSESSIONID for each request

Body:
I have a problem with a classic asp page and I just cannot solve it since 3 days.

The page is working with Sessions - sometimes it happens that the ASPSESSIONID cookie is set twice in the Request.ServerVariables("HTTP_COOKIE"). This causes the ASP-Page to jump between the two Sessions when the page is refreshed.

I have written an Test page which outputs the current SessionId, the Server Software and the HTTP_COOKIE value.

Sample Output:

Session ID: 308542840

Session Timeout: 20 minutes

Server Software: Microsoft-IIS/6.0

HTTP_COOKIE: ASPSESSIONIDQCBATRAD=MBHHDGCBGGBJBMAEGLDAJLGF; ASPSESSIONIDQCCDTTCB=PGHPDGCBPLKALGGKIPOFIGDM

Why are there two ASPSESSIONIDs?
When I refresh the page then it randomly outputs one of the two Session IDs.

Here is a screencast which shows the problem in IE9:
http://prinz-alexander.at/asp_test.avi

This error often occurs in ie8 and ie9.

Just do the following to recreate the Problem:

Completely close IE8 or IE9

Start IE8 or IE9 and open http://www.pfiffikus.at/pfiffikus/tests/

Immediatly after the page is loaded refresh the page mutiple times

If you repeat this steps then randomly (not always) the HTTP_COOKIE is populated with two different ASPSESSIONIDs.

The asp test file is only outputing the mentiod values, nothing else is happening in the source code.

This is the code of the asp test file:

<% If trim(Session("test_val")) = "" Then
     Dim my_num
     Randomize
     number = Int((rnd*1000))+1
     Session("test_val") = number
   End If
%>

Session ID:
<% response.write(Session.SessionId) %>

Session("test_val"):
<% response.write(Session("test_val")) %>

Session Timeout:
<% response.write(Session.Timeout) %> minutes

Server Software:
<% response.write(Request.ServerVariables("SERVER_SOFTWARE")) %>

HTTP_COOKIE: <% response.write(Request.ServerVariables("HTTP_COOKIE")) %>

How can i avoid multiple ASPSESSIONIds in cookies?

Thanks for any help!


问:
Peek ahead when iterating an array of arrays in PHP
I have a mysql query object result which I want to parse through. Let's say the array looks like this.

```<code>$superheroes = array(
    [0] => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        "age"=>"33",
        "sex"=>"male",
    ),
    [1] => array(
        "name" => "jLaw",
        "email" => "jlaw@mail.com",
        "age"=>"22",
        "sex"=>"female",
    ),
    [2] => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        "age"=>"36",
        "sex"=>"male",
    ),
    [3] => array(
        "name" => "Gal Gadot",
        "email" => "gal@mail.com",
        "age"=>"22",
        "sex"=>"female",
    )
);
</code>```

I want to iterate through this array, and while I am at each array, I want to look ahead in the next array, and find out the age difference between current male hero and next immediate female in the list. I found a lot of posts that talk about
1. array_keys
2. caching iterators,
3. prev, next, etc.

But all of them are talking about one dimensional arrays. Here Is what I tried

```<code>foreach ($superheroes as $key => $list){
if($list['sex']=="male"){
    $currentHerosAge=$list['age'];
    while($next=next($superheroes)){
        if($next['sex']=="female"){
            $diff=$currentHerosAge -$next['age'];
            echo "Age diff: ".$diff;
            break;
        }
    }
}
</code>```

}

But when I try this, for array[0], next misses the array[1], and picks up array[3]. Not sure how to work this out.

答:
You can use array_slice to slice array form the next key index and then look for the fist female age

```<code>$diff = [];

foreach($superheroes as $key => $male) {

    if ($male['sex'] === 'female' ) continue;

    // get the next key index
    $nextKey = $key + 1;

    if ( isset( $superheroes[ $nextKey ] ) ) {

        // slice from the next key index
        $nextSuperHeros = array_slice($superheroes, $nextKey);

        foreach($nextSuperHeros as $k => $female) {

            if ($female['sex'] === 'female') {

                $diff[] = $male['age'] - $female['age'];
                break;

            }

        }

    }

}
</code>```

A working Example

Hope this helps

Body:
I have a mysql query object result which I want to parse through. Let's say the array looks like this.

$superheroes = array(
    [0] => array(
        "name" => "Peter Parker",
        "email" => "peterparker@mail.com",
        "age"=>"33",
        "sex"=>"male",
    ),
    [1] => array(
        "name" => "jLaw",
        "email" => "jlaw@mail.com",
        "age"=>"22",
        "sex"=>"female",
    ),
    [2] => array(
        "name" => "Clark Kent",
        "email" => "clarkkent@mail.com",
        "age"=>"36",
        "sex"=>"male",
    ),
    [3] => array(
        "name" => "Gal Gadot",
        "email" => "gal@mail.com",
        "age"=>"22",
        "sex"=>"female",
    )
);

I want to iterate through this array, and while I am at each array, I want to look ahead in the next array, and find out the age difference between current male hero and next immediate female in the list. I found a lot of posts that talk about
1. array_keys
2. caching iterators,
3. prev, next, etc.

But all of them are talking about one dimensional arrays. Here Is what I tried

foreach ($superheroes as $key => $list){
if($list['sex']=="male"){
    $currentHerosAge=$list['age'];
    while($next=next($superheroes)){
        if($next['sex']=="female"){
            $diff=$currentHerosAge -$next['age'];
            echo "Age diff: ".$diff;
            break;
        }
    }
}

}

But when I try this, for array[0], next misses the array[1], and picks up array[3]. Not sure how to work this out.

Body:
You can use array_slice to slice array form the next key index and then look for the fist female age

$diff = [];

foreach($superheroes as $key => $male) {

    if ($male['sex'] === 'female' ) continue;

    // get the next key index
    $nextKey = $key + 1;

    if ( isset( $superheroes[ $nextKey ] ) ) {

        // slice from the next key index
        $nextSuperHeros = array_slice($superheroes, $nextKey);

        foreach($nextSuperHeros as $k => $female) {

            if ($female['sex'] === 'female') {

                $diff[] = $male['age'] - $female['age'];
                break;

            }

        }

    }

}

A working Example

Hope this helps


问:
What exactly is it Xamarin.android.support.v7.appcompat
I'm working with Xamarin.Android.
Appcompat is actually necessary for use material design because the nougat package (Android.support.design) requires it.
But why, for example, if I work only with API 27, I must add the AppCompat package? In my toolBox i've not the floatingActionButton, NavigationDrawer etc.. so I must add this packet to unlock them.
What is exactly this package? I've read on the web that this package works with backward compatibility but I only work with new APIs, so why I must install it?
Thanks.

答: They are libraries used for accessing the latest features of an Android OS version. It is backward compatible by the way.</p>


问:
How can I trigger a reload of resolv.conf in my containers?
When running containers on startup I noticed some were using resolv.conf before systemd-resolved had updated it from the default using DHCP. This meant that containers that started too early after boot could not resolve anything and needed to be restarted to use the proper DNS settings. This is happening for different reasons for both rkt and Docker; Docker's method for updating resolv.conf inside containers is not compatible with the overlay filesystem driver and since systemd-resolved does not update the file in-place (rather creates a temporary one and renames) rkt's bind mounting does not update what the container sees.

Currently I am using a hacky systemd.unit to delay the network-online.target which docker.service and my rkt pods depend on.

```<code>[Unit]
Description=Wait for DNS

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/sh -c 'while ! getent ahosts google.com >dev/null; do sleep 1; done'

[Install]
WantedBy=network-online.target
</code>```

But this significantly delays my start-up time

```<code># systemd-analyze blame
         18.068s wait-for-dns.service
         ...
</code>```

and if resolv.conf changes again it won't help. So I was wondering if there's a more elegant solution to my problem. Idealy I'd like to be able to trigger a resolv.conf update in both rkt and Docker containers every time it changes.

答:
Run containers on a user defined network so they will use the embedded DNS server that will forward lookups to the systems DNS.

The default docker0 bridge has some special rules that were left in place for legacy support. Using a mounted /etc/resolv.conf is one of those legacy things.

If rkt doesn't support the same type of DNS then the general solution could be to setup a DNS server like Unbound to be a local forwarding resolver. Then containers have a static DNS server to reference.

Body:
When running containers on startup I noticed some were using resolv.conf before systemd-resolved had updated it from the default using DHCP. This meant that containers that started too early after boot could not resolve anything and needed to be restarted to use the proper DNS settings. This is happening for different reasons for both rkt and Docker; Docker's method for updating resolv.conf inside containers is not compatible with the overlay filesystem driver and since systemd-resolved does not update the file in-place (rather creates a temporary one and renames) rkt's bind mounting does not update what the container sees.

Currently I am using a hacky systemd.unit to delay the network-online.target which docker.service and my rkt pods depend on.

[Unit]
Description=Wait for DNS

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/sh -c 'while ! getent ahosts google.com >dev/null; do sleep 1; done'

[Install]
WantedBy=network-online.target

But this significantly delays my start-up time

# systemd-analyze blame
         18.068s wait-for-dns.service
         ...

and if resolv.conf changes again it won't help. So I was wondering if there's a more elegant solution to my problem. Idealy I'd like to be able to trigger a resolv.conf update in both rkt and Docker containers every time it changes.


问:
how to test Onesignal push notifications on localhost?
I want to test OneSignal push notifications on localhost before I deploy my app to a remote server.

I followed the instructions provided by the documentation. When I enter http://localhost as the site url I get an error message that says:

localhost is already taken. Please enter a different name.

Is there a way to use OneSignal on localhost ?

答: For anyone else struggling with this, the answer is to add 'http://localhost' but when the configurator comes back with a message similar to 'localhost is already taken. Please enter a different name.' jut scroll down and type in a different subdomain. It's not very intuitive but that worked for me.</p>


答:
I assume your question is "Which instance types can be launched without a VPC"?

Very old AWS accounts were NOT automatically creating a default VPC and there might be some instance types (I don't know which instance types) could be launched without a VPC.

Currently all AWS account will create a default VPC and you can create all instances ONLY inside a VPC.

Title: which aws instance types need subnet id specified?

Body:
Cloud formation says:

The specified instance type can only be used in a VPC. A subnet ID or
  network interface ID is required to carry out the request. Launching
  EC2 instance failed.

Which instance types do not need a subnet ID or network interface ID?


问:
Intercepting/Logging requests and Responses in GRPC
I'm developing a chat app using GRPC in which the server receives information from the client and sends it back out to all the clients connected to it. For this, I've used Saturnism's chat-example as a reference. I've replicated the code, the code compiles and runs but the server supposedly never receives any requests from client.

My question is:

Is there a way to enable verbos server side and client side logging in GRPC to see what requests and responses are going in and out & what might be failing?

I'm using the following code for server and client. What might be missing/wrong in the following code that's resulting in no communication between client and server.

WingokuServer.java

```<code>public class WingokuServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        Server server = ServerBuilder.forPort(8091)
                .intercept(recordRequestHeadersInterceptor())
                .addService(new WingokuServiceImpl())
                .build();

        System.out.println("Starting server...");
        server.start();
        System.out.println("Server started!");
        server.awaitTermination();
    }
</code>```

WingokuServerSideServiceImplementation:

```<code>public class WingokuServiceImpl extends WingokuServiceGrpc.WingokuServiceImplBase {
    private static Set<StreamObserver<Response>> observers =
            Collections.newSetFromMap(new ConcurrentHashMap<>());

    public WingokuServiceImpl() {
        System.out.println("WingokuServiceImp");
    }

    @Override
    public StreamObserver<Request> messages(StreamObserver<Response> responseObserver) {
        System.out.println("messages");
        observers.add(responseObserver);
        return new StreamObserver<Request>() {
            @Override
            public void onNext(Request request) {
                System.out.println("Server onNext: ");
                System.out.println("request from client is: "+ request.getRequestMessage());
                Response response = Response.newBuilder().setResponseMessage("new Message From server at time: "+ System.nanoTime()).build();
                for (StreamObserver<Response> observer : observers) {
                    observer.onNext(response);
                }
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("Server onError: ");
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {
                observers.remove(responseObserver);
                System.out.println("Server onCompleted ");
            }
        };
    }
}
</code>```

WingokuClient:

```<code>public class WingokuClient {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8091).usePlaintext(true).build();
        WingokuServiceGrpc.WingokuServiceStub asyncStub = WingokuServiceGrpc.newStub(channel);
        StreamObserver<Request> requestStreamObserver = asyncStub.messages(new StreamObserver<Response>() {
            @Override
            public void onNext(Response response) {
                System.out.println("Client onNext");
                System.out.println("REsponse from server is: "+ response.getResponseMessage());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("Client onError");
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("Client OnComplete");
            }
        });

        requestStreamObserver.onNext(Request.newBuilder().setRequestMessage("Message From Client").build());
        requestStreamObserver.onCompleted();
        channel.shutdown();
        System.out.println("exiting client");
    }
}
</code>```

Edit:

There is nothing wrong with the code. It works. I just needed to add awaitTermination to the client's channel because without it just closes the connection between client and server instantly, probably even before the requests go out of the client onto the network. That's why the server never received any requests.

However my question for enabling verbose logging and/or adding some sort of interceptor to the server side still remains unanswered. So I'm looking forward to getting some pointers from experts here.

答:
Also, if you would like to print the message contents or headers as seen on the server, you can create a ServerInterceptor:
https://grpc.io/grpc-java/javadoc/io/grpc/ServerInterceptor.html

You can look at the examples directory on how ServerInterceptor and ClientInterceptor work. There is not pre-existing interceptor that logs the network events.

Body:
I'm developing a chat app using GRPC in which the server receives information from the client and sends it back out to all the clients connected to it. For this, I've used Saturnism's chat-example as a reference. I've replicated the code, the code compiles and runs but the server supposedly never receives any requests from client.

My question is:

Is there a way to enable verbos server side and client side logging in GRPC to see what requests and responses are going in and out & what might be failing?

I'm using the following code for server and client. What might be missing/wrong in the following code that's resulting in no communication between client and server.

WingokuServer.java

public class WingokuServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        Server server = ServerBuilder.forPort(8091)
                .intercept(recordRequestHeadersInterceptor())
                .addService(new WingokuServiceImpl())
                .build();

        System.out.println("Starting server...");
        server.start();
        System.out.println("Server started!");
        server.awaitTermination();
    }

WingokuServerSideServiceImplementation:

public class WingokuServiceImpl extends WingokuServiceGrpc.WingokuServiceImplBase {
    private static Set<StreamObserver<Response>> observers =
            Collections.newSetFromMap(new ConcurrentHashMap<>());

    public WingokuServiceImpl() {
        System.out.println("WingokuServiceImp");
    }

    @Override
    public StreamObserver<Request> messages(StreamObserver<Response> responseObserver) {
        System.out.println("messages");
        observers.add(responseObserver);
        return new StreamObserver<Request>() {
            @Override
            public void onNext(Request request) {
                System.out.println("Server onNext: ");
                System.out.println("request from client is: "+ request.getRequestMessage());
                Response response = Response.newBuilder().setResponseMessage("new Message From server at time: "+ System.nanoTime()).build();
                for (StreamObserver<Response> observer : observers) {
                    observer.onNext(response);
                }
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("Server onError: ");
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {
                observers.remove(responseObserver);
                System.out.println("Server onCompleted ");
            }
        };
    }
}

WingokuClient:

public class WingokuClient {
    public static void main(String[] args) {
        ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8091).usePlaintext(true).build();
        WingokuServiceGrpc.WingokuServiceStub asyncStub = WingokuServiceGrpc.newStub(channel);
        StreamObserver<Request> requestStreamObserver = asyncStub.messages(new StreamObserver<Response>() {
            @Override
            public void onNext(Response response) {
                System.out.println("Client onNext");
                System.out.println("REsponse from server is: "+ response.getResponseMessage());
            }

            @Override
            public void onError(Throwable throwable) {
                System.out.println("Client onError");
                throwable.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("Client OnComplete");
            }
        });

        requestStreamObserver.onNext(Request.newBuilder().setRequestMessage("Message From Client").build());
        requestStreamObserver.onCompleted();
        channel.shutdown();
        System.out.println("exiting client");
    }
}

Edit:

There is nothing wrong with the code. It works. I just needed to add awaitTermination to the client's channel because without it just closes the connection between client and server instantly, probably even before the requests go out of the client onto the network. That's why the server never received any requests.

However my question for enabling verbose logging and/or adding some sort of interceptor to the server side still remains unanswered. So I'm looking forward to getting some pointers from experts here.


问:
How to extract just part of this string in C?
I have a version file I need to parse to get certain versions in C99. For example purposes, say one of the strings looks like this:

```<code>FILE: EXAMPLE ABC123459876-001 REV 1.IMG
</code>```

The 12345 numbers can be any arbitrary numbers, but always followed by 4 digits and a hyphen + a rev and an extension. I just want to return the middle of this string, that is, the file name + main version so: "EXAMPLE 9876-001 REV 1". I got it to work in the regex101 tester online with something like:

```<code>"(?<=EXAMPLE ABC.....)(....-... REV .)(?=.IMG)"
</code>```

... but C99 regex does not support positive lookahead / lookbehind operators so this does not work for me. Should I be using strstr() or strtok() instead? Just looking for some ideas as to the best way to be doing this in C, thanks.

答:
Simplest way would probably be to use sscanf but it does risk buffer overflow (make sure your buffers are longer than the max file path length on the system and you should be fine).

Try something like this (code not tested):

```<code>int ret;
char sequence_num_prefix[ MAX_PATH_LEN + 1 ] = {0};
char sequence_num_postfix[ MAX_PATH_LEN + 1 ] = {0};
char version_num[ MAX_PATH_LEN + 1 ] = {0};
char my_name[ MAX_PATH_LEN + 1 ] = {0};

ret = sscanf( input_path_buf, "EXAMPLE ABC%[0-9]-%[0-9] REV %[0-9]",
              sequence_num_prefix, sequence_num_postfix, version_num);

if( ret != 3 )
{
    //error
}

snprintf( my_name, sizeof( my_name ), "EXAMPLE %s-%s REV %s",
          sequence_num_prefix, sequence_num_postfix, version_num );
</code>```

Of course a safer way would be to use while loops, or, for cleanliness, use Bison.

Body:
I have a version file I need to parse to get certain versions in C99. For example purposes, say one of the strings looks like this:

FILE: EXAMPLE ABC123459876-001 REV 1.IMG

The 12345 numbers can be any arbitrary numbers, but always followed by 4 digits and a hyphen + a rev and an extension. I just want to return the middle of this string, that is, the file name + main version so: "EXAMPLE 9876-001 REV 1". I got it to work in the regex101 tester online with something like:

"(?<=EXAMPLE ABC.....)(....-... REV .)(?=.IMG)"

... but C99 regex does not support positive lookahead / lookbehind operators so this does not work for me. Should I be using strstr() or strtok() instead? Just looking for some ideas as to the best way to be doing this in C, thanks.

Body:
Simplest way would probably be to use sscanf but it does risk buffer overflow (make sure your buffers are longer than the max file path length on the system and you should be fine).

Try something like this (code not tested):

int ret;
char sequence_num_prefix[ MAX_PATH_LEN + 1 ] = {0};
char sequence_num_postfix[ MAX_PATH_LEN + 1 ] = {0};
char version_num[ MAX_PATH_LEN + 1 ] = {0};
char my_name[ MAX_PATH_LEN + 1 ] = {0};

ret = sscanf( input_path_buf, "EXAMPLE ABC%[0-9]-%[0-9] REV %[0-9]",
              sequence_num_prefix, sequence_num_postfix, version_num);

if( ret != 3 )
{
    //error
}

snprintf( my_name, sizeof( my_name ), "EXAMPLE %s-%s REV %s",
          sequence_num_prefix, sequence_num_postfix, version_num );

Of course a safer way would be to use while loops, or, for cleanliness, use Bison.


问:
Can not get button to turn uipageviewcontroller page programmatically (Using Pages extension)
I'm fiddling with uipageviewcontroller and I'm trying to go to the next page by pressing a button rather than swiping. I found a neat extension on github called 'Pages' that is supposed to be robust and easy to use, but I can't for the life of me figure this out.

The extension itself comes with previous and next button in the navigation area but I don't want those, I want to be able to press a button on the actual screen and have it go to the next page. Has anyone had any experience with this extension?

AppDelegate

```<code>import UIKit
import Pages
import Imaginary

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //let pages = pagesControllerInCode()
    let pages = pagesControllerInStoryboard()

    let navigationController = UINavigationController(rootViewController: pages)

    pages.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveBack))

    pages.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveForward))

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()

    pages.enableSwipe = false
    pages.showBottomLine = false

    return true
  }

  private func pagesControllerInCode() -> PagesController {
    var viewControllers: [UIViewController] = []

    for i in 0..<5 {
      if let imageURL = URL(string: "https://unsplash.it/375/667/?image=\(i+10)") {
        let viewController = ViewController()
        viewController.imageView.setImage(url: imageURL)

        viewControllers.append(viewController)
      }
    }

    let pages = PagesController(viewControllers)

    pages.enableSwipe = false
    pages.showBottomLine = false

    return pages
  }

  private func pagesControllerInStoryboard() -> PagesController {
    let storyboardIds = ["One","Two"]

    return PagesController(storyboardIds)
  }
}
</code>```

ViewController

```<code>import UIKit
import Pages

class ViewController: UIViewController {

  lazy var imageView = UIImageView()

  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func viewDidLayoutSubviews() {
    //corrects scrollview frame to allow for full-screen view controller pages
    for subView in self.view.subviews {
      if subView is UIScrollView {
        subView.frame = self.view.bounds
        subView.backgroundColor = UIColor.clear
      }
    }
    super.viewDidLayoutSubviews()
  }

  @IBAction func test(_ sender: UIButton) {
    NSLog("Test")
    // This is where I've been trying to figure out how to turn the page programmatically
    }
}
</code>```

答:
Since Pages is just a subclass of UIPageViewController, that class' usual method for transitioning between controllers it is:

```<code>self.transition(from:_, to: _, duration: _, options: _, animations: _, completion: _)
</code>```

If you can't seem to work with that library, i'd consider just resorting to using this method. Obviously, you'll have to manage which controllers to transition between on your own, but it could be a valuable thing to learn if you ask me.

Body:
I'm fiddling with uipageviewcontroller and I'm trying to go to the next page by pressing a button rather than swiping. I found a neat extension on github called 'Pages' that is supposed to be robust and easy to use, but I can't for the life of me figure this out.

The extension itself comes with previous and next button in the navigation area but I don't want those, I want to be able to press a button on the actual screen and have it go to the next page. Has anyone had any experience with this extension?

AppDelegate

import UIKit
import Pages
import Imaginary

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    //let pages = pagesControllerInCode()
    let pages = pagesControllerInStoryboard()

    let navigationController = UINavigationController(rootViewController: pages)

    pages.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Previous Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveBack))

    pages.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next Page",
      style: .plain,
      target: pages,
      action: #selector(PagesController.moveForward))

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()

    pages.enableSwipe = false
    pages.showBottomLine = false

    return true
  }

  private func pagesControllerInCode() -> PagesController {
    var viewControllers: [UIViewController] = []

    for i in 0..<5 {
      if let imageURL = URL(string: "https://unsplash.it/375/667/?image=\(i+10)") {
        let viewController = ViewController()
        viewController.imageView.setImage(url: imageURL)

        viewControllers.append(viewController)
      }
    }

    let pages = PagesController(viewControllers)

    pages.enableSwipe = false
    pages.showBottomLine = false

    return pages
  }

  private func pagesControllerInStoryboard() -> PagesController {
    let storyboardIds = ["One","Two"]

    return PagesController(storyboardIds)
  }
}

ViewController

import UIKit
import Pages

class ViewController: UIViewController {

  lazy var imageView = UIImageView()

  override func viewDidLoad() {
    super.viewDidLoad()

  }

  override func viewDidLayoutSubviews() {
    //corrects scrollview frame to allow for full-screen view controller pages
    for subView in self.view.subviews {
      if subView is UIScrollView {
        subView.frame = self.view.bounds
        subView.backgroundColor = UIColor.clear
      }
    }
    super.viewDidLayoutSubviews()
  }

  @IBAction func test(_ sender: UIButton) {
    NSLog("Test")
    // This is where I've been trying to figure out how to turn the page programmatically
    }
}

Body:
Since Pages is just a subclass of UIPageViewController, that class' usual method for transitioning between controllers it is:

self.transition(from:_, to: _, duration: _, options: _, animations: _, completion: _)

If you can't seem to work with that library, i'd consider just resorting to using this method. Obviously, you'll have to manage which controllers to transition between on your own, but it could be a valuable thing to learn if you ask me.


问:
working with typescript services and observables: why won't my event handler run?
I'm working with an Angular 2 project. I'm trying to work with observables and services in typescript. I am firing an event but the event handler in my observable is not running.

Here is my code:

The Service:

```<code>import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AllDataPageService {

    receptorFilterChanged$ = new Subject<any>();

}
</code>```

The service consist of one event: receptorFilterChanged.

Here is the component that fires the event (located at ~\src\results\app\all-data-page)

```<code>import { AllDataPageService } from './all-data-page.service';

...

@Component({
    selector: 'all-data-page',
    templateUrl: './all-data-page.component.html',
    styles: [require('./all-data-page.style.scss')],
    providers: [AllDataPageService]
})
export class AllDataPageComponent implements OnInit {

...

    constructor(private allDataPageService: AllDataPageService) {}

...

filterByReceptorTag() {

...

this.allDataPageService.receptorFilterChanged$.next(50.0);

...

}

...

}
</code>```

So it's the line this.allDataPageService.receptorFilterChanged$.next(50.0) in the function filterByReceptorTag() above that fires the event. I have confirmed in the Chrome debugger that this line executes.

Here is the component that handles the receptorFilterChanged event (located at ~\src\results\app\shared\components\all-data-row)

```<code>import { AllDataPageService } from '../../../all-data-page/all-data-page.service';

...

@Component({
  selector: 'all-data-row',
  templateUrl: './all-data-row.component.html',
  styles: [ require('./all-data-row.style.scss') ],
  encapsulation: ViewEncapsulation.None,
  providers: [AllDataPageService]
})
export class AllDataRowComponent implements OnInit {

...

  constructor(private allDataPageService: AllDataPageService) {
      this.allDataPageService.receptorFilterChanged$.subscribe(
          (value) => {

...

          }
      );
  }

...

}
</code>```

When the receptorFilterChanged fires, the event handler that I subscribe above does not run.

Can anyone see what might be going on?

Thanks.

答:
Can anyone see what might be going on?

Timing issue. subscribe is happening after next so doesn't get the original value

Body:
I'm working with an Angular 2 project. I'm trying to work with observables and services in typescript. I am firing an event but the event handler in my observable is not running.

Here is my code:

The Service:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class AllDataPageService {

    receptorFilterChanged$ = new Subject<any>();

}

The service consist of one event: receptorFilterChanged.

Here is the component that fires the event (located at ~\src\results\app\all-data-page)

import { AllDataPageService } from './all-data-page.service';

...

@Component({
    selector: 'all-data-page',
    templateUrl: './all-data-page.component.html',
    styles: [require('./all-data-page.style.scss')],
    providers: [AllDataPageService]
})
export class AllDataPageComponent implements OnInit {

...

    constructor(private allDataPageService: AllDataPageService) {}

...

filterByReceptorTag() {

...

this.allDataPageService.receptorFilterChanged$.next(50.0);

...

}

...

}

So it's the line this.allDataPageService.receptorFilterChanged$.next(50.0) in the function filterByReceptorTag() above that fires the event. I have confirmed in the Chrome debugger that this line executes.

Here is the component that handles the receptorFilterChanged event (located at ~\src\results\app\shared\components\all-data-row)

import { AllDataPageService } from '../../../all-data-page/all-data-page.service';

...

@Component({
  selector: 'all-data-row',
  templateUrl: './all-data-row.component.html',
  styles: [ require('./all-data-row.style.scss') ],
  encapsulation: ViewEncapsulation.None,
  providers: [AllDataPageService]
})
export class AllDataRowComponent implements OnInit {

...

  constructor(private allDataPageService: AllDataPageService) {
      this.allDataPageService.receptorFilterChanged$.subscribe(
          (value) => {

...

          }
      );
  }

...

}

When the receptorFilterChanged fires, the event handler that I subscribe above does not run.

Can anyone see what might be going on?

Thanks.


问:
Old version of sbjson throw exception in iOS 10
My problem is about coding in old version of sbjson,
there are some code which caused exception in iOS 10.3.3 compiled in XCode 8.3.3.

Update to new version of sbjson might work but since i am maintaining the iOS app, i don't want to change too much on the source code of the application.

In the old version, the class [SBJsonStreamParser.h] and [SBJsonStreamWriter.h] have code which define the @property of [SBJsonStreamParserState *state], [SBJsonStreamWriterState *state] as (nonatomic, assign) follow by a manual retain release setting [__weak],

which cause the error:

Unsafe_unretained property 'status' may not also be declared __weak

May i ask if it'll work fine if i just comment out the 'assign' setting of property, hence:

@property (nonatomic /* , assign*/) __weak SBJsonStreamWriterState
  *state

Thanks a lot for the help

答:
I don't think it was possible to use weak as a property modifier back when I wrote that, but the following might work now:

```<code>@property (nonatomic, weak) SBJsonStreamWriterState *state
</code>```

Body:
I don't think it was possible to use weak as a property modifier back when I wrote that, but the following might work now:

@property (nonatomic, weak) SBJsonStreamWriterState *state


问:
LoaderCallbacks.onLoadFinished not called if orientation change happens during AsyncTaskLoader run
Using android-support-v4.jar and FragmentActivity (no fragments at this point)

I have an AsyncTaskLoader which I start loading and then change the orientation while the background thread is still running.  In my logs I see the responses come through to the background requests.  The responses complete and I expect onLoadFinished() to be called, but it never is.

As a means of troubleshooting, in the Manifest, if I set android:configChanges="orientation" onLoadFinished() gets called as expected.

My Activity implements the loader callbacks.  In the source for LoaderManager.initLoader() I see that if the loader already exists, the new callback is set to the LoaderInfo inner object class but I don't see where Loader.registerListener() is called again.  registerListener only seems to be called when LoaderManagerImpl.createAndInstallLoader() is called.

I suspect that since the activity is destroyed and recreated on orientation change and since it is the listener for callbacks, the new activity is not registered to be notified.

Can anyone confirm my understanding and what the solution so that onLoadFinished is called after orientation change?

答:
It's actually not the call to initLoader() in onCreate() that's fixing it. It's the call to getLoaderManager(). In summary, what happens is that when an activity is restarted, it already knows about the loaders. It tries to restart them when your activity hits onStart(), but then it hits this code in FragmentHostCallback.doLoaderStart()*:

```<code>void doLoaderStart() {
    if (mLoadersStarted) {
        return;
    }
    mLoadersStarted = true;

    if (mLoaderManager != null) {
        mLoaderManager.doStart();
    } else if (!mCheckedForLoaderManager) {
        mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
        // WTF: Why aren't we calling doStart() here?!
    }
    mCheckedForLoaderManager = true;
}
</code>```

Since getLoaderManager() wasn't called yet, mLoaderManager is null. It therefore skips the first condition and the call to mLoaderManager.doStart().

You can test this by simply putting a call to getLoaderManager() in onCreate(). You don't need to call init / restart loaders there.

This really seems like a bug to me.

* This is the code path even if you aren't using fragments, so don't get confused by that.

Body:
It's actually not the call to initLoader() in onCreate() that's fixing it. It's the call to getLoaderManager(). In summary, what happens is that when an activity is restarted, it already knows about the loaders. It tries to restart them when your activity hits onStart(), but then it hits this code in FragmentHostCallback.doLoaderStart()*:

void doLoaderStart() {
    if (mLoadersStarted) {
        return;
    }
    mLoadersStarted = true;

    if (mLoaderManager != null) {
        mLoaderManager.doStart();
    } else if (!mCheckedForLoaderManager) {
        mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
        // WTF: Why aren't we calling doStart() here?!
    }
    mCheckedForLoaderManager = true;
}

Since getLoaderManager() wasn't called yet, mLoaderManager is null. It therefore skips the first condition and the call to mLoaderManager.doStart().

You can test this by simply putting a call to getLoaderManager() in onCreate(). You don't need to call init / restart loaders there.

This really seems like a bug to me.

* This is the code path even if you aren't using fragments, so don't get confused by that.


问:
Azure Function default authorization key changing on publish
Is this intended? We had an Azure function that we had running and setup our connection to it with the default function key since we specified function level authorization and everything was working great. We also setup CD on this function with it syncing to a github repo on the master branch. We just found out this morning that when we pushed some new changes to master last night and it built that our connection broke. When we looked back at the function key it was different than when we had originally configured it.

So my question is this. Does the generated default function key get automatically renewed when you publish new changes to a function? Is that intended behavior? And if so, what do you do to keep a stable connection for your clients even when updates are made to these kinds of functions?

Or is this potentially just an issue with CD?

答: There was an issue around keys getting deleted, and a new Functions Runtime (version 1.0.11380) was deployed on Monday to address the issue.</p>


问:
Empty return of NodeJS in Angular
My NodeJs application return in this url (http://localhost:3000/api/campaigns) a json response.

But when my Angular application call this url, get a empty response.
I try to change the 200 http code to 404, and I see this change, but always there ara a empty response.

Angular:

```<code>var campaigns = function(country) {
  var deferred = $q.defer();

  $http.get( "http://localhost:3000/api/campaigns" ).then(function(response) {
    deferred.resolve(response);
  }, function(response) {
     deferred.reject(response);
  });
  return deferred.promise
}
</code>```

And in my NodeJs code:

```<code>exports.findAllCampaigns = function(req, res) {

  Campaign
    .find({})
    .limit(10)
    .exec(function(err, campaigns) {
        if(err) res.send(500, err.message);

        res.status(200).jsonp(campaigns);
    });

};
</code>```

In my browser console, the XHR request is always empty (http 200).

答:
This is just to have a response on this question (i would like that either charlietfl or Carlos Vazquez posted this as response rather than me :) )

BY charlietfl --> Just implement CORS in api

BY Carlos Vázquez --> Thanks! I just enabled the cors middleware with:

var cors = require('cors');
 var app = express();
 app.use(cors());

Title: Empty return of NodeJS in Angular

Body:
My NodeJs application return in this url (http://localhost:3000/api/campaigns) a json response.

But when my Angular application call this url, get a empty response.
I try to change the 200 http code to 404, and I see this change, but always there ara a empty response.

Angular:

var campaigns = function(country) {
  var deferred = $q.defer();

  $http.get( "http://localhost:3000/api/campaigns" ).then(function(response) {
    deferred.resolve(response);
  }, function(response) {
     deferred.reject(response);
  });
  return deferred.promise
}

And in my NodeJs code:

exports.findAllCampaigns = function(req, res) {

  Campaign
    .find({})
    .limit(10)
    .exec(function(err, campaigns) {
        if(err) res.send(500, err.message);

        res.status(200).jsonp(campaigns);
    });

};

In my browser console, the XHR request is always empty (http 200).


问:
How do I add constraints to a subview loaded from a nib file?
I'm trying to load a sub view on to every single page of my app from a nib file. Right now I'm using a somewhat unusual approach to loading this sub view in that I am doing it through an extension of UIStoryboard (probably not relevant to my problem, but I'm not sure). So this is how the code looks when I load the nib file:

```<code>extension UIStoryboard {
    public func appendCustomView(to viewController: UIViewController) {
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            viewController.view.addSubview(myCustomSubview)
        }
    }
}
</code>```

This code does what it's supposed to do and adds "MyCustomSubview" to the view controller (I won't go in to detail on exactly how this method gets called because it works so it doesn't seem important). The problem is I can't for the life of me figure out how to add constraints that effect the size of myCustomSubview. I have tried putting code in the function I showed above as well as in the MyCustomSubview swift file to add constraints but no matter what I do the subview never changes.

Ideally the constraints would pin "MyCustomSubview" to the bottom of the ViewController, with width set to the size of the screen and a hard coded height constraint.

Here are the two main methods I tried (with about 100 minor variations for each) that did NOT work:

Method 1 - Add constraint directly from "appendCustomView"

```<code>public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        let top = NSLayoutConstraint(item: myCustomSubview, attribute: .top, relatedBy: .equal
        , toItem: viewController.view, attribute: .top, multiplier: 1, constant: 50.0)

        viewController.view.addSubview(myCustomSubview)
        viewController.view.addConstraint(top)
    }
}
</code>```

Method 2 - Add constraint outlets and setter method in MyCustomSubview

```<code>class MyCustomSubview: UIView {
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func setConstraints(){
        self.widthConstraint.constant = UIScreen.main.bounds.size.width
        self.heightConstraint.constant = 20
    }
}
</code>```

And call setter method in "appendCustomView"

```<code>public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        myCustomSubview.setConstraints()
        viewController.view.addSubview(myCustomSubview)
    }
}
</code>```

(*note: the actual constraints of these examples are irrelevant and I wasn't trying to meet the specs I mentioned above, I was just trying to make any sort of change to the view to know that the constraints were updating. They weren't.)

Edit : Changed "MyCustomNib" to "MyCustomSubview" for clarity.

答:
When you add constraints onto a view from a Nib, you have to call yourView.translatesAutoresizingMaskIntoConstraints = false, and you also need to make sure that you have all 4 (unless it's a label or a few other view types which only need 2) constraints in place:

Here's some sample code that makes a view fill it's parent view:

```<code>        parentView.addSubview(yourView)

        yourView.translatesAutoresizingMaskIntoConstraints = false

        yourView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
        yourView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
        yourView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
        yourView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true
</code>```

Edit: I've actually come around to perferring this method of adding NSLayoutConstraints, even though the results are the same

```<code>NSLayoutConstraint.activate([
            yourView.topAnchor.constraint(equalTo: parentView.topAnchor),
            yourView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            yourView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor),
            yourView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
])
</code>```

Body:
I'm trying to load a sub view on to every single page of my app from a nib file. Right now I'm using a somewhat unusual approach to loading this sub view in that I am doing it through an extension of UIStoryboard (probably not relevant to my problem, but I'm not sure). So this is how the code looks when I load the nib file:

extension UIStoryboard {
    public func appendCustomView(to viewController: UIViewController) {
        if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {
            viewController.view.addSubview(myCustomSubview)
        }
    }
}

This code does what it's supposed to do and adds "MyCustomSubview" to the view controller (I won't go in to detail on exactly how this method gets called because it works so it doesn't seem important). The problem is I can't for the life of me figure out how to add constraints that effect the size of myCustomSubview. I have tried putting code in the function I showed above as well as in the MyCustomSubview swift file to add constraints but no matter what I do the subview never changes.

Ideally the constraints would pin "MyCustomSubview" to the bottom of the ViewController, with width set to the size of the screen and a hard coded height constraint.

Here are the two main methods I tried (with about 100 minor variations for each) that did NOT work:

Method 1 - Add constraint directly from "appendCustomView"

public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        let top = NSLayoutConstraint(item: myCustomSubview, attribute: .top, relatedBy: .equal
        , toItem: viewController.view, attribute: .top, multiplier: 1, constant: 50.0)

        viewController.view.addSubview(myCustomSubview)
        viewController.view.addConstraint(top)
    }
}

Method 2 - Add constraint outlets and setter method in MyCustomSubview

class MyCustomSubview: UIView {
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!

    func setConstraints(){
        self.widthConstraint.constant = UIScreen.main.bounds.size.width
        self.heightConstraint.constant = 20
    }
}

And call setter method in "appendCustomView"

public func appendCustomView(to viewController: UIViewController) {
    if let myCustomSubview = Bundle.main.loadNibNamed("MyCustomSubview", owner: nil, options: nil)![0] as? MyCustomSubview {

        myCustomSubview.setConstraints()
        viewController.view.addSubview(myCustomSubview)
    }
}

(*note: the actual constraints of these examples are irrelevant and I wasn't trying to meet the specs I mentioned above, I was just trying to make any sort of change to the view to know that the constraints were updating. They weren't.)

Edit : Changed "MyCustomNib" to "MyCustomSubview" for clarity.

Body:
When you add constraints onto a view from a Nib, you have to call yourView.translatesAutoresizingMaskIntoConstraints = false, and you also need to make sure that you have all 4 (unless it's a label or a few other view types which only need 2) constraints in place:

Here's some sample code that makes a view fill it's parent view:

        parentView.addSubview(yourView)

        yourView.translatesAutoresizingMaskIntoConstraints = false

        yourView.topAnchor.constraint(equalTo: parentView.topAnchor).isActive = true
        yourView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor).isActive = true
        yourView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor).isActive = true
        yourView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor).isActive = true

Edit: I've actually come around to perferring this method of adding NSLayoutConstraints, even though the results are the same

NSLayoutConstraint.activate([
            yourView.topAnchor.constraint(equalTo: parentView.topAnchor),
            yourView.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            yourView.bottomAnchor.constraint(equalTo: parentView.bottomAnchor),
            yourView.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
])


问:
How do I query an n:n relationship from MS Dynamics CRM via SOAP?
I need to add some linked entities to a SOAP query on a Dynamics 365 CRM (the version it reports is Version 1612 (8.2.1.176) (DB 8.2.1.176)). The client implementation is in PHP.

With some trial and error and a lot of examples, I have been able to put together something like the following request body. (I'm not sure if this is the best way to structure a query; there seem to be several others including <fetch>, but this one has worked so far.)

```<code><Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:si="http://www.w3.org/2001/XMLSchema-instance">
  <request xmlns:c="http://schemas.microsoft.com/xrm/2011/Contracts" si:type="c:RetrieveMultipleRequest">
    <c:Parameters xmlns:c2="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
      <c:KeyValuePairOfstringanyType>
        <c2:key>Query</c2:key>
        <c2:value si:type="c:QueryExpression">
          <c:ColumnSet>
            <c:AllColumns>true</c:AllColumns>
            <c:Columns/>
          </c:ColumnSet>
          <c:EntityName>entity1</c:EntityName>
          <c:LinkEntities>
            <c:LinkEntity>
              <c:LinkFromAttributeName>entity2id</c:LinkFromAttributeName>
              <c:LinkFromEntityName>entity1</c:LinkFromEntityName>
              <c:LinkToAttributeName>entity2id</c:LinkToAttributeName>
              <c:LinkToEntityName>entity2</c:LinkToEntityName>
              <c:JoinOperator>Inner</c:JoinOperator>
              <c:LinkEntities>
                <c:LinkEntity>
                  <c:LinkFromAttributeName>entity3id</c:LinkFromAttributeName>
                  <c:LinkFromEntityName>entity2</c:LinkFromEntityName>
                  <c:LinkToAttributeName>entity3id</c:LinkToAttributeName>
                  <c:LinkToEntityName>entity3</c:LinkToEntityName>
                  <c:JoinOperator>Inner</c:JoinOperator>
                </c:LinkEntity>
              </c:LinkEntities>
            </c:LinkEntity>
          </c:LinkEntities>
          <c:Orders>
            <c:OrderExpression>
              <c:AttributeName>name</c:AttributeName>
              <c:OrderType>Ascending</c:OrderType>
            </c:OrderExpression>
          </c:Orders>
          <c:PageInfo>
            <c:Count>1</c:Count>
            <c:PageNumber>1</c:PageNumber>
          </c:PageInfo>
        </c2:value>
      </c:KeyValuePairOfstringanyType>
    </c:Parameters>
    <c:RequestName>RetrieveMultiple</c:RequestName>
  </request>
</Execute>
</code>```

(In this case, the relationship seems to be 1:n from entity1 to entity2, and n:1 from entity2 to entity3. In effect, entity2 contains only the foreign keys for joining entity1 and entity3, with some extra attributes.)

This query is apparently executed correctly (it runs without error, and it limits the result set according to the inner join), but I only get back columns from the first entity type.

How do I actually get the attributes of the joined entities?

Edit:

I have tried adding each of the following to the <c:LinkEntity> element:

```<code><c:ColumnSet>
  <c:AllColumns>true</c:AllColumns>
</c:ColumnSet>

<c:Columns>
  <c:AllColumns>true</c:AllColumns>
</c:Columns>

<c:Columns>
  <a:string xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    attribute1
  </a:string>
</c:Columns>

<c:ColumnSet>
  <c:Columns>
    <a:string xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
      attribute1
    </a:string>
  </c:Columns>
</c:ColumnSet>
</code>```

Unfortunately, while none of these have caused an error, they also haven't changed the output.

答:
Placing the Columns element like below worked.

```<code><Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:si="http://www.w3.org/2001/XMLSchema-instance">
  <request xmlns:c="http://schemas.microsoft.com/xrm/2011/Contracts" si:type="c:RetrieveMultipleRequest">
    <c:Parameters xmlns:c2="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
      <c:KeyValuePairOfstringanyType>
        <c2:key>Query</c2:key>
        <c2:value si:type="c:QueryExpression">
          <c:ColumnSet>
            <c:AllColumns>true</c:AllColumns>
            <c:Columns/>
          </c:ColumnSet>
          <c:EntityName>entity1</c:EntityName>
          <c:LinkEntities>
             <c:LinkEntity>

              <c:Columns>
                <c:AllColumns>true</c:AllColumns>
              </c:Columns>

              <c:LinkFromAttributeName>entity2id</c:LinkFromAttributeName>
              <c:LinkFromEntityName>entity1</c:LinkFromEntityName>
              <c:LinkToAttributeName>entity2id</c:LinkToAttributeName>
              <c:LinkToEntityName>entity2</c:LinkToEntityName>
              <c:JoinOperator>Inner</c:JoinOperator>
              <c:LinkEntities>
                <c:LinkEntity>
                  <c:LinkFromAttributeName>entity3id</c:LinkFromAttributeName>
                  <c:LinkFromEntityName>entity2</c:LinkFromEntityName>
                  <c:LinkToAttributeName>entity3id</c:LinkToAttributeName>
                  <c:LinkToEntityName>entity3</c:LinkToEntityName>
                  <c:JoinOperator>Inner</c:JoinOperator>
                </c:LinkEntity>
              </c:LinkEntities>
            </c:LinkEntity>
          </c:LinkEntities>
          <c:Orders>
            <c:OrderExpression>
              <c:AttributeName>name</c:AttributeName>
              <c:OrderType>Ascending</c:OrderType>
            </c:OrderExpression>
          </c:Orders>
          <c:PageInfo>
            <c:Count>1</c:Count>
            <c:PageNumber>1</c:PageNumber>
          </c:PageInfo>
        </c2:value>
      </c:KeyValuePairOfstringanyType>
    </c:Parameters>
    <c:RequestName>RetrieveMultiple</c:RequestName>
  </request>
</Execute>
</code>```

Body:
I need to add some linked entities to a SOAP query on a Dynamics 365 CRM (the version it reports is Version 1612 (8.2.1.176) (DB 8.2.1.176)). The client implementation is in PHP.

With some trial and error and a lot of examples, I have been able to put together something like the following request body. (I'm not sure if this is the best way to structure a query; there seem to be several others including <fetch>, but this one has worked so far.)

<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:si="http://www.w3.org/2001/XMLSchema-instance">
  <request xmlns:c="http://schemas.microsoft.com/xrm/2011/Contracts" si:type="c:RetrieveMultipleRequest">
    <c:Parameters xmlns:c2="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
      <c:KeyValuePairOfstringanyType>
        <c2:key>Query</c2:key>
        <c2:value si:type="c:QueryExpression">
          <c:ColumnSet>
            <c:AllColumns>true</c:AllColumns>
            <c:Columns/>
          </c:ColumnSet>
          <c:EntityName>entity1</c:EntityName>
          <c:LinkEntities>
            <c:LinkEntity>
              <c:LinkFromAttributeName>entity2id</c:LinkFromAttributeName>
              <c:LinkFromEntityName>entity1</c:LinkFromEntityName>
              <c:LinkToAttributeName>entity2id</c:LinkToAttributeName>
              <c:LinkToEntityName>entity2</c:LinkToEntityName>
              <c:JoinOperator>Inner</c:JoinOperator>
              <c:LinkEntities>
                <c:LinkEntity>
                  <c:LinkFromAttributeName>entity3id</c:LinkFromAttributeName>
                  <c:LinkFromEntityName>entity2</c:LinkFromEntityName>
                  <c:LinkToAttributeName>entity3id</c:LinkToAttributeName>
                  <c:LinkToEntityName>entity3</c:LinkToEntityName>
                  <c:JoinOperator>Inner</c:JoinOperator>
                </c:LinkEntity>
              </c:LinkEntities>
            </c:LinkEntity>
          </c:LinkEntities>
          <c:Orders>
            <c:OrderExpression>
              <c:AttributeName>name</c:AttributeName>
              <c:OrderType>Ascending</c:OrderType>
            </c:OrderExpression>
          </c:Orders>
          <c:PageInfo>
            <c:Count>1</c:Count>
            <c:PageNumber>1</c:PageNumber>
          </c:PageInfo>
        </c2:value>
      </c:KeyValuePairOfstringanyType>
    </c:Parameters>
    <c:RequestName>RetrieveMultiple</c:RequestName>
  </request>
</Execute>

(In this case, the relationship seems to be 1:n from entity1 to entity2, and n:1 from entity2 to entity3. In effect, entity2 contains only the foreign keys for joining entity1 and entity3, with some extra attributes.)

This query is apparently executed correctly (it runs without error, and it limits the result set according to the inner join), but I only get back columns from the first entity type.

How do I actually get the attributes of the joined entities?

Edit:

I have tried adding each of the following to the <c:LinkEntity> element:

<c:ColumnSet>
  <c:AllColumns>true</c:AllColumns>
</c:ColumnSet>

<c:Columns>
  <c:AllColumns>true</c:AllColumns>
</c:Columns>

<c:Columns>

    attribute1

</c:Columns>

<c:ColumnSet>
  <c:Columns>

      attribute1

  </c:Columns>
</c:ColumnSet>

Unfortunately, while none of these have caused an error, they also haven't changed the output.

Body:
Placing the Columns element like below worked.

<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:si="http://www.w3.org/2001/XMLSchema-instance">
  <request xmlns:c="http://schemas.microsoft.com/xrm/2011/Contracts" si:type="c:RetrieveMultipleRequest">
    <c:Parameters xmlns:c2="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
      <c:KeyValuePairOfstringanyType>
        <c2:key>Query</c2:key>
        <c2:value si:type="c:QueryExpression">
          <c:ColumnSet>
            <c:AllColumns>true</c:AllColumns>
            <c:Columns/>
          </c:ColumnSet>
          <c:EntityName>entity1</c:EntityName>
          <c:LinkEntities>
             <c:LinkEntity>

              <c:Columns>
                <c:AllColumns>true</c:AllColumns>
              </c:Columns>

              <c:LinkFromAttributeName>entity2id</c:LinkFromAttributeName>
              <c:LinkFromEntityName>entity1</c:LinkFromEntityName>
              <c:LinkToAttributeName>entity2id</c:LinkToAttributeName>
              <c:LinkToEntityName>entity2</c:LinkToEntityName>
              <c:JoinOperator>Inner</c:JoinOperator>
              <c:LinkEntities>
                <c:LinkEntity>
                  <c:LinkFromAttributeName>entity3id</c:LinkFromAttributeName>
                  <c:LinkFromEntityName>entity2</c:LinkFromEntityName>
                  <c:LinkToAttributeName>entity3id</c:LinkToAttributeName>
                  <c:LinkToEntityName>entity3</c:LinkToEntityName>
                  <c:JoinOperator>Inner</c:JoinOperator>
                </c:LinkEntity>
              </c:LinkEntities>
            </c:LinkEntity>
          </c:LinkEntities>
          <c:Orders>
            <c:OrderExpression>
              <c:AttributeName>name</c:AttributeName>
              <c:OrderType>Ascending</c:OrderType>
            </c:OrderExpression>
          </c:Orders>
          <c:PageInfo>
            <c:Count>1</c:Count>
            <c:PageNumber>1</c:PageNumber>
          </c:PageInfo>
        </c2:value>
      </c:KeyValuePairOfstringanyType>
    </c:Parameters>
    <c:RequestName>RetrieveMultiple</c:RequestName>
  </request>
</Execute>


答:
Your "AllDataPageService" is scoped to both the AllDataPageComponent and also the AllDataRowComponent. That means each of these components gets a new instance of that AllDataPageService service.

You should remove the

```<code>providers: [AllDataPageService]
</code>```

from each of your components and move it to a "Module" instead. That way, you'll only have one instance of your service so they'll be able to talk to each other.

Title: working with typescript services and observables: why won't my event handler run?

Body:
Your "AllDataPageService" is scoped to both the AllDataPageComponent and also the AllDataRowComponent. That means each of these components gets a new instance of that AllDataPageService service.

You should remove the

providers: [AllDataPageService]

from each of your components and move it to a "Module" instead. That way, you'll only have one instance of your service so they'll be able to talk to each other.


问:
How do I find all the modules used by a Perl script?
I'm getting ready to try to deploy some code to multiple machines. As far as I know, using a Makefile.pm to track dependencies is the best way to ensure they are installed everywhere.  The problem I have is I'm not sure our Makefile.pm has been updated as this application has passed through a few different developers.

Is there any way to automatically parse through either my source or a few full runs of my program to determine exactly what versions of what modules my application is depending on?  On top of that, is there any way to filter it based on CPAN packages? (So that I only depend on Moose instead of every single module that comes with Moose.)

A third related question is, if you depend on a version of a module that is not the latest, what is the best way to have someone else install it? Should I start including entire localized Perl installations with my application?

答:
Module::ScanDeps - Recursively scan Perl code for dependencies

Does both static and runtime scanning.  Just modules, I don't know of any exact way of verifying what versions from what distributions.  You could get old packages from BackPan, or just package your entire chain of local dependencies up with PAR.


问:
Removing class from scrollspy link
How can i remove the active class on this link and replace it with active2 using jQuery?

```<code><li class="contact active"><a href="#contact" class="contact">Contact</a></li>
</code>```

remove

active {background-color: black;}

replace

active2 {background-color: red;}

答:
Use switchClass:

```<code>$( "li.contact" ).switchClass( "active", "active2");
</code>```

For more info, see this link on switchClass.

Title: Removing class from scrollspy link

Body:
How can i remove the active class on this link and replace it with active2 using jQuery?

Contact

remove

active {background-color: black;}

replace

active2 {background-color: red;}

Body:
Use switchClass:

$( "li.contact" ).switchClass( "active", "active2");

For more info, see this link on switchClass.