问:
ValueError: could not convert string to float: '' in Python 3
I'm coding a little bot in Python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem:

```<code>old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))
</code>```

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number which should work with float()
"remove prc" is a little function I created to remove the % of a number, here it is:

```<code>def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string
</code>```

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

```<code>loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''
</code>```

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float()
of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time!
I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, I think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

```<code>a = "-0.06%"
def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)
    return string

b = float(removeprc(a))
print(b)
</code>```

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py

答:
The returned text is an empty string, so it can't be converted to float. Add a check

```<code>b = removeprc(a)
if b:
    print(float(b))
else:
    print('b is an empty string')
</code>```

Body:
I'm coding a little bot in Python and I'm having a problem. It seems to be a common problem, but I've never seen it asked in the same situation I'm in.

Ok so here is the code posing problem:

old_values = float((removeprc(browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text)))

browser.find_element_by_xpath('//*[@id="draggableNavRightResizable"]/section/section[2]/section[1]/div[3]/ul/li[1]/div[2]/div[6]/span').text) is a selenium tool used to get a value of a website. as you will see later, the element retrieved is a number which should work with float()
"remove prc" is a little function I created to remove the % of a number, here it is:

def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)

    return string

It's probably not the best way to do it, but it works when I test it alone.

anyway, here is what I get when I run my entire code

loading page ...
page loaded
acquiring values ...
values acquired
running eth trade
-0.37
Traceback (most recent call last):
  File "C:\Users\pc adam\Documents\EISTI\algoprog\perso\python\fichiers\btc\ETHtradingbotV1.py", line 138, in <module>
    profit = float(browser.find_element_by_xpath('/html/body/div[3]/section[16]/section[2]/section[2]/section[2]/div/div[1]/table/tbody/tr/td[15]/span').text)
ValueError: could not convert string to float: ''

the first 5 lines are useless. on the 6th line, I printed what i am trying to get the float()
of. As you can see, it should work and ... It does ! sometimes.

that's the weirdest thing about this, it works perfectly half the time!
I've read on the internet that this can happen if you try to float() things that are not numbers or that have weird shit in them, like spaces. As you can see, I think it's not the case here.

When I try to isolate the problem by running a simplified version of the program like this :

a = "-0.06%"
def removeprc(string): #removes the % from a string
    string = str(string)
    list = string.split('%')
    string = " ".join(list)
    return string

b = float(removeprc(a))
print(b)

it outputs -0.06 and works perfectly ???

So I'm really stuck here. It should work, but it doesn't. Even worst, it works sometimes, for no reason. And when I isolate the problem, it works fine.

Any help would be extremely appreciated!

Oh and if you want to see the entire code, it's here: https://github.com/Madaxuorel/proj-ethTB/blob/master/ETHtradingbotV1.py

Body:
The returned text is an empty string, so it can't be converted to float. Add a check

b = removeprc(a)
if b:
    print(float(b))
else:
    print('b is an empty string')


来源: stackexchange

问:
Splitting words in a list
How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

```<code>text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())
</code>```

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

答:
There is no replace function for a list. I guess what you want is to split on comma:

```<code>text = ['a,b', 'c,d']
result = []
for i in text:
  result.extend(i.split(','))
</code>```

Note the second change I did is to print i - the thing that iterates as opposed to the whole text. Additionally I am calling extend on the result to produce a single list.

ContentLicense: CC BY-SA 4.0

Title: Splitting words in a list

Body:
How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

Body:
There is no replace function for a list. I guess what you want is to split on comma:

text = ['a,b', 'c,d']
result = []
for i in text:
  result.extend(i.split(','))

Note the second change I did is to print i - the thing that iterates as opposed to the whole text. Additionally I am calling extend on the result to produce a single list.


答:
```<code>your_list = [ x for sublist in text for x in sublist.split(',') ]
</code>```

Title: Splitting words in a list


问:
Python 3.8: IndexError when using append()
I made a little "console" that splits the command with split(). I am separating the "command" (the first "word" from the input()) from the "arguments" coming after the first word. Here's the code that generates an error:

```<code>cmdCompl = input(prompt).strip().split()
cmdRaw = cmdCompl[0]
args = addArgsToList(cmdCompl)
</code>```

addArgsToList() function:

```<code>def addArgsToList(lst=[]):
    newList = []
    for i in range(len(lst)):
        newList.append(lst[i+1])
    return newList
</code>```

I try to add every word after cmdRaw to a list called args which is returned by addArgsToList(). But what I get instead is:

```<code>Welcome to the test console!

Type help or ? for a list of commands

testconsole >>> help
Traceback (most recent call last):
  File "testconsole.py", line 25, in <module>
    args = addArgsToList(cmdCompl)
  File "testconsole.py", line 15, in addArgsToList
    newList.append(lst[i+1])
IndexError: list index out of range
</code>```

I cannot figure out why I get an IndexError because as far as I know, newList can be dynamically allocated.

Any help?

答:
When you're doing:

```<code>for i in range(len(lst)):
    newList.append(lst[i+1])
</code>```

The last iteration tries to access lst at len(lst) which is out of bound.

Body:
I made a little "console" that splits the command with split(). I am separating the "command" (the first "word" from the input()) from the "arguments" coming after the first word. Here's the code that generates an error:

cmdCompl = input(prompt).strip().split()
cmdRaw = cmdCompl[0]
args = addArgsToList(cmdCompl)

addArgsToList() function:

def addArgsToList(lst=[]):
    newList = []
    for i in range(len(lst)):
        newList.append(lst[i+1])
    return newList

I try to add every word after cmdRaw to a list called args which is returned by addArgsToList(). But what I get instead is:

Welcome to the test console!

Type help or ? for a list of commands

testconsole >>> help
Traceback (most recent call last):
  File "testconsole.py", line 25, in <module>
    args = addArgsToList(cmdCompl)
  File "testconsole.py", line 15, in addArgsToList
    newList.append(lst[i+1])
IndexError: list index out of range

I cannot figure out why I get an IndexError because as far as I know, newList can be dynamically allocated.

Any help?

Body:
When you're doing:

for i in range(len(lst)):
    newList.append(lst[i+1])

The last iteration tries to access lst at len(lst) which is out of bound.


问:
Angular 8 unit test directive which includes setTimeout
I have the following simple autofocus directive:

```<code>@Directive({
  selector: '[appAutoFocus]',
})
export class AutofocusDirective implements AfterContentInit {

  @Input() public appAutoFocus: boolean;

  public constructor(private el: ElementRef) { }

  public ngAfterContentInit() {
    if (this.appAutoFocus) {
      setTimeout(() => {
        this.el.nativeElement.focus();
      }, 300);
    }
  }
}
</code>```

I'm now trying to write some simple unit tests, but 2 out of the 3 tests fail.

```<code>@Component({
  template: '<input type="text" [appAutoFocus]="true" />'
})
class TestComponent {
  constructor() { }
}

fdescribe('AutoFocusDirective', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let inputEl: DebugElement;
     beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [
            TestComponent,
            AutofocusDirective
          ]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));

        spyOn(inputEl.nativeElement, 'focus');
        fixture.detectChanges();
      });

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

      it('should call the focus event', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
         expect(inputEl.nativeElement.focus).toHaveBeenCalled();
        });
      }));

      it('should autofocus the input control', () => {
        const debugEl: DebugElement = fixture.debugElement;
        expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
      });
</code>```

"Should call the focus event" fails with Spec 'AutoFocusDirective should call the focus event' has no expectations.

"Should autofocus the input control" fails with Expected null not to be null

答:
The only way i could get this to work was to add a setTimeout to the test spec, so it now looks like so:

```<code>  it('should call the focus event', (done) => {
    fixture.detectChanges();
    setTimeout(() => {
      expect(inputEl.nativeElement.focus).toHaveBeenCalled();
      done();
    }, 500);
  });
</code>```

To be honest, it's a garbage solution but i've wasted too much time on this.

Body:
I have the following simple autofocus directive:

@Directive({
  selector: '[appAutoFocus]',
})
export class AutofocusDirective implements AfterContentInit {

  @Input() public appAutoFocus: boolean;

  public constructor(private el: ElementRef) { }

  public ngAfterContentInit() {
    if (this.appAutoFocus) {
      setTimeout(() => {
        this.el.nativeElement.focus();
      }, 300);
    }
  }
}

I'm now trying to write some simple unit tests, but 2 out of the 3 tests fail.

@Component({
  template: '<input type="text" [appAutoFocus]="true" />'
})
class TestComponent {
  constructor() { }
}

fdescribe('AutoFocusDirective', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let inputEl: DebugElement;
     beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [
            TestComponent,
            AutofocusDirective
          ]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));

        spyOn(inputEl.nativeElement, 'focus');
        fixture.detectChanges();
      });

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

      it('should call the focus event', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
         expect(inputEl.nativeElement.focus).toHaveBeenCalled();
        });
      }));

      it('should autofocus the input control', () => {
        const debugEl: DebugElement = fixture.debugElement;
        expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
      });

"Should call the focus event" fails with Spec 'AutoFocusDirective should call the focus event' has no expectations.

"Should autofocus the input control" fails with Expected null not to be null

Body:
The only way i could get this to work was to add a setTimeout to the test spec, so it now looks like so:

  it('should call the focus event', (done) => {
    fixture.detectChanges();
    setTimeout(() => {
      expect(inputEl.nativeElement.focus).toHaveBeenCalled();
      done();
    }, 500);
  });

To be honest, it's a garbage solution but i've wasted too much time on this.


问:
AutoML: out of memory on small training file
I am attempting to run H2OAutoML on a 2.7MB training CSV on a system with 4GB RAM using the python API and it is running out of memory.

The error messages I am encountering are either:

```<code>h2o_ubuntu_started_from_python.out:
02-17 17:57:25.063 127.0.0.1:54321       27097  FJ-3-15   INFO: Stopping XGBoost training because of timeout
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 247463936 bytes for committing reserved memory.
# An error report file with more information is saved as:
# /home/ubuntu/h20.ai/h2o-3.28.0.2/hs_err_pid27097.log
</code>```

or

```<code>03:37:07.509: XRT_1_AutoML_20200217_030816 [DRF XRT (Extremely Randomized Trees)] failed: java.lang.OutOfMemoryError: Java heap space
</code>```

in the output of the python depending on the exact crash instance I look at.

My init is:

```<code>h2o.init(max_mem_size='3G',min_mem_size='2G',jvm_custom_args=["-Xmx3g"])
</code>```

Though I have tried with:
h2o.init()

My H2OAutoML call is:

```<code>H2OAutoML(nfolds=5,max_models=20, max_runtime_secs_per_model=600, seed=1,project_name =project_name)
aml.train(x=x, y=y, training_frame=train,validation_frame=test)
</code>```

These are the server stats:

```<code>H2O cluster uptime:         02 secs
H2O cluster timezone:       Etc/UTC
H2O data parsing timezone:  UTC
H2O cluster version:        3.28.0.2
H2O cluster version age:    27 days
H2O cluster name:           H2O_from_python_ubuntu_htq5aj
H2O cluster total nodes:    1
H2O cluster free memory:    3 Gb
H2O cluster total cores:    2
H2O cluster allowed cores:  2
H2O cluster status:         accepting new members, healthy
H2O connection url:         http://127.0.0.1:54321
H2O connection proxy:       {'http': None, 'https': None}
H2O internal security:      False
H2O API Extensions:         Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4
Python version:             3.6.9 final
</code>```

Does this sound right? Am I not able to run 20 models?

I can run this just fine setting the max_models=10. This takes about 60 min.

Are there guidelines for the amount of RAM needed for a given max_models and filesize?

答:
Connect to the Flow interface, running at 127.0.0.1:54321.

There is a section there where you can view the remaining memory. You can also see what models and data frames are being created. You have max_runtime_secs_per_model set to 600, and say 10 models takes an hour, so if you check in every 5-10 minutes, you can get an idea of how much memory each model is taking up.

Your h2o.init() response looks fine. The guideline was to have 3-4 times the dataset size free. If your data is only 2.7MB, then this should not be a concern. Though if you have a lot of categorical columns, especially with a lot of choices, then they can take up more memory than you expect.

The memory used by a model can vary quite a lot, depending on the parameters chosen. Again, it is best to look on Flow, to see what parameters AutoML is choosing for you.

If it is simply the case that 10 models will fit in memory, and 20 models won't, and you don't want to take manual control of the parameters, then you could do batches of 10 models, and save after each hour. (Choose a different seed for each run.)

Body:
I am attempting to run H2OAutoML on a 2.7MB training CSV on a system with 4GB RAM using the python API and it is running out of memory.

The error messages I am encountering are either:

h2o_ubuntu_started_from_python.out:
02-17 17:57:25.063 127.0.0.1:54321       27097  FJ-3-15   INFO: Stopping XGBoost training because of timeout
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Native memory allocation (mmap) failed to map 247463936 bytes for committing reserved memory.
# An error report file with more information is saved as:
# /home/ubuntu/h20.ai/h2o-3.28.0.2/hs_err_pid27097.log

or

03:37:07.509: XRT_1_AutoML_20200217_030816 [DRF XRT (Extremely Randomized Trees)] failed: java.lang.OutOfMemoryError: Java heap space

in the output of the python depending on the exact crash instance I look at.

My init is:

h2o.init(max_mem_size='3G',min_mem_size='2G',jvm_custom_args=["-Xmx3g"])

Though I have tried with:
h2o.init()

My H2OAutoML call is:

H2OAutoML(nfolds=5,max_models=20, max_runtime_secs_per_model=600, seed=1,project_name =project_name)
aml.train(x=x, y=y, training_frame=train,validation_frame=test)

These are the server stats:

H2O cluster uptime:         02 secs
H2O cluster timezone:       Etc/UTC
H2O data parsing timezone:  UTC
H2O cluster version:        3.28.0.2
H2O cluster version age:    27 days
H2O cluster name:           H2O_from_python_ubuntu_htq5aj
H2O cluster total nodes:    1
H2O cluster free memory:    3 Gb
H2O cluster total cores:    2
H2O cluster allowed cores:  2
H2O cluster status:         accepting new members, healthy
H2O connection url:         http://127.0.0.1:54321
H2O connection proxy:       {'http': None, 'https': None}
H2O internal security:      False
H2O API Extensions:         Amazon S3, XGBoost, Algos, AutoML, Core V3, TargetEncoder, Core V4
Python version:             3.6.9 final

Does this sound right? Am I not able to run 20 models?

I can run this just fine setting the max_models=10. This takes about 60 min.

Are there guidelines for the amount of RAM needed for a given max_models and filesize?


问:
AWS - Why there is no Interface Endpoint (PrivateLink) for S3?
The VPC Gateway endpoint for S3 is an entry in a routing table of a subnet, not an ENI/IP Interface Endpoint such as for ELB, Athena, API GW, etc.

Why there is no Interface Endpoint for S3?

答: S3 and DynamoDB VPC endpoints (gateway endpoints) were introduced first and didn't leverage AWS PrivateLink, which was introduced later. All other service endpoints utilized PrivateLink from the get-go and therefore offer ENI type of interface.</p>


问:
how to give boder colors in html table without using style tags
I need to develop some example without using styles tags, i tried mostly, but i am unable to add border and border specific td borders please see my code and help me on this.

```<code><table style="width:100%" border='0' cellpadding="0" ><tr cellspacing="0">
<td rowspan='2' > <img  height='100' width='80' src="http://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg" alt=" Logo" /></td>
<td width='500' border='1' bordercolor="red"><b>some text</b></td></tr><tr cellspacing="0">
<td border='1' color='red' >some text
                  </td>
<td> <label> Name:  </label><br />
                <label>class:  </label><br />
                <label>  ID:  </label></td></tr></table>
</code>```

Output look like this:

答:
Use internal style with help of classes if support your PDF generation tool inside internal style.

    Some text with black border and green text color

     Name:

        Class:

        ID:

     Some text with green border & green text color

```

Body:
I need to develop some example without using styles tags, i tried mostly, but i am unable to add border and border specific td borders please see my code and help me on this.

some text

some text

  Name:

                class:

                  ID:

Output look like this:

Body:
Use internal style with help of classes if support your PDF generation tool inside internal style.

<style type="text/css">
.my-table{border-collapse:separate;width:100%;}
.my-table td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;}
/*Below border color defined*/
.border-black{border-color: #000000;}
.border-green{border-color: #00ff00;}
.border-red{border-color: #ff0000;}
.border-blue{border-color: #0000ff;}
/*Below text color defined*/
.text-green{color: #00ff00;}
</style>

<table class="my-table" cellspacing="10" cellpadding="0">
  <tr>
    <td class="border-red" rowspan="2" width="80">
     <img  height='100' width='80' src="http://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg" alt=" Logo" />
    </td>
    <td class="border-black text-green">Some text with black border and green text color</td>
    <td class="border-blue" rowspan="2">
     <label>Name: &nbsp;</label><br />
        <label>Class: &nbsp;</label><br />
        <label>ID: &nbsp;</label>
    </td>
  </tr>
  <tr>
    <td class="border-green text-green" width="400">
     Some text with green border & green text color
    </td>
  </tr>
</table>


问:
Create nested json file
I want to create a json file that can be used as a configuration file. I have different files from multiple companies that report the same information with different column names.

I want to use the information provided in the json file to run a python script to consolidate all the information from all files and companies in one master file.

The structure looks like follows:

```<code>{"companies":
    {"company1": [
        {"path": "C:/USER/Path/Company1/",
         "files": [
            {
                {"_CO": {"ID": "ID", "Report Number": "Report_Number"}},
                {"_TR": {"ID": "Trade_Ident", "Report Number": "Number of Report"}},
            },
         ],
        },
    ],
    },

    {"company2": [
        {"path": "C:/USER/Path/Company2/",
         "files": [
            {
                {"_CO": {"ID": "Identification", "Report Number": "Report-Number"}},
                {"_TR": {"ID": "Ident", "Report Number": "NumberReport"}},
            },
         ],
        },
    ],
    },
},
</code>```

However, I receive the following error when trying to read the .json in python.

json.decoder.JSONDecodeError: Expecting property name enclosed in
  double quotes: line 6 column 5 (char 90)

To read the file I use:

```<code>import json

path = "/user_folder/USER/Desktop/Data/"

file = "ConfigFile.json"

with open(path+file) as f:
    my_test = json.load(f)
</code>```

Any help appreciated, as I can't figure out my mistake in the file structure.

答:
You have some object (the ones with curly braces) without keys, for example in

```<code>{
    {"_CO": {"ID": "ID", "Report Number": "Report_Number"}}, ...

</code>```

Objects in JSON are key-value pairs. Just remove the external set of braces and it should be ok.

You can use some online JSON formatter/validator just like this one, and it will easily point out the problem. Otherwise, you can use some JSON linter for your editor. It just does the work for you and also improves indentation :)

Title: Create nested json file

Body:
I want to create a json file that can be used as a configuration file. I have different files from multiple companies that report the same information with different column names.

I want to use the information provided in the json file to run a python script to consolidate all the information from all files and companies in one master file.

The structure looks like follows:

{"companies":
    {"company1": [
        {"path": "C:/USER/Path/Company1/",
         "files": [
            {
                {"_CO": {"ID": "ID", "Report Number": "Report_Number"}},
                {"_TR": {"ID": "Trade_Ident", "Report Number": "Number of Report"}},
            },
         ],
        },
    ],
    },

    {"company2": [
        {"path": "C:/USER/Path/Company2/",
         "files": [
            {
                {"_CO": {"ID": "Identification", "Report Number": "Report-Number"}},
                {"_TR": {"ID": "Ident", "Report Number": "NumberReport"}},
            },
         ],
        },
    ],
    },
},

However, I receive the following error when trying to read the .json in python.

json.decoder.JSONDecodeError: Expecting property name enclosed in
  double quotes: line 6 column 5 (char 90)

To read the file I use:

import json

path = "/user_folder/USER/Desktop/Data/"

file = "ConfigFile.json"

with open(path+file) as f:
    my_test = json.load(f)

Any help appreciated, as I can't figure out my mistake in the file structure.

Body:
You have some object (the ones with curly braces) without keys, for example in

{
    {"_CO": {"ID": "ID", "Report Number": "Report_Number"}}, ...

Objects in JSON are key-value pairs. Just remove the external set of braces and it should be ok.

You can use some online JSON formatter/validator just like this one, and it will easily point out the problem. Otherwise, you can use some JSON linter for your editor. It just does the work for you and also improves indentation :)


问:
Is it possible to set 'border-radius' when reaching end of the div?
I'm trying to make a popup-div which has very long information.

I wonder that at inner div, there is no end-point at bottom, because there are hidden informs, like:

```<code>┌────────────────────────┐
│                        │
│ ┌───────────────────┐  │
│ │                   │  │
│ │                   │  │
│ │                   │  │
│ │        ...      ↓ │  │        // ↓ means scroll down to see more.
└────────────────────────┘
</code>```

And scrolling down to the end of the inner div:

```<code>┌────────────────────────┐
│                        │
│ ┌───────────────────┐  │
│ │       ...         │  │
│ │                   │  │
│ │                   │  │
│ └───────────────────┘  │                          //  │ └───────────────────┘  │   <- the endpoint showed up!
└────────────────────────┘
</code>```

│ └───────────────────┘  │ end-point has appeared.

Is it possible?

答:
You can do it by setting the top spacing to the parent and the bottom spacing to the child.

Make the parent scrollable

Hide parent scrollbars (since visually the scrollbars touch the window bottom edge)

Adding a margin-bottom to the child element

* {margin: 0;box-sizing: border-box;}

body {
  background: #0fb;
}

.Popup {
  position: fixed;
  width: 70vw;
  top: 15vh;
  left: 15vw;
  bottom: 0vh; /* has to be at 0! */
  overflow-x: hidden;
  overflow-y: auto;
  scrollbar-width: none; /* FF https://stackoverflow.com/a/49278385/383904 */
  -ms-overflow-style: none; /* IE 10+ */
}

.Popup::-webkit-scrollbar { /* WebKit */
  width: 0;
  height: 0;
}

.Popup-content {
  padding: 20px;
  height: 150vh;   /* Demo only... you place text inside */
  margin-bottom: 15vh;
  border: 10px dashed #000;
  background: #0bf;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Lorem Ipsum</h2>
<div class="Popup">
  <div class="Popup-content">
    Scroll...
  </div>
</div></code>```

Without hiding the scrollbars I don't think there's any sane solution to do it in pure CSS, not without the use of some JavaScript.

Body:
I'm trying to make a popup-div which has very long information.

I wonder that at inner div, there is no end-point at bottom, because there are hidden informs, like:

┌────────────────────────┐
│                        │
│ ┌───────────────────┐  │
│ │                   │  │
│ │                   │  │
│ │                   │  │
│ │        ...      ↓ │  │        // ↓ means scroll down to see more.
└────────────────────────┘

And scrolling down to the end of the inner div:

┌────────────────────────┐
│                        │
│ ┌───────────────────┐  │
│ │       ...         │  │
│ │                   │  │
│ │                   │  │
│ └───────────────────┘  │                          //  │ └───────────────────┘  │   <- the endpoint showed up!
└────────────────────────┘

│ └───────────────────┘  │ end-point has appeared.

Is it possible?

Body:
You can do it by setting the top spacing to the parent and the bottom spacing to the child.

Make the parent scrollable

Hide parent scrollbars (since visually the scrollbars touch the window bottom edge)

Adding a margin-bottom to the child element

* {margin: 0;box-sizing: border-box;}

body {
  background: #0fb;
}

.Popup {
  position: fixed;
  width: 70vw;
  top: 15vh;
  left: 15vw;
  bottom: 0vh; /* has to be at 0! */
  overflow-x: hidden;
  overflow-y: auto;
  scrollbar-width: none; /* FF https://stackoverflow.com/a/49278385/383904 */
  -ms-overflow-style: none; /* IE 10+ */
}

.Popup::-webkit-scrollbar { /* WebKit */
  width: 0;
  height: 0;
}

.Popup-content {
  padding: 20px;
  height: 150vh;   /* Demo only... you place text inside */
  margin-bottom: 15vh;
  border: 10px dashed #000;
  background: #0bf;
}

<h2>Lorem Ipsum</h2>
<div class="Popup">
  <div class="Popup-content">
    Scroll...
  </div>
</div>

Without hiding the scrollbars I don't think there's any sane solution to do it in pure CSS, not without the use of some JavaScript.


问:
Action button without Form | ASP.NET CORE Razor Pages
I want a  tag that basically performs a post action on my razor page model including a parameter. Ideally I don't want to have a form around it and have the linking to the according action in the href="post-to-action"

in MVC I was always able to call a controller action without having a form around a button/ with the following:

```<code> <a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
</code>```

This doesn't work for razor pages im pretty sure. Im struggling to find an alternative in razor pages. Of course ajax is an option but I didn't find an alternative to make a post call in razor pages without having a  around it.

Does anybody have a workaround without having to submit a form with javascript or something along those lines?

答:
In asp.net core razor pages , you can redirect user to another page with parameter like :

```<code><a asp-page="/pageName" asp-route-id="@Model.ID">redirect</a>
</code>```

But that is a Get request , you can't used to post data . You stil need to post use form :

https://www.learnrazorpages.com/razor-pages/handler-methods

Or use js to collect data and send to another page using AJAX .

Body:
I want a  tag that basically performs a post action on my razor page model including a parameter. Ideally I don't want to have a form around it and have the linking to the according action in the href="post-to-action"

in MVC I was always able to call a controller action without having a form around a button/ with the following:

 Add an Admin

This doesn't work for razor pages im pretty sure. Im struggling to find an alternative in razor pages. Of course ajax is an option but I didn't find an alternative to make a post call in razor pages without having a  around it.

Does anybody have a workaround without having to submit a form with javascript or something along those lines?

Body:
In asp.net core razor pages , you can redirect user to another page with parameter like :

<a asp-page="/pageName" asp-route-id="@Model.ID">redirect</a>

But that is a Get request , you can't used to post data . You stil need to post use form :

https://www.learnrazorpages.com/razor-pages/handler-methods

Or use js to collect data and send to another page using AJAX .


问:
List of IP addresses/hostnames from local network in Python
How can I get a list of the IP addresses or host names from a local network easily in Python?

It would be best if it was multi-platform, but it needs to work on Mac OS X first, then others follow.

Edit: By local I mean all active addresses within a local network, such as 192.168.xxx.xxx.

So, if the IP address of my computer (within the local network) is 192.168.1.1, and I have three other connected computers, I would want it to return the IP addresses 192.168.1.2, 192.168.1.3, 192.168.1.4, and possibly their hostnames.

答:
Update: The script is now located on github.

I wrote a small python script, that leverages scapy's arping().

OwnerDisplayName: joshhunt

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: joshhunt

OwnerDisplayName: bene

ContentLicense: CC BY-SA 3.0


问:
Is it possible to add a fallback template ref to a directive?
In Angular 8, I am using a directive to read a value in the store, and not render div depending on the value :

Directive :

```<code>@Directive({
    selector: '[appOperator]'
})
export class OperatorDirective implements OnInit, OnDestroy {

    private isOperator = false;
    private subscription: Subscription;

    constructor(private elementRef: ElementRef,
                private viewContainer: ViewContainerRef,
                private templateRef: TemplateRef<any>,
                private store$: Store<RootStoreState.IAppState>) { }

    ngOnInit() {
        this.subscription = this.store$.pipe(select(AuthStoreSelectors.isOperator)).subscribe((isOperator) => {
            this.isOperator = isOperator;
            this.setElementOperation();
        });
    }

    setElementOperation(): void {
        if (this.isOperator) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code>```

Use case :

```<code>      <app-name-input
        class="header_name"
        [name]="waypoint.name"
        (nameChange)="applyRename(waypoint, $event)"
        *appOperator
      ></app-name-input>
</code>```

I would like to have some sort of fallback template in case the original content is hidden. So I was trying to add a template fallback to the directive that would be displayed in this situation :

I added :

```<code>@Input() fallBackTemplateRef: TemplateRef<any>;
setElementOperation(): void {
    if (this.isOperator) {
        this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
        this.viewContainer.clear();

        if(this.fallBackTemplateRef) {
            this.viewContainer.createEmbeddedView(this.fallBackTemplateRef);
        }
    }
}
</code>```

And I am trying to use it as follow

```<code>      <ng-template #myTemplate let-waypoint="waypoint">
        <div class="header_name">{{waypoint.name}}</div>
      </ng-template>
      <app-name-input
        class="header_name"
        [name]="waypoint.name"
        (nameChange)="applyRename(waypoint, $event)"
        appOperator
        *appOperator
        fallBackTemplateRef="myTemplate"
      ></app-name-input>
</code>```

The problem I face is this compile but do not work in the app, fallBackTemplateRef is always undefined and I can't nothing is drawn

Is it possible to achieve what I am trying to do ? what am I missing ?

答:
In your version, you're not binding to fallbackTemplateRef. And trying to use the [fallbackTemplateRef] syntax would be attempting to bind to an input property on the component.

To bind to additional properties on a structural directive, you can take *ngFor as an example.

```<code>*ngFor="let item of collection;trackBy: trackByFn"
</code>```

In the source code, this is achieved by creating an input property prefixed with the directive selector:

```<code>@Input() set ngForTrackBy(fn: TrackByFn) {
  this._trackByFn = fn;
}
</code>```

The solution

DEMO: https://stackblitz.com/edit/router-template-vm1hsv

I have modified your directive to take an additional input property in the style of *ngForTrackBy:

```<code>import { Directive, OnInit, OnDestroy, ElementRef, ViewContainerRef, TemplateRef, Input } from '@angular/core';

import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Directive({
  selector: '[appOperator]'
})
export class OperatorDirective implements OnInit, OnDestroy {

  constructor(private elementRef: ElementRef,
    private viewContainer: ViewContainerRef,
    private templateRef: TemplateRef<any>
  ) {
  }

  // dummy default input
  @Input('appOperator') dummy: string;
  @Input('appOperatorFallback') fallback: TemplateRef<any>;

  private isOperator = false;
  private destroyed: Subject<void> = new Subject<void>();

  ngOnInit() {
    interval(1000).pipe(
      takeUntil(this.destroyed)
    ).subscribe(() => {
      this.isOperator = !this.isOperator;
      this.setElementOperation();
    });

    this.setElementOperation();
  }

  setElementOperation(): void {
    this.viewContainer.clear();

    if (this.isOperator) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else if(this.fallback) {
      this.viewContainer.createEmbeddedView(this.fallback);
    }
  }

  ngOnDestroy() {
    this.destroyed.next();
    this.destroyed.complete();
  }
}
</code>```

I used an rxjs interval to allow me to create a working demo. You would replace this with your observable.

This is then used in the html like this:

```<code><ng-template #myfallback>
  <div>
    FALLBACK
  </div>
</ng-template>

<other *appOperator="'';fallback:myfallback">
</other>
</code>```

Where <other> is some other component.

The breakdown of '';fallback:myfallback is this:

'' - this is the input for the @Input('appOperator') dummy input property. It can be literally anything except blank. I chose an empty string, but it could also be an undeclared variable: _;fallback:myfallback

; - input property separator

fallback:myfallback is passing the template #myfallback in to the @Input('appOperatorFallback') fallback: TemplateRef<any>; property

My problem with this is that *appLoading="'';fallback:fallback" is ugly. I chose to leave the default input as a dummy since it doesn't make sense given that the fallback isn't a primary input value for the operator directive.

In my research I couldn't find a way to specifiy additional inputs without specifying something in that initial spot.

If you were to only ever have one input and don't like the syntax I have reluctantly chosen, you could always pass the fallback in as the primary input:

```<code>@Input('appOperator') fallback: TemplateRef<any>;
</code>```

And then it's simply a case of using it like this:

```<code>*appOperator="myfallback"
</code>```

To me there is some cognitive dissonance with this, but at least it's pretty :)

Body:
In Angular 8, I am using a directive to read a value in the store, and not render div depending on the value :

Directive :

@Directive({
    selector: '[appOperator]'
})
export class OperatorDirective implements OnInit, OnDestroy {

    private isOperator = false;
    private subscription: Subscription;

    constructor(private elementRef: ElementRef,
                private viewContainer: ViewContainerRef,
                private templateRef: TemplateRef<any>,
                private store$: Store<RootStoreState.IAppState>) { }

    ngOnInit() {
        this.subscription = this.store$.pipe(select(AuthStoreSelectors.isOperator)).subscribe((isOperator) => {
            this.isOperator = isOperator;
            this.setElementOperation();
        });
    }

    setElementOperation(): void {
        if (this.isOperator) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

Use case :

      <app-name-input
        class="header_name"
        [name]="waypoint.name"
        (nameChange)="applyRename(waypoint, $event)"
        *appOperator
      ></app-name-input>

I would like to have some sort of fallback template in case the original content is hidden. So I was trying to add a template fallback to the directive that would be displayed in this situation :

I added :

@Input() fallBackTemplateRef: TemplateRef<any>;
setElementOperation(): void {
    if (this.isOperator) {
        this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
        this.viewContainer.clear();

        if(this.fallBackTemplateRef) {
            this.viewContainer.createEmbeddedView(this.fallBackTemplateRef);
        }
    }
}

And I am trying to use it as follow

      <ng-template #myTemplate let-waypoint="waypoint">

{{waypoint.name}}

      </ng-template>
      <app-name-input
        class="header_name"
        [name]="waypoint.name"
        (nameChange)="applyRename(waypoint, $event)"
        appOperator
        *appOperator
        fallBackTemplateRef="myTemplate"
      ></app-name-input>

The problem I face is this compile but do not work in the app, fallBackTemplateRef is always undefined and I can't nothing is drawn

Is it possible to achieve what I am trying to do ? what am I missing ?

Body:
In your version, you're not binding to fallbackTemplateRef. And trying to use the [fallbackTemplateRef] syntax would be attempting to bind to an input property on the component.

To bind to additional properties on a structural directive, you can take *ngFor as an example.

*ngFor="let item of collection;trackBy: trackByFn"

In the source code, this is achieved by creating an input property prefixed with the directive selector:

@Input() set ngForTrackBy(fn: TrackByFn) {
  this._trackByFn = fn;
}

The solution

DEMO: https://stackblitz.com/edit/router-template-vm1hsv

I have modified your directive to take an additional input property in the style of *ngForTrackBy:

import { Directive, OnInit, OnDestroy, ElementRef, ViewContainerRef, TemplateRef, Input } from '@angular/core';

import { Subject, interval } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Directive({
  selector: '[appOperator]'
})
export class OperatorDirective implements OnInit, OnDestroy {

  constructor(private elementRef: ElementRef,
    private viewContainer: ViewContainerRef,
    private templateRef: TemplateRef<any>
  ) {
  }

  // dummy default input
  @Input('appOperator') dummy: string;
  @Input('appOperatorFallback') fallback: TemplateRef<any>;

  private isOperator = false;
  private destroyed: Subject<void> = new Subject<void>();

  ngOnInit() {
    interval(1000).pipe(
      takeUntil(this.destroyed)
    ).subscribe(() => {
      this.isOperator = !this.isOperator;
      this.setElementOperation();
    });

    this.setElementOperation();
  }

  setElementOperation(): void {
    this.viewContainer.clear();

    if (this.isOperator) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else if(this.fallback) {
      this.viewContainer.createEmbeddedView(this.fallback);
    }
  }

  ngOnDestroy() {
    this.destroyed.next();
    this.destroyed.complete();
  }
}

I used an rxjs interval to allow me to create a working demo. You would replace this with your observable.

This is then used in the html like this:

<ng-template #myfallback>
  <div>
    FALLBACK
  </div>
</ng-template>

<other *appOperator="'';fallback:myfallback">
</other>

Where <other> is some other component.

The breakdown of '';fallback:myfallback is this:

'' - this is the input for the @Input('appOperator') dummy input property. It can be literally anything except blank. I chose an empty string, but it could also be an undeclared variable: _;fallback:myfallback

; - input property separator

fallback:myfallback is passing the template #myfallback in to the @Input('appOperatorFallback') fallback: TemplateRef<any>; property

My problem with this is that *appLoading="'';fallback:fallback" is ugly. I chose to leave the default input as a dummy since it doesn't make sense given that the fallback isn't a primary input value for the operator directive.

In my research I couldn't find a way to specifiy additional inputs without specifying something in that initial spot.

If you were to only ever have one input and don't like the syntax I have reluctantly chosen, you could always pass the fallback in as the primary input:

@Input('appOperator') fallback: TemplateRef<any>;

And then it's simply a case of using it like this:

*appOperator="myfallback"

To me there is some cognitive dissonance with this, but at least it's pretty :)


问:
Unable to get anchor tag value in the output
I wrote the anchor tag of json in typescript file and condition is written in html. So I am unable to get anchor tag value:

                    {{i+1}}. {{item.title}}

                  {{item.description}}

```

<p>In .ts file I wrote json:</p>

<pre class="lang-js prettyprint-override"><code>    this.items = [ {
              "id":"9","href":"#9","className":"addBorder collapsed","title":"Does the discount apply to my current insurance? ","description":"No. These are offers from other participating insurers, and the discount applies only to what they would otherwise charge in premiums without your driving data."
            },
            {
              "id":"10","href":"#10","className":"addBorder collapsed","title":"Click here to view more frequently asked questions","description":"FAQ"
            },
           ]
</code>```

答:
items is an array, so you need to pass index while referring it in the HTML

```<code><div id="{{item[0].id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
  <div class="panel-body" style="padding-top: 0px;font-style: italic;padding-left: 30px;">
    {{item[0].description}}
  </div>
</div>
</code>```

or loop the array like below

```<code><div *ngFor="let item of items">
  <div id="{{item.id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
    <div class="panel-body" style="padding-top: 0px;font-style: italic;padding-left: 30px;">
      {{item.description}}
    </div>
  </div>
</div>
</code>```

Body:
I wrote the anchor tag of json in typescript file and condition is written in html. So I am unable to get anchor tag value:

                    {{i+1}}. {{item.title}}

                  {{item.description}}

In .ts file I wrote json:

    this.items = [ {
              "id":"9","href":"#9","className":"addBorder collapsed","title":"Does the discount apply to my current insurance? ","description":"No. These are offers from other participating insurers, and the discount applies only to what they would otherwise charge in premiums without your driving data."
            },
            {
              "id":"10","href":"#10","className":"addBorder collapsed","title":"Click here to view more frequently asked questions","description":"FAQ"
            },
           ]

Body:
items is an array, so you need to pass index while referring it in the HTML

<div id="{{item[0].id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
  <div class="panel-body" style="padding-top: 0px;font-style: italic;padding-left: 30px;">
    {{item[0].description}}
  </div>
</div>

or loop the array like below

<div *ngFor="let item of items">
  <div id="{{item.id}}" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
    <div class="panel-body" style="padding-top: 0px;font-style: italic;padding-left: 30px;">
      {{item.description}}
    </div>
  </div>
</div>


问:
Construct an object from multiple sources including a vector of objects
I get different fields [of potentially one class] from two different sources on the fly in c++.
First a class A's fields gets passed on in function #1 (getData_Main) and then a vector of fields in another local function #2(getVecor_Sublass);
The function calls are always sequential #1 followed by #2.
Here are the simplified data structures;

```<code>class Subclass {
    string str;
    string str2;
    //a few other fields
};

class Main {
    string name;
    float somevar;
    // few more string fields
    vector<Subclass> vecSubclass;
};
</code>```

I need to save the state of data to make it persistent to be used in other interfaces, something like construct a vector object vector.
I thought about creating a variable that serves as an index to main class and use the same index in Subclass and form a sort of lookup table? But then how to do that in best possible and more efficient way?

Unfortunately I'm not much familiar with the modern C++ (11/14) features and constructs, still a c++ 03 developer) so thought about posting here to get some suggestions with some working piece of code snippet in case of lambdas or any newer features?

```<code>class Main
{
    int index; //create from some static variable in function A and pass on to function B
    string name;
    float somevar;
    vector<A> vecA;
};
</code>```

Update (Answering the comments)

Input is the data fields coming from java/jni native functions;

Desired output is the vector objects.

Issue#1 is the input fields of one java class are coming in two native functions, so C++ is getting two sets of fields (Set#1 is all the fields of Main class and set#2 is  vector<Subclass> contained in class Main fields;).

I'm just trying to reconstruct the object and trying different options.

As they are coming in local functions, there is nothing common to rebuild the vector objects unless we do something like creating an index to serve as a key and build vector objects in C++ from these two sources.
Issue#2 is how to do it in best possible way.

I hope the question makes some sense now?

Edited to add the following Java code which we are trying to mimic the functionality of:

```<code>public class MainLine {
    String name;
    String Locator;
    Sub[] SubList = new Sub[5];
}
public class Test {
   MainLine[] MainLineArray = new MainLine[10000];
    // Data coming from some other sources in Java
   for (int j=0;j<10000;j++){
       test.addMainLine(MainLineArray[j].Locator, MainLineArray[j].name);
       for (int k=0;k<5;k++) {
        test.addSubList(MainLineArray[j].SubList[k].field1, MainLineArray[j].SubList[k].field2, MainLineArray[j].subList[k].field3,.....);
    }
  }
}
</code>```

答:
I think you are asking how to make an object whose fields are made of data got in multiple separate calls of certain functions. In general to deal with these type situations you need to pass identifiers or something to the object-building functions to find out which values belong to which object.

But in JNI case as yours, a native function can return an address as jlong pointing to an incomplete object under construction to the Java program, which in turn can be repeatedly passed to native functions updating the same object.

In Java:

native static long createMain(int val);

native static void addSubToMain(long main, int val);

void createMainsInNative() {
  long main = createMain("a");
  addSubToMain(main, "X");
  addSubToMain(main, "Y");
}
```

<p>In C++:</p>

<pre class="lang-cpp prettyprint-override"><code>class Main {
  int val;
  std::vector<Sub> subs;
};

class Sub { int val; };

std::vector<std::unique_ptr<Main>> g_mains;

JNIEXPORT jlong Java_SomeClass_createMain(JEnv*, jclass, jint val)
{
  auto obj = std::make_unique<Main>();
  auto raw = static_cast<jlong>(reinterpret_cast<intptr_t>(obj.get()));
  obj->val = val;
  g_mains.emplace_back(std::move(obj));
  return raw
}

JNIEXPORT void Java_SomeClass_addSubToMain(JEnv*, jclass, jlong main, jint val)
{
  reinterpret_cast<Main*>(static_cast<intptr_t>(main))->subs.push_back(Sub { val });
}
</code>```

Body:
I get different fields [of potentially one class] from two different sources on the fly in c++.
First a class A's fields gets passed on in function #1 (getData_Main) and then a vector of fields in another local function #2(getVecor_Sublass);
The function calls are always sequential #1 followed by #2.
Here are the simplified data structures;

class Subclass {
    string str;
    string str2;
    //a few other fields
};

class Main {
    string name;
    float somevar;
    // few more string fields
    vector<Subclass> vecSubclass;
};

I need to save the state of data to make it persistent to be used in other interfaces, something like construct a vector object vector.
I thought about creating a variable that serves as an index to main class and use the same index in Subclass and form a sort of lookup table? But then how to do that in best possible and more efficient way?

Unfortunately I'm not much familiar with the modern C++ (11/14) features and constructs, still a c++ 03 developer) so thought about posting here to get some suggestions with some working piece of code snippet in case of lambdas or any newer features?

class Main
{
    int index; //create from some static variable in function A and pass on to function B
    string name;
    float somevar;
    vector vecA;
};

Update (Answering the comments)

Input is the data fields coming from java/jni native functions;

Desired output is the vector objects.

Issue#1 is the input fields of one java class are coming in two native functions, so C++ is getting two sets of fields (Set#1 is all the fields of Main class and set#2 is  vector<Subclass> contained in class Main fields;).

I'm just trying to reconstruct the object and trying different options.

As they are coming in local functions, there is nothing common to rebuild the vector objects unless we do something like creating an index to serve as a key and build vector objects in C++ from these two sources.
Issue#2 is how to do it in best possible way.

I hope the question makes some sense now?

Edited to add the following Java code which we are trying to mimic the functionality of:

public class MainLine {
    String name;
    String Locator;
    Sub[] SubList = new Sub[5];
}
public class Test {
   MainLine[] MainLineArray = new MainLine[10000];
    // Data coming from some other sources in Java
   for (int j=0;j<10000;j++){
       test.addMainLine(MainLineArray[j].Locator, MainLineArray[j].name);
       for (int k=0;k<5;k++) {
        test.addSubList(MainLineArray[j].SubList[k].field1, MainLineArray[j].SubList[k].field2, MainLineArray[j].subList[k].field3,.....);
    }
  }
}

Body:
I think you are asking how to make an object whose fields are made of data got in multiple separate calls of certain functions. In general to deal with these type situations you need to pass identifiers or something to the object-building functions to find out which values belong to which object.

But in JNI case as yours, a native function can return an address as jlong pointing to an incomplete object under construction to the Java program, which in turn can be repeatedly passed to native functions updating the same object.

In Java:

native static long createMain(int val);

native static void addSubToMain(long main, int val);

void createMainsInNative() {
  long main = createMain("a");
  addSubToMain(main, "X");
  addSubToMain(main, "Y");
}

In C++:

class Main {
  int val;
  std::vector<Sub> subs;
};

class Sub { int val; };

std::vector<std::unique_ptr<Main>> g_mains;

JNIEXPORT jlong Java_SomeClass_createMain(JEnv*, jclass, jint val)
{
  auto obj = std::make_unique<Main>();
  auto raw = static_cast<jlong>(reinterpret_cast<intptr_t>(obj.get()));
  obj->val = val;
  g_mains.emplace_back(std::move(obj));
  return raw
}

JNIEXPORT void Java_SomeClass_addSubToMain(JEnv*, jclass, jlong main, jint val)
{
  reinterpret_cast<Main*>(static_cast<intptr_t>(main))->subs.push_back(Sub { val });
}


问:
proper way to down a node/member in akka cluster
Is there any proper way to down a node when this become unreachable in akka cluster. I want to expose an api to down a node when it becomes unreachable but I prefer to find another way or something programmatically. Auto-downing is not an option anymore since I've been having split brain issues.

Can I just down the node in the receive  method :

def receive: Receive = {
    case MemberUp(member) =>

```<code>case UnreachableMember(member) => {
  Cluster(context.system).down(member.address)
}
</code>```

答:
If the node has crashed, downing it on any other node is fine.

But you must do it as a reaction to seeing it unreachable though, that will cause split brain if it is a network partition rather than a node crashing the unreachable each side of the partition will see the rest of the cluster as unreachable and down all those, and you will end up with two clusters thinking that they have downed the other side.

This is the exact reason why we have removed auto downing in Akka 2.6

If you want automatic removal of nodes with split brain resolution you will need to use/implement a downing provider that handles that for you.

Implementing a downing provider yourself will require quite a bit of effort and thinking it through. For more background on the problem you can read the docs of the commercial Lightbend SBR here: https://doc.akka.io/docs/akka-enhancements/current/split-brain-resolver.html

Body:
Is there any proper way to down a node when this become unreachable in akka cluster. I want to expose an api to down a node when it becomes unreachable but I prefer to find another way or something programmatically. Auto-downing is not an option anymore since I've been having split brain issues.

Can I just down the node in the receive  method :

def receive: Receive = {
    case MemberUp(member) =>

case UnreachableMember(member) => {
  Cluster(context.system).down(member.address)
}


问:
Is it possible to display 3D view of multiple DWG and Revit models together in a viewer
I have loaded Two models one is .dwg and Second one is .rvt in web viewer using Autodesk Forge API.
I want to see both files in 3D view in viewer But it shows .rvt file in 3D and .dwg file in 2D.</p>

答:
Unfortunately loading both 2D and 3D models onto one scene is not supported yet.

However you can have two Viewer instances in one page - see a sample in point here: https://github.com/Autodesk-Forge/viewer-navigation.sample


问:
Wordpress functions - get values without echo
How can I programmatically use the data of the bult-in Wordpress functions.

E.g. I'd like to use the data of

```<code>the_author_meta('login_name');
</code>```

in a php function. Problem: The function echoes the value by default. In order to use the actual value in a function I can think of using an output buffer like ...

```<code>ob_start();
the_author_meta('login_name');
$contents = ob_get_contents();
ob_end_clean();
</code>```

but I was hoping for a better (less bloated) solution.

Any idea how to get the echo values as simple return values instead?

答:
use get_the_author_meta() for return the value.

Note:  All of wordpress meta methods (the_post,the_author,the_page etc.) are supports the get_ prefix

Body:
How can I programmatically use the data of the bult-in Wordpress functions.

E.g. I'd like to use the data of

the_author_meta('login_name');

in a php function. Problem: The function echoes the value by default. In order to use the actual value in a function I can think of using an output buffer like ...

ob_start();
the_author_meta('login_name');
$contents = ob_get_contents();
ob_end_clean();

but I was hoping for a better (less bloated) solution.

Any idea how to get the echo values as simple return values instead?


问:
Angular interceptor - how do I logout if refresh token interceptor fails?
Info

I am creating an interceptor to use my refresh token to update my access token if I get a 401. The workflow looks like this now:

Sends request > gets 401 > sends refresh request > updates access token > sends new request

I am currently working with promises instead of observables.

Question

How do I logout if the last request fails?

Sends request > gets 401 > sends refresh request > updates access token > sends new request > fails > log out

I have a simple method for logging out, but I cannot find where to put it within the interceptor.

Code

export class RefreshInterceptor implements HttpInterceptor {
    currentUser: User | null = null;
    private isRefreshing = false;
    private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
        null
    );

    constructor(private authenticationService: AuthenticationService) {
        this.authenticationService.currentUser.subscribe(
            user => (this.currentUser = user)
        );
    }

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(error => {
                // check if user is signed in
                if (!this.currentUser) {
                    return throwError(error);
                }

                // handle only 401 error
                if (error instanceof HttpErrorResponse && error.status === 401) {
                    return from(this.handle401Error(request, next));
                } else {
                    return throwError(error);
                }
            })
        );
    }

    /**
     * Adds the new access token as a bearer header to the request
     * @param request - the request
     * @param token - the new access token
     */
    private async addToken(request: HttpRequest<any>, token: string) {
        const currentUser = this.authenticationService.currentUserValue;

        if (currentUser && currentUser.accessToken) {
            return request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`
                }
            });
        }

        return request;
    }

    private async handle401Error(request: HttpRequest<any>, next: HttpHandler) {
        // check if it is currently refreshing or not
        if (!this.isRefreshing) {
            this.isRefreshing = true;
            this.refreshTokenSubject.next(null);

            // send refresh request
            const token = await this.authenticationService.getRefresh();

            // update bearer token
            const newRequest = await this.addToken(request, token);

            // update values for next request
            this.isRefreshing = false;
            this.refreshTokenSubject.next(token);
            return next.handle(newRequest).toPromise();
        } else {
            const token = this.refreshTokenSubject.value();
            const newRequest = await this.addToken(request, token);
            return next.handle(newRequest).toPromise();
        }
    }
}
```

答:
I solved it with the following approach:

Modified the header of the outgoing, changed request (added a retry header so that I could identify it later).

Created a new interceptor for logout

Looked for a request with the retry header. Signed that request out.

Refresh token interceptor

if (currentUser && currentUser.accessToken) {
            return request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`,
                    Retry: "true"
                }
            });
        }
```

<h2>Logout interceptor</h2>

<pre class="lang-js prettyprint-override"><code>@Injectable()
export class LogoutInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(error => {
                // handle only 401 error
                if (error instanceof HttpErrorResponse && error.status === 401) {
                    from(this.handleRequest(request));
                    return throwError(error);
                }

                return next.handle(request);
            })
        );
    }

    private async handleRequest(request: HttpRequest<any>) {
        const isRetriedRequest = request.headers.get("retry");

        if (isRetriedRequest) {
            await this.authenticationService.logout();
        }
    }
}
</code>```

Body:
I solved it with the following approach:

Modified the header of the outgoing, changed request (added a retry header so that I could identify it later).

Created a new interceptor for logout

Looked for a request with the retry header. Signed that request out.

Refresh token interceptor

if (currentUser && currentUser.accessToken) {
            return request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`,
                    Retry: "true"
                }
            });
        }

Logout interceptor

@Injectable()
export class LogoutInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(error => {
                // handle only 401 error
                if (error instanceof HttpErrorResponse && error.status === 401) {
                    from(this.handleRequest(request));
                    return throwError(error);
                }

                return next.handle(request);
            })
        );
    }

    private async handleRequest(request: HttpRequest<any>) {
        const isRetriedRequest = request.headers.get("retry");

        if (isRetriedRequest) {
            await this.authenticationService.logout();
        }
    }
}


问:
c++ fold expression with user defined class
I'd like make a log function with multiple parameters, and I also want to call the log function with my class.

Here is my code (compiler : Visual studio 2019 or x86-64 gcc9.2)

Question 1> I cannot understand log function.
Is it possible to use fold expression like this ?
(this function comes from spdlog library)

Question 2>
How could I use the log function with Mystruct class ?

log(1, MyStruct(1, 1.1f, "hello world"s)); // compiler error

```<code>#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

template<typename ... Args>
void log(int level, Args const& ... args)
{
    std::ostringstream stream;
    using List = int[];
    (void)List {
        0, ((void)(stream << args), 0) ...
    };
    std::cout << stream.str() << std::endl;
}

class MyStruct
{
public:
    int val1 = 0;
    float val2 = 0.f;
    std::string val3;

    MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
    std::string to_string() const
    {
        std::stringstream stream;
        stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
        return stream.str();
    }
};

std::ostringstream& operator<< (std::ostringstream& stream, MyStruct&& val)
{
    auto str = val.to_string();
    std::operator <<(stream, str);
    return stream;
}

void work_good()
{
    using namespace std::string_literals;
    log(1, 1.1f, "hello world"s);
}

void compile_error()
{
    using namespace std::string_literals;
    log(1, MyStruct(1, 1.1f, "hello world"s));
}

int main()
{
    work_good();
}
</code>```

答:
I changed some code referred answer.
I want to log function to be more generic</p>

```<code>namespace nlog
{
    class MyStruct
    {
    public:
        int val1 = 0;
        float val2 = 0.f;
        std::string val3;

        MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
        std::string to_string() const
        {
            std::stringstream stream;
            stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
            return stream.str();
        }
    };

    template < typename T, typename decltype(std::declval<T>().to_string())* = nullptr>
        std::ostream& operator<< (std::ostream& stream, T&& val)
    {
        auto str = val.to_string();
        std::operator <<(stream, str);
        return stream;
    }

    template <typename ... Ts>
    void tolog(Ts && ...args)
    {
        std::stringstream strbuf;
        (strbuf << ... << std::forward<Ts>(args));

        std::cout << strbuf.str() << std::endl;
    }

    template <typename ... Ts>
    void toout(Ts && ...args)
    {
        (std::cout << ... << args);
    }
};

namespace nlog
{
    void Test1()
    {
        using namespace std::string_literals;
        std::stringstream strbuf;
        strbuf << MyStruct(0, 0.1f, "Eric"s);
        std::cout << strbuf.str() << std::endl;
    }

    void Test2()
    {
        using namespace std::string_literals;
        tolog(1, 1.1f, "hello world"s);
    }

    void Test3()
    {
        using namespace std::string_literals;
        tolog("I like this func val=", 100, ", youvalue=", 1.0f, ", MyStruct=",  MyStruct(0, 0.1f, "Eric"s));
    }
};

int main()
{
    nlog::Test1();
    nlog::Test2();
    nlog::Test3();
}
</code>```

Body:
I'd like make a log function with multiple parameters, and I also want to call the log function with my class.

Here is my code (compiler : Visual studio 2019 or x86-64 gcc9.2)

Question 1> I cannot understand log function.
Is it possible to use fold expression like this ?
(this function comes from spdlog library)

Question 2>
How could I use the log function with Mystruct class ?

log(1, MyStruct(1, 1.1f, "hello world"s)); // compiler error

#include <cstdio>
#include <iostream>
#include <string>
#include <sstream>

template<typename ... Args>
void log(int level, Args const& ... args)
{
    std::ostringstream stream;
    using List = int[];
    (void)List {
        0, ((void)(stream << args), 0) ...
    };
    std::cout << stream.str() << std::endl;
}

class MyStruct
{
public:
    int val1 = 0;
    float val2 = 0.f;
    std::string val3;

    MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
    std::string to_string() const
    {
        std::stringstream stream;
        stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
        return stream.str();
    }
};

std::ostringstream& operator<< (std::ostringstream& stream, MyStruct&& val)
{
    auto str = val.to_string();
    std::operator <<(stream, str);
    return stream;
}

void work_good()
{
    using namespace std::string_literals;
    log(1, 1.1f, "hello world"s);
}

void compile_error()
{
    using namespace std::string_literals;
    log(1, MyStruct(1, 1.1f, "hello world"s));
}

int main()
{
    work_good();
}

Body:
I changed some code referred answer.
I want to log function to be more generic

namespace nlog
{
    class MyStruct
    {
    public:
        int val1 = 0;
        float val2 = 0.f;
        std::string val3;

        MyStruct(int v1, float v2, std::string_view const& v3) : val1(v1), val2(v2), val3(v3) {};
        std::string to_string() const
        {
            std::stringstream stream;
            stream << "val1=" << val1 << ", val2=" << val2 << ",val3=" << val3;
            return stream.str();
        }
    };

    template < typename T, typename decltype(std::declval<T>().to_string())* = nullptr>
        std::ostream& operator<< (std::ostream& stream, T&& val)
    {
        auto str = val.to_string();
        std::operator <<(stream, str);
        return stream;
    }

    template <typename ... Ts>
    void tolog(Ts && ...args)
    {
        std::stringstream strbuf;
        (strbuf << ... << std::forward<Ts>(args));

        std::cout << strbuf.str() << std::endl;
    }

    template <typename ... Ts>
    void toout(Ts && ...args)
    {
        (std::cout << ... << args);
    }
};

namespace nlog
{
    void Test1()
    {
        using namespace std::string_literals;
        std::stringstream strbuf;
        strbuf << MyStruct(0, 0.1f, "Eric"s);
        std::cout << strbuf.str() << std::endl;
    }

    void Test2()
    {
        using namespace std::string_literals;
        tolog(1, 1.1f, "hello world"s);
    }

    void Test3()
    {
        using namespace std::string_literals;
        tolog("I like this func val=", 100, ", youvalue=", 1.0f, ", MyStruct=",  MyStruct(0, 0.1f, "Eric"s));
    }
};

int main()
{
    nlog::Test1();
    nlog::Test2();
    nlog::Test3();
}


问:
Can not install processr and procesR on Windows
Following this question, I am trying to install the package (running R64 as admin on Windows):

```<code>devtools::install_github("markhwhiteii/processr")
</code>```

or

```<code>devtools::install_github("cardiomoon/processR")
</code>```

However, I get the error message:

Error: Failed to install 'processr' from GitHub:
    (converted from warning) cannot remove prior installation of package 'digest'

no matter which update option I select. Running the command .libPaths() I found the packages installation folder C:/Program Files/R/R-3.6.2/library and manually deleted the digest package and reinstalled it with package.install("digest").  But I still get the same error! I would appreciate it if you could help me understand what is the problem and how I can resolve it.

答:
The simplest solution is to say no when install_github asks if it should replace digest.

If it still fails for some reason (and I can't see why; neither package requires a specific version of digest and you've reinstalled it in any case), then the problem is that devtools itself uses digest, so it can't be removed as long as devtools is loaded. So you can't use install_github.

You have a couple of options:

Clone the repo, then from the command line, run R CMD INSTALL . in that directory. Note that you'll need to insert the path to your R executable.

Install from the GitHub archive of the master branch: install.packages("https://github.com/markhwhiteii/processr/archive/master.tar.gz")

Body:
Following this question, I am trying to install the package (running R64 as admin on Windows):

devtools::install_github("markhwhiteii/processr")

or

devtools::install_github("cardiomoon/processR")

However, I get the error message:

Error: Failed to install 'processr' from GitHub:
    (converted from warning) cannot remove prior installation of package 'digest'

no matter which update option I select. Running the command .libPaths() I found the packages installation folder C:/Program Files/R/R-3.6.2/library and manually deleted the digest package and reinstalled it with package.install("digest").  But I still get the same error! I would appreciate it if you could help me understand what is the problem and how I can resolve it.


问:
Reactjs: How do I remove the page-not-found component from every existing URL?
I am building react app.

If a user types the wrong URL, the NoMatch component is shown (which is fine).

Challenge is that when a user types an existing URL, two components are shown. The NoMatch component and the expected component both appear.

Note: I found some questions about this on stackoverflow, but non of the solutions worked for me. I am using a <PrivateRoute> and react-router-dom.

App.js

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>

                    <Sidebar/>

                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute path="*" component={NoMatch}/>

            </Fragment>
        </Switch>
    </Router>
</Provider>
```

<p>PrivateRoute.js</p>

<pre class="lang-js prettyprint-override"><code>const PrivateRoute = ({component: Component, auth, ...rest}) => (
    <Route
        {...rest}
        render={props =>
            auth.isAuthenticated ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: {from: props.location}
                    }}
                />
            )
        }
    />
);
</code>```

That is the problem that I have.

Any idea what I am doing wrong that I do not get the result that I want?

答:
Switch only works for it's direct children, when you add something like a Fragment inside it, Switch loses it's effect on the Route components inside it.

In your case, you can simply move the Switch inside to contain the array of PrivateRoute components to make it work

```<code><Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>
                <div className="main-part">
                    <Sidebar/>
                    <main className="content shrunk-sidebar">
                        <Switch>
                            <PrivateRoute path="/" exact component={Home}/>
                            <PrivateRoute path="/files" exact component={Files}/>
                            <PrivateRoute path="/new_app" exact component={NewApp}/>
                            <PrivateRoute path="/applications/:app_name" exact component={Application}/>
                            <PrivateRoute path="*" component={NoMatch}/>
                        </Switch>
                    </main>
                </div>
            </Fragment>
        </Switch>
    </Router>
</Provider>
</code>```

Body:
I am building react app.

If a user types the wrong URL, the NoMatch component is shown (which is fine).

Challenge is that when a user types an existing URL, two components are shown. The NoMatch component and the expected component both appear.

Note: I found some questions about this on stackoverflow, but non of the solutions worked for me. I am using a <PrivateRoute> and react-router-dom.

App.js

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>

                    <Sidebar/>

                        <PrivateRoute path="/" exact component={Home}/>
                        <PrivateRoute path="/files" exact component={Files}/>
                        <PrivateRoute path="/new_app" exact component={NewApp}/>
                        <PrivateRoute path="/applications/:app_name" exact component={Application} />
                        <PrivateRoute path="*" component={NoMatch}/>

            </Fragment>
        </Switch>
    </Router>
</Provider>

PrivateRoute.js

const PrivateRoute = ({component: Component, auth, ...rest}) => (
    <Route
        {...rest}
        render={props =>
            auth.isAuthenticated ? (
                <Component {...props} />
            ) : (
                <Redirect
                    to={{
                        pathname: "/login",
                        state: {from: props.location}
                    }}
                />
            )
        }
    />
);

That is the problem that I have.

Any idea what I am doing wrong that I do not get the result that I want?

Body:
Switch only works for it's direct children, when you add something like a Fragment inside it, Switch loses it's effect on the Route components inside it.

In your case, you can simply move the Switch inside to contain the array of PrivateRoute components to make it work

<Provider store={store}>
    <Router>
        <Switch>
            <Route exact path="/login" component={Login}/>
            <Fragment>
                <Navigationbar/>
                <div className="main-part">
                    <Sidebar/>
                    <main className="content shrunk-sidebar">
                        <Switch>
                            <PrivateRoute path="/" exact component={Home}/>
                            <PrivateRoute path="/files" exact component={Files}/>
                            <PrivateRoute path="/new_app" exact component={NewApp}/>
                            <PrivateRoute path="/applications/:app_name" exact component={Application}/>
                            <PrivateRoute path="*" component={NoMatch}/>
                        </Switch>
                    </main>
                </div>
            </Fragment>
        </Switch>
    </Router>
</Provider>


问:
After Flutter GIT project checkout, unable to run the project
So I created a Flutter project in IntelliJ Idea Community Edition on machine A and then uploaded the whole project on GitHub. Now I cloned/checked out from GitHub in the same IDE on machine B, performed the following:

flutter packages get

flutter upgrade

Set up the dart path and all other prerequisites

But, I am still unable to run the flutter project from IDE.
I mean I can't even press the "Run" button.

Where did I go wrong?

You can try performing the same steps as I did. it if you want. Here's the Git repository code

Edit I can run the same project via terminal.

[Update] As requested by Günter Zöchbauer in the comment log, here's the logs for flutter doctor -v

```<code>BoringFlutterProject$ flutter doctor -v
[✓] Flutter (Channel dev, v0.5.8, on Linux, locale en_IN)
    • Flutter version 0.5.8 at /home/daksh/flutter
    • Framework revision e4b989bf3d (8 days ago), 2018-08-09 09:45:44 -0700
    • Engine revision 3777931801
    • Dart version 2.0.0-dev.69.5.flutter-eab492385c

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at /home/daksh/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • ANDROID_HOME = /home/daksh/Android/Sdk
    • Java binary at: /home/daksh/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)
    • All Android licenses accepted.

[✓] Android Studio (version 3.1)
    • Android Studio at /home/daksh/android-studio
    • Flutter plugin version 25.0.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)

[✓] IntelliJ IDEA Community Edition (version 2018.1)
    • IntelliJ at /home/daksh/Downloads/idea-IC-181.5281.24
    • Flutter plugin version 25.0.2
    • Dart plugin version 181.4892.1

[✓] VS Code (version 1.26.0)
    • VS Code at /usr/share/code
    • Flutter extension version 2.17.1

[!] Connected devices
    ! No devices available

! Doctor found issues in 1 category.
</code>```

I posted this question because I'm sure many of us will face the same problem, just like we used to face some issues in AndroidStudio back then

答:
It is an Android Studio issue. The IDE doesn't apply the flutter SDK location for every new project you clone.
The workaround is to open the cloned project go to File>Settings(Ctrl+Alt+S). In 'Languages & Frameworks'>Flutter set the SDK path to your Flutter SDK location (e.g. C:\src\flutter). Once you apply the changes and run the 'Packages Get' command the cloned project is fully accessible and understood by Android Studio.</p>

Body:
So I created a Flutter project in IntelliJ Idea Community Edition on machine A and then uploaded the whole project on GitHub. Now I cloned/checked out from GitHub in the same IDE on machine B, performed the following:

flutter packages get

flutter upgrade

Set up the dart path and all other prerequisites

But, I am still unable to run the flutter project from IDE.
I mean I can't even press the "Run" button.

Where did I go wrong?

You can try performing the same steps as I did. it if you want. Here's the Git repository code

Edit I can run the same project via terminal.

[Update] As requested by Günter Zöchbauer in the comment log, here's the logs for flutter doctor -v

BoringFlutterProject$ flutter doctor -v
[✓] Flutter (Channel dev, v0.5.8, on Linux, locale en_IN)
    • Flutter version 0.5.8 at /home/daksh/flutter
    • Framework revision e4b989bf3d (8 days ago), 2018-08-09 09:45:44 -0700
    • Engine revision 3777931801
    • Dart version 2.0.0-dev.69.5.flutter-eab492385c

[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
    • Android SDK at /home/daksh/Android/Sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-27, build-tools 27.0.3
    • ANDROID_HOME = /home/daksh/Android/Sdk
    • Java binary at: /home/daksh/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)
    • All Android licenses accepted.

[✓] Android Studio (version 3.1)
    • Android Studio at /home/daksh/android-studio
    • Flutter plugin version 25.0.1
    • Dart plugin version 173.4700
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1024-b01)

[✓] IntelliJ IDEA Community Edition (version 2018.1)
    • IntelliJ at /home/daksh/Downloads/idea-IC-181.5281.24
    • Flutter plugin version 25.0.2
    • Dart plugin version 181.4892.1

[✓] VS Code (version 1.26.0)
    • VS Code at /usr/share/code
    • Flutter extension version 2.17.1

[!] Connected devices
    ! No devices available

! Doctor found issues in 1 category.

I posted this question because I'm sure many of us will face the same problem, just like we used to face some issues in AndroidStudio back then


问:
How to create load test for SSE using jmeter?
I am testing rest service which has subscription end point with header(2 key value pairs) values. On sucessful subscription I get 200 ok and soon get data streaming. How can I load test this in Jmeter?</p>

答:
As of current JMeter version 5.2.1 there is no built-in SSE support.

The options are in:

Consider another load testing tool which supports SSE like Gatling

Add SSE support to JMeter by adding a library which supports server sent events like okhttp-eventsource to JMeter Classpath and implement your test scenario using JSR223 Sampler(s) and Groovy language. Check out How to Load Test SSE Services with JMeter article for more information if you decide to stay with JMeter


问:
new xib in xcode4
I develped an iPhone app. Now i would like to do it in iPad. To do this I have to create the new .XIB files and linked to his Class.

I don't know how to create a new .xib in xcode4. Could somebody help me?

Now, to solve this problem, I create a new file with his .XIB, delete the .m & .h and link the .XIB with my class.

Thanyou.

答:
We also need two more nib files, one for each of the two content views we just created. To create these, single-click the Resources folder in the Groups & Files pane so that we create them in the correct place, and then press ␣N or select New File... from the File menu again. This time, when the assistant window comes up, select User Interfaces under the iPhone OS
heading in the left pane .

Select the icon for the View XIB template, which will create a nib with a content view, and then click the Next button. When prompted for a filename, type BlueView.xib. Repeat the steps to create a second nib file called YellowView.xib. Once you’ve done that, you have all the files you need. It’s time to start hooking everything together.

Title: new xib in xcode4


问:
Merge Excel workbooks to one Worksheet
I am trying to merge 250 database excel workbooks into one continuous worksheet.

All of the workbooks have the same kind of data, with the same headers.

I have tried using this VBA code:

```<code>Sub mergeFiles()
    'Merges all files in a folder to a main file.

    'Define variables:
    Dim numberOfFilesChosen, i As Integer
    Dim tempFileDialog As fileDialog
    Dim mainWorkbook, sourceWorkbook As Workbook
    Dim tempWorkSheet As Worksheet

    Set mainWorkbook = Application.ActiveWorkbook
    Set tempFileDialog = Application.fileDialog(msoFileDialogFilePicker)

    'Allow the user to select multiple workbooks
    tempFileDialog.AllowMultiSelect = True

    numberOfFilesChosen = tempFileDialog.Show

    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.Count

        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)

        Set sourceWorkbook = ActiveWorkbook

        'Copy each worksheet to the end of the main workbook
        For Each tempWorkSheet In sourceWorkbook.Worksheets
            tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
        Next tempWorkSheet

        'Close the source workbook
        sourceWorkbook.Close
    Next i

End Sub
</code>```

The code works fine, but it creates a new sheet for every workbook, instead of copying the data to the bottom row of 1 sheet.

答:
I prepared a very fast method of data moving (using arrays and working in memory), avoiding Copy and Paste.

Copy this new declarations at your declarations area:

Dim sh As Worksheet, arrCopy As Variant, lastR As Long

Copy this code line before the loop (For i = 1 To ...):

Set sh = mainWorkbook.Sheets(mainWorkbook.Worksheets.count) 'You can use here your sheet where the data will be collected. I used the last sheet for easy testing reason

Replace (in the loop For Each ...) the existing code (tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)) with the next one:

lastR = sh.Range("A" & sh.Rows.count).End(xlUp).row

arrCopy = tempWorkSheet.Range(tempWorkSheet.Range("A" & IIf(lastR = 1, 1, 2)), _
          tempWorkSheet.Range("A1").SpecialCells(xlLastCell)).Value
 sh.Range("A" & lastR + IIf(lastR = 1, 0, 1)).Resize(UBound(arrCopy, 1), _
                                        UBound(arrCopy, 2)).Value = arrCopy

My solution will copy all sheet content (headers included) in case of empty sheet to collect data and after that, data range starting from the second row.

Your full code as it should be in order to work (untested):

```<code>Sub mergeFiles()
'Define variables:
Dim numberOfFilesChosen, i As Integer
Dim tempFileDialog As FileDialog
Dim mainWorkbook, sourceWorkbook As Workbook
Dim sh As Worksheet, arrCopy As Variant, lastR As Long
Dim tempWorkSheet As Worksheet, lastRtemp As Long

Set mainWorkbook = Application.ActiveWorkbook
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)

'Allow the user to select multiple workbooks
tempFileDialog.AllowMultiSelect = True

numberOfFilesChosen = tempFileDialog.Show

'You can use here your sheet where the data will be collected. I used the last sheet for easy testing reason
Set sh = mainWorkbook.Sheets(mainWorkbook.Worksheets.count)

    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.count

        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)

        Set sourceWorkbook = ActiveWorkbook

        'Copy each worksheet to the end of the main workbook
        Set tempWorkSheet = sourceWorkbook.Worksheets(1)
            lastR = sh.Range("A" & sh.Rows.count).End(xlUp).row
            lastRtemp = tempWorkSheet.Range("A" & tempWorkSheet.Rows.count).End(xlUp).row
            If lastRtemp < 2 Then
                MsgBox "The workbook " & tempWorkSheet.Name & " contains less the two rows..."
            Else
                arrCopy = tempWorkSheet.Range(tempWorkSheet.Range("A" & IIf(lastR = 1, 1, 2)), _
                  tempWorkSheet.Range("A1").SpecialCells(xlLastCell)).Value
                sh.Range("A" & lastR + IIf(lastR = 1, 0, 1)).Resize(UBound(arrCopy, 1), _
                                        UBound(arrCopy, 2)).Value = arrCopy
            End If

        'Close the source workbook
        sourceWorkbook.Close
    Next i
End Sub
</code>```

Title: Merge Excel workbooks to one Worksheet

Body:
I am trying to merge 250 database excel workbooks into one continuous worksheet.

All of the workbooks have the same kind of data, with the same headers.

I have tried using this VBA code:

Sub mergeFiles()
    'Merges all files in a folder to a main file.

    'Define variables:
    Dim numberOfFilesChosen, i As Integer
    Dim tempFileDialog As fileDialog
    Dim mainWorkbook, sourceWorkbook As Workbook
    Dim tempWorkSheet As Worksheet

    Set mainWorkbook = Application.ActiveWorkbook
    Set tempFileDialog = Application.fileDialog(msoFileDialogFilePicker)

    'Allow the user to select multiple workbooks
    tempFileDialog.AllowMultiSelect = True

    numberOfFilesChosen = tempFileDialog.Show

    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.Count

        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)

        Set sourceWorkbook = ActiveWorkbook

        'Copy each worksheet to the end of the main workbook
        For Each tempWorkSheet In sourceWorkbook.Worksheets
            tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)
        Next tempWorkSheet

        'Close the source workbook
        sourceWorkbook.Close
    Next i

End Sub

The code works fine, but it creates a new sheet for every workbook, instead of copying the data to the bottom row of 1 sheet.

Body:
I prepared a very fast method of data moving (using arrays and working in memory), avoiding Copy and Paste.

Copy this new declarations at your declarations area:

Dim sh As Worksheet, arrCopy As Variant, lastR As Long

Copy this code line before the loop (For i = 1 To ...):

Set sh = mainWorkbook.Sheets(mainWorkbook.Worksheets.count) 'You can use here your sheet where the data will be collected. I used the last sheet for easy testing reason

Replace (in the loop For Each ...) the existing code (tempWorkSheet.Copy after:=mainWorkbook.Sheets(mainWorkbook.Worksheets.Count)) with the next one:

lastR = sh.Range("A" & sh.Rows.count).End(xlUp).row

arrCopy = tempWorkSheet.Range(tempWorkSheet.Range("A" & IIf(lastR = 1, 1, 2)), _
          tempWorkSheet.Range("A1").SpecialCells(xlLastCell)).Value
 sh.Range("A" & lastR + IIf(lastR = 1, 0, 1)).Resize(UBound(arrCopy, 1), _
                                        UBound(arrCopy, 2)).Value = arrCopy

My solution will copy all sheet content (headers included) in case of empty sheet to collect data and after that, data range starting from the second row.

Your full code as it should be in order to work (untested):

Sub mergeFiles()
'Define variables:
Dim numberOfFilesChosen, i As Integer
Dim tempFileDialog As FileDialog
Dim mainWorkbook, sourceWorkbook As Workbook
Dim sh As Worksheet, arrCopy As Variant, lastR As Long
Dim tempWorkSheet As Worksheet, lastRtemp As Long

Set mainWorkbook = Application.ActiveWorkbook
Set tempFileDialog = Application.FileDialog(msoFileDialogFilePicker)

'Allow the user to select multiple workbooks
tempFileDialog.AllowMultiSelect = True

numberOfFilesChosen = tempFileDialog.Show

'You can use here your sheet where the data will be collected. I used the last sheet for easy testing reason
Set sh = mainWorkbook.Sheets(mainWorkbook.Worksheets.count)

    'Loop through all selected workbooks
    For i = 1 To tempFileDialog.SelectedItems.count

        'Open each workbook
        Workbooks.Open tempFileDialog.SelectedItems(i)

        Set sourceWorkbook = ActiveWorkbook

        'Copy each worksheet to the end of the main workbook
        Set tempWorkSheet = sourceWorkbook.Worksheets(1)
            lastR = sh.Range("A" & sh.Rows.count).End(xlUp).row
            lastRtemp = tempWorkSheet.Range("A" & tempWorkSheet.Rows.count).End(xlUp).row
            If lastRtemp < 2 Then
                MsgBox "The workbook " & tempWorkSheet.Name & " contains less the two rows..."
            Else
                arrCopy = tempWorkSheet.Range(tempWorkSheet.Range("A" & IIf(lastR = 1, 1, 2)), _
                  tempWorkSheet.Range("A1").SpecialCells(xlLastCell)).Value
                sh.Range("A" & lastR + IIf(lastR = 1, 0, 1)).Resize(UBound(arrCopy, 1), _
                                        UBound(arrCopy, 2)).Value = arrCopy
            End If

        'Close the source workbook
        sourceWorkbook.Close
    Next i
End Sub