问:
Prevent desktop sharing of a particular c# winforms or detect desktop sharing
While developing an examination software I have a requirement to prevent desktop sharing through applications like TeamViewer, AnyDesk, Ammyy Admin etc or at least detection of it. Our examination software is developed in C#, it's a winform renders question one by one.

I don't think detection is that easy as their are so many ways to capture the screen Desktop Duplication API, BitBlt, Direct3D, DirectX, DirectShow and so many.

So I started exploring for preventing my c# winform getting displayed when desktop sharing is started. To do This I have tried following thing so far:

As our application will run on windows 7 and above so I took advantage of DWM (Destop Window Manager) by checking desktop composition I set SetWindowDisplayAffinity to WDA_MONITOR to enable protection to my winform. By doing this when ever I start desktop sharing, the computer who has taken remote can see black layer over the form. But not all desktop sharing application have the same behavior. Like TeamViewer behaves as expected but Ammyy Admin, AnyDesk does not. How some applications shows black layer and some does not? Is there anything I can do additionally?

if (winForm != null)
{
    if (Protect)
        result = SetWindowDisplayAffinity(winForm.Handle, WDA_MONITOR);
    else
        result = SetWindowDisplayAffinity(winForm.Handle, WDA_NONE);
}
```

this approache I coded is not full proof with all desktop sharing applications, so is there any 100% solution to prevent/detect desktop sharing?

If you tried VLC player's "DirectX (DirectDraw) video output" then this output method also does the same thing like SetWindowDisplayAffinity, it puts black layer on video when any desktop sharing app is started and I tested this works with almost 9 desktop sharing apps, any idea how it's done? and can it be done with c# winform?

Update 29-05-2019

After checking VLC code I come to know that they are using hardware overlay using DirectDraw. So I created vc++ project and used d3d9 and created overlay with red color surface, now if I take remote of machine then the form with red color shows black in color. Bingo!! half problem is solved.

Now, I am trying to set transparency to that window so that, overlay will on top of my C# application and candidate can give the exam and if remote is taken then overlay will get shown in black. To make window transparent I used DwmExtendFrameIntoClientArea winapi, but now on remote also it's visible as transparent. Any way out for this?

答:
I would like to add this as the answer because lots of discussions is carried out in comments which are moved to chat, so I would like to summarize it so that upcoming viewers will get the idea about the discussion and the solution I ended up with.

First I would like to clear the thing how VLC's "DirectX (DirectDraw) video output" works? VLC's this particular output mode uses DirectDraw for creating hardware overlay and video is played on it. While screen capturing (not from mobile or external camera) most of the capture mechanism captures screen by requesting GDI for screens, but hardware overlays are directly rendered on GPU and GDI can't access GPU. It's like GDI->CPU+RAM, DirectX->GPU+VRAM that's why in screen capturing VLC's video playing part appears in black. For more info https://stackoverflow.com/a/21535254/1629242

But as RomanR. mentioned in chat "use of an overlay intended for video is NOT going to help to hide UI of an app".

I also confirm the same, as I mentioned in update, I have created a vc++ project which creates hardware overlay using D3D9 if I play video on it then in screen recording shows black area but I didn't find any way to make that overlay transparent so that it can be put on my app or put app content on overlay so that when screen is recorded app contents will not be visible.

Riddel throw a new idea of "the way anti-viruses work and iterate through all the processes and hash check common screen sharing tools" but I personally feels this will not be generic solution as, I have to maintain list of such applications and it's hash, also if any new applications are found then update that list. Also, anyone can edit bytes to break hashes to makes this false.

Solution I accepted:

Windows API provides a function which helps to display the window's contents only on a monitor. i.e. SetWindowDisplayAffinity, this works like charm!!

problem with Minimum supported OS:

Though the MSDN doc mentions "Minimum supported client::Windows 7" but on windows 7 it's not working for all the screen capturing applications. RomanR. said in a comment "This will work correctly starting from Windows 8 (and possibly also Platform Update for Windows 7). On pure Windows 7, you are exposed to free desktop sharing and being unable to secure your content."

So currently, I am done with SetWindowDisplayAffinity I implemented this as:

```<code>private const uint WDA_NONE = 0x0;
private const uint WDA_MONITOR = 0x1;

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SetWindowDisplayAffinity(IntPtr hWnd, uint dwAffinity);

public static bool SetDRM(Form winForm, bool Protect)
{
    bool result = false;
    if (winForm != null)
    {
        if (Protect)
            result = SetWindowDisplayAffinity(winForm.Handle, WDA_MONITOR);
        else
            result = SetWindowDisplayAffinity(winForm.Handle, WDA_NONE);
    }
    return result;
}
</code>```

Body:
While developing an examination software I have a requirement to prevent desktop sharing through applications like TeamViewer, AnyDesk, Ammyy Admin etc or at least detection of it. Our examination software is developed in C#, it's a winform renders question one by one.

I don't think detection is that easy as their are so many ways to capture the screen Desktop Duplication API, BitBlt, Direct3D, DirectX, DirectShow and so many.

So I started exploring for preventing my c# winform getting displayed when desktop sharing is started. To do This I have tried following thing so far:

As our application will run on windows 7 and above so I took advantage of DWM (Destop Window Manager) by checking desktop composition I set SetWindowDisplayAffinity to WDA_MONITOR to enable protection to my winform. By doing this when ever I start desktop sharing, the computer who has taken remote can see black layer over the form. But not all desktop sharing application have the same behavior. Like TeamViewer behaves as expected but Ammyy Admin, AnyDesk does not. How some applications shows black layer and some does not? Is there anything I can do additionally?

if (winForm != null)
{
    if (Protect)
        result = SetWindowDisplayAffinity(winForm.Handle, WDA_MONITOR);
    else
        result = SetWindowDisplayAffinity(winForm.Handle, WDA_NONE);
}

this approache I coded is not full proof with all desktop sharing applications, so is there any 100% solution to prevent/detect desktop sharing?

If you tried VLC player's "DirectX (DirectDraw) video output" then this output method also does the same thing like SetWindowDisplayAffinity, it puts black layer on video when any desktop sharing app is started and I tested this works with almost 9 desktop sharing apps, any idea how it's done? and can it be done with c# winform?

Update 29-05-2019

After checking VLC code I come to know that they are using hardware overlay using DirectDraw. So I created vc++ project and used d3d9 and created overlay with red color surface, now if I take remote of machine then the form with red color shows black in color. Bingo!! half problem is solved.

Now, I am trying to set transparency to that window so that, overlay will on top of my C# application and candidate can give the exam and if remote is taken then overlay will get shown in black. To make window transparent I used DwmExtendFrameIntoClientArea winapi, but now on remote also it's visible as transparent. Any way out for this?

Body:
I would like to add this as the answer because lots of discussions is carried out in comments which are moved to chat, so I would like to summarize it so that upcoming viewers will get the idea about the discussion and the solution I ended up with.

First I would like to clear the thing how VLC's "DirectX (DirectDraw) video output" works? VLC's this particular output mode uses DirectDraw for creating hardware overlay and video is played on it. While screen capturing (not from mobile or external camera) most of the capture mechanism captures screen by requesting GDI for screens, but hardware overlays are directly rendered on GPU and GDI can't access GPU. It's like GDI->CPU+RAM, DirectX->GPU+VRAM that's why in screen capturing VLC's video playing part appears in black. For more info https://stackoverflow.com/a/21535254/1629242

But as RomanR. mentioned in chat "use of an overlay intended for video is NOT going to help to hide UI of an app".

I also confirm the same, as I mentioned in update, I have created a vc++ project which creates hardware overlay using D3D9 if I play video on it then in screen recording shows black area but I didn't find any way to make that overlay transparent so that it can be put on my app or put app content on overlay so that when screen is recorded app contents will not be visible.

Riddel throw a new idea of "the way anti-viruses work and iterate through all the processes and hash check common screen sharing tools" but I personally feels this will not be generic solution as, I have to maintain list of such applications and it's hash, also if any new applications are found then update that list. Also, anyone can edit bytes to break hashes to makes this false.

Solution I accepted:

Windows API provides a function which helps to display the window's contents only on a monitor. i.e. SetWindowDisplayAffinity, this works like charm!!

problem with Minimum supported OS:

Though the MSDN doc mentions "Minimum supported client::Windows 7" but on windows 7 it's not working for all the screen capturing applications. RomanR. said in a comment "This will work correctly starting from Windows 8 (and possibly also Platform Update for Windows 7). On pure Windows 7, you are exposed to free desktop sharing and being unable to secure your content."

So currently, I am done with SetWindowDisplayAffinity I implemented this as:

private const uint WDA_NONE = 0x0;
private const uint WDA_MONITOR = 0x1;

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SetWindowDisplayAffinity(IntPtr hWnd, uint dwAffinity);

public static bool SetDRM(Form winForm, bool Protect)
{
    bool result = false;
    if (winForm != null)
    {
        if (Protect)
            result = SetWindowDisplayAffinity(winForm.Handle, WDA_MONITOR);
        else
            result = SetWindowDisplayAffinity(winForm.Handle, WDA_NONE);
    }
    return result;
}


来源: stackexchange

问:
Kubernetes | Any hooks available for Pod restarts?
Are there any hooks available for Pod lifecycle events? Specifically, I want to run a command to upload logs on pod restart. </p>

答:
Edit: PreStop hook doesn't work for container restart - please see rest of answer below

As standing in documentation there are PreStop and PostStart events and you can attach to them.

Example from docs:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: nginx
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
      preStop:
        exec:
          command: ["/bin/sh","-c","nginx -s quit; while killall -0 nginx; do sleep 1; done"]
</code>```

Edit:
So I checked with following POC if that preStop hook is executed on container crash and conclusion is: NOT

```<code>apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    volumeMounts:
    - mountPath: /data
      name: test-volume
    image: nginx
    command: ["/bin/sh"]
    args: ["-c", "sleep 5; exit 1"]
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /data/postStart"]
      preStop:
        exec:
          command: ["/bin/sh","-c","echo preStop handler! > /data/preStop"]

  volumes:
  - name: test-volume
    hostPath:
      path: /data
      type: Directory
</code>```

As solution for you I would recommend to override command section for you container this way:

```<code>command: ["/bin/sh"]
args: ["-c", "your-application-executable; your-logs-upload"]
</code>```

so your-logs-upload executable will be executed after your-application-executable crash/end

ContentLicense: CC BY-SA 4.0

Body:
Edit: PreStop hook doesn't work for container restart - please see rest of answer below

As standing in documentation there are PreStop and PostStart events and you can attach to them.

Example from docs:

apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    image: nginx
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /usr/share/message"]
      preStop:
        exec:
          command: ["/bin/sh","-c","nginx -s quit; while killall -0 nginx; do sleep 1; done"]

Edit:
So I checked with following POC if that preStop hook is executed on container crash and conclusion is: NOT

apiVersion: v1
kind: Pod
metadata:
  name: lifecycle-demo
spec:
  containers:
  - name: lifecycle-demo-container
    volumeMounts:
    - mountPath: /data
      name: test-volume
    image: nginx
    command: ["/bin/sh"]
    args: ["-c", "sleep 5; exit 1"]
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh", "-c", "echo Hello from the postStart handler > /data/postStart"]
      preStop:
        exec:
          command: ["/bin/sh","-c","echo preStop handler! > /data/preStop"]

  volumes:
  - name: test-volume
    hostPath:
      path: /data
      type: Directory

As solution for you I would recommend to override command section for you container this way:

command: ["/bin/sh"]
args: ["-c", "your-application-executable; your-logs-upload"]

so your-logs-upload executable will be executed after your-application-executable crash/end


问:
Can I disable SOP (Same Origin Policy) on any browser for development?
I want to develop JavaScript on my Windows machine. Do you know a browser where I can turn off Same Origin Policy so I can develop locally? Firefox would be optimal.

Or if you know a proxy I could use for a SOAP/WSDL site it would be great too.

I am trying to work with the JavaSCript SOAP Client.

答:
i run this command on mac, it works on me when i use google chrome to run my project.</p>

```<code>open -a Google\ Chrome --args --disable-web-security --user-data-dir
</code>```

OwnerDisplayName: Thomaschaaf

ContentLicense: CC BY-SA 3.0

Body:
i run this command on mac, it works on me when i use google chrome to run my project.

open -a Google\ Chrome --args --disable-web-security --user-data-dir


问:
How to decide the maximum number of faulty replicas in Practical Byzantine Fault Tolerance?
In PBFT consensus, we know that there should be 3f+1 replicas out of which 2f+1 correct ones and f are the maximum number of faulty replicas network can tolerate. I wonder while setting up fabric how to keep this thing in mind. What are the parameters on which we can predict the chances of faulty replicas?</p>

答:
I assume you are setting up your orderers with a BFT consensus plugin such as BFT-SMART. BFT algorithms are only required if you want to tolerate malicious faults. If you're only concerned about crash faults, you can also use Kafka consensus, which tolerates up to 50% crashing nodes.

So if you're setting up a business network, each partner should be running one ordering node. The number of tolerated malicious partners depends on your total number of partners. So if you have 4 partners, one of them can be malicious without your network breaking down, if you have 7 partners, you tolerate two, etc.

So it's not really a conscious choice that you're making in how many replicas to run. The number of tolerated malicious nodes depends on the number of independent partners you have running ordering nodes. There is no point in having one organization run multiple ordering nodes, since they could manipulate all of them if they were acting maliciously.


问:
error C2039: 'IsNearDeath': is not a member of 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>
I recently upgraded my nodejs to v12.3.1, and now when I try to run npm install in my project repository, I am getting the preceding errors.

```<code>error C2059: syntax error: ')' (compiling source file ..\src\custo
m_importer_bridge.cpp)

error C2660: 'v8::StringObject::New': function does not take 1 arg
uments (compiling source file ..\src\sass_context_wrapper.cpp)

node_modules\nan\nan_object_wrap.h(127): error C2039: 'IsNearDeath': is not a member of 'Nan::Persistent<v8::Object,v
8::NonCopyablePersistentTraits<T>>'
</code>```

Things I have tried

Deleted the node_modules folder and run npm install

Closed vscode and open the solution again

update npm to the latest

Anyone else are facing the same issue with v12.3.1?

答:
I have tried many things to solve this issue. It seems like the version v12.3.1 is not stable yet. As a workaround, I installed the version v10.16.0 and that fixed the issue. As I had installed the latest version previously (v12.3.1) the Node.js was not allowing me to install a lower version, so I had to uninstall the Node.js and install the v10.16.0. I hope it helps.

Update:

As @forsunnet mentioned in his comment, the issue is with the version 13.12 too, going back to version 11.x solved the issue for him.

Body:
I recently upgraded my nodejs to v12.3.1, and now when I try to run npm install in my project repository, I am getting the preceding errors.

error C2059: syntax error: ')' (compiling source file ..\src\custo
m_importer_bridge.cpp)

error C2660: 'v8::StringObject::New': function does not take 1 arg
uments (compiling source file ..\src\sass_context_wrapper.cpp)

node_modules\nan\nan_object_wrap.h(127): error C2039: 'IsNearDeath': is not a member of 'Nan::Persistent<v8::Object,v
8::NonCopyablePersistentTraits<T>>'

Things I have tried

Deleted the node_modules folder and run npm install

Closed vscode and open the solution again

update npm to the latest

Anyone else are facing the same issue with v12.3.1?


问:
How can I fix a "NoMethodError" exception?
I'm getting this error:

```<code>NoMethodError in Videos#index

Showing /rubyprograms/dreamstill/app/views/videos/index.html.erb where line #12 raised:

undefined method `upvoted_videos' for nil:NilClass
Extracted source (around line #12):

9: <div class="home_options">
10:     <ul class="home_options_list">
11:         <li> <%= link_to "Top Songs", videos_path, :class => "top_songs  chosen_home_option" %> </li>
12:         <li> <%= link_to "#{pluralize(current_user.upvoted_videos.count, 'Upvoted Song')}", upvoted_videos_path, :action => "upvoted_songs", :class => "upvoted_songs" %> </li>
</code>```

This is in my user model:

```<code>def upvoted_videos
  self.voted_videos.where("value = 1")
end
</code>```

答: It is throwing an error because you are trying to call upvoted_videos on a nil object. This means that current_user is nil. I would add some sort of check to see if current_user is not nil before calling calling upvoted_videos

Body:
I'm getting this error:

NoMethodError in Videos#index

Showing /rubyprograms/dreamstill/app/views/videos/index.html.erb where line #12 raised:

undefined method `upvoted_videos' for nil:NilClass
Extracted source (around line #12):

9:

10:

11:
 <%= link_to "Top Songs", videos_path, :class => "top_songs  chosen_home_option" %>

12:
 <%= link_to "#{pluralize(current_user.upvoted_videos.count, 'Upvoted Song')}", upvoted_videos_path, :action => "upvoted_songs", :class => "upvoted_songs" %>

This is in my user model:

def upvoted_videos
  self.voted_videos.where("value = 1")
end


问:
subcategory not showing on admin panel
I'm editing a Laravel 4.3 site and I have a db table called categories which has the following fields:

id
parent_id
name
I'm trying to output a list in my view of categories, and their subcategories:

Category
Another Category
Subcat
Subcat
Subcat
I'm not really sure of the best way of achieving this and hoping someone can help point me in the right direction :-)

this is my controller

public function store(Request $request)
    {

```<code>    $this->validate($request, [

        'name' =>'required'

    ]);

    $category= new Category;

    $category= Category::with('children')->whereNull('parent_id')->get();

    $category->name =$request->name;

    $category->save();}
</code>```

答:
I hope this would help you

Method to store the data:

```<code>public function store(Request $request) {

    $this->validate($request, [
        'name' =>'required',
        'parent_id' => 'nullable|exists:category,id', //This will check the parent availability
    ]);

    $category= new Category;

    if ($request->has('parent_id')) {
        $category->parent_id =$request->parent_id;
    }

    $category->name =$request->name;
    $category->save();

    return $category;
}
</code>```

Method to retrieve all data:

```<code>public function index() {
    $categories = Category::with('children')->all();

    return $categories;
}
</code>```

Method to get category by id :

```<code>public function categoryById(Category $category) {
    $category = Category::with('children')->where('id', $category->id)->first();

    return $category;
}
</code>```

Title: subcategory not showing on admin panel

Body:
I'm editing a Laravel 4.3 site and I have a db table called categories which has the following fields:

id
parent_id
name
I'm trying to output a list in my view of categories, and their subcategories:

Category
Another Category
Subcat
Subcat
Subcat
I'm not really sure of the best way of achieving this and hoping someone can help point me in the right direction :-)

this is my controller

public function store(Request $request)
    {

    $this->validate($request, [

        'name' =>'required'

    ]);

    $category= new Category;

    $category= Category::with('children')->whereNull('parent_id')->get();

    $category->name =$request->name;

    $category->save();}

Body:
I hope this would help you

Method to store the data:

public function store(Request $request) {

    $this->validate($request, [
        'name' =>'required',
        'parent_id' => 'nullable|exists:category,id', //This will check the parent availability
    ]);

    $category= new Category;

    if ($request->has('parent_id')) {
        $category->parent_id =$request->parent_id;
    }

    $category->name =$request->name;
    $category->save();

    return $category;
}

Method to retrieve all data:

public function index() {
    $categories = Category::with('children')->all();

    return $categories;
}

Method to get category by id :

public function categoryById(Category $category) {
    $category = Category::with('children')->where('id', $category->id)->first();

    return $category;
}


问:
all js files in javascript/packs are not loading in my application in production
The application was working fine. Its a Rails 5.1 with StimulusJS.

I've tried to do in the server

```<code>RAILS_ENV=production bundle exec rake assets:precompile
</code>```

with no effect.

it seems like it isn't accesible

this is the relevant code in production.rb

```<code>Rails.application.configure do
  # Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = false

  # Settings specified here will take precedence over those in config/application.rb.
  # Analytics account
  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true
</code>```

and a screen of the console showing the error

答:
Given the assets in the "normal" pipeline were working, and after trying variations in syntax what finally worked was getting by ssh in the server, and running this command:

```<code>RAILS_ENV=production bundle exec rails webpacker:compile
</code>```

It seems normal assets and webpacker go two different ways.

Body:
The application was working fine. Its a Rails 5.1 with StimulusJS.

I've tried to do in the server

RAILS_ENV=production bundle exec rake assets:precompile

with no effect.

it seems like it isn't accesible

this is the relevant code in production.rb

Rails.application.configure do
  # Verifies that versions and hashed value of the package contents in the project's package.json
config.webpacker.check_yarn_integrity = false

  # Settings specified here will take precedence over those in config/application.rb.
  # Analytics account
  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  # config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

and a screen of the console showing the error

Body:
Given the assets in the "normal" pipeline were working, and after trying variations in syntax what finally worked was getting by ssh in the server, and running this command:

RAILS_ENV=production bundle exec rails webpacker:compile

It seems normal assets and webpacker go two different ways.


问:
Testing flask-oauthlib locally without https
I have implemented an oauth2 server and an oauth2 client using flask-oauthlib.

When I am trying to test locally, the client returns an InsecureTransportError and tells me that I should be using https.

Is there a way to test the app locally without https?

The client is running on 127.0.0.2:5000 and the server is running on 127.0.0.1:5000.

Thanks

答:
For Authlib usesrs :

```<code>export AUTHLIB_INSECURE_TRANSPORT=1
</code>```

Or if you want to set it programmatically :

```<code>import os

os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'
</code>```

I know it's not answering the question but everytime I ask Google about it I land on this page.

Body:
For Authlib usesrs :

export AUTHLIB_INSECURE_TRANSPORT=1

Or if you want to set it programmatically :

import os

os.environ['AUTHLIB_INSECURE_TRANSPORT'] = '1'

I know it's not answering the question but everytime I ask Google about it I land on this page.


问:
How to get JSON data from an API in flutter
I'm facing the same issue since i start coding yesterday on my project which has a part of getting some of json data from a given api.

My api link is: http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

I'm working on flutter SDK and i'm confused why it is not working with me!, my job is to get only link, title, and source_url objects but i cannot get it.

I tried the following code in flutter documentation

https://flutter.dev/docs/cookbook/networking/fetch-data
and after some of modification according to my needs didn't got any data.

```<code>import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'].toString(),
      link: json['link'].toString()
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.link);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
</code>```

I only got the meesage below:

Type List dynamic is not a subtype of type Map String, dynamic

Any help will be appreciated.

Thanks in advance.

答:
Your JSON response is of type List<dynamic> but you are taking response in Map String, dynamic  but you can do something like this

```<code>     import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clickmeetplay/iam/user/postbean.dart';
import 'package:http/http.dart' as http;

class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: PostScreen(),),);
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {

  List<Post> _postList =new List<Post>();

  Future<List<Post> > fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values=new List<dynamic>();
      values = json.decode(response.body);
      if(values.length>0){
        for(int i=0;i<values.length;i++){
          if(values[i]!=null){
            Map<String,dynamic> map=values[i];
            _postList .add(Post.fromJson(map));
            debugPrint('Id-------${map['id']}');
          }
        }
      }
      return _postList;

    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  void initState() {

    fetchPost();

  }
}
</code>```

Bean class

```<code>class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        id: json['id'],
        title: json['title'].toString(),
        link: json['link'].toString()
    );
  }
}
</code>```

Body:
I'm facing the same issue since i start coding yesterday on my project which has a part of getting some of json data from a given api.

My api link is: http://alkadhum-col.edu.iq/wp-json/wp/v2/posts?_embed

I'm working on flutter SDK and i'm confused why it is not working with me!, my job is to get only link, title, and source_url objects but i cannot get it.

I tried the following code in flutter documentation

https://flutter.dev/docs/cookbook/networking/fetch-data
and after some of modification according to my needs didn't got any data.

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title'].toString(),
      link: json['link'].toString()
    );
  }
}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<Post> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Post>(
            future: post,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.link);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

I only got the meesage below:

Type List dynamic is not a subtype of type Map String, dynamic

Any help will be appreciated.

Thanks in advance.

Body:
Your JSON response is of type List<dynamic> but you are taking response in Map String, dynamic  but you can do something like this

     import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:clickmeetplay/iam/user/postbean.dart';
import 'package:http/http.dart' as http;

class PostHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: PostScreen(),),);
  }
}

class PostScreen extends StatefulWidget {
  @override
  _PostScreenState createState() => _PostScreenState();
}

class _PostScreenState extends State<PostScreen> {

  List<Post> _postList =new List<Post>();

  Future<List<Post> > fetchPost() async {
    final response =
    await http.get('http://alkadhum-col.edu.iq/wp-json/wp/v2/posts/');

    if (response.statusCode == 200) {
      // If the call to the server was successful, parse the JSON
      List<dynamic> values=new List<dynamic>();
      values = json.decode(response.body);
      if(values.length>0){
        for(int i=0;i<values.length;i++){
          if(values[i]!=null){
            Map<String,dynamic> map=values[i];
            _postList .add(Post.fromJson(map));
            debugPrint('Id-------${map['id']}');
          }
        }
      }
      return _postList;

    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }
  }
  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  void initState() {

    fetchPost();

  }
}

Bean class

class Post {

  final int id;
  String title;
  String link;

  Post({this.id, this.title, this.link});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        id: json['id'],
        title: json['title'].toString(),
        link: json['link'].toString()
    );
  }
}


问:
Getting a Docker x509 Certificate Error after upgrade
I recently migrated my dev environment from Windows Home to Pro and as part of the upgrade installed Docker Desktop instead of using Docker Toolbox.

After the upgrade, using the default Docker Desktop instance I kept receiving some variation on the below error.

Error response from daemon: Get https://docker.abc.xyz.net/v1/users/:
  x509:  certificate is valid for *.xyz.net, xyg.net, not
  docker.abc.xyz.net

What could be causing the problem? I have searched around the internet for hours and all the different solutions have no effect. Restarting Docker, uninstall and reinstall.

Can anybody help?

答:
It appears as part of the migration from Docker Toolbox to Docker Desktop a number of entries are leftover in the hosts file on Windows that cause a conflict when Docker is trying to access any external network. The simple fix? Remove these 5 lines from my hosts file </p>

```<code>52.3.153.154    index.docker.io
34.200.28.105   registry.docker.io
52.20.146.203   registry-1.docker.io
54.152.209.167  auth.docker.io
52.222.149.24   dseasb33srnrn.cloudfront.net
</code>```

Body:
It appears as part of the migration from Docker Toolbox to Docker Desktop a number of entries are leftover in the hosts file on Windows that cause a conflict when Docker is trying to access any external network. The simple fix? Remove these 5 lines from my hosts file

52.3.153.154    index.docker.io
34.200.28.105   registry.docker.io
52.20.146.203   registry-1.docker.io
54.152.209.167  auth.docker.io
52.222.149.24   dseasb33srnrn.cloudfront.net


问:
Sending payload in GET request's body instead of POST to resolve HTTP 414 URI Too Long
A 414 error is caused by a long URI parameters on a GET request. It has been suggested here and here to use a POST request in that case, however, wouldn't it be more realistic to send the data in the GET request's body, even though it is not recommended to do so?</p>

答:
It's not a good practice to send data in the GET request's body. According to RFC7231:

A payload within a GET request message has no defined semantics;
sending a payload body on a GET request might cause some existing
implementations to reject the request.

Thus, it's not "more realistic", but actually less realistic, as some browser or server may reject such HTTP request.


问:
Does Windows.CopyFile create a temporary local file while source and destination are network shares?
I have a D2007 application that uses Windows.CopyFile to copy MS Word and PowerPoint files from one network folder to another network folder. Our organization is migrating to Windows 7 from Vista. One of my migrated users got an error message that displayed a partial local folder (C:\Users\(username)\...\A100203.doc) during the copy. Does the CopyFile function cache a local copy of the document when it is copying from one network folder to another network folder or is it a direct write? I have never seen this error before and the application has been running for years on Win95, Win 98, Win2000, WinXP and Vista.</p>

答:
The user that launches the copy will require read access to the original and write access to the target, regardless of caching (if the user has read access to the file, then the file can be written to a local cache, so caching/no-caching is irrelevant).

It's basic security to disallow someone to be able to copy files/directories among machines just because the security attributes between the machines are compatible.

There's little else to say without the complete text of the error message.


问:
How to fix my layout so my nav bar doesn´t hide some content after linking to the desired section
my navbar is set to fixed, but everytime i press on e.g. home, it doesnt scroll to the most top, the site is just a little under the maximum you can possibly scroll to the top, this makes my H1 beeing covered partly by my navbar.

I've tried different settings for my nav bar like static etc.

I've tried to change the padding of my nav bar which didnt helped either.

I've tried to achieve better results with different min heights for the sections, currently its set to 85%

```<code><!-- Header -->
<header>

<div id="logo">
    <img src="img/111.jpg"="Kurzwarenmobil">
</div>

<nav>

    <ul>
        <a href="#home"><li>home</li></a>
        <a href="#about"><li>Über mich</li></a>
        <a href="#DasKurzwarenmobil"><li>Das Kurzwarenmobil</li></a>
        <a href="#Kontakt"><li>Kontakt</li></a>
    </ul>
</nav>
</code>```

Kurzwarenmobil

H.S. Schneiderbedarf

html, body{margin: 0; padding: 0; height: 100%; text-align: center;}
section { min-height: 85%}
a {text-decoration: none;}
li {list-style-type: none;}

header { width: 100%; height: 65px; position: fixed; top:0; left: 0;

background: #FEFCFB; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) ; z-index:
1; }

logo {

width: 140px;
float: left;
margin: 10px 0 0 -10px
}

home{

background: url(../img/landing.jpg);
background-position: center center;
background-size: cover;
background-attachment:  fixed;
}

home h1 {

margin: 62px auto 0 auto;
font-size: 110px}

home h2 {

margin: 50 auto 0 auto;
font-size: 25px;

}

home img  {

width: 32px;
margin-top: 150px;
opacity: 0.7;
}

home img:hover {

opacity: 1;
}

home {min-height: 100%}

I want my Nav bar to Navigate to the most top part of the site, which means that there is no more space to scroll to the top. right now when i click on "home" on the nav bar, half of my H1 is covered by the navbar because it´s not scrolled up enough

答: Welcome to Stackoverflow Burak  Please try linking to , so that it scrolls to the logo - I think it should solve your issue, but if not, plese care to include a link to href="http://jsfiddle.net" rel="nofollow noreferrer">http://jsfiddle.net where you can share your code and visualize the issue

Body:
my navbar is set to fixed, but everytime i press on e.g. home, it doesnt scroll to the most top, the site is just a little under the maximum you can possibly scroll to the top, this makes my H1 beeing covered partly by my navbar.

I've tried different settings for my nav bar like static etc.

I've tried to change the padding of my nav bar which didnt helped either.

I've tried to achieve better results with different min heights for the sections, currently its set to 85%

home

Über mich

Das Kurzwarenmobil

Kontakt

Kurzwarenmobil

H.S. Schneiderbedarf

html, body{margin: 0; padding: 0; height: 100%; text-align: center;}
section { min-height: 85%}
a {text-decoration: none;}
li {list-style-type: none;}

header { width: 100%; height: 65px; position: fixed; top:0; left: 0;

background: #FEFCFB; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1) ; z-index:
1; }

logo {

width: 140px;
float: left;
margin: 10px 0 0 -10px
}

home{

background: url(../img/landing.jpg);
background-position: center center;
background-size: cover;
background-attachment:  fixed;
}

home h1 {

margin: 62px auto 0 auto;
font-size: 110px}

home h2 {

margin: 50 auto 0 auto;
font-size: 25px;

}

home img  {

width: 32px;
margin-top: 150px;
opacity: 0.7;
}

home img:hover {

opacity: 1;
}

home {min-height: 100%}

I want my Nav bar to Navigate to the most top part of the site, which means that there is no more space to scroll to the top. right now when i click on "home" on the nav bar, half of my H1 is covered by the navbar because it´s not scrolled up enough

Body: Welcome to Stackoverflow Burak  Please try linking to <a href="#logo">, so that it scrolls to the logo - I think it should solve your issue, but if not, plese care to include a link to http://jsfiddle.net where you can share your code and visualize the issue


问:
POST method is not supported for this route
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

```<code><div class="card-body">
    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

        <div class="form-group">
            <label for="location">Location</label>
            <input class="form-control" type="text" name="location" value="{{$info->location}}">
        </div>
        <div class="form-group">
            <label for="about">About</label>
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
        </div>
        <div class="form-control">
            <p class="text-center">
                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
            </p>
        </div>
    </form>
</div>
</code>```

Routes:

```<code>Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});
</code>```

in controller:

```<code>public function update(Request $request, $id)
{

    dd($request->all());

}
</code>```

答:
You have an error in your form definition

```<code> <form class="{{route('profile.update', ['id' => $id])}}" method="post">
</code>```

should be

```<code> <form action="{{route('profile.update', ['id' => $id])}}" method="post">
</code>```

Body:
First, I've checked other question topic, but couldn't find the solution.

when I try to post my form. I am getting this error.

The POST method is not supported for this route. Supported methods:
  GET, HEAD.

Form:

    <form action="{{route('profile.update', ['id' => $id])}}" method="post">
      @csrf
      @put

            Location
            <input class="form-control" type="text" name="location" value="{{$info->location}}">

            About
            <textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>

                <button class="btn btn-primary btn-md" type="submit">Update Your Info</button>

    </form>

Routes:

Route::group(["middleware" => "auth"], function(){
    route::get("/profile/edit", [
        "uses" => "ProfilesController@edit",
        "as" => "profile.edit"
    ]);
    route::get("/profile/{slug}", [
        "uses" => "ProfilesController@index",
        "as" => "profile"
    ]);
    route::put("/profile/update/{id}", [
        "uses" => "ProfilesController@update",
        "as" => "profile.update"
    ]);
});

in controller:

public function update(Request $request, $id)
{

    dd($request->all());

}

Body:
You have an error in your form definition

 <form class="{{route('profile.update', ['id' => $id])}}" method="post">

should be

 <form action="{{route('profile.update', ['id' => $id])}}" method="post">


问:
EF6 Select from MySQL Table
I have an existing MySQL database with tables. I am creating a windows service which will fetch data from the MySql table c2b2_callbacks and pass the value to my DTO class.

Below is my select statement

```<code>public async Task<IEnumerable<Callback>> GetCallbacks()
    {

        using(MySqlConnection conn = new MySqlConnection(connectionString))
        {
            try
            {
                await conn.OpenAsync();
                //MySqlTransaction sqlTransaction = await conn.BeginTransactionAsync();

                using (M2AContext context = new M2AContext())
                {
                    //context.Database.UseTransaction(sqlTransaction);

                    // Error
                    IEnumerable<CallBack> transactions = await context.Transactions.SqlQuery("SELECT * FROM oapi_test.c2b2_callbacks WHERE Status = 0 AND MSISDN REGEXP \'^([a-z]*[a-z]\\s*){3}([0-9]*[0-9]){3}([a-z]){1}$\';").ToListAsync();
                    return transactions;
                }
            }
            catch(Exception e)
            {
                //log
                Console.WriteLine($"Error {e.Message}");
                return null;
            }
        }
    }
</code>```

Below is My CallBack class

```<code> public class CallBack
{
    public string TransID { get; set; }
    public DateTime TransTime { get; set; }
    public string MSISDN { get; set; }

    public Int16 Status { get; set; }
}
</code>```

Below is my context

```<code>[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class M2AContext: DbContext
{
    public M2AContext(): base()
    {

    }

    public M2AContext(DbConnection connection, bool ownedconnection): base(connection, ownedconnection)
    {

    }

    public DbSet<Callbacks> Transactions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}
</code>```

I am trying to get the transactions but it fails at the SELECT statement and throws this error

```<code>{"Object reference not set to an instance of an object."}
</code>```

I have gone through this documentation and I don't know why there is this error.

This is the stack trace

```<code>at MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
at MySql.Data.Entity.MySqlManifestTokenResolver.ResolveManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ExecuteSqlQueryAsync(String sql, Boolean asNoTracking, Nullable`1 streaming, Object[] parameters)
at System.Data.Entity.Internal.InternalSqlSetQuery.GetAsyncEnumerator()
at System.Data.Entity.Infrastructure.DbRawSqlQuery`1.System.Data.Entity.Infrastructure.IDbAsyncEnumerable<TElement>.GetAsyncEnumerator()
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ForEachAsync[T](IDbAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken)
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source, CancellationToken cancellationToken)
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source)
at System.Data.Entity.Infrastructure.DbRawSqlQuery`1.ToListAsync()
at m2a.Repositories.Repository.<GetCallbacks>d__2.MoveNext() in C:\Users\JNyingi\source\repos\m2a\Repositories\Repository.cs:line 38
</code>```

答:
I think you need to provide a mapping otherwise EF won't know how to bind to the CallBack object

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
```

<p>should be</p>

<pre class="lang-cs prettyprint-override"><code>    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<CallBack>("c2b2_callbacks");
    }
</code>```

Title: EF6 Select from MySQL Table

Body:
I have an existing MySQL database with tables. I am creating a windows service which will fetch data from the MySql table c2b2_callbacks and pass the value to my DTO class.

Below is my select statement

public async Task<IEnumerable<Callback>> GetCallbacks()
    {

        using(MySqlConnection conn = new MySqlConnection(connectionString))
        {
            try
            {
                await conn.OpenAsync();
                //MySqlTransaction sqlTransaction = await conn.BeginTransactionAsync();

                using (M2AContext context = new M2AContext())
                {
                    //context.Database.UseTransaction(sqlTransaction);

                    // Error
                    IEnumerable<CallBack> transactions = await context.Transactions.SqlQuery("SELECT * FROM oapi_test.c2b2_callbacks WHERE Status = 0 AND MSISDN REGEXP \'^([a-z]*[a-z]\\s*){3}([0-9]*[0-9]){3}([a-z]){1}$\';").ToListAsync();
                    return transactions;
                }
            }
            catch(Exception e)
            {
                //log
                Console.WriteLine($"Error {e.Message}");
                return null;
            }
        }
    }

Below is My CallBack class

 public class CallBack
{
    public string TransID { get; set; }
    public DateTime TransTime { get; set; }
    public string MSISDN { get; set; }

    public Int16 Status { get; set; }
}

Below is my context

[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class M2AContext: DbContext
{
    public M2AContext(): base()
    {

    }

    public M2AContext(DbConnection connection, bool ownedconnection): base(connection, ownedconnection)
    {

    }

    public DbSet<Callbacks> Transactions { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }
}

I am trying to get the transactions but it fails at the SELECT statement and throws this error

{"Object reference not set to an instance of an object."}

I have gone through this documentation and I don't know why there is this error.

This is the stack trace

at MySql.Data.MySqlClient.MySqlProviderServices.GetDbProviderManifestToken(DbConnection connection)
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifestToken(DbConnection connection)
at MySql.Data.Entity.MySqlManifestTokenResolver.ResolveManifestToken(DbConnection connection)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ExecuteSqlQueryAsync(String sql, Boolean asNoTracking, Nullable`1 streaming, Object[] parameters)
at System.Data.Entity.Internal.InternalSqlSetQuery.GetAsyncEnumerator()
at System.Data.Entity.Infrastructure.DbRawSqlQuery`1.System.Data.Entity.Infrastructure.IDbAsyncEnumerable<TElement>.GetAsyncEnumerator()
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ForEachAsync[T](IDbAsyncEnumerable`1 source, Action`1 action, CancellationToken cancellationToken)
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source, CancellationToken cancellationToken)
at System.Data.Entity.Infrastructure.IDbAsyncEnumerableExtensions.ToListAsync[T](IDbAsyncEnumerable`1 source)
at System.Data.Entity.Infrastructure.DbRawSqlQuery`1.ToListAsync()
at m2a.Repositories.Repository.<GetCallbacks>d__2.MoveNext() in C:\Users\JNyingi\source\repos\m2a\Repositories\Repository.cs:line 38

Body:
I think you need to provide a mapping otherwise EF won't know how to bind to the CallBack object

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

should be

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<CallBack>("c2b2_callbacks");
    }


问:
Firebase Authentication with multi-factor authentication
Is there a way to implement multi-factor authentication on Firebase Authentication? From my research it seems impossible since Firebase authentication has public REST api of which, assumingly, someone knowing API_KEY and user's email/pass could directly sign in to that user's account using

https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=[API_KEY]

Thank you

答: Firebase Authentication with multi-factor authentication should soon be available according to this Google I/O video</p>


问:
VS2010 Project Configuration - Anti Reverse Engineering Friendly
I am searching for some good tricks of project settings in Visual Studio 2010 to get binary harder to reverse engineering.</p>

答: Turn on as much optimization as you can without making your program crash, this will make the resultant binaries MUCH harder to reverse engineer.  You can get address-space layout randomization through the linker option.  Otherwise, there are obvious things like building a release version instead of a Debug version, Since 2003 Visual Studio comes with Dotfuscator, which does a good job of protecting .NET programs. To add to Abyx's comment, some protectors, like Software Passport and Oreans products allow you to insert anti-tampering things during the compilation process, which is much more effective than just applying the packer to the compiled binary.  </p>


问:
Unable to get children of IContent
I'm trying to get the Children of an Icontent object.

```<code>IContent filialsParent = cs.GetById(filialParrentId);

if (filialsParent != null)
{
    IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;
    bool hasChildren = contentService.HasChildren(filialsParent.Id);
    long totalChildren;

    IEnumerable<IContent> children = contentService.GetPagedChildren(filialsParent.Id, 1, 100, out totalChildren);

    foreach (var child in children)
    {
        context.WriteLine(string.Format("child: {0}", child.Name));
    }

    context.WriteLine(string.Format("Children found:({0}) in: {1}", children.Count(), filialParrentId));

}
</code>```

If I debug the code, I get the following.

My long totalChildren will be 1 after the line contentService.GetPagedChildren(filialsParent.Id, 1, 100, out totalChildren); runs.

My IEnumerable<IContent> children is null, and for that reason (of course) is my children.Count() 0

Sadly filialsParent does not contain the function .children() as I hoped it would.

Is there a way to get the Children of my filialsParent, and yes it does have children that are published.

答:
I dit got the exact same problem. For testing purposes I removed everything Only bare essentials.

==> umbraco 8.0.2

Make sure you got a parent and a few childeren attached

```<code>// For testing purposes hardcode your parent Id
var contentId = [ID];

// SET for returning total records
long totalChildren;

// int id ==> You even could hardcode your first param (contentID in here)
// long pageIndex ==> SET your index to 0 ==> first indexpage starts at 0 and not 1 ==> if you set this to 1 and the Pagesize = 100  and you have only 99 childeren you wil wil get null because we are requesting the second page
// int pageSize ==> We need max 10 childeren
// out long totalChildren
// IQuery<IContent> filter = null ==> not used
// Ordering ordering = null ==> not used
IEnumerable<IContent> children = Services.ContentService.GetPagedChildren(contentId, 0, 10, out totalChildren);
</code>```

Title: Unable to get children of IContent

Body:
I'm trying to get the Children of an Icontent object.

IContent filialsParent = cs.GetById(filialParrentId);

if (filialsParent != null)
{
    IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;
    bool hasChildren = contentService.HasChildren(filialsParent.Id);
    long totalChildren;

    IEnumerable<IContent> children = contentService.GetPagedChildren(filialsParent.Id, 1, 100, out totalChildren);

    foreach (var child in children)
    {
        context.WriteLine(string.Format("child: {0}", child.Name));
    }

    context.WriteLine(string.Format("Children found:({0}) in: {1}", children.Count(), filialParrentId));

}

If I debug the code, I get the following.

My long totalChildren will be 1 after the line contentService.GetPagedChildren(filialsParent.Id, 1, 100, out totalChildren); runs.

My IEnumerable<IContent> children is null, and for that reason (of course) is my children.Count() 0

Sadly filialsParent does not contain the function .children() as I hoped it would.

Is there a way to get the Children of my filialsParent, and yes it does have children that are published.

Body:
I dit got the exact same problem. For testing purposes I removed everything Only bare essentials.

==> umbraco 8.0.2

Make sure you got a parent and a few childeren attached

// For testing purposes hardcode your parent Id
var contentId = [ID];

// SET for returning total records
long totalChildren;

// int id ==> You even could hardcode your first param (contentID in here)
// long pageIndex ==> SET your index to 0 ==> first indexpage starts at 0 and not 1 ==> if you set this to 1 and the Pagesize = 100  and you have only 99 childeren you wil wil get null because we are requesting the second page
// int pageSize ==> We need max 10 childeren
// out long totalChildren
// IQuery<IContent> filter = null ==> not used
// Ordering ordering = null ==> not used
IEnumerable<IContent> children = Services.ContentService.GetPagedChildren(contentId, 0, 10, out totalChildren);


问:
onResume() and onPause() is being called on the first launch
I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.

I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.

I am including the simplest code i am using

ActivityClass.java

```<code>public class ActivityClass extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("TEST : onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lockscreen);
        ButterKnife.bind(this);

    }

    @Override
    protected void onPause() {
        System.out.println("TEST : onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        System.out.println("TEST : onDestroy");
        super.onDestroy();
    }

}
</code>```

Service class

```<code>public class OverlayService extends Service {

    Context context;
    public static final String TAG = OverlayService.class.getSimpleName();

    public OverlayService(Context applicationContext) {
        super();
        context = applicationContext;
    }

    public OverlayService() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "[onCreateService]");
        super.onStartCommand(intent, flags, startId);
        KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        if(myKM.inKeyguardRestrictedInputMode()) {
            //it is locked
            showOverlayActivity();
        } else {
            //it is not locked
        }
        registerOverlayReceiver();
        context = this;
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterOverlayReceiver();
        Log.i("EXIT", "ondestroy!");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void unregisterOverlayReceiver() {
        if (overlayReceiver != null) {
            unregisterReceiver(overlayReceiver);
        }
    }

    private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";

    private void registerOverlayReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ACTION_DEBUG);
        registerReceiver(overlayReceiver, filter);
    }

    private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "[onReceive]" + action);
            if (action.equals(Intent.ACTION_SCREEN_ON)) {
                // ACTON_SCREEN_ON
                showOverlayActivity();
            } else if (action.equals(ACTION_DEBUG)) {
                showOverlayActivity();
            }
        }
    };

    private void showOverlayActivity() {
        Intent intent = new Intent();
        intent.setClass(this, ActivityClass.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

}
</code>```

Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?

答: About service class, you should call registerReceiver() or initialize variables in onCreate instead of onStartCommand because onCreate is only called once at the first time of starting service and onStartCommand will be called every time you want to trigger an action to the service by calling startService(Intent).

Body:
I am having an activity and on Launching the activity through Intent from one of my service, onCreate(), onPause() and onResume() is called.

I am not very sure where i am doing wrong, i have removed all the code, just the basic function codes are available, and also i have removed all the codes which were opening that particular activity, still the behaviour is same.

I am including the simplest code i am using

ActivityClass.java

public class ActivityClass extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.out.println("TEST : onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lockscreen);
        ButterKnife.bind(this);

    }

    @Override
    protected void onPause() {
        System.out.println("TEST : onPause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        System.out.println("TEST : onDestroy");
        super.onDestroy();
    }

}

Service class

public class OverlayService extends Service {

    Context context;
    public static final String TAG = OverlayService.class.getSimpleName();

    public OverlayService(Context applicationContext) {
        super();
        context = applicationContext;
    }

    public OverlayService() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "[onCreateService]");
        super.onStartCommand(intent, flags, startId);
        KeyguardManager myKM = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
        if(myKM.inKeyguardRestrictedInputMode()) {
            //it is locked
            showOverlayActivity();
        } else {
            //it is not locked
        }
        registerOverlayReceiver();
        context = this;
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterOverlayReceiver();
        Log.i("EXIT", "ondestroy!");
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Intent broadcastIntent = new Intent("ac.in.ActivityRecognition.RestartSensor");
        sendBroadcast(broadcastIntent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void unregisterOverlayReceiver() {
        if (overlayReceiver != null) {
            unregisterReceiver(overlayReceiver);
        }
    }

    private static final String ACTION_DEBUG = "kunal.lockoverlay.action.DEBUG";

    private void registerOverlayReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(ACTION_DEBUG);
        registerReceiver(overlayReceiver, filter);
    }

    private BroadcastReceiver overlayReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "[onReceive]" + action);
            if (action.equals(Intent.ACTION_SCREEN_ON)) {
                // ACTON_SCREEN_ON
                showOverlayActivity();
            } else if (action.equals(ACTION_DEBUG)) {
                showOverlayActivity();
            }
        }
    };

    private void showOverlayActivity() {
        Intent intent = new Intent();
        intent.setClass(this, ActivityClass.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

}

Can someone point some of the possible reasons for this behaviour or could identify where i am doing wrong?


问:
Encrypt password was shows Chinese language
I want to change a password, in a stored procedure from NVARCHAR into its MD5 hash, but after executing it the password hash is shown as Chinese characters. Why?

I am using this code EncryptByPassPhrase('MD5', @Password) but it still shows the result as Chinese characters

```<code>BEGIN

DECLARE @HashThis nvarchar(4000);
SELECT @HashThis = CONVERT(nvarchar(4000),@Password);

Insert Into tblUserLogin (ICNumber,Email,[Password],CreateBy,CreateDate,LastUpdateBy,LastUpdateDate)
Values (@ICNumber,@Email,HASHBYTES('SHA1',@HashThis),@FirstName,GETDATE(),@FirstName,GETDATE())

END
</code>```

The Expected Result should like this:

0x01000000E6A0E10AF0144E38670D9B8E92E6E22787F9CD27B467E253

But the Actual Result is:

詫鸺쇬⒍맣㮶뎨뗮兴サ

答:
This is because you're storing the result of calling the HASHBYTES function into an NVARCHAR field when you should store it in a VARBINARY.

Here's a worked example that shows this:

```<code>CREATE TABLE UserHash
(
    [Password_NVARCHAR] NVARCHAR(200),
    [Password_VARBINARY] VARBINARY(20)
)

DECLARE @Password NVARCHAR(20) = 'Abcdefghijklmnop'
DECLARE @HashThis nvarchar(4000);
SELECT @HashThis = CONVERT(nvarchar(4000),@Password);

INSERT
INTO    [UserHash]
        (
            Password_NVARCHAR,
            Password_VARBINARY
        )
SELECT  HASHBYTES('SHA1',@HashThis),
        HASHBYTES('SHA1',@HashThis)

SELECT  *
FROM    [UserHash]
</code>```

Here's the result of the last statement in that code:

As you can see, the NVARCHAR version shows something you're not expecting which is because the result of calling HASHBYTES is being interpreted as text, rather than as a series of bytes.

If you look at the length of the text in the Password_NVARCHAR field (e.g. by executing SELECT LEN(Password_NVARCHAR) FROM [UserHash]) you'll see this returned as 10. As NVARCHAR stores text using 2 bytes per character, your 20 byte hash is being displayed as a 10 character string.

NOTE: In the script above I've sized Password_VARBINARY to fit an SHA1 result, as per the linked documentation for HASHBYTES you should size the column according to the hashing algorithm being used:

The output conforms to the algorithm standard: 128 bits (16 bytes) for MD2, MD4, and MD5; 160 bits (20 bytes) for SHA and SHA1; 256 bits (32 bytes) for SHA2_256, and 512 bits (64 bytes) for SHA2_512

ASIDE: Don't store a password as a hash, use a Salted Hash.

Body:
I want to change a password, in a stored procedure from NVARCHAR into its MD5 hash, but after executing it the password hash is shown as Chinese characters. Why?

I am using this code EncryptByPassPhrase('MD5', @Password) but it still shows the result as Chinese characters

BEGIN

DECLARE @HashThis nvarchar(4000);
SELECT @HashThis = CONVERT(nvarchar(4000),@Password);

Insert Into tblUserLogin (ICNumber,Email,[Password],CreateBy,CreateDate,LastUpdateBy,LastUpdateDate)
Values (@ICNumber,@Email,HASHBYTES('SHA1',@HashThis),@FirstName,GETDATE(),@FirstName,GETDATE())

END

The Expected Result should like this:

0x01000000E6A0E10AF0144E38670D9B8E92E6E22787F9CD27B467E253

But the Actual Result is:

詫鸺쇬⒍맣㮶뎨뗮兴サ

Body:
This is because you're storing the result of calling the HASHBYTES function into an NVARCHAR field when you should store it in a VARBINARY.

Here's a worked example that shows this:

CREATE TABLE UserHash
(
    [Password_NVARCHAR] NVARCHAR(200),
    [Password_VARBINARY] VARBINARY(20)
)

DECLARE @Password NVARCHAR(20) = 'Abcdefghijklmnop'
DECLARE @HashThis nvarchar(4000);
SELECT @HashThis = CONVERT(nvarchar(4000),@Password);

INSERT
INTO    [UserHash]
        (
            Password_NVARCHAR,
            Password_VARBINARY
        )
SELECT  HASHBYTES('SHA1',@HashThis),
        HASHBYTES('SHA1',@HashThis)

SELECT  *
FROM    [UserHash]

Here's the result of the last statement in that code:

As you can see, the NVARCHAR version shows something you're not expecting which is because the result of calling HASHBYTES is being interpreted as text, rather than as a series of bytes.

If you look at the length of the text in the Password_NVARCHAR field (e.g. by executing SELECT LEN(Password_NVARCHAR) FROM [UserHash]) you'll see this returned as 10. As NVARCHAR stores text using 2 bytes per character, your 20 byte hash is being displayed as a 10 character string.

NOTE: In the script above I've sized Password_VARBINARY to fit an SHA1 result, as per the linked documentation for HASHBYTES you should size the column according to the hashing algorithm being used:

The output conforms to the algorithm standard: 128 bits (16 bytes) for MD2, MD4, and MD5; 160 bits (20 bytes) for SHA and SHA1; 256 bits (32 bytes) for SHA2_256, and 512 bits (64 bytes) for SHA2_512

ASIDE: Don't store a password as a hash, use a Salted Hash.


问:
Insert into multimap causes segfault
I am working on a project using multimaps inside of my own class, and I have run into a segfault. Here are the parts of my code relating to the issue. I would really appreciate some help. Thanks.

Here is database.h

```<code>#include <iostream>
#include <map>

using namespace std;

class database{
 public:
  database(); // start up the database
  int update(string,int); // update it
  bool is_word(string); //advises if the word is a word
  double prox_mean(string); // finds the average prox
 private:
  multimap<string,int> *data; // must be pointer
 protected:

};
</code>```

Here is the database.cpp

```<code>#include <iostream>
#include <string>
#include <map>
#include <utility>

#include "database.h"

using namespace std;

// start with the constructor
database::database()
{
  data = new multimap<string,int>; // allocates new space for the database
}

int database::update(string word,int prox)
{
  // add another instance of the word to the database
  cout << "test1"<<endl;
  data->insert( pair<string,int>(word,prox));
  cout << "test2" <<endl;
  // need to be able to tell if it is a word
  bool isWord = database::is_word(word);
  // find the average proximity
  double ave = database::prox_mean(word);

  // tells the gui to updata
  // gui::update(word,ave,isWord); // not finished yet

  return 0;
}
</code>```

Here is test.cpp

```<code>#include <iostream>
#include <string>
#include <map>

#include "database.h" //this is my file

using namespace std;

int main()
{
  // first test the constructor
  database * data;

  data->update("trail",3);
  data->update("mix",2);
  data->update("nut",7);
  data->update("and",8);
  data->update("trail",8);
  data->update("and",3);
  data->update("candy",8);

  //  cout<< (int) data->size()<<endl;

  return 0;

}
</code>```

Thanks very much. It compiles and runs up to cout << "test1" << endl; but segfaults on the next line.

Rusty

答:
You need to allocate your database before starting to insert data on it.

Change:

database *data;

to:

database *data = new database();

or:

database data;

in main().

EDIT: if you use the latter, change -> to . on the subsequent method calls. Otherwise, remember to delete your data object after using it.

Title: Insert into multimap causes segfault

Body:
I am working on a project using multimaps inside of my own class, and I have run into a segfault. Here are the parts of my code relating to the issue. I would really appreciate some help. Thanks.

Here is database.h

#include <iostream>
#include <map>

using namespace std;

class database{
 public:
  database(); // start up the database
  int update(string,int); // update it
  bool is_word(string); //advises if the word is a word
  double prox_mean(string); // finds the average prox
 private:
  multimap<string,int> *data; // must be pointer
 protected:

};

Here is the database.cpp

#include <iostream>
#include <string>
#include <map>
#include <utility>

#include "database.h"

using namespace std;

// start with the constructor
database::database()
{
  data = new multimap<string,int>; // allocates new space for the database
}

int database::update(string word,int prox)
{
  // add another instance of the word to the database
  cout << "test1"<<endl;
  data->insert( pair<string,int>(word,prox));
  cout << "test2" <<endl;
  // need to be able to tell if it is a word
  bool isWord = database::is_word(word);
  // find the average proximity
  double ave = database::prox_mean(word);

  // tells the gui to updata
  // gui::update(word,ave,isWord); // not finished yet

  return 0;
}

Here is test.cpp

#include <iostream>
#include <string>
#include <map>

#include "database.h" //this is my file

using namespace std;

int main()
{
  // first test the constructor
  database * data;

  data->update("trail",3);
  data->update("mix",2);
  data->update("nut",7);
  data->update("and",8);
  data->update("trail",8);
  data->update("and",3);
  data->update("candy",8);

  //  cout<< (int) data->size()<<endl;

  return 0;

}

Thanks very much. It compiles and runs up to cout << "test1" << endl; but segfaults on the next line.

Rusty


问:
Animating Contour Plot in Matplotlib with FuncAnimation
I have a simple animation I'm trying to make with MatPlotLib FuncAnimation and a contour plot. Here's what I'm trying so far:

```<code># Create Figure and Axes
figure, ax = plot.subplots()

# Draw new contour with new data from u
def animate(i):
    a = u[:, :, int(i)]
    CS = ax.contourf(x.flatten(), y.flatten(), a, colors=['blue', 'white'], levels=0)
    return CS,

# create animation using the animate() function
myAnimation = FuncAnimation(figure, animate, frames=np.arange(0.0, t, t), interval=10, blit=True)

figure.show()
</code>```

Where u[:, :, i] contains the new Z data I want to plot in my contour.

This works for the very first frame, but then I immediately get the error: AttributeError: 'QuadContourSet' object has no attribute 'get_zorder' from the line CS = ax.contourf(...) for every iteration after that. I do have a crude animation working which is shown below:

```<code>figure, ax = plot.subplots()
for i in range(0, t):
        a = u[:, :, i]
        CS = ax.contourf(x.flatten(), y.flatten(), a, colors=['blue', 'white'], levels=0)
        figure.show()
        sleep(0.01)
</code>```

but this implementation creates a new graph for each step and thus is not efficient which is why I'm looking at FuncAnimation. If anyone knows why my FuncAnimation isn't working or if theres another way to animate all my data on one graph I'd be grateful! I've tried plotting it all on one graph using clf(), pause(), and draw() as well but to no avail!

答:
Another option is to use ArtistAnimation. You can use celluloid (disclaimer: I wrote it), to easily capture plots and then animate them. It uses ArtistAnimation under the hood. The basic idea is that you capture the figure each time you want an image in your animation. Then when you ask celluloid to create the animation it can handle the rest.

Please keep in mind is that while this method may be fewer lines of code it can take much longer to run depending on the length of your animation. It has to keep all those plots in memory unlike FuncAnimation.

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

X, Y = np.meshgrid(np.linspace(0, 10, 100), np.linspace(0, 10, 100))
fig, ax = plt.subplots()
camera = Camera(fig)
for i in np.linspace(0, 2 * np.pi, 30, endpoint=False):
    ax.contourf(np.sin(X + i) + np.sin(Y - i))
    camera.snap()
anim = camera.animate()
anim.save('contours.mp4')
</code>```

Body:
I have a simple animation I'm trying to make with MatPlotLib FuncAnimation and a contour plot. Here's what I'm trying so far:

# Create Figure and Axes
figure, ax = plot.subplots()

# Draw new contour with new data from u
def animate(i):
    a = u[:, :, int(i)]
    CS = ax.contourf(x.flatten(), y.flatten(), a, colors=['blue', 'white'], levels=0)
    return CS,

# create animation using the animate() function
myAnimation = FuncAnimation(figure, animate, frames=np.arange(0.0, t, t), interval=10, blit=True)

figure.show()

Where u[:, :, i] contains the new Z data I want to plot in my contour.

This works for the very first frame, but then I immediately get the error: AttributeError: 'QuadContourSet' object has no attribute 'get_zorder' from the line CS = ax.contourf(...) for every iteration after that. I do have a crude animation working which is shown below:

figure, ax = plot.subplots()
for i in range(0, t):
        a = u[:, :, i]
        CS = ax.contourf(x.flatten(), y.flatten(), a, colors=['blue', 'white'], levels=0)
        figure.show()
        sleep(0.01)

but this implementation creates a new graph for each step and thus is not efficient which is why I'm looking at FuncAnimation. If anyone knows why my FuncAnimation isn't working or if theres another way to animate all my data on one graph I'd be grateful! I've tried plotting it all on one graph using clf(), pause(), and draw() as well but to no avail!

Body:
Another option is to use ArtistAnimation. You can use celluloid (disclaimer: I wrote it), to easily capture plots and then animate them. It uses ArtistAnimation under the hood. The basic idea is that you capture the figure each time you want an image in your animation. Then when you ask celluloid to create the animation it can handle the rest.

Please keep in mind is that while this method may be fewer lines of code it can take much longer to run depending on the length of your animation. It has to keep all those plots in memory unlike FuncAnimation.

import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera

X, Y = np.meshgrid(np.linspace(0, 10, 100), np.linspace(0, 10, 100))
fig, ax = plt.subplots()
camera = Camera(fig)
for i in np.linspace(0, 2 * np.pi, 30, endpoint=False):
    ax.contourf(np.sin(X + i) + np.sin(Y - i))
    camera.snap()
anim = camera.animate()
anim.save('contours.mp4')


问:
SSH logged in as different users on same host
I have 2 BitBucket accounts with different keys.
Here is my ~/.ssh/config

```<code>Host company.bitbucket.org
  HostName bitbucket.org
  User company
  IdentityFile ~/.ssh/company

Host personal.bitbucket.org
  HostName bitbucket.org
  User personal
  IdentityFile ~/.ssh/personal
</code>```

In my repos:

```<code>[remote "origin"]
    url = company@bitbucket.org:companyworkspace/project1.git
[remote "origin"]
    url = personal@bitbucket.org:personal/project2.git
</code>```

When I use git fetch on each repository, sometime it connects correct, sometime it returns Forbidden.

After debugging, I consider a weird thing.

```<code>$ ssh -T company@bitbucket.org
logged in as personal

$ ssh -T company@bitbucket.org
logged in as company

$ ssh -T company@bitbucket.org
logged in as personal

$ ssh -T somethingwrong@bitbucket.org
logged in as personal
</code>```

Could someone please explain why it is happening?

UPDATED:
I misunderstood that I configured ssh correctly, because I am still able to connect git well. The question is about weird behavior when git choose wrong key.
However finally, I considered the domain in .git/config must be same the Host in .ssh/config.

```<code>Host company.bitbucket // This line should be same git config [...@company.bitbucket:...]
      HostName bitbucket.org
      User company
      IdentityFile ~/.ssh/company
</code>```

答:
you need to edit your git config

```<code>[remote "origin"]
url = git@personal.bitbucket.org:personal/repo.git
</code>```

and for the other one replace the user and URL to Company.

at the end add this to your ssh config:

```<code>IdentitiesOnly=yes
</code>```

Body:
I have 2 BitBucket accounts with different keys.
Here is my ~/.ssh/config

Host company.bitbucket.org
  HostName bitbucket.org
  User company
  IdentityFile ~/.ssh/company

Host personal.bitbucket.org
  HostName bitbucket.org
  User personal
  IdentityFile ~/.ssh/personal

In my repos:

[remote "origin"]
    url = company@bitbucket.org:companyworkspace/project1.git
[remote "origin"]
    url = personal@bitbucket.org:personal/project2.git

When I use git fetch on each repository, sometime it connects correct, sometime it returns Forbidden.

After debugging, I consider a weird thing.

$ ssh -T company@bitbucket.org
logged in as personal

$ ssh -T company@bitbucket.org
logged in as company

$ ssh -T company@bitbucket.org
logged in as personal

$ ssh -T somethingwrong@bitbucket.org
logged in as personal

Could someone please explain why it is happening?

UPDATED:
I misunderstood that I configured ssh correctly, because I am still able to connect git well. The question is about weird behavior when git choose wrong key.
However finally, I considered the domain in .git/config must be same the Host in .ssh/config.

Host company.bitbucket // This line should be same git config [...@company.bitbucket:...]
      HostName bitbucket.org
      User company
      IdentityFile ~/.ssh/company

Body:
you need to edit your git config

[remote "origin"]
url = git@personal.bitbucket.org:personal/repo.git

and for the other one replace the user and URL to Company.

at the end add this to your ssh config:

IdentitiesOnly=yes


问:
Rstuido Crash after changing graphic setting and no will not reopen even after reinstalling
I found that plotly was not working in my version of r studio that I was running through a VDI, I was reading a forum post online and tried changing the rendering engine to 'Desktop OpenGL'. However, during restarting rstudio crashed, and no when I try to reopen it I just get the error 'RStudio has stopped working'.

I have tried uninstalling and reinstalling both RStudio and R but this has had no effect on the problem.

I have R version 3.5.3 and Rstudio 1.2.1335

Can anyone offer some advice on how to fix this?

答:
For anyone who runs into a similar problem as this, in order to reset the graphics settings, or any settings for that matter, you will need to delete the preferences folder.

On windows find this by via start --> Run and entering the command

```<code>%appdata%\RStudio
</code>```

Once you have deleted this (or moved it somewhere to back it up) you can open RStudio, which will automatically create a new preferences folder.

Full information can be found here

Body:
For anyone who runs into a similar problem as this, in order to reset the graphics settings, or any settings for that matter, you will need to delete the preferences folder.

On windows find this by via start --> Run and entering the command

%appdata%\RStudio

Once you have deleted this (or moved it somewhere to back it up) you can open RStudio, which will automatically create a new preferences folder.

Full information can be found here


问:
C# if directive
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

```<code>void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif
</code>```

答:
This is not possible. The if statement is executed at run time, but preprocessor directives like #IF are executed at compile time. You need to decide at compile time how to build the code, and somewhere in your project (say in the project's properties) or at the top of the source file, set CONDITION to whatever you need it to be for that given build.

If this really needs to be a runtime decision, then you need to include all the possible code paths and decide at runtime which one to take.

Title: C# if directive

Body:
Can I write in code to set the variable to true or false depending on a button I pressed? See example below.

If not, what other ways are there to achieve similar effects? I have already marked the codes for different modes using directives and only want developers to have the option of switching the modes, but now I wish to give the user the option of switching between the modes. The choice of the mode will only be given at the start of the program, and user is not allowed to switch the mode. To switch the mode, he can only restart the program again.

If cannot use directives, what is the fastest way can I use? (note: the statements are all around the solution)

In pseduocode of what I wish to achieve:

void button_click(...){
    if(!CONDITION)
        CONDITION = true;
    else
        CONDITION = false;
}

...
#if CONDITION
   //mode X with addtional steps
#endif


问:
Oracle Query [need subquery?]
assuming I have the following table:

```<code>NUM  TYPE  STAT   ERR
123   10      6    62
123   10      6    62
123   10      6    62
123   17      4     0
321   10      6    62
321   10      6    62
</code>```

I'm currently using the following query:

```<code>select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MIN(ERR) as ERROR
     , MIN(retry) as RETRY
 from TABLE_TB
where ERR=62
group by NUM
having count(ERR) > 1;
</code>```

The output will be:

```<code>NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
321   10      6    62      2
</code>```

That's ok, but what I need is that the query will output only NUM WITH ERR=62 but also with ERR = 0 excluding those who have ERR=62 but without ERR=0. Taking the first table as example, the query should output

```<code>NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
</code>```

This because NUM 123 has ERR=62 (3 occurrency) but also ERR=0. So, NUM 321 will be excluded because even if has ERR=62, it doesn't have ERR=0.

Hope is cliear :)

Thank you very much.
Lucas

答:
You need to first filter the table on err in (62, 0) and then find how many distinct error types you have (you want 2, since you have two error codes that you're interested in).

Once you have that information, you can then filter on rows where the err = 62 and the distinct count = 2 - e.g.:

```<code>WITH results as (select num,
                        type,
                        stat,
                        err,
                        retry,
                        count(distinct err) over (partition by num) num_err_types
                 from   table_tb
                 where  err in (62, 0))
select min(num) as nmbr,
       min(stat) as status,
       min(err) as ERROR,
       min(retry) as retry
from   results
where  err = 62
and    num_err_types = 2;
</code>```

I used the COUNT() analytic function to find the distinct count - this way, the value is added to each row, regardless of the error code, which is what allows us to filter on it in the final query.

Title: Oracle Query [need subquery?]

Body:
assuming I have the following table:

NUM  TYPE  STAT   ERR
123   10      6    62
123   10      6    62
123   10      6    62
123   17      4     0
321   10      6    62
321   10      6    62

I'm currently using the following query:

select MIN(NUM) as NUMBER
     , MIN(STAT) as STATUS
     , MIN(ERR) as ERROR
     , MIN(retry) as RETRY
 from TABLE_TB
where ERR=62
group by NUM
having count(ERR) > 1;

The output will be:

NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3
321   10      6    62      2

That's ok, but what I need is that the query will output only NUM WITH ERR=62 but also with ERR = 0 excluding those who have ERR=62 but without ERR=0. Taking the first table as example, the query should output

NUM  TYPE  STAT   ERR  RETRY
123   10      6    62      3

This because NUM 123 has ERR=62 (3 occurrency) but also ERR=0. So, NUM 321 will be excluded because even if has ERR=62, it doesn't have ERR=0.

Hope is cliear :)

Thank you very much.
Lucas

Body:
You need to first filter the table on err in (62, 0) and then find how many distinct error types you have (you want 2, since you have two error codes that you're interested in).

Once you have that information, you can then filter on rows where the err = 62 and the distinct count = 2 - e.g.:

WITH results as (select num,
                        type,
                        stat,
                        err,
                        retry,
                        count(distinct err) over (partition by num) num_err_types
                 from   table_tb
                 where  err in (62, 0))
select min(num) as nmbr,
       min(stat) as status,
       min(err) as ERROR,
       min(retry) as retry
from   results
where  err = 62
and    num_err_types = 2;

I used the COUNT() analytic function to find the distinct count - this way, the value is added to each row, regardless of the error code, which is what allows us to filter on it in the final query.


问:
Websphere Migration from was7 to was9
Planning to Migrate the Websphere from 7.0 to 9 and 8.5 to 9.
Can anyone help me getting the detailed Process

Migration here is "In place". (Migration will be done on the same servers, where the old Installation are in)

if at all any migration tools need to be used, please provide the clear info on them.
any documental references, or any video references for the questioner is appreciated.

OS used : RHEL
CUrrent version: WAS 7x and 8.5
Migrating to : WAS 9.0

答:
If you are in the planning phase, I'd strongly suggest you to consider migrating to WebSphere Liberty instead of traditional WAS v9. All these migration tools (toolkit for binaries, Eclipse migration toolkit) support both migration scenarios.

Choosing Liberty might be a bit more work at the beginning, but you will gain more deployment flexibility and speed up future development. Liberty is also much better fitted for any cloud/containers environments, as it is much more lightweight, so in the future, if you would like to move to containers, it would be much easier.

Check this tutorial Migrate traditional WebSphere apps to WebSphere Liberty on IBM Cloud Private by using Kubernetes, although it shows the steps to migrate to Liberty on ICP, beginning is the same - analyzing of the application whether they are fit for Liberty and migrating. If you don't have access to IBM Cloud or ICP, you can use stand alone version of the Transformation Advisor that was released recently - IBM Cloud Transformation Advisor.

Having said all that, some apps include old or proprietary traditional WebSphere APIs and in that case it may be easier and cheaper to temporary migrate them to WAS v9, and modernize in the future.

Title: Websphere Migration from was7 to was9