问:
Accesing TabLayout's Fragment within the activity
I'm trying to access the fragment's tag within the activity to perform some logic in that particular fragment by triggering one method(refreshData).Since the fragment comes under Tablayout, i'm fully stuck on how to access the fragment under my activity.
The following is the code snippet:

```<code>   private void updateFragment(Intent intent){
        FragmentManager manager = getSupportFragmentManager();
        for (int i = 0; i < manager.getBackStackEntryCount(); i++) {
            if (MyFragment.class.getName().equalsIgnoreCase(manager.getBackStackEntryAt(i).getName())) {
                MyFragment currentFragment = (MyFragment)manager.findFragmentByTag(manager.getBackStackEntryAt(i).getName());
                currentFragment.refreshData(intent);
                break;
            }
        }
    }
</code>```

The following way I'm creating two fragment under TabLayout

```<code> @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    MyFragment newsFragment = new MyFragment();

                    return newsFragment;

                case 1:
                    return new MySecondFragment();
            }
            return null;
        }
</code>```

答:
I tend to favor the ArrayList approach for storing the Fragment references.  The key to this working is instantiateItem(ViewGroup container, int position). This is probably the most important method in the PagerAdapter as it is responsible for re-attaching the fragments on a configuration change.  It will only call getItem(int position) if it does not find a fragment in memory.  By implementing this method and having it put the re-attached fragments into the ArrayList you will have the same fragments in the list after a configuration change.

```<code>public class SomePagerAdapter extends FragmentPagerAdapter {

        private ArrayList<Fragment> fragments = new ArrayList<>(4);

        public SomePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return FirstFragment.newInstance();
                case 1:
                    return SecondFragment.newInstance();;
                default:
                    return new Fragment();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = (Fragment) super.instantiateItem(container, position);
            fragments.add(fragment);
            return fragment;
        }

        @Override
        public int getCount() {
            return 2;
        }

        public ArrayList<Fragment> getFragments() {
            return fragments;
        }
    }
</code>```

You can use the above code like this:

```<code>if(pagerAdapter.getFragments.get(whateverPosition) instanceof FirstFragment {
      ((FirstFragment)pagerAdapter.getFragments().get(whateverPosition)).refreshData(intent);
}
</code>```

The check for instanceof is not really needed if you are always sure of what you are accessing, I just prefer to be sure that what I am accessing is what I expect.

The other answer will work until a configuration change. After that you will find yourself referencing an entirely new fragment which may not be what you expected to happen.

Also keep in mind, it is best practice to instantiate a Fragment with the newInstance static method due to the way the System uses the consructors of a Fragment. You can pass anything you want through newInstance() which you cannot do with a constructor.

Body:
I'm trying to access the fragment's tag within the activity to perform some logic in that particular fragment by triggering one method(refreshData).Since the fragment comes under Tablayout, i'm fully stuck on how to access the fragment under my activity.
The following is the code snippet:

   private void updateFragment(Intent intent){
        FragmentManager manager = getSupportFragmentManager();
        for (int i = 0; i < manager.getBackStackEntryCount(); i++) {
            if (MyFragment.class.getName().equalsIgnoreCase(manager.getBackStackEntryAt(i).getName())) {
                MyFragment currentFragment = (MyFragment)manager.findFragmentByTag(manager.getBackStackEntryAt(i).getName());
                currentFragment.refreshData(intent);
                break;
            }
        }
    }

The following way I'm creating two fragment under TabLayout

 @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    MyFragment newsFragment = new MyFragment();

                    return newsFragment;

                case 1:
                    return new MySecondFragment();
            }
            return null;
        }

Body:
I tend to favor the ArrayList approach for storing the Fragment references.  The key to this working is instantiateItem(ViewGroup container, int position). This is probably the most important method in the PagerAdapter as it is responsible for re-attaching the fragments on a configuration change.  It will only call getItem(int position) if it does not find a fragment in memory.  By implementing this method and having it put the re-attached fragments into the ArrayList you will have the same fragments in the list after a configuration change.

public class SomePagerAdapter extends FragmentPagerAdapter {

        private ArrayList<Fragment> fragments = new ArrayList<>(4);

        public SomePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    return FirstFragment.newInstance();
                case 1:
                    return SecondFragment.newInstance();;
                default:
                    return new Fragment();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = (Fragment) super.instantiateItem(container, position);
            fragments.add(fragment);
            return fragment;
        }

        @Override
        public int getCount() {
            return 2;
        }

        public ArrayList<Fragment> getFragments() {
            return fragments;
        }
    }

You can use the above code like this:

if(pagerAdapter.getFragments.get(whateverPosition) instanceof FirstFragment {
      ((FirstFragment)pagerAdapter.getFragments().get(whateverPosition)).refreshData(intent);
}

The check for instanceof is not really needed if you are always sure of what you are accessing, I just prefer to be sure that what I am accessing is what I expect.

The other answer will work until a configuration change. After that you will find yourself referencing an entirely new fragment which may not be what you expected to happen.

Also keep in mind, it is best practice to instantiate a Fragment with the newInstance static method due to the way the System uses the consructors of a Fragment. You can pass anything you want through newInstance() which you cannot do with a constructor.


来源: stackexchange

问:
How to zip two Java Lists
I have 2 Lists:

```<code>List<String> subjectArr = Arrays.asList<String>("aa", "bb", "cc");
List<Long> numArr = Arrays.asList<Long>(2L, 6L, 4L);
</code>```

How do I create new List and zip two Lists into it?

```<code>List<?> subjectNumArr = zip(subjectArr, numArr);
// subjectNumArr == [{'aa',2},{'bb',6},{'cc',4}]
</code>```

答:
Use one of the answers from Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)
to zip and apply a function at the same time

e.g. Using a zipped Stream:

```<code><A,B,C>  Stream<C> zipped(List<A> lista, List<B> listb, BiFunction<A,B,C> zipper){
     int shortestLength = Math.min(lista.size(),listb.size());
     return IntStream.range(0,shortestLength).mapToObject( i -> {
          return zipper.apply(lista.get(i), listb.get(i));
     });
}
</code>```

for which you may also use Guava's Streams.zip()

ContentLicense: CC BY-SA 3.0

Title: How to zip two Java Lists

Body:
I have 2 Lists:

List<String> subjectArr = Arrays.asList<String>("aa", "bb", "cc");
List<Long> numArr = Arrays.asList<Long>(2L, 6L, 4L);

How do I create new List and zip two Lists into it?

List<?> subjectNumArr = zip(subjectArr, numArr);
// subjectNumArr == [{'aa',2},{'bb',6},{'cc',4}]

Body:
Use one of the answers from Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)
to zip and apply a function at the same time

e.g. Using a zipped Stream:

<A,B,C>  Stream<C> zipped(List<A> lista, List<B> listb, BiFunction<A,B,C> zipper){
     int shortestLength = Math.min(lista.size(),listb.size());
     return IntStream.range(0,shortestLength).mapToObject( i -> {
          return zipper.apply(lista.get(i), listb.get(i));
     });
}

for which you may also use Guava's Streams.zip()


问:
VBScript get process id by process name or program executable name
I need to do exactly as I asked in the question for any program that I have just started from my VBScript.

I am starting the System Properties program from VBscript as below:

```<code>Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "SystemPropertiesAdvanced.exe"
WScript.Sleep 1000
</code>```

Now I want to get the process id of SystemPropertiesAdvanced.exe program, how can I do that ?

I would like to do this purely by VBScript without mix coding as much as possible.

答:
```<code>Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * From Win32_Process where name='Calculator.exe'")
'msgbox colitems
For Each objItem in colItems
    msgbox objItem.name & " " & objItem.ProcessID & " " & objItem.CommandLine
    If objItem.name = "Calculator.exe" then objItem.terminate
Next
</code>```

This uses WMI to query for Calculator.exe and then terminates it.

Body:
I need to do exactly as I asked in the question for any program that I have just started from my VBScript.

I am starting the System Properties program from VBscript as below:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "SystemPropertiesAdvanced.exe"
WScript.Sleep 1000

Now I want to get the process id of SystemPropertiesAdvanced.exe program, how can I do that ?

I would like to do this purely by VBScript without mix coding as much as possible.

Body:
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * From Win32_Process where name='Calculator.exe'")
'msgbox colitems
For Each objItem in colItems
    msgbox objItem.name & " " & objItem.ProcessID & " " & objItem.CommandLine
    If objItem.name = "Calculator.exe" then objItem.terminate
Next

This uses WMI to query for Calculator.exe and then terminates it.


问:
TSerializer serializer = new TSerializer() in C#
Is there any equivalent of TSerializer in the Thrift C# API.

I am trying to use thrift serialization and then push the serialized object into MQ, not using Thrift transport mechanism. On the other end I'll deserialize it to the actual message.

I can do it in Java but not in C#.

答:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, and it include serializer：

```<code>[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

ThriftSerializer s = new ThriftSerializer(ThriftSerializer.SerializeProtocol.Binary);
byte[] s = s.Serialize<LogEntry>();

s.Deserialize<LogEntry>(s);
</code>```

more detail: https://github.com/endink/Thrifty

Body:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, and it include serializer：

[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

ThriftSerializer s = new ThriftSerializer(ThriftSerializer.SerializeProtocol.Binary);
byte[] s = s.Serialize<LogEntry>();

s.Deserialize<LogEntry>(s);

more detail: https://github.com/endink/Thrifty


问:
Defining a Type Alias in C# across multiple files
In C++, it's easy to write something along the lines of:

```<code>#ifdef FAST
typedef Real float;
#endif

#ifdef SLOW
typedef Real double;
#endif

#ifdef SLOWER
typedef Real quad;
#endif
</code>```

In some common header file so I could simply write one version of code and #define the appropriate version to get different binaries.

I know in C# you can do something similar along the lines of:

```<code>using Real = double;
</code>```

So that you can get the similar semantics to typedefs.
But is it possible to do something similar to the C++ code above that I wouldn't have to write in every single file?

答:
Not if you want it to use the inbuilt IL operators - you would have to do it per-file. However, if you don't need that (I suspect you do) you could encapsulate it in a struct:

```<code>public struct Real {
     private readonly REAL_TYPE value;
     public(REAL_TYPE value) { this.value = value; }
     // TODO add lots of operators (add, multiply. etc) here...
}
</code>```

(where REAL_TYPE is a using alias in the single file that declares Real)

For my money, not worth it. And the use if the static operators will be relatively slower that direct IL operations that you would get if it was in-situ.

ContentLicense: CC BY-SA 2.5

Body:
In C++, it's easy to write something along the lines of:

#ifdef FAST
typedef Real float;
#endif

#ifdef SLOW
typedef Real double;
#endif

#ifdef SLOWER
typedef Real quad;
#endif

In some common header file so I could simply write one version of code and #define the appropriate version to get different binaries.

I know in C# you can do something similar along the lines of:

using Real = double;

So that you can get the similar semantics to typedefs.
But is it possible to do something similar to the C++ code above that I wouldn't have to write in every single file?

Body:
Not if you want it to use the inbuilt IL operators - you would have to do it per-file. However, if you don't need that (I suspect you do) you could encapsulate it in a struct:

public struct Real {
     private readonly REAL_TYPE value;
     public(REAL_TYPE value) { this.value = value; }
     // TODO add lots of operators (add, multiply. etc) here...
}

(where REAL_TYPE is a using alias in the single file that declares Real)

For my money, not worth it. And the use if the static operators will be relatively slower that direct IL operations that you would get if it was in-situ.


问:
Microsoft-Teams custom bot : error while sending a reply
I'm currently working on a Custom bot for Microsoft-Teams; followed the steps described in Ms doc(https://msdn.microsoft.com/en-us/microsoft-teams/custombot)  but did not managed yet to properly send a reply on any request.

This is what my webhook handler receives when I send datas on a channel in Ms-teams, with @AgentSmith (AgentSmith is the name of my bot) :

```<code>{
"type": "message",
"id": "1503406241867",
"timestamp": "2017-08-22T12:50:41.978Z",
"localTimestamp": "2017-08-22T14:50:41.978+02:00",
"serviceUrl": "https://smba.trafficmanager.net/emea-client-ss.msg/",
"channelId": "msteams",
"from": {
    "id": "29:1nxaNQeM7AaQumVmUmPaS4K0gMHZD-FtA_gnJ9xFqZXG5nlpRnsIv-uWeAWQeuKKEQXEEXbwhK4LG1oqvqinGJg",
    "name": "John Doe"
},
"conversation": {
    "isGroup": true,
    "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype;messageid=1503406241867",
    "name": null
},
"recipient": null,
"textFormat": "plain",
"attachmentLayout": null,
"membersAdded": [],
"membersRemoved": [],
"topicName": null,
"historyDisclosed": null,
"locale": null,
"text": "<at>AgentSmith</at> test",
"speak": null,
"inputHint": null,
"summary": null,
"suggestedActions": null,
"attachments": [
    {
        "contentType": "text/html",
        "contentUrl": null,
        "content": "<div><span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">AgentSmith</span> test</div>",
        "name": null,
        "thumbnailUrl": null
    }
],
"entities": [
    {
        "type": "clientInfo",
        "locale": "fr-FR",
        "country": "FR",
        "platform": "Web"
    }
],
"channelData": {
    "teamsChannelId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "teamsTeamId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "channel": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "team": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "tenant": {
        "id": "c41d586a-6ec1-4ce3-89ed-54a2f844c8e1"
    }
},
"action": null,
"replyToId": null,
"value": null,
"name": null,
"relatesTo": null,
"code": null}
</code>```

The previous json is then sent to our platform, which computes a simple text response.

Once that response received from our platform, I just make a POST request on the following endpoint :

https://smba.trafficmanager.net/emea-client-ss.msg/v3/conversations/19:a438309226204de48783042c5bfd3bd9@thread.skype;messageid=1503406241867/activities/1503406241867

with the body including the computed response

```<code>{
"type": "message",
"id": "1503406241867",
"timestamp": "2017-08-22T14:01:31.352Z",
"localTimestamp": "2017-08-22T16:01:31.352+02:00",
"serviceUrl": "https://smba.trafficmanager.net/emea-client-ss.msg/",
"channelId": "msteams",
"from": {
    "name": "AgentSmith",
    "id": "fake string as I don t know the id"
},
"conversation": {
    "isGroup": true,
    "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype;messageid=1503406241867",
    "name": null
},
"recipient": {
    "id": "29:1nxaNQeM7AaQumVmUmPaS4K0gMHZD-FtA_gnJ9xFqZXG5nlpRnsIv-uWeAWQeuKKEQXEEXbwhK4LG1oqvqinGJg",
    "name": "John Doe"
},
"textFormat": "plain",
"attachmentLayout": null,
"membersAdded": [],
"membersRemoved": [],
"topicName": null,
"historyDisclosed": null,
"locale": null,
"text": "Désolé, je n'ai pas compris",
"speak": null,
"inputHint": null,
"summary": null,
"suggestedActions": null,
"attachments": [],
"entities": [
    {
        "type": "clientInfo",
        "locale": "fr-FR",
        "country": "FR",
        "platform": "Web"
    }
],
"channelData": {
    "teamsChannelId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "teamsTeamId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "channel": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "team": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "tenant": {
        "id": "c41d586a-6ec1-4ce3-89ed-54a2f844c8d0"
    }
},
"action": "message",
"replyToId": "1503406241867",
"value": null,
"name": null,
"relatesTo": null,
"code": null}
</code>```

The request fails as follow :

```<code>error: 0.4.0: send message error: statusCode:403, statusCodeMessage:Forbidden,
error: {
  "error": {
      "code":"ServiceError",
      "message":"not member of thread"
  }
}
</code>```

Any help would be appreciated. Can't see what is wrong with the reply message I built.

By the way, isn't that weird that the recipient on the object received by my webhook handler is null?

答:
Sorry for the late reply - didn't see this when it was posted.

You do not (and cannot) post to https://smba.trafficmanager.net/emea-client-ss.msg/...

You can only respond to the HTTP post to your endpoint.

That is, Teams does a POST to you, and your response contains the message object.

Here's an echo bot in node.js that illustrates the concept.

```<code>const util = require('util');

var http = require('http');
var PORT = process.env.port || process.env.PORT || 8080;

http.createServer(function(request, response) {
    var payload = '';
    request.on('data', function (data) {
        // console.log("Chunk size: %s bytes", data.length)
        payload += data;
    });

    request.on('end', function() {
        try {
            response.writeHead(200);
            var receivedMsg = JSON.parse(payload);
            var responseMsg = '{ "type": "message", "text": "You typed: ' + receivedMsg.text + '" }';
            response.write(responseMsg);
            response.end();
        }
        catch (err) {
            response.writeHead(400);
            return response.end("Error: " + err + "\n" + err.stack);
        }
    });

}).listen(PORT);

console.log('Listening on port %s', PORT);
</code>```

Body:
I'm currently working on a Custom bot for Microsoft-Teams; followed the steps described in Ms doc(https://msdn.microsoft.com/en-us/microsoft-teams/custombot)  but did not managed yet to properly send a reply on any request.

This is what my webhook handler receives when I send datas on a channel in Ms-teams, with @AgentSmith (AgentSmith is the name of my bot) :

{
"type": "message",
"id": "1503406241867",
"timestamp": "2017-08-22T12:50:41.978Z",
"localTimestamp": "2017-08-22T14:50:41.978+02:00",
"serviceUrl": "https://smba.trafficmanager.net/emea-client-ss.msg/",
"channelId": "msteams",
"from": {
    "id": "29:1nxaNQeM7AaQumVmUmPaS4K0gMHZD-FtA_gnJ9xFqZXG5nlpRnsIv-uWeAWQeuKKEQXEEXbwhK4LG1oqvqinGJg",
    "name": "John Doe"
},
"conversation": {
    "isGroup": true,
    "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype;messageid=1503406241867",
    "name": null
},
"recipient": null,
"textFormat": "plain",
"attachmentLayout": null,
"membersAdded": [],
"membersRemoved": [],
"topicName": null,
"historyDisclosed": null,
"locale": null,
"text": "<at>AgentSmith</at> test",
"speak": null,
"inputHint": null,
"summary": null,
"suggestedActions": null,
"attachments": [
    {
        "contentType": "text/html",
        "contentUrl": null,
        "content": "
AgentSmith test
",
        "name": null,
        "thumbnailUrl": null
    }
],
"entities": [
    {
        "type": "clientInfo",
        "locale": "fr-FR",
        "country": "FR",
        "platform": "Web"
    }
],
"channelData": {
    "teamsChannelId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "teamsTeamId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "channel": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "team": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "tenant": {
        "id": "c41d586a-6ec1-4ce3-89ed-54a2f844c8e1"
    }
},
"action": null,
"replyToId": null,
"value": null,
"name": null,
"relatesTo": null,
"code": null}

The previous json is then sent to our platform, which computes a simple text response.

Once that response received from our platform, I just make a POST request on the following endpoint :

https://smba.trafficmanager.net/emea-client-ss.msg/v3/conversations/19:a438309226204de48783042c5bfd3bd9@thread.skype;messageid=1503406241867/activities/1503406241867

with the body including the computed response

{
"type": "message",
"id": "1503406241867",
"timestamp": "2017-08-22T14:01:31.352Z",
"localTimestamp": "2017-08-22T16:01:31.352+02:00",
"serviceUrl": "https://smba.trafficmanager.net/emea-client-ss.msg/",
"channelId": "msteams",
"from": {
    "name": "AgentSmith",
    "id": "fake string as I don t know the id"
},
"conversation": {
    "isGroup": true,
    "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype;messageid=1503406241867",
    "name": null
},
"recipient": {
    "id": "29:1nxaNQeM7AaQumVmUmPaS4K0gMHZD-FtA_gnJ9xFqZXG5nlpRnsIv-uWeAWQeuKKEQXEEXbwhK4LG1oqvqinGJg",
    "name": "John Doe"
},
"textFormat": "plain",
"attachmentLayout": null,
"membersAdded": [],
"membersRemoved": [],
"topicName": null,
"historyDisclosed": null,
"locale": null,
"text": "Désolé, je n'ai pas compris",
"speak": null,
"inputHint": null,
"summary": null,
"suggestedActions": null,
"attachments": [],
"entities": [
    {
        "type": "clientInfo",
        "locale": "fr-FR",
        "country": "FR",
        "platform": "Web"
    }
],
"channelData": {
    "teamsChannelId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "teamsTeamId": "19:a438309226204de48783042c5bfd3bd9@thread.skype",
    "channel": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "team": {
        "id": "19:a438309226204de48783042c5bfd3bd9@thread.skype"
    },
    "tenant": {
        "id": "c41d586a-6ec1-4ce3-89ed-54a2f844c8d0"
    }
},
"action": "message",
"replyToId": "1503406241867",
"value": null,
"name": null,
"relatesTo": null,
"code": null}

The request fails as follow :

error: 0.4.0: send message error: statusCode:403, statusCodeMessage:Forbidden,
error: {
  "error": {
      "code":"ServiceError",
      "message":"not member of thread"
  }
}

Any help would be appreciated. Can't see what is wrong with the reply message I built.

By the way, isn't that weird that the recipient on the object received by my webhook handler is null?

Body:
Sorry for the late reply - didn't see this when it was posted.

You do not (and cannot) post to https://smba.trafficmanager.net/emea-client-ss.msg/...

You can only respond to the HTTP post to your endpoint.

That is, Teams does a POST to you, and your response contains the message object.

Here's an echo bot in node.js that illustrates the concept.

const util = require('util');

var http = require('http');
var PORT = process.env.port || process.env.PORT || 8080;

http.createServer(function(request, response) {
    var payload = '';
    request.on('data', function (data) {
        // console.log("Chunk size: %s bytes", data.length)
        payload += data;
    });

    request.on('end', function() {
        try {
            response.writeHead(200);
            var receivedMsg = JSON.parse(payload);
            var responseMsg = '{ "type": "message", "text": "You typed: ' + receivedMsg.text + '" }';
            response.write(responseMsg);
            response.end();
        }
        catch (err) {
            response.writeHead(400);
            return response.end("Error: " + err + "\n" + err.stack);
        }
    });

}).listen(PORT);

console.log('Listening on port %s', PORT);


问:
How do you pass an updated global class variable from one method into another?
I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:

```<code>public class Game{

    private int randomIndexX;

    protected String spawn(){
        randomIndexX = randomGenerator.nextInt(10);
        return null;
    }

    protected String test(){
        System.out.println(this.randomIndexX);
        return null;
    }
}

public class Player extends Game{
    protected String getNextAction(String command) {
        switch(command){
            case "test":
                test();
                break;
        }
    }
}

public static void main(String[] args) {
    Game game = new Game();
    Player player = new Player();

    game.spawn();
    player.getInputFromConsole();
}
</code>```

EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()

答:
The first problem I can see is that you don't have a constructor.(Optional)
 (If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.

The second problem I can see is that you missing the end bracket.
Fix shown below.

```<code>public class Game
</code>```

{

```<code>private int randomIndexX;

protected String spawn()
{
    randomIndexX = 0;
    return null;
}

protected String test()
{
    System.out.println(randomIndexX);
    return null;
}
</code>```

}

You can construct it and trigger any methods you wish:

```<code>Game game = new Game();
game.spawn();
game.test()
</code>```

Body:
I update a variable (which is global in the class) in one method and I cannot seem to be able to then pass that updated variable into another method.
Any help would be appreciated, thank you.
Here's my shortened code:

public class Game{

    private int randomIndexX;

    protected String spawn(){
        randomIndexX = randomGenerator.nextInt(10);
        return null;
    }

    protected String test(){
        System.out.println(this.randomIndexX);
        return null;
    }
}

public class Player extends Game{
    protected String getNextAction(String command) {
        switch(command){
            case "test":
                test();
                break;
        }
    }
}

public static void main(String[] args) {
    Game game = new Game();
    Player player = new Player();

    game.spawn();
    player.getInputFromConsole();
}

EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test()

Body:
The first problem I can see is that you don't have a constructor.(Optional)
 (If you don't make one the compiler makes what is called a "Default" constructor which is a constructor without any parameters. Its usually good practice to explicitly create a class constructor.

The second problem I can see is that you missing the end bracket.
Fix shown below.

public class Game

{

private int randomIndexX;

protected String spawn()
{
    randomIndexX = 0;
    return null;
}

protected String test()
{
    System.out.println(randomIndexX);
    return null;
}

}

You can construct it and trigger any methods you wish:

Game game = new Game();
game.spawn();
game.test()


答:
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().

So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:

```<code>private static in randomIndexX;
</code>```

As it's value won't change depending on an object instance.

So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):

```<code>public static int getRandomIndex(){
    return randomIndexX;
}
</code>```

So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:

```<code>System.out.println(Game.getRandomIndex());
</code>```

The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:

```<code>public static void setRandomIndex(int n){
   randomIndexX = n;
}
</code>```

And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.

For example, the code below will set value of randomIndexX to 5 and then print it in the console:

```<code>Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());
</code>```

Title: How do you pass an updated global class variable from one method into another?

Body:
EDIT: so when i call test() from the Player class i want it to print out randomIndexX but it still doesn't seem to be working even with this.randomIndexX in the method test().

So test() is instance method, which means you'll have to make an instance of Class Game in order to call that method, your randomIndexX is instance member so you need to think well what you want to do, IF randomIndexX is common for all the objects of Game class, you should declare it static as in:

private static in randomIndexX;

As it's value won't change depending on an object instance.

So in order to access that variable from outside of the class since it's private you declare a public method to retrieve that value (getter or also known as accessor):

public static int getRandomIndex(){
    return randomIndexX;
}

So when in main, you don't even have to make an instance of the Game class to access value that's being held in randomIndexX, you just call the getter method like this:

System.out.println(Game.getRandomIndex());

The line above will print 0 to the console as 0 is default value for members of type int, now if you want to be able to change it, you just make a setter or mutator method in Game class as well:

public static void setRandomIndex(int n){
   randomIndexX = n;
}

And there you go, you can now set and retrieve "randomIndexX" field from outside of the Game class.

For example, the code below will set value of randomIndexX to 5 and then print it in the console:

Game.setRandomIndex(5);
System.out.println(Game.getRandomIndex());


问:
Converting massive binary input string into character string C

I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

```<code>char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}
</code>```

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!

答:
Maybe this can help. I didnt compile it but there is the idea. You can loop every 8 bit separately with while loop. And assign 8 bit to binary array with for loop. After that send this binary array to convert8BitToChar function to get letter equivalent of 8 bit. Then append the letter to result array. I'm not writing c for 3 year if there is mistakes sorry about that. Here pseudo code.</p>
```<code>char* binaryToString(char* b){
char* result = malloc(sizeof(256*char));
char binary[8];
int nextLetter = 0;
while (b[nextLetter*8] != NULL) { // loop every 8 bit
    for(int i=0; i<8; ++i){
        binary[i] = b[nextLetter*8+i];
    }
    result[nextLetter] = 8bitToChar(binary));// convert 8bitToChar and append yo result
    nextLetter++;
}
result[nextLetter] = '\0';
return result;
}
</code>```

Body:
I'm not familiar with C at all so this might be a simple problem to solve. I'm trying to take an input char* array of binary character sequences, ex. "0100100001101001", and output its relative string ("Hi"). The problem I'm having is coming up with a way to split the input into seperate strings of length 8 and then convert them individually to ulimately get the full output string.

char* binaryToString(char* b){
    char binary[8];
    for(int i=0; i<8; ++i){
    binary[i] = b[i];
}
printf("%s", binary);
}

I'm aware of how to convert 8-bit into its character, I just need a way to split the input string in a way that will allow me to convert massive inputs of 8-bit binary characters.

Any help is appreciated... thanks!

Body:
Maybe this can help. I didnt compile it but there is the idea. You can loop every 8 bit separately with while loop. And assign 8 bit to binary array with for loop. After that send this binary array to convert8BitToChar function to get letter equivalent of 8 bit. Then append the letter to result array. I'm not writing c for 3 year if there is mistakes sorry about that. Here pseudo code.

char* binaryToString(char* b){
char* result = malloc(sizeof(256*char));
char binary[8];
int nextLetter = 0;
while (b[nextLetter*8] != NULL) { // loop every 8 bit
    for(int i=0; i<8; ++i){
        binary[i] = b[nextLetter*8+i];
    }
    result[nextLetter] = 8bitToChar(binary));// convert 8bitToChar and append yo result
    nextLetter++;
}
result[nextLetter] = '\0';
return result;
}

ContentLicense: CC BY-SA 4.0


问:
Numpy - slicing 2d row or column vector from array
I'm trying to find a neat little trick for slicing a row/column from a 2d array and obtaining an array of (col_size x 1) or (1 x row_size).

Is there an easier way than to use numpy.reshape() after every slicing?

Cheers,
Stephan

Body:
How about this nice and easy way?

In [73]: arr = (np.arange(5, 25)).reshape(5, 4)

In [74]: arr
Out[74]:
array([[ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16],
       [17, 18, 19, 20],
       [21, 22, 23, 24]])

# extract column 1 as a column vector
In [79]: col1 = arr[:, [0]]
In [80]: col1.shape
Out[80]: (5, 1)

In [81]: col1
Out[81]:
array([[ 5],
       [ 9],
       [13],
       [17],
       [21]])

# extract row 1 as a row vector
In [82]: row1 = arr[[0], :]

In [83]: row1.shape
Out[83]: (1, 4)

In [84]: row1
Out[84]: array([[5, 6, 7, 8]])


问:
WCF Pub/Sub with subscriber caching
Problem: how to provide a distributed, scalable and disaster resistant pub/sub service with WCF.

Details:

Note that this approach is being considered in addition to messaging/middleware solutions such as Tibco EMS.

I've been looking into WCF, particularly how it may be used to offer pub/sub.  On this subject this article is very good: WCF pub-sub.

In the article the author attempts to tackle the problem of having multiple publishers (as one would have with a service layer scaled across several boxes).  The problem being that if client A registers with Publisher A but Publisher B wishes to publish an event, then publisher B won't know about client A.  i.e. no one told publisher B that client A wanted to be notified about events.  The author suggests a pub/sub service as a solution.  The pub/sub service would centrally store subscriptions.  However, if I wanted to make the pub/sub service disaster resistant by having a secondary/dual pub/sub service then I have the same original problem.

So, I think there are a couple of solutions to the problem:

Store subscriber details in a distributed cache (see questions: q1 and q2).

Store subscriber details in a database/central file system.

Can anyone think of any other solutions (i.e. I've not missed some fantastic magical feature of WCF?)
Any comments appreciated.

答:
I had the same problem and I did a lot of research on the issue. The problem is actually simple. You want to keep some centralized state, but in distributed way. I found that the best way to achieve this is by using a distributed cache. Look at velocity for example. There is no native WCF solution that I know that can solve the state management issue. I have even looked into durable services, where state management is handled by WCF, however not suitable for a pub/ sub service, because the state needs to be centralized for all client connections. Storing data in a database is also an option, but the cost is the need for a database, and even with a database you can have a single point of failure if the database is not clustered accorss multiple machines.

At the end, I figured it is actually expensive to implement something with zero points of failure and if you do decide to go there then take a look at Azure, the future of storage is on the cloud, Azure services will be fully scalable and distributed, but we are not there yet.

Title: WCF Pub/Sub with subscriber caching

OwnerDisplayName: WCFGuy


问:
Comparition inconsistence when using IF inside WHILE Loop in Lua
When checking a IF evaluation in WHILE in lua:

```<code>stopper = 0;
needle = 0.14;
    while stopper < 0.2 do
        if stopper == needle then
        print ("Finally!")
    end
    stopper = stopper + 0.01
end
</code>```

"Finally!" never gets printed if needle = 0.14 but does if needle = 0.15 (or 0.16, 0.17).

Is there a way to make it work? I suppose that this has to do with how LUA handles floats but I am not sure.

Obs:

both counter and needle types are number (when checked like: type(counter))

using tonumber(counter) == tonumber(needle) does not help

there is a work around using tostring but I do not want it for obvious performance reasons

答:
The decimal numerals in your source code are converted to binary floating-point, and they are added using binary floating-point.

I am guessing Lua uses 64-bit binary IEEE-754 floating-point, in which case “.01” is converted to 0.01000000000000000020816681711721685132943093776702880859375, and the result of adding it 14 times is 0.1399999999999999855671006798729649744927883148193359375, whereas “.14” is converted to 0.14000000000000001332267629550187848508358001708984375. As you can see, they are not equal.

A solution for you might be to count loop iterations using integers and to use integers for the stopper and needle positions. Convert to floating-point only when necessary. If you need to use floating-point operations beyond simple loop control, you will need to explain further.

Body:
When checking a IF evaluation in WHILE in lua:

stopper = 0;
needle = 0.14;
    while stopper < 0.2 do
        if stopper == needle then
        print ("Finally!")
    end
    stopper = stopper + 0.01
end

"Finally!" never gets printed if needle = 0.14 but does if needle = 0.15 (or 0.16, 0.17).

Is there a way to make it work? I suppose that this has to do with how LUA handles floats but I am not sure.

Obs:

both counter and needle types are number (when checked like: type(counter))

using tonumber(counter) == tonumber(needle) does not help

there is a work around using tostring but I do not want it for obvious performance reasons


问:
What column type does SQLAlchemy use for "Text" on MySQL?
My overall use-case is trying to determine whether I can write a somewhat database agnostic (at least supporting Postgres and MySQL) store for some large data as raw text (think ~500MB as a rough theoretical upper bound).

Based on this answer about MySQL string/text types, it looks like only the LONGTEXT column type can meet my requirements. I'm using SQLAlchemy, which claims for its Text column type that it is for variable length strings, but also that it generally maps to the database's CLOB or TEXT types. MySQL doesn't have a CLOB type (though it does have a BLOB), and its TEXT type would be insufficient for my needs.

So, What column type does SQLAlchemy use for Text on MySQL?

答:
Looks like SQLAlchemy supports LONGTEXT:

```<code>$ python
Python 2.7.13 (default, Sep 29 2017, 15:31:18)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlalchemy.dialects.mysql import LONGTEXT
>>>
</code>```

See how to use vendor-specific types here:
http://docs.sqlalchemy.org/en/latest/core/type_basics.html#vendor-specific-types

For what it's worth, trying to develop a totally brand-neutral database layer is difficult, and rarely worth the effort. I worked on the Zend Framework 1.0 some years ago, and I tried to create a generic unit testing suite for all the SQL databases supported by that framework. I found that very few data types are supported in the same way across all implementations of SQL, despite them all claiming to support the ANSI/ISO SQL standard.

Ultimately, you have to develop your own class hierarchy for your data layer, and implement the code slightly differently for each database-specific adapter.

Update: I think the news is better than we think. I tried this test:

```<code>t2 = Table('t2', metadata,
      Column('id', Integer, primary_key=True),
      Column('t1', String(64000)),
      Column('t2', String(16000000)),
      Column('t3', String(4294000000)),
      Column('t4', Text)
     )

metadata.create_all(engine)
</code>```

Then I checked to see what it ended up creating in the MySQL database:

```<code>mysql> show create table t2;

CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `t1` mediumtext,
  `t2` longtext,
  `t3` longtext,
  `t4` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
</code>```

So it does map SQLAlchemy's generic String data type to a more-or-less appropriate MySQL data type.

It's not surprising to me that it used larger data types than we might expect. The MEDIUMTEXT supports 16MB in bytes, not in characters. Because my default character set is the multi-byte utfmb4, the max length of MEDIUMTEXT is actually much fewer than 2^24 characters. So it had to upgrade it to LONGTEXT. Of course, 2^32 characters won't fit in LONGTEXT either, but it appears SQLAlchemy assumes you mean to create a column anyway.

I still think that it's hard to do totally implementation-neutral code. For example, what if you want to use some MySQL features like table options for the storage engine, or specific data types with no generic equivalent (for example, ENUM)?

Body:
Looks like SQLAlchemy supports LONGTEXT:

$ python
Python 2.7.13 (default, Sep 29 2017, 15:31:18)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.37)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sqlalchemy.dialects.mysql import LONGTEXT
>>>

See how to use vendor-specific types here:
http://docs.sqlalchemy.org/en/latest/core/type_basics.html#vendor-specific-types

For what it's worth, trying to develop a totally brand-neutral database layer is difficult, and rarely worth the effort. I worked on the Zend Framework 1.0 some years ago, and I tried to create a generic unit testing suite for all the SQL databases supported by that framework. I found that very few data types are supported in the same way across all implementations of SQL, despite them all claiming to support the ANSI/ISO SQL standard.

Ultimately, you have to develop your own class hierarchy for your data layer, and implement the code slightly differently for each database-specific adapter.

Update: I think the news is better than we think. I tried this test:

t2 = Table('t2', metadata,
      Column('id', Integer, primary_key=True),
      Column('t1', String(64000)),
      Column('t2', String(16000000)),
      Column('t3', String(4294000000)),
      Column('t4', Text)
     )

metadata.create_all(engine)

Then I checked to see what it ended up creating in the MySQL database:

mysql> show create table t2;

CREATE TABLE `t2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `t1` mediumtext,
  `t2` longtext,
  `t3` longtext,
  `t4` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

So it does map SQLAlchemy's generic String data type to a more-or-less appropriate MySQL data type.

It's not surprising to me that it used larger data types than we might expect. The MEDIUMTEXT supports 16MB in bytes, not in characters. Because my default character set is the multi-byte utfmb4, the max length of MEDIUMTEXT is actually much fewer than 2^24 characters. So it had to upgrade it to LONGTEXT. Of course, 2^32 characters won't fit in LONGTEXT either, but it appears SQLAlchemy assumes you mean to create a column anyway.

I still think that it's hard to do totally implementation-neutral code. For example, what if you want to use some MySQL features like table options for the storage engine, or specific data types with no generic equivalent (for example, ENUM)?


问:
"Error C1083: Cannot open source file" Shouldn't Be Looking For The File At All
I was trying to #include a cpp file with some functions so I can use that cpp file later with other projects. It gave me an 'already defined in .obj' error and since then that .cpp file was like binded with my project. (I understood that's not the way, the answer here helped me with the already defined)

If I exclude the .cpp file from the project, remove it from the directory and remove the #include line it still looks for it:

```<code>c1xx : fatal error C1083: Cannot open source file: 'std.cpp': No such file or directory
</code>```

Diagnostic:

```<code>Outputs for D:\MY DOCUMENTS\C#\PROJECT\D3DTESTC++\COWS AND BULLS\CBMAIN.CPP|D:\MY DOCUMENTS\C#\PROJECT\D3DTESTC++\COWS AND BULLS\STD.CPP: (TaskId:15)
</code>```

It shouldn't be looking for the std.cpp at all, I removed it! So is there a way I can reset the project and recompile so that the program doesn't look for it? I already tried Rebuild and Clear -> Build Project

答:
Many of the solutions here will not work

Fullproof method:

Open the vxproj file that is giving you trouble in a text editor.

remove all references to the file it cannot find.

Body:
I was trying to #include a cpp file with some functions so I can use that cpp file later with other projects. It gave me an 'already defined in .obj' error and since then that .cpp file was like binded with my project. (I understood that's not the way, the answer here helped me with the already defined)

If I exclude the .cpp file from the project, remove it from the directory and remove the #include line it still looks for it:

c1xx : fatal error C1083: Cannot open source file: 'std.cpp': No such file or directory

Diagnostic:

Outputs for D:\MY DOCUMENTS\C#\PROJECT\D3DTESTC++\COWS AND BULLS\CBMAIN.CPP|D:\MY DOCUMENTS\C#\PROJECT\D3DTESTC++\COWS AND BULLS\STD.CPP: (TaskId:15)

It shouldn't be looking for the std.cpp at all, I removed it! So is there a way I can reset the project and recompile so that the program doesn't look for it? I already tried Rebuild and Clear -> Build Project


问:
Django : NoReverseMatch error
everyone!

I'm new to Django and actually making a study project. I'm getting a NoReverseMatch exception and can't understand why. It seems not to have namespace conflicts, the other list views are made in the same way as for the StoredItem model, but only this one throws an exception:

models.py:

```<code>from django.db import models
from django.urls import reverse

# Create your models here.
class LegalEntity(models.Model):
    name = models.CharField(max_length=100, help_text="Name")
    rif = models.CharField(max_length=10, help_text="RIF")
    address = models.TextField(help_text="Address")
    phone_num = models.CharField(max_length=15, help_text="Phone number")

    def __str__(self):
        pass

class Contract(models.Model):
    name = models.CharField(max_length=100, help_text="Name")
    number = models.CharField(max_length=50, help_text="Contract number")
    description = models.TextField(help_text="Contract description")
    start_date = models.DateField(null=False, blank=False, help_text="Start date")
    expiry_date = models.DateField(null=True, blank=True, help_text="Expiry date")

    def __str__(self):
        return "number: {0}, " \
               "name: \"{1}\", " \
               "starts: {2}, " \
               "expires: {3}."\
              .format(self.number, self.name, self.start_date, self.expiry_date)

    def get_absolute_url(self):
        return reverse('contract-detail', args=[str(self.id)])

class Provider(LegalEntity):
    contract = models.ForeignKey(Contract)

    def __str__(self):
        return "name: \"{0}\", " \
               "RIF: {1}, " \
               "phone: {2}."\
               .format(self.name, self.rif, self.phone_num)

    def get_absolute_url(self):
        return reverse('provider-detail', args=[str(self.id)])

class Item(models.Model):
    name = models.CharField(max_length=100, help_text="Name")
    serial = models.CharField(max_length=50, help_text="Serial No.")
    manufacturer = models.CharField(max_length=50, help_text="Manufacturer")
    provider = models.ForeignKey(Provider)

    def __str__(self):
        return "name: \"{0}\", " \
               "serial: {1}, " \
               "manufacturer: {2}," \
               "provider: {3}."\
              .format(self.name, self.serial, self.manufacturer, self.provider.name)

    def get_absolute_url(self):
        return reverse('item-detail', args=[str(self.id)])

class StoredItem(models.Model):
    item = models.ForeignKey(Item)
    quantity = models.IntegerField(default=0)

    def __str__(self):
        return "{0} - {1}, {2} pcs.".format(self.item.serial, self.item.name, self.quantity)

    def get_absolute_url(self):
        return reverse('storeditem-detail', args=[str(self.id)])
</code>```

urls.py

```<code>from django.conf.urls import url

from . import views

app_name = 'almacen'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^providers/$', views.ProviderListView.as_view(), name='providers'),
    url(r'^items/$', views.ItemListView.as_view(), name='items'),
    url(r'^storeditems/$', views.StoredItemListView.as_view(), name='storeditems'),
    url(r'^contracts/$', views.ContractListView.as_view(), name='contracts')
]
</code>```

views.py

```<code>from django.shortcuts import render
from django.views import generic

# Create your views here.
from almacen.models import Contract, StoredItem, Provider, Item

def index(request):
    stored_items_num = len([x for x in StoredItem.objects.all() if x.quantity > 0])
    providers_num = Provider.objects.all().count()

    return render(request,
    'index.html',
    context = {'stored_items_num': stored_items_num, 'providers_num': providers_num})

class ContractListView(generic.ListView):
    model = Contract

class ProviderListView(generic.ListView):
    model = Provider

class ItemListView(generic.ListView):
    model = Item

class StoredItemListView(generic.ListView):
    model = StoredItem
</code>```

base_template.html

```<code><!DOCTYPE html>
<html lang="en">
    <head>

        {% block title %}<title>Almacen Application</title>{% endblock %}
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

        <!-- Добавление дополнительного статического CSS файла -->
        {% load static %}
        <link rel="stylesheet" href="{% static 'css/styles.css' %}">
    </head>

    <body>

        <div class="container-fluid">
            <div class="content">
                <div class="row">
                    <div class="col-sm-2 sidenav">
                        <h4>Options: </h4>
                        {% block sidebar %}
                            <ul class="nav nav-pills nav-stacked">
                                <li><a href="{% url 'almacen:index' %}">Home</a></li>
                                <li><a href="{% url 'almacen:items' %}">Items</a></li>
                                <li><a href="{% url 'almacen:providers' %}">Providers</a></li>
                                <li><a href="{% url 'almacen:contracts' %}">Contracts</a></li>
                                <li><a href="{% url 'almacen:storeditems' %}">Store</a></li>
                            </ul>
                        {% endblock %}
                    </div>
                    <div class="col-sm-9 ">
                        {% block content %}{% endblock %}
                    </div>
                </div>
            </div>
        </div>
        <footer id="center" class="container-fluid">
            <p>
                PerfoSAP Package Application<br>
                created by caesar_84
            </p>
        </footer>
    </body>
</html>
</code>```

storeditem_list.html

```<code>{% extends 'base_template.html' %}

{% block content %}

    <h1>Items list</h1>

    {% if storeditem_list %}

        <table style="width:100%">
            <tr>
                <th>Serial</th>
                <th>Name</th>
                <th>Manufacturer</th>
                <th>Provider</th>
                <th>Quantity</th>
            </tr>

            {% for storeditem in storeditem_list %}

            <tr>
                <td>
                <a href="{{storeditem.get_absolute_url}}"> {{ storeditem.item.serial }} </a>
                </td>
                <td>{{ storeditem.item.name }}</td>
                <td>{{ storeditem.item.manufacturer }}</td>
                <td>{{ storeditem.item.provider.name }}</td>
                <td>{{ storeditem.quantity }}</td>
            </tr>

            {% endfor %}
        </table>

    {% endif %}

{% endblock %}
</code>```

This is the message I'm getting:

Reverse for 'storeditem-detail' not found. 'storeditem-detail' is not a valid view function or pattern name.

答:
I found the error that stole me some hours today xD

The error is in storeditem_list.html in the line

```<code><a href="{{storeditem.get_absolute_url}}"> {{ storeditem.item.serial }} </a>
</code>```

Instead of "{{storeditem.get_absolute_url}}" it had to be "{{storeditems.get_absolute_url}}"

Title: Django : NoReverseMatch error

Body:
everyone!

I'm new to Django and actually making a study project. I'm getting a NoReverseMatch exception and can't understand why. It seems not to have namespace conflicts, the other list views are made in the same way as for the StoredItem model, but only this one throws an exception:

models.py:

from django.db import models
from django.urls import reverse

# Create your models here.
class LegalEntity(models.Model):
    name = models.CharField(max_length=100, help_text="Name")
    rif = models.CharField(max_length=10, help_text="RIF")
    address = models.TextField(help_text="Address")
    phone_num = models.CharField(max_length=15, help_text="Phone number")

    def __str__(self):
        pass

class Contract(models.Model):
    name = models.CharField(max_length=100, help_text="Name")
    number = models.CharField(max_length=50, help_text="Contract number")
    description = models.TextField(help_text="Contract description")
    start_date = models.DateField(null=False, blank=False, help_text="Start date")
    expiry_date = models.DateField(null=True, blank=True, help_text="Expiry date")

    def __str__(self):
        return "number: {0}, " \
               "name: \"{1}\", " \
               "starts: {2}, " \
               "expires: {3}."\
              .format(self.number, self.name, self.start_date, self.expiry_date)

    def get_absolute_url(self):
        return reverse('contract-detail', args=[str(self.id)])

class Provider(LegalEntity):
    contract = models.ForeignKey(Contract)

    def __str__(self):
        return "name: \"{0}\", " \
               "RIF: {1}, " \
               "phone: {2}."\
               .format(self.name, self.rif, self.phone_num)

    def get_absolute_url(self):
        return reverse('provider-detail', args=[str(self.id)])

class Item(models.Model):
    name = models.CharField(max_length=100, help_text="Name")
    serial = models.CharField(max_length=50, help_text="Serial No.")
    manufacturer = models.CharField(max_length=50, help_text="Manufacturer")
    provider = models.ForeignKey(Provider)

    def __str__(self):
        return "name: \"{0}\", " \
               "serial: {1}, " \
               "manufacturer: {2}," \
               "provider: {3}."\
              .format(self.name, self.serial, self.manufacturer, self.provider.name)

    def get_absolute_url(self):
        return reverse('item-detail', args=[str(self.id)])

class StoredItem(models.Model):
    item = models.ForeignKey(Item)
    quantity = models.IntegerField(default=0)

    def __str__(self):
        return "{0} - {1}, {2} pcs.".format(self.item.serial, self.item.name, self.quantity)

    def get_absolute_url(self):
        return reverse('storeditem-detail', args=[str(self.id)])

urls.py

from django.conf.urls import url

from . import views

app_name = 'almacen'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^providers/$', views.ProviderListView.as_view(), name='providers'),
    url(r'^items/$', views.ItemListView.as_view(), name='items'),
    url(r'^storeditems/$', views.StoredItemListView.as_view(), name='storeditems'),
    url(r'^contracts/$', views.ContractListView.as_view(), name='contracts')
]

views.py

from django.shortcuts import render
from django.views import generic

# Create your views here.
from almacen.models import Contract, StoredItem, Provider, Item

def index(request):
    stored_items_num = len([x for x in StoredItem.objects.all() if x.quantity > 0])
    providers_num = Provider.objects.all().count()

    return render(request,
    'index.html',
    context = {'stored_items_num': stored_items_num, 'providers_num': providers_num})

class ContractListView(generic.ListView):
    model = Contract

class ProviderListView(generic.ListView):
    model = Provider

class ItemListView(generic.ListView):
    model = Item

class StoredItemListView(generic.ListView):
    model = StoredItem

base_template.html

<!DOCTYPE html>

        {% block title %}<title>Almacen Application</title>{% endblock %}
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        {% load static %}
        <link rel="stylesheet" href="{% static 'css/styles.css' %}">

Options:

                        {% block sidebar %}

Home

Items

Providers

Contracts

Store

                        {% endblock %}

                        {% block content %}{% endblock %}

                PerfoSAP Package Application

                created by caesar_84

storeditem_list.html

{% extends 'base_template.html' %}

{% block content %}

Items list

    {% if storeditem_list %}

                Serial
                Name
                Manufacturer
                Provider
                Quantity

            {% for storeditem in storeditem_list %}

                 {{ storeditem.item.serial }}

                {{ storeditem.item.name }}
                {{ storeditem.item.manufacturer }}
                {{ storeditem.item.provider.name }}
                {{ storeditem.quantity }}

            {% endfor %}

    {% endif %}

{% endblock %}

This is the message I'm getting:

Reverse for 'storeditem-detail' not found. 'storeditem-detail' is not a valid view function or pattern name.

Body:
I found the error that stole me some hours today xD

The error is in storeditem_list.html in the line

<a href="{{storeditem.get_absolute_url}}"> {{ storeditem.item.serial }} </a>

Instead of "{{storeditem.get_absolute_url}}" it had to be "{{storeditems.get_absolute_url}}"


问:
DbUnit DbComparisonFailure expected:<uniqueidentifier>
We do databas / dataset comparison.

Source DB: SQL Server

Target DB: SAP HANA

Error message:

org.dbunit.assertion.DbComparisonFailure: Incompatible data types: (table=dataset, col=JobId) expected:<uniqueidentifier> but was:<VARCHAR>

Work-around: cast(JobId as varchar(36)) JobId

But why does this error occure? JobId is defined as varchar(36) in the source table

How to make this work (The SQLs are generated and manually adding a cast is cumbersome)

答:
Looking through the google results, this seems to be a common issue with MS SQL Servers UniqueIdentifier column type. See http://dbunit.wikidot.com/mssql.

There, they basically put the type mapping in the DBUnit factory code, instead of a CAST on every column:
public class MsSqlDataTypeFactory extends DefaultDataTypeFactory
{
    public static int NVARCHAR = -9;
    public static int UNIQUEIDENTIFIER = -11;

```<code>public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException
{
    if (sqlType == NVARCHAR)
    {
        return DataType.VARCHAR;
    }

    if (sqlType == UNIQUEIDENTIFIER)
    {
        return DataType.VARCHAR;
    }

    return super.createDataType(sqlType, sqlTypeName);
 }
}
</code>```

Body:
Looking through the google results, this seems to be a common issue with MS SQL Servers UniqueIdentifier column type. See http://dbunit.wikidot.com/mssql.

There, they basically put the type mapping in the DBUnit factory code, instead of a CAST on every column:
public class MsSqlDataTypeFactory extends DefaultDataTypeFactory
{
    public static int NVARCHAR = -9;
    public static int UNIQUEIDENTIFIER = -11;

public DataType createDataType(int sqlType, String sqlTypeName) throws DataTypeException
{
    if (sqlType == NVARCHAR)
    {
        return DataType.VARCHAR;
    }

    if (sqlType == UNIQUEIDENTIFIER)
    {
        return DataType.VARCHAR;
    }

    return super.createDataType(sqlType, sqlTypeName);
 }
}


问:
Stripe iOS integration get payment transaction id
I have integrated Stripe with iOS and the payments are working with the test cards, however, I cannot find a way to get payment transaction id so that I can store the transaction id on my server for future reference.

I looked into STPPaymentResult and STPPaymentContext but couldn't find anything.

So is there a way I can get the transaction id after the payment has been charged using Stripe in iOS application?

答: I found that STPPaymentResult returned during didCreatePaymentResult does contain transaction id. You can get it by paymentResult.source.stripeID


问:
How to check if letter in a string appear in another string in the same order

I would love to check if the letters from a text appear in another text in the same order.

```<code>text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False
</code>```

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

答:
Its simple</p>

```<code>text = "Au"
name = "Gold"
text.lower() in name.lower()
False

text = "C"
name = "Carbon"
text.lower() in name.lower()
True
</code>```

Body:
I would love to check if the letters from a text appear in another text in the same order.

text    "Ce"
name    "Arsenic"
Answer   False

for x in text:
    if x.lower() not in name.lower():
        return False

I would like that the order is checked too so that the elements appear in the same order in the other string : True else False.

At the moment my code only checks if the letters also appear in the string but not if they are in the same order.

Body:
Its simple

text = "Au"
name = "Gold"
text.lower() in name.lower()
False

text = "C"
name = "Carbon"
text.lower() in name.lower()
True


问:
Is it possible to use Go to send and receive file descriptors over Unix domain sockets?
In the unix(7) man page for Unix domain sockets, it says that sendmsg can be used with the SCM_RIGHTS flag to send file descriptors over these sockets. Is this supported in Go? Is there any good example code out there showing how it's done?

It appears that there is a Msghdr structure declared in the syscall package. But no functions take it. Maybe I have to use the raw system call interface?

答:
There's a package that does it here: https://github.com/ftrvxmtrx/fd/blob/master/fd.go. However that's using the Syscall package to achieve it. I'm not sure if there's a way to do this with Go standard library API.

In the syscall package, the things to look at are UnixRights, ParseUnixRights, and ParseSocketControlMessage. These can be used in conjunction with Readmsg and Sendmsg to send file descriptors over AF_UNIX sockets.

The basic structure goes something like this for receiving:

```<code>buf := make([]byte, syscall.CmsgSpace(<number of file descriptors expected> * 4))
_, _, _, _, err = syscall.Recvmsg(socket, nil, buf, 0)
if err != nil {
    panic(err)
}
var msgs []syscall.SocketControlMessage
msgs, err = syscall.ParseSocketControlMessage(buf)
var allfds []int
for i := 0, i < len(msgs) && err == null; i++ {
    var msgfds []int
    msgfds, err = syscall.ParseUnixRights(&msgs[i])
    append(allfds, msgfds...)
}
</code>```

And for sending, it's much simpler (var fds []int):

```<code>rights := syscall.UnixRights(fds...)
err := syscall.Sendmsg(socket, nil, rights, nil, 0)
</code>```

Body:
There's a package that does it here: https://github.com/ftrvxmtrx/fd/blob/master/fd.go. However that's using the Syscall package to achieve it. I'm not sure if there's a way to do this with Go standard library API.

In the syscall package, the things to look at are UnixRights, ParseUnixRights, and ParseSocketControlMessage. These can be used in conjunction with Readmsg and Sendmsg to send file descriptors over AF_UNIX sockets.

The basic structure goes something like this for receiving:

buf := make([]byte, syscall.CmsgSpace(<number of file descriptors expected> * 4))
_, _, _, _, err = syscall.Recvmsg(socket, nil, buf, 0)
if err != nil {
    panic(err)
}
var msgs []syscall.SocketControlMessage
msgs, err = syscall.ParseSocketControlMessage(buf)
var allfds []int
for i := 0, i < len(msgs) && err == null; i++ {
    var msgfds []int
    msgfds, err = syscall.ParseUnixRights(&msgs[i])
    append(allfds, msgfds...)
}

And for sending, it's much simpler (var fds []int):

rights := syscall.UnixRights(fds...)
err := syscall.Sendmsg(socket, nil, rights, nil, 0)


问:
How to draw labels on Dimple.js donut or pie chart?
Trying to show the percentages right on the donut charts in dimple.plot.pie

Here is some code that kind of works but places the labels right onto the slices.

Having trouble making the labels show up outside the pie.

```<code>rings = chart.addSeries("series", dimple.plot.pie);
rings.afterDraw = function(shape, data) {
  var bbox, ctm;
  ctm = shape.getCTM();
  bbox = shape.getBBox();
  return this.chart.svg.append("text")
    .attr("x", ctm.e + bbox.x + bbox.width/2)
    .attr("y", ctm.f + bbox.y + bbox.height/2)
    .text(Math.round(1000*data.piePct)/10 + "%");;
};
</code>```

Here's the best I can do..

答:
2 years later and still no solution that works out-of-the-box?

The solution below is a working compilation of all I could find on the topic. Updates are welcome :-)

```<code>var pies = chart.addSeries("series", dimple.plot.pie);
pies.radius = 60;
pies.innerRadius = "50%";
pies.afterDraw = function (shape, data) {
    var arc = d3.arc()
        .outerRadius(radius)
        .innerRadius(radius/2);

    var ctm = shape.getCTM();

    chart.svg.append("text")
    // Position text in the centre of the shape
        .attr("x", arc.centroid(data)[0])
        .attr("y", arc.centroid(data)[1])
        .attr("transform", function () {
            return "translate("+ctm.e+","+ctm.f+")";
        })
    // Centre align and nicer display
        .style("text-anchor", "middle")
        .style("font-size", "10px")
        .style("font-family", "sans-serif")
        .style("opacity", 0.8)
    // Prevent text cursor on hover and allow tooltips
        .style("pointer-events", "none")
    // Display text
        .text((data.piePct*100).toFixed(2) + "%)");
}
</code>```

Body:
Trying to show the percentages right on the donut charts in dimple.plot.pie

Here is some code that kind of works but places the labels right onto the slices.

Having trouble making the labels show up outside the pie.

rings = chart.addSeries("series", dimple.plot.pie);
rings.afterDraw = function(shape, data) {
  var bbox, ctm;
  ctm = shape.getCTM();
  bbox = shape.getBBox();
  return this.chart.svg.append("text")
    .attr("x", ctm.e + bbox.x + bbox.width/2)
    .attr("y", ctm.f + bbox.y + bbox.height/2)
    .text(Math.round(1000*data.piePct)/10 + "%");;
};

Here's the best I can do..

Body:
2 years later and still no solution that works out-of-the-box?

The solution below is a working compilation of all I could find on the topic. Updates are welcome :-)

var pies = chart.addSeries("series", dimple.plot.pie);
pies.radius = 60;
pies.innerRadius = "50%";
pies.afterDraw = function (shape, data) {
    var arc = d3.arc()
        .outerRadius(radius)
        .innerRadius(radius/2);

    var ctm = shape.getCTM();

    chart.svg.append("text")
    // Position text in the centre of the shape
        .attr("x", arc.centroid(data)[0])
        .attr("y", arc.centroid(data)[1])
        .attr("transform", function () {
            return "translate("+ctm.e+","+ctm.f+")";
        })
    // Centre align and nicer display
        .style("text-anchor", "middle")
        .style("font-size", "10px")
        .style("font-family", "sans-serif")
        .style("opacity", 0.8)
    // Prevent text cursor on hover and allow tooltips
        .style("pointer-events", "none")
    // Display text
        .text((data.piePct*100).toFixed(2) + "%)");
}


问:
Generate all possibilities for a string where some letters can be numbers, in Python
Say I have a string like this.

```<code>sentence = "i like to go fishing on saturday"
</code>```

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

```<code>"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.
</code>```

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

答:
Write a list of substitutions, such as

```<code>[
  [1, 'l'],
  [3, 'e'],
  [4, 'a'],
  ...
]
</code>```

Next, divide your text into sections, separating any letter that you can substitute.  For instance, "fishing on saturday" becomes

```<code>[ "fishing ", "o", "n s", "a", "turd", "a", "y"]
</code>```

Now, bring in the substitution lists for all appropriate letters: o a a in this case.  Use itertools.product to generate all of the possible combinations.

Is that enough to get you started?  Implementation is left as an exercise for the student.

Body:
Say I have a string like this.

sentence = "i like to go fishing on saturday"

And some letters can be numbers, in the tradition of '1337' speak i.e. h3110, h0w 4r3 y0u?

However I want to get all possible combinations where some letters are converted to numbers, but others are not. Some examples with the above sentence.

"i 1ik3 70 g0 fishing 0n s4turd4y"
"i lik3 70 g0 fishing 0n s4turd4y"
"i like 70 g0 fishing 0n s4turd4y"
"i 1ike 70 g0 fishing 0n s4turd4y"
etc.

How could I write in Python a dictionary of substitutions for each letter and then a way to generate all possible combinations for the sentence?

Body:
Write a list of substitutions, such as

[
  [1, 'l'],
  [3, 'e'],
  [4, 'a'],
  ...
]

Next, divide your text into sections, separating any letter that you can substitute.  For instance, "fishing on saturday" becomes

[ "fishing ", "o", "n s", "a", "turd", "a", "y"]

Now, bring in the substitution lists for all appropriate letters: o a a in this case.  Use itertools.product to generate all of the possible combinations.

Is that enough to get you started?  Implementation is left as an exercise for the student.


问:
numpy/pandas NaN difference confusion
I happened onto this when trying to find the means/sums of non-nan elements in rows of a pandas dataframe. It seems that

```<code>df.apply(np.mean, axis=1)
</code>```

works fine.

However, applying np.mean to a numpy array containing nans returns a nan.

Is this all speced out somewhere? I would not want to get burned down the road...

答:
Divakar has correctly suggested using np.nanmean

If I may answer the question still standing, the semantics differ because Numpy supports masked arrays, while Pandas does not.

Title: numpy/pandas NaN difference confusion

Body:
I happened onto this when trying to find the means/sums of non-nan elements in rows of a pandas dataframe. It seems that

df.apply(np.mean, axis=1)

works fine.

However, applying np.mean to a numpy array containing nans returns a nan.

Is this all speced out somewhere? I would not want to get burned down the road...


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
What projects are you sifting through? Are these professional projects or something random?

One of the things I've noticed is that a lot of legacy type code (I worked on a code base that pre-dated C++98) avoids the C++ standard library because of performance worries of the implementations at that time, or just because the libraries didn't exist at the time. Of course, some environments (embedded systems, games, defense, etc.) might have other requirements that preclude the use of C++ standard library in many cases, like a coworker of mine worked in defense and couldn't use the STL stuff at all, due to customer requirements not to use it.

In general, if there's a choice of using the standard library vs. inventing your own wheel vs. using someone else's library, then in general I'd pick the first choice first. The code gets tested by thousands, hundreds of thousands of people, subject to more testing and scrutiny than most things you'd implement yourself.

A third party library (let's pick an example like Boost) if it has things that you require. A library like Boost is well respected, has a reputation of being exceptional quality code, and is used/tested/maintained by many, many people.

The final choice is invention of your own code, I think this really falls into a few categories:

Self-learning - writing code just to learn, but this means there's no expectation you're shipping it as production code.

You have specific requirements that are not met by anything that can be acquired, or must be adapted from something else. There is a lot of this, you might need to write your own algorithms specific to whatever you're doing.

But remember that if you implement your own, think about whether or not the standard library already has it, otherwise you could run into a maintenance problem if something gets very ingrained in your code. My last company implemented their own container classes, and of course the code base grew to millions of lines of code (across tons of products) and everyone used these internally-developed container classes. Bugs in those containers cost significant amounts of developer time and money to fix because there were just fundamental bugs in the classes (linked lists, vectors, associative arrays, nothing that standard C++ doesn't provide). While new code used the standard library, the company just didn't have the resources to start refactoring all the old code.

If you can offload that worry to other developers who are experienced with such code, AND get the testing of thousands of people? That's a big win!


问:
AVCapturePhotoSettings not accepting accept NSDictionary element
not sure what I am doing wrong, I wanna create a simple custom camera, I'm creating the AVCapturePhotoOutput attaching it to AVCaptureSession, then creating AVCapturePhotoSettings with minimum settings to make taking a picture work, see code below.

I get exception kCVPixelBufferPixelFormatTypeKey is not being define but it is indeed in the NSDictionary I am passing.

I need some light here, thanks

```<code>    public void TakePicture()
    {
        var output = new AVCapturePhotoOutput();
        _captureSession.AddOutput(output);
        var settings = AVCapturePhotoSettings.Create();
        var previewPixelType = settings.AvailablePreviewPhotoPixelFormatTypes.First();

        var keys = new[]
        {
            new NSString("kCVPixelBufferPixelFormatTypeKey"),
            new NSString("kCVPixelBufferWidthKey"),
            new NSString("kCVPixelBufferHeightKey"),
        };

        var objects = new NSObject[]
        {
            // don't have to be strings... can be any NSObject.
            previewPixelType,
            new NSString("160"),
            new NSString("160")
        };

        var dicionary = new NSDictionary<NSString, NSObject>(keys, objects);
        settings.PreviewPhotoFormat = dicionary;
        output.CapturePhoto(settings,this);
    }
</code>```

答:
It is because kCVPixelBufferPixelFormatTypeKey is not available in Xamarin.

We should use CVPixelBuffer.PixelFormatTypeKey  here . It will be convert to kCVPixelBufferPixelFormatTypeKey automatically when compiling.

The same reason for kCVPixelBufferWidthKey and kCVPixelBufferHeightKey , the api is CVPixelBuffer.WidthKey and CVPixelBuffer.HeightKey in Xamarin.iOS.

Body:
not sure what I am doing wrong, I wanna create a simple custom camera, I'm creating the AVCapturePhotoOutput attaching it to AVCaptureSession, then creating AVCapturePhotoSettings with minimum settings to make taking a picture work, see code below.

I get exception kCVPixelBufferPixelFormatTypeKey is not being define but it is indeed in the NSDictionary I am passing.

I need some light here, thanks

    public void TakePicture()
    {
        var output = new AVCapturePhotoOutput();
        _captureSession.AddOutput(output);
        var settings = AVCapturePhotoSettings.Create();
        var previewPixelType = settings.AvailablePreviewPhotoPixelFormatTypes.First();

        var keys = new[]
        {
            new NSString("kCVPixelBufferPixelFormatTypeKey"),
            new NSString("kCVPixelBufferWidthKey"),
            new NSString("kCVPixelBufferHeightKey"),
        };

        var objects = new NSObject[]
        {
            // don't have to be strings... can be any NSObject.
            previewPixelType,
            new NSString("160"),
            new NSString("160")
        };

        var dicionary = new NSDictionary<NSString, NSObject>(keys, objects);
        settings.PreviewPhotoFormat = dicionary;
        output.CapturePhoto(settings,this);
    }


问:
Changing the overall app theme from a fragment in Android Studio
Is it possible to change the theme of the overall app to a dark theme from a fragment? The idea is that I have a switch that can be toggled to swap between a dark/light theme. This is all being done within a fragment, so I'm starting to get a little bit confused. Is this at all possible>

Here is that listener:

```<code>    Switch switchTheme = (Switch) view.findViewById(R.id.switchTheme);

    switchTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         //   switchDark(getView(), isChecked);
            TextView txt = (TextView) getView().findViewById(R.id.lblDark);
            if (isChecked) {
                txt.setText("checked");
                // switchDark(getView(), isChecked);
                (MainActivity) getActivity().getTheme().applyStyle(R.style.AppThemeDark, true);
            }
            else{
                txt.setText("unchecked");
            }
        }
    });
</code>```

Here is my styles.xml:

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
<!-- colors for the dark theme -->
<style name="AppThemeDark" parent="Theme.AppCompat">
    <item name="colorPrimary">@color/darkColorPrimary</item>
    <item name="colorPrimaryDark">@color/darkColorPrimaryDark</item>
    <item name="colorAccent">@color/darkColorAccent</item>
</style>
<style name="AppThemeDark.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.Dark.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.Dark.PopupOverlay" parent="ThemeOverlay.AppCompat" />
</code>```

And here is my colors.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorGrey">#D3D3D3</color>
    <color name="colorTransparent">#FFFFFF</color>
    <color name="colorLearned">#32CD32</color>
    <!-- app/src/main/res/values/colors.xml -->
    <color name="darkColorPrimary">#1e2756</color>
    <color name="darkColorPrimaryDark">#141831</color>
    <color name="darkColorAccent">#2aac4b</color>
</resources>
</code>```

Is there an easier way to do this? Is there a way that I can access the styles.xml and color.xml through the code and manually change the colors myself?
For instance, can I literally just do something like getResources().getColor(R.color.colorAccent) = "FFFFFF";?

Update What I have done now is created a function inside of the main activity, which is this:

```<code>public void ToggleTheme(boolean isChecked){
    if (isChecked) {
        this.getTheme().applyStyle(R.style.AppThemeDark_NoActionBar, true);
    }
    else{
        this.getTheme().applyStyle(R.style.AppTheme, true);
    }
}
</code>```

It is then called inside the fragment like such:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_settings, container, false);

    Switch switchTheme = (Switch) view.findViewById(R.id.switchTheme);

    switchTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         //   switchDark(getView(), isChecked);
            TextView txt = (TextView) getView().findViewById(R.id.lblDark);
            if (isChecked) {
                txt.setText("checked");
                // switchDark(getView(), isChecked);
               // getResources().getColor(R.color.colorPrimary);
                ((MainActivity) getActivity()).ToggleTheme(isChecked);
            }
            else{
                txt.setText("unchecked");
                ((MainActivity) getActivity()).ToggleTheme(isChecked);
            }
        }
    });

    return view;
}
</code>```

It seems to change the theme, but keeps the background as white. I have checked and my colors are indeed set to darker colors that should take effect.

答:
I think this is the best way to switch theme by defining them on the styles and just calling the style name to be set, instead of setting each style/color manually.

And to set your background to white, try to add this code inside the style you want to change:

```<code><item name="android:windowBackground">@color/background</item>
</code>```

reference: Android - how to set background color of all screens?

Body:
Is it possible to change the theme of the overall app to a dark theme from a fragment? The idea is that I have a switch that can be toggled to swap between a dark/light theme. This is all being done within a fragment, so I'm starting to get a little bit confused. Is this at all possible>

Here is that listener:

    Switch switchTheme = (Switch) view.findViewById(R.id.switchTheme);

    switchTheme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
         //   switchDark(getView(), isChecked);
            TextView txt = (TextView) getView().findViewById(R.id.lblDark);
            if (isChecked) {
                txt.setText("checked");
                // switchDark(getView(), isChecked);
                (MainActivity) getActivity().getTheme().applyStyle(R.style.AppThemeDark, true);
            }
            else{
                txt.setText("unchecked");
            }
        }
    });

Here is my styles.xml:

Body:
I think this is the best way to switch theme by defining them on the styles and just calling the style name to be set, instead of setting each style/color manually.

And to set your background to white, try to add this code inside the style you want to change:

<item name="android:windowBackground">@color/background</item>

reference: Android - how to set background color of all screens?


问:
Is it possible to add custom icons to Bootstrap 4 tabs?
Is it possible to add a custom icon to a Bootstrap 4 tabs? When I try to use the following code, the icon fails to show. What is wrong?

HTML

```<code>        <ul class="nav nav-tabs navbar-light bg-light" id="leftTabs" role="tablist">
            <li class="nav-item nav-link active" id="nav-leftDefault-tab" data-toggle="tab"
               href="#nav-leftDefault"
               role="tab" aria-controls="tabA1" aria-selected="true"><span class="listicon"></span></li></ul>
</code>```

SCSS:

```<code>$listico: ("images/icons/list.png");

.listicon{
  background-image: $listico;
}
</code>```

答:
You need to use the background-image property correctly with a valid value. In this case you want to use url()

```<code>$listico: url("images/icons/list.png");

.listicon{
  background-image: $listico;
}
</code>```

https://developer.mozilla.org/en-US/docs/Web/CSS/background-image

Body:
Is it possible to add a custom icon to a Bootstrap 4 tabs? When I try to use the following code, the icon fails to show. What is wrong?

HTML

SCSS:

$listico: ("images/icons/list.png");

.listicon{
  background-image: $listico;
}

Body:
You need to use the background-image property correctly with a valid value. In this case you want to use url()

$listico: url("images/icons/list.png");

.listicon{
  background-image: $listico;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/background-image


问:
LLVM scc_iterator crashes when I use scc_begin on CallGraph
I'm using the scc_iterator on an LLVM CallGraph.

Here's how I get it the CallGraph:

```<code>CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
CG.dump();
</code>```

This causes the segfault:

```<code>scc_iterator<CallGraph*> SCCI = scc_begin(&CG)
</code>```

These are the the passes I've registered:

```<code>legacy::PassManager passManager;
passManager.add(new llvm::CallGraphWrapperPass);
passManager.add(new me::myPass);
</code>```

Additional Notes:
When I dump the callGraph I get this:

```<code>Call graph node <<null function>><<0x21d2910>>  #uses=0
CS<0x0> calls function 'qux'
CS<0x0> calls function 'syscall'
CS<0x0> calls function 'id'
CS<0x0> calls function 'llvm.dbg.declare'
CS<0x0> calls function 'foo'
CS<0x0> calls function 'bar'
CS<0x0> calls function 'main'
CS<0x0> calls function 'llvm.dbg.value'
Call graph node for function: 'bar'<<0x21ceb10>>  #uses=2
CS<0x21cf9c0> calls function 'syscall'

Call graph node for function: 'foo'<<0x21ceba0>>  #uses=2
CS<0x21cf168> calls function 'qux'
CS<0x21cf380> calls function 'id'

Call graph node for function: 'id'<<0x21d2640>>  #uses=2

Call graph node for function: 'llvm.dbg.declare'<<0x21d01b0>>  #uses=1

Call graph node for function: 'llvm.dbg.value'<<0x21d0a10>>  #uses=1

Call graph node for function: 'main'<<0x21ceb70>>  #uses=1
CS<0x21d08e8> calls function 'foo'
CS<0x21d0aa8> calls function 'bar'

Call graph node for function: 'qux'<<0x21ce8e0>>  #uses=2
CS<0x21cd3b0> calls function 'syscall'

Call graph node for function: 'syscall'<<0x21ce940>>  #uses=3
CS<0x0> calls external node
</code>```

Backtrace:
https://pastebin.com/46e5sr5p

答: I was using llvm 4.0. Upgrading to llvm 5.0 seems to be working.</p>

Body:
I'm using the scc_iterator on an LLVM CallGraph.

Here's how I get it the CallGraph:

CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
CG.dump();

This causes the segfault:

scc_iterator<CallGraph*> SCCI = scc_begin(&CG)

These are the the passes I've registered:

legacy::PassManager passManager;
passManager.add(new llvm::CallGraphWrapperPass);
passManager.add(new me::myPass);

Additional Notes:
When I dump the callGraph I get this:

Call graph node <<null function>><<0x21d2910>>  #uses=0
CS<0x0> calls function 'qux'
CS<0x0> calls function 'syscall'
CS<0x0> calls function 'id'
CS<0x0> calls function 'llvm.dbg.declare'
CS<0x0> calls function 'foo'
CS<0x0> calls function 'bar'
CS<0x0> calls function 'main'
CS<0x0> calls function 'llvm.dbg.value'
Call graph node for function: 'bar'<<0x21ceb10>>  #uses=2
CS<0x21cf9c0> calls function 'syscall'

Call graph node for function: 'foo'<<0x21ceba0>>  #uses=2
CS<0x21cf168> calls function 'qux'
CS<0x21cf380> calls function 'id'

Call graph node for function: 'id'<<0x21d2640>>  #uses=2

Call graph node for function: 'llvm.dbg.declare'<<0x21d01b0>>  #uses=1

Call graph node for function: 'llvm.dbg.value'<<0x21d0a10>>  #uses=1

Call graph node for function: 'main'<<0x21ceb70>>  #uses=1
CS<0x21d08e8> calls function 'foo'
CS<0x21d0aa8> calls function 'bar'

Call graph node for function: 'qux'<<0x21ce8e0>>  #uses=2
CS<0x21cd3b0> calls function 'syscall'

Call graph node for function: 'syscall'<<0x21ce940>>  #uses=3
CS<0x0> calls external node

Backtrace:
https://pastebin.com/46e5sr5p