问:
Unit testing routes with Mock ActivatedRoute configuration
I am configuring test spec for my component which has routes, also I have defined my spec with dependencies as follows. And the ActivatedRoute has these properties, But I don't see its object/instance being created while debugging my test spec. Also I have referred different methods of mocking ActivatedRoute but nothing is helping me. Please correct me if I am doing anything wrong

class UserInfotypeDetailComponent implements OnInit, OnDestroy {
    constructor(
        private userInfotypeDetailService: UserInfotypeDetailService,
        private appLookupService: AppLookupService,
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) {}

 performAction(event: { action: string; objectKey: string | null }) {
    let extras: any = { relativeTo: this.activatedRoute };
    if (event.objectKey) {
          extras.queryParams = { objectKey: event.objectKey };
    }

    switch (event.action) {
      case "new":
      case "edit":
      case "copy":
      case "view":
        this.router.navigate([event.action], extras);
        break;
      case "delete":
        this.deleteRecord(event.objectKey as string);
    }
  }

}
```

<p>Here is my Routes: </p>

<pre class="lang-js prettyprint-override"><code>{
        path: "infotype/:id",
        component: UserInfotypeDetailComponent,
        outlet: "slidein",
        children: [
          {
            path: "new",
            component: UserRecordFormComponent,
            data: { actionId: "A", buttonDesc: "Save" }
          },
          {
            path: "edit",
            component: UserRecordFormComponent,
            data: { actionId: "E", buttonDesc: "Update" }
          },
          {
            path: "copy",
            component: UserRecordFormComponent,
            data: { actionId: "C", buttonDesc: "Save" }
          },
          {
            path: "view",
            component: UserRecordFormComponent,
            data: { actionId: "V", actionDesc: "View" }
          }
        ]
      }
</code>```

And my test spec is as follows:

beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
              RouterTestingModule.withRoutes([]),
                BrowserAnimationsModule,
                RouterModule
            ],
            declarations: [
                UserInfotypeDetailComponent
            ],
            providers: [
                { provide: ActivatedRoute, useValue: {
                                          outlet: "slidein",
                                          params: of({
                                              id: "0009"
                                          })
                                      }
                },
                { provide: AppLookupService, useClass: AppLookupServiceStub },
                { provide: UserInfotypeDetailService, useClass: UserInfotypeDetailServiceStub },
                { provide: Router, useClass: AppRouterStub }
            ],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    class AppRouterStub {
        navigate() {}
    }
```

<p>And test case:</p>

<pre class="lang-js prettyprint-override"><code>it('make expect calls to router navigate', fakeAsync(() => {
      let router = TestBed.get(Router);
      let spy = spyOn(router, 'navigate');

      component.performAction(event);

      let extras: any = { relativeTo: ActivatedRoute };
      if (event.objectKey) {
        extras.queryParams = { objectKey: event.objectKey };
      }
      fixture.detectChanges();

      expect(spy).toHaveBeenCalledWith([event.action], extras);
    }))
</code>```

The error that it throws is:

"spy navigate to have been called with [ [ 'edit' ], Object({ relativeTo: Function, queryParams: Object({ objectKey: '36353539363A393C3535353E352525252525253E3E3E3E363738363735363E35363536353535' }) }) ] but actual calls were [ [ 'edit' ], Object({ relativeTo: Object({ snapshot: Object({  }), parent: Object({ params: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }) }), params: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }), queryParams: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }), testParams: Object({ id: '0009' }) }), queryParams: Object({ objectKey: '36353539363A393C3535353E352525252525253E3E3E3E363738363735363E35363536353535' }) }) ]."

答:
It's failing because with

```<code>let extras: any = { relativeTo: ActivatedRoute };
</code>```

you are actually using angular's ActivatedRoute but what you should be using is the useValue which you have defined in providers.

Make activatedRoute public in constructor of the component, so that we can access it

```<code>public activatedRoute: ActivatedRoute,
public router : Router
</code>```

Try:

```<code>it('make expect calls to router navigate', fakeAsync(() => {
      spyOn(component.router, 'navigate');

      component.performAction(event);
      // I hope you have defined "event" somewhere in code, because I can't see
      // it anywhere here !

      let extras: any = { relativeTo: component.activatedRoute};
      if (event.objectKey) {
        extras.queryParams = { objectKey: event.objectKey };
      }

      expect(component.router.navigate).toHaveBeenCalledWith([event.action], extras);
    }))
</code>```

Body:
I am configuring test spec for my component which has routes, also I have defined my spec with dependencies as follows. And the ActivatedRoute has these properties, But I don't see its object/instance being created while debugging my test spec. Also I have referred different methods of mocking ActivatedRoute but nothing is helping me. Please correct me if I am doing anything wrong

class UserInfotypeDetailComponent implements OnInit, OnDestroy {
    constructor(
        private userInfotypeDetailService: UserInfotypeDetailService,
        private appLookupService: AppLookupService,
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) {}

 performAction(event: { action: string; objectKey: string | null }) {
    let extras: any = { relativeTo: this.activatedRoute };
    if (event.objectKey) {
          extras.queryParams = { objectKey: event.objectKey };
    }

    switch (event.action) {
      case "new":
      case "edit":
      case "copy":
      case "view":
        this.router.navigate([event.action], extras);
        break;
      case "delete":
        this.deleteRecord(event.objectKey as string);
    }
  }

}

Here is my Routes:

{
        path: "infotype/:id",
        component: UserInfotypeDetailComponent,
        outlet: "slidein",
        children: [
          {
            path: "new",
            component: UserRecordFormComponent,
            data: { actionId: "A", buttonDesc: "Save" }
          },
          {
            path: "edit",
            component: UserRecordFormComponent,
            data: { actionId: "E", buttonDesc: "Update" }
          },
          {
            path: "copy",
            component: UserRecordFormComponent,
            data: { actionId: "C", buttonDesc: "Save" }
          },
          {
            path: "view",
            component: UserRecordFormComponent,
            data: { actionId: "V", actionDesc: "View" }
          }
        ]
      }

And my test spec is as follows:

beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
              RouterTestingModule.withRoutes([]),
                BrowserAnimationsModule,
                RouterModule
            ],
            declarations: [
                UserInfotypeDetailComponent
            ],
            providers: [
                { provide: ActivatedRoute, useValue: {
                                          outlet: "slidein",
                                          params: of({
                                              id: "0009"
                                          })
                                      }
                },
                { provide: AppLookupService, useClass: AppLookupServiceStub },
                { provide: UserInfotypeDetailService, useClass: UserInfotypeDetailServiceStub },
                { provide: Router, useClass: AppRouterStub }
            ],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();
    }));

    class AppRouterStub {
        navigate() {}
    }

And test case:

it('make expect calls to router navigate', fakeAsync(() => {
      let router = TestBed.get(Router);
      let spy = spyOn(router, 'navigate');

      component.performAction(event);

      let extras: any = { relativeTo: ActivatedRoute };
      if (event.objectKey) {
        extras.queryParams = { objectKey: event.objectKey };
      }
      fixture.detectChanges();

      expect(spy).toHaveBeenCalledWith([event.action], extras);
    }))

The error that it throws is:

"spy navigate to have been called with [ [ 'edit' ], Object({ relativeTo: Function, queryParams: Object({ objectKey: '36353539363A393C3535353E352525252525253E3E3E3E363738363735363E35363536353535' }) }) ] but actual calls were [ [ 'edit' ], Object({ relativeTo: Object({ snapshot: Object({  }), parent: Object({ params: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }) }), params: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }), queryParams: Subject({ _isScalar: false, observers: [  ], closed: false, isStopped: false, hasError: false, thrownError: null }), testParams: Object({ id: '0009' }) }), queryParams: Object({ objectKey: '36353539363A393C3535353E352525252525253E3E3E3E363738363735363E35363536353535' }) }) ]."

Body:
It's failing because with

let extras: any = { relativeTo: ActivatedRoute };

you are actually using angular's ActivatedRoute but what you should be using is the useValue which you have defined in providers.

Make activatedRoute public in constructor of the component, so that we can access it

public activatedRoute: ActivatedRoute,
public router : Router

Try:

it('make expect calls to router navigate', fakeAsync(() => {
      spyOn(component.router, 'navigate');

      component.performAction(event);
      // I hope you have defined "event" somewhere in code, because I can't see
      // it anywhere here !

      let extras: any = { relativeTo: component.activatedRoute};
      if (event.objectKey) {
        extras.queryParams = { objectKey: event.objectKey };
      }

      expect(component.router.navigate).toHaveBeenCalledWith([event.action], extras);
    }))


来源: stackexchange

问:
Listen to twiml without calling number
I am making my TwiML for incoming calls and want to hear what it sounds like without having to call the phone number directly. Are there any twilio dev tools that help with that problem?

I tried looking through the developer console and searching online, but I couldn't find anything.

```<code><?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="alice">I want to hear this message without calling my number!</Say>
</Response>
</code>```

I expect to hit a listen button and hear Alices voice say the message that I've written, but in order to do that I have to call my twilio number, and I shouldn't have to.

答:
You can do this from the Twilio console, visit the link below, when logged into your Twilio console:

Text-to-Speech

Then select the language under Current Language Mapping, say "English (US) (en-US)" and then under "Test this Voice", enter the phrase and click the play button to listen to it.

ContentLicense: CC BY-SA 4.0

Title: Listen to twiml without calling number

Body:
I am making my TwiML for incoming calls and want to hear what it sounds like without having to call the phone number directly. Are there any twilio dev tools that help with that problem?

I tried looking through the developer console and searching online, but I couldn't find anything.

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say voice="alice">I want to hear this message without calling my number!</Say>
</Response>

I expect to hit a listen button and hear Alices voice say the message that I've written, but in order to do that I have to call my twilio number, and I shouldn't have to.


问:
How to get the top level key with the highest value of a specific lower level key in json file?
My json file looks like:

```<code>{
    "One": {
        "action": "One",
        "delay": 1558834290.2415142,
        "seconds": 60,
        "score": 10,
        "delta": 1558828290.2415142,
        "grace_sec": 6060
    },
    "Two": {
        "action": "Two",
        "delay": 1558834292.6928985,
        "seconds": 60,
        "score": 9,
        "delta": 1558828292.6928985,
        "grace_sec": 6060
    }
}
</code>```

I want to get the top level key that has the highest value of score, so in this case I would want key One.

I've tried:

```<code>with open("streak.json", "r") as read_file:
                data = json.load(read_file)

highest = max(int(d['score'] for d in data.values()))
</code>```

but I get TypeError: int() argument must be a string, a bytes-like object or a number, not 'generator'

答:
You could write it like this:</p>

```<code>result = max(data, key=lambda k: data[k]["score"])
</code>```

Body:
My json file looks like:

{
    "One": {
        "action": "One",
        "delay": 1558834290.2415142,
        "seconds": 60,
        "score": 10,
        "delta": 1558828290.2415142,
        "grace_sec": 6060
    },
    "Two": {
        "action": "Two",
        "delay": 1558834292.6928985,
        "seconds": 60,
        "score": 9,
        "delta": 1558828292.6928985,
        "grace_sec": 6060
    }
}

I want to get the top level key that has the highest value of score, so in this case I would want key One.

I've tried:

with open("streak.json", "r") as read_file:
                data = json.load(read_file)

highest = max(int(d['score'] for d in data.values()))

but I get TypeError: int() argument must be a string, a bytes-like object or a number, not 'generator'

Body:
You could write it like this:

result = max(data, key=lambda k: data[k]["score"])


问:
Input parameters validation and response
I want to validate operation parameters sent from the client (using IParameterInspector) in my service and in case of wrong parameter input I would like to send response code as a part of the response object instead of throwing fault exception.
Please let me know how I can achieve this.

UPDATE :
If it is not possible with IParameterInspector, what other options you will suggest ?

答: do you use  wcf ? if yes you can use FualtException of Wcf</p>

ContentLicense: CC BY-SA 3.0


问:
Data not show in view using express.js + mysql + ejs + typeORM
I'm sorry if I have some stupid question, in my end, I'm a newbie in node.js, my probme is i'm failed to displaying data from entity in express.js framework, I'm using Mysql with TypeORM, and ejs template engine.

I have tried many examples, and below is one of them
https://github.com/typeorm/typescript-express-example
but seem's not work.

my editor is VSC, and below is my directory. directory

below is my codes

1 - the entity (MasterKategori.ts):

```<code>import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity("mst_kategori")
export class MasterKategori {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column("varchar")
    public KodeKategori: string;

    @Column("varchar")
    public NamaKategori: string;

    @Column("varchar")
    public Keterangan: string;

    @Column("timestamp")
    public AddDate: Date;

    @Column("datetime")
    public ModifiedDate: Date;

    @Column("int")
    public ModifiedUser: number;

    @Column("int")
    public AddUser: number;
}
</code>```

2 - index.ts

below is my index.ts, in this script I called the routes (routes.ts):

```<code>import dotenv from "dotenv";
import express from "express";
import path from "path";
import "reflect-metadata";
import {createConnection} from "typeorm";

import * as routes from "./routes";
createConnection().then(async (connection) => {
    dotenv.config();

    const port = process.env.SERVER_PORT;
    const app = express();

    app.set( "views", path.join( __dirname, "views" ) );
    app.set( "view engine", "ejs" );

    routes.web(app);

    app.listen(port);
    console.log(`Alhamdulillah, aplikasi ini menggunakan port ${port}!`);
}).catch((error) => console.log("TypeORM connection error: ", error));
</code>```

3 - routes.ts:

```<code>import * as express from "express";
import HomeController from "./controllers/HomeController";

export const web = ( app: express.Application ) => {
   // default homepage routes, and calling the controller
   app.get( "/", HomeController.home);
};
</code>```

4 - mycontroller (HomeController.ts), in this code I called the entity (MasterKategori.ts) and rendered to the view, I'm using ejs template engine

```<code>import * as express from "express";
import {getConnection} from "typeorm"; //calling typeORM
import {MasterKategori} from "../entity/MasterKategori"; //calling the Entity

class HomeController {
    public home = (request: express.Request, response: express.Response) => {
        const kategoriData = getConnection().getRepository(MasterKategori).find(); //get all data
        const kategori = Object.entries(kategoriData);
        response.render("page", {kat: kategori});
    }
}

export default new HomeController();
</code>```

5 - the view (page.ejs)

```<code><ul>
    <% kat.forEach(function(katdata){ %>
        <li><%= katdata.NamaKategori %> - <%= katdata.KodeKategori %></li>
    <% }) %>
</ul>
</code>```

and below is the mysql table and records:

```<code>select * from `mst_kategori`;

    id  KodeKategori  NamaKategori  Keterangan  AddDate              ModifiedDate         ModifiedUser  AddUser
------  ------------  ------------  ----------  -------------------  -------------------  ------------  ---------
     1  Coba          Coba          Coba        2019-05-25 09:21:00  0000-00-00 00:00:00             0          0
     2  lagi          lagi          lagi        2019-05-25 10:02:48  0000-00-00 00:00:00             0          0

</code>```

Unfortunately the result is given blank in the browser, and if I do 'console.log(kategori)' the return is '[]' (no data given).

I'm really appreciate for your any kind of help, I' getting headache for this problem in my end.

however I'm very newbie in node.js, this is will help me to start with ORM and MVC in express.js for my project

答:
Sorry the error is

```<code>HomeController.ts:7:26 - non-arrow functions are forbidden
</code>```

below is the changes

```<code>import * as express from "express";
import {getConnection} from "typeorm";
import {MasterKategori} from "../entity/MasterKategori";

class HomeController {

    public home  = async function(request: express.Request, response: express.Response) {
        const kategoriData = getConnection().getRepository(MasterKategori).find();
        const kategori = Object.entries(kategoriData);
        console.log(kategori);
        response.render("page", {kat: kategori});
    };
}

export default new HomeController();

</code>```

Body:
I'm sorry if I have some stupid question, in my end, I'm a newbie in node.js, my probme is i'm failed to displaying data from entity in express.js framework, I'm using Mysql with TypeORM, and ejs template engine.

I have tried many examples, and below is one of them
https://github.com/typeorm/typescript-express-example
but seem's not work.

my editor is VSC, and below is my directory. directory

below is my codes

1 - the entity (MasterKategori.ts):

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity("mst_kategori")
export class MasterKategori {

    @PrimaryGeneratedColumn()
    public id: number;

    @Column("varchar")
    public KodeKategori: string;

    @Column("varchar")
    public NamaKategori: string;

    @Column("varchar")
    public Keterangan: string;

    @Column("timestamp")
    public AddDate: Date;

    @Column("datetime")
    public ModifiedDate: Date;

    @Column("int")
    public ModifiedUser: number;

    @Column("int")
    public AddUser: number;
}

2 - index.ts

below is my index.ts, in this script I called the routes (routes.ts):

import dotenv from "dotenv";
import express from "express";
import path from "path";
import "reflect-metadata";
import {createConnection} from "typeorm";

import * as routes from "./routes";
createConnection().then(async (connection) => {
    dotenv.config();

    const port = process.env.SERVER_PORT;
    const app = express();

    app.set( "views", path.join( __dirname, "views" ) );
    app.set( "view engine", "ejs" );

    routes.web(app);

    app.listen(port);
    console.log(`Alhamdulillah, aplikasi ini menggunakan port ${port}!`);
}).catch((error) => console.log("TypeORM connection error: ", error));

3 - routes.ts:

import * as express from "express";
import HomeController from "./controllers/HomeController";

export const web = ( app: express.Application ) => {
   // default homepage routes, and calling the controller
   app.get( "/", HomeController.home);
};

4 - mycontroller (HomeController.ts), in this code I called the entity (MasterKategori.ts) and rendered to the view, I'm using ejs template engine

import * as express from "express";
import {getConnection} from "typeorm"; //calling typeORM
import {MasterKategori} from "../entity/MasterKategori"; //calling the Entity

class HomeController {
    public home = (request: express.Request, response: express.Response) => {
        const kategoriData = getConnection().getRepository(MasterKategori).find(); //get all data
        const kategori = Object.entries(kategoriData);
        response.render("page", {kat: kategori});
    }
}

export default new HomeController();

5 - the view (page.ejs)

    <% kat.forEach(function(katdata){ %>

<%= katdata.NamaKategori %> - <%= katdata.KodeKategori %>

    <% }) %>

and below is the mysql table and records:

select * from `mst_kategori`;

    id  KodeKategori  NamaKategori  Keterangan  AddDate              ModifiedDate         ModifiedUser  AddUser
------  ------------  ------------  ----------  -------------------  -------------------  ------------  ---------
     1  Coba          Coba          Coba        2019-05-25 09:21:00  0000-00-00 00:00:00             0          0
     2  lagi          lagi          lagi        2019-05-25 10:02:48  0000-00-00 00:00:00             0          0

Unfortunately the result is given blank in the browser, and if I do 'console.log(kategori)' the return is '[]' (no data given).

I'm really appreciate for your any kind of help, I' getting headache for this problem in my end.

however I'm very newbie in node.js, this is will help me to start with ORM and MVC in express.js for my project

Body:
Sorry the error is

HomeController.ts:7:26 - non-arrow functions are forbidden

below is the changes

import * as express from "express";
import {getConnection} from "typeorm";
import {MasterKategori} from "../entity/MasterKategori";

class HomeController {

    public home  = async function(request: express.Request, response: express.Response) {
        const kategoriData = getConnection().getRepository(MasterKategori).find();
        const kategori = Object.entries(kategoriData);
        console.log(kategori);
        response.render("page", {kat: kategori});
    };
}

export default new HomeController();


问:
How to create a circular animation when a tab is pressed in (Swift)
Essentially I would like to recreate the following animation that occurs in the Youtube app when a tab is selected.

This is currently what I have in my custom Tab Bar Controller class:

```<code>import UIKit

class AnimatedTabBarController: UITabBarController {

    private var bounceAnimation: CAKeyframeAnimation = {
        let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        bounceAnimation.values = [1.0, 0.9, 1.00, 1.00, 1.0]
        bounceAnimation.duration = TimeInterval(0.3)
        bounceAnimation.calculationMode = CAAnimationCalculationMode.cubic
        return bounceAnimation
    }()

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        // find index if the selected tab bar item, then find the corresponding view and get its image, the view position is offset by 1 because the first item is the background (at least in this case)
        guard let idx = tabBar.items?.index(of: item), tabBar.subviews.count > idx + 1, let imageView = tabBar.subviews[idx + 1].subviews.first as? UIImageView else {
            return
        }

        imageView.layer.add(bounceAnimation, forKey: nil)
    }
}
</code>```

The code above allows my tabs to bounce inwards when being selected, what can be added to the class to also add the circle and have it subtly disappear.

答:
There are several methods you can use. You can take third party or you can create custom. In my case, I use custom.

take a viewController in storyboard

create same view as your question's images

set containerView in same viewController

give touchupinside animation in buttons or use coreGraphichs or use layers

add controller in containerView when tap.

Body:
Essentially I would like to recreate the following animation that occurs in the Youtube app when a tab is selected.

This is currently what I have in my custom Tab Bar Controller class:

import UIKit

class AnimatedTabBarController: UITabBarController {

    private var bounceAnimation: CAKeyframeAnimation = {
        let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
        bounceAnimation.values = [1.0, 0.9, 1.00, 1.00, 1.0]
        bounceAnimation.duration = TimeInterval(0.3)
        bounceAnimation.calculationMode = CAAnimationCalculationMode.cubic
        return bounceAnimation
    }()

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        // find index if the selected tab bar item, then find the corresponding view and get its image, the view position is offset by 1 because the first item is the background (at least in this case)
        guard let idx = tabBar.items?.index(of: item), tabBar.subviews.count > idx + 1, let imageView = tabBar.subviews[idx + 1].subviews.first as? UIImageView else {
            return
        }

        imageView.layer.add(bounceAnimation, forKey: nil)
    }
}

The code above allows my tabs to bounce inwards when being selected, what can be added to the class to also add the circle and have it subtly disappear.


问:
Creating a lambda function dynamically
Is there some way I could create a lambda function dynamically? For example,

```<code>f = lambda t : (1 + 32*t + 23*np.power(t,2) + 23*np.power(t,3) + 23*np.power(t,4))
</code>```

in the above lambda function f, I want to increment the value of t in 23*np.power(t,2) and want it to go until 467. So:

```<code>f = lambda t : (1 + 32*t + 23*np.power(t,2) + .. + 23*np.power(t,467))
</code>```

Is there a way I could do this automatically?

Title: Creating a lambda function dynamically

Body:
Is there some way I could create a lambda function dynamically? For example,

f = lambda t : (1 + 32*t + 23*np.power(t,2) + 23*np.power(t,3) + 23*np.power(t,4))

in the above lambda function f, I want to increment the value of t in 23*np.power(t,2) and want it to go until 467. So:

f = lambda t : (1 + 32*t + 23*np.power(t,2) + .. + 23*np.power(t,467))

Is there a way I could do this automatically?

Body:
The two parameters of np.power broadcast against each other.

def foo(t, p):
    return 1+32*t + np.sum(23*np.power(t,np.arange(*p)[:,None]), axis=0)

This is written to take a t array, and a power range:

In [445]: foo(np.linspace(0,1,11),(2,4))
Out[445]:
array([ 1.   ,  4.453,  8.504, 13.291, 18.952, 25.625, 33.448, 42.559,
       53.096, 65.197, 79.   ])
In [446]: foo(np.linspace(0,1,11),(2,468))
Out[446]:
array([1.00000000e+00, 4.45555556e+00, 8.55000000e+00, 1.35571429e+01,
       1.99333333e+01, 2.85000000e+01, 4.09000000e+01, 6.09666667e+01,
       1.00200000e+02, 2.16100000e+02, 1.07510000e+04])

This version gives the caller more control:

def foo(t, p, axis=0):
    return 1+32*t + np.sum(23*np.power(t,p), axis=axis)

e.g. a 2d t array (but you have to understand broadcasting well):

In [449]: foo(np.linspace(0,1,10).reshape(2,5),np.arange(2,468)[:,None,None])
Out[449]:
array([[1.00000000e+00, 4.87500000e+00, 9.57142857e+00, 1.55000000e+01,
        2.34000000e+01],
       [3.47500000e+01, 5.30000000e+01, 8.85000000e+01, 1.93000000e+02,
        1.07510000e+04]])


问:
Is it average loss for tf.estimator.DNNRegressor in tensorflow the same with MSE?
In model.evaluate of tensorflow, there is a variable called "average_loss". Is it the same as MSE between labels and predictions? However in tf.losses, there is another function mean_squared_error as well. Which one is the correct MSE?

答:
The loss is computed depending on the model (see here).

Very likely your model uses mean squared error for the loss function, thus the mean_squared_error is also the loss variable.

Instead, the average_loss would be the loss averaged over the last N iterations, because sometimes the training is performed with small batch size and the loss might be noisy.


问:
Swift4: How to resolve "Fatal error: Can't form Range with upperBound < lowerBound"? (duration time delay in UI)
I try to close the menu animatedly using animation,
I decided to reduce the size of the UIScrollView on button press when size reduces up to my desired value, then I hide it.

to accomplish the task according to my desired user interface at some points, I had used the "time delay function" (300 milisec given)

everything goes well: if I don't press the button again and again until time limit reached

Error occurred: when i press button again and again before  with in 300 milisec

```<code>func disAppearBlanceMenu(){
    let x1 = btn_addBalance.clickableimg.frame.midX
    let y1 = btn_addBalance.clickableimg.frame.maxY

    UIView.animate(withDuration: 0.3) {
        self.BalanceMenu.scrollview.frame = CGRect(x: x1 - 150, y: y1 + 20, width: 200, height: 20)
    }
    time.delay(milliSec: 300) {
        self.BalanceMenu.triangle.isHidden = true
        self.BalanceMenu.scrollview.isHidden = true
        for i in 0...(self.BalanceMenuBtn.count - 1) {
            self.BalanceMenuBtn[i].imag.removeFromSuperview()
            self.BalanceMenuBtn[i].button.removeFromSuperview()
        }
        self.BalanceMenuBtn.removeAll()

    }
    displayBalanceMenu = true
}
</code>```

Where

```<code>class time {
    static func delay(milliSec:Int, code: @escaping () -> Void ) {
        let deadline = DispatchTime.now() + .milliseconds(milliSec)
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            code()
        }
    }
}
</code>```

The error occurs here:

```<code>time.delay(milliSec: 300) {
</code>```

It says

'Thread 1: Fatal error: Can't form Range with upperBound < lowerBound'

答:
In your code, you should add a condition before executing the for loop like this :

```<code>time.delay(milliSec: 300) {
            self.BalanceMenu.triangle.isHidden = true
            self.BalanceMenu.scrollview.isHidden = true
       if self.BalanceMenuBtn.count > 0 {
            for i in 0...(self.BalanceMenuBtn.count - 1) {
                self.BalanceMenuBtn[i].imag.removeFromSuperview()
                self.BalanceMenuBtn[i].button.removeFromSuperview()
            }
           self.BalanceMenuBtn.removeAll()
       }
    }
</code>```

You get this error when in for loop the lower bound is greater than the upper bound. In your code, when the first time the animation is completed then the count of the array will be 0 and for second time the condition would be like this

```<code>for I in 0...-1
</code>```

That is why you are getting a crash and by checking the condition of the count as shown in my answer this would not crash.

Hope this helps.

Body:
I try to close the menu animatedly using animation,
I decided to reduce the size of the UIScrollView on button press when size reduces up to my desired value, then I hide it.

to accomplish the task according to my desired user interface at some points, I had used the "time delay function" (300 milisec given)

everything goes well: if I don't press the button again and again until time limit reached

Error occurred: when i press button again and again before  with in 300 milisec

func disAppearBlanceMenu(){
    let x1 = btn_addBalance.clickableimg.frame.midX
    let y1 = btn_addBalance.clickableimg.frame.maxY

    UIView.animate(withDuration: 0.3) {
        self.BalanceMenu.scrollview.frame = CGRect(x: x1 - 150, y: y1 + 20, width: 200, height: 20)
    }
    time.delay(milliSec: 300) {
        self.BalanceMenu.triangle.isHidden = true
        self.BalanceMenu.scrollview.isHidden = true
        for i in 0...(self.BalanceMenuBtn.count - 1) {
            self.BalanceMenuBtn[i].imag.removeFromSuperview()
            self.BalanceMenuBtn[i].button.removeFromSuperview()
        }
        self.BalanceMenuBtn.removeAll()

    }
    displayBalanceMenu = true
}

Where

class time {
    static func delay(milliSec:Int, code: @escaping () -> Void ) {
        let deadline = DispatchTime.now() + .milliseconds(milliSec)
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            code()
        }
    }
}

The error occurs here:

time.delay(milliSec: 300) {

It says

'Thread 1: Fatal error: Can't form Range with upperBound < lowerBound'

Body:
In your code, you should add a condition before executing the for loop like this :

time.delay(milliSec: 300) {
            self.BalanceMenu.triangle.isHidden = true
            self.BalanceMenu.scrollview.isHidden = true
       if self.BalanceMenuBtn.count > 0 {
            for i in 0...(self.BalanceMenuBtn.count - 1) {
                self.BalanceMenuBtn[i].imag.removeFromSuperview()
                self.BalanceMenuBtn[i].button.removeFromSuperview()
            }
           self.BalanceMenuBtn.removeAll()
       }
    }

You get this error when in for loop the lower bound is greater than the upper bound. In your code, when the first time the animation is completed then the count of the array will be 0 and for second time the condition would be like this

for I in 0...-1

That is why you are getting a crash and by checking the condition of the count as shown in my answer this would not crash.

Hope this helps.


问:
Rotate screen in mac os with terminal
I want to rotate screen in mac os with the help of commands in terminal.I was able to do so in linux with xrandr commands but not in mac os.

答:
I wrote a terminal util for macOS that lets you rotate, change resolution, and position monitors on macOS. When I switched from Linux to macOS I really missed XRandR.

displayplacer - also available via Homebrew brew tap jakehilborn/jakehilborn && brew install displayplacer

Title: Rotate screen in mac os with terminal


问:
what is the most similar queue service in Azure to Aws SqS?
i am using AWS SqS and as part of migration to Azure i am testing Azure testing Azure queue https://learn.microsoft.com/en-us/azure/storage/queues/storage-python-how-to-use-queue-storage and also rabbitmq https://www.rabbitmq.com/tutorials/tutorial-one-python.html . the  App is in python so what is the most similar ? </p>

答:
There are many alternative available, i would recommend you to use Service bus queue.

```<code>from azure.servicebus import QueueClient, Message
</code>```

Create the QueueClient

```<code>queue_client = QueueClient.from_connection_string("<CONNECTION STRING>", "<QUEUE NAME>")
</code>```

Send a test message to the queue

```<code>msg = Message(b'Test Message')
queue_client.send(msg)
</code>```

Here is the documentation on how to get started with python.

Body:
There are many alternative available, i would recommend you to use Service bus queue.

from azure.servicebus import QueueClient, Message

Create the QueueClient

queue_client = QueueClient.from_connection_string("<CONNECTION STRING>", "<QUEUE NAME>")

Send a test message to the queue

msg = Message(b'Test Message')
queue_client.send(msg)

Here is the documentation on how to get started with python.


问:
why numpy.ndarray is object is not callable in my simple for python loop
I loaded a text file containing a two column matrix (e.g. below)

```<code>[ 1   3
  2   4
  3   5
  2   0]
</code>```

My calculation is just to sum each row i.e. 1+3, 2+4, 3+5 and 2+0. I am using the below code:

```<code>data=np.loadtxt(fname="textfile.txt")## to load the above two column
xy= data
for XY in xy:
   i=0
   Z=XY(i,0)+XY(i,1)
   i=i+1
   print (Z)
</code>```

But I received an error saying numpy.ndarray object is not callable. Why does this happen? How can I do this simple calculation? Thanks.

答: Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.</p>

Body:
I loaded a text file containing a two column matrix (e.g. below)

[ 1   3
  2   4
  3   5
  2   0]

My calculation is just to sum each row i.e. 1+3, 2+4, 3+5 and 2+0. I am using the below code:

data=np.loadtxt(fname="textfile.txt")## to load the above two column
xy= data
for XY in xy:
   i=0
   Z=XY(i,0)+XY(i,1)
   i=i+1
   print (Z)

But I received an error saying numpy.ndarray object is not callable. Why does this happen? How can I do this simple calculation? Thanks.


问:
Taking integer inputs from user to compute Python function
I have the function below, and I'm trying to modify it so that, it takes in Input parameter, "n" from the user.

```<code>def difference(xs):
    min_elem = xs[0]
    max_elem = xs[0]
    max_diff = -1

    for elem in xs[1:]:
        min_elem = min(elem, min_elem)
        if elem > max_elem:
            max_diff = max(max_diff, elem - min_elem)
            max_elem = elem

    return max_diff
</code>```

Currently it finds the maximum difference within an array. However, I would
like to have a function that can do:

```<code>difference(n, xs)
</code>```

Meaning, given a number, n (for example n=5) like the following:

```<code>difference(5, [1,2,3,4,5])
</code>```

the function should simply print out the array numbers line by line, and then output the difference that the function computes.

答:
You can do something like below. Just add one more function difference_with_input that will get the inputs from user and call the function that is already written, with the inputs entered.

```<code>
def difference(xs):
    min_elem = xs[0]
    max_elem = xs[0]
    max_diff = -1

    for elem in xs[1:]:
        min_elem = min(elem, min_elem)
        if elem > max_elem:
            max_diff = max(max_diff, elem - min_elem)
            max_elem = elem

    return max_diff

def difference_with_input(n):
    vals = []
    for i in range(1, n+1):
        vals.append(int(input("Enter value {0} : ".format(i))))
    print(difference(vals))

difference_with_input(5)

</code>```

Output:

```<code>Enter value 1 : 2
Enter value 2 : 1
Enter value 3 : 3
Enter value 4 : 4
Enter value 5 : 5
4
</code>```

Body:
I have the function below, and I'm trying to modify it so that, it takes in Input parameter, "n" from the user.

def difference(xs):
    min_elem = xs[0]
    max_elem = xs[0]
    max_diff = -1

    for elem in xs[1:]:
        min_elem = min(elem, min_elem)
        if elem > max_elem:
            max_diff = max(max_diff, elem - min_elem)
            max_elem = elem

    return max_diff

Currently it finds the maximum difference within an array. However, I would
like to have a function that can do:

difference(n, xs)

Meaning, given a number, n (for example n=5) like the following:

difference(5, [1,2,3,4,5])

the function should simply print out the array numbers line by line, and then output the difference that the function computes.

Body:
You can do something like below. Just add one more function difference_with_input that will get the inputs from user and call the function that is already written, with the inputs entered.

def difference(xs):
    min_elem = xs[0]
    max_elem = xs[0]
    max_diff = -1

    for elem in xs[1:]:
        min_elem = min(elem, min_elem)
        if elem > max_elem:
            max_diff = max(max_diff, elem - min_elem)
            max_elem = elem

    return max_diff

def difference_with_input(n):
    vals = []
    for i in range(1, n+1):
        vals.append(int(input("Enter value {0} : ".format(i))))
    print(difference(vals))

difference_with_input(5)

Output:

Enter value 1 : 2
Enter value 2 : 1
Enter value 3 : 3
Enter value 4 : 4
Enter value 5 : 5
4


问:
Why do we multiply calls to numpy.random.random by numbers and subtract numbers?
I found this snippet of code in an article about backpropagation and I got confused on how exactly it works. The article says the following

"This is our weight matrix for this neural network. It's called "syn0" to imply "synapse zero". Since we only have 2 layers (input and output), we only need one matrix of weights to connect them. Its dimension is (3,1) because we have 3 inputs and 1 output."

I want to specify that by input the author is referring to array "X" and output refers to array "Y".

My first question is why does the article claim we have only 3 inputs. A glance at the code reveals that our array, X, has size 4. Am I just misunderstanding something?

My second question is why are multiplying the call to np.random.random() by 2?

Thanks for the help!

```<code>import numpy as np

X = np.array([ [0,0,1],
               [0,1,1],
               [1,0,1],
               [1,1,1] ])

y = np.array([[0,0,1,1]]).T

# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1
</code>```

答:
The shape (3, 1) gives you a 3 by 1 matrix; 1 column in each of 3 rows. That’s only 3 values.

The multiplication and subtraction takes the range of values that numpy.random.random() produces to produce a broader range.

random() always produces floating point values between 0 and 1, and multiplying those by 2, then subtracting 1 means you now have values between -1 and 1, instead.

See the numpy.random.random() documentation:

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

```<code>(b - a) * random_sample() + a
</code>```

(Note that np.random.random() is an alias of np.random.random_sample())

So to produce values between a = -1 and b = 1 you need to multiply by b - a = 2 and then subtract 1 (+ -1).

You can try running the code in an interactive session:

```<code>>>> import numpy as np
>>> np.random.random((3, 1))  # a 3 x 1 matrix of values between 0 and 1
array([[0.11605033],
       [0.31756365],
       [0.4690499 ]])
>>> 2 * np.random.random((3, 1))  # a 3 x 1 matrix of values between 0 and 2
array([[1.30127808],
       [0.3982432 ],
       [1.96544242]])
>>> 2 * np.random.random((3, 1)) - 1  # a 3 x 1 matrix of values between -1 and 1
array([[ 0.39767412],
       [-0.83410998],
       [-0.62446309]])
</code>```

Body:
I found this snippet of code in an article about backpropagation and I got confused on how exactly it works. The article says the following

"This is our weight matrix for this neural network. It's called "syn0" to imply "synapse zero". Since we only have 2 layers (input and output), we only need one matrix of weights to connect them. Its dimension is (3,1) because we have 3 inputs and 1 output."

I want to specify that by input the author is referring to array "X" and output refers to array "Y".

My first question is why does the article claim we have only 3 inputs. A glance at the code reveals that our array, X, has size 4. Am I just misunderstanding something?

My second question is why are multiplying the call to np.random.random() by 2?

Thanks for the help!

import numpy as np

X = np.array([ [0,0,1],
               [0,1,1],
               [1,0,1],
               [1,1,1] ])

y = np.array([[0,0,1,1]]).T

# initialize weights randomly with mean 0
syn0 = 2*np.random.random((3,1)) - 1

Body:
The shape (3, 1) gives you a 3 by 1 matrix; 1 column in each of 3 rows. That’s only 3 values.

The multiplication and subtraction takes the range of values that numpy.random.random() produces to produce a broader range.

random() always produces floating point values between 0 and 1, and multiplying those by 2, then subtracting 1 means you now have values between -1 and 1, instead.

See the numpy.random.random() documentation:

Return random floats in the half-open interval [0.0, 1.0).

Results are from the “continuous uniform” distribution over the stated interval. To sample Unif[a, b), b > a multiply the output of random_sample by (b-a) and add a:

(b - a) * random_sample() + a

(Note that np.random.random() is an alias of np.random.random_sample())

So to produce values between a = -1 and b = 1 you need to multiply by b - a = 2 and then subtract 1 (+ -1).

You can try running the code in an interactive session:

>>> import numpy as np
>>> np.random.random((3, 1))  # a 3 x 1 matrix of values between 0 and 1
array([[0.11605033],
       [0.31756365],
       [0.4690499 ]])
>>> 2 * np.random.random((3, 1))  # a 3 x 1 matrix of values between 0 and 2
array([[1.30127808],
       [0.3982432 ],
       [1.96544242]])
>>> 2 * np.random.random((3, 1)) - 1  # a 3 x 1 matrix of values between -1 and 1
array([[ 0.39767412],
       [-0.83410998],
       [-0.62446309]])


问:
Custom field/column attribute for a model with relationships
I'm trying to figure out how to have to make a custom attribute when I'm setting up fields with relationship.

So I have students who are having a hasMany relationship with promotions. Now my problem is when the attribute that I want is in another model/table. For example I need the belt color, but the belt color is not stored in promotions.. promotion table holds just the belt_id. I need to extract the color of that belt from the belts table. I have all the relationships set up but I don't know how to manipulate the attribute. I hope this makes sense.

$this->crud->addField([
    'label' => "Promotions",
    'type' => 'select2_multiple',
    'name' => 'promotion',
    'entity' => 'promotion',
    'attribute' => 'name', // <- how can I make a custom query for this?
    'pivot' => true,
]);
```

Thank you!

答:
It looks like I found a solution and fixed a little bug.. at least It looks like to be a bug cuz I can't find the documentation for this feature.. I found it by inspecting the code. Anyway the cool thing is that we can chain relationships with ".", so the column setup will look like this:

$this->crud->addColumn([
   'label' => "Rank", // Table column heading
   'type' => "select",
   'name' => 'promotion_id', // the column that contains the ID of that connected entity;
   'entity' => 'promotion.belt', // <- here I'm chaining the model relationships
   'attribute' => 'color', // the belt's attribute
   'model' => "App\Models\Promotion" // foreign key model
]);
```

<p>In theory everything should work fine but there is a lil bug in a method located in <code>vendore\backpack\crud\src\CrudPanel.php</code>:</p>

<pre class="lang-php prettyprint-override"><code>private function getRelationModelInstances($model, $relationString)
{
    $relationArray = explode('.', $relationString);
    $firstRelationName = array_first($relationArray);

    // this is the line with the bug
    //$relation = $model->{$firstRelationName};

    // Fix the bug above
    if($model instanceof Collection) {
        $relation = $model->{$firstRelationName};
    } else {
        $relation = $model[$firstRelationName];
    }

    $results = [];
    if (! empty($relation)) {
        if ($relation instanceof Collection) {
            $currentResults = $relation->toArray();
        } else {
            $currentResults[] = $relation;
        }

        array_shift($relationArray);

        if (! empty($relationArray)) {
            foreach ($currentResults as $currentResult) {
                $results = array_merge($results, $this->getRelationModelInstances($currentResult, implode('.', $relationArray)));
            }
        } else {
            $results = $currentResults;
        }
    }

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

Basically this recursive function when is calling itself it passes the $model parameter as an array not object.. so when it s trying to get $firstRelationName from the $model like this $model->{$firstRelationName} will result in an error.

Meanwhile I discovered a better solution. To accomplish the same goal, I used accessors.

In my promotion model I have:

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */
     public function belt()
    {
        return $this->belongsTo('App\Models\Belt');
    }

    /*
    |--------------------------------------------------------------------------
    | ACCESORS
    |--------------------------------------------------------------------------
    */
    public function getPromotionSummaryAttribute()
    {
        return $this->belt()->get()[0]->color . ', ' . $this->stripe . ' stripe';
    }
```

<p>And for <code>students</code> I have:</p>

<pre class="lang-php prettyprint-override"><code>    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */
    public function promotion()
    {
        return $this->hasMany('App\Models\Promotion');
    }

    /*
    |--------------------------------------------------------------------------
    | ACCESORS
    |--------------------------------------------------------------------------
    */

    public function GetLastPromotionAttribute()
    {
        return $this->promotion()->get()->last()->promotion_summary;
    }
</code>```

And the column setup will be simple like this:

   $this->crud->addColumn([
        'name' => 'last_promotion',
        'type' => 'text',
        'label' => 'Rank'
   ]);
```

I hope this will help someone out there :)

Body:
I'm trying to figure out how to have to make a custom attribute when I'm setting up fields with relationship.

So I have students who are having a hasMany relationship with promotions. Now my problem is when the attribute that I want is in another model/table. For example I need the belt color, but the belt color is not stored in promotions.. promotion table holds just the belt_id. I need to extract the color of that belt from the belts table. I have all the relationships set up but I don't know how to manipulate the attribute. I hope this makes sense.

$this->crud->addField([
    'label' => "Promotions",
    'type' => 'select2_multiple',
    'name' => 'promotion',
    'entity' => 'promotion',
    'attribute' => 'name', // <- how can I make a custom query for this?
    'pivot' => true,
]);

Thank you!

Body:
It looks like I found a solution and fixed a little bug.. at least It looks like to be a bug cuz I can't find the documentation for this feature.. I found it by inspecting the code. Anyway the cool thing is that we can chain relationships with ".", so the column setup will look like this:

$this->crud->addColumn([
   'label' => "Rank", // Table column heading
   'type' => "select",
   'name' => 'promotion_id', // the column that contains the ID of that connected entity;
   'entity' => 'promotion.belt', // <- here I'm chaining the model relationships
   'attribute' => 'color', // the belt's attribute
   'model' => "App\Models\Promotion" // foreign key model
]);

In theory everything should work fine but there is a lil bug in a method located in vendore\backpack\crud\src\CrudPanel.php:

private function getRelationModelInstances($model, $relationString)
{
    $relationArray = explode('.', $relationString);
    $firstRelationName = array_first($relationArray);

    // this is the line with the bug
    //$relation = $model->{$firstRelationName};

    // Fix the bug above
    if($model instanceof Collection) {
        $relation = $model->{$firstRelationName};
    } else {
        $relation = $model[$firstRelationName];
    }

    $results = [];
    if (! empty($relation)) {
        if ($relation instanceof Collection) {
            $currentResults = $relation->toArray();
        } else {
            $currentResults[] = $relation;
        }

        array_shift($relationArray);

        if (! empty($relationArray)) {
            foreach ($currentResults as $currentResult) {
                $results = array_merge($results, $this->getRelationModelInstances($currentResult, implode('.', $relationArray)));
            }
        } else {
            $results = $currentResults;
        }
    }

    return $results;
}

Basically this recursive function when is calling itself it passes the $model parameter as an array not object.. so when it s trying to get $firstRelationName from the $model like this $model->{$firstRelationName} will result in an error.

Meanwhile I discovered a better solution. To accomplish the same goal, I used accessors.

In my promotion model I have:

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */
     public function belt()
    {
        return $this->belongsTo('App\Models\Belt');
    }

    /*
    |--------------------------------------------------------------------------
    | ACCESORS
    |--------------------------------------------------------------------------
    */
    public function getPromotionSummaryAttribute()
    {
        return $this->belt()->get()[0]->color . ', ' . $this->stripe . ' stripe';
    }

And for students I have:

    /*
    |--------------------------------------------------------------------------
    | RELATIONS
    |--------------------------------------------------------------------------
    */
    public function promotion()
    {
        return $this->hasMany('App\Models\Promotion');
    }

    /*
    |--------------------------------------------------------------------------
    | ACCESORS
    |--------------------------------------------------------------------------
    */

    public function GetLastPromotionAttribute()
    {
        return $this->promotion()->get()->last()->promotion_summary;
    }

And the column setup will be simple like this:

   $this->crud->addColumn([
        'name' => 'last_promotion',
        'type' => 'text',
        'label' => 'Rank'
   ]);

I hope this will help someone out there :)


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答:
It is probably better to use a different algorithm, but you could optimise this code pretty easily as well.

This function will be twice as fast:

```<code>def is_prime(n):
    import math
    n = abs(n)
    if n % 2 == 0:
        return False
    i = 3
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 2

    return True
</code>```

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break

Body:
It is probably better to use a different algorithm, but you could optimise this code pretty easily as well.

This function will be twice as fast:

def is_prime(n):
    import math
    n = abs(n)
    if n % 2 == 0:
        return False
    i = 3
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 2

    return True


问:
How to extract numbers from a string and add to an array?
I want to convert this string:

```<code><5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>
</code>```

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

```<code>$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");
</code>```

Response: String could not be parsed as XML

I expect an array like this:

```<code>[5=>20825.24,7=>0.0,8=>0.0]
</code>```

答:
Here, we can also use a regular expression and collect our desired numbers, then push it to a new array:

```<code>(?:<)(\d?)(?:>)(?:.+?)([0-9.]+)?
</code>```

This expression might also work with nested elements.

Test

```<code>$re = '/(?:<)(\d?)(?:>)(?:.+?)([0-9.]+)?/m';
$str = '<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$arr = array();
foreach ($matches as $key => $value) {
    $arr[$value[1]] = $value[2];
}

var_dump($arr);
</code>```

Output

```<code>array(3) {
  [5]=>
  string(8) "20825.24"
  [7]=>
  string(3) "0.0"
  [8]=>
  string(3) "0.0"
}
</code>```

DEMO

RegEx Circuit

jex.im visualizes regular expressions:

Body:
I want to convert this string:

<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>

to an array with key value

I would really appreciate the help

I tried different xmlParse strategies but it is not exactly an xml.

$xml = new \SimpleXMLElement("<5>20825.24</5><7>0.0</ 7><8>0.0</8>");

Response: String could not be parsed as XML

I expect an array like this:

[5=>20825.24,7=>0.0,8=>0.0]

Body:
Here, we can also use a regular expression and collect our desired numbers, then push it to a new array:

(?:<)(\d?)(?:>)(?:.+?)([0-9.]+)?

This expression might also work with nested elements.

Test

$re = '/(?:<)(\d?)(?:>)(?:.+?)([0-9.]+)?/m';
$str = '<5> 20825.24 </ 5> <7> 0.0 </ 7> <8> 0.0 </ 8>';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

$arr = array();
foreach ($matches as $key => $value) {
    $arr[$value[1]] = $value[2];
}

var_dump($arr);

Output

array(3) {
  [5]=>
  string(8) "20825.24"
  [7]=>
  string(3) "0.0"
  [8]=>
  string(3) "0.0"
}

DEMO

RegEx Circuit

jex.im visualizes regular expressions:


问:
Can I control the execution order of VUnit testbenches?
I have several VUnit unit testbenches and a single top level testbench in my design projects. VUnit finds all my testbenches and executes them. I would like to control the order the testbenches are executed, so I can have the shorter testbenches execute first. Is this a feature available in VUnit?</p>

答:
No, there is no such feature but it would be possible to create a script that takes the previous test report, extracts timing information and run tests one by one in timing order.

I think you should open an issue for this on Github to get better built in support. There are also other related features that would be interesting, for example load balancing when running multiple threads.


问:
How to XOR scramble a string in C and back again with the same function?
I am trying to obfuscate a string in a program. Currently, I only have a simple string reversal working. I would like to be able to perform XOR scrambling on the data to make it much more secure, however the method I have tried is not working.

The same function and input type is used to decode the string. This is no problem with string reversal, as it just reverses back, but can this be done easily with XORing without getting too complex? I would prefer if the process kept just the one string, like the reversal does. Here is my reversal function.

```<code>void reverse_string(unsigned char *buf, int length)
{
int i;
unsigned char temp;

    for (i = 0; i < length / 2; i++)
    {
        temp = buf[i];
        buf[i] = buf[length - i - 1];
        buf[length - i - 1] = temp;
    }
}
</code>```

And here is the attempt at a XOR function

```<code>void charxor(char * text, int len) {
const unsigned char enc[8]={173,135,131,121,110,119,187,143};
char ch;
int i;
int ind=0;
for (i=0;i<len;i++) {
    ch=*text++;
    if (ch)
        *text = ch ^ enc[ind++];
    ind %=8;
}

}
</code>```

Can anyone help? Would be much appreciated!

答:
this is a pbox, it would require you to make a non repeating integer key - random - same size as said block. the last block would start with the offset which could be just random data.  Doesn't cover null terminators so decide where the data is going / what your doing with it. you could realloc(buff, "A") to use memmove. make 3 64 bit boxes, and a subset of 16 4 bit boxes from the output of the 64 and it starts to look like a poor implementation of des, which openssl has build into it.  The fundamental advantage is being able to encrypt/decrypt with the same function / address space.  This could also allow you to encrypt in place without a extra buffer.  KSZ is the length of your block(s)/key

```<code>char
*zecr
(bff, zbf, ky, ze)
 char *bff;
 char *zbf;
 unsigned int ky[];
 short ze;
{
/* main encrypt decrypt function */

int i=0;
while( i < KSZ ) {
 int dx = ky[i];

 if( ze == 1 ) {            // encrypt
    char c = bff[dx];
    sprintf(zbf + i, "%c", c);

 } else {                   // decrypt
    char c = bff[i];
    char tk[1] = "";
    sprintf(tk, "%c", c);
    memmove(zbf +dx,  tk, 1);
 }

 i++;
}

return zbf;
}
</code>```

xoring is a binary operation, which will yield vastly different results depending on how you cast it.  You got the right idea using ocdec but if the idea is to keep it simple im going to assume you don't actually know assembly despite the requested reference,  stick with c calls its simpler for how you are most likely going to be using the data.

-the female orgasm, that's the myth.  -SUN TZU

Body:
I am trying to obfuscate a string in a program. Currently, I only have a simple string reversal working. I would like to be able to perform XOR scrambling on the data to make it much more secure, however the method I have tried is not working.

The same function and input type is used to decode the string. This is no problem with string reversal, as it just reverses back, but can this be done easily with XORing without getting too complex? I would prefer if the process kept just the one string, like the reversal does. Here is my reversal function.

void reverse_string(unsigned char *buf, int length)
{
int i;
unsigned char temp;

    for (i = 0; i < length / 2; i++)
    {
        temp = buf[i];
        buf[i] = buf[length - i - 1];
        buf[length - i - 1] = temp;
    }
}

And here is the attempt at a XOR function

void charxor(char * text, int len) {
const unsigned char enc[8]={173,135,131,121,110,119,187,143};
char ch;
int i;
int ind=0;
for (i=0;i<len;i++) {
    ch=*text++;
    if (ch)
        *text = ch ^ enc[ind++];
    ind %=8;
}

}

Can anyone help? Would be much appreciated!

Body:
this is a pbox, it would require you to make a non repeating integer key - random - same size as said block. the last block would start with the offset which could be just random data.  Doesn't cover null terminators so decide where the data is going / what your doing with it. you could realloc(buff, "A") to use memmove. make 3 64 bit boxes, and a subset of 16 4 bit boxes from the output of the 64 and it starts to look like a poor implementation of des, which openssl has build into it.  The fundamental advantage is being able to encrypt/decrypt with the same function / address space.  This could also allow you to encrypt in place without a extra buffer.  KSZ is the length of your block(s)/key

char
*zecr
(bff, zbf, ky, ze)
 char *bff;
 char *zbf;
 unsigned int ky[];
 short ze;
{
/* main encrypt decrypt function */

int i=0;
while( i < KSZ ) {
 int dx = ky[i];

 if( ze == 1 ) {            // encrypt
    char c = bff[dx];
    sprintf(zbf + i, "%c", c);

 } else {                   // decrypt
    char c = bff[i];
    char tk[1] = "";
    sprintf(tk, "%c", c);
    memmove(zbf +dx,  tk, 1);
 }

 i++;
}

return zbf;
}

xoring is a binary operation, which will yield vastly different results depending on how you cast it.  You got the right idea using ocdec but if the idea is to keep it simple im going to assume you don't actually know assembly despite the requested reference,  stick with c calls its simpler for how you are most likely going to be using the data.

-the female orgasm, that's the myth.  -SUN TZU


问:
Why is db.findAll() is not a function?
I create and instance of database with sequelize, but it does not have methods like findAll(). What am i doing wrong?

```<code>const Sequelize = require('sequelize');
const router = require('express').Router();

const db = new Sequelize('web-prog', 'postgres', '1234', {
    host: 'localhost',
    dialect: 'postgres',
    logging: false
});

router.get('/', (req, res) => {
    db
        .findAll()
        .then(itemlist => res.json(itemlist))
        .catch(err => console.log(err))
});

module.exports = { db, router };
</code>```

//then i require it like this

```<code>const db = require('./database').db;
</code>```

TypeError: db.findAll is not a function

答:
You are trying to call findAll() on the Sequelize connection, however this method is found on the Model which is why you are getting the error.

Create a Model called MyModel

```<code>module.exports = function Model(db, DataTypes) {
  const MyModel = db.define('myModel', {/* fields */, {/* options */});
  return MyModel;
}
</code>```

Then you would load the models -

```<code>  const db = require('./database').db;
  const myModel = db.import(path.join(__dirname, '/', 'myModel'));
  myModel.findAll() <-- this will exist and return a promise
</code>```

Title: Why is db.findAll() is not a function?

Body:
I create and instance of database with sequelize, but it does not have methods like findAll(). What am i doing wrong?

const Sequelize = require('sequelize');
const router = require('express').Router();

const db = new Sequelize('web-prog', 'postgres', '1234', {
    host: 'localhost',
    dialect: 'postgres',
    logging: false
});

router.get('/', (req, res) => {
    db
        .findAll()
        .then(itemlist => res.json(itemlist))
        .catch(err => console.log(err))
});

module.exports = { db, router };

//then i require it like this

const db = require('./database').db;

TypeError: db.findAll is not a function

Body:
You are trying to call findAll() on the Sequelize connection, however this method is found on the Model which is why you are getting the error.

Create a Model called MyModel

module.exports = function Model(db, DataTypes) {
  const MyModel = db.define('myModel', {/* fields */, {/* options */});
  return MyModel;
}

Then you would load the models -

  const db = require('./database').db;
  const myModel = db.import(path.join(__dirname, '/', 'myModel'));
  myModel.findAll() <-- this will exist and return a promise


问:
How to prove intersection of two non-equal singleton sets is empty
I've boiled down the meat of a proof to a few statements that the intersection of two distinct singleton sets are empty, but am not able to prove this seemingly simple fact.

I've looked through the library of Ensembles, Powerset Facts, Constructive Sets and the like, but haven't been able to find anything that turns out to be useful.

```<code>Require Import Coq.Sets.Ensembles.
Require Import Coq.Strings.String.

Example x: string := "x".
Example y: string := "y".

Lemma ex:
Intersection string (Singleton string x)
  (Singleton string y) = Empty_set string.
Proof.
  ???
</code>```

答:
The key is to use the extensionality axiom:</p>

```<code>Require Import Coq.Sets.Ensembles.
Require Import Coq.Strings.String.

Example x: string := "x".
Example y: string := "y".

Lemma ex:
Intersection string (Singleton string x)
  (Singleton string y) = Empty_set string.
Proof.
apply Extensionality_Ensembles. split.
- intros _ [b Ha Hb].
  inversion Ha. inversion Hb. unfold x, y in *. congruence.
- now intros _ [].
Qed.
</code>```

Body:
I've boiled down the meat of a proof to a few statements that the intersection of two distinct singleton sets are empty, but am not able to prove this seemingly simple fact.

I've looked through the library of Ensembles, Powerset Facts, Constructive Sets and the like, but haven't been able to find anything that turns out to be useful.

Require Import Coq.Sets.Ensembles.
Require Import Coq.Strings.String.

Example x: string := "x".
Example y: string := "y".

Lemma ex:
Intersection string (Singleton string x)
  (Singleton string y) = Empty_set string.
Proof.
  ???

Body:
The key is to use the extensionality axiom:

Require Import Coq.Sets.Ensembles.
Require Import Coq.Strings.String.

Example x: string := "x".
Example y: string := "y".

Lemma ex:
Intersection string (Singleton string x)
  (Singleton string y) = Empty_set string.
Proof.
apply Extensionality_Ensembles. split.
- intros _ [b Ha Hb].
  inversion Ha. inversion Hb. unfold x, y in *. congruence.
- now intros _ [].
Qed.


问:
Modifying dictionary inside function without return statement
I'm trying to modify a dictionary inside a function. And since dictionaries are mutable data types. I was wondering if a return statement is necessary?

e.g:

```<code>def modify_dict(a_dict,a_key,a_value):
    a_dict = {a_key:a_value}

# Why wouldn't the function actually modify the dictionary?
# Wouldn't the dictionary still be changed to sample_dict={e_key:e_value} anyways?

sample_dict = {b_key:b_value,c_key:c_value,d_key:d_value}
modify_dict(sample_dict,e_key,e_value)
</code>```

答:
Your modify dict is not modifying the variable. It is rebinding it.

Try:

```<code>def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value
</code>```

And No.. you don't need to "return".

Body:
I'm trying to modify a dictionary inside a function. And since dictionaries are mutable data types. I was wondering if a return statement is necessary?

e.g:

def modify_dict(a_dict,a_key,a_value):
    a_dict = {a_key:a_value}

# Why wouldn't the function actually modify the dictionary?
# Wouldn't the dictionary still be changed to sample_dict={e_key:e_value} anyways?

sample_dict = {b_key:b_value,c_key:c_value,d_key:d_value}
modify_dict(sample_dict,e_key,e_value)

Body:
Your modify dict is not modifying the variable. It is rebinding it.

Try:

def modify_dict(a_dict,a_key,a_value):
    a_dict[a_key] = a_value

And No.. you don't need to "return".


答: When you're reassigning a_dict inside the function you're actually creating a new dictionary that has the same name as the one outside of the function scope. If you update the dictionary, the change would be visible outside of the function scope, but you're reassigning the name.

Title: Modifying dictionary inside function without return statement


答:
While you can modify a dict in place, you're assigning the stack variable a_dict to a new dictionary, which is different than changing a value in the dict. You want something more like:

test = {'k1': 'v1', 'k2': 'v2'}
def changes_dict(d, k, new_v):
    d[k] = new_v

changes_dict(test, 'k1', 'changed')
test['k1']
# 'changed'
```


问:
What is the best practice of updating child relationship rows of a state?
hope you all well, am working on updating a Linear persistent Corda state that has some entity relationships attached to it.

But am getting an issue of Hibernate "Unique index or primary key violation" on persisting updated state details in my update Flow.

-> Am wondering if I should create different entity relationships table IDs for rows of the new updated state and children rows information.

-> OR If you can give me the best practice of updating child contract state relations table rows of a state.

Any help will be appreciated thank you

答:
You may take a look at the https://docs.corda.net/api-persistence.html#schemas.
The Corda Site Provides a suitable example to  achieve you requirement.
In case this doesn't solve your query a code snippet of your Schema representation would help .</p>


问:
Drupal: sidebar only shown on build/block page
I added a sidebar to my admin theme in Drupal. The sidebar is shown correctly on the /admin/build/block/list/* pages but not in the other pages.

I am using the fubik theme, a theme close to rubik but with the ability to display sidebars.

I checked the page.tpl.php page, and it seems the $left variable is empty (on the pages that are not /admin/build/block/list/* pages), but I set two blocks to be displayed in that sidebar.

Am I missing a configuration step?

答:
All the regions will be shown in admin/build/block/list/* pages irrespective of whether they have any content(any blocks). ie even if there is no content to be shown these blocks will be highlighted and shown.

Whereas in other pages, the regions will only be shown if they have some content to be shown.

In your case though you have enabled the blocks it is not being shown, the reason may be that the blocks you have enabled don't have any content in them.
Try putting some blocks with static content.

Even then if it doesn't show up, then may be you are enabling the blocks in the wrong theme. Make sure that you are enabling them in the right theme.


问:
SQL Server Complex Add/Update merge million rows daily
I have 7 reports which are downloaded daily at late night.

These reports can be downloaded in csv/xml. I am downloading them csv format as they are memory efficient.

This process runs in background and is managed by hangfire.

After they are downloaded, I am using dapper to run a stored procedure which insert/update/update data using merge statements. This stored procedure has seven table value parameters.

Instead of delete, I am updating that record's IsActive column to false.

Note that 2 reports have more than 1 million records.

I am getting timeout exceptions only in Azure SQL. In SQL Server, it works fine. As a workaround, I have increased timeouts to 1000 for this query.

This app is running in Azure s2.

I have pondered over the option of sending xml but I have found SQL Server is slow at processing xml which counter productive.

I can not also use SqlBulkCopy as I have to update based on some conditions.

Also note that more reports will be added in future.

Also when a new report is added then there are large amount of inserts. If previously added report is ran again then majority updates are run.

These tables currently do not have any indexes, only clustered integer primary key.

Each row has a unique code. This code is used to identify whether to insert/update/delete

Can you recommend a way to increase performance?

答: Is your source inputting the whole data? Whether they are updated/new. I assume by saying the unique code(insert/update/delete) you are only considering changes (Delta). If not that's one area. Another is to consider parallelism. I think then you need to have different stored procedures for each table. Non dependent tables could be processed together</p>


问:
Want to loop through a json array after selecting a dropdown box list
I want to be able to select a list of options from a dropdown box with "Station" values taken from json array -"smallData.json" (which I am able to do and it is working) and then produce a set of results from the same json array based on the specific "station" option chosen from the dropdown list (which is not working currently). I assume I may need a function to be called and loop through the array with the onchange method, however, I am not certain how that would work.

```<code>[
 {
   "ID": 1,
   "Station": "Carmichael Rd.",
   "Address": "54 Myers Rd.",
   "Monthly_CStore_Sales": "120,000",
   "Operator": "Michael Sears",
   "Top_SKU": "Hotdogs"
 },
 {
   "ID": 2,
   "Station": "Baillou Hill",
   "Address": "564 Jackson Ave.",
   "Monthly_CStore_Sales": "89000",
   "Operator": "Sarah Pikes",
   "Top_SKU": "Patties"
 },
 {
   "ID": 3,
   "Station": "Oakesfield",
   "Address": "42 Peterson St.",
   "Monthly_CStore_Sales": "150000",
   "Operator": "Yolanda Gray",
   "Top_SKU": "Chicken"
 }
 ]
</code>```

Code

```<code><select id="dmenu"></select>
<div id="optionT"></div>

<script>
let dropdown = document.getElementById('dmenu');
dropdown.length = 0;

let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Station';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

const url = './smallData.json';

const request = new XMLHttpRequest();
request.open('GET', url, true);

request.onload = function() {
  if (request.status === 200) {
    const data = JSON.parse(request.responseText);
    let option;
    for (let i = 0; i < data.length; i++) {
      option = document.createElement('option');
      option.text = data[i].Station;

      dropdown.add(option);

      var optionText = "";
      for (x in data){
          optionText += '<ul>' +

            '<li>Station: '+ data.Station[x] +'</li>' +

            document.getElementById('optionT').innerHTML = optionText;
      }

    } else {
    // Reached the server, but it returned an error

}
}
request.onerror = function() {
  console.error('An error occurred fetching the JSON from ' + url);
};

request.send();
</script>
</code>```

Example:
If I select for example: "Station Carmichael Road", all the key value pairs associated with that Station field I want to come up:

```<code> "ID:1",
   "Address": "54 Myers Rd.",
   "Monthly_CStore_Sales": "120,000",
   "Operator": "Michael Sears",
   "Top_SKU": "Hotdogs"
</code>```

答:
You want to show Station's data when a drop-down option is selected.

Add onchange event on your drop-down element.

```<code><select id="dmenu" onchange="handleOnChange(this)"></select>
</code>```

Then move your list-rendering logic to handleOnChange()

```<code>function handleOnChange(selectedDropdown) {
    // Find array element by "Station" value
    var station = data.find(function(element) {
        return element.Station == selectedDropdown.value;
    });

    // If station exists
    if (station) {
        // Show station's key-value in list
        let optionText = '<ul>';

        Object.keys(station).forEach(function(key) {
            optionText += '<li>' + key +': ' + station[key] +  '</li>';
            document.getElementById('optionT').innerHTML = optionText;
        });

        optionText += '</ul>';
    }
}
</code>```

Full Code

```<code><script>
function handleOnChange(selectedDropdown) {
    // Find array element by "Station" value
    var station = data.find(function(element) {
        return element.Station == selectedDropdown.value;
    });

    // If station exists
    if (station) {
        // Show station's key-value in list
        let optionText = '<ul>';

        Object.keys(station).forEach(function(key) {
            optionText += '<li>' + key +': ' + station[key] +  '</li>';
            document.getElementById('optionT').innerHTML = optionText;
        });

        optionText += '</ul>';
    }
}

let dropdown = document.getElementById('dmenu');
dropdown.length = 0;

let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Station';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

const url = './smallData.json';
let data;

const request = new XMLHttpRequest();
request.open('GET', url, true);

request.onload = function() {
    if (request.status === 200) {
        data = JSON.parse(request.responseText);
        let option;

        for (let i = 0; i < data.length; i++) {
            option = document.createElement('option');
            option.text = data[i].Station;

            dropdown.add(option);
        }
    }
    else {
        // Reached the server, but it returned an error
    }
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};

request.send();
</script>
</code>```

Body:
I want to be able to select a list of options from a dropdown box with "Station" values taken from json array -"smallData.json" (which I am able to do and it is working) and then produce a set of results from the same json array based on the specific "station" option chosen from the dropdown list (which is not working currently). I assume I may need a function to be called and loop through the array with the onchange method, however, I am not certain how that would work.

[
 {
   "ID": 1,
   "Station": "Carmichael Rd.",
   "Address": "54 Myers Rd.",
   "Monthly_CStore_Sales": "120,000",
   "Operator": "Michael Sears",
   "Top_SKU": "Hotdogs"
 },
 {
   "ID": 2,
   "Station": "Baillou Hill",
   "Address": "564 Jackson Ave.",
   "Monthly_CStore_Sales": "89000",
   "Operator": "Sarah Pikes",
   "Top_SKU": "Patties"
 },
 {
   "ID": 3,
   "Station": "Oakesfield",
   "Address": "42 Peterson St.",
   "Monthly_CStore_Sales": "150000",
   "Operator": "Yolanda Gray",
   "Top_SKU": "Chicken"
 }
 ]

Code

<select id="dmenu"></select>

Example:
If I select for example: "Station Carmichael Road", all the key value pairs associated with that Station field I want to come up:

 "ID:1",
   "Address": "54 Myers Rd.",
   "Monthly_CStore_Sales": "120,000",
   "Operator": "Michael Sears",
   "Top_SKU": "Hotdogs"

Body:
You want to show Station's data when a drop-down option is selected.

Add onchange event on your drop-down element.

<select id="dmenu" onchange="handleOnChange(this)"></select>

Then move your list-rendering logic to handleOnChange()

function handleOnChange(selectedDropdown) {
    // Find array element by "Station" value
    var station = data.find(function(element) {
        return element.Station == selectedDropdown.value;
    });

    // If station exists
    if (station) {
        // Show station's key-value in list
        let optionText = '<ul>';

        Object.keys(station).forEach(function(key) {
            optionText += '<li>' + key +': ' + station[key] +  '</li>';
            document.getElementById('optionT').innerHTML = optionText;
        });

        optionText += '</ul>';
    }
}

Full Code

<script>
function handleOnChange(selectedDropdown) {
    // Find array element by "Station" value
    var station = data.find(function(element) {
        return element.Station == selectedDropdown.value;
    });

    // If station exists
    if (station) {
        // Show station's key-value in list
        let optionText = '<ul>';

        Object.keys(station).forEach(function(key) {
            optionText += '<li>' + key +': ' + station[key] +  '</li>';
            document.getElementById('optionT').innerHTML = optionText;
        });

        optionText += '</ul>';
    }
}

let dropdown = document.getElementById('dmenu');
dropdown.length = 0;

let defaultOption = document.createElement('option');
defaultOption.text = 'Choose Station';

dropdown.add(defaultOption);
dropdown.selectedIndex = 0;

const url = './smallData.json';
let data;

const request = new XMLHttpRequest();
request.open('GET', url, true);

request.onload = function() {
    if (request.status === 200) {
        data = JSON.parse(request.responseText);
        let option;

        for (let i = 0; i < data.length; i++) {
            option = document.createElement('option');
            option.text = data[i].Station;

            dropdown.add(option);
        }
    }
    else {
        // Reached the server, but it returned an error
    }
}
request.onerror = function() {
console.error('An error occurred fetching the JSON from ' + url);
};

request.send();
</script>


问:
Django : How can I find a list of models that the ORM knows?
In Django, is there a place I can get a list of or look up the models that the ORM knows about?</p>

答:
If you want a dictionary with all models you can use:</p>

```<code>from django.apps import apps

models = {
    model.__name__: model for model in apps.get_models()
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If you want a dictionary with all models you can use:

from django.apps import apps

models = {
    model.__name__: model for model in apps.get_models()
}


问:
applications of mutation testing
what are different applications of mutation testing?</p>

答:
Mutation testing is used to "test your test cases".  The idea is to make small mutations to your application and then run your tests to make sure they catch the bugs added by these mutations.

There is a good explanation with examples posted here.

Title: applications of mutation testing


问:
Why does Twilio call forwarding operate differently than carrier call forwarding?
From what I understand, there is a difference between how Twilio handles call forwarding and how the telcom carriers do it.

In the first situation, for standard carrier forwarding, say A calls B.  The call gets forwarded to C if either B doesn't answer (conditional call forwarding) or they've set up to always forward (unconditional call forwarding).  In other words, the call is routed from the red line to the purple.  This is done on the carrier side (B's phone does not even need to be on for this to work).

However, in the case with Twilio, if A is already talking to Twilio (purple path) and application logic decides it is OK to connect A to C (same final result as with the first situation), it does this by passing through Twilio (green path).  Twilio calls this Call Forwarding even though it does not behave the same way as before.  In this case, there is a middleman in the picture (Twilio), and Twilio also charges you for both the ingoing and outgoing legs.

Is it possible for Twilio to forward the call such that it just takes the blue path, and connects A to C directly?  Or am I missing something?

答:
Twilio Programmable Voice uses Twilio Markup Language (TwiML) to control the call flow. If you call your Twilio number and want to forward that call to an end-point off Twilio, Twilio still remains in the signaling and media path, which allows you to remain in control of the call, which is the key part of why that call path is the way it is.

There is no way to remove Twilio from this call flow, as Programmable Voice depends on Twilio remaining in the call path.

Setting Up Call Forwarding


问:
How to clear a file using FILE*
I am developing a study project. It includes registration, authorization, and saving records of customer. In my project reading the information from file using fstream is not working so I use FILE* method. And I need to clear all data in file to rewrite it for saving new records.

There is a question. How to clear it? I found a lot of examples how to do this but all of their are for using fstream. Is it real to do using FILE* ?

Here is some code:

```<code>FILE* Usrs = fopen("Users.dat", "rb");
        StructForReg Array[100];
        StructForReg Perenos;
        int i = 0;
        while (!!(feof(Usrs) == 0))
        {
            fread(&Perenos, sizeof(StructForReg), 15, Usrs);
            Array[i] = Perenos;
            i += 1;
        }
        fclose(Usrs);
//here must be a code with clearing and rewriting
</code>```

答:
How to clear a file using FILE*?

And I need to clear all data in file to rewrite it for saving new records.

Just open with using "w" (or "wb") mode. From cppreference the w mode destroys file contents if the file exists. If the file does not exists, it will create a new one.

Title: How to clear a file using FILE*

Body:
I am developing a study project. It includes registration, authorization, and saving records of customer. In my project reading the information from file using fstream is not working so I use FILE* method. And I need to clear all data in file to rewrite it for saving new records.

There is a question. How to clear it? I found a lot of examples how to do this but all of their are for using fstream. Is it real to do using FILE* ?

Here is some code:

FILE* Usrs = fopen("Users.dat", "rb");
        StructForReg Array[100];
        StructForReg Perenos;
        int i = 0;
        while (!!(feof(Usrs) == 0))
        {
            fread(&Perenos, sizeof(StructForReg), 15, Usrs);
            Array[i] = Perenos;
            i += 1;
        }
        fclose(Usrs);
//here must be a code with clearing and rewriting


问:
Is there a way to check for a word within cell?
I am looking for a way to check if a cell contains text in Google Apps Script and Google Sheets.</p>

```<code>var cell = "Joe, Bob, Tim, John"

//I would want this to execute
if(cell contains "Tim") {
//code
}
</code>```

答:
Recently, a TextFinder class was has been added to the SpreadsheetApp service that allows you to do this on a live Range (or Sheet or even a Spreadsheet itself). See documentation for more details. Simply set the finder on a context with a createTextFinder() with the text you want to find as an argument.
Calling a findNext() method on the resulting TextFinder instance will either return the Range it was called on or null if nothing was found. For example:

```<code>function findText() {

  var sh = getSheet(); //custom function that returns target Sheet;
  var rng = sh.getRange(1,1); //change to desired Range boundaries;

  //create TextFinder and configure;
  var tf = rng.createTextFinder('textToFind');
      tf.matchCase(false); //{Boolean} -> match target text's case or not;
      tf.matchEntireCell(false); //{Boolean} -> check the whole Range or within;
      tf.ignoreDiacritics(true); //{Boolean} -> ignore diacretic signs during match;
      tf.matchFormulaText(false); //{Boolean} -> search in formulas (if any) or values;

  //invoke search;
  var res = tf.findNext();

  //do something with result;
  if(res!==null) {
    var vals = res.getValues();
    Logger.log(vals);
  }

}
</code>```

Body:
I am looking for a way to check if a cell contains text in Google Apps Script and Google Sheets.

var cell = "Joe, Bob, Tim, John"

//I would want this to execute
if(cell contains "Tim") {
//code
}

Body:
Recently, a TextFinder class was has been added to the SpreadsheetApp service that allows you to do this on a live Range (or Sheet or even a Spreadsheet itself). See documentation for more details. Simply set the finder on a context with a createTextFinder() with the text you want to find as an argument.
Calling a findNext() method on the resulting TextFinder instance will either return the Range it was called on or null if nothing was found. For example:

function findText() {

  var sh = getSheet(); //custom function that returns target Sheet;
  var rng = sh.getRange(1,1); //change to desired Range boundaries;

  //create TextFinder and configure;
  var tf = rng.createTextFinder('textToFind');
      tf.matchCase(false); //{Boolean} -> match target text's case or not;
      tf.matchEntireCell(false); //{Boolean} -> check the whole Range or within;
      tf.ignoreDiacritics(true); //{Boolean} -> ignore diacretic signs during match;
      tf.matchFormulaText(false); //{Boolean} -> search in formulas (if any) or values;

  //invoke search;
  var res = tf.findNext();

  //do something with result;
  if(res!==null) {
    var vals = res.getValues();
    Logger.log(vals);
  }

}


答: See the manpage for fopen. "w" or "w+" in the flags causes the file to get truncated.

Title: How to clear a file using FILE*


问:
Assign max value of group to all rows in that group
I would like to assign the max value of a group to all rows within that group. How do I do that?

I have a dataframe containing the names of the group and the max number of credits that belongs to it.

course_credits <- aggregate(bsc_academic$Credits, by = list(bsc_academic$Course_code), max)
```

<p>which gives</p>

<pre class="lang-r prettyprint-override"><code>    Course    Credits
1   ABC1000  6.5
2   ABC1003  6.5
3   ABC1004  6.5
4   ABC1007  5.0
5   ABC1010  6.5
6   ABC1021  6.5
7   ABC1023  6.5
</code>```

The main dataframe looks like this:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Final result       0       6.5    ABC1000           10
Final result       0       6.5    ABC1003           10
Grade supervisor   0       0      ABC1000           10
Grade supervisor   0       0      ABC1003           10
Final result       0       12     ABC1294           23
Grade supervisor   0       0      ABC1294           23
```

<p>As you see, student 10 took course ABC1000, worth 6.5 credits. For each course (per student), however, two rows exist: Final result and Grade supervisor. In the end, Final result should be deleted, but the credits should be kept. Therefore, I want to assign the max value of 6.5 to the Grade supervisor row.
Likewise, student 23 has followed course ABC1294, worth 12 credits. </p>

<p>In the end, this should be the result: </p>

<pre class="lang-r prettyprint-override"><code>Appraisal.Type   Resits   Credits Course_code   Student_ID
Grade supervisor   0       6.5      ABC1000           10
Grade supervisor   0       6.5      ABC1003           10
Grade supervisor   0       12       ABC1294           23
</code>```

How do I go about this?

答:
Here's a data.table solution,

```<code>DT[,Credits := max(Credits),by=Student_ID]
Result <- DT[Appraisal.Type == "Grade supervisor"]
</code>```

Body:
I would like to assign the max value of a group to all rows within that group. How do I do that?

I have a dataframe containing the names of the group and the max number of credits that belongs to it.

course_credits <- aggregate(bsc_academic$Credits, by = list(bsc_academic$Course_code), max)

which gives

    Course    Credits
1   ABC1000  6.5
2   ABC1003  6.5
3   ABC1004  6.5
4   ABC1007  5.0
5   ABC1010  6.5
6   ABC1021  6.5
7   ABC1023  6.5

The main dataframe looks like this:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Final result       0       6.5    ABC1000           10
Final result       0       6.5    ABC1003           10
Grade supervisor   0       0      ABC1000           10
Grade supervisor   0       0      ABC1003           10
Final result       0       12     ABC1294           23
Grade supervisor   0       0      ABC1294           23

As you see, student 10 took course ABC1000, worth 6.5 credits. For each course (per student), however, two rows exist: Final result and Grade supervisor. In the end, Final result should be deleted, but the credits should be kept. Therefore, I want to assign the max value of 6.5 to the Grade supervisor row.
Likewise, student 23 has followed course ABC1294, worth 12 credits.

In the end, this should be the result:

Appraisal.Type   Resits   Credits Course_code   Student_ID
Grade supervisor   0       6.5      ABC1000           10
Grade supervisor   0       6.5      ABC1003           10
Grade supervisor   0       12       ABC1294           23

How do I go about this?

Body:
Here's a data.table solution,

DT[,Credits := max(Credits),by=Student_ID]
Result <- DT[Appraisal.Type == "Grade supervisor"]


问:
Adding the last two elements of a list
In Mathematica, what is the cleanest way of taking a list

```<code>{r1, r2, r3, ..., rn, a, b}
</code>```

and returning

```<code>{r1, r2, r3, ..., rn, a + b}
</code>```

or more generally

```<code>{r1, r2, r3, ..., rn, f[a, b]}
</code>```

for some function f?

答:
If I hadn't second guessed Simon I would have been first to answer. Nuts. Anyway, here is my late-to-the-party reply.

```<code>combineLast =
  Module[{x = #},
    x[[-2]] = #2 @@ x[[-2 ;;]];
    Most[x]
  ] &;
</code>```

Comparison:

```<code>leoCL[lst_, f_] := Replace[lst, {left__, ntl_, l_} :> {left, f[ntl, l]}, {0}]

a = RandomInteger[1*^9, 5000];

Do[combineLast[a, Plus], {5000}] // Timing
Do[leoCL[a, Plus], {5000}] // Timing
</code>```

```{0.078, Null}

{1.844, Null}```

Title: Adding the last two elements of a list

Body:
In Mathematica, what is the cleanest way of taking a list

{r1, r2, r3, ..., rn, a, b}

and returning

{r1, r2, r3, ..., rn, a + b}

or more generally

{r1, r2, r3, ..., rn, f[a, b]}

for some function f?

Body:
If I hadn't second guessed Simon I would have been first to answer. Nuts. Anyway, here is my late-to-the-party reply.

combineLast =
  Module[{x = #},
    x[[-2]] = #2 @@ x[[-2 ;;]];
    Most[x]
  ] &;

Comparison:

leoCL[lst_, f_] := Replace[lst, {left__, ntl_, l_} :> {left, f[ntl, l]}, {0}]

a = RandomInteger[1*^9, 5000];

Do[combineLast[a, Plus], {5000}] // Timing
Do[leoCL[a, Plus], {5000}] // Timing

{0.078, Null}

{1.844, Null}


问:
Applescript to change Mac display resolution to "Scaled", "Larger text"
I want to use an Applescript to set my Mac screen resolution to "Scaled", "Larger text".

I found the stackoverflow script below which works great to select the 2nd scaled resolution button. However, I would like to select the 1st, "Larger text". That resolution requires an OK button click which I don't know how to do.

```<code>tell application "System Preferences"
    reveal anchor "displaysDisplayTab" of pane
               "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
    click radio button "Scaled" of radio group 1 of tab group 1
    click radio button 2 of radio group 1 of group 1 of tab group 1
end tell
quit application "System Preferences"
</code>```

I changed button 2 to button 1, but there was no change in the resolution.

Thanks for your help.

答:
I wrote a command line util called displayplacer that makes this super easy - especially for multi-monitor setups. For example, I can set my MacBook Pro to Larger Text by executing displayplacer "id:F466F621-B5FA-04A0-0800-CFA6C258DECD res:1024x640 scaling:on origin:(-1024,1060) degree:0"

Also available via Homebrew: brew tap jakehilborn/jakehilborn && brew install displayplacer

Body:
I want to use an Applescript to set my Mac screen resolution to "Scaled", "Larger text".

I found the stackoverflow script below which works great to select the 2nd scaled resolution button. However, I would like to select the 1st, "Larger text". That resolution requires an OK button click which I don't know how to do.

tell application "System Preferences"
    reveal anchor "displaysDisplayTab" of pane
               "com.apple.preference.displays"
end tell
tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
    click radio button "Scaled" of radio group 1 of tab group 1
    click radio button 2 of radio group 1 of group 1 of tab group 1
end tell
quit application "System Preferences"

I changed button 2 to button 1, but there was no change in the resolution.

Thanks for your help.