问:
Using quicksort on lists >=7000 causes stack overflow
I'm trying to test the computation time of multiple sorting algorithms on increasingly larger sets of data. Quicksort has a memory error when it reaches 7000.

I have set the recursion limit to 10**6 in order to combat the maximum recursion depth when using timsort

```<code>from random import randint
import time
import math
start = 1000
finish = 10000
inc = 1000
import  sys
sys.setrecursionlimit(10**6)
def generateNew(z):
    listt = []
    for o in range(z):
        listt.append(randint(0, z))
    return listt

...

def partition(arr,low,high):
    i = ( low-1 )
    pivot = arr[high]

    for j in range(low , high):
        if   arr[j] <= pivot:
            i = i+1
            arr[i],arr[j] = arr[j],arr[i]

    arr[i+1],arr[high] = arr[high],arr[i+1]
    return ( i+1 )
def quickSort(arr,low,high):
    if low < high:
        pi = partition(arr,low,high)
        quickSort(arr, low, pi-1)
        quickSort(arr, pi+1, high)

def quickSortTimer(unsorted):
    start = time.time()
    array = unsorted
    quickSort(array,0,len(array)-1)

    end = time.time()
    print("Quick Sort: "+str(end - start))

...

def runAll():

    for h in range(start, finish+1, inc):
        print("\n\nCurrent: "+str(h))
        unsorted = generateNew(h)
        oddEvenSortTimer(unsorted)
        #stoogeSortTimer(unsorted)
        gnomeSortTimer(unsorted)
        #bogoSortTimer(unsorted)
        binaryInserionSortTimer(unsorted)
        pancakeSortTimer(unsorted)
        bitonicSortTimer(unsorted)
        cocktailSortTimer(unsorted)
        cycleSortTimer(unsorted)
        pigeonholeSortTimer(unsorted)
        combSortTimer(unsorted)
        timSortTimer(unsorted)
        shellSortTimer(unsorted)
        bucketSortTimer(unsorted)
        radixSortTimer(unsorted)
        heapSortTimer(unsorted)
        quickSortTimer(unsorted)
        mergeSortTimer(unsorted)
        selectionSortTimer(unsorted)
        insertionSortTimer(unsorted)
        bubbleSortTimer(unsorted)
</code>```

I expect the program to continue running but instead I get the error: MemoryError: Stack overflow. This question got marked as a duplicate of another question explaining how to increase the recursion depth, but this is another error. I want to maintain the recursion depth but avoid the stack overflow error.

答:
To avoid stack overflow, use recursion on the smaller (or equal) part, then iterate back to handle the larger part.</p>

```<code>def quicksort(a, lo, hi):
    while(hi - lo > 0):
        pivot = a[hi]
        i = lo
        for j in xrange(lo, hi):
            if a[j] <= pivot:
                a[i],a[j] = a[j],a[i]
                i += 1
        a[i],a[hi] = a[hi],a[i]
        if(i - lo <= hi - i):
            quicksort(a, lo, i-1)
            lo = i+1
        else:
            quicksort(a, i+1, hi)
            hi = i-1
</code>```

Body:
I'm trying to test the computation time of multiple sorting algorithms on increasingly larger sets of data. Quicksort has a memory error when it reaches 7000.

I have set the recursion limit to 10**6 in order to combat the maximum recursion depth when using timsort

from random import randint
import time
import math
start = 1000
finish = 10000
inc = 1000
import  sys
sys.setrecursionlimit(10**6)
def generateNew(z):
    listt = []
    for o in range(z):
        listt.append(randint(0, z))
    return listt

...

def partition(arr,low,high):
    i = ( low-1 )
    pivot = arr[high]

    for j in range(low , high):
        if   arr[j] <= pivot:
            i = i+1
            arr[i],arr[j] = arr[j],arr[i]

    arr[i+1],arr[high] = arr[high],arr[i+1]
    return ( i+1 )
def quickSort(arr,low,high):
    if low < high:
        pi = partition(arr,low,high)
        quickSort(arr, low, pi-1)
        quickSort(arr, pi+1, high)

def quickSortTimer(unsorted):
    start = time.time()
    array = unsorted
    quickSort(array,0,len(array)-1)

    end = time.time()
    print("Quick Sort: "+str(end - start))

...

def runAll():

    for h in range(start, finish+1, inc):
        print("\n\nCurrent: "+str(h))
        unsorted = generateNew(h)
        oddEvenSortTimer(unsorted)
        #stoogeSortTimer(unsorted)
        gnomeSortTimer(unsorted)
        #bogoSortTimer(unsorted)
        binaryInserionSortTimer(unsorted)
        pancakeSortTimer(unsorted)
        bitonicSortTimer(unsorted)
        cocktailSortTimer(unsorted)
        cycleSortTimer(unsorted)
        pigeonholeSortTimer(unsorted)
        combSortTimer(unsorted)
        timSortTimer(unsorted)
        shellSortTimer(unsorted)
        bucketSortTimer(unsorted)
        radixSortTimer(unsorted)
        heapSortTimer(unsorted)
        quickSortTimer(unsorted)
        mergeSortTimer(unsorted)
        selectionSortTimer(unsorted)
        insertionSortTimer(unsorted)
        bubbleSortTimer(unsorted)

I expect the program to continue running but instead I get the error: MemoryError: Stack overflow. This question got marked as a duplicate of another question explaining how to increase the recursion depth, but this is another error. I want to maintain the recursion depth but avoid the stack overflow error.

Body:
To avoid stack overflow, use recursion on the smaller (or equal) part, then iterate back to handle the larger part.

def quicksort(a, lo, hi):
    while(hi - lo > 0):
        pivot = a[hi]
        i = lo
        for j in xrange(lo, hi):
            if a[j] <= pivot:
                a[i],a[j] = a[j],a[i]
                i += 1
        a[i],a[hi] = a[hi],a[i]
        if(i - lo <= hi - i):
            quicksort(a, lo, i-1)
            lo = i+1
        else:
            quicksort(a, i+1, hi)
            hi = i-1


来源: stackexchange

问:
CORS issue with Vue js
I used vuejs, with address http://localhost:8000.

When calling api, I get CORS error. Sid not succeed request headers
request

Domain from origin http://localhost:8080 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

let headers = {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': true,
};
```

答:
You need to create a "vue.config.js" with proxy configuration.

Example :

```<code> module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        ws: true,
        changeOrigin: true
      }
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: CORS issue with Vue js

Body:
You need to create a "vue.config.js" with proxy configuration.

Example :

 module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        ws: true,
        changeOrigin: true
      }
    }
  }
}


问:
Need to call function of another controller from current? Is that a right approach?
I have fresh laravel 5.7 setup for my academic project. I want to make medicine reminder project using laravel.
For this I have 2 tables :

User

Medicine

I have models and controllers for User and Medicine.

Controllers

MedicineController

UserController

MedUserController

Models

User

Medicine

Med_User

In Model, User and Medicine have relation of Many-to-Many. And to maintain Many-to-Many I have linking table User_Medicine containing foreign key of both parent tables.

Now in controller, User adds medicine details and the app should check if the medicine is already in database. If medicine is already exists app should assign its med_id with user_id in linking table. But if medicine is not exist in db app should add new medicine detail. This process is written in MedUserController.

Now problem is, I have a function to add medicine in MedicineController@store. And I want to reuse that function from current controller ( MedUserController ).

What would be the best way to do that. Please suggest.

答:
A controller is meant to elaborate inputs and provide a response object. That being said, calling a controller from another controller is a bad practice.

In your case you should handle this with a Repository Pattern meaning that you have a class responsible for creating/retrieving objects from the database, and you can call it from any controller/class.

This is a stub of what I would do

```<code>public function controllerAction() {
    $user = Auth::user();
    $medicineData = request()->all();
    $medicine = $this->medicineRepository->store($medicineData);
    $user->medicines()->attach($medicine);
}
</code>```

In the store method of the repository you can check whether the medicine already exists or it's a new one, and you always return a Medicine object.

Body:
A controller is meant to elaborate inputs and provide a response object. That being said, calling a controller from another controller is a bad practice.

In your case you should handle this with a Repository Pattern meaning that you have a class responsible for creating/retrieving objects from the database, and you can call it from any controller/class.

This is a stub of what I would do

public function controllerAction() {
    $user = Auth::user();
    $medicineData = request()->all();
    $medicine = $this->medicineRepository->store($medicineData);
    $user->medicines()->attach($medicine);
}

In the store method of the repository you can check whether the medicine already exists or it's a new one, and you always return a Medicine object.


问:
How to make a drop chance of a item on button click
I'm making a clicker type game and one section has like a mine. I want the mine when your Mininglv < 10 to have a 50% chance when you click it top drop 1 bronze. I'm new to HTML and not sure how math.random works. I want to maybe later add a way to upgrade the chance so maybe I should define the first drop chance as BronzeDropChance.

I've tried this:

```<code>var Minechance = Math.random();

function Miningaction(){
    if (MiningCexp < NextMaxMiningExp && Mininglv < 10){
        MiningCexp = MiningCexp + 1;
        if(Minechance < 0.5)
            Bronze = Bronze + 1
        document.getElementById("Bronze").innerHTML = Bronze;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;
        }else{
</code>```

This is the rest of my code for mining:

```<code>var Bronze = 0;
var Silver = 0;
var Gold = 0;
var Diamond = 0;

var Mining = 1;
var Mininglv = 1;
var MiningCexp = 0;
var MiningMexp = 100;
var NextMaxMiningExp =  MiningMexp;
var Minechance = Math.random();

function Miningaction(){
    if (MiningCexp < NextMaxMiningExp && Mininglv < 10){
        MiningCexp = MiningCexp + 1;
        if(Minechance < 0.5)
            Bronze = Bronze + 1
        document.getElementById("Bronze").innerHTML = Bronze;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;
        }else{
        Mininglv = Mininglv + 1
        MiningCexp = 0
        Mining = Mining + 1
        NextMaxMiningExp = NextMaxMiningExp * 1.5;
        document.getElementById('MiningMexp').innerHTML =
NextMaxMiningExp;
        document.getElementById('Mininglv').innerHTML = Mininglv;
        document.getElementById('MiningCexp').innerHTML = MiningCexp;
        document.getElementById('Mining').innerHTML = Mining;
    }
}
</code>```

HTML markup for reference on how I have it formatted: (I don't have a button for every skill yet just using one button to test if the skills works)

```<code>Mining: Lv <span id="Mininglv">1</span> <span id="MiningCexp">0</span> /
<span id="MiningMexp">100</span>
                    <br />
                    Fishing: Lv <span id="Fishinglv">1</span> <span
id="FishingCexp">0</span> / <span id="FishingMexp">100</span>
                    <br />
                    <button onclick="Miningaction()">Click Me!</button>
                    <br />
                </div>
</code>```

I expect after clicking the button for exp to always go up by 1 and also while mining lv below 10 for there to be a 50% chance drop of bronze so it would get added to the inventory:

But the actual output it doesn't drop any bronze at all no matter how much I click it. I'm sure I have it formatted wrong.

答: MineChance is initially set to Math.Random(), which will give you a value between 0 and 1, but it will stay as that value throughout the program. If you change the if statement to if(Math.random() < 0.5) or resetting MineChance to a new Math.random() in your statements (if you want it as a variable), otherwise it will remain as the same constant value that it is initialized to on startup.

Body:
I'm making a clicker type game and one section has like a mine. I want the mine when your Mininglv < 10 to have a 50% chance when you click it top drop 1 bronze. I'm new to HTML and not sure how math.random works. I want to maybe later add a way to upgrade the chance so maybe I should define the first drop chance as BronzeDropChance.

I've tried this:

var Minechance = Math.random();

function Miningaction(){
    if (MiningCexp < NextMaxMiningExp && Mininglv < 10){
        MiningCexp = MiningCexp + 1;
        if(Minechance < 0.5)
            Bronze = Bronze + 1
        document.getElementById("Bronze").innerHTML = Bronze;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;
        }else{

This is the rest of my code for mining:

var Bronze = 0;
var Silver = 0;
var Gold = 0;
var Diamond = 0;

var Mining = 1;
var Mininglv = 1;
var MiningCexp = 0;
var MiningMexp = 100;
var NextMaxMiningExp =  MiningMexp;
var Minechance = Math.random();

function Miningaction(){
    if (MiningCexp < NextMaxMiningExp && Mininglv < 10){
        MiningCexp = MiningCexp + 1;
        if(Minechance < 0.5)
            Bronze = Bronze + 1
        document.getElementById("Bronze").innerHTML = Bronze;
        document.getElementById("MiningCexp").innerHTML = MiningCexp;
        }else{
        Mininglv = Mininglv + 1
        MiningCexp = 0
        Mining = Mining + 1
        NextMaxMiningExp = NextMaxMiningExp * 1.5;
        document.getElementById('MiningMexp').innerHTML =
NextMaxMiningExp;
        document.getElementById('Mininglv').innerHTML = Mininglv;
        document.getElementById('MiningCexp').innerHTML = MiningCexp;
        document.getElementById('Mining').innerHTML = Mining;
    }
}

HTML markup for reference on how I have it formatted: (I don't have a button for every skill yet just using one button to test if the skills works)

Mining: Lv 1 0 /
100

                    Fishing: Lv 1 0 / 100

                    <button onclick="Miningaction()">Click Me!</button>

I expect after clicking the button for exp to always go up by 1 and also while mining lv below 10 for there to be a 50% chance drop of bronze so it would get added to the inventory:

But the actual output it doesn't drop any bronze at all no matter how much I click it. I'm sure I have it formatted wrong.


问:
Session Problem with Rails 3
I'm using Authlogic 2.1.6 for Authorization in Rails 3.0.5 and I have a session cookie problem with AJAX requests.

After a POST or PUT AJAX Call I'm getting a 401 Response and a new session key. After that every call will return a 401 response. Before the POST or PUT call every GET call succeeds.

This doesn't happen in test mode, only in development and production mode.

Does anybody know how to avoid that?

EDIT: I think there is a problem with the forgery protection authenticity key, because after disabling forgery protection everything worked fine.

This is a request header which will produce a 401:

```<code>Accept:*/*
Cache-Control:max-age=0
Content-Type:application/json; charset=UTF-8
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.19.4    (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4
X-Requested-With:XMLHttpRequest
</code>```

Rails Log entry is the following:

```<code>Started POST "/users.json" for 127.0.0.1 at Tue Apr 12 10:47:33 +0200 2011
Processing by UsersController#create as JSON
Parameters: {"user"=>{"password_confirmation"=>"[FILTERED]", "group_id"=>2, "lastname"=>"test1", "prename"=>"test1", "password"=>"[FILTERED]", "login"=>"test1"}}
Rendered text template (0.0ms)
Completed 401 Unauthorized in 19ms (Views: 0.9ms | ActiveRecord: 3.0ms)
</code>```

EDIT2:

Next weird thing: I i send a BASIC AUTH Header instead of a cookie with session ID, I'm not getting a 401, very weird

答:
A basic error with the 'forgery protection authenticity' is to forget adding the csrf_meta_tag

In your layout add it in your header tag. Without it no Ajax request is do with the good token.

If it's not with Ajax use the simple_form helper to generate the token in your form

ContentLicense: CC BY-SA 3.0

Title: Session Problem with Rails 3

Body:
I'm using Authlogic 2.1.6 for Authorization in Rails 3.0.5 and I have a session cookie problem with AJAX requests.

After a POST or PUT AJAX Call I'm getting a 401 Response and a new session key. After that every call will return a 401 response. Before the POST or PUT call every GET call succeeds.

This doesn't happen in test mode, only in development and production mode.

Does anybody know how to avoid that?

EDIT: I think there is a problem with the forgery protection authenticity key, because after disabling forgery protection everything worked fine.

This is a request header which will produce a 401:

Accept:*/*
Cache-Control:max-age=0
Content-Type:application/json; charset=UTF-8
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; de-de) AppleWebKit/533.19.4    (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4
X-Requested-With:XMLHttpRequest

Rails Log entry is the following:

Started POST "/users.json" for 127.0.0.1 at Tue Apr 12 10:47:33 +0200 2011
Processing by UsersController#create as JSON
Parameters: {"user"=>{"password_confirmation"=>"[FILTERED]", "group_id"=>2, "lastname"=>"test1", "prename"=>"test1", "password"=>"[FILTERED]", "login"=>"test1"}}
Rendered text template (0.0ms)
Completed 401 Unauthorized in 19ms (Views: 0.9ms | ActiveRecord: 3.0ms)

EDIT2:

Next weird thing: I i send a BASIC AUTH Header instead of a cookie with session ID, I'm not getting a 401, very weird


问:
How to tell object type from NSPersistentHistoryChange
I'm trying to use Persistent History Tracking to implement data synchronization with the server. The idea is that for every NSPersistentHistoryTransaction, I want to (eventually) make analogous REST requests to perform identical change on the server.

My code iterates through all the changes in the transaction. When the change is a DELETE, I can't figure out, how to tell what object type was deleted. As far as I can tell, the only thing I've got is the tombstone - which are some of the original object's fields (externalId in my case). While ID is an identifier, I also need to know what entity that ID belongs to.

The documentation for the whole Core Data feature is next to none :-/

Is this even a good use case for Persistent History Tracking?

Thanks a lot

答:
I have asked the same question on Apple Developer forum:

https://forums.developer.apple.com/thread/116951

Long story short: change.changedObjectID.entity.name is what I needed.


问:
Custom converter in ModelMapper not being fired
I am trying to conver a String to a Date but the converter doesn't seem to be fired and I'm getting a MappingException. This is my code:

```<code>    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        Converter<String, Date> dateConverter = context -> {
            Date date;
            try {
                date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
            } catch (ParseException e) {
                date = null;
            }

            System.out.println("working");
            return date;
        };

        modelMapper.addConverter(dateConverter);
        return modelMapper;
    }
</code>```

And then I just use it like this but I continue getting the same error:

```<code>Date date = this.modelMapper.map("20/12/2019", Date.class);

1) Converter org.modelmapper.internal.converter.DateConverter@27c7dc27 failed to convert java.lang.String to java.util.Date.
</code>```

It's not even printing the working word.

What am I missing?

Thanks.

答:
Okay, for some reason my dumb IDE (IntelliJ) adviced me to change the code above for how it is in the question. That's what's making it not work, having it as a lambda, it seems. With this code it works perfectly:</p>

```<code>       Converter<String, Date> dateConverter = new Converter<String, Date>()
        {
            public Date convert(MappingContext<String, Date> context)
            {
                Date date = null;
                try {
                    date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
                } catch (ParseException e) {
                    System.out.println(e.toString());
                }

                return date;
            }
        };
</code>```

Body:
I am trying to conver a String to a Date but the converter doesn't seem to be fired and I'm getting a MappingException. This is my code:

    @Bean
    public ModelMapper modelMapper() {
        ModelMapper modelMapper = new ModelMapper();
        Converter<String, Date> dateConverter = context -> {
            Date date;
            try {
                date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
            } catch (ParseException e) {
                date = null;
            }

            System.out.println("working");
            return date;
        };

        modelMapper.addConverter(dateConverter);
        return modelMapper;
    }

And then I just use it like this but I continue getting the same error:

Date date = this.modelMapper.map("20/12/2019", Date.class);

1) Converter org.modelmapper.internal.converter.DateConverter@27c7dc27 failed to convert java.lang.String to java.util.Date.

It's not even printing the working word.

What am I missing?

Thanks.

Body:
Okay, for some reason my dumb IDE (IntelliJ) adviced me to change the code above for how it is in the question. That's what's making it not work, having it as a lambda, it seems. With this code it works perfectly:

       Converter<String, Date> dateConverter = new Converter<String, Date>()
        {
            public Date convert(MappingContext<String, Date> context)
            {
                Date date = null;
                try {
                    date = new SimpleDateFormat("dd/MM/yyyy").parse(context.getSource());
                } catch (ParseException e) {
                    System.out.println(e.toString());
                }

                return date;
            }
        };


问:
Add React Component to TinyMCE Editor content
We are building an editor and we would like to use TimyMCE and React for it. We have scenarios where on an event we have to add template based content to the Editor. I am planning to design the templates as React component.

So, with TinyMCE and React, how do I add react component to the TinyMCE editor.

```<code>    export class AppEditor extends React.Component<iEditorProps, iEditorState> {

    innerEditor: React.RefObject<Editor>;

    constructor(props: iEditorProps) {
        super(props);
        this.state = {
            content: ''
        };
        this.innerEditor = React.createRef();
    }

    handleChange = (content) => {
        this.setState({ content });
    }

    handleAddContent = (e) => {
        this.setState(prevState => {
            return { content: prevState.content + <TemplateComp>Added Content</TemplateComp> }
        });
    }

    render() {
        return (
            <div>
                <Editor ref={this.innerEditor} inline onEditorChange={this.handleChange} value={this.state.content} />
            </div>);
    }
}
</code>```

In the above code at "handleAddContent" I am trying to add <TemplateComp> to the editor, but it's get's rendered as [object] [Object]. I understand string concatenation does that. TinyMCE package being used - https://github.com/tinymce/tinymce-react.

But how do I add component to editor?

答:
Concatenating string with JSX expression (which in fact is javascript object tree of virtual nodes) in

```<code>prevState.content + <TemplateComp>Added Content</TemplateComp>
</code>```

results in that you have described. You have to convert virtual DOM nodes to HTML, e.g. in following way:

```<code>prevState.content + ReactDOMServer.renderToStaticMarkup(<TemplateComp>Added Content</TemplateComp>)
</code>```

this will work, albeit it is one way route how to statically render React component to Tiny MCE editor. If you really want to place React component with its lifecycle to rich text editor consider using Draft.js or a component based on it instead of Tiny MCE.

Body:
We are building an editor and we would like to use TimyMCE and React for it. We have scenarios where on an event we have to add template based content to the Editor. I am planning to design the templates as React component.

So, with TinyMCE and React, how do I add react component to the TinyMCE editor.

    export class AppEditor extends React.Component<iEditorProps, iEditorState> {

    innerEditor: React.RefObject<Editor>;

    constructor(props: iEditorProps) {
        super(props);
        this.state = {
            content: ''
        };
        this.innerEditor = React.createRef();
    }

    handleChange = (content) => {
        this.setState({ content });
    }

    handleAddContent = (e) => {
        this.setState(prevState => {
            return { content: prevState.content + <TemplateComp>Added Content</TemplateComp> }
        });
    }

    render() {
        return (

                <Editor ref={this.innerEditor} inline onEditorChange={this.handleChange} value={this.state.content} />

);
    }
}

In the above code at "handleAddContent" I am trying to add <TemplateComp> to the editor, but it's get's rendered as [object] [Object]. I understand string concatenation does that. TinyMCE package being used - https://github.com/tinymce/tinymce-react.

But how do I add component to editor?

Body:
Concatenating string with JSX expression (which in fact is javascript object tree of virtual nodes) in

prevState.content + <TemplateComp>Added Content</TemplateComp>

results in that you have described. You have to convert virtual DOM nodes to HTML, e.g. in following way:

prevState.content + ReactDOMServer.renderToStaticMarkup(<TemplateComp>Added Content</TemplateComp>)

this will work, albeit it is one way route how to statically render React component to Tiny MCE editor. If you really want to place React component with its lifecycle to rich text editor consider using Draft.js or a component based on it instead of Tiny MCE.


问:
"Length cannot be less than zero." on a blank line
I keep getting the above error message, even if I comment out the line that the error is occurring on.  Any idea what could be causing this?  I've tried re-writing the lines with test values, but I still get the same error.

This works perfectly in debug mode, it's only in the deployment that this came up.

Original code:

```<code>Line 21:             string domain, username;
Line 22:             string text = Page.User.Identity.Name;
Line 23:
Line 24:             domain = text.Substring(0, text.IndexOf("\\"));
Line 25:             username = text.Substring(text.IndexOf("\\") + 1, text.Length - text.IndexOf("\\") - 1);

Source File: F:\<file path>\Default.aspx.cs    Line: 23
</code>```

Test code (same error):

```<code>Line 21:             string domain, username;
Line 22:             //string text = "TEST"; // Page.User.Identity.Name;
Line 23:             // this line is blank
Line 24:             domain = "TEST"; //text.Substring(0, text.IndexOf("\\"));
Line 25:             username = "TEST"; // text.Substring(text.IndexOf("\\") + 1,

Source File: F:\<file path>\Default.aspx.cs    Line: 23
</code>```

Here's the stack trace if it helps at all:

```<code>[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +12681546
Insufficiencies._Default.Page_Load(Object sender, EventArgs e) in F:\<file path>\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048
</code>```

答:
```<code>text.IndexOf("\\")
</code>```

This will return -1 if the index of the characters is not found, and taking a substring from character 0 with length of -1 will throw that error.

Another caveat of ASP.net c# is that the length parameter of a sub string also can't be larger than the actual string (Classic ASP lets you do this).

Try this:

```<code>int SlashPos = text.IndexOf("\\");
if(SlashPos > 0)
    domain = text.Substring(0, SlashPos);
else
    domain = text;
</code>```

Body:
I keep getting the above error message, even if I comment out the line that the error is occurring on.  Any idea what could be causing this?  I've tried re-writing the lines with test values, but I still get the same error.

This works perfectly in debug mode, it's only in the deployment that this came up.

Original code:

Line 21:             string domain, username;
Line 22:             string text = Page.User.Identity.Name;
Line 23:
Line 24:             domain = text.Substring(0, text.IndexOf("\\"));
Line 25:             username = text.Substring(text.IndexOf("\\") + 1, text.Length - text.IndexOf("\\") - 1);

Source File: F:\<file path>\Default.aspx.cs    Line: 23

Test code (same error):

Line 21:             string domain, username;
Line 22:             //string text = "TEST"; // Page.User.Identity.Name;
Line 23:             // this line is blank
Line 24:             domain = "TEST"; //text.Substring(0, text.IndexOf("\\"));
Line 25:             username = "TEST"; // text.Substring(text.IndexOf("\\") + 1,

Source File: F:\<file path>\Default.aspx.cs    Line: 23

Here's the stack trace if it helps at all:

[ArgumentOutOfRangeException: Length cannot be less than zero.
Parameter name: length]
System.String.InternalSubStringWithChecks(Int32 startIndex, Int32 length, Boolean fAlwaysCopy) +12681546
Insufficiencies._Default.Page_Load(Object sender, EventArgs e) in F:\<file path>\Default.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048

Body:
text.IndexOf("\\")

This will return -1 if the index of the characters is not found, and taking a substring from character 0 with length of -1 will throw that error.

Another caveat of ASP.net c# is that the length parameter of a sub string also can't be larger than the actual string (Classic ASP lets you do this).

Try this:

int SlashPos = text.IndexOf("\\");
if(SlashPos > 0)
    domain = text.Substring(0, SlashPos);
else
    domain = text;


问:
How to use google API Key into a CDN link get json format for fetch user's current Address?
I want to set User's current location for my website, I use java script geographical location, I got user's longitude and latitude, then I tried to change that into a address format, so I'm using google maps content delivery network link with my google maps applet programming interface  key, and then I pass my Content delivery network link with that longitude and latitude on my browser, but it show some JavaScript Object Notation format error message like following code,

```<code>{
   "error_message" : "This API project is not authorized to use this API.",
   "results" : [],
   "status" : "REQUEST_DENIED"
}
</code>```

What should I do for solve this issue ?

I have tried on a e-learn website html geographical location and then I added some java script codes.

I need to show a user current location like an address on my navigation bar, when user click the location icon.

答:
It's not a CDN (Content Delivery Network), which serves files, but an API (Application Programming Interface).

You need to log in to your Google developers console.

Then in the navigation menu on the left, go to APIs & services > Credentials.

Here you have your API keys, you can enable/disable restrictions to applications, domains and IP addresses that can use this key.

Unless you explicitely authorise your application to use this key, access will be denied.

Body:
I want to set User's current location for my website, I use java script geographical location, I got user's longitude and latitude, then I tried to change that into a address format, so I'm using google maps content delivery network link with my google maps applet programming interface  key, and then I pass my Content delivery network link with that longitude and latitude on my browser, but it show some JavaScript Object Notation format error message like following code,

{
   "error_message" : "This API project is not authorized to use this API.",
   "results" : [],
   "status" : "REQUEST_DENIED"
}

What should I do for solve this issue ?

I have tried on a e-learn website html geographical location and then I added some java script codes.

I need to show a user current location like an address on my navigation bar, when user click the location icon.


问:
CSS Flex One Large Div on the left and two small divs on the right
I know I can easily achieve this kind of layout using the css float which is the current way I have the divs have the layout right now. But, I am trying to recode it and change it to flex alignment.

Here is my markup:

Post 1

Post 2

Post 3

```

<p>And here is my CSS:</p>

<pre class="lang-css prettyprint-override"><code>.the-post-inner {
    clear: both;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    align-content: flex-start;
}

.the-post-inner a {
    margin-bottom: 4%;
}

.the-post-inner a .image {
      padding-bottom: 60%;
}

.the-post-inner a .content {
      padding: 20px;
}

.the-post-inner a .content h2 {
      margin: 0;
}

.the-post-inner a:first-child {
    flex: 0 0 60%;
    margin-right: 4%;
}

.the-post-inner a:not(:first-child) {
    margin-right: 0;
    flex: 0 0 36%;
    align-self: flex-start;

    overflow: hidden;
    float: left;
    display: block;
}
</code>```

I tried several codes based on the answers in other posts but I can't seem to make this work.

Thanks in advance for the suggestions.

EDIT:

I was wondering if there is a way to achieve this without changing the current markup which is not to separate the left post in another div and the right posts in another container.

https://jsfiddle.net/pextb1of/

答:
I just put some fix. maybe will help you.

.the-post-inner {
    clear: both;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    align-content: flex-start;
    flex-direction: column;
    height: 100px;
    border: 1px solid #000;
}

a {
    /*border: 1px solid #000;*/
    margin-bottom: 4%;
    /*padding: 20px;*/
}

.the-post-inner {
    flex: 0 0 60%;
    margin-right: 4%;
}

.sec-inner {
    margin-right: 0;
    flex: 0 0 36%;
    align-self: flex-start;
    flex-direction: column;

    overflow: hidden;
    float: left;
    display: flex;
}

#the-posts{
  display: flex;
  flex-direction: row;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="the-posts">
    <div class="the-post-inner">
        Post 1

    </div>
    <div class="sec-inner">
        Post 2
        Post 3
    </div>
</div></code>```

Body:
I know I can easily achieve this kind of layout using the css float which is the current way I have the divs have the layout right now. But, I am trying to recode it and change it to flex alignment.

Here is my markup:

Post 1

Post 2

Post 3

And here is my CSS:

.the-post-inner {
    clear: both;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    align-content: flex-start;
}

.the-post-inner a {
    margin-bottom: 4%;
}

.the-post-inner a .image {
      padding-bottom: 60%;
}

.the-post-inner a .content {
      padding: 20px;
}

.the-post-inner a .content h2 {
      margin: 0;
}

.the-post-inner a:first-child {
    flex: 0 0 60%;
    margin-right: 4%;
}

.the-post-inner a:not(:first-child) {
    margin-right: 0;
    flex: 0 0 36%;
    align-self: flex-start;

    overflow: hidden;
    float: left;
    display: block;
}

I tried several codes based on the answers in other posts but I can't seem to make this work.

Thanks in advance for the suggestions.

EDIT:

I was wondering if there is a way to achieve this without changing the current markup which is not to separate the left post in another div and the right posts in another container.

https://jsfiddle.net/pextb1of/

Body:
I just put some fix. maybe will help you.

.the-post-inner {
    clear: both;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    align-items: flex-start;
    align-content: flex-start;
    flex-direction: column;
    height: 100px;
    border: 1px solid #000;
}

a {
    /*border: 1px solid #000;*/
    margin-bottom: 4%;
    /*padding: 20px;*/
}

.the-post-inner {
    flex: 0 0 60%;
    margin-right: 4%;
}

.sec-inner {
    margin-right: 0;
    flex: 0 0 36%;
    align-self: flex-start;
    flex-direction: column;

    overflow: hidden;
    float: left;
    display: flex;
}

#the-posts{
  display: flex;
  flex-direction: row;
}

<div id="the-posts">
    <div class="the-post-inner">
        <a href="#">Post 1</a>

    </div>
    <div class="sec-inner">
        <a href="#">Post 2</a>
        <a href="#">Post 3</a>
    </div>
</div>


问:
How to remove SQL Azure Data Sync objects manually
Having given up on SQL Azure Data Sync for synchronizing data between two SQL Azure databases, how can I remove all the DataSync related objects (tables, triggers etc)?

E.g:

```<code>DataSync.<table>_dss_tracking
DataSync.schema_info_dss
DataSync.scope_config_dss
DataSync.scope_info_dss
</code>```

And all the other objects?  Is there a script that can be run?

答:
Microsoft released this script a while ago. Handy if you need to remove a single table</p>

```<code>declare @TableName nvarchar(max)
set @TableName = 'yourTableName'
--In case you wish to delete objects related to all the tables you can uncomment the following:
--set @TableName = ''

-- Generate the script to drop Data Sync tables
select 'drop table [DataSync].['+ st.name+ '];' from sys.tables as st join sys.schemas as ss on ss.schema_id = st.schema_id
where ss.name = 'DataSync' and st.name like '%' + @TableName + '_dss_%'

-- Generate the script to drop Data Sync stored procedures
select 'drop procedure [DataSync].['+ sp.name+ '];' from sys.procedures as sp join sys.schemas as ss on ss.schema_id = sp.schema_id
where ss.name = 'DataSync' and sp.name like '%' + @TableName + '_dss_%'

-- Generate the script to delete Data Sync triggers
select 'drop trigger [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects where type = 'TR' and name like '%' + @TableName + '_dss_%'

-- Generate the script to delete Data Sync-related udtt
select 'drop type  [DataSync].['+ st.name+ '];' from sys.types as st join sys.schemas as ss on st.schema_id = ss.schema_id
where ss.name = 'DataSync' and st.name like '%' + @TableName + '_dss_%'
</code>```

Body:
Having given up on SQL Azure Data Sync for synchronizing data between two SQL Azure databases, how can I remove all the DataSync related objects (tables, triggers etc)?

E.g:

DataSync.
_dss_tracking
DataSync.schema_info_dss
DataSync.scope_config_dss
DataSync.scope_info_dss

And all the other objects?  Is there a script that can be run?

Body:
Microsoft released this script a while ago. Handy if you need to remove a single table

declare @TableName nvarchar(max)
set @TableName = 'yourTableName'
--In case you wish to delete objects related to all the tables you can uncomment the following:
--set @TableName = ''

-- Generate the script to drop Data Sync tables
select 'drop table [DataSync].['+ st.name+ '];' from sys.tables as st join sys.schemas as ss on ss.schema_id = st.schema_id
where ss.name = 'DataSync' and st.name like '%' + @TableName + '_dss_%'

-- Generate the script to drop Data Sync stored procedures
select 'drop procedure [DataSync].['+ sp.name+ '];' from sys.procedures as sp join sys.schemas as ss on ss.schema_id = sp.schema_id
where ss.name = 'DataSync' and sp.name like '%' + @TableName + '_dss_%'

-- Generate the script to delete Data Sync triggers
select 'drop trigger [' + schema_name(schema_id) + '].[' + name + ']'
from sys.objects where type = 'TR' and name like '%' + @TableName + '_dss_%'

-- Generate the script to delete Data Sync-related udtt
select 'drop type  [DataSync].['+ st.name+ '];' from sys.types as st join sys.schemas as ss on st.schema_id = ss.schema_id
where ss.name = 'DataSync' and st.name like '%' + @TableName + '_dss_%'


问:
How to implement Repository pattern withe LinqToEntities?
How to implement Repository pattern withe LinqToEntities
how to implement the interface </p>

答:
I do the following:

A service layer contains my business objects. It is passed the repository via an Inversion of Control (Castle Windor is my usual choice). The repository is in charge of mapping between the business objects and my entity framework objects.

The advantages: You have no problems with object state or the context of the EF objects because you are just loading them during data manipulation on the repository side. This eases the situation when passing them to WCF/Web-Services.

The disadvantages: You are losing some of the tracking functionality of Entity Framework, you have to manually load the data object (ef objects), possibly if required manually to optimistic concurrency checks (via a timestamp on the business object for example).

But generally I prefer this solution, because it is possible to later change the repository. It allows me to have different repositories (for example my user object is actually using the ASPNetAuthenticationRepository instead of the EntityFrameworkRepository) but for my service layer it's transparent.

With regards to the interface, I would use the business objects from the service layer as your parameter objects and don't let those EF objects out of the repository layer.
Hope that helps

OwnerDisplayName: BigOmar

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Gidion


问:
Strip Images, CSS and JS from servlet-mapping
I am using the following servlet-mapping in my web.xml file:

```<code><servlet>
    <servlet-name>PostController</servlet-name>
    <servlet-class>com.webcodei.controller.PostController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PostController</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</code>```

To do some kind of a search. ex: ```<code> <a href="http://www.myweb.com/The" rel="nofollow noreferrer">http://www.myweb.com/The</a> search string here </code>```

But the problem is that CSS, JS and Images are treated like a search request.

There are any patterns that strip out *.css, *.js, *.gif and etc, so the requests don't need to pass through my controller?

Thank you so much, bye bye!

答: Jetty interprets web.xml as you're expecting it to.  I exposed this problem recently when I moved an application from jetty to tomcat, and all of a sudden couldn't see my static resources anymore.  Very frustrating.</p>

OwnerDisplayName: José Leal

Body:
I am using the following servlet-mapping in my web.xml file:

<servlet>
    <servlet-name>PostController</servlet-name>
    <servlet-class>com.webcodei.controller.PostController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PostController</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

To do some kind of a search. ex:
 http://www.myweb.com/The search string here

But the problem is that CSS, JS and Images are treated like a search request.

There are any patterns that strip out *.css, *.js, *.gif and etc, so the requests don't need to pass through my controller?

Thank you so much, bye bye!

LastEditorDisplayName: sblundy


答: You are passing a number less than zero into the Substring call.  I doubt your example of initializing the string to "TEST" has the same problem...

Title: "Length cannot be less than zero." on a blank line


问:
how to run citrus test from a main application
I'm trying to use Citrus to build a configurable mockup that I'd like to run from the command line passing different parameters to the test each time I run it.

I tried to use this as a reference to get started https://github.com/citrusframework/citrus/issues/325 but could not get it to work in my case.

I've got a running test running with one test case inside and I can run it like that

```<code>mvn clean verify -Dit.test=myTest#myTestCase
</code>```

But when trying to run the following app:

```<code>package com.grge.citrus;

import com.consol.citrus.dsl.design.DefaultTestDesigner;
import com.consol.citrus.Citrus;
import com.consol.citrus.context.TestContext;

import org.springframework.context.ConfigurableApplicationContext;
import com.grge.citrus.*;
import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;

public class App {
    public static void main(String[] args) {
        String suiteName = "mySuite";

        Citrus citrus = Citrus.newInstance();
        // my test with one testcase inside
        TestNGCitrusTestDesigner myTest  = new MyTest();

        try {
            citrus.beforeSuite(suiteName);

              // This works it come from the sample
              citrus.run(new SampleJavaDslTest().getTestCase());
            // fails null pointer exception
            citrus.run(myTest.getTestCase());

            citrus.afterSuite(suiteName);
        } finally {
            ((ConfigurableApplicationContext) citrus.getApplicationContext()).close();
        }
    }

    private static class SampleJavaDslTest extends DefaultTestDesigner {
        public SampleJavaDslTest() {
            super();
            echo("Hello from Java DSL!");
        }
    }
}
</code>```

It fails with the following error

```<code>22:08:21,691 DEBUG        citrus.Citrus| Loading Citrus application properties
22:08:21,696 DEBUG        citrus.Citrus| Setting application property citrus.spring.java.config=com.grge.citrus.VCenterActorConfigSSL
22:08:22,025 DEBUG BeanDefinitionReader| Loaded 0 bean definitions from location pattern [classpath*:citrus-context.xml]
22:08:23,059 DEBUG    server.HttpServer| Starting server: vCenterServer ...
22:08:23,217 DEBUG CachingServletFilter| Initializing filter 'request-caching-filter'
22:08:23,220 DEBUG CachingServletFilter| Filter 'request-caching-filter' configured successfully
22:08:23,220 DEBUG et.GzipServletFilter| Initializing filter 'gzip-filter'
22:08:23,220 DEBUG et.GzipServletFilter| Filter 'gzip-filter' configured successfully
22:08:23,222 DEBUG rusDispatcherServlet| Initializing servlet 'vCenterServer-servlet'
22:08:23,241 INFO  rusDispatcherServlet| FrameworkServlet 'vCenterServer-servlet': initialization started
22:08:23,250 DEBUG rusDispatcherServlet| Servlet with name 'vCenterServer-servlet' will try to create custom WebApplicationContext context of class 'org.springframework.web.context.support.XmlWebApplicationContext', using parent context [null]
22:08:23,865 DEBUG rusDispatcherServlet| Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
22:08:23,869 DEBUG rusDispatcherServlet| Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@16fb356]
22:08:23,873 DEBUG rusDispatcherServlet| Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver@1095f122]
22:08:23,894 DEBUG rusDispatcherServlet| No HandlerExceptionResolvers found in servlet 'vCenterServer-servlet': using default
22:08:23,896 DEBUG rusDispatcherServlet| Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@733c423e]
22:08:23,910 DEBUG rusDispatcherServlet| No ViewResolvers found in servlet 'vCenterServer-servlet': using default
22:08:23,915 DEBUG rusDispatcherServlet| Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@681aad3b]
22:08:23,922 DEBUG rusDispatcherServlet| Published WebApplicationContext of servlet 'vCenterServer-servlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.vCenterServer-servlet]
22:08:23,922 INFO  rusDispatcherServlet| FrameworkServlet 'vCenterServer-servlet': initialization completed in 678 ms
22:08:23,923 DEBUG rusDispatcherServlet| Servlet 'vCenterServer-servlet' configured successfully
22:08:54,266 INFO     server.HttpServer| Started server: vCenterServer
22:08:54,362 INFO  port.LoggingReporter|
22:08:54,362 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,362 INFO  port.LoggingReporter|        .__  __
22:08:54,362 INFO  port.LoggingReporter|   ____ |__|/  |________ __ __  ______
22:08:54,362 INFO  port.LoggingReporter| _/ ___\|  \   __\_  __ \  |  \/  ___/
22:08:54,362 INFO  port.LoggingReporter| \  \___|  ||  |  |  | \/  |  /\___ \
22:08:54,362 INFO  port.LoggingReporter|  \___  >__||__|  |__|  |____//____  >
22:08:54,362 INFO  port.LoggingReporter|      \/                           \/
22:08:54,362 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter| C I T R U S  T E S T S  2.7.8
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,363 DEBUG port.LoggingReporter| BEFORE TEST SUITE
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter| BEFORE TEST SUITE: SUCCESS
22:08:54,363 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,370 DEBUG t.TestContextFactory| Created new test context - using global variables: '{}'
22:08:54,370 INFO  port.LoggingReporter|
22:08:54,370 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,370 DEBUG port.LoggingReporter| STARTING TEST SampleJavaDslTest <com.grge.citrus>
22:08:54,370 INFO  port.LoggingReporter|
22:08:54,370 DEBUG      citrus.TestCase| Initializing test case
22:08:54,372 DEBUG  context.TestContext| Setting variable: citrus.test.name with value: 'SampleJavaDslTest'
22:08:54,372 DEBUG  context.TestContext| Setting variable: citrus.test.package with value: 'com.grge.citrus'
22:08:54,372 DEBUG      citrus.TestCase| Test variables:
22:08:54,372 DEBUG      citrus.TestCase| citrus.test.name = SampleJavaDslTest
22:08:54,372 DEBUG      citrus.TestCase| citrus.test.package = com.grge.citrus
22:08:54,373 INFO    actions.EchoAction| Hello from Java DSL!
22:08:54,493 INFO  port.LoggingReporter|
22:08:54,493 INFO  port.LoggingReporter| TEST SUCCESS SampleJavaDslTest (com.grge.citrus)
22:08:54,493 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,493 INFO  port.LoggingReporter|
Exception in thread "main" java.lang.NullPointerException
    at com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner.getTestCase(TestNGCitrusTestDesigner.java:113)
    at com.grge.citrus.App.main(App.java:25)
</code>```

Effectively using the debugger I can see that when entering the try section, myTest has:

applicationContext

testDesigner

and many other attributes set to null and so the testDesigner.getTestCase() raise an Exception

Thx

答:
Since Citrus 2.7 the framework provides a main CLI class that does exactly what you want:

https://github.com/citrusframework/citrus/blob/10d3954fd6c051d32e9cd974f685322c6454c779/modules/citrus-core/src/main/java/com/consol/citrus/main/CitrusApp.java#L38

```<code>Citrus application option usage:
  -h or --help = Displays cli option usage
  -d or --duration = Maximum time in milliseconds the server should be up and running - server will terminate automatically when time exceeds
  -c or --config = Custom Spring configuration class
  -s or --skipTests = Skip test execution
  -p or --package = Test package to execute
  -D or --properties = Default system properties to set
  -e or --exit = Force system exit when finished
  -t or --test = Test class/method to execute
  -j or --jar = External test jar to load tests from
</code>```

Body:
I'm trying to use Citrus to build a configurable mockup that I'd like to run from the command line passing different parameters to the test each time I run it.

I tried to use this as a reference to get started https://github.com/citrusframework/citrus/issues/325 but could not get it to work in my case.

I've got a running test running with one test case inside and I can run it like that

mvn clean verify -Dit.test=myTest#myTestCase

But when trying to run the following app:

package com.grge.citrus;

import com.consol.citrus.dsl.design.DefaultTestDesigner;
import com.consol.citrus.Citrus;
import com.consol.citrus.context.TestContext;

import org.springframework.context.ConfigurableApplicationContext;
import com.grge.citrus.*;
import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;

public class App {
    public static void main(String[] args) {
        String suiteName = "mySuite";

        Citrus citrus = Citrus.newInstance();
        // my test with one testcase inside
        TestNGCitrusTestDesigner myTest  = new MyTest();

        try {
            citrus.beforeSuite(suiteName);

              // This works it come from the sample
              citrus.run(new SampleJavaDslTest().getTestCase());
            // fails null pointer exception
            citrus.run(myTest.getTestCase());

            citrus.afterSuite(suiteName);
        } finally {
            ((ConfigurableApplicationContext) citrus.getApplicationContext()).close();
        }
    }

    private static class SampleJavaDslTest extends DefaultTestDesigner {
        public SampleJavaDslTest() {
            super();
            echo("Hello from Java DSL!");
        }
    }
}

It fails with the following error

22:08:21,691 DEBUG        citrus.Citrus| Loading Citrus application properties
22:08:21,696 DEBUG        citrus.Citrus| Setting application property citrus.spring.java.config=com.grge.citrus.VCenterActorConfigSSL
22:08:22,025 DEBUG BeanDefinitionReader| Loaded 0 bean definitions from location pattern [classpath*:citrus-context.xml]
22:08:23,059 DEBUG    server.HttpServer| Starting server: vCenterServer ...
22:08:23,217 DEBUG CachingServletFilter| Initializing filter 'request-caching-filter'
22:08:23,220 DEBUG CachingServletFilter| Filter 'request-caching-filter' configured successfully
22:08:23,220 DEBUG et.GzipServletFilter| Initializing filter 'gzip-filter'
22:08:23,220 DEBUG et.GzipServletFilter| Filter 'gzip-filter' configured successfully
22:08:23,222 DEBUG rusDispatcherServlet| Initializing servlet 'vCenterServer-servlet'
22:08:23,241 INFO  rusDispatcherServlet| FrameworkServlet 'vCenterServer-servlet': initialization started
22:08:23,250 DEBUG rusDispatcherServlet| Servlet with name 'vCenterServer-servlet' will try to create custom WebApplicationContext context of class 'org.springframework.web.context.support.XmlWebApplicationContext', using parent context [null]
22:08:23,865 DEBUG rusDispatcherServlet| Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided
22:08:23,869 DEBUG rusDispatcherServlet| Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver@16fb356]
22:08:23,873 DEBUG rusDispatcherServlet| Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver@1095f122]
22:08:23,894 DEBUG rusDispatcherServlet| No HandlerExceptionResolvers found in servlet 'vCenterServer-servlet': using default
22:08:23,896 DEBUG rusDispatcherServlet| Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator@733c423e]
22:08:23,910 DEBUG rusDispatcherServlet| No ViewResolvers found in servlet 'vCenterServer-servlet': using default
22:08:23,915 DEBUG rusDispatcherServlet| Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager@681aad3b]
22:08:23,922 DEBUG rusDispatcherServlet| Published WebApplicationContext of servlet 'vCenterServer-servlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.vCenterServer-servlet]
22:08:23,922 INFO  rusDispatcherServlet| FrameworkServlet 'vCenterServer-servlet': initialization completed in 678 ms
22:08:23,923 DEBUG rusDispatcherServlet| Servlet 'vCenterServer-servlet' configured successfully
22:08:54,266 INFO     server.HttpServer| Started server: vCenterServer
22:08:54,362 INFO  port.LoggingReporter|
22:08:54,362 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,362 INFO  port.LoggingReporter|        .__  __
22:08:54,362 INFO  port.LoggingReporter|   ____ |__|/  |________ __ __  ______
22:08:54,362 INFO  port.LoggingReporter| _/ ___\|  \   __\_  __ \  |  \/  ___/
22:08:54,362 INFO  port.LoggingReporter| \  \___|  ||  |  |  | \/  |  /\___ \
22:08:54,362 INFO  port.LoggingReporter|  \___  >__||__|  |__|  |____//____  >
22:08:54,362 INFO  port.LoggingReporter|      \/                           \/
22:08:54,362 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter| C I T R U S  T E S T S  2.7.8
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,363 DEBUG port.LoggingReporter| BEFORE TEST SUITE
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,363 INFO  port.LoggingReporter| BEFORE TEST SUITE: SUCCESS
22:08:54,363 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,363 INFO  port.LoggingReporter|
22:08:54,370 DEBUG t.TestContextFactory| Created new test context - using global variables: '{}'
22:08:54,370 INFO  port.LoggingReporter|
22:08:54,370 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,370 DEBUG port.LoggingReporter| STARTING TEST SampleJavaDslTest <com.grge.citrus>
22:08:54,370 INFO  port.LoggingReporter|
22:08:54,370 DEBUG      citrus.TestCase| Initializing test case
22:08:54,372 DEBUG  context.TestContext| Setting variable: citrus.test.name with value: 'SampleJavaDslTest'
22:08:54,372 DEBUG  context.TestContext| Setting variable: citrus.test.package with value: 'com.grge.citrus'
22:08:54,372 DEBUG      citrus.TestCase| Test variables:
22:08:54,372 DEBUG      citrus.TestCase| citrus.test.name = SampleJavaDslTest
22:08:54,372 DEBUG      citrus.TestCase| citrus.test.package = com.grge.citrus
22:08:54,373 INFO    actions.EchoAction| Hello from Java DSL!
22:08:54,493 INFO  port.LoggingReporter|
22:08:54,493 INFO  port.LoggingReporter| TEST SUCCESS SampleJavaDslTest (com.grge.citrus)
22:08:54,493 INFO  port.LoggingReporter| ------------------------------------------------------------------------
22:08:54,493 INFO  port.LoggingReporter|
Exception in thread "main" java.lang.NullPointerException
    at com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner.getTestCase(TestNGCitrusTestDesigner.java:113)
    at com.grge.citrus.App.main(App.java:25)

Effectively using the debugger I can see that when entering the try section, myTest has:

applicationContext

testDesigner

and many other attributes set to null and so the testDesigner.getTestCase() raise an Exception

Thx

Body:
Since Citrus 2.7 the framework provides a main CLI class that does exactly what you want:

https://github.com/citrusframework/citrus/blob/10d3954fd6c051d32e9cd974f685322c6454c779/modules/citrus-core/src/main/java/com/consol/citrus/main/CitrusApp.java#L38

Citrus application option usage:
  -h or --help = Displays cli option usage
  -d or --duration = Maximum time in milliseconds the server should be up and running - server will terminate automatically when time exceeds
  -c or --config = Custom Spring configuration class
  -s or --skipTests = Skip test execution
  -p or --package = Test package to execute
  -D or --properties = Default system properties to set
  -e or --exit = Force system exit when finished
  -t or --test = Test class/method to execute
  -j or --jar = External test jar to load tests from


问:
Regular Expression in .NET
I should write a regex pattern in c# that checks for input string whether it conains certain characters and does not conain another characters, for example:
I want that the string contain only a-z, not contain (d,b) and the length of all the string longer than 5, I write "[a-z]{5,}", how can I avoid that the input contain d and b?

Additional question: Can I have option to condition in the regex, in other words if whichever boolian var equals true check somthing and if it equals false not check it?

Thanks

答:
if you want to skip d and b

[ace-z]{5,}

And yes you can have a boolean check using isMatch method of Regex class

```<code> Regex regex = new Regex("^[ace-z]{5,}$");
    if (regex.IsMatch(textBox1.Text))
    {
        errorProvider1.SetError(textBox1, String.Empty);
    }
    else
    {
        errorProvider1.SetError(textBox1,
              "Invalid entry");
    }
</code>```

Source

Title: Regular Expression in .NET

Body:
if you want to skip d and b

[ace-z]{5,}

And yes you can have a boolean check using isMatch method of Regex class

 Regex regex = new Regex("^[ace-z]{5,}$");
    if (regex.IsMatch(textBox1.Text))
    {
        errorProvider1.SetError(textBox1, String.Empty);
    }
    else
    {
        errorProvider1.SetError(textBox1,
              "Invalid entry");
    }

Source


问:
Problems with adb.exe - AdbHostServer.cpp:93: Unable to connect to adb daemon on port: 5037
I have a problem with adb.exe of Android Studio 3.4.

When I run the emulator, I get this error:

Emulator: emulator: ERROR: AdbHostServer.cpp:93: Unable to connect to adb
      daemon on port: 5037

I opened a terminal with the rute of the adb.exe: C:\Users\Christian\AppData\Local\Android\Sdk\platform-tools

And here I tried with adb kill-server and then adb start-server and I get this:

```<code>*daemon not running; starting now at tcp:5037
*daemon started successfully
</code>```

When i run again the same error appears, i get this in terminal with the command adb devices:

```<code>List of devices attached
emulator-5554   offline
</code>```

I emulate Nexus 5X API 28 with System Image: Pie 28 x86 Android 9.0.

I download the last version of abd.exe in for Windows

I also reinstalled the Android Studio and the emulator, but the error still appears.

How can I solve that?

答:
If you have any port utilizing software like Xampp, Vmware workstation, or virtual box
they normally utilize the port through which the Android Studio can access the devices.
Therefore,

On your Android Studio interface click on Assistant

It will show you Troubleshoot your connection

click on next until you see Restart ADB Server

do that until it restarts.

Body:
I have a problem with adb.exe of Android Studio 3.4.

When I run the emulator, I get this error:

Emulator: emulator: ERROR: AdbHostServer.cpp:93: Unable to connect to adb
      daemon on port: 5037

I opened a terminal with the rute of the adb.exe: C:\Users\Christian\AppData\Local\Android\Sdk\platform-tools

And here I tried with adb kill-server and then adb start-server and I get this:

*daemon not running; starting now at tcp:5037
*daemon started successfully

When i run again the same error appears, i get this in terminal with the command adb devices:

List of devices attached
emulator-5554   offline

I emulate Nexus 5X API 28 with System Image: Pie 28 x86 Android 9.0.

I download the last version of abd.exe in for Windows

I also reinstalled the Android Studio and the emulator, but the error still appears.

How can I solve that?


问:
What's the proper way to receive C++ virtual-method calls into an Objective-C++ application?
I've got a library of portable C++ networking code that makes a lot of use of abstract and semi-abstract interface classes, e.g. stuff like this:

```<code>// Semi-abstract interface for any C++ object that wants to
// be notified about network events
class INetworkEventReceiver
{
public:
   INetworkEventReceiver(INetworkEventGenerator * master)
      : m_master (master)
   {
      m_master->RegisterEventReceiver(this);
   }

   virtual ~INetworkEventReceiver()
   {
      m_master->UnregisterEventReceiver(this);
   }

   // Called by our m_master object whenever a network event happens
   // Implemented by subclasses to do something useful.
   virtual void NetworkEventReceived(const NetworkEvent & event) = 0;

private:
   INetworkEventGenerator * m_master;
};
</code>```

That all works fine.  However, there is now interest in using this library in an iOS app, via Objective C++.

My question is, what is the best way for Objective-C++ code to implement "hook methods" like NetworkEventReceived(const NetworkEvent & event) above?  I was hoping that an Objective-C++ class could simply subclass INetworkEventReceiver and declare its own virtual method, the way a C++ subclass would, but it seems that Objective-C++ doesn't support that.  What is the next-best way to accomplish this?

答:
You can embed a C++ class as an ivar in an Objective-C class. Something like:

```<code>// header:
@interface Receiver : NSObject
@end

// .mm:
// declare any methods with C++ typed parameters or return types here so the header
// can be #imported in Objective-C, not just Obj-C++. This class extension
// can also be moved to an Objective-C++-only header if necessary to get to
// those methods from multiple .mm files.

@interface Receiver()
- (void) receivedNetworkEvent:(const NetworkEvent& event)event;
@end

struct ConcreteReceiver : INetworkEventReceiver
{
  __weak Receiver* target;

  virtual void NetworkEventReceived(const NetworkEvent& event) override;

};

void ConcreteReceiver::NetworkEventReceived(const NetworkEvent& event)
{
  [this->target receivedNetworkEvent:event];
}

@implementation Receiver
{
  ConcreteReceiver receiverShim;
}

- (instancetype)init
{
  self = [super init];
  if (self != nil)
  {
    self->receiverShim.target = self;
  }
  return self;
}

- (void) receivedNetworkEvent:(const NetworkEvent& event)event
{
  // Do the thing
}

@end
</code>```

It's a little awkward, especially with larger interfaces, but it works. Note that the C++ object holds a __weak reference to its containing Objective-C object to avoid leaks.

Body:
I've got a library of portable C++ networking code that makes a lot of use of abstract and semi-abstract interface classes, e.g. stuff like this:

// Semi-abstract interface for any C++ object that wants to
// be notified about network events
class INetworkEventReceiver
{
public:
   INetworkEventReceiver(INetworkEventGenerator * master)
      : m_master (master)
   {
      m_master->RegisterEventReceiver(this);
   }

   virtual ~INetworkEventReceiver()
   {
      m_master->UnregisterEventReceiver(this);
   }

   // Called by our m_master object whenever a network event happens
   // Implemented by subclasses to do something useful.
   virtual void NetworkEventReceived(const NetworkEvent & event) = 0;

private:
   INetworkEventGenerator * m_master;
};

That all works fine.  However, there is now interest in using this library in an iOS app, via Objective C++.

My question is, what is the best way for Objective-C++ code to implement "hook methods" like NetworkEventReceived(const NetworkEvent & event) above?  I was hoping that an Objective-C++ class could simply subclass INetworkEventReceiver and declare its own virtual method, the way a C++ subclass would, but it seems that Objective-C++ doesn't support that.  What is the next-best way to accomplish this?

Body:
You can embed a C++ class as an ivar in an Objective-C class. Something like:

// header:
@interface Receiver : NSObject
@end

// .mm:
// declare any methods with C++ typed parameters or return types here so the header
// can be #imported in Objective-C, not just Obj-C++. This class extension
// can also be moved to an Objective-C++-only header if necessary to get to
// those methods from multiple .mm files.

@interface Receiver()
- (void) receivedNetworkEvent:(const NetworkEvent& event)event;
@end

struct ConcreteReceiver : INetworkEventReceiver
{
  __weak Receiver* target;

  virtual void NetworkEventReceived(const NetworkEvent& event) override;

};

void ConcreteReceiver::NetworkEventReceived(const NetworkEvent& event)
{
  [this->target receivedNetworkEvent:event];
}

@implementation Receiver
{
  ConcreteReceiver receiverShim;
}

- (instancetype)init
{
  self = [super init];
  if (self != nil)
  {
    self->receiverShim.target = self;
  }
  return self;
}

- (void) receivedNetworkEvent:(const NetworkEvent& event)event
{
  // Do the thing
}

@end

It's a little awkward, especially with larger interfaces, but it works. Note that the C++ object holds a __weak reference to its containing Objective-C object to avoid leaks.


问:
Convert 4 level nested JSON file to 1 level nested with Python
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

```<code>{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }
</code>```

Desired output is like this:

```<code>{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }
</code>```

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

```<code>import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))
</code>```

This is the current output tabulated, where shows that column is a nested element:

```<code>                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...
</code>```

The print with one level nesting would be:

```<code>text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72
</code>```

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

```<code>{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}
</code>```

答:
Try this,</p>

```<code>#!/usr/bin/python
# -*- coding: utf-8 -*-

def flatten_json(y):
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(y)
    return out

expected_output = flatten_json(input_data)  # This will convert
</code>```

Body:
I have the 4 level nested JSON file below, that I would like to normalize to a one level nesting:

Input file is like this:

{
    "@index": "40",
    "row": [
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "text 1"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "text 2"
            }
          },
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "text 3"
            }
          }
        ]
      },
      {
        "column": [
          {
            "text": {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "text 4"
            }
          }
        ]
      }
    ]
  }

Desired output is like this:

{
    "@index": "40",
    "row": [
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "663.12",
              "@width": "250.01",
              "@height": "12.00",
              "#text": "Text 1"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "8.0",
              "@x": "121.10",
              "@y": "675.36",
              "@width": "348.98",
              "@height": "8.04",
              "#text": "Text 2"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "473.30",
              "@y": "676.92",
              "@width": "42.47",
              "@height": "12.00",
              "#text": "Text 3"
          },
          {
              "@fontName": "Times New Roman",
              "@fontSize": "12.0",
              "@x": "85.10",
              "@y": "690.72",
              "@width": "433.61",
              "@height": "12.00",
              "#text": "Text 4"
          }
    ]
  }

The code I have so far is this using pandas is below, but I don´t know how to continue to normalize to one level.

import json
import pandas as pd
from pandas.io.json import json_normalize #package for flattening json in pandas df

#load json object
with open('D:\Files\JSON\4Level.json') as f:
    d = json.load(f)

nycphil = json_normalize(d['row'])
print (nycphil.head(4))

This is the current output tabulated, where shows that column is a nested element:

                                            column
0  [{'text': {'@fontName': 'Times New Roman', '@f...
1  [{'text': {'@fontName': 'Times New Roman', '@f...
2  [{'text': {'@fontName': 'Times New Roman', '@f...

The print with one level nesting would be:

text.#text   text.@fontName text.@fontSize   ...   text.@width text.@x text.@y
0     Text 1  Times New Roman           12.0   ...        250.01   85.10  663.12
1     Text 2  Times New Roman            8.0   ...        348.98  121.10  675.36
2     Text 3  Times New Roman           12.0   ...         42.47  473.30  676.92
3     Text 4  Times New Roman           12.0   ...        433.61   85.10  690.72

The Input/Output comparison is like this:

Maybe someone could help me with this. Thanks for any help.

UPDATE

In order to make a small sample in first sample input I showed, I removed some elements that seems to be are needed in your scripts to work. So now I show exactly the same structure as real file but with this input your scripts don't work. I think they need a little tweak but I've been trying and I don't know how to change them to get the same output with this new input. Maybe you can help me and sorry for not show the correct input from beginning.

{
   "document":{
      "page":[
         {
            "@index":"0",
            "image":{
               "@data":"ABC",
               "@format":"png",
               "@height":"620.00",
               "@type":"base64encoded",
               "@width":"450.00",
               "@x":"85.00",
               "@y":"85.00"
            }
         },
         {
            "@index":"1",
            "row":[
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text1",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"71.04",
                           "@x":"121.10",
                           "@y":"83.42"
                        }
                     }
                  ]
               },
               {
                  "column":[
                     {
                        "text":""
                     },
                     {
                        "text":{
                           "#text":"Text2",
                           "@fontName":"Arial",
                           "@fontSize":"12.0",
                           "@height":"12.00",
                           "@width":"101.07",
                           "@x":"121.10",
                           "@y":"124.82"
                        }
                     }
                  ]
               }
            ]
         },
         {
            "@index":"2",
            "row":[
               {
                  "column":{
                     "text":{
                        "#text":"Text3",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"363.44",
                        "@x":"85.10",
                        "@y":"69.62"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text4",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"382.36",
                        "@x":"85.10",
                        "@y":"83.42"
                     }
                  }
               },
               {
                  "column":{
                     "text":{
                        "#text":"Text5",
                        "@fontName":"Arial",
                        "@fontSize":"12.0",
                        "@height":"12.00",
                        "@width":"435.05",
                        "@x":"85.10",
                        "@y":"97.22"
                     }
                  }
               }
            ]
         },
         {
            "@index":"3"
         }
      ]
   }
}

Body:
Try this,

#!/usr/bin/python
# -*- coding: utf-8 -*-

def flatten_json(y):
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        elif type(x) is list:
            i = 0
            for a in x:
                flatten(a, name + str(i) + '_')
                i += 1
        else:
            out[name[:-1]] = x

    flatten(y)
    return out

expected_output = flatten_json(input_data)  # This will convert


问:
Nav menu not opening beneath header for medium screens using bootstrap 4
I am unable to make the nav menu load from the bottom when the browser screen is medium size.

On Firefox browser, when the hamburger icon is pressed, it should be loading beneath the header. It is appearing correctly when I make the width of the browser really small like this:

But for some reason, when I start to increase the width, it loads the menu from the right hand side. Like this:

I attempted updating the CSS but to no effect.

Please find the code here and any help will be appreciated. Thanks.
https://www.codeply.com/go/qMkYwnOOrH

答:
Because of the way you're using rows and cols, you need to change this div:

```<code><div class="row no-gutters nav-item-container">
</code>```

like this:

```<code><div class="row no-gutters nav-item-container collapse navbar-collapse" id="navbarsExampleDefault">
</code>```

and here delete the class and id attributes:

```<code><div class="collapse navbar-collapse" id="navbarsExampleDefault">
</code>```

Body:
Because of the way you're using rows and cols, you need to change this div:

<div class="row no-gutters nav-item-container">

like this:

<div class="row no-gutters nav-item-container collapse navbar-collapse" id="navbarsExampleDefault">

and here delete the class and id attributes:

<div class="collapse navbar-collapse" id="navbarsExampleDefault">


问:
How to switch flutter plugin architecture from arm64 to armv7
When I tried to decrease my flutter app's deployment target (iOS 12 to 9.3), I received this error when running flutter build ios:

```<code>=== BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Release ===
    fatal error: lipo: -extract armv7 specified but fat file:
    /Users/xxx/development/myapp/build/ios/Release-iphoneos/Runner.app/Frameworks/flutter_webview_plugin.framework/flutter_webview_plugin does not contain that architecture
    Failed to extract armv7 for /Users/xxx/development/myapp/build/ios/Release-iphoneos/Runner.app/Frameworks/flutter_webview_plugin.framework/flutter_webview_plugin. Running
    lipo -info:
    Architectures in the fat file: /Users/xxx/development/myapp/build/ios/Release-iphoneos/Runner.app/Frameworks/flutter_webview_plugin.framework/flutter_webview_plugin are:
    arm64

</code>```

I am unable to find any information on how to change the architecture in question - can I even do this? Or is this something the plugin developer has to build in?

I would like to be able to run the app with the lowest possible iOS version for maximum compatibility.

答: In the project build settings, there is a section called Architectures, there you can set the ones you need. As far as I know, the latest iPhones need to use arm64, but in my picture you can see that I'm also set as valid armv7, that seems to be your problem.

Body:
When I tried to decrease my flutter app's deployment target (iOS 12 to 9.3), I received this error when running flutter build ios:

=== BUILD TARGET Runner OF PROJECT Runner WITH CONFIGURATION Release ===
    fatal error: lipo: -extract armv7 specified but fat file:
    /Users/xxx/development/myapp/build/ios/Release-iphoneos/Runner.app/Frameworks/flutter_webview_plugin.framework/flutter_webview_plugin does not contain that architecture
    Failed to extract armv7 for /Users/xxx/development/myapp/build/ios/Release-iphoneos/Runner.app/Frameworks/flutter_webview_plugin.framework/flutter_webview_plugin. Running
    lipo -info:
    Architectures in the fat file: /Users/xxx/development/myapp/build/ios/Release-iphoneos/Runner.app/Frameworks/flutter_webview_plugin.framework/flutter_webview_plugin are:
    arm64

I am unable to find any information on how to change the architecture in question - can I even do this? Or is this something the plugin developer has to build in?

I would like to be able to run the app with the lowest possible iOS version for maximum compatibility.


问:
Pattern recognition (muscular activity)
I need a recommendation from your side. I am currently working with an EMG (muscle) sensor on Arduino and my target is to identify and measure a time of the muscular activity. On the picture below you find the raw data. <img src="https://i.stack.imgur.com/kOOxJ.png" alt="Serial plotter">  As you can see, during the muscular activity the range of the analog output is much higher. But I don't know which mathematical approach is suitable for this task. </p>

答:
Use sliding window...

select window size

its a time in which you would analyze the signal properties. It should be long enough to hold at least one period of signal but 2-3 periods is better.

now pass your signal through FIFO of size equal to your window size

after your FIFO is full at each new input value remove the first one from it and compute min and max of the FIFO content. Such FIFO is best implemented in form of cyclic buffer of fixed length. The difference of max-min is the dynamic range of the window and will tell you if your sensor detects activity or not.

Threshold max(t)-min(t)

so for each computed window t compute:

```<code>d(t) = max(t) - min(t)
</code>```

where t is the start time of your window. Now:

```<code>if (d(t)>=threshold) muscle_is_working;
</code>```

the passive area in your signal has difference up do ~40 so set threshold to be bigger than that but smaller than active area in your signal for example

```<code>threshold = 50
</code>```

If you need more speed (as you are on god knows which MCU ... and yes Arduino is not a MCU its just framework) you can use abs sum of the window instead which does not require to process whole FIFO contents in each slide of window. Instead you just remove first item from sum and add the last one to it. So the equation would be:

```<code>d(t) = sum(i=t,...,t+size-1) of abs(signal(t)-inactive_average)
</code>```

Also its a good idea to round up the window size to power of 2 so you can use bit operations instead of division and modulo in the cyclic buffer implementation.

Title: Pattern recognition (muscular activity)

Body: I need a recommendation from your side. I am currently working with an EMG (muscle) sensor on Arduino and my target is to identify and measure a time of the muscular activity. On the picture below you find the raw data.   As you can see, during the muscular activity the range of the analog output is much higher. But I don't know which mathematical approach is suitable for this task.

Body:
Use sliding window...

select window size

its a time in which you would analyze the signal properties. It should be long enough to hold at least one period of signal but 2-3 periods is better.

now pass your signal through FIFO of size equal to your window size

after your FIFO is full at each new input value remove the first one from it and compute min and max of the FIFO content. Such FIFO is best implemented in form of cyclic buffer of fixed length. The difference of max-min is the dynamic range of the window and will tell you if your sensor detects activity or not.

Threshold max(t)-min(t)

so for each computed window t compute:

d(t) = max(t) - min(t)

where t is the start time of your window. Now:

if (d(t)>=threshold) muscle_is_working;

the passive area in your signal has difference up do ~40 so set threshold to be bigger than that but smaller than active area in your signal for example

threshold = 50

If you need more speed (as you are on god knows which MCU ... and yes Arduino is not a MCU its just framework) you can use abs sum of the window instead which does not require to process whole FIFO contents in each slide of window. Instead you just remove first item from sum and add the last one to it. So the equation would be:

d(t) = sum(i=t,...,t+size-1) of abs(signal(t)-inactive_average)

Also its a good idea to round up the window size to power of 2 so you can use bit operations instead of division and modulo in the cyclic buffer implementation.


问:
Replace values from one column in dataframe
import pandas as pd
import numpy as np
import ast

pd.options.display.max_columns = 20

I have dataframe column season that looks like this (first 20 entries):

```<code>      season
0     2006-07
1     2007-08
2     2008-09
3     2009-10
4     2010-11
5     2011-12
6     2012-13
7     2013-14
8     2014-15
9     2015-16
10    2016-17
11    2017-18
12    2018-19
13     Career
14     season
15    2018-19
16     Career
17     season
18    2017-18
19    2018-19
</code>```

It starts with season and ends with Career. I want to replace years with numbers starting with 1 and ending when there's career. I want to be like this:

```<code>      season
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9     10
10    11
11    12
12    13
13     Career
14     season
15    1
16     Career
17     season
18    1
19    2
</code>```

So counting should reset every time there's season in column and end every time there's career.

答:
Create consecutive groups by compare mask created by Series.isin with shifted values with GroupBy.cumcount for counter:

```<code>s = df['season'].isin(['Career', 'season'])
df['new'] = np.where(s, df['season'], df.groupby(s.ne(s.shift()).cumsum()).cumcount() + 1)
print (df)
     season     new
0   2006-07       1
1   2007-08       2
2   2008-09       3
3   2009-10       4
4   2010-11       5
5   2011-12       6
6   2012-13       7
7   2013-14       8
8   2014-15       9
9   2015-16      10
10  2016-17      11
11  2017-18      12
12  2018-19      13
13   Career  Career
14   season  season
15  2018-19       1
16   Career  Career
17   season  season
18  2017-18       1
19  2018-19       2
</code>```

For replace column season:

```<code>s = df['season'].isin(['Career', 'season'])
df.loc[~s, 'season'] = df.groupby(s.ne(s.shift()).cumsum()).cumcount() + 1
print (df)
    season
0        1
1        2
2        3
3        4
4        5
5        6
6        7
7        8
8        9
9       10
10      11
11      12
12      13
13  Career
14  season
15       1
16  Career
17  season
18       1
19       2
</code>```

Body:
import pandas as pd
import numpy as np
import ast

pd.options.display.max_columns = 20

I have dataframe column season that looks like this (first 20 entries):

      season
0     2006-07
1     2007-08
2     2008-09
3     2009-10
4     2010-11
5     2011-12
6     2012-13
7     2013-14
8     2014-15
9     2015-16
10    2016-17
11    2017-18
12    2018-19
13     Career
14     season
15    2018-19
16     Career
17     season
18    2017-18
19    2018-19

It starts with season and ends with Career. I want to replace years with numbers starting with 1 and ending when there's career. I want to be like this:

      season
0     1
1     2
2     3
3     4
4     5
5     6
6     7
7     8
8     9
9     10
10    11
11    12
12    13
13     Career
14     season
15    1
16     Career
17     season
18    1
19    2

So counting should reset every time there's season in column and end every time there's career.

Body:
Create consecutive groups by compare mask created by Series.isin with shifted values with GroupBy.cumcount for counter:

s = df['season'].isin(['Career', 'season'])
df['new'] = np.where(s, df['season'], df.groupby(s.ne(s.shift()).cumsum()).cumcount() + 1)
print (df)
     season     new
0   2006-07       1
1   2007-08       2
2   2008-09       3
3   2009-10       4
4   2010-11       5
5   2011-12       6
6   2012-13       7
7   2013-14       8
8   2014-15       9
9   2015-16      10
10  2016-17      11
11  2017-18      12
12  2018-19      13
13   Career  Career
14   season  season
15  2018-19       1
16   Career  Career
17   season  season
18  2017-18       1
19  2018-19       2

For replace column season:

s = df['season'].isin(['Career', 'season'])
df.loc[~s, 'season'] = df.groupby(s.ne(s.shift()).cumsum()).cumcount() + 1
print (df)
    season
0        1
1        2
2        3
3        4
4        5
5        6
6        7
7        8
8        9
9       10
10      11
11      12
12      13
13  Career
14  season
15       1
16  Career
17  season
18       1
19       2


问:
How to type hint a return value of Exception's subclass?
I have an abstract method in my base class, and I want all the subclasses to return an iterable of their expected Exception classes:

```<code>class Foo(metaclass=ABCMeta):
    @abstractmethod
    def expected_exceptions(self):
        raise NotImplementedError()

class Bar(Foo):
    def expected_exceptions(self):
        return ValueError, IndexError

class Baz(Foo):
    def expected_exceptions(self):
        yield from self.manager._get_exceptions()
</code>```

How do I type hint this return value? At first I thought of -> Iterable[Exception], but that would mean they are instances of Exception, as opposed to subclasses.

答:
You want typing.Type, which specifies that you are returning a type, as opposed to an instance:

```<code>from typing import Type, Iterable

def expected_exceptions(self) -> Iterable[Type[Exception]]:
    return ValueError, IndexError
</code>```

Body:
I have an abstract method in my base class, and I want all the subclasses to return an iterable of their expected Exception classes:

class Foo(metaclass=ABCMeta):
    @abstractmethod
    def expected_exceptions(self):
        raise NotImplementedError()

class Bar(Foo):
    def expected_exceptions(self):
        return ValueError, IndexError

class Baz(Foo):
    def expected_exceptions(self):
        yield from self.manager._get_exceptions()

How do I type hint this return value? At first I thought of -> Iterable[Exception], but that would mean they are instances of Exception, as opposed to subclasses.

Body:
You want typing.Type, which specifies that you are returning a type, as opposed to an instance:

from typing import Type, Iterable

def expected_exceptions(self) -> Iterable[Type[Exception]]:
    return ValueError, IndexError