问:
How to implement an action listener with generic enums?
I am in the process of refactoring my application and my teacher recommended that I replace the GUI builder generated code with a more generic one.

Right now every JMenuItem has its own action listener. What I'm trying to achieve is a sort of generic control function for every menu item by using  enums in a single action listener. The code below should give you a general idea. clE is the enum key and I believe the enum should implement an interface for reading its label.

I've been doing a bit of research and I'm sure it's something simple, but I can't get fully grasp it yet. Thanks in advance!

```<code>public class JECheckBox<E extends ENUM_Label_INTF<?>> extends JCheckBox {

     private final E clE;

     // +++++++ CONSTRUCTOR +++++++++
     public JECheckBox(final E clE) {
         super( ((GetLabelINTF) clE).GetLabel() );
         this.clE = clE;
     }

     public E GetKey() {
         return clE;
     }
}
</code>```

答:
I believe the enum should implement an interface for reading its label.

If you want to read the text of the check box, then you create a generic listener by doing something like:

```<code>Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JCheckBox checkbox = (JCheckBox)e.getSource();
        System.out.println( checkbox.getText() );
    }
};
</code>```

Now you can add the Action to each check box.

Note an Action is a more versatile ActionListener. Read the section from the Swing tutorial on How to Use Actions for more information and examples.

Body:
I am in the process of refactoring my application and my teacher recommended that I replace the GUI builder generated code with a more generic one.

Right now every JMenuItem has its own action listener. What I'm trying to achieve is a sort of generic control function for every menu item by using  enums in a single action listener. The code below should give you a general idea. clE is the enum key and I believe the enum should implement an interface for reading its label.

I've been doing a bit of research and I'm sure it's something simple, but I can't get fully grasp it yet. Thanks in advance!

public class JECheckBox<E extends ENUM_Label_INTF<?>> extends JCheckBox {

     private final E clE;

     // +++++++ CONSTRUCTOR +++++++++
     public JECheckBox(final E clE) {
         super( ((GetLabelINTF) clE).GetLabel() );
         this.clE = clE;
     }

     public E GetKey() {
         return clE;
     }
}

Body:
I believe the enum should implement an interface for reading its label.

If you want to read the text of the check box, then you create a generic listener by doing something like:

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        JCheckBox checkbox = (JCheckBox)e.getSource();
        System.out.println( checkbox.getText() );
    }
};

Now you can add the Action to each check box.

Note an Action is a more versatile ActionListener. Read the section from the Swing tutorial on How to Use Actions for more information and examples.


来源: stackexchange

问:
typescript mapping destructured parameter with type gives error
Lets say I have the following object

```<code>const a = {
   history: string[]
}
</code>```

Now I am trying to assign history using to another variable historyMapped giving the object type (string[]) as well.

```<code>const { history: mappedCareerHistory }: { mappedCarerHistory: string[] } = a;
</code>```

However I'm getting the following error here

property mappedHistory is missing in type.....

If I simply remove the type and then include the following it works without a compilation issue

```<code>const { history: mappedCareerHistory } = a;
</code>```

答:
it's because you are unwrapping object not changing key.

For Ex

```<code>let a = {history:['1','2']};
const {history: mappedCareerHistory} = a;
console.log(mappedCareerHistory); // ["1", "2"];
</code>```

You are not changing the key of the object you are unwrapping the object so compiler giving errors. so type must be a string array not mapped object type.

ContentLicense: CC BY-SA 4.0

Body:
Lets say I have the following object

const a = {
   history: string[]
}

Now I am trying to assign history using to another variable historyMapped giving the object type (string[]) as well.

const { history: mappedCareerHistory }: { mappedCarerHistory: string[] } = a;

However I'm getting the following error here

property mappedHistory is missing in type.....

If I simply remove the type and then include the following it works without a compilation issue

const { history: mappedCareerHistory } = a;

Body:
it's because you are unwrapping object not changing key.

For Ex

let a = {history:['1','2']};
const {history: mappedCareerHistory} = a;
console.log(mappedCareerHistory); // ["1", "2"];

You are not changing the key of the object you are unwrapping the object so compiler giving errors. so type must be a string array not mapped object type.


问:
AKMIDIListener not firing due to AKMIDIEvent data packet length
I'm using an existing app (Midi Link Sync) to send MIDI clock data to my separate AudioKit iOS application.

AudioKit does pick-up the message, however, the AKMIDIListener does not fire.

AKMIDIListener implemented as-is from playground demo: link

This is because in the _AKMIDI+Receiving.swift_ file, the handleMIDIMessage function is not called (line 155) due to the event status & command being nil.

The misfiring occurs in line 69-70 of the AKMIDIEvent.swift (see
  source code on AudioKit
  master).
  On my end, the data packet with the MIDI clock sent via the MIDI link
  sync app contains one data entry: 0xF8 (clock). Line 69 enforces
  the data length to be > 1 rather than >= 1.

Is this a bug with the AudioKit framework or should MIDI messages be structured with more than one data entry by default?

答:
You should check out AKMIDITempoListener.  It's a helper object to deal with clock events.  This helper object observes clock messages to determine tempo and it provides some conveniences for observing clock message events and tempo events.  It can be used to observe clock quantum events and beat events (24 clock ticks), quantum events (6 clock ticks), tempo events,  start/continue, and stop events.  It can also be used to synchronize a start with the next clock event.

You can check out an example of my testing usage by opening the MacOS development project located in AudioKit ▸ Developer ▸ macOS ▸ macOSDevelopment.  Then open "MIDI Connection Manger.swift".

```<code>public let tempoListener = AKMIDITempoListener(smoothing: 0.98, bpmHistoryLimit: 1)

init() {
    midi.addListener(tempoListener)
    tempoListener.clockListener?.addObserver(self)
    tempoListener.addObserver(self)
}
</code>```

Then further down in the file there is the extension to receive the events:

```<code>extension MIDIConnectionManger: AKMIDIBeatObserver {

    func preparePlay(continue: Bool) {
        debugPrint("MMC Start Prepare Play")
    }

    func startFirstBeat(continue: Bool) {
        debugPrint("MMC Start First Beat")
    }

    func stopSRT() {
        debugPrint("MMC Stop")
    }

    func receivedBeatEvent(beat: UInt64) {

    }

    func receivedQuantum(quarterNote: UInt8, beat: UInt64, quantum: UInt64) {

    }

    func receivedQuarterNoteBeat(quarterNote: UInt8) {
        //debugPrint("Quarter Note: ", quarterNote)
    }
}
</code>```

You probably want to just focus on the receivedQuantum function if you all you care about are clock events.  The main midi listeners are quite focused on midi note events and such, less so than the single byte midi messages.

Body:
You should check out AKMIDITempoListener.  It's a helper object to deal with clock events.  This helper object observes clock messages to determine tempo and it provides some conveniences for observing clock message events and tempo events.  It can be used to observe clock quantum events and beat events (24 clock ticks), quantum events (6 clock ticks), tempo events,  start/continue, and stop events.  It can also be used to synchronize a start with the next clock event.

You can check out an example of my testing usage by opening the MacOS development project located in AudioKit ▸ Developer ▸ macOS ▸ macOSDevelopment.  Then open "MIDI Connection Manger.swift".

public let tempoListener = AKMIDITempoListener(smoothing: 0.98, bpmHistoryLimit: 1)

init() {
    midi.addListener(tempoListener)
    tempoListener.clockListener?.addObserver(self)
    tempoListener.addObserver(self)
}

Then further down in the file there is the extension to receive the events:

extension MIDIConnectionManger: AKMIDIBeatObserver {

    func preparePlay(continue: Bool) {
        debugPrint("MMC Start Prepare Play")
    }

    func startFirstBeat(continue: Bool) {
        debugPrint("MMC Start First Beat")
    }

    func stopSRT() {
        debugPrint("MMC Stop")
    }

    func receivedBeatEvent(beat: UInt64) {

    }

    func receivedQuantum(quarterNote: UInt8, beat: UInt64, quantum: UInt64) {

    }

    func receivedQuarterNoteBeat(quarterNote: UInt8) {
        //debugPrint("Quarter Note: ", quarterNote)
    }
}

You probably want to just focus on the receivedQuantum function if you all you care about are clock events.  The main midi listeners are quite focused on midi note events and such, less so than the single byte midi messages.


问:
Sorting in Tableview
I am new to xamarin.ios wants to sort tableview in alphabetical order.ie every alphabet should display all the books starting with respective letter.I am able to list the details in tableview..need to sort and update cells

```<code>public class BooklistTableSourceClass : UITableViewSource
{
    public List<Booklist> Bookdata { get; set; }
   BooklistViewController parentcontroller;

    NSString cellIdentifier = new NSString("BooklistCell");

    public BooklistTableSourceClass(List<Booklist> listdata,BooklistViewController callingcontroller)
    {

        this.Bookdata = listdata;
        this.parentcontroller = callingcontroller;
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return Bookdata.Count;
    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {

                var cell = (BooklistCell)tableView.DequeueReusableCell("Bcell_id", indexPath);

                var Bookitem = Bookdata[indexPath.Row];

                cell.UpdateCell(Bookitem);

                return cell;
    }

}
</code>```

Output:
A->section header
1)A1  //book name
2)A2
3)A3

答:
Have you tried the Enumerable.OrderBy Method in LINQ?

Sort the Bookdata first and then pass it as source of tableView instead of UpdateCell in GetCell.

```<code>public partial class ViewController : UIViewController
    {

        public List<Booklist> Bookdata { get; set; }

        public ViewController (IntPtr handle) : base (handle)
        {
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.

            Bookdata = new List<Booklist>();
            Bookdata.Add(new Booklist("A2"));
            Bookdata.Add(new Booklist("A3"));
            Bookdata.Add(new Booklist("A1"));
            Bookdata.Add(new Booklist("122"));
            Bookdata.Add(new Booklist("C2"));
            Bookdata.Add(new Booklist("b2"));

            List<Booklist> sortedList = Bookdata.OrderBy(r => r.name).ToList();

            //pass the sortedList as source of tableview
            //...
        }
    }

    public class Booklist
    {
        public Booklist(string n){
            name = n;
        }

        public string name;
    }
</code>```

If you want the  A->section header, I think there is another list that hold the header data. Or you can pick the first letter of data shows in each section as text shows in section header.

Title: Sorting in Tableview

Body:
I am new to xamarin.ios wants to sort tableview in alphabetical order.ie every alphabet should display all the books starting with respective letter.I am able to list the details in tableview..need to sort and update cells

public class BooklistTableSourceClass : UITableViewSource
{
    public List<Booklist> Bookdata { get; set; }
   BooklistViewController parentcontroller;

    NSString cellIdentifier = new NSString("BooklistCell");

    public BooklistTableSourceClass(List<Booklist> listdata,BooklistViewController callingcontroller)
    {

        this.Bookdata = listdata;
        this.parentcontroller = callingcontroller;
    }

    public override nint RowsInSection(UITableView tableview, nint section)
    {
        return Bookdata.Count;
    }

    public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {

                var cell = (BooklistCell)tableView.DequeueReusableCell("Bcell_id", indexPath);

                var Bookitem = Bookdata[indexPath.Row];

                cell.UpdateCell(Bookitem);

                return cell;
    }

}

Output:
A->section header
1)A1  //book name
2)A2
3)A3

Body:
Have you tried the Enumerable.OrderBy Method in LINQ?

Sort the Bookdata first and then pass it as source of tableView instead of UpdateCell in GetCell.

public partial class ViewController : UIViewController
    {

        public List<Booklist> Bookdata { get; set; }

        public ViewController (IntPtr handle) : base (handle)
        {
        }

        public override void ViewDidLoad ()
        {
            base.ViewDidLoad ();
            // Perform any additional setup after loading the view, typically from a nib.

            Bookdata = new List<Booklist>();
            Bookdata.Add(new Booklist("A2"));
            Bookdata.Add(new Booklist("A3"));
            Bookdata.Add(new Booklist("A1"));
            Bookdata.Add(new Booklist("122"));
            Bookdata.Add(new Booklist("C2"));
            Bookdata.Add(new Booklist("b2"));

            List<Booklist> sortedList = Bookdata.OrderBy(r => r.name).ToList();

            //pass the sortedList as source of tableview
            //...
        }
    }

    public class Booklist
    {
        public Booklist(string n){
            name = n;
        }

        public string name;
    }

If you want the  A->section header, I think there is another list that hold the header data. Or you can pick the first letter of data shows in each section as text shows in section header.


问:
lazyloading nested module using Angular Ionic4 app not working properly?
My app has a public routes like login, register as well as protected routes members. Member routes has a child routes of tabs. Tabs has some child routes categories, items etc. Whenever I run the ionic serve I get the following ERROR in Could not resolve module ./dashboard/dashboard.module relative to app/members/tabs/tabs-routing.module.ts

I have used the relative path while configuring the routes.

In the tsconfig.app.json file I have added the "baseUrl": "./"

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [],
    "baseUrl": "./"
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
</code>```

This is my AppRoutingModule:

```<code>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuardService } from './services/auth-guard.service';

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
  {
    path: 'members',
    loadChildren: './members/members-routing.module#MemberRoutingModule' ,
    canActivate : [AuthGuardService]
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

</code>```

This is my MemberRoutingModule:

```<code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
    {
        path: '',
        redirectTo: 'members',
        pathMatch: 'full'
      },
    { path: 'tabs', loadChildren: './tabs/tabs.module#TabsPageModule' },
    { path: 'profile', loadChildren: './profile/profile.module#ProfilePageModule' },
    { path: 'logout', loadChildren: './logout/logout.module#LogoutPageModule' },
    { path: 'menu', loadChildren: './menu/menu.module#MenuPageModule' },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class MemberRoutingModule { }

</code>```

This is my TabsRoutingModule:

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';

const routes: Routes = [
    {
        path: '',
        redirectTo: '/tabs/tabs/dashboard',
        pathMatch: 'full'
    },
    {
        path: 'tabs',
        component: TabsPage,
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardPageModule'
            },
            {
                path: 'categories',
                children: [
                    {
                        path: '',
                        loadChildren: './categories/categories.module#CategoriesPageModule'
                    },
                    {
                        path: 'new-category',
                        loadChildren: './new-category/new-category.module#NewCategoryPageModule'
                    },
                    {
                        path: ':categoryId',
                        loadChildren: './category-details/category-details.module#CategoryDetailsPageModule'
                    }
                ]
            },
            {
                path: 'items',
                children: [
                    {
                        path: '',
                        loadChildren: './items/items.module#ItemsPageModule'
                    },
                    {
                        path: 'new-item',
                        loadChildren: './new-item/new-item.module#NewItemPageModule'
                    }
                ]
            },
            {
                path: '',
                redirectTo: '/tabs/tabs/dashboard',
                pathMatch: 'full'
            }

        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class TabsRoutingModule {}

</code>```

This is my tabs.page.html

```<code><ion-content>
  <ion-tabs>
    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="dashboard">
        <ion-label>Dashboard</ion-label>
        <ion-icon name="podium"></ion-icon>
      </ion-tab-button>
      <ion-tab-button tab="categories">
        <ion-label>Categories</ion-label>
        <ion-icon name="pricetags"></ion-icon>
      </ion-tab-button>
      <ion-tab-button tab="items">
        <ion-label>Items</ion-label>
        <ion-icon name="cash"></ion-icon>
      </ion-tab-button>
    </ion-tab-bar>
  </ion-tabs>
</ion-content>
</code>```

It was working in the beginning then I restarted the app without any changes and now whenever I run the ionic-serve I get the below error where the lazyloading of the modules are not working. This is the error: "ERROR in Could not resolve module ./dashboard/dashboard.module relative to app/members/tabs/tabs-routing.module.ts"

答:
I have solved the problem. Really it was just an error due to ionic couldn't locate the modules. The confusion was at first ionic was able to locate them properly. I was able to solve it using the path intellisence plugin in vscode by christian-kohler.path-intellisense
. This is the link of the plugin https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense This is how the final routes looks like </p>

```<code>const routes: Routes = [
{
    path: '',
    component: TabsPage,
    children: [
        {
            path: 'dashboard',
            loadChildren: '../dashboard/dashboard.module#DashboardPageModule'
        },
        {
            path: 'categories',
            children: [
                {
                    path: '',
                    loadChildren: '../categories/categories.module#CategoriesPageModule'
                },
                {
                    path: 'new-category',
                    loadChildren: '../new-category/new-category.module#NewCategoryPageModule'
                },
                {
                    path: 'edit/:id',
                    loadChildren: '../new-category/new-category.module#NewCategoryPageModule'
                },
                {
                    path: ':id/items',
                    children: [
                        {
                            path: '',
                            loadChildren: '../items/items.module#ItemsPageModule'
                        },
                        {
                            path: 'new-item',
                            loadChildren: '../new-item/new-item.module#NewItemPageModule'
                        },
                        {
                            path: 'edit/:itemId',
                            loadChildren: '../new-item/new-item.module#NewItemPageModule'
                        }
                    ]
                }
                // {
                //     path: ':id/new-item',
                //     loadChildren: '../new-item/new-item.module#NewItemPageModule'
                // },
                // {
                //     path: ':id/items',
                //     loadChildren: '../items/items.module#ItemsPageModule'
                // }
            ]
        },
        {
            path: 'category-details',
            loadChildren: '../category-details/category-details.module#CategoryDetailsPageModule'

        },
        {
            path: '',
            redirectTo: './tabs/dashboard',
            pathMatch: 'full'
        }

    ]
},
{
    path: '',
    redirectTo: '/tabs/dashboard',
    pathMatch: 'full'
}
</code>```

<p>];</p>

Body:
My app has a public routes like login, register as well as protected routes members. Member routes has a child routes of tabs. Tabs has some child routes categories, items etc. Whenever I run the ionic serve I get the following ERROR in Could not resolve module ./dashboard/dashboard.module relative to app/members/tabs/tabs-routing.module.ts

I have used the relative path while configuring the routes.

In the tsconfig.app.json file I have added the "baseUrl": "./"

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [],
    "baseUrl": "./"
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

This is my AppRoutingModule:

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { AuthGuardService } from './services/auth-guard.service';

const routes: Routes = [
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', loadChildren: './login/login.module#LoginPageModule' },
  { path: 'register', loadChildren: './register/register.module#RegisterPageModule' },
  {
    path: 'members',
    loadChildren: './members/members-routing.module#MemberRoutingModule' ,
    canActivate : [AuthGuardService]
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This is my MemberRoutingModule:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
    {
        path: '',
        redirectTo: 'members',
        pathMatch: 'full'
      },
    { path: 'tabs', loadChildren: './tabs/tabs.module#TabsPageModule' },
    { path: 'profile', loadChildren: './profile/profile.module#ProfilePageModule' },
    { path: 'logout', loadChildren: './logout/logout.module#LogoutPageModule' },
    { path: 'menu', loadChildren: './menu/menu.module#MenuPageModule' },
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class MemberRoutingModule { }

This is my TabsRoutingModule:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs.page';

const routes: Routes = [
    {
        path: '',
        redirectTo: '/tabs/tabs/dashboard',
        pathMatch: 'full'
    },
    {
        path: 'tabs',
        component: TabsPage,
        children: [
            {
                path: 'dashboard',
                loadChildren: './dashboard/dashboard.module#DashboardPageModule'
            },
            {
                path: 'categories',
                children: [
                    {
                        path: '',
                        loadChildren: './categories/categories.module#CategoriesPageModule'
                    },
                    {
                        path: 'new-category',
                        loadChildren: './new-category/new-category.module#NewCategoryPageModule'
                    },
                    {
                        path: ':categoryId',
                        loadChildren: './category-details/category-details.module#CategoryDetailsPageModule'
                    }
                ]
            },
            {
                path: 'items',
                children: [
                    {
                        path: '',
                        loadChildren: './items/items.module#ItemsPageModule'
                    },
                    {
                        path: 'new-item',
                        loadChildren: './new-item/new-item.module#NewItemPageModule'
                    }
                ]
            },
            {
                path: '',
                redirectTo: '/tabs/tabs/dashboard',
                pathMatch: 'full'
            }

        ]
    }
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class TabsRoutingModule {}

This is my tabs.page.html

<ion-content>
  <ion-tabs>
    <ion-tab-bar slot="bottom">
      <ion-tab-button tab="dashboard">
        <ion-label>Dashboard</ion-label>
        <ion-icon name="podium"></ion-icon>
      </ion-tab-button>
      <ion-tab-button tab="categories">
        <ion-label>Categories</ion-label>
        <ion-icon name="pricetags"></ion-icon>
      </ion-tab-button>
      <ion-tab-button tab="items">
        <ion-label>Items</ion-label>
        <ion-icon name="cash"></ion-icon>
      </ion-tab-button>
    </ion-tab-bar>
  </ion-tabs>
</ion-content>

It was working in the beginning then I restarted the app without any changes and now whenever I run the ionic-serve I get the below error where the lazyloading of the modules are not working. This is the error: "ERROR in Could not resolve module ./dashboard/dashboard.module relative to app/members/tabs/tabs-routing.module.ts"

Body:
I have solved the problem. Really it was just an error due to ionic couldn't locate the modules. The confusion was at first ionic was able to locate them properly. I was able to solve it using the path intellisence plugin in vscode by christian-kohler.path-intellisense
. This is the link of the plugin https://marketplace.visualstudio.com/items?itemName=christian-kohler.path-intellisense This is how the final routes looks like

const routes: Routes = [
{
    path: '',
    component: TabsPage,
    children: [
        {
            path: 'dashboard',
            loadChildren: '../dashboard/dashboard.module#DashboardPageModule'
        },
        {
            path: 'categories',
            children: [
                {
                    path: '',
                    loadChildren: '../categories/categories.module#CategoriesPageModule'
                },
                {
                    path: 'new-category',
                    loadChildren: '../new-category/new-category.module#NewCategoryPageModule'
                },
                {
                    path: 'edit/:id',
                    loadChildren: '../new-category/new-category.module#NewCategoryPageModule'
                },
                {
                    path: ':id/items',
                    children: [
                        {
                            path: '',
                            loadChildren: '../items/items.module#ItemsPageModule'
                        },
                        {
                            path: 'new-item',
                            loadChildren: '../new-item/new-item.module#NewItemPageModule'
                        },
                        {
                            path: 'edit/:itemId',
                            loadChildren: '../new-item/new-item.module#NewItemPageModule'
                        }
                    ]
                }
                // {
                //     path: ':id/new-item',
                //     loadChildren: '../new-item/new-item.module#NewItemPageModule'
                // },
                // {
                //     path: ':id/items',
                //     loadChildren: '../items/items.module#ItemsPageModule'
                // }
            ]
        },
        {
            path: 'category-details',
            loadChildren: '../category-details/category-details.module#CategoryDetailsPageModule'

        },
        {
            path: '',
            redirectTo: './tabs/dashboard',
            pathMatch: 'full'
        }

    ]
},
{
    path: '',
    redirectTo: '/tabs/dashboard',
    pathMatch: 'full'
}

];


问:
Using the API to set 'multiChStereo' and '2chStereo' soundFields on bullt-in Chromecast input
Regarding programming with the Sony Audio Control API.

I am aware that the only 2 soundFields that are selectable when using the built-in Chromecast on the Sony STR-DN1080 are '2Ch Stereo' and 'Multi Ch Stereo'. You can press the "2ch/Multi" button on the IR remote control when using this input, as per the online help.

However, when using the API to select these two soundFields using:

```<code>{
    "id":8,
    "method":"setSoundSettings",
    "params":[{
        "settings":[{
        "target":"soundField",
        "value":"2chStereo"
    }]
    }],
    "version":"1.1"
}
</code>```

and:

```<code>{
    "id":9,
    "method":"setSoundSettings",
    "params":[{
        "settings":[{
        "target":"soundField",
        "value":"multiChStereo"
    }]
    }],
    "version":"1.1"
}
</code>```

I received the following JSON response:

```<code>{
  "error": [
    15,
    "unsupported operation"
  ],
  "id": 8
}
</code>```

This two JSON requests are able to select the soundFields on other inputs however. And the IR remote works to select these soundFields when using the built-in Chromecast (as per the online help), but I cannot access them when using API.

答:
Looking at the response it looks like the "target": "soundField" is "currentValue": "off" for both and the "target": "soundField" is set to "isAvailable": false. So my guess is that even if it looks like you are switching then using the remote in practice nothing is really happening in the receiver. Can't confirm this right now since I'm traveling this week.

Another way to test what is available is to use "Sony | Music Center" (App) and my guess is that "sound field" settings is not available in this case there also.

Body:
Regarding programming with the Sony Audio Control API.

I am aware that the only 2 soundFields that are selectable when using the built-in Chromecast on the Sony STR-DN1080 are '2Ch Stereo' and 'Multi Ch Stereo'. You can press the "2ch/Multi" button on the IR remote control when using this input, as per the online help.

However, when using the API to select these two soundFields using:

{
    "id":8,
    "method":"setSoundSettings",
    "params":[{
        "settings":[{
        "target":"soundField",
        "value":"2chStereo"
    }]
    }],
    "version":"1.1"
}

and:

{
    "id":9,
    "method":"setSoundSettings",
    "params":[{
        "settings":[{
        "target":"soundField",
        "value":"multiChStereo"
    }]
    }],
    "version":"1.1"
}

I received the following JSON response:

{
  "error": [
    15,
    "unsupported operation"
  ],
  "id": 8
}

This two JSON requests are able to select the soundFields on other inputs however. And the IR remote works to select these soundFields when using the built-in Chromecast (as per the online help), but I cannot access them when using API.


问:
Can I somehow give this shortcode custom css even tho Advanced settings > Custom css says "Pro only"?
For a final assignment I need to make a website in wordpress. I'm making it using an existing theme and Elementor, a drag and drop website builder. I used a shortcode widget to get posts with the tag 'featured' displayed on the homepage.  However it doesn't look very pretty. The theme & page builder I'm using only offers custom css for those that pay for the pro version. Is there a way to work around this and maybe add css directly to a file somewhere?

This is the shortcode I use to display the posts with the 'featured' tag:

```<code>[display-posts tag="featured" include_date="true" date_format="F j, Y" image_size="thumbnail" include_excerpt="true" wrapper="div" posts_per_page="1"]
</code>```

答:
You can use the child theme then put your custom CSS code to the file style.css in the child theme folder.

Simply create a child theme with this plugin https://wordpress.org/plugins/child-theme-generator/

Body:
For a final assignment I need to make a website in wordpress. I'm making it using an existing theme and Elementor, a drag and drop website builder. I used a shortcode widget to get posts with the tag 'featured' displayed on the homepage.  However it doesn't look very pretty. The theme & page builder I'm using only offers custom css for those that pay for the pro version. Is there a way to work around this and maybe add css directly to a file somewhere?

This is the shortcode I use to display the posts with the 'featured' tag:

[display-posts tag="featured" include_date="true" date_format="F j, Y" image_size="thumbnail" include_excerpt="true" wrapper="div" posts_per_page="1"]


问:
How to achieve the following using functions/stored procedure in SQL Server database
I have the following table with following data as

```<code>                                            Tab1
FutureMISBoundaryVersion  CurrentMISBoundaryVersion  FutureHAMBoundaryVersion  CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33  2:12,5:40,4:35,7:60,9:87   2:52,5:90,4:75,7:30,9:57  2:42,5:60,4:95,7:70,9:37
</code>```

This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion

```<code>FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
              33     |              80     |            21       |            55       |  50                  | 87                 |  60                 |12                  |35                   | 40
</code>```

i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.

Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys

when it finds column 'CurrentMISBoundaryVersion' then

'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.

The table structure may extend as I have shown only 4 source table column  but logic for all the columns remain same

答:
Very funky requirements to be honest.
Please note solution below will work only in SQL Server 2016+ as I'm using JSON to parse the data. However you can write your own parser, in this case code will work in almost all versions of SQL Server.

Parse function:

```<code>CREATE FUNCTION dbo.ParseIt(@Type NVARCHAR(255),@Value NVARCHAR(MAX))
RETURNS @Parsed TABLE (Code NVARCHAR(255),Value NVARCHAR(255))
AS
BEGIN
    INSERT INTO @Parsed(Code,Value)
    SELECT @Type + '-' + m.Code + 'Version' AS [Code],p.[1] AS [Value]
    FROM (
        SELECT j.[key] AS [ID],i.[key],i.value
        FROM OPENJSON('["' + REPLACE(@Value,',','","') + '"]') j
        CROSS APPLY OPENJSON('[' + REPLACE(j.[value],':',',') + ']') i
    ) a
    PIVOT(MAX(a.value) FOR a.[key] IN ([0],[1])) p
    INNER JOIN ( VALUES
        (2,'DUR')
        ,(4,'BUR')
        ,(5,'YRT')
        ,(7,'HAM')
        ,(9,'OAK')
    ) m(ID, Code) ON m.ID = p.[0]
    ;
    RETURN;
END
</code>```

Initial data:

```<code>DECLARE @Table TABLE (FutureMISBoundaryVersion NVARCHAR(MAX), CurrentMISBoundaryVersion NVARCHAR(MAX),FutureHAMBoundaryVersion NVARCHAR(MAX),CurrentHAMBoundaryVersion NVARCHAR(MAX));
INSERT INTO @Table(FutureMISBoundaryVersion,CurrentMISBoundaryVersion,FutureHAMBoundaryVersion,CurrentHAMBoundaryVersion)VALUES
    ('2:21,5:50,4:55,7:80,9:33','2:12,5:40,4:35,7:60,9:87','2:52,5:90,4:75,7:30,9:57','2:42,5:60,4:95,7:70,9:37')
;
</code>```

The code:

```<code>SELECT COALESCE(p.[FutureMIS-OAKVersion],'') AS [FutureMIS-OAKVersion]
    ,COALESCE(p.[FutureMIS-HAMVersion],'') AS [FutureMIS-HAMVersion]
    ,COALESCE(p.[FutureMIS-DURVersion],'') AS [FutureMIS-DURVersion]
    ,COALESCE(p.[FutureMIS-BURVersion],'') AS [FutureMIS-BURVersion]
    ,COALESCE(p.[FutureMIS-YRTVersion],'') AS [FutureMIS-YRTVersion]
    ,COALESCE(p.[DeviceMIS-OAKVersion],'') AS [DeviceMIS-OAKVersion]
    ,COALESCE(p.[DeviceMIS-HAMVersion],'') AS [DeviceMIS-HAMVersion]
    ,COALESCE(p.[DeviceMIS-DURVersion],'') AS [DeviceMIS-DURVersion]
    ,COALESCE(p.[DeviceMIS-BURVersion],'') AS [DeviceMIS-BURVersion]
    ,COALESCE(p.[DeviceMIS-YRTVersion],'') AS [DeviceMIS-YRTVersion]
FROM (
    SELECT f.Code,f.Value FROM @Table t CROSS APPLY dbo.ParseIt('FutureMIS',t.FutureMISBoundaryVersion) f
    UNION ALL
    SELECT f.Code,f.Value FROM @Table t CROSS APPLY dbo.ParseIt('DeviceMIS',t.CurrentMISBoundaryVersion) f
) a
PIVOT(MAX(a.Value) FOR a.Code IN ([DeviceMIS-BURVersion],[DeviceMIS-DURVersion],[DeviceMIS-HAMVersion],[DeviceMIS-OAKVersion]
    ,[DeviceMIS-YRTVersion],[FutureMIS-BURVersion],[FutureMIS-DURVersion],[FutureMIS-HAMVersion],[FutureMIS-OAKVersion]
    ,[FutureMIS-YRTVersion])) p
;
</code>```

Body:
I have the following table with following data as

                                            Tab1
FutureMISBoundaryVersion  CurrentMISBoundaryVersion  FutureHAMBoundaryVersion  CurrentHAMBoundaryVersion
2:21,5:50,4:55,7:80,9:33  2:12,5:40,4:35,7:60,9:87   2:52,5:90,4:75,7:30,9:57  2:42,5:60,4:95,7:70,9:37

This key value pair has to be split into and the value of each key has to be inserted into another table in the following fashion

FutureMIS-OAKVersion |FutureMIS-HAMVersion |FutureMIS-DURVersion | FutureMIS-BURVersion| FutureMIS-YRTVersion |DeviceMIS-OAKVersion|DeviceMIS-HAMVersion |DeviceMIS-DURVersion| DeviceMIS-BURVersion| DeviceMIS-YRTVersion
              33     |              80     |            21       |            55       |  50                  | 87                 |  60                 |12                  |35                   | 40

i,e: when it finds column 'FutureMISBoundaryVersion' in tab1 then its value
'2:21,5:50,4:55,7:80,9:33' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:21 will be inserted into FutureMIS-DURVersion column.

Similarly key 5's value 50 will be inserted into FutureMIS-BURVersion column and so on for other keys

when it finds column 'CurrentMISBoundaryVersion' then

'2:12,5:40,4:35,7:60,9:87' will be split and its value is inserted in such a way that the corresponding value of key 2 i,e:12 will be inserted into CurrentMIS-DURVersion column similarly key 5's 40 value will be inserted into DeviceMIS-YRTVersion column and so on for other columns of the source table.

The table structure may extend as I have shown only 4 source table column  but logic for all the columns remain same

Body:
Very funky requirements to be honest.
Please note solution below will work only in SQL Server 2016+ as I'm using JSON to parse the data. However you can write your own parser, in this case code will work in almost all versions of SQL Server.

Parse function:

CREATE FUNCTION dbo.ParseIt(@Type NVARCHAR(255),@Value NVARCHAR(MAX))
RETURNS @Parsed TABLE (Code NVARCHAR(255),Value NVARCHAR(255))
AS
BEGIN
    INSERT INTO @Parsed(Code,Value)
    SELECT @Type + '-' + m.Code + 'Version' AS [Code],p.[1] AS [Value]
    FROM (
        SELECT j.[key] AS [ID],i.[key],i.value
        FROM OPENJSON('["' + REPLACE(@Value,',','","') + '"]') j
        CROSS APPLY OPENJSON('[' + REPLACE(j.[value],':',',') + ']') i
    ) a
    PIVOT(MAX(a.value) FOR a.[key] IN ([0],[1])) p
    INNER JOIN ( VALUES
        (2,'DUR')
        ,(4,'BUR')
        ,(5,'YRT')
        ,(7,'HAM')
        ,(9,'OAK')
    ) m(ID, Code) ON m.ID = p.[0]
    ;
    RETURN;
END

Initial data:

DECLARE @Table TABLE (FutureMISBoundaryVersion NVARCHAR(MAX), CurrentMISBoundaryVersion NVARCHAR(MAX),FutureHAMBoundaryVersion NVARCHAR(MAX),CurrentHAMBoundaryVersion NVARCHAR(MAX));
INSERT INTO @Table(FutureMISBoundaryVersion,CurrentMISBoundaryVersion,FutureHAMBoundaryVersion,CurrentHAMBoundaryVersion)VALUES
    ('2:21,5:50,4:55,7:80,9:33','2:12,5:40,4:35,7:60,9:87','2:52,5:90,4:75,7:30,9:57','2:42,5:60,4:95,7:70,9:37')
;

The code:

SELECT COALESCE(p.[FutureMIS-OAKVersion],'') AS [FutureMIS-OAKVersion]
    ,COALESCE(p.[FutureMIS-HAMVersion],'') AS [FutureMIS-HAMVersion]
    ,COALESCE(p.[FutureMIS-DURVersion],'') AS [FutureMIS-DURVersion]
    ,COALESCE(p.[FutureMIS-BURVersion],'') AS [FutureMIS-BURVersion]
    ,COALESCE(p.[FutureMIS-YRTVersion],'') AS [FutureMIS-YRTVersion]
    ,COALESCE(p.[DeviceMIS-OAKVersion],'') AS [DeviceMIS-OAKVersion]
    ,COALESCE(p.[DeviceMIS-HAMVersion],'') AS [DeviceMIS-HAMVersion]
    ,COALESCE(p.[DeviceMIS-DURVersion],'') AS [DeviceMIS-DURVersion]
    ,COALESCE(p.[DeviceMIS-BURVersion],'') AS [DeviceMIS-BURVersion]
    ,COALESCE(p.[DeviceMIS-YRTVersion],'') AS [DeviceMIS-YRTVersion]
FROM (
    SELECT f.Code,f.Value FROM @Table t CROSS APPLY dbo.ParseIt('FutureMIS',t.FutureMISBoundaryVersion) f
    UNION ALL
    SELECT f.Code,f.Value FROM @Table t CROSS APPLY dbo.ParseIt('DeviceMIS',t.CurrentMISBoundaryVersion) f
) a
PIVOT(MAX(a.Value) FOR a.Code IN ([DeviceMIS-BURVersion],[DeviceMIS-DURVersion],[DeviceMIS-HAMVersion],[DeviceMIS-OAKVersion]
    ,[DeviceMIS-YRTVersion],[FutureMIS-BURVersion],[FutureMIS-DURVersion],[FutureMIS-HAMVersion],[FutureMIS-OAKVersion]
    ,[FutureMIS-YRTVersion])) p
;


问:
Can I pass a dynamic value from craft CMS to another template as well as a string value?
Can I pass a dynamic value from craft CMS using twig to another template as well as a string value?
Using the following gives me a syntax error

"Twig_Error_Syntax: A hash key must be followed by a colon (:).
Unexpected token "punctuation" of value "," ("punctuation" expected with value ":") "

```<code>        {% set myEntry= craft.entries.slug('myEntry').first %}
        {% embed '_layouts/_hero' with {
            'extraClasses': "{{ myEntry.featuredBgPosition }} hero--medium",
            'heroImage': myEntry.featuredImage.first
        } %}
</code>```

Other answers say to not use curly braces but this doesn't work either

'extraClasses': myEntry.featuredBgPosition "hero--medium",

and when using it within the quotations I get the string myEntry.featuredBgPosition as a class

'extraClasses': myEntry.featuredBgPosition "hero--medium",

答:
The answers that suggest removing the curly braces are correct, but you need to concatentate strings with variables.</p>

```<code>        {% set myEntry= craft.entries.slug('myEntry').first %}
        {% embed '_layouts/_hero' with {
            'extraClasses': myEntry.featuredBgPosition ~ " hero--medium",
            'heroImage': myEntry.featuredImage.first
        } %}
</code>```

Body:
Can I pass a dynamic value from craft CMS using twig to another template as well as a string value?
Using the following gives me a syntax error

"Twig_Error_Syntax: A hash key must be followed by a colon (:).
Unexpected token "punctuation" of value "," ("punctuation" expected with value ":") "

        {% set myEntry= craft.entries.slug('myEntry').first %}
        {% embed '_layouts/_hero' with {
            'extraClasses': "{{ myEntry.featuredBgPosition }} hero--medium",
            'heroImage': myEntry.featuredImage.first
        } %}

Other answers say to not use curly braces but this doesn't work either

'extraClasses': myEntry.featuredBgPosition "hero--medium",

and when using it within the quotations I get the string myEntry.featuredBgPosition as a class

'extraClasses': myEntry.featuredBgPosition "hero--medium",

Body:
The answers that suggest removing the curly braces are correct, but you need to concatentate strings with variables.

        {% set myEntry= craft.entries.slug('myEntry').first %}
        {% embed '_layouts/_hero' with {
            'extraClasses': myEntry.featuredBgPosition ~ " hero--medium",
            'heroImage': myEntry.featuredImage.first
        } %}


问:
How do I perform either a push UIViewController or a present of UIAlertController?
After some API calls, I have a check to either navigate to another screen or show an alert on the same screen. Currently, I am doing this by creating an observable that returns a UIViewController type but pushing a UIAlertController causes problem.

Any suggestions/ideas on how this should be done?

ViewModel.swift

```<code>let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                              resultSelector:
        { appVersion, _, _ -> UIViewController in
            if appVersion.currentAppVersion == "1.0.0" {
                let appServiceAvailability = Availability.shared.getAppStatus()
                if appServiceAvailability {
                    return LoginLandingViewController()
                } else {
                    return ServiceMaintenanceViewController()
                }
            } else {
                return UIAlertController()
            }
        })
</code>```

ViewController.swift

```<code>viewModel.output.nextAction
        .subscribe(onNext: { [weak self] screen in
            self?.navigationController?.pushViewController(screen, animated: true)
        }) // PROBLEM FACED: Pushing a UIAlertController
        .disposed(by: disposeBag)
</code>```

答:
You can look at the is keyword which allows you to check the object type. More on is keyword. An alternative will be to use type(of: object) and compare to UIAlertViewController.self

Since you have to present a UIAlertViewController and not push it, use if and else with the above to present if type is UIAlertViewController and push if otherwise. NB: Unnecessary to check for UIViewController since they all are.

Body:
After some API calls, I have a check to either navigate to another screen or show an alert on the same screen. Currently, I am doing this by creating an observable that returns a UIViewController type but pushing a UIAlertController causes problem.

Any suggestions/ideas on how this should be done?

ViewModel.swift

let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                              resultSelector:
        { appVersion, _, _ -> UIViewController in
            if appVersion.currentAppVersion == "1.0.0" {
                let appServiceAvailability = Availability.shared.getAppStatus()
                if appServiceAvailability {
                    return LoginLandingViewController()
                } else {
                    return ServiceMaintenanceViewController()
                }
            } else {
                return UIAlertController()
            }
        })

ViewController.swift

viewModel.output.nextAction
        .subscribe(onNext: { [weak self] screen in
            self?.navigationController?.pushViewController(screen, animated: true)
        }) // PROBLEM FACED: Pushing a UIAlertController
        .disposed(by: disposeBag)


问:
Grep to identify flles in a directory that contain all zeros and list or delete them
Have numerous image files in a directory that have been corrupted and contain only zero hex value (although some are very large)- among other images that are not corrupt.Want to search through the directory identify files that contain only zeros and delete them.

I am running this from terminal on a mac.

I am thinking grep, recursive, stop searching and eliminate from deletion any file if it contains a value other than zeros, delete zero value files with rm. However- I am a novice and do not know how to put it together.

Or have the zero files moved to a directory from which I can delete them (want to be careful not to delete any good image files.)

答:
find to gawk to xargs is very efficient.

Please remove the echo safety after confirming desired command.

#!/bin/bash
mapfile -t Files < <(find . -type f -not -empty)    #1
gawk '
  /[^\x00]/ {f=1; nextfile}                         #2
  ENDFILE {if(!f) print FILENAME; f=0}              #3
' "${Files[@]}" |xargs echo rm                      #4
```

Recursively store all non-empty files in the current directory in array "Files"

If any line matches a character other than a hex zero, set flag and go to next file

After nextfile or normal EOF, print filename if flag is unset, then unset flag

Feed gawk our find results, then use xargs to construct a single rm command.

Body:
find to gawk to xargs is very efficient.

Please remove the echo safety after confirming desired command.

#!/bin/bash
mapfile -t Files < <(find . -type f -not -empty)    #1
gawk '
  /[^\x00]/ {f=1; nextfile}                         #2
  ENDFILE {if(!f) print FILENAME; f=0}              #3
' "${Files[@]}" |xargs echo rm                      #4

Recursively store all non-empty files in the current directory in array "Files"

If any line matches a character other than a hex zero, set flag and go to next file

After nextfile or normal EOF, print filename if flag is unset, then unset flag

Feed gawk our find results, then use xargs to construct a single rm command.


问:
Symfony4 use external class library as a service
I have a little external library that expose many classes.

Into my symfony4 project I would like to declare my class from vendor, as a service with autowire and public.
So I have include my library with composer and add psr configuration like this into composer.json:

```<code>"autoload": {
        "psr-4": {
            "App\\": "src/",
            "ExternalLibrary\\": "vendor/external-library/api/src/"
        }
    }
</code>```

After that I have tried to change my services.yaml into symfony like this:

```<code>ExternalLibrary\:
    resource: '../vendor/external-library/api/src/*'
    public: true
    autowire: true
</code>```

If I launch tests or run the application returns me this error:

```<code>Cannot autowire service "App\Domain\Service\MyService": argument "$repository" of method "__construct()" references interface "ExternalLibrary\Domain\Model\Repository" but no such service exists. You should maybe alias this interface to the existing "App\Infrastructure\Domain\Model\MysqlRepository" service.
</code>```

If I declare into services.yaml the interface this works fine:

```<code>ExternalLibrary\Domain\Model\Lotto\Repository:
    class: '../vendor/external-library/api/src/Domain/Model/Repository.php'
    public: true
    autowire: true
</code>```

But I have many classes and I don't want to declare each class, how can I fix services.yaml without declare every single service?

Thanks

答:
Let's take Dompdf as an example :

When you try to add type-hint Dompdf in your action controller or service method , an error will be occurred saying that auto-wiring isn't possible because Dompdf is an external PHP library

So to solve this problem we'll make a little change in our services.yaml file by adding this short config

```<code>Dompdf\: #Add the global namespace
   resource: '../vendor/dompdf/dompdf/src/*' #Where can we find your external lib ?
   autowire: true  #Turn autowire to true
</code>```

Apply the above example to all external PHP libs :)

That's all !

Body:
I have a little external library that expose many classes.

Into my symfony4 project I would like to declare my class from vendor, as a service with autowire and public.
So I have include my library with composer and add psr configuration like this into composer.json:

"autoload": {
        "psr-4": {
            "App\\": "src/",
            "ExternalLibrary\\": "vendor/external-library/api/src/"
        }
    }

After that I have tried to change my services.yaml into symfony like this:

ExternalLibrary\:
    resource: '../vendor/external-library/api/src/*'
    public: true
    autowire: true

If I launch tests or run the application returns me this error:

Cannot autowire service "App\Domain\Service\MyService": argument "$repository" of method "__construct()" references interface "ExternalLibrary\Domain\Model\Repository" but no such service exists. You should maybe alias this interface to the existing "App\Infrastructure\Domain\Model\MysqlRepository" service.

If I declare into services.yaml the interface this works fine:

ExternalLibrary\Domain\Model\Lotto\Repository:
    class: '../vendor/external-library/api/src/Domain/Model/Repository.php'
    public: true
    autowire: true

But I have many classes and I don't want to declare each class, how can I fix services.yaml without declare every single service?

Thanks

Body:
Let's take Dompdf as an example :

When you try to add type-hint Dompdf in your action controller or service method , an error will be occurred saying that auto-wiring isn't possible because Dompdf is an external PHP library

So to solve this problem we'll make a little change in our services.yaml file by adding this short config

Dompdf\: #Add the global namespace
   resource: '../vendor/dompdf/dompdf/src/*' #Where can we find your external lib ?
   autowire: true  #Turn autowire to true

Apply the above example to all external PHP libs :)

That's all !


问:
What is the maximum length of a string in JavaScript?
I thought this would be an easy google search but nothing came up.

Say I create a loop that continually appends one character at a time to a variable.

At what point will the program crash?

I expect it will take <6 seconds for someone to comment "Why don't you try it and find out?", but trying it wouldn't tell me the answer to the question. Is it implementation-specific? Is it defined anywhere? It doesn't seem to be in the ECMAScript spec.

Are there any known limitations beyond available memory? Does performance degrade with strings holding Mbs or Gbs of text?

For the record, I did try running that loop....and it just crashed my browser :( Maybe if I make some adjustments and try again.

答:
ECMAScript 2016 (ed. 7) established a maximum length of 2^53 - 1
  elements. Previously, no maximum length was specified. In Firefox,
  strings have a maximum length of 2**30 - 2 (~1GB).
  In versions prior
  to Firefox 65, the maximum length was 2**28- 1 (~256MB).

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length


问:
White space beside content when I reduce the screen size
I am studying CSS and creating a responsive web page. I have started working in a media query. When I maximize the screen, all works as expected, but when I reduce its size, the content that does not fit in the viewport is hidden, and a white space stays in its place. That space can be seen scrolling the screen to side. Why is that space appearing instead the rest of the content? I also don't understand why my content doesn't fit in the screen, because I am using percentage values to elements' width. My code is below:

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
html, body{
 width: 99.13vw;
}
body{
 font-family: 'Open Sans', sans-serif;
 margin: 0;
}
h2, h3{
 margin-top: 10px;
 margin-bottom: 10px;
}
a{
 text-decoration: none;
 transition: 0.2s linear;
}
header{
 background-color: rgb(93, 158, 76);
 display: flex;
 align-items: center;
 padding: 10px 30px;
 width: 100%;
}
header img{
 width: 45px;
}
header h1{
 font-family: 'Doppio One', cursive;
 margin-left: 10px;
 color: rgb(214, 245, 210);
}
nav ul{
 display: flex;
 list-style: none;
}
nav ul li a{
 margin-left: 55px;
}
nav a{
 color: rgb(230, 245, 229);
 font-size: 17px;
}
nav a:hover{
 background-color: rgb(143, 182, 135);
 padding: 10px 15px;
 margin: 0 -15px 0 40px;
}
nav img{
 display: none;
 width: 30px;
 height: 35px;
}
#firstsection{
 background-image: url(Images/coffee-3289259_1280.jpg);
 background-size: cover;
 height: 900px;
 position: relative;
}
#firstsection div{
 margin-top: 0;
 position: absolute;
 left: 100px;
 top: 150px;
 color: rgb(47, 119, 27);
 text-align: center;
}
#firstsection h1{
 margin-bottom: 45px;
}
#firstsection div a{
 font-weight: bold;
 border: 2px solid rgb(47, 119, 27);
 padding: 13px 30px;
 font-size: 16.5px;
 color: rgb(47, 119, 27);
}
#firstsection div a:hover{
 color: rgb(133, 163, 131);
 border: 2px solid rgb(133, 163, 131);
}
#textboxes{
 display: flex;
 margin-top: 50px;
 flex-wrap: wrap;
}
#textboxes div{
 text-align: center;
 margin: 15px 60px;
 border: 2px solid rgb(93, 158, 76);
 padding: 30px 30px;
 width: 27%;
}
#middlesection img:first-of-type{
 width: 55px;
}
#middlesection h2{
 text-align: center;
 width: 100%;
}
#lastsection{
 text-align: center;
}
#lastsection img{
 width: 30%;
 margin: 100px auto 0px;
}
#lastsection div{
 position: relative;
 bottom: 450px;
}
#lastsection div a:visited{
 color: blue;
}
footer{
 background-color: rgb(93, 158, 76);
 padding: 15px;
 color: rgb(214, 245, 210);
 font-size: 14px;
 display: flex;
 justify-content: center;
 align-items: center;
}
footer img{
 height: 35px;
 width: 35px;
 margin-right: 15px;
}
footer div{
 text-align: center;
}
@media screen and (max-width: 800px){
 #textboxes div{
  width: 100%;
 }
 #lastsection img{
  width: 85%;
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Finances | Manage your money easily</title>
 <meta charset="UTF-8">
 <meta content="width=device-width, initial-scale=1.0" name="viewport">
 <meta content="Control you spending and manage your money easily. Your finances by the short hairs." name="description">
 <meta content="Bruno M. B. Sdoukos" name="author">
 <meta content="finances, managing money, spending control" name="keywords">
 <link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
 <header>
  <img src="Images/icons8-fund-accounting-80.png">
  <h1>Finances</h1>
  <nav>
   <ul>
    <li>
     Home
    </li>
    <li>
     About
    </li>
    <li>
     Contact us
    </li>
    <li>
     Register
    </li>
    <li>
     Login
    </li>
   </ul>
  </nav>
 </header>
 <main>
  <section id="firstsection">
   <div>
    <h1>Manage your money easily, anywhere, anytime.</h1>Get started
   </div>
  </section>
  <section id="middlesection">
   <div id="textboxes">
    <div>
     <img src="Images/icons8-increase-64.png">
     <h3>Concrete data</h3>
     <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
    </div>
    <div>
     <img src="Images/icons8-navigation-toolbar-left-filled-50%20(1).png">
     <h3>Easy interface</h3>
     <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
    </div>
    <div>
     <img src="Images/icons8-natural-user-interface-2-filled-50.png">
     <h3>Fast access</h3>
     <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
    </div>
   </div>
  </section>
  <section id="lastsection">
   <img src="Images/board-1362851_1280.png">
   <div>
    <h2>Register now and enjoy<br>
    the best of Finances.</h2>Create an account
   </div>
  </section>
 </main>
 <footer>
  <img src="Images/icons8-fund-accounting-80.png">
  <div>
   <p>A work of Bruno Sdoukos.</p>
  </div>
 </footer>
</body>
</html></code>```

答:
Actually it's not hidden. The links in the header just happen to have a color that's close enough to white that the contrast is really low. They're overflowing the right side of the header when the header's content is wider than the viewport.

The simplest solution would be to give flex-wrap:wrap to header, but I recommend using a media query to override the display:flex instead (for better backwards compatibility).

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html,
body,
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 99.13vw;
}

body {
  font-family: 'Open Sans', sans-serif;
  margin: 0;
}

h2,
h3 {
  margin-top: 10px;
  margin-bottom: 10px;
}

a {
  text-decoration: none;
  transition: 0.2s linear;
}

header {
  background-color: rgb(93, 158, 76);
  display: flex;
  align-items: center;
  padding: 10px 30px;
  width: 100%;
}

@media all and (max-width:56em) {
  header {
    display: block;
  }
  header>a,
  header>nav {
    display: inline-block;
  }
}

header img {
  width: 45px;
}

header h1 {
  font-family: 'Doppio One', cursive;
  margin-left: 10px;
  color: rgb(214, 245, 210);
}

nav ul {
  display: flex;
  list-style: none;
}

nav ul li a {
  margin-left: 55px;
}

nav a {
  color: rgb(230, 245, 229);
  font-size: 17px;
}

nav a:hover {
  background-color: rgb(143, 182, 135);
  padding: 10px 15px;
  margin: 0 -15px 0 40px;
}

nav img {
  display: none;
  width: 30px;
  height: 35px;
}

#firstsection {
  background-image: url(Images/coffee-3289259_1280.jpg);
  background-size: cover;
  height: 900px;
  position: relative;
}

#firstsection div {
  margin-top: 0;
  position: absolute;
  left: 100px;
  top: 150px;
  color: rgb(47, 119, 27);
  text-align: center;
}

#firstsection h1 {
  margin-bottom: 45px;
}

#firstsection div a {
  font-weight: bold;
  border: 2px solid rgb(47, 119, 27);
  padding: 13px 30px;
  font-size: 16.5px;
  color: rgb(47, 119, 27);
}

#firstsection div a:hover {
  color: rgb(133, 163, 131);
  border: 2px solid rgb(133, 163, 131);
}

#textboxes {
  display: flex;
  margin-top: 50px;
  flex-wrap: wrap;
}

#textboxes div {
  text-align: center;
  margin: 15px 60px;
  border: 2px solid rgb(93, 158, 76);
  padding: 30px 30px;
  width: 27%;
}

#middlesection img:first-of-type {
  width: 55px;
}

#middlesection h2 {
  text-align: center;
  width: 100%;
}

#lastsection {
  text-align: center;
}

#lastsection img {
  width: 30%;
  margin: 100px auto 0px;
}

#lastsection div {
  position: relative;
  bottom: 450px;
}

#lastsection div a:visited {
  color: blue;
}

footer {
  background-color: rgb(93, 158, 76);
  padding: 15px;
  color: rgb(214, 245, 210);
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}

footer img {
  height: 35px;
  width: 35px;
  margin-right: 15px;
}

footer div {
  text-align: center;
}

@media screen and (max-width: 800px) {
  #textboxes div {
    width: 100%;
  }
  #lastsection img {
    width: 85%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title>Finances | Manage your money easily</title>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Control you spending and manage your money easily. Your finances by the short hairs." name="description">
  <meta content="Bruno M. B. Sdoukos" name="author">
  <meta content="finances, managing money, spending control" name="keywords">
  <link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>

<body>
  <header>
    <img src="Images/icons8-fund-accounting-80.png">

      <h1>Finances</h1>

    <nav>
      <ul>
        <li>
          Home
        </li>
        <li>
          About
        </li>
        <li>
          Contact us
        </li>
        <li>
          Register
        </li>
        <li>
          Login
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section id="firstsection">
      <div>
        <h1>Manage your money easily, anywhere, anytime.</h1>Get started
      </div>
    </section>
    <section id="middlesection">
      <div id="textboxes">
        <div>
          <img src="Images/icons8-increase-64.png">
          <h3>Concrete data</h3>
          <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
        </div>
        <div>
          <img src="Images/icons8-navigation-toolbar-left-filled-50%20(1).png">
          <h3>Easy interface</h3>
          <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
        </div>
        <div>
          <img src="Images/icons8-natural-user-interface-2-filled-50.png">
          <h3>Fast access</h3>
          <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
        </div>
      </div>
    </section>
    <section id="lastsection">
      <img src="Images/board-1362851_1280.png">
      <div>
        <h2>Register now and enjoy<br> the best of Finances.</h2>Create an account
      </div>
    </section>
  </main>
  <footer>
    <img src="Images/icons8-fund-accounting-80.png">
    <div>
      <p>A work of Bruno Sdoukos.</p>
    </div>
  </footer>
</body>

</html></code>```

Body:
I am studying CSS and creating a responsive web page. I have started working in a media query. When I maximize the screen, all works as expected, but when I reduce its size, the content that does not fit in the viewport is hidden, and a white space stays in its place. That space can be seen scrolling the screen to side. Why is that space appearing instead the rest of the content? I also don't understand why my content doesn't fit in the screen, because I am using percentage values to elements' width. My code is below:

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html, body, *, *::before, *::after {
 margin: 0;
 padding: 0;
 box-sizing: border-box;
}
html, body{
 width: 99.13vw;
}
body{
 font-family: 'Open Sans', sans-serif;
 margin: 0;
}
h2, h3{
 margin-top: 10px;
 margin-bottom: 10px;
}
a{
 text-decoration: none;
 transition: 0.2s linear;
}
header{
 background-color: rgb(93, 158, 76);
 display: flex;
 align-items: center;
 padding: 10px 30px;
 width: 100%;
}
header img{
 width: 45px;
}
header h1{
 font-family: 'Doppio One', cursive;
 margin-left: 10px;
 color: rgb(214, 245, 210);
}
nav ul{
 display: flex;
 list-style: none;
}
nav ul li a{
 margin-left: 55px;
}
nav a{
 color: rgb(230, 245, 229);
 font-size: 17px;
}
nav a:hover{
 background-color: rgb(143, 182, 135);
 padding: 10px 15px;
 margin: 0 -15px 0 40px;
}
nav img{
 display: none;
 width: 30px;
 height: 35px;
}
#firstsection{
 background-image: url(Images/coffee-3289259_1280.jpg);
 background-size: cover;
 height: 900px;
 position: relative;
}
#firstsection div{
 margin-top: 0;
 position: absolute;
 left: 100px;
 top: 150px;
 color: rgb(47, 119, 27);
 text-align: center;
}
#firstsection h1{
 margin-bottom: 45px;
}
#firstsection div a{
 font-weight: bold;
 border: 2px solid rgb(47, 119, 27);
 padding: 13px 30px;
 font-size: 16.5px;
 color: rgb(47, 119, 27);
}
#firstsection div a:hover{
 color: rgb(133, 163, 131);
 border: 2px solid rgb(133, 163, 131);
}
#textboxes{
 display: flex;
 margin-top: 50px;
 flex-wrap: wrap;
}
#textboxes div{
 text-align: center;
 margin: 15px 60px;
 border: 2px solid rgb(93, 158, 76);
 padding: 30px 30px;
 width: 27%;
}
#middlesection img:first-of-type{
 width: 55px;
}
#middlesection h2{
 text-align: center;
 width: 100%;
}
#lastsection{
 text-align: center;
}
#lastsection img{
 width: 30%;
 margin: 100px auto 0px;
}
#lastsection div{
 position: relative;
 bottom: 450px;
}
#lastsection div a:visited{
 color: blue;
}
footer{
 background-color: rgb(93, 158, 76);
 padding: 15px;
 color: rgb(214, 245, 210);
 font-size: 14px;
 display: flex;
 justify-content: center;
 align-items: center;
}
footer img{
 height: 35px;
 width: 35px;
 margin-right: 15px;
}
footer div{
 text-align: center;
}
@media screen and (max-width: 800px){
 #textboxes div{
  width: 100%;
 }
 #lastsection img{
  width: 85%;
 }
}

<!DOCTYPE html>

 <title>Finances | Manage your money easily</title>
 <meta charset="UTF-8">
 <meta content="width=device-width, initial-scale=1.0" name="viewport">
 <meta content="Control you spending and manage your money easily. Your finances by the short hairs." name="description">
 <meta content="Bruno M. B. Sdoukos" name="author">
 <meta content="finances, managing money, spending control" name="keywords">
 <link href="stylesheet.css" rel="stylesheet" type="text/css">

Finances

     Home

     About

     Contact us

     Register

     Login

Manage your money easily, anywhere, anytime.
Get started

Concrete data

Simple but concrete data that are the answer to all the quesions about your current money, spending and.

Easy interface

An interface easy to use, made to you who want to manage your money faster and with no problems.

Fast access

No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.

Register now and enjoy

    the best of Finances.
Create an account

A work of Bruno Sdoukos.

Body:
Actually it's not hidden. The links in the header just happen to have a color that's close enough to white that the contrast is really low. They're overflowing the right side of the header when the header's content is wider than the viewport.

The simplest solution would be to give flex-wrap:wrap to header, but I recommend using a media query to override the display:flex instead (for better backwards compatibility).

@charset "UTF-8";
@import url('https://fonts.googleapis.com/css?family=Doppio+One|Open+Sans&display=swap');
html,
body,
*,
*::before,
*::after {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  width: 99.13vw;
}

body {
  font-family: 'Open Sans', sans-serif;
  margin: 0;
}

h2,
h3 {
  margin-top: 10px;
  margin-bottom: 10px;
}

a {
  text-decoration: none;
  transition: 0.2s linear;
}

header {
  background-color: rgb(93, 158, 76);
  display: flex;
  align-items: center;
  padding: 10px 30px;
  width: 100%;
}

@media all and (max-width:56em) {
  header {
    display: block;
  }
  header>a,
  header>nav {
    display: inline-block;
  }
}

header img {
  width: 45px;
}

header h1 {
  font-family: 'Doppio One', cursive;
  margin-left: 10px;
  color: rgb(214, 245, 210);
}

nav ul {
  display: flex;
  list-style: none;
}

nav ul li a {
  margin-left: 55px;
}

nav a {
  color: rgb(230, 245, 229);
  font-size: 17px;
}

nav a:hover {
  background-color: rgb(143, 182, 135);
  padding: 10px 15px;
  margin: 0 -15px 0 40px;
}

nav img {
  display: none;
  width: 30px;
  height: 35px;
}

#firstsection {
  background-image: url(Images/coffee-3289259_1280.jpg);
  background-size: cover;
  height: 900px;
  position: relative;
}

#firstsection div {
  margin-top: 0;
  position: absolute;
  left: 100px;
  top: 150px;
  color: rgb(47, 119, 27);
  text-align: center;
}

#firstsection h1 {
  margin-bottom: 45px;
}

#firstsection div a {
  font-weight: bold;
  border: 2px solid rgb(47, 119, 27);
  padding: 13px 30px;
  font-size: 16.5px;
  color: rgb(47, 119, 27);
}

#firstsection div a:hover {
  color: rgb(133, 163, 131);
  border: 2px solid rgb(133, 163, 131);
}

#textboxes {
  display: flex;
  margin-top: 50px;
  flex-wrap: wrap;
}

#textboxes div {
  text-align: center;
  margin: 15px 60px;
  border: 2px solid rgb(93, 158, 76);
  padding: 30px 30px;
  width: 27%;
}

#middlesection img:first-of-type {
  width: 55px;
}

#middlesection h2 {
  text-align: center;
  width: 100%;
}

#lastsection {
  text-align: center;
}

#lastsection img {
  width: 30%;
  margin: 100px auto 0px;
}

#lastsection div {
  position: relative;
  bottom: 450px;
}

#lastsection div a:visited {
  color: blue;
}

footer {
  background-color: rgb(93, 158, 76);
  padding: 15px;
  color: rgb(214, 245, 210);
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}

footer img {
  height: 35px;
  width: 35px;
  margin-right: 15px;
}

footer div {
  text-align: center;
}

@media screen and (max-width: 800px) {
  #textboxes div {
    width: 100%;
  }
  #lastsection img {
    width: 85%;
  }
}

<!DOCTYPE html>
<html>

<head>
  <title>Finances | Manage your money easily</title>
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <meta content="Control you spending and manage your money easily. Your finances by the short hairs." name="description">
  <meta content="Bruno M. B. Sdoukos" name="author">
  <meta content="finances, managing money, spending control" name="keywords">
  <link href="stylesheet.css" rel="stylesheet" type="text/css">
</head>

<body>
  <header>
    <a href="index.html"><img src="Images/icons8-fund-accounting-80.png"></a>
    <a href="index.html">
      <h1>Finances</h1>
    </a>
    <nav>
      <ul>
        <li>
          <a href="index.html">Home</a>
        </li>
        <li>
          <a href="#">About</a>
        </li>
        <li>
          <a href="#">Contact us</a>
        </li>
        <li>
          <a href="#">Register</a>
        </li>
        <li>
          <a href="#">Login</a>
        </li>
      </ul>
    </nav>
  </header>
  <main>
    <section id="firstsection">
      <div>
        <h1>Manage your money easily, anywhere, anytime.</h1><a href="#">Get started</a>
      </div>
    </section>
    <section id="middlesection">
      <div id="textboxes">
        <div>
          <img src="Images/icons8-increase-64.png">
          <h3>Concrete data</h3>
          <p>Simple but concrete data that are the answer to all the quesions about your current money, spending and.</p>
        </div>
        <div>
          <img src="Images/icons8-navigation-toolbar-left-filled-50%20(1).png">
          <h3>Easy interface</h3>
          <p>An interface easy to use, made to you who want to manage your money faster and with no problems.</p>
        </div>
        <div>
          <img src="Images/icons8-natural-user-interface-2-filled-50.png">
          <h3>Fast access</h3>
          <p>No complications that make you lose time. Just some clicks and done, you are in Finances, with all you need.</p>
        </div>
      </div>
    </section>
    <section id="lastsection">
      <img src="Images/board-1362851_1280.png">
      <div>
        <h2>Register now and enjoy<br> the best of Finances.</h2><a href="#">Create an account</a>
      </div>
    </section>
  </main>
  <footer>
    <img src="Images/icons8-fund-accounting-80.png">
    <div>
      <p>A work of Bruno Sdoukos.</p>
    </div>
  </footer>
</body>

</html>


问:
How to create skewed axes?
I am trying to create something like this geology visual below that maps soil by its composition (of a given three components):

To my knowledge there is only d3.axisBottom() but nothing like d3.axis45Degrees(). So unfortunately my attempts at this visual were cut short virtually right off the bat because I can't even figure out how to set up the axes for a triangular coordinate plane.

Question

Can d3 handle such an axis configuration, or are there any other d3 methods that would be relevant for a task such as this?

答:
This question is borderline "too broad". However, I believe that it's an interesting question, since the documentation may lead someone to believe that only vertical/horizontal axes are possible.

You can always rotate the axis (any axis, be it axisBottom, axisTop, axisRight or axisLeft) and rotate the <text> elements back.

Here is a simple demo (full of magic numbers):

const svg = d3.select("svg");
const scale = d3.scaleLinear([10, 380]);
const axis = d3.axisLeft(scale);
const axis2 = d3.axisRight(scale);
const axis3 = d3.axisBottom(scale);
const axisGroup = svg.append("g")
  .attr("transform", "rotate(30, 100, 400)")
  .call(axis)
  .selectAll("text")
  .attr("transform", "rotate(-30, -10, 0)");
const axisGroup2 = svg.append("g")
  .attr("transform", "rotate(-30, 108, -378)")
  .call(axis2)
  .selectAll("text")
  .attr("transform", "rotate(30, 10, 0)");
const axisGroup3 = svg.append("g")
  .attr("transform", "translate(14,333)")
  .call(axis3)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="450" height="400"></svg></code>```

Change those magic numbers accordingly. By the way, in that triangle you shared in your question the internal angles are 60 degrees (not 45), so here I'm rotating the axes by 30 degrees.

Finally, it's worth mentioning that I just transformed (translate, rotate etc...) those axes. For a real plot, like the one in your image, you'll have to create a whole math just to calculate where in the SVG the values of the 3 coordinates will fall.

Title: How to create skewed axes?

Body:
This question is borderline "too broad". However, I believe that it's an interesting question, since the documentation may lead someone to believe that only vertical/horizontal axes are possible.

You can always rotate the axis (any axis, be it axisBottom, axisTop, axisRight or axisLeft) and rotate the <text> elements back.

Here is a simple demo (full of magic numbers):

const svg = d3.select("svg");
const scale = d3.scaleLinear([10, 380]);
const axis = d3.axisLeft(scale);
const axis2 = d3.axisRight(scale);
const axis3 = d3.axisBottom(scale);
const axisGroup = svg.append("g")
  .attr("transform", "rotate(30, 100, 400)")
  .call(axis)
  .selectAll("text")
  .attr("transform", "rotate(-30, -10, 0)");
const axisGroup2 = svg.append("g")
  .attr("transform", "rotate(-30, 108, -378)")
  .call(axis2)
  .selectAll("text")
  .attr("transform", "rotate(30, 10, 0)");
const axisGroup3 = svg.append("g")
  .attr("transform", "translate(14,333)")
  .call(axis3)

<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="450" height="400"></svg>

Change those magic numbers accordingly. By the way, in that triangle you shared in your question the internal angles are 60 degrees (not 45), so here I'm rotating the axes by 30 degrees.

Finally, it's worth mentioning that I just transformed (translate, rotate etc...) those axes. For a real plot, like the one in your image, you'll have to create a whole math just to calculate where in the SVG the values of the 3 coordinates will fall.


问:
Dompdf-Laravel not working with Unicode character
I'm using Laravel 5.5 with DOMPDF its work fine for English but not working for Unicode it's always output ???? symbol to me

Controller

```<code>namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PdfController extends Controller
{
    public function export(){
        $data['title']="Print Report";
        $pdf = PDF::loadView('pdf.invoice', $data);
        return $pdf->download('invoice.pdf');
    }
}
</code>```

Blade

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <style>
        @font-face {
            font-family: khmer;
            font-style: normal;
            font-weight: 400;
            src: url({{asset('fonts/khmer.ttf')}}) format('true-type');
        }
    </style>

</head>
<body>
    កម្ពុជាក្រោម
</body>
</html>
</code>```

Result ?????????

答:
@Plan-B

i use this package it works the same way as this Dompdf-Laravel library (Dompdf-Laravel library works great for other languages but not Khmer font).

composer require niklasravnsborg/laravel-pdf

It has a good doc about font installation: https://mpdf.github.io/

after installing the package, go to its repo https://github.com/niklasravnsborg/laravel-pdf read the instruction.

run php artisan vendor:publish select the library from the command prompt. You'll get the pdf.php in config directory

Now you need to choose appropriate Khmer fonts from the doc https://mpdf.github.io/fonts-languages/available-fonts-v6.html

In the doc, it recommends from two Khmer font websites. You must download the fonts from the websites otherwise the fonts will not display correctly.

download the fonts and store somewhere in the project - by default, the config/pdf.php choose resources/fonts directory
And here is my setup in the pdf.php

// some code here...
'font_path' => base_path('resources/fonts/'),
  'font_data' => [
    "khmerosmoul" => [/* Khmer */
      'R' => "KhmerOSmuol.ttf",
      'useOTL' => 0xFF,
    ],
    "khmerosmoullight" => [/* Khmer */
      'R' => "KhmerOSmuollight.ttf",
      'useOTL' => 0xFF,
    ],
    "khmerosbokor" => [/* Khmer */
      'R' => "KhmerOSBokor.ttf",
      'useOTL' => 0xFF,
    ],
    "khmerosmoulpali" => [/* Khmer */
      'R' => "KhmerOSmuolpali.ttf",
      'useOTL' => 0xFF,
      'useKashida' => 75
    ]
    // ...add as many as you want.
  ]
```

Note: you might got trouble with the pdf html structure. Copy its template example form the repo and redesign it as you like.
https://github.com/niklasravnsborg/laravel-pdf/blob/master/tests/views/exposify-expose.html

ContentLicense: CC BY-SA 3.0

Body:
I'm using Laravel 5.5 with DOMPDF its work fine for English but not working for Unicode it's always output ???? symbol to me

Controller

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;

class PdfController extends Controller
{
    public function export(){
        $data['title']="Print Report";
        $pdf = PDF::loadView('pdf.invoice', $data);
        return $pdf->download('invoice.pdf');
    }
}

Blade

<!doctype html>

    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    កម្ពុជាក្រោម

Result ?????????

Body:
@Plan-B

i use this package it works the same way as this Dompdf-Laravel library (Dompdf-Laravel library works great for other languages but not Khmer font).

composer require niklasravnsborg/laravel-pdf

It has a good doc about font installation: https://mpdf.github.io/

after installing the package, go to its repo https://github.com/niklasravnsborg/laravel-pdf read the instruction.

run php artisan vendor:publish select the library from the command prompt. You'll get the pdf.php in config directory

Now you need to choose appropriate Khmer fonts from the doc https://mpdf.github.io/fonts-languages/available-fonts-v6.html

In the doc, it recommends from two Khmer font websites. You must download the fonts from the websites otherwise the fonts will not display correctly.

download the fonts and store somewhere in the project - by default, the config/pdf.php choose resources/fonts directory
And here is my setup in the pdf.php

// some code here...
'font_path' => base_path('resources/fonts/'),
  'font_data' => [
    "khmerosmoul" => [/* Khmer */
      'R' => "KhmerOSmuol.ttf",
      'useOTL' => 0xFF,
    ],
    "khmerosmoullight" => [/* Khmer */
      'R' => "KhmerOSmuollight.ttf",
      'useOTL' => 0xFF,
    ],
    "khmerosbokor" => [/* Khmer */
      'R' => "KhmerOSBokor.ttf",
      'useOTL' => 0xFF,
    ],
    "khmerosmoulpali" => [/* Khmer */
      'R' => "KhmerOSmuolpali.ttf",
      'useOTL' => 0xFF,
      'useKashida' => 75
    ]
    // ...add as many as you want.
  ]

Note: you might got trouble with the pdf html structure. Copy its template example form the repo and redesign it as you like.
https://github.com/niklasravnsborg/laravel-pdf/blob/master/tests/views/exposify-expose.html


问:
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array

```<code>HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        3,
        4,
        5,
        6,
        9,
        10
    ],
    "cardio": [
        4
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        1,
        2,
        7,
        8
    ],
    "cardio": []
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": [
        2,
        3,
        4
    ]
}
]
</code>```

Serializer (So I want to display the title and not the id for every exercise)

```<code>class WorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        fields = ('id', 'title', 'description', 'exercises', 'cardio')
</code>```

Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :)

```<code>class Bodypart(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Exercise(models.Model):
    name = models.CharField(max_length=40)
    bodyparts = models.ManyToManyField(Bodypart, blank=True)

    def __str__(self):
        return self.name

class Cardio(models.Model):
    name = models.CharField(max_length=40)
    time = models.IntegerField(default=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cardio'

class Workout(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=1000, blank=True)
    exercises = models.ManyToManyField(Exercise, blank=True)
    cardio = models.ManyToManyField(Cardio, blank=True)

    def __str__(self):
        return self.title
</code>```

答:
You can get this by changing your WorkoutSerializer like this

```<code>class WorkoutSerializer(serializers.ModelSerializer):
    exercises = serializers.StringRelatedField(many=True, read_only=True)
    class Meta:
        fields = ('id', 'title', 'description', 'exercises', 'cardio', )
</code>```

You will get the result json like this

```<code>[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        "Exercise 1",
        "Exercise 2",
        "Exercise 4",
        "Exercise 3"
    ],
    "cardio": [
        4
    ]
},
...
</code>```

More about django rest serializers see https://www.django-rest-framework.org/api-guide/relations/

Body:
Django Rest Api - ManyToManyField, Display 'title' instead of 'id' in the Exercises Array

HTTP 200 OK
Allow: GET, POST, PUT, DELETE, PATCH
Content-Type: application/json
Vary: Accept

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        3,
        4,
        5,
        6,
        9,
        10
    ],
    "cardio": [
        4
    ]
},
{
    "id": 2,
    "title": "Pull Workout Loddekopinge",
    "description": "",
    "exercises": [
        1,
        2,
        7,
        8
    ],
    "cardio": []
},
{
    "id": 3,
    "title": "CardioPass",
    "description": "",
    "exercises": [],
    "cardio": [
        2,
        3,
        4
    ]
}
]

Serializer (So I want to display the title and not the id for every exercise)

class WorkoutSerializer(serializers.ModelSerializer):
    class Meta:
        model = Workout
        fields = ('id', 'title', 'description', 'exercises', 'cardio')

Here are the models, note that I want to display the exercise name for every exercise in the api array, I don't want the id! - That is passed right now! :)

class Bodypart(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Exercise(models.Model):
    name = models.CharField(max_length=40)
    bodyparts = models.ManyToManyField(Bodypart, blank=True)

    def __str__(self):
        return self.name

class Cardio(models.Model):
    name = models.CharField(max_length=40)
    time = models.IntegerField(default=10)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = 'cardio'

class Workout(models.Model):
    title = models.CharField(max_length=120)
    description = models.CharField(max_length=1000, blank=True)
    exercises = models.ManyToManyField(Exercise, blank=True)
    cardio = models.ManyToManyField(Cardio, blank=True)

    def __str__(self):
        return self.title

Body:
You can get this by changing your WorkoutSerializer like this

class WorkoutSerializer(serializers.ModelSerializer):
    exercises = serializers.StringRelatedField(many=True, read_only=True)
    class Meta:
        fields = ('id', 'title', 'description', 'exercises', 'cardio', )

You will get the result json like this

[
{
    "id": 1,
    "title": "Push Workout Bjarred",
    "description": "Kör Hårt!",
    "exercises": [
        "Exercise 1",
        "Exercise 2",
        "Exercise 4",
        "Exercise 3"
    ],
    "cardio": [
        4
    ]
},
...

More about django rest serializers see https://www.django-rest-framework.org/api-guide/relations/


问:
Find an element using href and click on it. Copying xpath does not work
I am trying to scrape some information off this website using python's selenium.

First, I log into the website and get to the page. Then, I would like to click on the tab "Quickscan" to scrape some info. However, that's where I get stuck. I can't find a way to click on the tab.

Note that this problem would be surmounted if I managed to navigate to the page, though when I log in, even if I put such page in my WebDriver, I still get redirected to this one.

To get to the desired page I have tried finding the element both through the xpath and through the link, but it does not find the element.

```<code>import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

driver =webdriver.Chrome(executable_path ="mypath")

driver.get("https://vc4a.com/ventures/autocollect/#quickscan-tab")

#find username and password bar
username = driver.find_element_by_id("user_login")
password = driver.find_element_by_id("user_pass")

#Input password and username
username.send_keys("username")
password.send_keys("password")

#click on submit
driver.find_element_by_name("wp-submit").click()
driver.find_element_by_name("rememberme").click()

#try to find element using text in the link
driver.find_elements_by_link_text('#quickscan-tab')[0].click()

#try to find element using xpath from the inspected element
driver.find_element_by_xpath('//*[@id="subnav"]/li[3]/a').click()
</code>```

I would like to be able to open the tab so that I can scrape the content.

When I use the first code it returns the following error:

```<code>IndexError: list index out of range
</code>```

However, by inspecting the page I can see there is indeed 2 elements with the text "#quickscan-tab", so I don't understand why the index 0 would be out of range.

When I use the second code it returns the following error:

```<code>NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="subnav"]/li[3]/a"}
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.5 x86_64)
</code>```

What I did was just copying the xpath.

答:
Try this:</p>

```<code>scanelements = driver.find_elements_by_xpath('//*[@id='quickscan-tab']')
for elt in scanelements :
   elt.click()
   break
</code>```

Body:
I am trying to scrape some information off this website using python's selenium.

First, I log into the website and get to the page. Then, I would like to click on the tab "Quickscan" to scrape some info. However, that's where I get stuck. I can't find a way to click on the tab.

Note that this problem would be surmounted if I managed to navigate to the page, though when I log in, even if I put such page in my WebDriver, I still get redirected to this one.

To get to the desired page I have tried finding the element both through the xpath and through the link, but it does not find the element.

import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

driver =webdriver.Chrome(executable_path ="mypath")

driver.get("https://vc4a.com/ventures/autocollect/#quickscan-tab")

#find username and password bar
username = driver.find_element_by_id("user_login")
password = driver.find_element_by_id("user_pass")

#Input password and username
username.send_keys("username")
password.send_keys("password")

#click on submit
driver.find_element_by_name("wp-submit").click()
driver.find_element_by_name("rememberme").click()

#try to find element using text in the link
driver.find_elements_by_link_text('#quickscan-tab')[0].click()

#try to find element using xpath from the inspected element
driver.find_element_by_xpath('//*[@id="subnav"]/li[3]/a').click()

I would like to be able to open the tab so that I can scrape the content.

When I use the first code it returns the following error:

IndexError: list index out of range

However, by inspecting the page I can see there is indeed 2 elements with the text "#quickscan-tab", so I don't understand why the index 0 would be out of range.

When I use the second code it returns the following error:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="subnav"]/li[3]/a"}
  (Session info: chrome=74.0.3729.169)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Mac OS X 10.14.5 x86_64)

What I did was just copying the xpath.

Body:
Try this:

scanelements = driver.find_elements_by_xpath('//*[@id='quickscan-tab']')
for elt in scanelements :
   elt.click()
   break