问:
Trigger a dialog box in background script
I have a chrome extension, where I periodically throw out an alert based on something.

The thing is that the default alert in Javascript is very ugly and I am trying to replace it with something more beautiful.

The problem is that currently the alert is triggered from the background script. Google doesn't allow us to include any external libraries in the background html.

Given this problem, how do I go about replacing the default alert with a more modern UI alert?

I was looking to replace the default alert with something like the SweetAlert.

My background.js currently looks like this:

```<code> // on some alarm trigger
 function showpopup() {

        console.log(" in show popuup");
        console.log(Date());
        alert("ugly alert");
}
</code>```

I also explored the option of injecting another js file from my background file.

```<code>function showpopup() {
        console.log(" in show popuup");
        console.log(Date());
        var s = document.createElement('script');
        // added "script.js" to web_accessible_resources in manifest.json
        s.src = chrome.extension.getURL('script.js');
        s.onload = function() {
            this.remove();
        };
        (document.head || document.documentElement).appendChild(s);
}
</code>```

My script.js currently just calls an alert

```<code>alert("ugly alert now in script.js");
</code>```

I am not able to figure out how to create my own dialog box in this javascript file script.js.

答:
The problem is where your alert will be shown?

In an browser/OS dialog window? That's what alert() and friends do; as you see yourself, it's ugly and inflexible. In addition, it's technically challenging: it's an old mechanism that stops execution of JS code until closed, which can lead to API malfunctioning; Firefox WebExtensions specifically don't support calling this from the background page.

In the background page? By definition, it's invisible. You can add DOM nodes with an alert there, but you will not see it. Your problem isn't loading a library, your problem is where to display results.

(invisible, so no picture here!)

In the currently open tab? Hijacking an arbitrary page to show your own UI is hard, prone to break, would require draconian permissions with user warnings at install, won't always work. Wouldn't recommend.

In a fresh window? Possible (see chrome.windows API), but hardly "modern UI" at all (at least you can hide the URL bar).

In a browser action popup? Still not possible to trigger it to open in Chrome, so that's out.

The de-facto standard for informing the user about such things is the chrome.notifications API. It offers limited customization, but that's the "modern" approach considering that your extension has no UI surfaces already open at alert time.

Body:
I have a chrome extension, where I periodically throw out an alert based on something.

The thing is that the default alert in Javascript is very ugly and I am trying to replace it with something more beautiful.

The problem is that currently the alert is triggered from the background script. Google doesn't allow us to include any external libraries in the background html.

Given this problem, how do I go about replacing the default alert with a more modern UI alert?

I was looking to replace the default alert with something like the SweetAlert.

My background.js currently looks like this:

 // on some alarm trigger
 function showpopup() {

        console.log(" in show popuup");
        console.log(Date());
        alert("ugly alert");
}

I also explored the option of injecting another js file from my background file.

function showpopup() {
        console.log(" in show popuup");
        console.log(Date());
        var s = document.createElement('script');
        // added "script.js" to web_accessible_resources in manifest.json
        s.src = chrome.extension.getURL('script.js');
        s.onload = function() {
            this.remove();
        };
        (document.head || document.documentElement).appendChild(s);
}

My script.js currently just calls an alert

alert("ugly alert now in script.js");

I am not able to figure out how to create my own dialog box in this javascript file script.js.


来源: stackexchange

问:
Check Specfic row with multiple rows in ORACLE
I want to select users list who is status is disabled for all application in username(ur_username table and that users should be active in Person Table(ur_person).

I tried with the following query :

```<code> select distinct E.PERSON_ID , E.DOMAIN_ID,e.first_name,e.last_name,e.type,E.username, E.SYSTEM_name  from
(SELECT  distinct p.person_id,p.domain_id,p.first_name,p.last_name,p.type,u.username, U.STATUS, U.SYSTEM_ID,s.system_name from ur_username u join
ur_username_person up on u.username_id=up.username_id
join ur_person p on up.person_id=p.person_id join ur_system s on u.system_id=s.system_id
 WHERE p.status='ACTIVE') E WHERE E.person_id IN
  ( select distinct P.PERSON_ID from ur_username u join  ur_username_person up on u.username_id=up.username_id
    join ur_person p on up.person_id=p.person_id
   where u.status='DISABLED')
</code>```

I need to get the person list who is status is Disabled in all system in username Table as below image:

But instead I am getting person who is disable in one system but active in some other systems also:

答:
You can get the person_ids using aggregation and having:

```<code>select p.person_id
from ur_username u join
     ur_username_person up
     on u.username_id = up.username_id join
     ur_person p join
     ur_system s
     on u.system_id = s.system_id
where p.status = 'ACTIVE'
group by p.person_id
having max(u.status) = min(u.status) and max(u.status) ='DISABLED';
</code>```

You specify that you want the persons, so this seems to answer your question.  You can easily enhance this query to return more columns.

ContentLicense: CC BY-SA 3.0

Body:
I want to select users list who is status is disabled for all application in username(ur_username table and that users should be active in Person Table(ur_person).

I tried with the following query :

 select distinct E.PERSON_ID , E.DOMAIN_ID,e.first_name,e.last_name,e.type,E.username, E.SYSTEM_name  from
(SELECT  distinct p.person_id,p.domain_id,p.first_name,p.last_name,p.type,u.username, U.STATUS, U.SYSTEM_ID,s.system_name from ur_username u join
ur_username_person up on u.username_id=up.username_id
join ur_person p on up.person_id=p.person_id join ur_system s on u.system_id=s.system_id
 WHERE p.status='ACTIVE') E WHERE E.person_id IN
  ( select distinct P.PERSON_ID from ur_username u join  ur_username_person up on u.username_id=up.username_id
    join ur_person p on up.person_id=p.person_id
   where u.status='DISABLED')

I need to get the person list who is status is Disabled in all system in username Table as below image:

But instead I am getting person who is disable in one system but active in some other systems also:

Body:
You can get the person_ids using aggregation and having:

select p.person_id
from ur_username u join
     ur_username_person up
     on u.username_id = up.username_id join
     ur_person p join
     ur_system s
     on u.system_id = s.system_id
where p.status = 'ACTIVE'
group by p.person_id
having max(u.status) = min(u.status) and max(u.status) ='DISABLED';

You specify that you want the persons, so this seems to answer your question.  You can easily enhance this query to return more columns.


答:
You can insert your code into the tab content via

JS: chrome.tabs.executeScript()

CSS: chrome.tabs.insertCSS()

The second possibility would be to use a content script (content.js). But then you would have to use messaging to communicate between background.js and content.js.

Title: Trigger a dialog box in background script


问:
Words in a list with consecutively repeated letters
Right now I have a list of for example

```<code>data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
</code>```

I want to remove the words with the repeated letters, in which I want to remove the words

```<code>'aa','aac','bbb','bcca','ffffff'
</code>```

Maybe import re?

答:
Thanks to this thread: Regex to determine if string is a single repeating character

Here is the re version, but I would stick to PM2 ring and Tameem's solutions if the task was as simple as this:

```<code>import re
data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
[i for i in data if not re.search(r'^(.)\1+$', i)]
</code>```

Output

```<code>['dog', 'cat', 'a', 'aac', 'bcca']
</code>```

And the other:

```<code>import re
data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
[i for i in data if not re.search(r'((\w)\2{1,})', i)]
</code>```

Output

```<code>['dog', 'cat', 'a']
</code>```

Body:
Right now I have a list of for example

data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']

I want to remove the words with the repeated letters, in which I want to remove the words

'aa','aac','bbb','bcca','ffffff'

Maybe import re?

Body:
Thanks to this thread: Regex to determine if string is a single repeating character

Here is the re version, but I would stick to PM2 ring and Tameem's solutions if the task was as simple as this:

import re
data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
[i for i in data if not re.search(r'^(.)\1+$', i)]

Output

['dog', 'cat', 'a', 'aac', 'bcca']

And the other:

import re
data = ['dog','cat','a','aa','aac','bbb','bcca','ffffff']
[i for i in data if not re.search(r'((\w)\2{1,})', i)]

Output

['dog', 'cat', 'a']


问:
If a date is today
```<code><?php
   $null=0;
   $sql = 'SELECT cl.id, cl.leaving_date, rn.id as rnid, rn.name as room_number
   FROM CLIENTS as cl
   JOIN room_number as rn ON cl.room_number_id=rn.id
   ORDER BY rn.name
   ';
   $strm = $DBcon ->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
   $strm -> execute(array(':id' => $null));
   $rows = $strm->fetchALL(PDO::FETCH_ASSOC);
   ?>
   <main>
     <?php
     $SQL = "SELECT name FROM cities";
     $strm = $DBcon->prepare($SQL);
     $strm->execute();
     $city = $strm->fetchAll();
     ?>
     <table>
       <tr>
         <th>Kambario numeris</th>
         <th>Atsilaisvins</th>
       </tr>
       <?php
       foreach ($rows as $row) {
         echo '<tr>
         <td>'.$row['room_number'].'</td>
         <td>'.$row['leaving_date'].'</td>
         </tr>';}
         ?>
</code>```

Database has 2 tables clients and room_number. Page shows the room number and client leaving date. How to check if a date is today then echo "room is free"?

答:
You could use a CASE for check if the date match with curdate()

```<code>SELECT cl.id, cl.leaving_date,
 case when date(cl.leaving_date)  = date(curdate() )
         then 'Room is free' else 'Room Occuped'
 END free_or_not,
      rn.id as rnid, rn.name as room_number
 FROM CLIENTS as cl
 JOIN room_number as rn ON cl.room_number_id=rn.id
 ORDER BY rn.name
</code>```

and show the correct echo

```<code>  foreach ($rows as $row) {
     echo '<tr>
     <td>'.$row['room_number'].'</td>
     <td>'.$row['free_or_not'].'</td>
     </tr>';}
     ?>
</code>```

Title: If a date is today

Body:
<?php
   $null=0;
   $sql = 'SELECT cl.id, cl.leaving_date, rn.id as rnid, rn.name as room_number
   FROM CLIENTS as cl
   JOIN room_number as rn ON cl.room_number_id=rn.id
   ORDER BY rn.name
   ';
   $strm = $DBcon ->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
   $strm -> execute(array(':id' => $null));
   $rows = $strm->fetchALL(PDO::FETCH_ASSOC);
   ?>

     <?php
     $SQL = "SELECT name FROM cities";
     $strm = $DBcon->prepare($SQL);
     $strm->execute();
     $city = $strm->fetchAll();
     ?>

         Kambario numeris
         Atsilaisvins

       <?php
       foreach ($rows as $row) {
         echo '

         '.$row['room_number'].'
         '.$row['leaving_date'].'

';}
         ?>

Database has 2 tables clients and room_number. Page shows the room number and client leaving date. How to check if a date is today then echo "room is free"?

Body:
You could use a CASE for check if the date match with curdate()

SELECT cl.id, cl.leaving_date,
 case when date(cl.leaving_date)  = date(curdate() )
         then 'Room is free' else 'Room Occuped'
 END free_or_not,
      rn.id as rnid, rn.name as room_number
 FROM CLIENTS as cl
 JOIN room_number as rn ON cl.room_number_id=rn.id
 ORDER BY rn.name

and show the correct echo

  foreach ($rows as $row) {
     echo '<tr>
     <td>'.$row['room_number'].'</td>
     <td>'.$row['free_or_not'].'</td>
     </tr>';}
     ?>


问:
I want to use characterAtIndex:(NSUInteger)index method of NSString class
I want to compare the value returned by characterAtIndex:(NSUInteger)index
of NSString class with a another NSString having one character stored in it any suggestion </p>

答:
On the top of my head, you can compare them directly using characterAtIndex on the other NSString as well.</p>

```<code>if([string characterAtIndex:index] == [stringWithOneChar characterAtIndex:0]){
   // Do something here...
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
On the top of my head, you can compare them directly using characterAtIndex on the other NSString as well.

if([string characterAtIndex:index] == [stringWithOneChar characterAtIndex:0]){
   // Do something here...
}


问:
ObjectUnsubscribedError when trying to prevent subscribing twice
I have a Service and a component that uses it:

PagesService

PagesListComponent

In the PagesService I have an array of Pages. I notify changes in the array via a BehaviorSubject which both of them are subscribed to.

The PagesService are provided at bootstrap, to have just one instance shared. That's because I need to keep the array, instead of downloading the pages everytime they are needed.

The code is the following:

pages.service.ts

```<code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/Rx';
import { Http, Response } from '@angular/http';

import { Page } from './../models/page';

@Injectable() export class PagesService {

    public pages$: BehaviorSubject<Page[]> = new BehaviorSubject<Page[]>([]);
    private pages: Page[] = [];

    constructor(private http: Http) { }

    getPagesListener() {
        return this.pages$;
    }
    getAll() {
        this.http.get('/mockups/pages.json').map((res: Response) => res.json()).subscribe(
            res => { this.resetPagesFromJson(res); },
            err => { console.log('Pages could not be fetched'); }
        );
    }

    private resetPagesFromJson(pagesArr: Array<any>) {
        // Parses de Array<any> and creates an Array<Page>
        this.pages$.next(this.pages);
    }
}
</code>```

pages_list.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { BehaviorSubject } from 'rxjs/Rx';

import { PagesService } from '../../shared/services/pages.service';
import { GoPage } from '../../shared/models/page';

@Component({
    moduleId: module.id,
    selector: 'go-pages-list',
    templateUrl: 'pages_list.component.html',
    styleUrls: ['pages_list.component.css']
})
export class PagesListComponent implements OnInit {
    pages$: BehaviorSubject<GoPage[]>;
    pages: GoPage[];
    constructor(private pagesService: PagesService, private router: Router) { }

    ngOnInit() {
        this.pages$ = this.pagesService.getPagesListener();
        this.pages$.subscribe((pages) => { this.pages = pages; console.log(pages) });
        this.pagesService.getAll();
    }
    ngOnDestroy() {
        this.pages$.unsubscribe();
    }
}
</code>```

This works fine the first time, both the subscription onInit and de unsubscription onDestroy. But when I return to the list and try to subscribe again (to fetch the current value of pages[] and listen for future changes), it fires the error EXCEPTION: ObjectUnsubscribedError.

If I don't unsubscribe, everytime I enter to the list, a new subscription is stacked, and all of them are fired when a next() is received.

答:
.subscribe() returns a Subscription

You should use this to unsubscribe

e.g.
Parent has a reloadSubject: Subject;

child1 -> subscribes

child2 -> subscribes

child1 - "WORKS" -> unsubscribe's his subscription

```<code>ngOnInit{
  sub: Subscription = parent.subscribe();
}
onDestroy{
  this.sub.unsubscribe();
}
</code>```

child2 - "DOES NOT WORK" -> unsubscribe's the whole parent

```<code>ngOnInit{
  parent.subscribe();
}

onDestroy{
  parent.unsubscribe();
}
</code>```

If you call unsubscribe on the parent both children are gone.

If you unsubscribe the Subscription that you get from the .subscribe()
then only one child is unsubscribed.

Please correct me if I am wrong!

Body:
I have a Service and a component that uses it:

PagesService

PagesListComponent

In the PagesService I have an array of Pages. I notify changes in the array via a BehaviorSubject which both of them are subscribed to.

The PagesService are provided at bootstrap, to have just one instance shared. That's because I need to keep the array, instead of downloading the pages everytime they are needed.

The code is the following:

pages.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/Rx';
import { Http, Response } from '@angular/http';

import { Page } from './../models/page';

@Injectable() export class PagesService {

    public pages$: BehaviorSubject<Page[]> = new BehaviorSubject<Page[]>([]);
    private pages: Page[] = [];

    constructor(private http: Http) { }

    getPagesListener() {
        return this.pages$;
    }
    getAll() {
        this.http.get('/mockups/pages.json').map((res: Response) => res.json()).subscribe(
            res => { this.resetPagesFromJson(res); },
            err => { console.log('Pages could not be fetched'); }
        );
    }

    private resetPagesFromJson(pagesArr: Array<any>) {
        // Parses de Array<any> and creates an Array<Page>
        this.pages$.next(this.pages);
    }
}

pages_list.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router-deprecated';
import { BehaviorSubject } from 'rxjs/Rx';

import { PagesService } from '../../shared/services/pages.service';
import { GoPage } from '../../shared/models/page';

@Component({
    moduleId: module.id,
    selector: 'go-pages-list',
    templateUrl: 'pages_list.component.html',
    styleUrls: ['pages_list.component.css']
})
export class PagesListComponent implements OnInit {
    pages$: BehaviorSubject<GoPage[]>;
    pages: GoPage[];
    constructor(private pagesService: PagesService, private router: Router) { }

    ngOnInit() {
        this.pages$ = this.pagesService.getPagesListener();
        this.pages$.subscribe((pages) => { this.pages = pages; console.log(pages) });
        this.pagesService.getAll();
    }
    ngOnDestroy() {
        this.pages$.unsubscribe();
    }
}

This works fine the first time, both the subscription onInit and de unsubscription onDestroy. But when I return to the list and try to subscribe again (to fetch the current value of pages[] and listen for future changes), it fires the error EXCEPTION: ObjectUnsubscribedError.

If I don't unsubscribe, everytime I enter to the list, a new subscription is stacked, and all of them are fired when a next() is received.

Body:
.subscribe() returns a Subscription

You should use this to unsubscribe

e.g.
Parent has a reloadSubject: Subject;

child1 -> subscribes

child2 -> subscribes

child1 - "WORKS" -> unsubscribe's his subscription

ngOnInit{
  sub: Subscription = parent.subscribe();
}
onDestroy{
  this.sub.unsubscribe();
}

child2 - "DOES NOT WORK" -> unsubscribe's the whole parent

ngOnInit{
  parent.subscribe();
}

onDestroy{
  parent.unsubscribe();
}

If you call unsubscribe on the parent both children are gone.

If you unsubscribe the Subscription that you get from the .subscribe()
then only one child is unsubscribed.

Please correct me if I am wrong!


问:
Foundation 6 catch drilldown click event
I'm trying to catch the event of Foundation's 6 Drilldown.

I used a simple on() method with jQuery which doesn't seem to work.

```<code>$(document).foundation();

$("body").on("click",".is-drilldown-submenu-parent",function(){
  alert("!");
})
</code>```

Here's a Codepen: https://codepen.io/Nirtz89/pen/jGExPd

Any ideas as to why it happens?

答:
The method is already catched by foundation so you coulf try overriding it inserting a off() before the on() like

```<code>$(document).off().on("click",".is-drilldown-submenu-parent",function(){
  alert("!");
})
</code>```

Body:
I'm trying to catch the event of Foundation's 6 Drilldown.

I used a simple on() method with jQuery which doesn't seem to work.

$(document).foundation();

$("body").on("click",".is-drilldown-submenu-parent",function(){
  alert("!");
})

Here's a Codepen: https://codepen.io/Nirtz89/pen/jGExPd

Any ideas as to why it happens?

Body:
The method is already catched by foundation so you coulf try overriding it inserting a off() before the on() like

$(document).off().on("click",".is-drilldown-submenu-parent",function(){
  alert("!");
})


问:
What is the search scope of CDI in case of injectable bean lookup?
I have a multi module maven project (a Java EE app with ear, persistence, web, ejb, api, bl and other modules), where I'd like to use Weld CDI.

When I try to inject a bean, where will Weld search for injectable beans? Will Weld search in all the modules, where a beans.xml is placed to WEB-INF or META-INF regardless from their dependencies (or dependencies matter somehow?), or will Weld be able to inject a bean from an other deployment? I tried to find a document, which describes the mechanism and boundaries of bean lookup, but I haven't found anything yet.

答: What you're describing is part of the overall EE spec, not the CDI spec.  but yes, in general the contents of your EAR will be discovered as distinct applications (per the EE spec).  This means that you may not be able to access individual beans across JARs.  It is highly recommended to use WAR deployment with CDI.</p>


问:
Angular 2 unit test case using Function not provider
I am using a function in my actual service but I want to know how can i inject that function in unit test case. Below isSameDay is a function not provider. How can i inject it into test case as this function is working fine in actual service.

```<code>import { LoggerService, isSameDay } from '../../../shared';

describe('NavBaseComponent', () => {
  let component: NavBaseComponent;
  let fixture: ComponentFixture<NavBaseComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [NavBaseComponent],
      providers: [
        LoggerService
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NavBaseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

Code for isSameDay function

```<code>export function isSameDay(d1: Date, d2: Date): boolean {
    return !!d1 && !!d2 &&
        d1.getDate() === d2.getDate() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getFullYear() === d2.getFullYear();
};
</code>```

答:
You don't need to inject it anywhere, you can test it as is.

```<code>import { LoggerService, isSameDay } from '../../../shared';

describe..

  it('should test isSameDay', ()=>{
      expect(isSameDay(new Date(), new Date())).toEqual(true);
  })

..
</code>```

Here's a plunker example: http://plnkr.co/edit/TyTyaJvDD28AqPH2yDKa?p=preview

Body:
I am using a function in my actual service but I want to know how can i inject that function in unit test case. Below isSameDay is a function not provider. How can i inject it into test case as this function is working fine in actual service.

import { LoggerService, isSameDay } from '../../../shared';

describe('NavBaseComponent', () => {
  let component: NavBaseComponent;
  let fixture: ComponentFixture<NavBaseComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [NavBaseComponent],
      providers: [
        LoggerService
      ]
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(NavBaseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});

Code for isSameDay function

export function isSameDay(d1: Date, d2: Date): boolean {
    return !!d1 && !!d2 &&
        d1.getDate() === d2.getDate() &&
        d1.getMonth() === d2.getMonth() &&
        d1.getFullYear() === d2.getFullYear();
};

Body:
You don't need to inject it anywhere, you can test it as is.

import { LoggerService, isSameDay } from '../../../shared';

describe..

  it('should test isSameDay', ()=>{
      expect(isSameDay(new Date(), new Date())).toEqual(true);
  })

..

Here's a plunker example: http://plnkr.co/edit/TyTyaJvDD28AqPH2yDKa?p=preview


问:
How does back_inserter work?
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:

```<code>template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;

    explicit back_insert_iterator( C& __x ) :container( &__x ) {
    }

    back_insert_iterator<C>& operator=( const typename C::value_type& val ) {
        container->push_back( val );
        return *this;
    }

    back_insert_iterator<C>& operator*() {
        return *this;
    }

    back_insert_iterator<C>& operator++() {
        return *this;
    }

    back_insert_iterator<C>& operator++( int ) {
        return *this;
    }
};
</code>```

I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?

Thanks,

Chan

答:
Your guess is correct and there is nothing more than that. It's all about OutputIterator concept. back_insert_iterator is an OutputIterator, that means that it should work with any algorithm that expects OutputIterators. OutputIterator must have these operators defined so algorithms like this could work:</p>

```<code>template<class InputIterator, class OutputIterator>
OutputIterator copy(
    InputIterator first, InputIterator last, OutputIterator result)
{
    while(first != last)
        // uses operators =, * and post ++ of OutputIterator.
        *result++ = *first++;
    return result;
}
</code>```

Title: How does back_inserter work?

Body:
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:

template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;

    explicit back_insert_iterator( C& __x ) :container( &__x ) {
    }

    back_insert_iterator<C>& operator=( const typename C::value_type& val ) {
        container->push_back( val );
        return *this;
    }

    back_insert_iterator<C>& operator*() {
        return *this;
    }

    back_insert_iterator<C>& operator++() {
        return *this;
    }

    back_insert_iterator<C>& operator++( int ) {
        return *this;
    }
};

I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?

Thanks,

Chan

Body:
Your guess is correct and there is nothing more than that. It's all about OutputIterator concept. back_insert_iterator is an OutputIterator, that means that it should work with any algorithm that expects OutputIterators. OutputIterator must have these operators defined so algorithms like this could work:

template<class InputIterator, class OutputIterator>
OutputIterator copy(
    InputIterator first, InputIterator last, OutputIterator result)
{
    while(first != last)
        // uses operators =, * and post ++ of OutputIterator.
        *result++ = *first++;
    return result;
}


问:
Excel Date to Text Conversion Error
My Excel does not convert a simple date to a text. Instead, it will only convert the month. I tried different date formats und small/ capital letters to define the date format, but the result does not change.

I tried to sketch the problem in the following table:

```<code>             |    Date    | Date as Text
Cell Formula | 03.03.2009 | =TEXT(B7;"DD-MM-YYYY")
Cell Output  | 03.03.2009 | DD-03-YYYY
</code>```

答: Go On Format cells and search for standard type letter that your excel accept the Day and Years

Title: Excel Date to Text Conversion Error

Body:
My Excel does not convert a simple date to a text. Instead, it will only convert the month. I tried different date formats und small/ capital letters to define the date format, but the result does not change.

I tried to sketch the problem in the following table:

             |    Date    | Date as Text
Cell Formula | 03.03.2009 | =TEXT(B7;"DD-MM-YYYY")
Cell Output  | 03.03.2009 | DD-03-YYYY


问:
Daily bible verse from ourmanna.com API is not always displaying
I have HTML and JS code that should display the daily verse from ourmanna.com API. However, the verse is not always displaying. I was wondering if it's a problem on their side or my side?

here is the html code:

Daily Verse

Loading...

```

Thanks very much

答:
If you look at the script returned by ourmanna, you see the problem is a not escaped quote in the mannaverse:

```<code>var mannaverse='"'If you can'?" said Jesus. "Everything is possible for him who believes."';
</code>```

Correct would be

```<code>var mannaverse='"\'If you can\'?" said Jesus. "Everything is possible for him who believes."';
</code>```

So you cannot do anything about it, it is a ourmanna-problem.

ContentLicense: CC BY-SA 4.0

Body:
I have HTML and JS code that should display the daily verse from ourmanna.com API. However, the verse is not always displaying. I was wondering if it's a problem on their side or my side?

here is the html code:

Daily Verse

Loading...

Thanks very much

Body:
If you look at the script returned by ourmanna, you see the problem is a not escaped quote in the mannaverse:

var mannaverse='"'If you can'?" said Jesus. "Everything is possible for him who believes."';

Correct would be

var mannaverse='"\'If you can\'?" said Jesus. "Everything is possible for him who believes."';

So you cannot do anything about it, it is a ourmanna-problem.


问:
Maximum path cost in matrix
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down  movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0

Constraints

1 <= nxm <= 4x10^6

INPUT

```<code>4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20
</code>```

OUTPUT

```<code>37
</code>```

Explanation is given in the image
Explanation of Output

答:
Since moving up is not allowed, paths always look like a set of horizontal intervals that share at least 1 position (for the down move). Answers can be characterized as, say

```<code>struct Answer {
   int layer[N][2]; // layer[i][0] and [i][1] represent interval start&end
                    // with 0 <= layer[i][0] <= layer[i][1] < M
                    // layer[0][0] = 0, layer[N][1] = M-1
                    // and non-empty intersection of layers i and i+1
};
</code>```

An alternative encoding is to note only layer widths and offsets to each other; but you would still have to make sure that the last layer includes the exit cell.

Assuming that you have a maxLayer routine that finds the highest-scoring interval in each layer (const O(M) per layer), and that all such such layers overlap, this would yield an O(N+M) optimal answer. However, it may be necessary to expand intervals to ensure that overlap occurs; and there may be multiple highest-scoring intervals in a given layer. At this point I would model the problem as a directed graph:

each layer has one node per score-maximizing horizontal continuous interval.

nodes from one layer are connected to nodes in the next layer according to the cost of expanding both intervals to achieve at least 1 overlap. If they already overlap, the cost is 0. Edge costs will always be zero or negative (otherwise, either source or target intervals could have scored higher by growing bigger). Add the (expanded) source-node interval value to the connection cost to get an "edge weight".

You can then run Dijkstra on this graph (negate edge weights so that the "longest path" is returned) to find the optimal path. Even better, since all paths pass once and only once through each layer, you only need to keep track of the best route to each node, and only need to build nodes and edges for the layer you are working on.

Implementation details ahead

to calculate maxLayer in O(M), use Kadane's Algorithm, modified to return all maximal intervals instead of only the first. Where the linked algorithm discards an interval and starts anew, you would instead keep a copy of that contender to use later.

given the sample input, the maximal intervals would look like this:

```<code>                     [0]
 1  2  3   -1   -2   [1 2 3]
-5 -8 -1    2 -150 =>        [2]
 1  2  3 -250  100   [1 2 3]     [100]
 1  1  1    1   20   [1 1 1   1    20]
                                   [0]
</code>```

given those intervals, they would yield the following graph:

```<code>    (0)
      |  =>0
    (+6)
       \ -1=>5
        \
        (+2)
    =>7/    \ -150=>-143
      /      \
   (+7)      (+100)
 =>12 \      / =>-43
       \    /
        (+24)
          |  =>37
         (0)
</code>```

when two edges incide on a single node (row 1 1 1 1 20), carry forward only the highest incoming value.

Title: Maximum path cost in matrix

Body:
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down  movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0

Constraints

1 <= nxm <= 4x10^6

INPUT

4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20

OUTPUT

37

Explanation is given in the image
Explanation of Output

Body:
Since moving up is not allowed, paths always look like a set of horizontal intervals that share at least 1 position (for the down move). Answers can be characterized as, say

struct Answer {
   int layer[N][2]; // layer[i][0] and [i][1] represent interval start&end
                    // with 0 <= layer[i][0] <= layer[i][1] < M
                    // layer[0][0] = 0, layer[N][1] = M-1
                    // and non-empty intersection of layers i and i+1
};

An alternative encoding is to note only layer widths and offsets to each other; but you would still have to make sure that the last layer includes the exit cell.

Assuming that you have a maxLayer routine that finds the highest-scoring interval in each layer (const O(M) per layer), and that all such such layers overlap, this would yield an O(N+M) optimal answer. However, it may be necessary to expand intervals to ensure that overlap occurs; and there may be multiple highest-scoring intervals in a given layer. At this point I would model the problem as a directed graph:

each layer has one node per score-maximizing horizontal continuous interval.

nodes from one layer are connected to nodes in the next layer according to the cost of expanding both intervals to achieve at least 1 overlap. If they already overlap, the cost is 0. Edge costs will always be zero or negative (otherwise, either source or target intervals could have scored higher by growing bigger). Add the (expanded) source-node interval value to the connection cost to get an "edge weight".

You can then run Dijkstra on this graph (negate edge weights so that the "longest path" is returned) to find the optimal path. Even better, since all paths pass once and only once through each layer, you only need to keep track of the best route to each node, and only need to build nodes and edges for the layer you are working on.

Implementation details ahead

to calculate maxLayer in O(M), use Kadane's Algorithm, modified to return all maximal intervals instead of only the first. Where the linked algorithm discards an interval and starts anew, you would instead keep a copy of that contender to use later.

given the sample input, the maximal intervals would look like this:

                     [0]
 1  2  3   -1   -2   [1 2 3]
-5 -8 -1    2 -150 =>        [2]
 1  2  3 -250  100   [1 2 3]     [100]
 1  1  1    1   20   [1 1 1   1    20]
                                   [0]

given those intervals, they would yield the following graph:

    (0)
      |  =>0
    (+6)
       \ -1=>5
        \
        (+2)
    =>7/    \ -150=>-143
      /      \
   (+7)      (+100)
 =>12 \      / =>-43
       \    /
        (+24)
          |  =>37
         (0)

when two edges incide on a single node (row 1 1 1 1 20), carry forward only the highest incoming value.


问:
How can one flush input stream in C?
I am not able to flush stdin here, is there a way to flush it? If not then how to make getchar() to take a character as input from user, instead of a "\n" left by scanf() in the input buffer??

```<code>#include "stdio.h"
#include "stdlib.h"

int main(int argc,char*argv[]) {
    FILE *fp;
    char another='y';
    struct emp {
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    if(argc!=2) {
        printf("please write 1 target file name\n");
    }
    fp=fopen(argv[1],"wb");
    if(fp==NULL) {
        puts("cannot open file");
        exit(1);
    }
    while(another=='y') {
        printf("\nEnter name,age and basic salary");
        scanf("%s %d %f",e.name,&e.age,&e.bs);
        fwrite(&e,sizeof(e),1,fp);

        printf("Add another record (Y/N)");
        fflush(stdin);
        another=getchar();
    }
    fclose(fp);
    return 0;
}
</code>```

EDIT: updated code, still not working properly

```<code>#include "stdio.h"
#include "stdlib.h"

int main(int argc,char*argv[]) {
    FILE *fp;
    char another='y';
    struct emp {
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    unsigned int const BUF_SIZE = 1024;
    char buf[BUF_SIZE];

    if(argc!=2) {
        printf("please write 1 target file name\n");
    }
    fp=fopen(argv[1],"wb");
    if(fp==NULL) {
        puts("cannot open file");
        exit(1);
    }
    while(another=='y') {
        printf("\nEnter name,age and basic salary : ");
        fgets(buf, BUF_SIZE, stdin);
        sscanf(buf, "%s %d %f", e.name, &e.age, &e.bs);
        fwrite(&e,sizeof(e),1,fp);
        printf("Add another record (Y/N)");
        another=getchar();
    }
    fclose(fp);
    return 0;
}
</code>```

Output:

```<code>dev@dev-laptop:~/Documents/c++_prac/google_int_prac$ ./a.out emp.dat

Enter name,age and basic salary : deovrat 45 23
Add another record (Y/N)y

Enter name,age and basic salary : Add another record (Y/N)y

Enter name,age and basic salary : Add another record (Y/N)
</code>```

答:
If you are doing this under windows, you can use winapi to flush input buffer before your getch().

```<code>#include <windows.h>
hStdin = GetStdHandle(STD_INPUT_HANDLE);
FlushConsoleInputBuffer(hStdin);
</code>```

-or-

```<code>#include <windows.h>
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));
</code>```

Title: How can one flush input stream in C?

Body:
I am not able to flush stdin here, is there a way to flush it? If not then how to make getchar() to take a character as input from user, instead of a "\n" left by scanf() in the input buffer??

#include "stdio.h"
#include "stdlib.h"

int main(int argc,char*argv[]) {
    FILE *fp;
    char another='y';
    struct emp {
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    if(argc!=2) {
        printf("please write 1 target file name\n");
    }
    fp=fopen(argv[1],"wb");
    if(fp==NULL) {
        puts("cannot open file");
        exit(1);
    }
    while(another=='y') {
        printf("\nEnter name,age and basic salary");
        scanf("%s %d %f",e.name,&e.age,&e.bs);
        fwrite(&e,sizeof(e),1,fp);

        printf("Add another record (Y/N)");
        fflush(stdin);
        another=getchar();
    }
    fclose(fp);
    return 0;
}

EDIT: updated code, still not working properly

#include "stdio.h"
#include "stdlib.h"

int main(int argc,char*argv[]) {
    FILE *fp;
    char another='y';
    struct emp {
        char name[40];
        int age;
        float bs;
    };
    struct emp e;
    unsigned int const BUF_SIZE = 1024;
    char buf[BUF_SIZE];

    if(argc!=2) {
        printf("please write 1 target file name\n");
    }
    fp=fopen(argv[1],"wb");
    if(fp==NULL) {
        puts("cannot open file");
        exit(1);
    }
    while(another=='y') {
        printf("\nEnter name,age and basic salary : ");
        fgets(buf, BUF_SIZE, stdin);
        sscanf(buf, "%s %d %f", e.name, &e.age, &e.bs);
        fwrite(&e,sizeof(e),1,fp);
        printf("Add another record (Y/N)");
        another=getchar();
    }
    fclose(fp);
    return 0;
}

Output:

dev@dev-laptop:~/Documents/c++_prac/google_int_prac$ ./a.out emp.dat

Enter name,age and basic salary : deovrat 45 23
Add another record (Y/N)y

Enter name,age and basic salary : Add another record (Y/N)y

Enter name,age and basic salary : Add another record (Y/N)

Body:
If you are doing this under windows, you can use winapi to flush input buffer before your getch().

#include <windows.h>
hStdin = GetStdHandle(STD_INPUT_HANDLE);
FlushConsoleInputBuffer(hStdin);

-or-

#include <windows.h>
FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));


问:
Add 0 or 1 in a df depending on conditions from another df
I have a dataframe df1 with:

```<code>file_name  loc
rep1   chr1:62161618:62162663:-
rep2   chr1:62161618:62162669:-
...
</code>```

And I generate an empty matrix (df2) with file_name as rows and loc as columns. I want to add "1" value in every position that is present in df1. As an example:

```<code>     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           1                            0
rep2           0                            1
...
</code>```

Any suggestions?
Thanks!

答:
A solution using dplyr and tidyr.

```<code>library(dplyr)
library(tidyr)

dt2 <- dt %>%
  mutate(condition = 1) %>%
  spread(loc, condition, fill = 0)
dt2
#   file_name chr1:62161618:62162663:- chr1:62161618:62162669:-
# 1      rep1                        1                        0
# 2      rep2                        0                        1
</code>```

DATA

```<code>dt <- read.table(text = "file_name  loc
rep1   'chr1:62161618:62162663:-'
                 rep2   'chr1:62161618:62162669:-'",
                 header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
I have a dataframe df1 with:

file_name  loc
rep1   chr1:62161618:62162663:-
rep2   chr1:62161618:62162669:-
...

And I generate an empty matrix (df2) with file_name as rows and loc as columns. I want to add "1" value in every position that is present in df1. As an example:

     chr1:62161618:62162663:-    chr1:62161618:62162669:-...
rep1           1                            0
rep2           0                            1
...

Any suggestions?
Thanks!

Body:
A solution using dplyr and tidyr.

library(dplyr)
library(tidyr)

dt2 <- dt %>%
  mutate(condition = 1) %>%
  spread(loc, condition, fill = 0)
dt2
#   file_name chr1:62161618:62162663:- chr1:62161618:62162669:-
# 1      rep1                        1                        0
# 2      rep2                        0                        1

DATA

dt <- read.table(text = "file_name  loc
rep1   'chr1:62161618:62162663:-'
                 rep2   'chr1:62161618:62162669:-'",
                 header = TRUE, stringsAsFactors = FALSE)


问:
Exposing resources from jar files in web applications (Tomcat7)
Some time ago I read an article what is expected to be in Servlet API 3.0. I remember I read that you can save some .jsp files in a /WEB-INF/lib/somelib.jar/META-INF/web/.jsp and this resources will be exposed to the context root of the web application.

I have just installed Tomcat7 to give it a try, but I found no documentation that I can put some web-resources in jar-files.

Does this feature exists in servlet api 3.0?

Does this feature exists in tomcat 7.0?

Is there another way to have jsp-files in /lib/*.jar files?

答:
There is a feature in servlet 3.0 that allows you to package resources (images, jsp, etc.) in a JAR file. What you do is in your jar file, you create META-INF/resources and dump anything you want in there including directories for structuring your resources. What happens is that META-INF/resources will be mapped to the docroot of your web application.

When there is a clash of resource between your app and the JAR file, your apps resource will be returned. See this

Tomcat 7 supports Servlet 3 so it should support this feature


问:
Capture output of a shell script inside a docker container to a file using docker sdk for python)
I have a shell script inside my docker container called test.sh. I would like to pipe the output of this script to a file. I can do this using docker exec command or by logging into the shell (using docker run -it) and running ./test.sh > test.txt. However, I would like to know how the same result can be achieved using the docker sdk for python. This is my code so far:

```<code>import docker

client = docker.APIClient(base_url='unix://var/run/docker.sock')

container= client.create_container(
'ubuntu:16.04', '/bin/bash', stdin_open=True, tty=True, working_dir='/home/psr', \
volumes=['/home/psr/data'], \
host_config=client.create_host_config(binds={
    '/home/xxxx/data_generator/data/': {
        'bind': '/home/psr/data',
        'mode': 'rw',
    },

})
)

client.start(container=container.get('Id'))
cmds= './test.sh > test.txt'
exe=client.exec_create(container=container.get('Id'), cmd= cmds,
stdout=True)
exe_start=client.exec_start(exec_id=exe, stream=True)

for val in exe_start:
    print (val)
</code>```

I am using the Low-Level API of the docker sdk. In case you know how to achieve the same result as above using the high level API, please let me know.

答:
In case anyone else had the same problem, here is how I solved it. Please let me know in case you have a better solution.</p>

```<code>import docker

client = docker.APIClient(base_url='unix://var/run/docker.sock')

container= client.create_container(
'ubuntu:16.04', '/bin/bash', stdin_open=True, tty=True,
working_dir='/home/psr', \
 volumes=['/home/psr/data'], \
 host_config=client.create_host_config(binds={
 '/home/xxxx/data_generator/data/': {
    'bind': '/home/psr/data',
    'mode': 'rw',
},

})
)

client.start(container=container.get('Id'))
cmds= './test.sh'
exe=client.exec_create(container=container.get('Id'), cmd=cmds,
stdout=True)
exe_start=client.exec_start(exec_id=exe, stream=True)

with open('path_to_host_directory/test.txt', 'wb') as f: # wb: For Binary Output
    for val in exe_start:
        f.write(val)
</code>```

Body:
I have a shell script inside my docker container called test.sh. I would like to pipe the output of this script to a file. I can do this using docker exec command or by logging into the shell (using docker run -it) and running ./test.sh > test.txt. However, I would like to know how the same result can be achieved using the docker sdk for python. This is my code so far:

import docker

client = docker.APIClient(base_url='unix://var/run/docker.sock')

container= client.create_container(
'ubuntu:16.04', '/bin/bash', stdin_open=True, tty=True, working_dir='/home/psr', \
volumes=['/home/psr/data'], \
host_config=client.create_host_config(binds={
    '/home/xxxx/data_generator/data/': {
        'bind': '/home/psr/data',
        'mode': 'rw',
    },

})
)

client.start(container=container.get('Id'))
cmds= './test.sh > test.txt'
exe=client.exec_create(container=container.get('Id'), cmd= cmds,
stdout=True)
exe_start=client.exec_start(exec_id=exe, stream=True)

for val in exe_start:
    print (val)

I am using the Low-Level API of the docker sdk. In case you know how to achieve the same result as above using the high level API, please let me know.

Body:
In case anyone else had the same problem, here is how I solved it. Please let me know in case you have a better solution.

import docker

client = docker.APIClient(base_url='unix://var/run/docker.sock')

container= client.create_container(
'ubuntu:16.04', '/bin/bash', stdin_open=True, tty=True,
working_dir='/home/psr', \
 volumes=['/home/psr/data'], \
 host_config=client.create_host_config(binds={
 '/home/xxxx/data_generator/data/': {
    'bind': '/home/psr/data',
    'mode': 'rw',
},

})
)

client.start(container=container.get('Id'))
cmds= './test.sh'
exe=client.exec_create(container=container.get('Id'), cmd=cmds,
stdout=True)
exe_start=client.exec_start(exec_id=exe, stream=True)

with open('path_to_host_directory/test.txt', 'wb') as f: # wb: For Binary Output
    for val in exe_start:
        f.write(val)


问:
Firebase cocoa pod installation show error lGoogleToolboxForMac missing
I have tried to add firebase sdk using pods, but when I run the project I am getting the error framework not found. What can I do to solve this issue?

Error : Library not found for -lGoogleToolboxForMac
Also  pods -> products libGoogleToolboxForMac.a is showing red

答:
pod ‘Firebase/Core’
pod ‘Firebase/Messaging’
pod ‘GoogleSignIn’

I was getting the same error but after adding above pods I am not getting it.

and also check if your firebase.plist is correctly put.


问:
Many to Many on Laravel migration
I have 3 tables to connect each other. Tables name's roles, role_user, and users. I want to make migration on laravel and adding some constraint. and here's what in my role tables migration:

```<code>    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('description');
        $table->timestamps();
    });
</code>```

and here's my Users table migration:

```<code>Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->boolean('active')->default(0);
    $table->softDeletes();
    $table->rememberToken();
    $table->timestamps();
});
</code>```

and here's my role_user table migration:

```<code>    Schema::create('role_user', function (Blueprint $table) {
        $table->integer('role_id')->unsigned();
        $table->integer('user_id')->unsigned();

        $table->unique(['role_id', 'user_id']);
        $table->foreign('role_id')->references('id')->on('roles')
            ->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('user_id')->references('id')->on('users')
            ->onDelete('cascade')->onUpdate('cascade');
    });
</code>```

in my Migration order i put roles table on top of users already but i got this kind of errors:

```<code>  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `role_user` add constraint `role_user_role_id_foreign` foreign key (`role_id
  `) references `roles` (`id`) on delete cascade on update cascade)

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
</code>```

答:
I delete all my table and left just 4 tables :

```<code>create_user_table,
create_password_reset,
create_roles_table,
create_role_user
</code>```

and everything works fine.

Till now I don't understand what makes these errors although I already put the same orders.

Title: Many to Many on Laravel migration

Body:
I have 3 tables to connect each other. Tables name's roles, role_user, and users. I want to make migration on laravel and adding some constraint. and here's what in my role tables migration:

    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('description');
        $table->timestamps();
    });

and here's my Users table migration:

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('username')->unique();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->boolean('active')->default(0);
    $table->softDeletes();
    $table->rememberToken();
    $table->timestamps();
});

and here's my role_user table migration:

    Schema::create('role_user', function (Blueprint $table) {
        $table->integer('role_id')->unsigned();
        $table->integer('user_id')->unsigned();

        $table->unique(['role_id', 'user_id']);
        $table->foreign('role_id')->references('id')->on('roles')
            ->onDelete('cascade')->onUpdate('cascade');
        $table->foreign('user_id')->references('id')->on('users')
            ->onDelete('cascade')->onUpdate('cascade');
    });

in my Migration order i put roles table on top of users already but i got this kind of errors:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `role_user` add constraint `role_user_role_id_foreign` foreign key (`role_id
  `) references `roles` (`id`) on delete cascade on update cascade)

  [PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

Body:
I delete all my table and left just 4 tables :

create_user_table,
create_password_reset,
create_roles_table,
create_role_user

and everything works fine.

Till now I don't understand what makes these errors although I already put the same orders.


问:
Yii2- How to align text on left and right side php
I want to align text on both the right and the left side. For solution I have looked into the text on left and right side of element. But it didn't worked for me.

What I have done?

```<code><section class="content">

<div>
    <div class="div1" style="text-align:left; float: left;">
        Date:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>
        </span>

    </div>
    <div class="div2" style="text-align:right; float: right;">
        Reciept#:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>
        </span>

    </div>

</div>

</section>
</code>```

Output

As mentioned I already have checked for the solution.

Any help would be highly appreciated.

答:
Apply width and it will work:

        Date:

            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>

        Reciept#:

            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>

```

Body:
I want to align text on both the right and the left side. For solution I have looked into the text on left and right side of element. But it didn't worked for me.

What I have done?

        Date:

            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>

        Reciept#:

            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>

Output

As mentioned I already have checked for the solution.

Any help would be highly appreciated.

Body:
Apply width and it will work:

<section class="content">
<div>
    <div class="div1" style="text-align:left; float:left; width:50%;">
        Date:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black;">
            <?php $model=$dataProvider->getModels()[0]; print_r($model['Date'])?>
        </span>

    </div>
    <div class="div2" style="text-align:right; float:right; width:50%;">
        Reciept#:
        <span style="padding-bottom: 10px; border-bottom: 1px solid black">
            OGP-<?php $model=$dataProvider->getModels()[0]; print_r($model['OGP_Serial_No'])?>
        </span>

    </div>

</div>
</section>


问:
Is it possible to use Selenium Webdriver to stimulate several users hitting a site?
I have a crucial question please. Is it possible to use selenium webdriver to stimulate like 50 users hitting on a site at the same time? If not any recommendations on what to use for this test?

Thanks!

答: Selenium Webdriver is not recommended, but is able to do it. I'd suggest JMeter to do something like this. It has a simple interface and is relatively easy to use after a couple of YouTube tutorials.</p>


问:
Load object from table with id as foreign key
i have define users with UserRole type Role as foreing key of another table. Entiti framework auto transformed name UserRole to UserRoleId with type integer (Id). Its ok. But i have UserRoleId = 2 in table User table preview
and when i trying get user by Id:

```<code>var user = await _userManager.FindByIdAsync(id);
</code>```

so parameter UserRole is null user preview from debuging.

Application user:

```<code>public class ApplicationUser : IdentityUser
{
    public int PriorityLevel { get; set; }
    public Role UserRole { get; set; }
    public string ForName { get; set; }
    public string LastName { get; set; }
    public string Mobile { get; set; }
    public string WorkPlace { get; set; }
    public string Notice { get; set; }
}
</code>```

Must i use some entity framework command for load UserRole as type Role? Or can i get UserRoleId from table?

Thanks for any advice.

答:
You can get all the roles of the user using this method.</p>

```<code>_userManager.GetRolesAsync(id);
</code>```

Body:
i have define users with UserRole type Role as foreing key of another table. Entiti framework auto transformed name UserRole to UserRoleId with type integer (Id). Its ok. But i have UserRoleId = 2 in table User table preview
and when i trying get user by Id:

var user = await _userManager.FindByIdAsync(id);

so parameter UserRole is null user preview from debuging.

Application user:

public class ApplicationUser : IdentityUser
{
    public int PriorityLevel { get; set; }
    public Role UserRole { get; set; }
    public string ForName { get; set; }
    public string LastName { get; set; }
    public string Mobile { get; set; }
    public string WorkPlace { get; set; }
    public string Notice { get; set; }
}

Must i use some entity framework command for load UserRole as type Role? Or can i get UserRoleId from table?

Thanks for any advice.

Body:
You can get all the roles of the user using this method.

_userManager.GetRolesAsync(id);


问:
I want to use characterAtIndex:(NSUInteger)index method of NSString class
I want to compare the value returned by characterAtIndex:(NSUInteger)index
of NSString class with a another NSString having one character stored in it any suggestion </p>

答:
```<code>NSString *temp = @"Hello";
NSString *temp2 = @"H";

if([temp characterAtIndex:0] == [temp2 characterAtIndex:0] )
</code>```


问:
Angular 4 Router ':any/component'
I am new to angular4. I am trying to route. My problem is component there is dynamic appName will come Like the following one.

```<code>localhost:4200/dynamic-name/login.
</code>```

Here I need to check if the dynamic name present on some services before hitting any component. Which means I need to check it on router module before going to the page. if there is present allow the router got to the login component. Otherwise, redirect to some default component. And I need to keep this dynamic-name all over the route link if exist.

please guide me anyone.

答:
You can set APP_BASE_HREF dynamically.

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './service/baselocation.service';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }
</code>```

And in ./service/baselocation.service,

```<code>export function getBaseLocation() {
     var basePath = "your dynamical base path" //add logic to get your base path
    return '/' + basePath;
}
</code>```

And Another way is to let the user to hit "/logn" route, then use AuthGuard to redirect to dynamic login route.

```<code>@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    var path=YourPathService.getPath();

     this.router.navigate(['/' + path + '/login']);

     return false;

  }
}

export const ROUTES: Routes = [
  {path: 'login', component: LoginComponent, canActivate: [AuthGuard]},
  {path: 'path1/login', Path1LoginComponent },
  {path: 'path2/login', Path1LoginComponent }
];
</code>```

Title: Angular 4 Router ':any/component'

Body:
I am new to angular4. I am trying to route. My problem is component there is dynamic appName will come Like the following one.

localhost:4200/dynamic-name/login.

Here I need to check if the dynamic name present on some services before hitting any component. Which means I need to check it on router module before going to the page. if there is present allow the router got to the login component. Otherwise, redirect to some default component. And I need to keep this dynamic-name all over the route link if exist.

please guide me anyone.

Body:
You can set APP_BASE_HREF dynamically.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';

import { AppComponent } from './';
import { getBaseLocation } from './service/baselocation.service';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    HttpModule,
  ],
  bootstrap: [AppComponent],
  providers: [
    appRoutingProviders,
    {
        provide: APP_BASE_HREF,
        useFactory: getBaseLocation
    },
  ]
})
export class AppModule { }

And in ./service/baselocation.service,

export function getBaseLocation() {
     var basePath = "your dynamical base path" //add logic to get your base path
    return '/' + basePath;
}

And Another way is to let the user to hit "/logn" route, then use AuthGuard to redirect to dynamic login route.

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {

    var path=YourPathService.getPath();

     this.router.navigate(['/' + path + '/login']);

     return false;

  }
}

export const ROUTES: Routes = [
  {path: 'login', component: LoginComponent, canActivate: [AuthGuard]},
  {path: 'path1/login', Path1LoginComponent },
  {path: 'path2/login', Path1LoginComponent }
];


问:
Strange Bootstrap Container Breakpoint Behaviour
If I set the browser width to 1024px the following bootstrap container rule is being applied:

```<code>@media (min-width: 768px) {
    .container {
        width: 750px;
    }
}
</code>```

If I extend the browser width to 1092px then the following bootstrap container rule is being applied:

```<code>@media (min-width: 992px) {
    .container {
        width: 970px;
    }
}
</code>```

There are no other CSS rules applied to the container, just the standard bootstrap rules:

```<code>.container {
    margin-right: auto;
    margin-left: auto;
    padding-left: 15px;
    padding-right: 15px;
}
</code>```

Can anyone explain to me why a browser width of 1024px isn't getting the min-width: 992px rules applied to it?

答:
I think you forget open close bracket { }

```<code>@media (min-width: 768px) {
            .container {
                width: 750px;
                background: yellow;
            }
        }

        @media (min-width: 992px) {
            .container {
                width: 970px;
                background: red;
            }
        }
</code>```

Body:
If I set the browser width to 1024px the following bootstrap container rule is being applied:

@media (min-width: 768px) {
    .container {
        width: 750px;
    }
}

If I extend the browser width to 1092px then the following bootstrap container rule is being applied:

@media (min-width: 992px) {
    .container {
        width: 970px;
    }
}

There are no other CSS rules applied to the container, just the standard bootstrap rules:

.container {
    margin-right: auto;
    margin-left: auto;
    padding-left: 15px;
    padding-right: 15px;
}

Can anyone explain to me why a browser width of 1024px isn't getting the min-width: 992px rules applied to it?

Body:
I think you forget open close bracket { }

@media (min-width: 768px) {
            .container {
                width: 750px;
                background: yellow;
            }
        }

        @media (min-width: 992px) {
            .container {
                width: 970px;
                background: red;
            }
        }


问:
Replace anchor tag value with anchor title if href value is empty by regex
I am trying to replace the anchor tag value with anchor's title value if any anchor tag's href attribute is blank.

Like

```<code><a xlink:href="">Lorem Ipsum</a>  is simply dummy text of the printing and typesetting industry<a xlink:href ="http://google.com">Google</a>.
</code>```

if I try with below regex:

```<code><a [^>]+>(.*?)<\/a>
</code>```

DEMO http://regexr.com/3h6on

then output I am getting below

```<code>Lorem Ipsum is simply dummy text of the printing and typesetting industry Google.
</code>```

it replaced both anchor tag with Anchor Text value, and I need to replace those anchor tag where the href attribute value is empty.

I need an output like below

```<code>Lorem Ipsum is simply dummy text of the printing and typesetting industry<a xlink:href ="http://google.com">Google</a>
</code>```

Body:
I am trying to replace the anchor tag value with anchor's title value if any anchor tag's href attribute is blank.

Like

Lorem Ipsum  is simply dummy text of the printing and typesetting industryGoogle.

if I try with below regex:

]+>(.*?)<\/a>

DEMO http://regexr.com/3h6on

then output I am getting below

Lorem Ipsum is simply dummy text of the printing and typesetting industry Google.

it replaced both anchor tag with Anchor Text value, and I need to replace those anchor tag where the href attribute value is empty.

I need an output like below

Lorem Ipsum is simply dummy text of the printing and typesetting industryGoogle

Body:
Please try this: <a[^<]+href=(['"]{2})\1?[^>]*?>([^<>]*)<\/a>

Try it here.


问:
Center Vis.js timeline on current date on open
I have a VisJS timeline ranging from January 2017-2018. The timeline opens centered on a three month range mid-year, but I would like it to open every time centered at the current time.</p>

```<code>min: new Date(2017, 1, 5),           // lower limit of visible range
max: new Date(2018, 1, 11),          // upper limit of visible range
zoomMin: 1000 * 60 * 60 * 24,        // one day in milliseconds
zoomMax: 1000 * 60 * 60 * 24*31*3,   // three months in milliseconds
</code>```

答:
You may try with something like this (timeline.setWindow()):

```<code>const todayStart = new Date();
todayStart.setHours(8, 0, 0, 0);
const todayEnd = new Date();
todayEnd.setHours(18, 0, 0, 0);

console.log(todayStart, ':', todayEnd);
setTimeout(_ => {
  this.timeline.setWindow(todayStart, todayEnd, { animation: true });
});
</code>```

or better with the moveTo

```<code>  this.timeline.moveTo(new Date());//or
  this.timeline.moveTo(new Date(), { animation: true });//or
  this.timeline.moveTo(new Date(), { animation: true }, (props) => {
    console.log("movedTo", props);
  });
</code>```

Body:
I have a VisJS timeline ranging from January 2017-2018. The timeline opens centered on a three month range mid-year, but I would like it to open every time centered at the current time.

min: new Date(2017, 1, 5),           // lower limit of visible range
max: new Date(2018, 1, 11),          // upper limit of visible range
zoomMin: 1000 * 60 * 60 * 24,        // one day in milliseconds
zoomMax: 1000 * 60 * 60 * 24*31*3,   // three months in milliseconds

Body:
You may try with something like this (timeline.setWindow()):

const todayStart = new Date();
todayStart.setHours(8, 0, 0, 0);
const todayEnd = new Date();
todayEnd.setHours(18, 0, 0, 0);

console.log(todayStart, ':', todayEnd);
setTimeout(_ => {
  this.timeline.setWindow(todayStart, todayEnd, { animation: true });
});

or better with the moveTo

  this.timeline.moveTo(new Date());//or
  this.timeline.moveTo(new Date(), { animation: true });//or
  this.timeline.moveTo(new Date(), { animation: true }, (props) => {
    console.log("movedTo", props);
  });


问:
Convert Lat/Lon to Integer
A service that I'm consuming requires that I pass it the lat/lon for an address as integers. Currently, my lat/lon's are stored as doubles:

```<code>double lat = 38.898748;
double lon = -77.037684;
</code>```

I've exhausted my Google-fu and can't find a method for converting lat/lon to an integer representation. Any help would be appreciated.

答:
```<code>double_lat = 38.898748;

double_lon = -77.037684;
</code>```

A simple way to store decimal positions as integers:

```<code>lat = (double_lat + 90) * 1000000;

lon = (double_lon + 180) * 1000000;

lat = 128898748;
lon = 102962316;
</code>```

Title: Convert Lat/Lon to Integer

Body:
A service that I'm consuming requires that I pass it the lat/lon for an address as integers. Currently, my lat/lon's are stored as doubles:

double lat = 38.898748;
double lon = -77.037684;

I've exhausted my Google-fu and can't find a method for converting lat/lon to an integer representation. Any help would be appreciated.

Body:
double_lat = 38.898748;

double_lon = -77.037684;

A simple way to store decimal positions as integers:

lat = (double_lat + 90) * 1000000;

lon = (double_lon + 180) * 1000000;

lat = 128898748;
lon = 102962316;


问:
How can I pad an integer with zeros on the left?
How do you left pad an int with zeros when converting to a String in java?

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

答:
Found this example... Will test...

```<code>import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}
</code>```

Tested this and:

```<code>String.format("%05d",number);
</code>```

Both work, for  my purposes I think String.Format is better and more succinct.

OwnerDisplayName: Omar Kooheji

Body:
Found this example... Will test...

import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
    public static void main(String [] args)
    {
        int x=1;
        DecimalFormat df = new DecimalFormat("00");
        System.out.println(df.format(x));
    }
}

Tested this and:

String.format("%05d",number);

Both work, for  my purposes I think String.Format is better and more succinct.


问:
How many arguments takes the foldr function of Haskell?
I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

```<code>
theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys
</code>```

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.

答: In this case foldr is used to build up a function. (\_ -> False) is the argument to that function.

Body:
I am new to Haskell and I am reading the book  "Real World Haskell". In the Chapter 4 of the book the author asks as an exercise to rewrite the groupBy function using fold. One of the readers of the book (Octavian Voicu ) gave the following solution:

theCoolGroupBy :: (a -> a -> Bool) -> [a] -> [[a]]
theCoolGroupBy eq xs = tail $ foldr step (\_ -> [[]]) xs $ (\_ -> False)
                       where step x acc = \p -> if p x then rest p else []:rest (eq x)
                                          where rest q = let y:ys = acc q in (x:y):ys

My question is simple: I know that foldr takes 3 arguments: a function, an initial value and a list. But in the second line of the code foldr takes 4 arguments. Why this happens?
Thank you.


问:
How does back_inserter work?
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:

```<code>template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;

    explicit back_insert_iterator( C& __x ) :container( &__x ) {
    }

    back_insert_iterator<C>& operator=( const typename C::value_type& val ) {
        container->push_back( val );
        return *this;
    }

    back_insert_iterator<C>& operator*() {
        return *this;
    }

    back_insert_iterator<C>& operator++() {
        return *this;
    }

    back_insert_iterator<C>& operator++( int ) {
        return *this;
    }
};
</code>```

I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?

Thanks,

Chan

答:
back_inserter() returns a back_insert_iterator, which has to function like an output iterator. Specifically, it has to support operations such as pre- and post increment, and dereference assignment.

If it didn't support those operations, it couldn't be used where output iterators are required.

Title: How does back_inserter work?

Body:
I'm trying to understand how back_inserter work, and this is its implementation that I have from SGI-STL:

template<class C>
class back_insert_iterator {
protected:
    C* container;
public:
    typedef C                   container_type;
    typedef output_iterator_tag iterator_category;
    typedef void                value_type;
    typedef void                difference_type;
    typedef void                pointer;
    typedef void                reference;

    explicit back_insert_iterator( C& __x ) :container( &__x ) {
    }

    back_insert_iterator<C>& operator=( const typename C::value_type& val ) {
        container->push_back( val );
        return *this;
    }

    back_insert_iterator<C>& operator*() {
        return *this;
    }

    back_insert_iterator<C>& operator++() {
        return *this;
    }

    back_insert_iterator<C>& operator++( int ) {
        return *this;
    }
};

I understood most parts, except the last three operator *, ++, ++( int ). My guess for their existence is because they need to support operations when placed inside the STL algorithm. Other than that, I don't know what are they used for? Could anyone help me clarify this?

Thanks,

Chan


问:
Javascript confusion for scope of 'this' inside closure function
I tried below function to understand this keyword scope global/private.

I understood it 97%. but got stuck in confusion over the output of x.private_fa() which returns a private function but not the private value inside it.

a = 1.1;
b = 2.1;
c = 3.1;

function fa() {
  return "Global fa()";
}

function f() {
  var a = 1;
  this.b = 2;

  function fa() {
    return this.b; // or this.a not working..!
    //return b // 2.2
    //return a // 1
  }

  return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: c, // 3.1
    private_c: this.c // 3
  };
}

try {

  f.prototype.c = 3;

  var x = new f();

  f.prototype.c = 4;

  console.log("x:", x);

  /*??? Please explain this.. ??? */
  console.log("x.private_fa():", x.private_fa());

  console.log(x.private_c);
  var x1 = new f();
  console.log(x1.private_c);

  console.log(" - End - ");
} catch (e) {
  console.error("Error: ", e.message);
}```

答:
In the code you posted, a call to x.private_fa() returns undefined, just because the object x hasn't a b member (and fa returns this.b).

If you want it to return that value let your object's private_fa return a bound version of the "private" fa():

```<code>var bound_fa = fa.bind(this);

return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: window.b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: bound_fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: window.c, // 3.1
    private_c: this.c // 3
};
</code>```

In bound_fa function, this will be forever tied to f() context (where the desired variable b belongs).

This reading could clarify the this enigma further: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md

Body:
In the code you posted, a call to x.private_fa() returns undefined, just because the object x hasn't a b member (and fa returns this.b).

If you want it to return that value let your object's private_fa return a bound version of the "private" fa():

var bound_fa = fa.bind(this);

return {
    private_a: a, // 1
    global_a: window.a, // 1.1
    private_b: this.b, // 2
    global_b: window.b, // 2.1
    private_fax: fa(), // 2.1
    private_fa: bound_fa, // function private fa()
    global_fa: window.fa(), // Global fa()
    global_c: window.c, // 3.1
    private_c: this.c // 3
};

In bound_fa function, this will be forever tied to f() context (where the desired variable b belongs).

This reading could clarify the this enigma further: https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch1.md


问:
Two module verilog is not working
```<code>module rff_try_1(q,inp,clk);
input clk,inp;
output q;
reg q;

DFF dff0(q,inp,clk);
endmodule

module DFF(q,inp,clk);
input inp,clk;
output q;
reg q;
always @ (posedge clk)begin
if(clk)begin
q=inp;
end
end

endmodule
</code>```

here I'm using two modules but output is not coming
I'm trying to make two bit right shift register but 1st i have to make one single bit register but even this is not working

答:
There are several mistakes in the code.

1) The line if(clk)begin and relevant end should be removed, posedge clk already describes trigger condition of the flip-flop.

2) A non-blocking assignment (<=) is required for the sequential logic.

The always block should be as follows:

```<code>always @ (posedge clk) begin
    q <= inp;
end
</code>```

3) Some simulators don't complain, but signal q should be wire in module rff_try_1.

```<code>wire q;
</code>```

Simulation

I simulated the code (after the modifications) on EDA Playground with the testbench below. Used Icarus Verilog 0.9.7 as simulator.

```<code>module tb();

  reg clk = 1;
  always clk = #5 ~clk;

  reg  inp;
  wire q;

  rff_try_1 dut(q, inp, clk);

  initial begin
    inp = 0;
    #12;
    inp = 1;
    #27;
    inp = 0;
    #24;
    inp = 1;
  end

  initial begin
    $dumpfile("dump.vcd"); $dumpvars;
    #200;
    $finish;
  end

endmodule
</code>```

The signal q is as expected as seen on the waveform.

Title: Two module verilog is not working

Body:
module rff_try_1(q,inp,clk);
input clk,inp;
output q;
reg q;

DFF dff0(q,inp,clk);
endmodule

module DFF(q,inp,clk);
input inp,clk;
output q;
reg q;
always @ (posedge clk)begin
if(clk)begin
q=inp;
end
end

endmodule

here I'm using two modules but output is not coming
I'm trying to make two bit right shift register but 1st i have to make one single bit register but even this is not working

Body:
There are several mistakes in the code.

1) The line if(clk)begin and relevant end should be removed, posedge clk already describes trigger condition of the flip-flop.

2) A non-blocking assignment (<=) is required for the sequential logic.

The always block should be as follows:

always @ (posedge clk) begin
    q <= inp;
end

3) Some simulators don't complain, but signal q should be wire in module rff_try_1.

wire q;

Simulation

I simulated the code (after the modifications) on EDA Playground with the testbench below. Used Icarus Verilog 0.9.7 as simulator.

module tb();

  reg clk = 1;
  always clk = #5 ~clk;

  reg  inp;
  wire q;

  rff_try_1 dut(q, inp, clk);

  initial begin
    inp = 0;
    #12;
    inp = 1;
    #27;
    inp = 0;
    #24;
    inp = 1;
  end

  initial begin
    $dumpfile("dump.vcd"); $dumpvars;
    #200;
    $finish;
  end

endmodule

The signal q is as expected as seen on the waveform.


问:
Split a large character column with different amount of values into multiple columns
I have a character column with a different amount of values per row. This is just a small example:

```<code>GoodForMeal %>% head(5)
# A tibble: 5 x 1
GoodForMeal
<chr>
1 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
2 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
3 <NA>
4 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
5 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
</code>```

Here is a dput() of the first row of the column:

```<code>structure(list(GoodForMeal = "dessert': False, 'latenight': False, 'lunch': True, 'dinner': True, 'breakfast': False, 'brunch': False}"), .Names = "GoodForMeal", row.names = c(NA,
-1L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

I want to assign the values before the colon as column names and the values after the colon as the values of the respective column.

Example:

```<code>   desert latenight lunch diner
1  False  False     True  True
2  False  False     True  True
3  NA     NA        NA    NA
4  False  False     True  True
5  False  False     True  True
</code>```

I tried it with the tidyr packadge and the separate and the spread function:

```<code>separate(GoodForMeal, c("key", "value"), sep = ":", extra = "merge") %>% spread(key, value)
</code>```

The problem is the r is not splitting all the values before the colon but just the first value.

So the result looks like this:

```<code>GoodForMeal %>% str()

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   4464 obs. of  2 variables:
 $ dessert': chr  " False, 'latenight': False, 'lunch': True, 'dinner': False, 'breakfast': False, 'brunch': False}" " False, 'latenight': False, 'lunch': True, 'dinner': True, 'breakfast': False, 'brunch': False}" " False, 'latenight': False, 'lunch': False, 'dinner': False, 'breakfast': False, 'brunch': False}" " False, 'latenight': False, 'lunch': True, 'dinner': True, 'breakfast': False, 'brunch': False}" ...
 $ <NA>    : chr  NA NA NA NA ...
</code>```

Any Idea how to split the values so that it´s looking like in the example? THX

答:
This is not an elegant solution (and long) but seems to work. I did change the data to make it more general. Hope this can be a good start.</p>

```<code># i made some changes in the data; remove lunch entry in the 4th element and remove dessert in the 1st
sampleData <- c("'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True",
            "'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True",
            NA,
            "'dessert': False, 'latenight': False, 'dinner': True",
            "'latenight': False, 'lunch': True, 'dinner': True")

# [1] "'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True"
# [2] "'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True"
# [3] NA
# [4] "'dessert': False, 'latenight': False, 'dinner': True"
# [5] "'latenight': False, 'lunch': True, 'dinner': True"

# not sure if this is necessary, but jsut to clean the data
sampleData <- gsub(x = sampleData, pattern = "'| ", replacement = "")

# i'm a data.table user, so i'll jsut use tstrsplit
# split the pairs within each elements first
x <- data.table::tstrsplit(sampleData, ",")

# split the header and the entry
test <- lapply(x, function(x) data.table::tstrsplit(x, ":", fixed = TRUE))

# get the headers
indexHeader <- do.call("rbind", lapply(test, function(x) x[[1]]))

# get the entries
indexValue <- do.call("rbind",
                      lapply(test, function(x){if(length(x) > 1){ return(x[[2]])}else{ return(x[[1]])} }))

# get unique headers
colNames <- unique(as.vector(indexHeader))

colNames <- colNames[!is.na(colNames)]

# determine the order of the entries using the header matrix
indexUse <- apply(indexHeader, 2, function(x) match(colNames, x))

# index the entry matrix using the above matching
resA <- mapply(FUN = function(x,y) x[y],
               x = as.data.frame(indexValue),
               y = as.data.frame(indexUse))

# convert to data frame
final <- as.data.frame(t(resA))

# rename columns
colnames(final) <- colNames

# should give something like this
final
# dessert latenight lunch dinner
# False     False  True   True
# False     False  True   True
# <NA>      <NA>  <NA>   <NA>
# False     False  <NA>   True
# <NA>     False  True   True
</code>```

Body:
I have a character column with a different amount of values per row. This is just a small example:

GoodForMeal %>% head(5)
# A tibble: 5 x 1
GoodForMeal
<chr>
1 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
2 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
3 <NA>
4 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True
5 dessert': False, 'latenight': False, 'lunch': True, 'dinner': True

Here is a dput() of the first row of the column:

structure(list(GoodForMeal = "dessert': False, 'latenight': False, 'lunch': True, 'dinner': True, 'breakfast': False, 'brunch': False}"), .Names = "GoodForMeal", row.names = c(NA,
-1L), class = c("tbl_df", "tbl", "data.frame"))

I want to assign the values before the colon as column names and the values after the colon as the values of the respective column.

Example:

   desert latenight lunch diner
1  False  False     True  True
2  False  False     True  True
3  NA     NA        NA    NA
4  False  False     True  True
5  False  False     True  True

I tried it with the tidyr packadge and the separate and the spread function:

separate(GoodForMeal, c("key", "value"), sep = ":", extra = "merge") %>% spread(key, value)

The problem is the r is not splitting all the values before the colon but just the first value.

So the result looks like this:

GoodForMeal %>% str()

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':   4464 obs. of  2 variables:
 $ dessert': chr  " False, 'latenight': False, 'lunch': True, 'dinner': False, 'breakfast': False, 'brunch': False}" " False, 'latenight': False, 'lunch': True, 'dinner': True, 'breakfast': False, 'brunch': False}" " False, 'latenight': False, 'lunch': False, 'dinner': False, 'breakfast': False, 'brunch': False}" " False, 'latenight': False, 'lunch': True, 'dinner': True, 'breakfast': False, 'brunch': False}" ...
 $ <NA>    : chr  NA NA NA NA ...

Any Idea how to split the values so that it´s looking like in the example? THX

Body:
This is not an elegant solution (and long) but seems to work. I did change the data to make it more general. Hope this can be a good start.

# i made some changes in the data; remove lunch entry in the 4th element and remove dessert in the 1st
sampleData <- c("'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True",
            "'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True",
            NA,
            "'dessert': False, 'latenight': False, 'dinner': True",
            "'latenight': False, 'lunch': True, 'dinner': True")

# [1] "'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True"
# [2] "'dessert': False, 'latenight': False, 'lunch': True, 'dinner': True"
# [3] NA
# [4] "'dessert': False, 'latenight': False, 'dinner': True"
# [5] "'latenight': False, 'lunch': True, 'dinner': True"

# not sure if this is necessary, but jsut to clean the data
sampleData <- gsub(x = sampleData, pattern = "'| ", replacement = "")

# i'm a data.table user, so i'll jsut use tstrsplit
# split the pairs within each elements first
x <- data.table::tstrsplit(sampleData, ",")

# split the header and the entry
test <- lapply(x, function(x) data.table::tstrsplit(x, ":", fixed = TRUE))

# get the headers
indexHeader <- do.call("rbind", lapply(test, function(x) x[[1]]))

# get the entries
indexValue <- do.call("rbind",
                      lapply(test, function(x){if(length(x) > 1){ return(x[[2]])}else{ return(x[[1]])} }))

# get unique headers
colNames <- unique(as.vector(indexHeader))

colNames <- colNames[!is.na(colNames)]

# determine the order of the entries using the header matrix
indexUse <- apply(indexHeader, 2, function(x) match(colNames, x))

# index the entry matrix using the above matching
resA <- mapply(FUN = function(x,y) x[y],
               x = as.data.frame(indexValue),
               y = as.data.frame(indexUse))

# convert to data frame
final <- as.data.frame(t(resA))

# rename columns
colnames(final) <- colNames

# should give something like this
final
# dessert latenight lunch dinner
# False     False  True   True
# False     False  True   True
# <NA>      <NA>  <NA>   <NA>
# False     False  <NA>   True
# <NA>     False  True   True


问:
Jenkins Build Failure because of Ui Tests (Selenium)
I've got the following problem:

One GWT application(internet shop) with unit Tests and selenium UI Tests (automated)

One jenkins server where i can build my application (new version number or snapshot)

The failure:

The build on jenkins doesn't work because ui Tests can't run (The application needs to be deployed at that moment)

How can jenkins deploy the programm at that moment, so the application can run the selenium tests?

答:
You can use Jenkins to model your pipeline, which in its most basic setup will have, three stages which should be defined in a Jenkinsfile. Simple Declarative Pipeline example:

```<code>pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying'
            }
        }
    }
}
</code>```

In your case, after Unit tests pass, you can promote your Application to higher environment, like QA and trigger UI tests. If utilized properly, this setup will be very handy as Staging/Production phase.

Body:
You can use Jenkins to model your pipeline, which in its most basic setup will have, three stages which should be defined in a Jenkinsfile. Simple Declarative Pipeline example:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building'
            }
        }
        stage('Test') {
            steps {
                echo 'Testing'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying'
            }
        }
    }
}

In your case, after Unit tests pass, you can promote your Application to higher environment, like QA and trigger UI tests. If utilized properly, this setup will be very handy as Staging/Production phase.


问:
Firebase Firestore - Iterate collection with restricted security rules
In Firestore I defined a rule like this:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, list: if request.data.visibility == "public";
    }
  }
}
</code>```

Then I want to get all public documents, so I subscribe to the collection using AngularFire:

```<code>this.docs = db.collection('documents', ref => ref.where("visibility", "==", 'public')).snapshotChanges();
</code>```

But this throws:

Missing or insufficient permissions.

Is this supposed to happen? Is it possible to iterate a collection with restricted documents? I'm not a big fan of subcollections, but is that the only way to achieve this?

答:
Solved, I was missing the list rule, and I also didn't add the documents collection. The final rule is this:</p>

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /documents/{document=**} {
      allow read, list: if resource.data.visibility == "public"
    }
  }
}
</code>```

Body:
In Firestore I defined a rule like this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, list: if request.data.visibility == "public";
    }
  }
}

Then I want to get all public documents, so I subscribe to the collection using AngularFire:

this.docs = db.collection('documents', ref => ref.where("visibility", "==", 'public')).snapshotChanges();

But this throws:

Missing or insufficient permissions.

Is this supposed to happen? Is it possible to iterate a collection with restricted documents? I'm not a big fan of subcollections, but is that the only way to achieve this?

Body:
Solved, I was missing the list rule, and I also didn't add the documents collection. The final rule is this:

service cloud.firestore {
  match /databases/{database}/documents {
    match /documents/{document=**} {
      allow read, list: if resource.data.visibility == "public"
    }
  }
}


问:
Change element in arraylist to true from user input
```<code>package issue;
import java.util.*;

public class Issue {

    private static ArrayList<Object> list = new ArrayList<Object>();

    public static ArrayList<Object> getArrayStringList(){
        for (Object o : list)
            System.out.println("["+o+"]");
        return list;
    }

    public static void removeIssue(){
        for (int i = 0; i<list.size(); i++){;
            System.out.println("["+"["+i+"] "+list.get(i)+"]");
        }
        Scanner scan = new Scanner(System.in);
        System.out.println("Which one would you like to mark as solved?");
        int choice = scan.nextInt();

       ##This is where my problem is ##
        Object issue = list.get(choice);
        issue
    }

    public static void addIssue(){
        Scanner scan = new Scanner(System.in);
        String text= scan.nextLine();
        newIssue issue = new newIssue(text);
        list.add(issue);
    }
}
</code>```

I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to

```<code>package issue;

public class newIssue {

    public String issueText;
    public boolean returned = false;

    public newIssue(String issueText){
        this.issueText = issueText;
    }

    public String toString(){
        return issueText + returned;
    }
}
</code>```

答:
Try this.</p>

```<code>if(list.size() > 0 && choice <= list.size()-1) {
    newIssue issue = (newIssue)list.get(choice);
    issue.returned = true;
    System.out.println("newIssue = "+ issue.toString())
}
</code>```

Body:
package issue;
import java.util.*;

public class Issue {

    private static ArrayList<Object> list = new ArrayList<Object>();

    public static ArrayList<Object> getArrayStringList(){
        for (Object o : list)
            System.out.println("["+o+"]");
        return list;
    }

    public static void removeIssue(){
        for (int i = 0; i<list.size(); i++){;
            System.out.println("["+"["+i+"] "+list.get(i)+"]");
        }
        Scanner scan = new Scanner(System.in);
        System.out.println("Which one would you like to mark as solved?");
        int choice = scan.nextInt();

       ##This is where my problem is ##
        Object issue = list.get(choice);
        issue
    }

    public static void addIssue(){
        Scanner scan = new Scanner(System.in);
        String text= scan.nextLine();
        newIssue issue = new newIssue(text);
        list.add(issue);
    }
}

I want the user input to choose the appropriate element in the ArrayList and then set it to true using the newIssue class. But I can't figure out how to

package issue;

public class newIssue {

    public String issueText;
    public boolean returned = false;

    public newIssue(String issueText){
        this.issueText = issueText;
    }

    public String toString(){
        return issueText + returned;
    }
}

Body:
Try this.

if(list.size() > 0 && choice <= list.size()-1) {
    newIssue issue = (newIssue)list.get(choice);
    issue.returned = true;
    System.out.println("newIssue = "+ issue.toString())
}