问:
Angular - karma Unit test cases
I m writing unit test cases for angular application. I m getting a typeerror which i m not able to figure out.

```<code>
<footer class="footer row no-gutters" *ngIf="showFilterResult()">
    Showing
    {{filteredData.length}} of {{data.length}} results
</footer>

</code>```

Component file:

```<code>
import {Component, OnInit} from '@angular/core';
import {AService} from '@core/services/search-helper.service';
import {BService} from '@core/http/firmware.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss'],
})
export class FooterComponent implements OnInit {
  private data = [];

  private filteredData = [];

  constructor(
    public a: AService,
    public b: BService,
    public router: Router) {}

  ngOnInit() {}

  showFilterResult() {
    if (
      this.router.url === '/currenturl' &&
      !this.b.hideFilter &&
      this.a.data &&
      this.a.data.length > 0
    ) {
      this.data = this.a.data;
      this.filteredData = this.b.searchResults;
      return true;
    }
    return false;
  }
}
</code>```

My default test cases:

```<code>import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {HttpClientTestingModule} from '@angular/common/http/testing';

import {RouterTestingModule} from '@angular/router/testing';
import {AService} from '@core/services/b.service';
import {BService} from '@core/http/b.service';
import {FooterComponent} from './footer.component';

describe('FooterComponent', () => {
  let component: FooterComponent;
  let fixture: ComponentFixture<FooterComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      declarations: [FooterComponent],
      providers: [AService, BService],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FooterComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

</code>```

I m getting the below error which i m nt able to correlate why its happening. Also which variable is undefined while creating a component

```<code>
  FooterComponent
    ✖ should create
      HeadlessChrome 77.0.3865 (Linux 0.0.0)
    TypeError: Cannot read property 'length' of undefined
    error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 3, rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 2, directChildFlags: 2, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'footer', attrs: [ Array ], template: null, componentProvider: null, componentView: null, componentRendererType: null, publicProviders: null({  }), allProviders: null({  }), handleEvent: Function }), provider: null, text: null, query: null, ngContent: null }), Object({ nodeIndex: 1, parent: Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 2, directChildFlags: 2, childMatchedQueries: 0,  ...
        at <Jasmine>
        at Object.eval [as updateRenderer] (ng:///DynamicTestModule/FooterComponent.ngfactory.js:12:38)
        at Object.debugUpdateRenderer [as updateRenderer] (node_modules/@angular/core/fesm2015/core.js:36090:1)
        at checkAndUpdateView (node_modules/@angular/core/fesm2015/core.js:35073:1)
        at callViewAction (node_modules/@angular/core/fesm2015/core.js:35433:1)
        at execEmbeddedViewsAction (node_modules/@angular/core/fesm2015/core.js:35390:1)
        at checkAndUpdateView (node_modules/@angular/core/fesm2015/core.js:35068:1)
        at callViewAction (node_modules/@angular/core/fesm2015/core.js:35433:1)
        at execComponentViewsAction (node_modules/@angular/core/fesm2015/core.js:35361:1)
        at checkAndUpdateView (node_modules/@angular/core/fesm2015/core.js:35074:1)
        at callWithDebugContext (node_modules/@angular/core/fesm2015/core.js:36407:1)

</code>```

Please help me to figure this out

答:
Try

```<code>class MockAService{
   data = []
}

class MockBService{
   searchResults = []
}

</code>```

then useClass as below:

```<code>  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      declarations: [FooterComponent],
      providers: [{provide: AService , useClass: MockAService}, {provide: BService, useClass: MockBService}],
    }).compileComponents();
  }));
</code>```

You can refer this article of mine for reference . A collection of such articles can be found at : https://medium.com/@shashankvivek.7/say-hi-to-jasmine-karma-in-angular-intro-d728d669a1c7

Title: Angular - karma Unit test cases

Body:
I m writing unit test cases for angular application. I m getting a typeerror which i m not able to figure out.

    Showing
    {{filteredData.length}} of {{data.length}} results

Component file:

import {Component, OnInit} from '@angular/core';
import {AService} from '@core/services/search-helper.service';
import {BService} from '@core/http/firmware.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-footer',
  templateUrl: './footer.component.html',
  styleUrls: ['./footer.component.scss'],
})
export class FooterComponent implements OnInit {
  private data = [];

  private filteredData = [];

  constructor(
    public a: AService,
    public b: BService,
    public router: Router) {}

  ngOnInit() {}

  showFilterResult() {
    if (
      this.router.url === '/currenturl' &&
      !this.b.hideFilter &&
      this.a.data &&
      this.a.data.length > 0
    ) {
      this.data = this.a.data;
      this.filteredData = this.b.searchResults;
      return true;
    }
    return false;
  }
}

My default test cases:

import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {HttpClientTestingModule} from '@angular/common/http/testing';

import {RouterTestingModule} from '@angular/router/testing';
import {AService} from '@core/services/b.service';
import {BService} from '@core/http/b.service';
import {FooterComponent} from './footer.component';

describe('FooterComponent', () => {
  let component: FooterComponent;
  let fixture: ComponentFixture<FooterComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      declarations: [FooterComponent],
      providers: [AService, BService],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FooterComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

I m getting the below error which i m nt able to correlate why its happening. Also which variable is undefined while creating a component

  FooterComponent
    ✖ should create
      HeadlessChrome 77.0.3865 (Linux 0.0.0)
    TypeError: Cannot read property 'length' of undefined
    error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 3, rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 2, directChildFlags: 2, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'footer', attrs: [ Array ], template: null, componentProvider: null, componentView: null, componentRendererType: null, publicProviders: null({  }), allProviders: null({  }), handleEvent: Function }), provider: null, text: null, query: null, ngContent: null }), Object({ nodeIndex: 1, parent: Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 2, directChildFlags: 2, childMatchedQueries: 0,  ...
        at <Jasmine>
        at Object.eval [as updateRenderer] (ng:///DynamicTestModule/FooterComponent.ngfactory.js:12:38)
        at Object.debugUpdateRenderer [as updateRenderer] (node_modules/@angular/core/fesm2015/core.js:36090:1)
        at checkAndUpdateView (node_modules/@angular/core/fesm2015/core.js:35073:1)
        at callViewAction (node_modules/@angular/core/fesm2015/core.js:35433:1)
        at execEmbeddedViewsAction (node_modules/@angular/core/fesm2015/core.js:35390:1)
        at checkAndUpdateView (node_modules/@angular/core/fesm2015/core.js:35068:1)
        at callViewAction (node_modules/@angular/core/fesm2015/core.js:35433:1)
        at execComponentViewsAction (node_modules/@angular/core/fesm2015/core.js:35361:1)
        at checkAndUpdateView (node_modules/@angular/core/fesm2015/core.js:35074:1)
        at callWithDebugContext (node_modules/@angular/core/fesm2015/core.js:36407:1)

Please help me to figure this out

Body:
Try

class MockAService{
   data = []
}

class MockBService{
   searchResults = []
}

then useClass as below:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule, HttpClientTestingModule],
      declarations: [FooterComponent],
      providers: [{provide: AService , useClass: MockAService}, {provide: BService, useClass: MockBService}],
    }).compileComponents();
  }));

You can refer this article of mine for reference . A collection of such articles can be found at : https://medium.com/@shashankvivek.7/say-hi-to-jasmine-karma-in-angular-intro-d728d669a1c7


来源: stackexchange

问:
WPF application is using a lot of GPU power
I am developing a WPF App. I have added few controls around 50+ including labels buttons grid panels etc.

But on some Views the GPU power spikes to around 40-50% in the Task Manager.

What could be the issue?

I read this article

But found no conclusion on what control could be causing this.

答:
I found the issue which was causing it. It was the DropShaddowEffect.

When I removed the DropShaddowEffect from the Grids and Borders my GPU went down to 5-6% from 40-50%. I call that a success

I also want to reference this solution from stackoverflow as the search parameters differ when searching for this kind of problem

ContentLicense: CC BY-SA 4.0


问:
Send and run multiple lines of Python to a visible running python/bpython/ipython interpreter process
I am running a full-screen tmux, split into two panes.  The left pane runs vim, where I edit Python files.  The right pane runs a Python interpreter.

I would like to be able to highlight multiple lines in vim (Shift+V), then using some shortcut key, send these lines to the running Python interpreter on the other pane.

Is there some vim plugin that does this?

This functionality is similar to that in Spyder, where you can highlight multiple lines, right-click, then send those lines to the active interpreter within Spyder.  I hesitate moving to Spyder because my muscle memory is already heavily invested in vim and tmux (keeping hands on the keyboard and all that).

答:
I don't use vim so I can't help you with that part of it, but if you can figure out how to make vim pipe its selection to a command, you can pipe it to something like:</p>

```<code>tmux loadb -bvim_copy - \; pasteb -bvim_copy -t'{right}' \; deleteb -bvim_copy'
</code>```

Body:
I don't use vim so I can't help you with that part of it, but if you can figure out how to make vim pipe its selection to a command, you can pipe it to something like:

tmux loadb -bvim_copy - \; pasteb -bvim_copy -t'{right}' \; deleteb -bvim_copy'


问:
How can we create Boolean-like object in JavaScript?
I want to create my Boolean-like object.
But I don't want to pollute Boolean.prototype.
So I created MyBool like

```<code>MyBool = function (x) {
  this.value = x;
  this.valueOf = function () { return x; };
  this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
  if (y.constructor !== MyBool) throw 'You cannot do that!';
  return this.value && y.value;
}
</code>```

and its instances

```<code>mytrue = new MyBool(true);
myfalse = new MyBool(false);
</code>```

But now, I noticed that

```<code>if (myfalse) {
  console.log ("myfalse is true!!!")
}
</code>```

prints that myfalse is true!!!

(Yet +myfalse (that is [[ToNumber]] conversion) comes to falsy, thanks to valueOf)

It's obvious because only following values are falsy in ECMAScript.

```<code>undefined, null, false, +0, -0, NaN, ''
</code>```

If Argument Type is Object, [[ToBoolean]] brings us true, in any case.
(see ECMA Type Conversion and Testing)

Is there any crafty way to create a falsy object?
It's ok if

```<code>myfalse.constructor is MyBool
(!! myfalse) is false
</code>```

Any cheat is welcome, including ECMA5's set/get/defineProperty or anything else.

Thanks in advance.

答:
I don't think this is currently possible, if you consider:</p>

```<code>var myBool = new Boolean(false);
if (myBool) {
    alert('Not false');
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to create my Boolean-like object.
But I don't want to pollute Boolean.prototype.
So I created MyBool like

MyBool = function (x) {
  this.value = x;
  this.valueOf = function () { return x; };
  this.toString = function () { return x; };
}
MyBool.prototype.and = function (y) {
  if (y.constructor !== MyBool) throw 'You cannot do that!';
  return this.value && y.value;
}

and its instances

mytrue = new MyBool(true);
myfalse = new MyBool(false);

But now, I noticed that

if (myfalse) {
  console.log ("myfalse is true!!!")
}

prints that myfalse is true!!!

(Yet +myfalse (that is [[ToNumber]] conversion) comes to falsy, thanks to valueOf)

It's obvious because only following values are falsy in ECMAScript.

undefined, null, false, +0, -0, NaN, ''

If Argument Type is Object, [[ToBoolean]] brings us true, in any case.
(see ECMA Type Conversion and Testing)

Is there any crafty way to create a falsy object?
It's ok if

myfalse.constructor is MyBool
(!! myfalse) is false

Any cheat is welcome, including ECMA5's set/get/defineProperty or anything else.

Thanks in advance.

Body:
I don't think this is currently possible, if you consider:

var myBool = new Boolean(false);
if (myBool) {
    alert('Not false');
}


问:
Blank screen in flutter app once application back from permission setting screen
I am working on app where i am asking for location permission.
If user click deny i am navigating user to setting screen so that they can manually turn on the location. But when i change the location permission from setting screen and click back and navigate to application blank screen appears and also i am not able to detect the change permission status.
Below is code :</p>

```<code>import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/widgets.dart';

    class LocationScreenState extends State<LocationScreen> with WidgetsBindingObserver{
      PermissionStatus _status;
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance
            .addPostFrameCallback((_) => afterFirstLayout(context));
      }
void afterFirstLayout(BuildContext context){
     PermissionHandler().requestPermissions([PermissionGroup.locationAlways]).then(__onStatusRequested);
  }

  void __onStatusRequested(Map<PermissionGroup, PermissionStatus> statuses){
    if(statuses != PermissionStatus.granted){
       PermissionHandler().openAppSettings();
    }else{
      _status = PermissionStatus.granted;

    }
  }
</code>```

答:
This is the code I have used. Take a look hope it will help</p>

```<code>void _askPermission() {
    PermissionHandler().requestPermissions(
        [PermissionGroup.locationWhenInUse]).then(_onStatusrequested);
  }

 void _onStatusrequested(Map<PermissionGroup, PermissionStatus> statuses) {
    final status = statuses[PermissionGroup.locationWhenInUse];
    if (status == PermissionStatus.neverAskAgain) {
      // openSettingsDialog();
      setState(() {
        isPermissionIgnored = true;
      });
      _updateStatus(_status);
    } else if (status == PermissionStatus.denied) {
      setState(() {
        isPermissionIgnored = false;
      });

      _updateStatus(status);
    } else if (status == PermissionStatus.granted) {
      setState(() {
        isPermissionIgnored = false;
      });

      _updateStatus(status);
    }
  }
void _updateStatus(PermissionStatus status) {
if (status != _status) {
  _status = status;
  print(_status);
}
print(status);
}
</code>```

Body:
I am working on app where i am asking for location permission.
If user click deny i am navigating user to setting screen so that they can manually turn on the location. But when i change the location permission from setting screen and click back and navigate to application blank screen appears and also i am not able to detect the change permission status.
Below is code :

import 'package:permission_handler/permission_handler.dart';
import 'package:flutter/widgets.dart';

    class LocationScreenState extends State<LocationScreen> with WidgetsBindingObserver{
      PermissionStatus _status;
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance
            .addPostFrameCallback((_) => afterFirstLayout(context));
      }
void afterFirstLayout(BuildContext context){
     PermissionHandler().requestPermissions([PermissionGroup.locationAlways]).then(__onStatusRequested);
  }

  void __onStatusRequested(Map<PermissionGroup, PermissionStatus> statuses){
    if(statuses != PermissionStatus.granted){
       PermissionHandler().openAppSettings();
    }else{
      _status = PermissionStatus.granted;

    }
  }

Body:
This is the code I have used. Take a look hope it will help

void _askPermission() {
    PermissionHandler().requestPermissions(
        [PermissionGroup.locationWhenInUse]).then(_onStatusrequested);
  }

 void _onStatusrequested(Map<PermissionGroup, PermissionStatus> statuses) {
    final status = statuses[PermissionGroup.locationWhenInUse];
    if (status == PermissionStatus.neverAskAgain) {
      // openSettingsDialog();
      setState(() {
        isPermissionIgnored = true;
      });
      _updateStatus(_status);
    } else if (status == PermissionStatus.denied) {
      setState(() {
        isPermissionIgnored = false;
      });

      _updateStatus(status);
    } else if (status == PermissionStatus.granted) {
      setState(() {
        isPermissionIgnored = false;
      });

      _updateStatus(status);
    }
  }
void _updateStatus(PermissionStatus status) {
if (status != _status) {
  _status = status;
  print(_status);
}
print(status);
}


问:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY
I am trying to parse the incoming Json (given below) to Java object using Gson. The Json request seems to be a valid one, but I am getting the following exception while parsing it.

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 5 column 19 path $.metadata.
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) ~[gson-2.8.5.jar:?]
        at com.google.gson.Gson.fromJson(Gson.java:927) ~[gson-2.8.5.jar:?]
</code>```

Incoming Json request :

```<code>{
    "metadata": {
        "salesId": "123",
        "promoCode": "2010",
        "items": [
            {
                "0": {
                    "productCode": "1234",
                    "total": 169900
                },
                "1": {
                    "productCode": "4567",
                    "total": 19900
                }
            }
        ]
    }
}
</code>```

Parsing logic :

```<code>protected <T extends GenericModel> Optional<T> convertFromJson(final String json, final Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        return Optional.of(new Gson().fromJson(json, clazz));
    }
</code>```

Java class :

```<code>public class Metadata {
    private String salesId;
    private String promoCode;
    private ArrayList<Object> items = new ArrayList<Object>();

    public String getSalesId() {
        return salesId;
    }

    public void setSalesId(String salesId) {
        this.salesId = salesId;
    }

    public String getPromoCode() {
        return promoCode;
    }

    public void setPromoCode(String promoCode) {
        this.promoCode = promoCode;
    }

    public ArrayList<Object> getItems() {
        return items;
    }

    public void setItems(ArrayList<Object> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "salesId=" + getSalesId() +
                "promoCode=" + getPromoCode() +
                "items=" + getItems() +
                '}';
    }
}
</code>```

Please note that Metadata.java is an inner class.

Have been trying to resolve the issue, but no luck. Could anyone let me know how to solve it? TIA.

答:
As your json has all data in metadata attribute, I created a new POJO having metadata field.

class ParentMetadata {
    private Metadata metadata;
    // getters and setters
}
```

<p>And then parsed json to POJO using below code:</p>

<pre class="lang-java prettyprint-override"><code>ParentMetadata parentMetadata = new Gson().fromJson(jsonStr, ParentMetadata.class);
</code>```

This works fine for me.

Also, as items is of type ArrayList<Object>, during debugging I could see items are deserialized as List of LinkedTreeMap.

Body:
I am trying to parse the incoming Json (given below) to Java object using Gson. The Json request seems to be a valid one, but I am getting the following exception while parsing it.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 5 column 19 path $.metadata.
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) ~[gson-2.8.5.jar:?]
        at com.google.gson.Gson.fromJson(Gson.java:927) ~[gson-2.8.5.jar:?]

Incoming Json request :

{
    "metadata": {
        "salesId": "123",
        "promoCode": "2010",
        "items": [
            {
                "0": {
                    "productCode": "1234",
                    "total": 169900
                },
                "1": {
                    "productCode": "4567",
                    "total": 19900
                }
            }
        ]
    }
}

Parsing logic :

protected <T extends GenericModel> Optional<T> convertFromJson(final String json, final Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        return Optional.of(new Gson().fromJson(json, clazz));
    }

Java class :

public class Metadata {
    private String salesId;
    private String promoCode;
    private ArrayList<Object> items = new ArrayList<Object>();

    public String getSalesId() {
        return salesId;
    }

    public void setSalesId(String salesId) {
        this.salesId = salesId;
    }

    public String getPromoCode() {
        return promoCode;
    }

    public void setPromoCode(String promoCode) {
        this.promoCode = promoCode;
    }

    public ArrayList<Object> getItems() {
        return items;
    }

    public void setItems(ArrayList<Object> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "salesId=" + getSalesId() +
                "promoCode=" + getPromoCode() +
                "items=" + getItems() +
                '}';
    }
}

Please note that Metadata.java is an inner class.

Have been trying to resolve the issue, but no luck. Could anyone let me know how to solve it? TIA.

Body:
As your json has all data in metadata attribute, I created a new POJO having metadata field.

class ParentMetadata {
    private Metadata metadata;
    // getters and setters
}

And then parsed json to POJO using below code:

ParentMetadata parentMetadata = new Gson().fromJson(jsonStr, ParentMetadata.class);

This works fine for me.

Also, as items is of type ArrayList<Object>, during debugging I could see items are deserialized as List of LinkedTreeMap.


问:
Why I am getting SAXNotRecognizedException while setting isSupportingExternalEntities?
I am getting SAXNotRecognizedException, while trying to set the property of 'isSupportingExternalEntities' in Java 8

```<code>final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
sf.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
</code>```

Exception:

org.xml.sax.SAXNotRecognizedException: Property 'javax.xml.stream.isSupportingExternalEntities' is not recognized.

答:
I guess you use the wrong property for SchemeFactory. According to OWASP docs you should use the following code</p>

```<code>SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
Schema schema = factory.newSchema(Source);
</code>```

Body:
I am getting SAXNotRecognizedException, while trying to set the property of 'isSupportingExternalEntities' in Java 8

final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
sf.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);

Exception:

org.xml.sax.SAXNotRecognizedException: Property 'javax.xml.stream.isSupportingExternalEntities' is not recognized.

Body:
I guess you use the wrong property for SchemeFactory. According to OWASP docs you should use the following code

SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
Schema schema = factory.newSchema(Source);


问:
Is there a way to find a string in a list and print just the list element associated with that string?
I am working on an Employee Management System and would like my user to search for an employee by SSN. Once the employee is found, I'd like to print the list associated with that SSN. Eventually, I'd like to search for an employee by SSN and allow the user to edit the data in the fields as well. Right now, I can't figure out how to associate the SSN search to the list. I can find the SSN, but I don't know how to display it.  How do I do that?</p>

```<code>employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL." To find an employee, type: "FIND." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW ALL':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "FIND":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        if find_emp in employee_index:
</code>```

答:
Looks like you're reading in a list of employee indexes, and each employee index is a list of five elements, with the second of five being the SSN. So you could run through the list of 5-item-lists, checking the 2nd of the 5 for a match to the SSN.  So...

```<code>def match_the_ssn(list_of_lists, ssn):
    for item in list_of_lists:
        try:
            if item[1] == ssn:
                print(item)
                return item
        except:
            pass
    return
</code>```

Something along these lines.... Run through the list, looking at each sublist. For each sublist, check if sublist[1] is the ssn  you want.  If so, you've got the sublist right there to do with what you want.

Body:
I am working on an Employee Management System and would like my user to search for an employee by SSN. Once the employee is found, I'd like to print the list associated with that SSN. Eventually, I'd like to search for an employee by SSN and allow the user to edit the data in the fields as well. Right now, I can't figure out how to associate the SSN search to the list. I can find the SSN, but I don't know how to display it.  How do I do that?

employee_info = [ ]

while True: # While loop created to make the script constantly run
    counter = len(employee_info) # Counter created so that the user will know how many entries there are

    print('There are', '(', (int(counter)), ')', 'employees in the system.\n')

    add_new = input('Would you like to add a new employee to the system, find an employee\'s record by SSN, change an employee\'s information or view all employee entries in the system?\
    To add an employee, type: "ADD". To view all employees currently in the system, type: "VIEW ALL." To find an employee, type: "FIND." To change employee info, type: "CHANGE."\n'\
    ) #Added option to add an employee, find an employee by SSN, change information or to view all employees currently the system

    if add_new == 'ADD':
        while True: # Loop created to input employees with option to quit
            employee_index = [input('Employee Name\n'), input('Employee SSN\n'), \
            input('Employee Telephone Number ***Entered as (555)555-5555*** \n'), input('Employee Email\n'), input('Employee Salary ***Entered as $xxxx***\n')]
            employee_info.append(employee_index)
            more_employees = input('Would you like to add another employee? Y or N.\n')
            if more_employees == 'Y':
                continue
            elif more_employees == 'N':
                break

    elif add_new == 'VIEW ALL':
        for employee_index in employee_info:
            print('            -----------------', employee_index[0], '-----------------\n')
            print('SSN:', employee_index[1], '\n')
            print('Phone:', '(' + employee_index[2][0] + employee_index[2][1] + employee_index[2][2] + ')' + employee_index[2][3] + employee_index[2][4] + employee_index[2][
            5] + '-' + employee_index[2][6] + employee_index[2][7] + employee_index[2][8] + employee_index[2][9], '\n')
            print('Email:', employee_index[3], '\n')
            print('Salary:', '$' + str(employee_index[4]), '\n')
            print('            ----------------------------------------------------')

    elif add_new == "FIND":
        find_emp = input('Please enter the employee SSN in the following format: 333221111.\n')
        if find_emp in employee_index:

Body:
Looks like you're reading in a list of employee indexes, and each employee index is a list of five elements, with the second of five being the SSN. So you could run through the list of 5-item-lists, checking the 2nd of the 5 for a match to the SSN.  So...

def match_the_ssn(list_of_lists, ssn):
    for item in list_of_lists:
        try:
            if item[1] == ssn:
                print(item)
                return item
        except:
            pass
    return

Something along these lines.... Run through the list, looking at each sublist. For each sublist, check if sublist[1] is the ssn  you want.  If so, you've got the sublist right there to do with what you want.


问:
How to make firebase storage reference to a certain bucket?

I create a new bucket in a region near from my users location (asia-southeast1) so hopefully it will fetch the image faster in the client side, I want to upload image and also to download image from that new bucket.

but I don't how to make reference to that new bucket. usually I use the code below in Android to create reference for default bucket

```<code>val ref = FirebaseStorage.getInstance().reference.child("profilePicture")
</code>```

so how to download and upload image from that bucket? I assume that I have to make some change when creating the reference, but I don't know how to pointing the reference to that new bucket

答:
In the API documentation for FirebaseStorage, it says:

FirebaseStorage is a service that supports uploading and downloading
  large objects to Google Cloud Storage. Pass a custom instance of
  FirebaseApp to getInstance(FirebaseApp) which will initialize it with
  a storage location (bucket) specified via setStorageBucket(String).

Otherwise, if you call getReference() without a FirebaseApp, the
  FirebaseStorage instance will initialize with the default FirebaseApp
  obtainable from getInstance(). The storage location in this case will
  come the JSON configuration file downloaded from the web.

The bolded text is what you will need to do.  Initialize a new FirebaseApp instance using a FirebaseOptions object using a builder where you called setStorageBucket() with the name of the bucket you want to use.

Then, when you call FirebaseStorage.getInstance(app), passing that FirebaseApp instance, your references will come from that bucket.

Body:
I create a new bucket in a region near from my users location (asia-southeast1) so hopefully it will fetch the image faster in the client side, I want to upload image and also to download image from that new bucket.

but I don't how to make reference to that new bucket. usually I use the code below in Android to create reference for default bucket

val ref = FirebaseStorage.getInstance().reference.child("profilePicture")

so how to download and upload image from that bucket? I assume that I have to make some change when creating the reference, but I don't know how to pointing the reference to that new bucket


问:
Catastrophic Failure EXCEL VBA - error '-2147418113 (8000ffff)'
I am struggling to find relevant information on the

'run-time error '-2147418113 (8000ffff)' - Catastrophic Failure'

I am experiencing.

```<code>Sub GenerateAIA_Click()
Dim SQL_query, SQL_syntax, DB_path, setting_conn As String
Dim conn As New ADODB.Connection
Dim query_rslt As New ADODB.Recordset

Dim mth, mth_yr As Variant
Dim dt As Date
Dim i, bol As Integer
Dim temp1, temp2 As Variant

dt = Sheets("Main").Range("C4")
mth_yr = MonthName(Month(Sheets("Main").Range("I12")), False) & " " & Year(Sheets("Main").Range("I12"))

ThisWorkbook.Sheets("AIA").Select

DB_path = ThisWorkbook.FullName 'Refering the same workbook as Data Source
setting_conn = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DB_path & ";HDR=Yes';"
conn.Open setting_conn
SQL_syntax = "SELECT * FROM [Setup$]"   'Your SQL Statement (Table Name= Sheet Name=[Sheet1$])
query_rslt.Open SQL_syntax, conn
</code>```

I have also noticed that this error is shown on the line

```<code>conn.Open setting_conn
</code>```

I use excel 2016 and also my file format .xlsm

Anyone have idea why is this happening?

答:
It seems your connection string has a problem.
Here's how I got it to work:

(First make sure to add a reference to the Microsoft Active-X Data Objects Library)

```<code>Sub test()
  Dim conn As New ADODB.Connection
  Dim rs As New ADODB.Recordset

  conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\PC\test.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=NO"";"
  conn.Open

  rs.Open "SELECT * FROM [Sheet1$]", conn

  If Not rs.EOF Then
    MsgBox rs(0) ' display the value of the first field in the first row
  Else
    MsgBox "No records found."
  End If

  rs.Close
  conn.Close

End Sub
</code>```

So take my example, change the filename to your XLSM file, and the sheet name to your sheet name (with a $ added to the end of it)

If your sheet has header names in the first now, use HDR=Yes, and if not, HDR=No

Body:
I am struggling to find relevant information on the

'run-time error '-2147418113 (8000ffff)' - Catastrophic Failure'

I am experiencing.

Sub GenerateAIA_Click()
Dim SQL_query, SQL_syntax, DB_path, setting_conn As String
Dim conn As New ADODB.Connection
Dim query_rslt As New ADODB.Recordset

Dim mth, mth_yr As Variant
Dim dt As Date
Dim i, bol As Integer
Dim temp1, temp2 As Variant

dt = Sheets("Main").Range("C4")
mth_yr = MonthName(Month(Sheets("Main").Range("I12")), False) & " " & Year(Sheets("Main").Range("I12"))

ThisWorkbook.Sheets("AIA").Select

DB_path = ThisWorkbook.FullName 'Refering the same workbook as Data Source
setting_conn = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DB_path & ";HDR=Yes';"
conn.Open setting_conn
SQL_syntax = "SELECT * FROM [Setup$]"   'Your SQL Statement (Table Name= Sheet Name=[Sheet1$])
query_rslt.Open SQL_syntax, conn

I have also noticed that this error is shown on the line

conn.Open setting_conn

I use excel 2016 and also my file format .xlsm

Anyone have idea why is this happening?

Body:
It seems your connection string has a problem.
Here's how I got it to work:

(First make sure to add a reference to the Microsoft Active-X Data Objects Library)

Sub test()
  Dim conn As New ADODB.Connection
  Dim rs As New ADODB.Recordset

  conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\PC\test.xlsm;Extended Properties=""Excel 12.0 Macro;HDR=NO"";"
  conn.Open

  rs.Open "SELECT * FROM [Sheet1$]", conn

  If Not rs.EOF Then
    MsgBox rs(0) ' display the value of the first field in the first row
  Else
    MsgBox "No records found."
  End If

  rs.Close
  conn.Close

End Sub

So take my example, change the filename to your XLSM file, and the sheet name to your sheet name (with a $ added to the end of it)

If your sheet has header names in the first now, use HDR=Yes, and if not, HDR=No


问:
In WaitForSingleObject, is timeout=INFINITE the same as timeout=-1?
I'm working with some Visual Basic for Applications (VB 6.3) code written by someone else, and they've written:

```<code>WaitForSingleObject SEI.hProcess, -1
</code>```

The process this appears in is supposed to return some data in a text box; sometimes it fails to return anything, and I think it's because of this, possibly because it's its timing out. Is that code the same as:

```<code>WaitForSingleObject SEI.hProcess, INFINITE
</code>```

???

Thanks for your help.

答:
So basically your question translates to whether WaitForSingleObject SEI.hProcess, -1 and WaitForSingleObject SEI.hProcess, INFINITE are same or not?

As Reed's answer says, yes, they are same and so is WaitForSingleObject SEI.hProcess, -3999. Basically any negative number will wrap around and become the maximum unsigned int available which is coincidentally the value of INFINITE.

Now, does it mean you should use either of these. NO. You should always use the documented version otherwise C++ is very famous to have undefined behaviour for undocumented features.

Body:
I'm working with some Visual Basic for Applications (VB 6.3) code written by someone else, and they've written:

WaitForSingleObject SEI.hProcess, -1

The process this appears in is supposed to return some data in a text box; sometimes it fails to return anything, and I think it's because of this, possibly because it's its timing out. Is that code the same as:

WaitForSingleObject SEI.hProcess, INFINITE

???

Thanks for your help.


问:
Auto select value of dropdown
i have an dropdown like this:

```<code><select id="cbvms" name="cbvms" class="SelectList">
        <?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected=\"".$value."\">".$value."</option>";
            else
                //echo "<option value=\"".$key."\">".$value."</option>";
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
    and in my database i have an option value like this ....
</code>```

VM name:

```<code> 172.125.4.186
 172.125.4.101
 172.125.4.194
 172.125.4.126
 172.125.4.167
 172.125.4.102
 172.125.4.171
 172.125.4.118
 172.125.4.169
 Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101
 salman
 saman
 172.125.4.198
 172.125.4.200
 172.125.4.189
 172.125.4.191
</code>```

now i want when some one select any option value as shown as above my dropdown autosize

for example: when user select 172.125.4.169 then its fit on the size of dropdown, or when the user select "Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101" then its also fit on the dropdown.

Right now if the VM name is long, the drop down field for Select VM goes out of range....

答:
u need to use jquery for this

```<code> if ($.browser.msie) $('select.SelectList')
                    .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
                    .bind('click', function() { $(this).toggleClass('clicked'); })
                    .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
                    .bind('blur', function() { $(this).removeClass('expand clicked'); });
</code>```

CSS:

```<code> select {
                width: 120px; /* Or whatever width you want. */
            }
            select.expand {
                width: auto;
            }
</code>```

All you need to do is to add the class SelectList to the dropdown element(s) in question.

```<code><select id="cbvms" name="cbvms" class="SelectList">
<?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected>".$value."</option>";
            else
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
</code>```

Title: Auto select value of dropdown

Body:
i have an dropdown like this:

<select id="cbvms" name="cbvms" class="SelectList">
        <?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected=\"".$value."\">".$value."</option>";
            else
                //echo "<option value=\"".$key."\">".$value."</option>";
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>
    and in my database i have an option value like this ....

VM name:

 172.125.4.186
 172.125.4.101
 172.125.4.194
 172.125.4.126
 172.125.4.167
 172.125.4.102
 172.125.4.171
 172.125.4.118
 172.125.4.169
 Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101
 salman
 saman
 172.125.4.198
 172.125.4.200
 172.125.4.189
 172.125.4.191

now i want when some one select any option value as shown as above my dropdown autosize

for example: when user select 172.125.4.169 then its fit on the size of dropdown, or when the user select "Microsoft Windows Server 2003 Enterprise x64 Edition 5.2.3790 xen - 121 - centos 5.4 - ip 101" then its also fit on the dropdown.

Right now if the VM name is long, the drop down field for Select VM goes out of range....

Body:
u need to use jquery for this

 if ($.browser.msie) $('select.SelectList')
                    .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); })
                    .bind('click', function() { $(this).toggleClass('clicked'); })
                    .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }})
                    .bind('blur', function() { $(this).removeClass('expand clicked'); });

CSS:

 select {
                width: 120px; /* Or whatever width you want. */
            }
            select.expand {
                width: auto;
            }

All you need to do is to add the class SelectList to the dropdown element(s) in question.

<select id="cbvms" name="cbvms" class="SelectList">
<?php
        foreach($vm_array as $key => $value)
        {
            if(strcmp($vmguid,$key) == 0)
                echo "<option value=\"".$key."\" selected>".$value."</option>";
            else
                echo "<option value=\"".$key."\" title=\"".$value."\">".$value."</option>";
        }
        ?>
        </select>


问:
CSS Responsive image "shows up fully" on-screen no-stretch background with precise text placement

Testing

```

I'm trying to have an image fully show up based on the size of a screen, and to have text ("Testing" in the textbox class) show up in a precise designated area in the image, as shown above.

Trying to get the above to work with this codepen, but I am defeated to admit that after an hour of fiddling with css, I am nowhere close.

It is pretty frustrating that css doesn't seem to work as expected, where the image doesn't seem to want to nest to full height etc.

答:
Backgorund Image

you have to make background-size:cover instead of 100% and make height:100vh to make it visible.

Body:
Testing

I'm trying to have an image fully show up based on the size of a screen, and to have text ("Testing" in the textbox class) show up in a precise designated area in the image, as shown above.

Trying to get the above to work with this codepen, but I am defeated to admit that after an hour of fiddling with css, I am nowhere close.

It is pretty frustrating that css doesn't seem to work as expected, where the image doesn't seem to want to nest to full height etc.


问:
ES6 in JShint - .jshintrc has esversion, but still getting warning (using atom)
I am using atom, and I've tried several different jshint packages and they all give a warning which says

```<code>"template literal syntax' is only available in ES6 (use 'esversion: 6')"
</code>```

I created a top level .jshintrc file (at root), and added the following json:

```<code>{
  "esversion":6
}
</code>```

However, it is still throwing the same error. Any ideas how to resolve. I've included the link to the JSHint options page. I'd like to start playing around with ES6 syntax, but would prefer not to have extra warnings.

Thanks SO community!

答:
The config file in which you have enabled es6 should be enabled through your IDE;
eg:for Intellij there's a clear option for adding config files.JSHint for Intellij</p>

Body:
I am using atom, and I've tried several different jshint packages and they all give a warning which says

"template literal syntax' is only available in ES6 (use 'esversion: 6')"

I created a top level .jshintrc file (at root), and added the following json:

{
  "esversion":6
}

However, it is still throwing the same error. Any ideas how to resolve. I've included the link to the JSHint options page. I'd like to start playing around with ES6 syntax, but would prefer not to have extra warnings.

Thanks SO community!


问:
Python nested for loops - inner loop iterator type change
In this function, exs is assumed to be a list of lists of floats. It represents the list of all my training examples, each of which is a list (length num_vars) of floats, representing perceptron input. target is assumed to be a list (length num_vars) of floats, representing the target function's coefficients.

```<code>def gradDesc(exs, target, num_vars, n=0.5, its=256):
    import random
    weights = []
    # Create and initialize delWeights to 0. Make its size num_vars.
    delWeights = [0.0]*num_vars

    # Initializes the weights to a real number in [-1,1]. Also makes weights
    # contain num_vars entries.
    for i in range(num_vars):
        weights.append(random.uniform(-1,1))

    # To make the printouts look nicer
    print("Iteration\tError")
    print("---------\t-----")

    for i in range(its):

        # Reset delWeights to 0
        for j in range(num_vars):
            delWeights[j] = 0

        for e in exs:

            # Plug e into the current hypothesis and get the output.
            output = test_hypo(weights, e, num_vars)

            print("delWeights: ", delWeights)
            for dw in delWeights:
                print("type(dw): ", type(dw))
                delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]

        for w in weights:
            weights[w] = weights[w] + delWeights[dw]

        # Print out the error every tenth iteration
        if i % 10 == 0:
            print(i + "\t" + train_err(exs, target, weights, num_vars))

    # Print out the final hypothesis
    print(i + "\t" + train_err(exs, target, weights, num_vars))

    return weights
</code>```

The problem is, when I try to run this given the (finite) test input

```<code>trainers =
[[1, 2.7902232015508766, -4.624194135789617],
[1, -7.964359679418456, 2.1940274082288624],
[1, 8.445941538761794, -8.86567924774781],
... other sub-lists following this same format ...]
</code>```

and

```<code>target = [-2, 1, 2]
</code>```

I get this odd output:

```<code>gradDesc(trainers, target, num_vars)
Iteration       Error
---------       -----
delWeights:  [0, 0, 0]
type(dw):  <class 'int'>
type(dw):  <class 'int'>
type(dw):  <class 'int'>
delWeights:  [0.0, 0, 0]
type(dw):  <class 'float'>
Traceback (most recent call last):

  File "<ipython-input-19-97298b385113>", line 1, in <module>
    gradDesc(trainers, target, num_vars)

  File "C:/Users/Me/.spyder-py3/Machine Learning/gradDesc.py", line 107, in gradDesc
    delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]

TypeError: list indices must be integers or slices, not float
</code>```

So my question is: why is the type of dw changing from an int to a float on the second iteration through the for e in exs loop?

答:
Did you mean to loop through the indexes of delWeight using for i in range(len(delWeights)) instead of for dw in delWeights?

for dw in delWeights loops through all the values in delWeights, so the first iteration of your loop probably assigns a float to one of the delWeights indices in delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw].

Body:
In this function, exs is assumed to be a list of lists of floats. It represents the list of all my training examples, each of which is a list (length num_vars) of floats, representing perceptron input. target is assumed to be a list (length num_vars) of floats, representing the target function's coefficients.

def gradDesc(exs, target, num_vars, n=0.5, its=256):
    import random
    weights = []
    # Create and initialize delWeights to 0. Make its size num_vars.
    delWeights = [0.0]*num_vars

    # Initializes the weights to a real number in [-1,1]. Also makes weights
    # contain num_vars entries.
    for i in range(num_vars):
        weights.append(random.uniform(-1,1))

    # To make the printouts look nicer
    print("Iteration\tError")
    print("---------\t-----")

    for i in range(its):

        # Reset delWeights to 0
        for j in range(num_vars):
            delWeights[j] = 0

        for e in exs:

            # Plug e into the current hypothesis and get the output.
            output = test_hypo(weights, e, num_vars)

            print("delWeights: ", delWeights)
            for dw in delWeights:
                print("type(dw): ", type(dw))
                delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]

        for w in weights:
            weights[w] = weights[w] + delWeights[dw]

        # Print out the error every tenth iteration
        if i % 10 == 0:
            print(i + "\t" + train_err(exs, target, weights, num_vars))

    # Print out the final hypothesis
    print(i + "\t" + train_err(exs, target, weights, num_vars))

    return weights

The problem is, when I try to run this given the (finite) test input

trainers =
[[1, 2.7902232015508766, -4.624194135789617],
[1, -7.964359679418456, 2.1940274082288624],
[1, 8.445941538761794, -8.86567924774781],
... other sub-lists following this same format ...]

and

target = [-2, 1, 2]

I get this odd output:

gradDesc(trainers, target, num_vars)
Iteration       Error
---------       -----
delWeights:  [0, 0, 0]
type(dw):  <class 'int'>
type(dw):  <class 'int'>
type(dw):  <class 'int'>
delWeights:  [0.0, 0, 0]
type(dw):  <class 'float'>
Traceback (most recent call last):

  File "<ipython-input-19-97298b385113>", line 1, in <module>
    gradDesc(trainers, target, num_vars)

  File "C:/Users/Me/.spyder-py3/Machine Learning/gradDesc.py", line 107, in gradDesc
    delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]

TypeError: list indices must be integers or slices, not float

So my question is: why is the type of dw changing from an int to a float on the second iteration through the for e in exs loop?


问:
focus() not working in this getUi().showSidebar html in Chrome
I'm opening a sidebar containing a form in Google Sheets using a custom Menubar function.

I want the <textarea> to be focused whenever sidebar opens (so that cursor is in it, and any typing adds to it right away). But using focus() is not working. (Applying style to it is working, as per the next line.)

How can I accomplish that please? Thank you very much for your help.

NOTE: It is not working in Chrome (Win 10), but it does in Firefox.

```<code>function abc() {
    var html =
    '<form id="form">' +
    '<textarea id="title"> </textarea> '+
    '</form> <button>Submit</button> '+
    '<script>'+
    ' document.getElementById("title").focus(); '+ // << NOT WORKING
    ' document.getElementById("title").style.outline ="solid 2px red"' +  // << WORKING
    ' </script>'+
    '';

  var a = HtmlService.createHtmlOutput(html)
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle('MY-FORM')
  SpreadsheetApp.getUi().showSidebar(a);
}

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Functions')
  .addItem('Start', 'abc')
  .addSeparator()
  .addToUi();
}

</code>```

答:
You have to wait for the Page to load.

Try this:

```<code>function abc() {
  var html ='<form><input type="text" id="title" name="title" /><br /><input type="button" value="Submit" onclick="google.script.run.processForm(this.parentNode);"/></form>';
  html+='<script>window.onload=function(){document.getElementById("title").focus();document.getElementById("title").style.outline="solid 2px red";}</script>';
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showSidebar(ui);
}

function processForm(obj) {
  console.log(JSON.stringify(obj));
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  sh.getRange('A1').setValue(obj.title);
}
</code>```

You can also use a textarea as well:

```<code>function abc() {
  var html ='<form><textarea rows="1" cols="15" id="title" name="title"></textarea><br /><input type="button" value="Submit" onclick="google.script.run.processForm(this.parentNode);"/></form>';
  html+='<script>window.onload=function(){document.getElementById("title").focus();document.getElementById("title").style.outline="solid 2px red";}</script>';
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showSidebar(ui);
}
</code>```

Body:
I'm opening a sidebar containing a form in Google Sheets using a custom Menubar function.

I want the <textarea> to be focused whenever sidebar opens (so that cursor is in it, and any typing adds to it right away). But using focus() is not working. (Applying style to it is working, as per the next line.)

How can I accomplish that please? Thank you very much for your help.

NOTE: It is not working in Chrome (Win 10), but it does in Firefox.

function abc() {
    var html =
    '<form id="form">' +
    '<textarea id="title"> </textarea> '+
    '</form> <button>Submit</button> '+
    ''+
    '';

  var a = HtmlService.createHtmlOutput(html)
  .setSandboxMode(HtmlService.SandboxMode.IFRAME)
  .setTitle('MY-FORM')
  SpreadsheetApp.getUi().showSidebar(a);
}

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Functions')
  .addItem('Start', 'abc')
  .addSeparator()
  .addToUi();
}

Body:
You have to wait for the Page to load.

Try this:

function abc() {
  var html ='<form><input type="text" id="title" name="title" /><br /><input type="button" value="Submit" onclick="google.script.run.processForm(this.parentNode);"/></form>';
  html+='<script>window.onload=function(){document.getElementById("title").focus();document.getElementById("title").style.outline="solid 2px red";}</script>';
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showSidebar(ui);
}

function processForm(obj) {
  console.log(JSON.stringify(obj));
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  sh.getRange('A1').setValue(obj.title);
}

You can also use a textarea as well:

function abc() {
  var html ='<form><textarea rows="1" cols="15" id="title" name="title"></textarea><br /><input type="button" value="Submit" onclick="google.script.run.processForm(this.parentNode);"/></form>';
  html+='<script>window.onload=function(){document.getElementById("title").focus();document.getElementById("title").style.outline="solid 2px red";}</script>';
  var ui=HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showSidebar(ui);
}


问:
Present SiteMaps Diagrammatically
I have a web application with a number of pages, I would like to display the sitemaps for this application diagrammatically, is there a professional/recommended tool for doing this?

I am using MS Word using flowcharts, but it doesnt look very professional.

Are there any alternative suggestions as to what I could use?

Thank you

答:
You can try:

http://www.gliffy.com/

http://www.altova.com/umodel.html

http://creately.com/

http://gomockingbird.com/

http://www.drawanywhere.com/

http://cacoo.com/

http://www.lovelycharts.com/

Title: Present SiteMaps Diagrammatically


问:
How to make an excel non-editable?
I export excel in protected or using password manner and there is a chance to unprotect the sheet. I want that, there is no option to edit after export the excel in vb.net. </p>

答:
To make a column non-editable:

Select the whole worksheet, Right Click->Format Cells->Protection, uncheck the "Locked" check box.

Select the column you want to protect, right Click->Format Cells->Protection, select the "Locked" check box.

Review tab->Protect Sheet, select the "Protect worksheet and contents of locked cells" check box and protect the sheet using a password.

Title: How to make an excel non-editable?


问:
Xamarin Forms saving image in sqlite database
How do I save an image I captured directly to sqlite(sqlite-net-pcl) database?

Here's my code but it can only save in "Internal Storage" of the phone.

private async void TakePhotoButton_Clicked(object sender, EventArgs e)
{
    try
    {
        await CrossMedia.Current.Initialize();
        if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
        {
            await DisplayAlert("No Camera", "No Camera Available", "OK");
            return;
        }

        var file = await CrossMedia.Current.TakePhotoAsync(
        new StoreCameraMediaOptions
        {
            SaveToAlbum = true,
            //Directory = "Sample",
            //Name = "Test.jpg"
        });

        if (file == null)
            return;

        PathLabel.Text = file.AlbumPath;
        MainImage.Source = ImageSource.FromStream(() =>
        {
            var stream = file.GetStream();
            file.Dispose();
            return stream;

        });
    }
    catch (Exception ex)
    {
        await DisplayAlert("error", ex.ToString(), "OK");
    }

}
```

答:
You should convert the stream to Byte array so that you save them to sqlite.</p>

```<code>public byte[] GetImageStreamAsBytes(Stream input)
{
  var buffer = new byte[16*1024];
  using (MemoryStream ms = new MemoryStream())
  {
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
                ms.Write(buffer, 0, read);
    }
      return ms.ToArray();
   }
}
</code>```

```<code>var imgDate = GetImageStreamAsBytes(file.GetStream());
</code>```

Body:
You should convert the stream to Byte array so that you save them to sqlite.

public byte[] GetImageStreamAsBytes(Stream input)
{
  var buffer = new byte[16*1024];
  using (MemoryStream ms = new MemoryStream())
  {
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
                ms.Write(buffer, 0, read);
    }
      return ms.ToArray();
   }
}

var imgDate = GetImageStreamAsBytes(file.GetStream());


问:
Is it possible to change the pydantic error messages in fastAPI?
In the FastAPI framework, the pydantic error messages are showing like below.

```<code>{"detail": [
{
    "loc": [
        "body",
        "location",
        "name"
    ],
    "msg": "field required",
    "type": "value_error.missing"
},
{
    "loc": [
        "body",
        "location",
        "name12"
    ],
    "msg": "extra fields not permitted",
    "type": "value_error.extra"
}
]
}
</code>```

I want to send a simple message: {"field-name":"error message"}.

In Pydantic document they mentioned like, create a model instance in the try: except blocks and construct the error message in the except block. But in fast API, model instance created by fastapi itself, for example, if I write an URL like below

```<code>@router.post("/", response_model=DataModelOut)
async def create_location(location: schemas.LocationIn, user: str = Depends(get_current_user) ):
return model.save(location,user)
</code>```

Here the location instance created by fastapi itself is the problem.

Is there any way to construct the error message?

答:
I am writing a middle ware for it.</p>

```<code>async def genrange(s):
    import json
    s = json.loads(s)
    yield json.dumps({"message":{k.get("loc")[-1]:k.get("msg") for k in s['detail']},
        "id":None})

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    response = await call_next(request)
    status_code = response.status_code
    if status_code >=300:
        async for i in response.body_iterator:
            data = genrange(i)
        response.body_iterator = data
    return response
</code>```

Body:
In the FastAPI framework, the pydantic error messages are showing like below.

{"detail": [
{
    "loc": [
        "body",
        "location",
        "name"
    ],
    "msg": "field required",
    "type": "value_error.missing"
},
{
    "loc": [
        "body",
        "location",
        "name12"
    ],
    "msg": "extra fields not permitted",
    "type": "value_error.extra"
}
]
}

I want to send a simple message: {"field-name":"error message"}.

In Pydantic document they mentioned like, create a model instance in the try: except blocks and construct the error message in the except block. But in fast API, model instance created by fastapi itself, for example, if I write an URL like below

@router.post("/", response_model=DataModelOut)
async def create_location(location: schemas.LocationIn, user: str = Depends(get_current_user) ):
return model.save(location,user)

Here the location instance created by fastapi itself is the problem.

Is there any way to construct the error message?

Body:
I am writing a middle ware for it.

async def genrange(s):
    import json
    s = json.loads(s)
    yield json.dumps({"message":{k.get("loc")[-1]:k.get("msg") for k in s['detail']},
        "id":None})

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    response = await call_next(request)
    status_code = response.status_code
    if status_code >=300:
        async for i in response.body_iterator:
            data = genrange(i)
        response.body_iterator = data
    return response


问:
Heatmap correlation using values of column?
Suppose I have the following data of repeat observations for US states with some value of interest:

```<code>US_State Value
Alabama  1
Alabama  10
Alabama  9
Michigan 8
Michigan 9
Michigan 2
...
</code>```

How can I generate pairwise correlations for Value between all the US_State combinations? I've tried a few different things (pivot, groupby, and more), but I can't seem to wrap my head around the proper approach.

The ideal output would look like:

```<code>          Alabama   Michigan    ...
Alabama      1          0.5
Michigan     0.5        1
...
</code>```

答:
There is a way utilising Pandas to its extents, but this is only under the assumption that each state in the input dataset has the same number of observations, otherwise correlation coefficient does not really make sense and the results will become a bit funky.

```<code>import pandas as pd

df = pd.DataFrame()
df['US_State'] = ["Alabama", "Alabama", "Alabama", "Michigan", "Michigan", "Michigan", "Oregon", "Oregon", "Oregon"]
df['Value'] = [1, 10, 9, 8, 9, 2, 6, 1, 2]

pd.DataFrame(df.groupby("US_State")['Value'].apply(lambda x: list(x))).T.apply(lambda x: pd.Series(*x), axis=0).corr()
</code>```

which results into

```<code>US_State   Alabama  Michigan    Oregon
US_State
Alabama   1.000000 -0.285578 -0.996078
Michigan -0.285578  1.000000  0.199667
Oregon   -0.996078  0.199667  1.000000
</code>```

What the code basically does is it collects the data for each state into a single cell as a list, transposes the dataframe to make the states columns and then expands the collected cell of list data into dataframe rows for each state. Then you can just call the standard corr() method of pandas dataframe.

Body:
Suppose I have the following data of repeat observations for US states with some value of interest:

US_State Value
Alabama  1
Alabama  10
Alabama  9
Michigan 8
Michigan 9
Michigan 2
...

How can I generate pairwise correlations for Value between all the US_State combinations? I've tried a few different things (pivot, groupby, and more), but I can't seem to wrap my head around the proper approach.

The ideal output would look like:

          Alabama   Michigan    ...
Alabama      1          0.5
Michigan     0.5        1
...

Body:
There is a way utilising Pandas to its extents, but this is only under the assumption that each state in the input dataset has the same number of observations, otherwise correlation coefficient does not really make sense and the results will become a bit funky.

import pandas as pd

df = pd.DataFrame()
df['US_State'] = ["Alabama", "Alabama", "Alabama", "Michigan", "Michigan", "Michigan", "Oregon", "Oregon", "Oregon"]
df['Value'] = [1, 10, 9, 8, 9, 2, 6, 1, 2]

pd.DataFrame(df.groupby("US_State")['Value'].apply(lambda x: list(x))).T.apply(lambda x: pd.Series(*x), axis=0).corr()

which results into

US_State   Alabama  Michigan    Oregon
US_State
Alabama   1.000000 -0.285578 -0.996078
Michigan -0.285578  1.000000  0.199667
Oregon   -0.996078  0.199667  1.000000

What the code basically does is it collects the data for each state into a single cell as a list, transposes the dataframe to make the states columns and then expands the collected cell of list data into dataframe rows for each state. Then you can just call the standard corr() method of pandas dataframe.


问:
how to absolute button when it reach footer Bootstrap Affix
I have created a button in the right bottom of screen and footer in bottom of the screen and i have make the button it position: fixed I want to change position to absolute on scrolling down reach the footer
my css:

```<code>.affix-top {
    position:fixed;
}
.affix {
    position:absolute;

}
</code>```

my script:

```<code>$("#myBtn").affix({
        offset: {
            top: $("#footer").outerHeight(true),
            bottom: null
        }
    });
</code>```

my footer:

```<code><footer class="footer" id="footer">
    <div class="container">
        <div class="row">
            <div class="col-sm-3">
                <h4 class="title">KYK Restaurant ★</h4>
                <p>THE BEST Delivery Restaurants - ★★★★★</p>
            </div>
    </div>
</div>
</code>```

答:
1)Add data-spy=”affix” to the div you would like to fix in the right side. Also Add a class to the div, in the example i added the class as my-affix-div.
Then add the below Javascript code.
in js:

```<code>$('.my-affix-div').affix(
   {offset:{top: 75, bottom: 240}}
);
</code>```

in css:

```<code>.affix-bottom{
    position: absolute;
    right: 0;
}
.affix-top{
    position: absolute;
    right: 0;
}
.affix {
        top: 200px;
        right: 0;

 }
</code>```

Body:
I have created a button in the right bottom of screen and footer in bottom of the screen and i have make the button it position: fixed I want to change position to absolute on scrolling down reach the footer
my css:

.affix-top {
    position:fixed;
}
.affix {
    position:absolute;

}

my script:

$("#myBtn").affix({
        offset: {
            top: $("#footer").outerHeight(true),
            bottom: null
        }
    });

my footer:

KYK Restaurant ★

THE BEST Delivery Restaurants - ★★★★★

Body:
1)Add data-spy=”affix” to the div you would like to fix in the right side. Also Add a class to the div, in the example i added the class as my-affix-div.
Then add the below Javascript code.
in js:

$('.my-affix-div').affix(
   {offset:{top: 75, bottom: 240}}
);

in css:

.affix-bottom{
    position: absolute;
    right: 0;
}
.affix-top{
    position: absolute;
    right: 0;
}
.affix {
        top: 200px;
        right: 0;

 }


问:
ContentLoadingProgressBar is not displaying for a minimum amount of time before hiding
I'm trying to use ContentLoadingProgressBar to display 1 second before hiding itself. However I can't seem to find any examples of how to use it correctly with a recyclerview.

So I've tried using just testing it, but I can't get it to display for a minimum amount of time. How would I do so?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.ContentLoadingProgressBar
        android:id="@+id/main_progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        style="?android:attr/progressBarStyleLarge"
        android:visibility="visible"/>

</RelativeLayout>
</code>```

I've simply just tried doing it like this:

```<code>mProgressBar.show();
mProgressBar.hide();
</code>```

However it's not displaying for 1 second before hiding. It just hides automatically.

答: ContentLoadingProgressBar has minimum threshold time 500ms, so you should wait this time before hiding</p>

Body:
I'm trying to use ContentLoadingProgressBar to display 1 second before hiding itself. However I can't seem to find any examples of how to use it correctly with a recyclerview.

So I've tried using just testing it, but I can't get it to display for a minimum amount of time. How would I do so?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.core.widget.ContentLoadingProgressBar
        android:id="@+id/main_progressbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        style="?android:attr/progressBarStyleLarge"
        android:visibility="visible"/>

</RelativeLayout>

I've simply just tried doing it like this:

mProgressBar.show();
mProgressBar.hide();

However it's not displaying for 1 second before hiding. It just hides automatically.


问:
How to increment a Vote field within a Django database of Voting System
I'm trying to make a system in which a person(Voter) will vote for a candidate against their 'Candidate Id', so for that Voter has to input the 'Emirates Id' (which is primary key of Voter) and 'Election Id' -which is primary key of the polling station - both these ID's will get validated to check if vote has been cast or not, but the problem really lies within my logic. here is my
Views.py :

```<code>def vote(request):
        can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID'])
        voterrecord = Election_Day(  #through this we will create an object of the class or our model
            Can = can_id_obj,   #these are the fields in my 'Election Day' model
            emirates_id = Emirates_ID,
            election_id = Election_ID
        )
        voterrecord.Vote += 1   #we will call a field to manipulate it
        voterrecord.save()  #finally we can call save method on the object
        return render(request, 'Election_Day.html')
</code>```

Everytime the vote gets polled, Instead of incrementing the same record for which the vote was previously cast, it will make a new record and then save the vote as 1, so basically i want it to increment the same record, if the vote has been polled for the same candidate.I hope you understand the explanation..

Models.py For reference

```<code>class Election_Day(models.Model):
    Can = models.ForeignKey('Candidate_Form', on_delete=models.CASCADE)  #you refer the primary key to the whole class and it will automatically pick the id (primary key) of that class and make it a foreign key      #with that you can also access all the data stored in that table
    Elec = models.ForeignKey('Election_Info', on_delete=models.CASCADE, null =
    True) #you can make a foreign key null
    Vote = models.IntegerField(default=0)
    emirates_id = models.IntegerField()
    election_id = models.IntegerField()
</code>```

答:
You are not saving Candidate_Form object. Just add can_id_obj.save() in the end like this.

```<code>def vote(request):
        can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID'])
        voterrecord = Election_Day(  #through this we will create an object of the class or our model
            Can = can_id_obj,   #these are the fields in my 'Election Day' model
            emirates_id = Emirates_ID,
            election_id = Election_ID
        )
        can_id_obj.Vote += 1   #we will call a field to manipulate it
        can_id_obj.save()
        voterrecord.save()  #finally we can call save method on the object
        return render(request, 'Election_Day.html')
</code>```

Body:
I'm trying to make a system in which a person(Voter) will vote for a candidate against their 'Candidate Id', so for that Voter has to input the 'Emirates Id' (which is primary key of Voter) and 'Election Id' -which is primary key of the polling station - both these ID's will get validated to check if vote has been cast or not, but the problem really lies within my logic. here is my
Views.py :

def vote(request):
        can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID'])
        voterrecord = Election_Day(  #through this we will create an object of the class or our model
            Can = can_id_obj,   #these are the fields in my 'Election Day' model
            emirates_id = Emirates_ID,
            election_id = Election_ID
        )
        voterrecord.Vote += 1   #we will call a field to manipulate it
        voterrecord.save()  #finally we can call save method on the object
        return render(request, 'Election_Day.html')

Everytime the vote gets polled, Instead of incrementing the same record for which the vote was previously cast, it will make a new record and then save the vote as 1, so basically i want it to increment the same record, if the vote has been polled for the same candidate.I hope you understand the explanation..

Models.py For reference

class Election_Day(models.Model):
    Can = models.ForeignKey('Candidate_Form', on_delete=models.CASCADE)  #you refer the primary key to the whole class and it will automatically pick the id (primary key) of that class and make it a foreign key      #with that you can also access all the data stored in that table
    Elec = models.ForeignKey('Election_Info', on_delete=models.CASCADE, null =
    True) #you can make a foreign key null
    Vote = models.IntegerField(default=0)
    emirates_id = models.IntegerField()
    election_id = models.IntegerField()

Body:
You are not saving Candidate_Form object. Just add can_id_obj.save() in the end like this.

def vote(request):
        can_id_obj = Candidate_Form.objects.get(pk=request.POST['Can_ID'])
        voterrecord = Election_Day(  #through this we will create an object of the class or our model
            Can = can_id_obj,   #these are the fields in my 'Election Day' model
            emirates_id = Emirates_ID,
            election_id = Election_ID
        )
        can_id_obj.Vote += 1   #we will call a field to manipulate it
        can_id_obj.save()
        voterrecord.save()  #finally we can call save method on the object
        return render(request, 'Election_Day.html')


问:
CentOS 7 - Install Paramiko - bash: paramiko: command not found... error
I am new to Python and CentOS and looking for some options to automate some daily job using Paramiko.

However, got below error when installing Paramiko. Hope you guys can help.

[jason@centos7 ~]$ sudo pip install paramiko
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting paramiko
  Using cached paramiko-2.7.1-py2.py3-none-any.whl (206 kB)
Requirement already satisfied: bcrypt>=3.1.3 in /usr/lib64/python2.7/site-packages (from paramiko) (3.1.7)
Requirement already satisfied: pynacl>=1.0.1 in /usr/lib64/python2.7/site-packages (from paramiko) (1.3.0)
Requirement already satisfied: cryptography>=2.5 in /usr/lib64/python2.7/site-packages (from paramiko) (2.8)
Requirement already satisfied: six>=1.4.1 in /usr/lib/python2.7/site-packages (from bcrypt>=3.1.3->paramiko) (1.9.0)
Requirement already satisfied: cffi>=1.1 in /usr/lib64/python2.7/site-packages (from bcrypt>=3.1.3->paramiko) (1.6.0)
Requirement already satisfied: ipaddress; python_version < "3" in /usr/lib/python2.7/site-packages (from cryptography>=2.5->paramiko) (1.0.16)
Requirement already satisfied: enum34; python_version < "3" in /usr/lib/python2.7/site-packages (from cryptography>=2.5->paramiko) (1.0.4)
Requirement already satisfied: pycparser in /usr/lib/python2.7/site-packages (from cffi>=1.1->bcrypt>=3.1.3->paramiko) (2.14)
Installing collected packages: paramiko
Successfully installed paramiko-2.7.1
[jason@centos7 ~]$
[jason@centos7 ~]$
[jason@centos7 ~]$
[jason@centos7 ~]$
**[jason@centos7 ~]$ paramiko --version
bash: paramiko: command not found...**
[jason@centos7 ~]$
[jason@centos7 ~]$ python --version
Python 2.7.5
[jason@centos7 ~]$
```
<p>Tried to add the path into system path - still no luck</p>
<pre class="lang-none prettyprint-override"><code>[jason@centos7 ~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/jason/.local/bin:/home/jason/bin:/usr/:/usr/lib/python2.7/site-packages/
</code>```

答:
There's no paramiko shell command.

Paramiko is Python module. You have to write Python code to make use of it.

For some examples, see Paramiko demos.

Body:
I am new to Python and CentOS and looking for some options to automate some daily job using Paramiko.

However, got below error when installing Paramiko. Hope you guys can help.

[jason@centos7 ~]$ sudo pip install paramiko
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting paramiko
  Using cached paramiko-2.7.1-py2.py3-none-any.whl (206 kB)
Requirement already satisfied: bcrypt>=3.1.3 in /usr/lib64/python2.7/site-packages (from paramiko) (3.1.7)
Requirement already satisfied: pynacl>=1.0.1 in /usr/lib64/python2.7/site-packages (from paramiko) (1.3.0)
Requirement already satisfied: cryptography>=2.5 in /usr/lib64/python2.7/site-packages (from paramiko) (2.8)
Requirement already satisfied: six>=1.4.1 in /usr/lib/python2.7/site-packages (from bcrypt>=3.1.3->paramiko) (1.9.0)
Requirement already satisfied: cffi>=1.1 in /usr/lib64/python2.7/site-packages (from bcrypt>=3.1.3->paramiko) (1.6.0)
Requirement already satisfied: ipaddress; python_version < "3" in /usr/lib/python2.7/site-packages (from cryptography>=2.5->paramiko) (1.0.16)
Requirement already satisfied: enum34; python_version < "3" in /usr/lib/python2.7/site-packages (from cryptography>=2.5->paramiko) (1.0.4)
Requirement already satisfied: pycparser in /usr/lib/python2.7/site-packages (from cffi>=1.1->bcrypt>=3.1.3->paramiko) (2.14)
Installing collected packages: paramiko
Successfully installed paramiko-2.7.1
[jason@centos7 ~]$
[jason@centos7 ~]$
[jason@centos7 ~]$
[jason@centos7 ~]$
**[jason@centos7 ~]$ paramiko --version
bash: paramiko: command not found...**
[jason@centos7 ~]$
[jason@centos7 ~]$ python --version
Python 2.7.5
[jason@centos7 ~]$

Tried to add the path into system path - still no luck

[jason@centos7 ~]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/jason/.local/bin:/home/jason/bin:/usr/:/usr/lib/python2.7/site-packages/


答:
```<code>delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]
</code>```

sets delWeights[dw] to a float, because e[dw] is a float. So the next time you do the for dw in delWeights: loop, dw is a float.

It doesn't make sense to use the elements of delWeights as indexes. If you want to iterate over a list and also get the indexes, you should use enumerate()

```<code>for i, dw in enumerate(delWeights):
    delWeights[i] = dw + n*(test_hypo(target, e, num_vars) - output)*e[i]
</code>```

Title: Python nested for loops - inner loop iterator type change

Body:
delWeights[dw] = delWeights[dw] + n*(test_hypo(target, e, num_vars) - output)*e[dw]

sets delWeights[dw] to a float, because e[dw] is a float. So the next time you do the for dw in delWeights: loop, dw is a float.

It doesn't make sense to use the elements of delWeights as indexes. If you want to iterate over a list and also get the indexes, you should use enumerate()

for i, dw in enumerate(delWeights):
    delWeights[i] = dw + n*(test_hypo(target, e, num_vars) - output)*e[i]