问:
How to call Multiple Website Store in sub folder of main magento installation?
How to call Multiple Website Store in sub folder of main magento installation?

HowMultiple Website Store call in sub folder of main magento installation directoy with same bakend.

Index.php

```<code>$mageFilename = '../app/Mage.php';
require_once $mageFilename;
/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'abc';
/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'website';
Mage::run($mageRunCode, $mageRunType);
</code>```

.htaccess File is:

```<code>RewriteCond %{REQUEST_URI} ^/abc/$
RewriteRule .* - [E=MAGE_RUN_CODE:store]
RewriteCond %{ENV:REDIRECT_MAGE_RUN_CODE} (.+)
RewriteRule .* - [E=MAGE_RUN_CODE:%1]
</code>```

But then after category URL go to 404 page.

答:
So you can remove either the .htaccess or index.php override. </p>

```<code>$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = $mageRunCode;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = $mageRunType;
</code>```

Body:
How to call Multiple Website Store in sub folder of main magento installation?

HowMultiple Website Store call in sub folder of main magento installation directoy with same bakend.

Index.php

$mageFilename = '../app/Mage.php';
require_once $mageFilename;
/* Store or website code */
$mageRunCode = isset($_SERVER['MAGE_RUN_CODE']) ? $_SERVER['MAGE_RUN_CODE'] : 'abc';
/* Run store or run website */
$mageRunType = isset($_SERVER['MAGE_RUN_TYPE']) ? $_SERVER['MAGE_RUN_TYPE'] : 'website';
Mage::run($mageRunCode, $mageRunType);

.htaccess File is:

RewriteCond %{REQUEST_URI} ^/abc/$
RewriteRule .* - [E=MAGE_RUN_CODE:store]
RewriteCond %{ENV:REDIRECT_MAGE_RUN_CODE} (.+)
RewriteRule .* - [E=MAGE_RUN_CODE:%1]

But then after category URL go to 404 page.

Body:
So you can remove either the .htaccess or index.php override.

$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE] = $mageRunCode;
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_TYPE] = $mageRunType;


来源: stackexchange

问:
Implementing Ecwid on a Angular 8 Application with script tags
I'm working on a website based on the latest Angular 8 version and I need to implement a Ecwid e-shop page on one of my components with the following code generated by Ecwid:

```<code><div id="my-store-24629028"></div>
<div>
  <script
    data-cfasync="false"
    type="text/javascript"
    src="https://app.ecwid.com/script.js?24629028&data_platform=code&data_date=2020-02-17"
    charset="utf-8"
  ></script>
  <script type="text/javascript">
    xProductBrowser(
      'categoriesPerRow=3',
      'views=grid(20,3) list(60) table(60)',
      'categoryView=grid',
      'searchView=list',
      'id=my-store-24629028',
    );
  </script>
</div>
</code>```

Angular generates the component and the

 section but none of the scripts is rendered.. and so my e-shop page isn't rendered. From what I could find online it's a design choice from the Angular Team but isn't there any option or solution to disable this ?

The closest solution for the first script I've found is this stackoverflow thread but I don't see how to handle the second script tag Ecwid generates..

UPDATE

TS File:

```<code>import { Component, Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.scss'],
})
export class ShopComponent implements OnInit {
  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document: Document) {}

  public ngOnInit() {
    const script = this.renderer2.createElement('script');
    script.type = `text/javascript`;
    script.src = 'https://app.ecwid.com/script.js?24629028&data_platform=code&data_date=2020-02-17';

    const script2 = this.renderer2.createElement('script');
    script2.type = `text/javascript`;
    script2.text = `
      xProductBrowser(
        'categoriesPerRow=3',
        'views=grid(20,3) list(60) table(60)',
        'categoryView=grid',
        'searchView=list',
        'id=my-store-24629028',
      );
        `;

    this.renderer2.appendChild(this.document.getElementById('toto'), script);
    this.renderer2.appendChild(this.document.getElementById('toto'), script2);
  }
}
</code>```

After following @Supporterino advices I managed to inject both scripts on the HTML sadly I'm now facing a variable not defined error:

```<code>Uncaught ReferenceError: xProductBrowser is not defined
    at <anonymous>:2:7
    at EmulatedEncapsulationDomRenderer2.push../node_modules/@angular/platform-browser/fesm5/platform-browser.js.DefaultDomRenderer2.appendChild (platform-browser.js:1100)
    at DebugRenderer2.push../node_modules/@angular/core/fesm5/core.js.DebugRenderer2.appendChild (core.js:30407)
    at ShopComponent.push../src/app/pages/shop/shop.component.ts.ShopComponent.ngOnInit (shop.component.ts:30)
    at checkAndUpdateDirectiveInline (core.js:21096)
    at checkAndUpdateNodeInline (core.js:29494)
    at checkAndUpdateNode (core.js:29456)
    at debugCheckAndUpdateNode (core.js:30090)
    at debugCheckDirectivesFn (core.js:30050)
    at Object.eval [as updateDirectives] (ShopComponent_Host.ngfactory.js? [sm]:1)
</code>```

SOLUTION

So after a few hours trying to handle the script loading @juvs anwser helped getting this implementation to finally work !

Final TS File

```<code>import { Component, Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.scss'],
})
export class ShopComponent implements OnInit {
  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document: Document) {}

  public ngOnInit() {
    const storeId = 24629028;
    const script = this.renderer2.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('charset', 'utf-8');
    script.setAttribute('data-cfasync', 'false');
    script.setAttribute('src', `https://app.ecwid.com/script.js?${storeId}&data_platform=code&data_date=2020-02-17`);
    script.onload = this.injectEcwidProductBrowser(storeId);

    this.renderer2.appendChild(this.document.getElementById('ecwidScriptsSection'), script);
  }

  private injectEcwidProductBrowser(storeId) {
    return () => {
      const ecwidBrowserScript = document.createElement('script');
      ecwidBrowserScript.setAttribute('type', 'text/javascript');
      ecwidBrowserScript.setAttribute('charset', 'utf-8');
      ecwidBrowserScript.text = `xProductBrowser("categoriesPerRow=3","views=grid(20,3) list(60) table(60)","categoryView=grid","searchView=list","id=my-store-${storeId}");`;
      document.head.appendChild(ecwidBrowserScript);
    };
  }
}
</code>```

Final HTML File

```<code><div id="my-store-24629028"></div>
<div id="ecwidScriptsSection"></div>
</code>```

Hope this helps someone in the future cause as of right now there's actually not that much information around, even Ecwid support say they don't support Angular2 & AngularJS ..

答: You could take a look at this answer https://stackoverflow.com/a/43559644/11193058 which describes how to work around the removable of the script tag and use this method to inject your javascript code.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a website based on the latest Angular 8 version and I need to implement a Ecwid e-shop page on one of my components with the following code generated by Ecwid:

Angular generates the component and the

 section but none of the scripts is rendered.. and so my e-shop page isn't rendered. From what I could find online it's a design choice from the Angular Team but isn't there any option or solution to disable this ?

The closest solution for the first script I've found is this stackoverflow thread but I don't see how to handle the second script tag Ecwid generates..

UPDATE

TS File:

import { Component, Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.scss'],
})
export class ShopComponent implements OnInit {
  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document: Document) {}

  public ngOnInit() {
    const script = this.renderer2.createElement('script');
    script.type = `text/javascript`;
    script.src = 'https://app.ecwid.com/script.js?24629028&data_platform=code&data_date=2020-02-17';

    const script2 = this.renderer2.createElement('script');
    script2.type = `text/javascript`;
    script2.text = `
      xProductBrowser(
        'categoriesPerRow=3',
        'views=grid(20,3) list(60) table(60)',
        'categoryView=grid',
        'searchView=list',
        'id=my-store-24629028',
      );
        `;

    this.renderer2.appendChild(this.document.getElementById('toto'), script);
    this.renderer2.appendChild(this.document.getElementById('toto'), script2);
  }
}

After following @Supporterino advices I managed to inject both scripts on the HTML sadly I'm now facing a variable not defined error:

Uncaught ReferenceError: xProductBrowser is not defined
    at <anonymous>:2:7
    at EmulatedEncapsulationDomRenderer2.push../node_modules/@angular/platform-browser/fesm5/platform-browser.js.DefaultDomRenderer2.appendChild (platform-browser.js:1100)
    at DebugRenderer2.push../node_modules/@angular/core/fesm5/core.js.DebugRenderer2.appendChild (core.js:30407)
    at ShopComponent.push../src/app/pages/shop/shop.component.ts.ShopComponent.ngOnInit (shop.component.ts:30)
    at checkAndUpdateDirectiveInline (core.js:21096)
    at checkAndUpdateNodeInline (core.js:29494)
    at checkAndUpdateNode (core.js:29456)
    at debugCheckAndUpdateNode (core.js:30090)
    at debugCheckDirectivesFn (core.js:30050)
    at Object.eval [as updateDirectives] (ShopComponent_Host.ngfactory.js? [sm]:1)

SOLUTION

So after a few hours trying to handle the script loading @juvs anwser helped getting this implementation to finally work !

Final TS File

import { Component, Renderer2, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-shop',
  templateUrl: './shop.component.html',
  styleUrls: ['./shop.component.scss'],
})
export class ShopComponent implements OnInit {
  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document: Document) {}

  public ngOnInit() {
    const storeId = 24629028;
    const script = this.renderer2.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('charset', 'utf-8');
    script.setAttribute('data-cfasync', 'false');
    script.setAttribute('src', `https://app.ecwid.com/script.js?${storeId}&data_platform=code&data_date=2020-02-17`);
    script.onload = this.injectEcwidProductBrowser(storeId);

    this.renderer2.appendChild(this.document.getElementById('ecwidScriptsSection'), script);
  }

  private injectEcwidProductBrowser(storeId) {
    return () => {
      const ecwidBrowserScript = document.createElement('script');
      ecwidBrowserScript.setAttribute('type', 'text/javascript');
      ecwidBrowserScript.setAttribute('charset', 'utf-8');
      ecwidBrowserScript.text = `xProductBrowser("categoriesPerRow=3","views=grid(20,3) list(60) table(60)","categoryView=grid","searchView=list","id=my-store-${storeId}");`;
      document.head.appendChild(ecwidBrowserScript);
    };
  }
}

Final HTML File

Hope this helps someone in the future cause as of right now there's actually not that much information around, even Ecwid support say they don't support Angular2 & AngularJS ..


问:
How to hide url in the popup window opened using window.open
I am using below code to open a popup window in my page:

```<code>window.open("myPopupWindow.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no, addressbar=no, top=200, left=300");
</code>```

Although the url is disabled but even then it can be seen and copied. I have already set addressbar to no. How can I hide url in popup window?

答:
Simple solution open new tab after that add url to location.href.

```<code>window.open('','_blank').location.href = "url"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using below code to open a popup window in my page:

window.open("myPopupWindow.html", "_blank", "height=400, width=550, status=yes, toolbar=no, menubar=no, location=no, addressbar=no, top=200, left=300");

Although the url is disabled but even then it can be seen and copied. I have already set addressbar to no. How can I hide url in popup window?

Body:
Simple solution open new tab after that add url to location.href.

window.open('','_blank').location.href = "url"


问:
What's the difference between Text.ParserCombinators.Parsec and Text.Parsec
```<code>Text
    Text.Parsec
        Text.Parsec.ByteString
            Text.Parsec.ByteString.Lazy
        Text.Parsec.Char
        Text.Parsec.Combinator
        Text.Parsec.Error
        Text.Parsec.Expr
        Text.Parsec.Language
        Text.Parsec.Perm
        Text.Parsec.Pos
        Text.Parsec.Prim
        Text.Parsec.String
        Text.Parsec.Token
    ParserCombinators
        Text.ParserCombinators.Parsec
            Text.ParserCombinators.Parsec.Char
            Text.ParserCombinators.Parsec.Combinator
            Text.ParserCombinators.Parsec.Error
            Text.ParserCombinators.Parsec.Expr
            Text.ParserCombinators.Parsec.Language
            Text.ParserCombinators.Parsec.Perm
            Text.ParserCombinators.Parsec.Pos
            Text.ParserCombinators.Parsec.Prim
            Text.ParserCombinators.Parsec.Token
</code>```

Are they the same?

答: I believe the latter is a backwards-compatible layer for Parsec 2, implemented in terms of the newer API.</p>

Body:
Text
    Text.Parsec
        Text.Parsec.ByteString
            Text.Parsec.ByteString.Lazy
        Text.Parsec.Char
        Text.Parsec.Combinator
        Text.Parsec.Error
        Text.Parsec.Expr
        Text.Parsec.Language
        Text.Parsec.Perm
        Text.Parsec.Pos
        Text.Parsec.Prim
        Text.Parsec.String
        Text.Parsec.Token
    ParserCombinators
        Text.ParserCombinators.Parsec
            Text.ParserCombinators.Parsec.Char
            Text.ParserCombinators.Parsec.Combinator
            Text.ParserCombinators.Parsec.Error
            Text.ParserCombinators.Parsec.Expr
            Text.ParserCombinators.Parsec.Language
            Text.ParserCombinators.Parsec.Perm
            Text.ParserCombinators.Parsec.Pos
            Text.ParserCombinators.Parsec.Prim
            Text.ParserCombinators.Parsec.Token

Are they the same?


问:
Swift: click inside programmatically generated view inside table
Tried many things, but none of it worked.

My current views hierarchy:

TableView Cell

Vertical Stack View

Programmatically generated View - gesture recognizer not fired

```<code>let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)
</code>```

later in class:

```<code>    @objc private func showValuePicker(sender: UITapGestureRecognizer) {
        print("showValuePicker")
    }
</code>```

Red box is View, where i want to add click.

答:
Found a problem...

"self" was pointing to View Generating class, that has no relations to View Controller

Passing click events directly to the View Controller solved problem

Body:
Tried many things, but none of it worked.

My current views hierarchy:

TableView Cell

Vertical Stack View

Programmatically generated View - gesture recognizer not fired

let vContainer = UIView()
vContainer.translatesAutoresizingMaskIntoConstraints = false
vContainer.isUserInteractionEnabled = true
vContainer.backgroundColor = .red
//Some view generation inside box is skipped (can be seen on image)
self.vsvViewContainer.addArrangedSubview(vContainer)
var tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(showValuePicker(sender:)))
vContainer.addGestureRecognizer(tapRecognizer)

later in class:

    @objc private func showValuePicker(sender: UITapGestureRecognizer) {
        print("showValuePicker")
    }

Red box is View, where i want to add click.


问:
Empty project symfony + mongo: Attempted to load interface CommandSubscriber in index page
I have a problem with the Symfony 4 project from MongoDB

Empty project Symfony + mongo = Attempted to load interface CommandSubscriber in index page Symfony after  installation

error:

Attempted to load interface "CommandSubscriber" from namespace "MongoDB\Driver\Monitoring".
  Did you forget a "use" statement for another namespace?

```<code>doctrine/mongodb-odm                2.0.5
doctrine/mongodb-odm-bundle         4.1.0
mongodb/mongodb                     1.5.2

php-mongodb                      1.6.1-1+0~20191219.12+debian10~1.gbpe14612
</code>```

mongo 3.6.17

how to fix it?

答: php-mongodb 1.6.1 is too old, use > 1.6.7 with pecl https://www.php.net/manual/fr/mongodb.installation.pecl.php</p>

Body:
I have a problem with the Symfony 4 project from MongoDB

Empty project Symfony + mongo = Attempted to load interface CommandSubscriber in index page Symfony after  installation

error:

Attempted to load interface "CommandSubscriber" from namespace "MongoDB\Driver\Monitoring".
  Did you forget a "use" statement for another namespace?

doctrine/mongodb-odm                2.0.5
doctrine/mongodb-odm-bundle         4.1.0
mongodb/mongodb                     1.5.2

php-mongodb                      1.6.1-1+0~20191219.12+debian10~1.gbpe14612

mongo 3.6.17

how to fix it?


问:
C# - OpenOfficeXML Date Format
I am having an issue when passing some data to an Excel spreadsheet, using OOX. Thing is, everything works great, except the dates, which are shown in a numeric value instead of the datetime format. Here's my code:

```<code>private object ProcessXLSFile(PayeesWorkingHoursFullDataDTO payeesWorkingHoursFullDataDTO)
    {
        DataTable dt = Functions.ObjectToDataTable(payeesWorkingHoursFullDataDTO.ListWorkingHours);

        ExcelPackage pck = new ExcelPackage();

        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("WorkSheet1");

        //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
        ws.Cells["A1"].LoadFromDataTable(dt, true);

        string _range = "G2:G" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "#,##0.00";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
        }

        _range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        _range = "T2:T" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd-MM-yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment; filename=Payee-Grid.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.End();

        throw new NotImplementedException();
    }
</code>```

These lines are the ones where the columns should be converted to datetime:

```<code>_range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }
</code>```

But that's definitely not working.

This is the code where I create the DataTable:

```<code>public static DataTable ObjectToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }
</code>```

Debugging the columns I have been able to see that, up to the lines where I format the columns to "dd-MM-yyyy", the date information is still in datetime format. I have tried everything, but I really don't seem to be able to get this to work properly. Do you guys have any idea on how to make it work?

答: The problem was with the width of the columns. For some reason, if the width was too narrow, all text in the cells was converted to ####, weird thing. I figured it out because it was only a visual glitch, the values in the cells where the right ones. Using AutoFit() in all the cells of the grid solved the problem. Thanks everyone!</p>

Title: C# - OpenOfficeXML Date Format

Body:
I am having an issue when passing some data to an Excel spreadsheet, using OOX. Thing is, everything works great, except the dates, which are shown in a numeric value instead of the datetime format. Here's my code:

private object ProcessXLSFile(PayeesWorkingHoursFullDataDTO payeesWorkingHoursFullDataDTO)
    {
        DataTable dt = Functions.ObjectToDataTable(payeesWorkingHoursFullDataDTO.ListWorkingHours);

        ExcelPackage pck = new ExcelPackage();

        //Create the worksheet
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add("WorkSheet1");

        //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
        ws.Cells["A1"].LoadFromDataTable(dt, true);

        string _range = "G2:G" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "#,##0.00";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
        }

        _range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        _range = "T2:T" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd-MM-yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

        //Write it back to the client
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment; filename=Payee-Grid.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.End();

        throw new NotImplementedException();
    }

These lines are the ones where the columns should be converted to datetime:

_range = "J2:J" + (dt.Rows.Count + 1).ToString();
        using (ExcelRange col = ws.Cells[_range])
        {
            col.Style.Numberformat.Format = "dd/MM/yyyy";
            col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
        }

But that's definitely not working.

This is the code where I create the DataTable:

public static DataTable ObjectToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;
    }

Debugging the columns I have been able to see that, up to the lines where I format the columns to "dd-MM-yyyy", the date information is still in datetime format. I have tried everything, but I really don't seem to be able to get this to work properly. Do you guys have any idea on how to make it work?


问:
Bartender error: 'Web Service' requires the 'Enterprise Automation' edition or better to run
I am trying to add a web service following this tutorial. However, when I try to test the web service, pressing Start I am getting the above error:

Web Service Integration' requires the 'Enterprise Automation' edition
  or better to run.

BarTender version that I have is:

```<code>Program:    BarTender Designer 2016 R8
License:    Automation (3 Printers)
Version:    11.0.8.3153 (64-bit)
OS: Windows 10 Pro x64 build 18362
</code>```

I also tried Enterprise Automation edition (DEMO version) but I am getting the same error. What am I doing wrong?

答:
I had exactly the same issue, so I used ActiveX instead and it works.
My back end is running on python. See code attached. You can also convert it to work with different programming languages.</p>

```<code>import win32com.client as win32

btApp = win32.Dispatch("BarTender.Application")
btApp.Visible = True

btFormat = btApp.Formats.Open("C:\\Users\\someUser\\Desktop\\YourLabel.btw", False, "PrinterName")

btFormat.SetNamedSubStringValue("btField1", "Data1")
btFormat.SetNamedSubStringValue("btField2", "Data2")
btFormat.SetNamedSubStringValue("btField3", "Data3")

btFormat.IdenticalCopiesOfLabel = 1
btFormat.PrintOut(False, False)
btFormat.Close(1)
btApp.Quit(1)
</code>```

Body:
I am trying to add a web service following this tutorial. However, when I try to test the web service, pressing Start I am getting the above error:

Web Service Integration' requires the 'Enterprise Automation' edition
  or better to run.

BarTender version that I have is:

Program:    BarTender Designer 2016 R8
License:    Automation (3 Printers)
Version:    11.0.8.3153 (64-bit)
OS: Windows 10 Pro x64 build 18362

I also tried Enterprise Automation edition (DEMO version) but I am getting the same error. What am I doing wrong?

Body:
I had exactly the same issue, so I used ActiveX instead and it works.
My back end is running on python. See code attached. You can also convert it to work with different programming languages.

import win32com.client as win32

btApp = win32.Dispatch("BarTender.Application")
btApp.Visible = True

btFormat = btApp.Formats.Open("C:\\Users\\someUser\\Desktop\\YourLabel.btw", False, "PrinterName")

btFormat.SetNamedSubStringValue("btField1", "Data1")
btFormat.SetNamedSubStringValue("btField2", "Data2")
btFormat.SetNamedSubStringValue("btField3", "Data3")

btFormat.IdenticalCopiesOfLabel = 1
btFormat.PrintOut(False, False)
btFormat.Close(1)
btApp.Quit(1)


问:
cannot detect div's radio button no output is produced only can detect the main radio button
hi guys i tried to run a simple program using python flux and html. Im able to detect the first 2 radio button which is "Bitcoin Address" and "a transaction hash". But im not able to detect the last 3 radio button "Dual Mode", "Address Network" and "Transaction Network". when i say cant detect means after selecting the 3 div radio buttons (any of it) it will return me with no result can someone help me please.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!----<style>
      body { </b>ackground: url(https://specials-images.forbesimg.com/imageserve/5e00d824e961e1000739c13a/960x0.jpg?fit=scale); background-size:100%; }
    </style>--->
<style>
* {
  box-sizing: border-box;
}

div {
  border: double;
}

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

/* The grid: Three equal columns that floats next to each other */
.column {
  float: left;
  width: 20%;
  padding: 15px;
  text-align: center;
  font-size: 20px;
  cursor: pointer;
  color: white;
}

.containerTab {
  padding: 15px;
  color: black;
  text-align: left;

}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Closable button inside the container tab */
.closebtn {
  float: right;
  color: black;
  font-size: 35px;
  cursor: pointer;
}

</style>
<head>
</head>
<body>
<form method="post">
    <br>
    <span style="font-size: 250%"><center> Bitcoin Dashboard </center></span><br>
    <input style="font-size:15px;" type="text" name="transactionid" size="60" placeholder="Enter a Bitcoin address/transaction">
     This is:
    <input type="radio" name="gender" id ="BitcoinAddr" value="bitcoin" checked>
    <label for="BitcoinAddr">Bitcoin Address</label>

    <input style="font-size:20px;" type="submit" value="Submit"><br>
    Search depth:
    <input type="range" name="rangeInput" min="1" max="10" onchange="updateTextInput(this.value);">
    <input style="font-size:15px;" type="text" id="textInput" value="5">

    <input type="radio" name="gender" id="TrHash" value="transaction">
    <label for="TrHash">a transaction hash</label><br><br><br>
</form>
<div class="row">
  <div class="column" onclick="openTab('b1');" style="background:grey;">Plot</div>
  <div class="column" onclick="openTab('b2');" style="background:grey;">Filter Edges</div>
  <div class="column" onclick="openTab('b3');" style="background:grey;">Find Paths</div>
  <div class="column" onclick="openTab('b4');" style="background:grey;">Cluster</div>
  <div class="column" onclick="openTab('b5');" style="background:grey;">Neighbours</div>
</div>

<!------------------------------------------------------------------->
<!-- The expanding grid (hidden by default) -->
<div id="b1" class="containerTab" style="background:white">
  <!-- If you want the ability to close the container, add a close button -->
  <span onclick="this.parentElement.style.display='none'" class="closebtn">x</span>
  <form method="post">
    <span style="float: left"><b>View: </b></span>
    <center><b> Zoom: <input type="range" name="rangeInput" min="1" max="10" onchange="updateTextInput1(this.value);"><input style="font-size:15px;" type="text" id="textInput1" value="5"></b>
    <b><input style="font-size:20px;" type="checkbox" name="Label" value="Label"> Labels</b>
    <input style="font-size:20px;" type="submit" value="Submit"></center>

    <input type="radio" name="gender" id="DualMode" value="DualMode" checked>
    <label for="DualMode">Dual Mode</label><br>

    <input type="radio" name="gender" id="AddrNet" value="AddrNet">
    <label for="AddrNet">Address Network</label><br>

    <input type="radio" name="gender" id="TrNet" value="TrNet">
    <label for="TrNet">Transaction Network</label>
    <br><br>
    <div>
      {{outputresult}}
<!--     {% if result != None %}
      <img src="data:image/png;base64,{{ outputresult }}"\>
    {% endif %} -->
    </div>
  </form>
</div>
</code>```

im using flask to link with HTML.

```<code>from flask import Flask, render_template, url_for, request
import base64 #enconder, encodes the graph into html strings
from io import BytesIO # converter, convert the data into the encoder strings
from flask import Flask
from neo4j import GraphDatabase #Graphdatabase for Neo4j
from neo4j.types.graph import Node, Relationship
import networkx as nx #graph plotting tool for neo4j,create the graph without display
import time
import matplotlib as plt #displaying the graph that is plotted by networkx
plt.use('TkAgg')
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

app = Flask(__name__)

@app.route("/")
def home():
    return render_template('home.html')

@app.route("/", methods=['GET','POST'])
def index():
    # if form.validate_on_submit():
    if request.method == 'POST':
      if 'transactionid' in request.form:
          option = request.form['gender']
          option1 = request.form['gender']
          if option == "bitcoin" and option1 == "DualMode":
          # transactionaddr = request.form['transactionid']
          # newresult = generateAndConvertGraph(transactionaddr)
                newresult = "bitcoin and DualMode"
                return render_template('home.html', outputresult=newresult)
          elif option == "bitcoin" and option1 == "AddrNet":
                newresult = "bitcoin and Adress Network"
                return render_template('home.html', outputresult=newresult)
          elif option == "bitcoin" and option1 == "TrNet":
                newresult = "bitcoin and Transaction address"
                return render_template('home.html', outputresult=newresult)
          else:
            newresult = "cant detect div radio button"
            return render_template('home.html', outputresult=newresult)

      elif 'BTCamt' in request.form:
          BTCaddr = request.form['BTCamt']
          newresult = generateAndConvertGraph(BTCaddr)
          return render_template('home.html', outBTC=newresult)

    return render_template('home.html')
</code>```

答:
First, you have two @app.route( "/")'s. one which does handle the GET and POST requests and one that doesnt. Applying another route to the actual form 'handler' would be a good idea here. If only for clarity.
Your route could look like this:

```<code>@app.route("/form_handler", methods=['GET','POST'])
</code>```

Secondly, maybe it has something to do with not setting an action attribute of "form". The action attribute defines which page should be redirected to and which route the form should be posted to when submitted.
This could help: https://www.w3schools.com/html/html_forms.asp.
The value of the action attribute in your case should be: "/". If using the route like said above it should be: "/form_handler".

your form should look like this:

```<code><form method="post" action="/form_handler">
</code>```

Hope this will help.

Body:
hi guys i tried to run a simple program using python flux and html. Im able to detect the first 2 radio button which is "Bitcoin Address" and "a transaction hash". But im not able to detect the last 3 radio button "Dual Mode", "Address Network" and "Transaction Network". when i say cant detect means after selecting the 3 div radio buttons (any of it) it will return me with no result can someone help me please.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

<form method="post">

     Bitcoin Dashboard

    <input style="font-size:15px;" type="text" name="transactionid" size="60" placeholder="Enter a Bitcoin address/transaction">
     This is:
    <input type="radio" name="gender" id ="BitcoinAddr" value="bitcoin" checked>
    Bitcoin Address

    <input style="font-size:20px;" type="submit" value="Submit">

    Search depth:
    <input type="range" name="rangeInput" min="1" max="10" onchange="updateTextInput(this.value);">
    <input style="font-size:15px;" type="text" id="textInput" value="5">

    <input type="radio" name="gender" id="TrHash" value="transaction">
    a transaction hash

</form>

Plot

Filter Edges

Find Paths

Cluster

Neighbours

  x
  <form method="post">
    View:
     Zoom: <input type="range" name="rangeInput" min="1" max="10" onchange="updateTextInput1(this.value);"><input style="font-size:15px;" type="text" id="textInput1" value="5">
    <input style="font-size:20px;" type="checkbox" name="Label" value="Label"> Labels
    <input style="font-size:20px;" type="submit" value="Submit">

    <input type="radio" name="gender" id="DualMode" value="DualMode" checked>
    Dual Mode

    <input type="radio" name="gender" id="AddrNet" value="AddrNet">
    Address Network

    <input type="radio" name="gender" id="TrNet" value="TrNet">
    Transaction Network

      {{outputresult}}

  </form>

im using flask to link with HTML.

from flask import Flask, render_template, url_for, request
import base64 #enconder, encodes the graph into html strings
from io import BytesIO # converter, convert the data into the encoder strings
from flask import Flask
from neo4j import GraphDatabase #Graphdatabase for Neo4j
from neo4j.types.graph import Node, Relationship
import networkx as nx #graph plotting tool for neo4j,create the graph without display
import time
import matplotlib as plt #displaying the graph that is plotted by networkx
plt.use('TkAgg')
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

app = Flask(__name__)

@app.route("/")
def home():
    return render_template('home.html')

@app.route("/", methods=['GET','POST'])
def index():
    # if form.validate_on_submit():
    if request.method == 'POST':
      if 'transactionid' in request.form:
          option = request.form['gender']
          option1 = request.form['gender']
          if option == "bitcoin" and option1 == "DualMode":
          # transactionaddr = request.form['transactionid']
          # newresult = generateAndConvertGraph(transactionaddr)
                newresult = "bitcoin and DualMode"
                return render_template('home.html', outputresult=newresult)
          elif option == "bitcoin" and option1 == "AddrNet":
                newresult = "bitcoin and Adress Network"
                return render_template('home.html', outputresult=newresult)
          elif option == "bitcoin" and option1 == "TrNet":
                newresult = "bitcoin and Transaction address"
                return render_template('home.html', outputresult=newresult)
          else:
            newresult = "cant detect div radio button"
            return render_template('home.html', outputresult=newresult)

      elif 'BTCamt' in request.form:
          BTCaddr = request.form['BTCamt']
          newresult = generateAndConvertGraph(BTCaddr)
          return render_template('home.html', outBTC=newresult)

    return render_template('home.html')

Body:
First, you have two @app.route( "/")'s. one which does handle the GET and POST requests and one that doesnt. Applying another route to the actual form 'handler' would be a good idea here. If only for clarity.
Your route could look like this:

@app.route("/form_handler", methods=['GET','POST'])

Secondly, maybe it has something to do with not setting an action attribute of "form". The action attribute defines which page should be redirected to and which route the form should be posted to when submitted.
This could help: https://www.w3schools.com/html/html_forms.asp.
The value of the action attribute in your case should be: "/". If using the route like said above it should be: "/form_handler".

your form should look like this:

<form method="post" action="/form_handler">

Hope this will help.


问:
Why echo of combined variables in for loop doesn't work?
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

```<code>#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
</code>```

Console output:

```<code>./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell
</code>```

Thanks

答:
You're almost there. Just use an array and populate it inside the loop.

```<code>#!/usr/bin/env bash

values=()
for i in {1..3}; do
  read -p "Insert value $i: " v
  values+=("$v")
  printf '%s %s\n' "you wrote" "$v"
done

echo
echo "check of saved values:"
echo ${values[0]}
echo ${values[1]}
echo ${values[2]}
</code>```

Just keep in mind that bash arrays are starts from zero 0 index.

EDIT: As pointed out by Ivan, the zero indexed array can be change according to the value of the for loop.

```<code>#!/usr/bin/env bash
values=()
for i in {1..3}; do
  read -p "Insert value $i: " v
  values[$i]="$v"
  printf '%s %s\n' "you wrote" "$v"
done

echo
echo "check of saved values:"
echo ${values[1]}
echo ${values[2]}
echo ${values[3]}
</code>```

Body:
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3

Console output:

./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell

Thanks

Body:
You're almost there. Just use an array and populate it inside the loop.

#!/usr/bin/env bash

values=()
for i in {1..3}; do
  read -p "Insert value $i: " v
  values+=("$v")
  printf '%s %s\n' "you wrote" "$v"
done

echo
echo "check of saved values:"
echo ${values[0]}
echo ${values[1]}
echo ${values[2]}

Just keep in mind that bash arrays are starts from zero 0 index.

EDIT: As pointed out by Ivan, the zero indexed array can be change according to the value of the for loop.

#!/usr/bin/env bash
values=()
for i in {1..3}; do
  read -p "Insert value $i: " v
  values[$i]="$v"
  printf '%s %s\n' "you wrote" "$v"
done

echo
echo "check of saved values:"
echo ${values[1]}
echo ${values[2]}
echo ${values[3]}


问:
Cannot find DbContext class using dotnet ef migrations add Initial -s <project> -c <full class name from referenced project> -o <output dir>
I am trying to learn how to generate migrations using dotnet core Entity Framework.

I have an ASP.NET Core Web API project that references two projects, each containing a DBContext.

I have successfully managed to generate the migrations for one dbcontext using:

```<code>dotnet ef migrations add Initial -s <startup_project> -c <fully qualified class name from referenced project> -o <output dir>
</code>```

However, for the second DbContext it fails to find the DbContext with the message:
No DbContext named 'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext' was found.

The project file for the referenced project has the path correctly referenced with contents:

<Project Sdk="Microsoft.NET.Sdk">

  <ItemGroup>
    <ProjectReference Include="..\EventBus\EventBus.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

</Project>
```

<p>The project file for the ASP.NET Core Web API startup project is:</p>

<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk.Web">

  <ItemGroup>
    <ProjectReference Include="..\Courses.Domain\Courses.Domain.csproj" />
    <ProjectReference Include="..\Courses.Infrastructure\Courses.Infrastructure.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\WebHost.Customization\WebHost.Customization.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.AzureServiceBus" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Npgsql" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="3.0.5" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="3.0.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="MediatR" Version="8.0.0" />
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql" Version="4.1.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
    <PackageReference Include="Polly" Version="7.2.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.Http" Version="5.2.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
    <PackageReference Include="System.Reflection" Version="4.3.0" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>
</code>```

The source code for the context class that cannot be found is:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF
{
    public class IntegrationEventLogContext : DbContext
    {
        public IntegrationEventLogContext(DbContextOptions<IntegrationEventLogContext> options) : base(options)
        {
        }

        public DbSet<IntegrationEventLogEntry> IntegrationEventLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<IntegrationEventLogEntry>(ConfigureIntegrationEventLogEntry);
        }

        void ConfigureIntegrationEventLogEntry(EntityTypeBuilder<IntegrationEventLogEntry> builder)
        {
            builder.ToTable("IntegrationEventLog");

            builder.HasKey(e => e.EventId);

            builder.Property(e => e.EventId)
                .IsRequired();

            builder.Property(e => e.Content)
                .IsRequired();

            builder.Property(e => e.CreationTime)
                .IsRequired();

            builder.Property(e => e.State)
                .IsRequired();

            builder.Property(e => e.TimesSent)
                .IsRequired();

            builder.Property(e => e.EventTypeName)
                .IsRequired();
        }
    }
}
```

<p>The Startup.cs of the ASP.NET Core Web API project adds the DB Contexts is as follows: </p>

<pre class="lang-cs prettyprint-override"><code>services.AddEntityFrameworkNpgsql()
                   .AddDbContext<CourseContext>(options =>
                   {
                       options.UseNpgsql(configuration["ConnectionString"],
                           npgsqlOptionsAction: sqlOptions =>
                           {
                               sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                               sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                           });
                   },
                       ServiceLifetime.Scoped  //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   );

            services.AddDbContext<IntegrationEventLogContext>(options =>
            {
                options.UseNpgsql(configuration["ConnectionString"],
                                     npgsqlOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                         //Configuring Connection Resiliency: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                                         sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                                     });
            });
</code>```

Is it possible to generate migrations for many DbContext subclasses from within a startup project?

If so, what are the potential causes of not been able to find a DBContext class?

答:
Solved it by implementing an instance of IDesignTimeDbContextFactory. Found this solution after reading this

Now when I run...

dotnet ef migrations add Initial -s <startup_project> -c <fully.qualified.context.class.name> -o <output dir>

EntityFrameworkCore locates my second context class.

Body:
I am trying to learn how to generate migrations using dotnet core Entity Framework.

I have an ASP.NET Core Web API project that references two projects, each containing a DBContext.

I have successfully managed to generate the migrations for one dbcontext using:

dotnet ef migrations add Initial -s <startup_project> -c <fully qualified class name from referenced project> -o <output dir>

However, for the second DbContext it fails to find the DbContext with the message:
No DbContext named 'dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF.IntegrationEventLogContext' was found.

The project file for the referenced project has the path correctly referenced with contents:

<Project Sdk="Microsoft.NET.Sdk">

  <ItemGroup>
    <ProjectReference Include="..\EventBus\EventBus.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

</Project>

The project file for the ASP.NET Core Web API startup project is:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <ItemGroup>
    <ProjectReference Include="..\Courses.Domain\Courses.Domain.csproj" />
    <ProjectReference Include="..\Courses.Infrastructure\Courses.Infrastructure.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBus\EventBus.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\IntegrationEventLogEF\IntegrationEventLogEF.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\WebHost.Customization\WebHost.Customization.csproj" />
    <ProjectReference Include="..\..\..\BuildingBlocks\EventBus\EventBusRabbitMQ\EventBusRabbitMQ.csproj" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="AspNetCore.HealthChecks.AzureServiceBus" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Npgsql" Version="3.0.0" />
    <PackageReference Include="AspNetCore.HealthChecks.Rabbitmq" Version="3.0.5" />
    <PackageReference Include="AspNetCore.HealthChecks.UI.Client" Version="3.0.2" />
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="Dapper" Version="2.0.30" />
    <PackageReference Include="MediatR" Version="8.0.0" />
    <PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Npgsql" Version="4.1.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.1.2" />
    <PackageReference Include="Polly" Version="7.2.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
    <PackageReference Include="Serilog.Enrichers.Environment" Version="2.1.3" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.1.0" />
    <PackageReference Include="Serilog.Sinks.Console" Version="3.1.1" />
    <PackageReference Include="Serilog.Sinks.Http" Version="5.2.0" />
    <PackageReference Include="Serilog.Sinks.Seq" Version="4.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0" />
    <PackageReference Include="System.Reflection" Version="4.3.0" />
  </ItemGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>

The source code for the context class that cannot be found is:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace dcs3spp.courseManagementContainers.BuildingBlocks.IntegrationEventLogEF
{
    public class IntegrationEventLogContext : DbContext
    {
        public IntegrationEventLogContext(DbContextOptions<IntegrationEventLogContext> options) : base(options)
        {
        }

        public DbSet<IntegrationEventLogEntry> IntegrationEventLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.Entity<IntegrationEventLogEntry>(ConfigureIntegrationEventLogEntry);
        }

        void ConfigureIntegrationEventLogEntry(EntityTypeBuilder<IntegrationEventLogEntry> builder)
        {
            builder.ToTable("IntegrationEventLog");

            builder.HasKey(e => e.EventId);

            builder.Property(e => e.EventId)
                .IsRequired();

            builder.Property(e => e.Content)
                .IsRequired();

            builder.Property(e => e.CreationTime)
                .IsRequired();

            builder.Property(e => e.State)
                .IsRequired();

            builder.Property(e => e.TimesSent)
                .IsRequired();

            builder.Property(e => e.EventTypeName)
                .IsRequired();
        }
    }
}

The Startup.cs of the ASP.NET Core Web API project adds the DB Contexts is as follows:

services.AddEntityFrameworkNpgsql()
                   .AddDbContext<CourseContext>(options =>
                   {
                       options.UseNpgsql(configuration["ConnectionString"],
                           npgsqlOptionsAction: sqlOptions =>
                           {
                               sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                               sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                           });
                   },
                       ServiceLifetime.Scoped  //Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
                   );

            services.AddDbContext<IntegrationEventLogContext>(options =>
            {
                options.UseNpgsql(configuration["ConnectionString"],
                                     npgsqlOptionsAction: sqlOptions =>
                                     {
                                         sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name);
                                         //Configuring Connection Resiliency: https://learn.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
                                         sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorCodesToAdd: null);
                                     });
            });

Is it possible to generate migrations for many DbContext subclasses from within a startup project?

If so, what are the potential causes of not been able to find a DBContext class?


问:
Error: Connection lost: The server closed the connection node js mysql

I am getting this error. after some time. I think this error comes because MySQL is in idle. anyone suggest me to prevent this error.

```<code>Error: Connection lost: The server closed the connection.
    at Protocol.end (/var/www/html/invoice/invoice2/node_modules/mysql/lib/protocol/Protocol.js:112:13)
    at Socket.<anonymous> (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:94:28)
    at Socket.<anonymous> (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:526:10)
    at Socket.emit (events.js:333:22)
    at endReadableNT (_stream_readable.js:1204:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on Connection instance at:
    at Connection._handleProtocolError (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:423:8)
    at Protocol.emit (events.js:321:20)
    at Protocol._delegateError (/var/www/html/invoice/invoice2/node_modules/mysql/lib/protocol/Protocol.js:398:10)
    at Protocol.end (/var/www/html/invoice/invoice2/node_modules/mysql/lib/protocol/Protocol.js:116:8)
    at Socket.<anonymous> (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:94:28)
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  fatal: true,
  code: 'PROTOCOL_CONNECTION_LOST'
}
</code>```

答:
Hi when you connect mysql with normal connection with node js server , after some time your mysql client will down
so you have to connect to mysql server with pooling mechanism.

Please go through here you can find the how to connect mysql with pooling connection
(https://github.com/mysqljs/mysql#pooling-connections)

```<code>var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret',
  database        : 'my_db'
});

pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});
</code>```

Body:
I am getting this error. after some time. I think this error comes because MySQL is in idle. anyone suggest me to prevent this error.

Error: Connection lost: The server closed the connection.
    at Protocol.end (/var/www/html/invoice/invoice2/node_modules/mysql/lib/protocol/Protocol.js:112:13)
    at Socket.<anonymous> (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:94:28)
    at Socket.<anonymous> (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:526:10)
    at Socket.emit (events.js:333:22)
    at endReadableNT (_stream_readable.js:1204:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on Connection instance at:
    at Connection._handleProtocolError (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:423:8)
    at Protocol.emit (events.js:321:20)
    at Protocol._delegateError (/var/www/html/invoice/invoice2/node_modules/mysql/lib/protocol/Protocol.js:398:10)
    at Protocol.end (/var/www/html/invoice/invoice2/node_modules/mysql/lib/protocol/Protocol.js:116:8)
    at Socket.<anonymous> (/var/www/html/invoice/invoice2/node_modules/mysql/lib/Connection.js:94:28)
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:84:21) {
  fatal: true,
  code: 'PROTOCOL_CONNECTION_LOST'
}

Body:
Hi when you connect mysql with normal connection with node js server , after some time your mysql client will down
so you have to connect to mysql server with pooling mechanism.

Please go through here you can find the how to connect mysql with pooling connection
(https://github.com/mysqljs/mysql#pooling-connections)

var mysql = require('mysql');
var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : 'example.org',
  user            : 'bob',
  password        : 'secret',
  database        : 'my_db'
});

pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});


问:
Image lib - can`t reduce the quality of a image
Im trying to reduce the quality of uploaded image. Here is my code

```<code>$image_config['source_image'] = 'file.jpg';
$image_config['maintain_ratio'] = TRUE;
$image_config['quality']    = '30%';
$image_config['width'] = 1680;
$image_config['height'] = 1050;

$this->load->library('image_lib', $image_config);
$this->image_lib->resize();
</code>```

The problem is so image has the same quality as the file.jpg etc it is not reduced.

答:
Hey Nick, have you tried to display the errors?

```<code>if ( ! $this->image_lib->resize())
{
    echo $this->image_lib->display_errors();
}
</code>```

Possible errors I can think of : not giving the correct path to the file or not having installed one of the 3 image libraries (GD/GD2, NetPBM or ImageMagick)

Hope this helps!

Body:
Im trying to reduce the quality of uploaded image. Here is my code

$image_config['source_image'] = 'file.jpg';
$image_config['maintain_ratio'] = TRUE;
$image_config['quality']    = '30%';
$image_config['width'] = 1680;
$image_config['height'] = 1050;

$this->load->library('image_lib', $image_config);
$this->image_lib->resize();

The problem is so image has the same quality as the file.jpg etc it is not reduced.

Body:
Hey Nick, have you tried to display the errors?

if ( ! $this->image_lib->resize())
{
    echo $this->image_lib->display_errors();
}

Possible errors I can think of : not giving the correct path to the file or not having installed one of the 3 image libraries (GD/GD2, NetPBM or ImageMagick)

Hope this helps!


问:
Not matching sample in y axis for knn
Im trying to make my way to a sligthly more flexible knn input script than the tutorials based of the iris dataset but Im having some trouble (I think) to add the matching 2nd dimension to the numpy array in #6 and when I come to #11. the fitting.

File "G:\PROGRAMMERING\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 212, in check_consistent_length
      " samples: %r" % [int(l) for l in lengths]) ValueError: Found input variables with inconsistent numbers of samples: [150, 1]

x is (150,5) and y is (150,1). 150 is the number of samples in both, but they differ in number of fields, is this the problem and if so how do I fix it?

```<code>#1. Loading the Pandas libraries as pd
import pandas as pd
import numpy as np

#2. Read data from the file 'custom.csv' placed in your code directory
data = pd.read_csv("custom.csv")

#3. Preview the first 5 lines of the loaded data
print(data.head())
print(type(data))

#4.Test the shape of the data
print(data.shape)
df = pd.DataFrame(data)
print(df)

#5. Convert non-numericals to numericals
print(df.dtypes)
# Any object should be converted to numerical
df['species'] = pd.Categorical(df['species'])
df['species'] = df.species.cat.codes
print("outcome:")
print(df.dtypes)

#6.Convert df to numpy.ndarray
np = df.to_numpy()
print(type(np)) #this should state <class 'numpy.ndarray'>
print(data.shape)
print(np)
x = np.data
y = [df['species']]
print(y)

#K-nearest neighbor (find closest) - searach for the K nearest observations in the dataset
#The model calculates the distance to all, and selects the K nearest ones.
#8. Import the class you plan to use
from sklearn.neighbors import (KNeighborsClassifier)
#9. Pick a value for K
k = 2
#10. Instantiate the "estimator" (make an instance of the model)
knn  = KNeighborsClassifier(n_neighbors=k)
print(knn)
#11. fit the model with data/model training
knn.fit(x, y)
#12. Predict the response for a new observation
print(knn.predict([[3, 5, 4, 2]]))```
```

答:
The input prediction input is 4 columns, leaving the fifth 'species' without prediction. Also, if 'species' was the target it cannot be given as input to the knn at the same time. The pop removes this particular column from the dataFrame df.</p>

```<code>#npdf = df.to_numpy()
df = df.apply(lambda x:pd.Series(x))
y = np.asarray(df['species'])
#removes the target from the sample
df.pop('species')
x = df.to_numpy()

</code>```

Title: Not matching sample in y axis for knn

Body:
Im trying to make my way to a sligthly more flexible knn input script than the tutorials based of the iris dataset but Im having some trouble (I think) to add the matching 2nd dimension to the numpy array in #6 and when I come to #11. the fitting.

File "G:\PROGRAMMERING\Anaconda\lib\site-packages\sklearn\utils\validation.py", line 212, in check_consistent_length
      " samples: %r" % [int(l) for l in lengths]) ValueError: Found input variables with inconsistent numbers of samples: [150, 1]

x is (150,5) and y is (150,1). 150 is the number of samples in both, but they differ in number of fields, is this the problem and if so how do I fix it?

#1. Loading the Pandas libraries as pd
import pandas as pd
import numpy as np

#2. Read data from the file 'custom.csv' placed in your code directory
data = pd.read_csv("custom.csv")

#3. Preview the first 5 lines of the loaded data
print(data.head())
print(type(data))

#4.Test the shape of the data
print(data.shape)
df = pd.DataFrame(data)
print(df)

#5. Convert non-numericals to numericals
print(df.dtypes)
# Any object should be converted to numerical
df['species'] = pd.Categorical(df['species'])
df['species'] = df.species.cat.codes
print("outcome:")
print(df.dtypes)

#6.Convert df to numpy.ndarray
np = df.to_numpy()
print(type(np)) #this should state <class 'numpy.ndarray'>
print(data.shape)
print(np)
x = np.data
y = [df['species']]
print(y)

#K-nearest neighbor (find closest) - searach for the K nearest observations in the dataset
#The model calculates the distance to all, and selects the K nearest ones.
#8. Import the class you plan to use
from sklearn.neighbors import (KNeighborsClassifier)
#9. Pick a value for K
k = 2
#10. Instantiate the "estimator" (make an instance of the model)
knn  = KNeighborsClassifier(n_neighbors=k)
print(knn)
#11. fit the model with data/model training
knn.fit(x, y)
#12. Predict the response for a new observation
print(knn.predict([[3, 5, 4, 2]]))```

Body:
The input prediction input is 4 columns, leaving the fifth 'species' without prediction. Also, if 'species' was the target it cannot be given as input to the knn at the same time. The pop removes this particular column from the dataFrame df.

#npdf = df.to_numpy()
df = df.apply(lambda x:pd.Series(x))
y = np.asarray(df['species'])
#removes the target from the sample
df.pop('species')
x = df.to_numpy()


问:
How to compare two lists and if they have an equal value take the two indexes of the lists
How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them.  My code looks like this...

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        /// <summary>
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas,
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        /// </summary>
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter();

        #endregion

        #region Skapa excel

        /// <summary>
        /// Funktion som skapar de nya Excelfilerna
        /// </summary>
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count);
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count);
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    }
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i];
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}
</code>```

TestCode

```<code>    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }

    }

Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys
</code>```

This is an ish result that i whant but im just getting them scrambled so how to do this?

答:
I did not understand quite well you're question.
I looked at your code and it seems reasonable.

If you want you could take a look at LinQ, especially at the Where and Distinct extension mothods.

I hope I was useful.

Body:
How would you go about comparing two lists and saying that if these two lists have an equal value take index of the two different spots and spit out two other list values from two different lists at that index. Both lists have equally as many values both of the lists that should be compared have ids in them and the other two that are supposed to write out value have categoryNames in them.  My code looks like this...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace PrestaConverter
{
    public class ExcellCreation
    {
        #region privata variabler

        ///
        /// WhatExcelFile Håller reda på Vilken excelfil som ska sparas,
        /// Name Namnet på sparfilen,
        /// count är en räknare som ger id till Kategorierna
        ///
        Hashtable myHashtable = new Hashtable();
        private int WhatExcellFile;
        private string name = "CategoriesCatalog";
        private List<string> ColumnNames = new List<string>() {"ID",
            "Active(0/1)",
            "Name*",
            "Parent Category",
            "Root Category(0/1)",
            "Description",
            "Meta title",
            "Meta keywords",
            "Meta description",
            "URL rewritten",
            "Image URL"
        };
        private Categories categories1 = new Categories();
        private Categories categories2 = new Categories();
        private Categories categories3 = new Categories();
        private int count;
        ExcelConverter converter = new ExcelConverter();

        #endregion

        #region Skapa excel

        ///
        /// Funktion som skapar de nya Excelfilerna
        ///
        /// <param name="excelValue">Kategorinamnen sänds över till denna funktion för upplägg i ny fil</param>
        /// <param name="rowAmmount">Används till att få tag på hur många rader som ska existera i excel filen</param>
        /// <returns></returns>
        public string CreateExcel(List<Categories> categories)
        {
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

            if (xlApp == null)
            {
                return "Excel är inte korrekt installerat";
            }

            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;

            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            categories1 = categories[0];
            categories2 = categories[1];
            categories3 = categories[2];

            for(int i = 0; i < categories1.CategoryId.Count; i++)
            {
                if(categories1.NewCategoryId.Contains(categories1.CategoryId[i]) == false && categories1.CategoryId[i].Substring(3,4) == "0000")
                {
                    categories1.NewCategoryId.Add(categories1.CategoryId[i]);
                    categories1.NewCategoryName.Add(categories1.CategoryName[i]);
                }
            }
            Console.WriteLine(categories1.NewCategoryId.Count);
            for(int i = 0; i < ColumnNames.Count; i++)
            {
                xlWorkSheet.Cells[1, i + 1].Value2 = ColumnNames[i];
            }
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[2 + i , 3].Value2 = categories1.NewCategoryName[i];
                xlWorkSheet.Cells[2 + i, 4].Value2 = "Home";
            }
            for(int i = 0; i < categories2.CategoryId.Count; i++)
            {
                if(categories2.NewCategoryId.Contains(categories2.CategoryId[i]) == false && categories2.CategoryId[i].Substring(5, 2) == "00")
                {
                    categories2.NewCategoryId.Add(categories2.CategoryId[i]);
                    categories2.NewCategoryName.Add(categories2.CategoryName[i]);
                }
            }

            Console.WriteLine(categories2.NewCategoryName.Count);
            for(int i = 0; i < categories1.NewCategoryId.Count; i++)
            {
                for(int j = 0; j < categories2.NewCategoryId.Count; j++)
                {
                    if(categories1.NewCategoryId[i].Substring(0,3) == categories2.NewCategoryId[j].Substring(0, 3))
                    {
                        categories2.parentCategoryId.Add(categories1.NewCategoryId[i]);
                        categories2.parentCategoryName.Add(categories1.NewCategoryName[i]);
                    }
                }
            }
            for(int i = 0; i < categories2.parentCategoryId.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 4].Value2 = categories2.parentCategoryName[i];
            }
            for(int i = 0; i < categories2.NewCategoryName.Count; i++)
            {
                xlWorkSheet.Cells[categories1.NewCategoryId.Count + i, 3].Value2 = categories2.NewCategoryName[i];
            }

            //Here saving the file in xlsx
            xlWorkBook.SaveAs(@"C:\Users\Jens Svensson\Documents\" + name + ".xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook, misValue,
                misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            xlWorkBook.Close(true);
            xlApp.Quit();

            return "Funkar";
        }

        #endregion

        private string createId(string Id, int start, int end)
        {
            return Id.Substring(start, end);
        }
    }
}

TestCode

    public List<string> NewCategoryId = new List<string>();
    public List<string> NewCategoryName = new List<string>();

    public List<string> parentCategoryId = new List<string>();
    public List<string> parentCategoryName = new List<string>();

    parentCategoryId = <"3930000", "3930000",4230000, 5200000 >
    parentCategoryName = <"Computers", "Computers", Toys, Furniture>

    NewCategoryId = <"3931200", "4231400","5201300" "3931700">
    NewCategoryName = <"Chairs","HP","ToyCars", "Lenovo">

    for(int i = 0; i < NewCategoryId.Count; i++){

       for(int j = 0; parentCategoryId.Count; j++){
           if(parentCategoryId[j] == NewCategoryId[i]){
               Console.Write(NewCategoryId[i] + "     ")
               Console.Write(NewCategoryName[i] + "     ")
               Console.Write(parentCategoryId[j] + "   " )
               Console.Write(parentCategoryName[j] + "\n")
           }
       }

    }

Wanted result
3931700 Lenovo  3930000 Computers
3931200 HP      3930000 Computers
4231400 Chairs  4230000 Furniture
5201300 ToyCars 5201300 Toys

This is an ish result that i whant but im just getting them scrambled so how to do this?


问:
how we can split a data input where some of them are separated by one space and some with 2 space?
I have a data input as below:

```<code>[-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914]
[ 228 -114 -114  914  228 -114 -114  228  228 -114 -114  228  228 -114 -114]
</code>```

as you can see there is 1 space before  negative numbers and 2 spaces before positive.

I read file as this :

```<code>def switch(letter):
    switcher = {
        "[": "",
        "]": "",
        "\n": "@",
    }
    return switcher.get(letter, letter)

converted_data = ''
with open("/Users/naghmeh/Documents/python/core1", "r") as file:
    data = file.read()

for letter in data:
    letter = switch(letter)
    converted_data = converted_data+letter

converted_data = converted_data.split('@')
split_converted_data = []
for i in converted_data:
    i = i.split(" ")
    split_converted_data.append(i)
</code>```

which i = i.split(" ") separate by 1 space. so code can not be run correctly. how I can fix it?

答:
In the split documentation, you can find :

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

So, use split() without indicating the separator.

```<code>"-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914".split()
</code>```

Body:
I have a data input as below:

[-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914]
[ 228 -114 -114  914  228 -114 -114  228  228 -114 -114  228  228 -114 -114]

as you can see there is 1 space before  negative numbers and 2 spaces before positive.

I read file as this :

def switch(letter):
    switcher = {
        "[": "",
        "]": "",
        "\n": "@",
    }
    return switcher.get(letter, letter)

converted_data = ''
with open("/Users/naghmeh/Documents/python/core1", "r") as file:
    data = file.read()

for letter in data:
    letter = switch(letter)
    converted_data = converted_data+letter

converted_data = converted_data.split('@')
split_converted_data = []
for i in converted_data:
    i = i.split(" ")
    split_converted_data.append(i)

which i = i.split(" ") separate by 1 space. so code can not be run correctly. how I can fix it?

Body:
In the split documentation, you can find :

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

So, use split() without indicating the separator.

"-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914".split()


问:
Test SqlAlchemy session events with Flask and PyTest
I'm using the SqlAlchemy before_flush event to validate objects before saving them in the database like so:

```<code>from models import db

@event.listens_for(db.session, 'before_flush')
def validateSomething(session, flush_context, instances):
    pass
</code>```

I'd really like to test what I'm doing there. However, in my tests - I'm using pytest - a new session gets created for each test using a fixture. It is similar to this setup: http://alexmic.net/flask-sqlalchemy-pytest/ A function scoped fixture creates a transaction alongside a session and rolls back / removes them during teardown.

Since the event is registered on the (scoped) session in models.db, it doesn't fire for the events of the sessions used in the tests. Is there a way to fix this, so events get fired during tests?

答: Instead of listening for the session instance, listens_for() allows to listen to events of all instances of a session class. So replacing db.session with SignallingSession did the trick.

Body:
I'm using the SqlAlchemy before_flush event to validate objects before saving them in the database like so:

from models import db

@event.listens_for(db.session, 'before_flush')
def validateSomething(session, flush_context, instances):
    pass

I'd really like to test what I'm doing there. However, in my tests - I'm using pytest - a new session gets created for each test using a fixture. It is similar to this setup: http://alexmic.net/flask-sqlalchemy-pytest/ A function scoped fixture creates a transaction alongside a session and rolls back / removes them during teardown.

Since the event is registered on the (scoped) session in models.db, it doesn't fire for the events of the sessions used in the tests. Is there a way to fix this, so events get fired during tests?


问:
RQDA - Export categories per file in a project
I have coded a number of texts in RQDA and I am trying to export the categories in a database. I would be looking as an final result to be a Data Frame something like this:

Files   Categories
File1   Category1
File2   Category2
File3   Category3
File4   Category2
File5   Category1
```

<p>I tried the following code which I have adapted from here Rblogger:</p>

```categories <- RQDAQuery("select filecat.name as category, source.name as filename
                         from treefile, filecat, source
                         where treefile.catid=filecat.catid and treefile.fid=source.id and treefile.status=1")
```

<p>But it has resulted in an empty file so far:</p>

```str(categories)
'data.frame':   0 obs. of  2 variables:
 $ category: chr
 $ filename: chr

> dim(categories)
[1] 0 2
> summarise(categories)
data frame with 0 columns and 1 row
```

Any help is welcome.

答:
Some friend in an old email list was kind enough to help me, so here goes the answer:

```<code>codings <-RQDAQuery("select s.name as 'filename', f.name as 'codes' from source s,
                   coding c,
                   freecode f where s.id = c.fid and c.cid = f.id and s.status = 1 order by s.name")

categories <- RQDAQuery("select s.name as 'filename',
                    co.name as 'categories' from source s,
                    coding c, freecode f, codecat co,
                    treecode tr where s.id =
                    c.fid and c.cid = f.id and co.catid =
                    tr.catid and tr.cid = f.id and s.status = 1 and c.status = 1 and
                    f.status = 1 order by s.name")
</code>```

All the best

Body:
I have coded a number of texts in RQDA and I am trying to export the categories in a database. I would be looking as an final result to be a Data Frame something like this:

Files   Categories
File1   Category1
File2   Category2
File3   Category3
File4   Category2
File5   Category1

I tried the following code which I have adapted from here Rblogger:

categories <- RQDAQuery("select filecat.name as category, source.name as filename
                         from treefile, filecat, source
                         where treefile.catid=filecat.catid and treefile.fid=source.id and treefile.status=1")

But it has resulted in an empty file so far:

str(categories)
'data.frame':   0 obs. of  2 variables:
 $ category: chr
 $ filename: chr

> dim(categories)
[1] 0 2
> summarise(categories)
data frame with 0 columns and 1 row

Any help is welcome.

Body:
Some friend in an old email list was kind enough to help me, so here goes the answer:

codings <-RQDAQuery("select s.name as 'filename', f.name as 'codes' from source s,
                   coding c,
                   freecode f where s.id = c.fid and c.cid = f.id and s.status = 1 order by s.name")

categories <- RQDAQuery("select s.name as 'filename',
                    co.name as 'categories' from source s,
                    coding c, freecode f, codecat co,
                    treecode tr where s.id =
                    c.fid and c.cid = f.id and co.catid =
                    tr.catid and tr.cid = f.id and s.status = 1 and c.status = 1 and
                    f.status = 1 order by s.name")

All the best


问:
java regex : getting a substring from a string which can vary
I have a String like - "Bangalore,India=Karnataka". From this String I would like to extract only the substring "Bangalore". In this case the regex can be - (.+),.*=.*. But the problem is, the String can sometimes come like only "Bangalore". Then in that case the above regex wont work. What will be the regex to get the substring "Bangalore" whatever the String be ?

答:
Try this one:

```<code>^(.+?)(?:,.*?)?=.*$
</code>```

Explanation:

```<code>^               # Begining of the string
  (             # begining of capture group 1
    .+?         # one or more any char non-greedy
  )             # end of group 1
  (?:           # beginig of NON capture group
    ,           # a comma
    .*?         # 0 or more any char non-greedy
  )?            # end of non capture group, optional
  =             # equal sign
  .*            # 0 or more any char
$               # end of string
</code>```

Updated:
I thougth OP have to match Bangalore,India=Karnataka or Bangalore=Karnataka but as farr as I understand it is Bangalore,India=Karnataka or Bangalore so the regex is much more simpler :

```<code>^([^,]+)
</code>```

This will match, at the begining of the string, one or more non-comma character and capture them in group 1.

Body:
Try this one:

^(.+?)(?:,.*?)?=.*$

Explanation:

^               # Begining of the string
  (             # begining of capture group 1
    .+?         # one or more any char non-greedy
  )             # end of group 1
  (?:           # beginig of NON capture group
    ,           # a comma
    .*?         # 0 or more any char non-greedy
  )?            # end of non capture group, optional
  =             # equal sign
  .*            # 0 or more any char
$               # end of string

Updated:
I thougth OP have to match Bangalore,India=Karnataka or Bangalore=Karnataka but as farr as I understand it is Bangalore,India=Karnataka or Bangalore so the regex is much more simpler :

^([^,]+)

This will match, at the begining of the string, one or more non-comma character and capture them in group 1.


问:
Publishing build artifacts failed with an error: Not found PathtoPublish: D:\a\1\s\$(buildStagingDirectory)
Building CI pipeline for .Net core APIs in VSTS. But while building getting the below error.

```<code>Publishing build artifacts failed with an error: Not found PathtoPublish: D:\a\1\s\$(buildStagingDirectory)
</code>```

This is my build definition looks like

I have mentioned PathToPublish as $(buildStagingDirectory)

How do I get rid of this error??

答:
this worked for me</p>

```<code>- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: $(System.DefaultWorkingDirectory)/bin/Any CPU/Release/netcoreapp3.1
    ArtifactName: 'drop'
    publishLocation: 'Container'
</code>```

Body:
Building CI pipeline for .Net core APIs in VSTS. But while building getting the below error.

Publishing build artifacts failed with an error: Not found PathtoPublish: D:\a\1\s\$(buildStagingDirectory)

This is my build definition looks like

I have mentioned PathToPublish as $(buildStagingDirectory)

How do I get rid of this error??

Body:
this worked for me

- task: PublishBuildArtifacts@1
  inputs:
    PathtoPublish: $(System.DefaultWorkingDirectory)/bin/Any CPU/Release/netcoreapp3.1
    ArtifactName: 'drop'
    publishLocation: 'Container'