问:
c++ assignment operator helper
I'm trying to write a helper .h file with some operators.

Mainly something like this

```<code>QVector3D &operator=(const someDataObj&data){
      QVector3D out(data[0],data[10],data[12]);
      return out;
}
</code>```

But when ever I try it I get :
error C2801: 'operator =' must be a non-static member

if I try :

```<code>Vector3D operator=(QVector3D &left, const someDataObj &other) {}

</code>```

I get : error C2801: 'operator =' must be a non-static member

I'm just lost... how can I properly do it ?

Edit: I forgot to mention, its main usage will be converting of data from libraryA to libraryB.

答:
As the error message explains, assignment operator can only be defined as a member. Assuming QVector3D comes from Qt and is therefore not modifiable by you, and, on the other hand, someDataObj is of a type you've defined, you can make a conversion operator for that type, instead. If that's not the case, then you have to perform the conversion explicitly via a non-member function.

Edit:

The syntax library_a_data = library_b_data, but one of those types must be wrapped in your own:

private inheritance

```<code>class MyVector3D : private QVector3D // do not allow implicit conversions
// to the base class for safety, as the destructor is not virtual
{
public:
    using QVector3D::member_1;
    using QVector3D::member_n; // very tedious work of bringing the names back

    // hurray, you can define your assignment or conversion operator
};
</code>```

composition

```<code>class MyVector3D
{
    QVector3D m_data;

public:
    auto member_1() { return m_data.member_1(); }
    auto member_n() { return m_data.member_n(); } // even more tedious

    // hurray, you can define your assignment or conversion operator
};
</code>```

However, I think that this kind of conversion should be left explicit, but the above code should be already discouraging enough. Can we consider this as an improvement, since at one point you have to convert to your type? I don't think so.

Title: c++ assignment operator helper

Body:
I'm trying to write a helper .h file with some operators.

Mainly something like this

QVector3D &operator=(const someDataObj&data){
      QVector3D out(data[0],data[10],data[12]);
      return out;
}

But when ever I try it I get :
error C2801: 'operator =' must be a non-static member

if I try :

Vector3D operator=(QVector3D &left, const someDataObj &other) {}

I get : error C2801: 'operator =' must be a non-static member

I'm just lost... how can I properly do it ?

Edit: I forgot to mention, its main usage will be converting of data from libraryA to libraryB.

Body:
As the error message explains, assignment operator can only be defined as a member. Assuming QVector3D comes from Qt and is therefore not modifiable by you, and, on the other hand, someDataObj is of a type you've defined, you can make a conversion operator for that type, instead. If that's not the case, then you have to perform the conversion explicitly via a non-member function.

Edit:

The syntax library_a_data = library_b_data, but one of those types must be wrapped in your own:

private inheritance

class MyVector3D : private QVector3D // do not allow implicit conversions
// to the base class for safety, as the destructor is not virtual
{
public:
    using QVector3D::member_1;
    using QVector3D::member_n; // very tedious work of bringing the names back

    // hurray, you can define your assignment or conversion operator
};

composition

class MyVector3D
{
    QVector3D m_data;

public:
    auto member_1() { return m_data.member_1(); }
    auto member_n() { return m_data.member_n(); } // even more tedious

    // hurray, you can define your assignment or conversion operator
};

However, I think that this kind of conversion should be left explicit, but the above code should be already discouraging enough. Can we consider this as an improvement, since at one point you have to convert to your type? I don't think so.


来源: stackexchange

问:
Get table row text python selenium
This is the html

```<code><table id="dataLstSubCat" cellspacing="0" style="border-collapse:collapse;">
    <tbody><tr>
        <td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_0" href="javascript:__doPostBack('dataLstSubCat$ctl00$LnkBtnSubCat','')">Primers</a>
                      </td><td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_1" href="javascript:__doPostBack('dataLstSubCat$ctl01$LnkBtnSubCat','')">Intermediates</a>
                      </td><td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_2" href="javascript:__doPostBack('dataLstSubCat$ctl02$LnkBtnSubCat','')">Finishes</a>
                      </td>
    </tr>
</tbody></table>
</code>```

Now I want to extract the table data(td) text
like I want to extract the text

[Primers,Intermediates,Finishes]

This is what I have tried

```<code>new_text=driver.find_element_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr"))
new_text.text
</code>```

which gives o/p in string and not in list

```<code>Primers Intermediates Finishes
</code>```

Is there any way by which it can be done.

答:
One option is to use find_elements_by_xpath and then with for loop add it to the list like:

```<code>list = []
new_text=driver.find_elements_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr/td"))
for text in new_text:
   list.append(text.text)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Get table row text python selenium

Body:
This is the html

                        Primers

                        Intermediates

                        Finishes

Now I want to extract the table data(td) text
like I want to extract the text

[Primers,Intermediates,Finishes]

This is what I have tried

new_text=driver.find_element_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr"))
new_text.text

which gives o/p in string and not in list

Primers Intermediates Finishes

Is there any way by which it can be done.

Body:
One option is to use find_elements_by_xpath and then with for loop add it to the list like:

list = []
new_text=driver.find_elements_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr/td"))
for text in new_text:
   list.append(text.text)


问:
CompletableTransformer is not applying subscribeOn and observeOn to the Upstream
I'm creating offline first app as my side project using rxKotlin, MVVM + Clean Architecture and yesterday I decided to get ride off boilerplate subscribeOn and observeOn by using transformers. I quickly realized that apply function of transformers are ignored.

Here is code of my base completable use case (interactor):

```<code>abstract class CompletableUseCase(private val transformer: CompletableTransformer) {

    abstract fun createCompletable(data: Map<String, Any>? = null) : Completable

    fun completable(data: Map<String, Any>? = null) : Completable {
        return createCompletable(data).compose(transformer)
    }
}
</code>```

And here is implementation of specific interactor:

```<code>class SaveRouteInteractor(
    transformer: CompletableTransformer,
    private val routeRepository: RouteRepository
) : CompletableUseCase(transformer) {

    companion object {
        private const val PARAM_ROUTE = "param_route"
    }

    fun saveRoute(route: Route) : Completable {
        val data = HashMap<String, Route>()
        data[PARAM_ROUTE] = route
        return completable(data)
    }

    override fun createCompletable(data: Map<String, Any>?): Completable {
        val routeEntity = data?.get(PARAM_ROUTE)

        routeEntity?.let {
            return routeRepository.saveRoute(routeEntity as Route)
        } ?: return Completable.error(IllegalArgumentException("Argument @route must be provided."))
    }
}
</code>```

My custom transformer that is passed to the constructor of SaveRouteInteractor:

```<code>class IOCompletableTransformer(private val mainThreadScheduler: Scheduler) : CompletableTransformer {

    override fun apply(upstream: Completable): CompletableSource {
        return upstream.subscribeOn(Schedulers.io()).observeOn(mainThreadScheduler)
    }
}
</code>```

And implementation of RouteRepository method:

```<code>override fun saveRoute(route: Route): Completable {
        return localRouteSource.saveRoute(route)
            .flatMap { localID ->
                route.routeId = localID
                remoteRouteSource.saveRoute(route)
            }
            .flatMapCompletable { localRouteSource.updateRouteID(route.routeId, it) }
    }
</code>```

I'm using Room as my local source so after calling save interactor in my ViewModel I'm getting IlligalStateException telling me that I'm not allowed to access database on the main thread.

Maybe I'm missing something but it seems that transform function is ignored. I debugged this method and it is applying subscribeOn and observeOn to the upstream.

Thanks for help in advance,
Pace!

答:
It's hard to tell you where the issue is because the code is partial.

For example here:

```<code>    return localRouteSource.saveRoute(route)
        .flatMap { localID ->
            route.routeId = localID
            remoteRouteSource.saveRoute(route)
        }
        .flatMapCompletable { localRouteSource.updateRouteID(route.routeId, it) }
</code>```

I suppose the localRouteSource.saveRoute() is using the interactor you show us but it is not clear how remoteRouteSource.saveRoute() or localRouteSource.updateRouteID() are implemented.

they also need to be subscribed on the IO thread.

As a rule of thumb you should switch thread when you KNOW that you need it.

In other words, you should use subscribeOn() in places where you know you are doing IO as close as possible to the actual job. ObserveOn instead is to be used when you know you need to obtain those results in the UI thread and that you might get in some other thread.

in your example there's absolutely no need to keep using observeOn(MAIN_THREAD), the only time you do need it (I suppose) is when you want to show the result.

A couple of other things:

This code

```<code>override fun createCompletable(data: Map<String, Any>?): Completable {
    val routeEntity = data?.get(PARAM_ROUTE)

    routeEntity?.let {
        return routeRepository.saveRoute(routeEntity as Route)
    } ?: return Completable.error(IllegalArgumentException("Argument @route must be provided."))
}
</code>```

it is evaluated at the time when the method is called rather then when the completable  is subscribed.

In other words it break the Rx contract and compute data?.get(PARAM_ROUTE) when you call the method. If it is immutable there's no much difference, but if it can change value during execution it should be wrapped in a Completable.defer { }

Finally, here

```<code>        .flatMap { localID ->
            route.routeId = localID
            remoteRouteSource.saveRoute(route)
        }
</code>```

you are modyfing something outside the chain (route.routeId = localID), this is called a side effect.

be careful with those kind of stuff, Rx is build in a way that is safer to be used with immutable objects.

I personally wouldn't mind too much as long as you understand what's going on and when it could create issues.

Body:
I'm creating offline first app as my side project using rxKotlin, MVVM + Clean Architecture and yesterday I decided to get ride off boilerplate subscribeOn and observeOn by using transformers. I quickly realized that apply function of transformers are ignored.

Here is code of my base completable use case (interactor):

abstract class CompletableUseCase(private val transformer: CompletableTransformer) {

    abstract fun createCompletable(data: Map<String, Any>? = null) : Completable

    fun completable(data: Map<String, Any>? = null) : Completable {
        return createCompletable(data).compose(transformer)
    }
}

And here is implementation of specific interactor:

class SaveRouteInteractor(
    transformer: CompletableTransformer,
    private val routeRepository: RouteRepository
) : CompletableUseCase(transformer) {

    companion object {
        private const val PARAM_ROUTE = "param_route"
    }

    fun saveRoute(route: Route) : Completable {
        val data = HashMap<String, Route>()
        data[PARAM_ROUTE] = route
        return completable(data)
    }

    override fun createCompletable(data: Map<String, Any>?): Completable {
        val routeEntity = data?.get(PARAM_ROUTE)

        routeEntity?.let {
            return routeRepository.saveRoute(routeEntity as Route)
        } ?: return Completable.error(IllegalArgumentException("Argument @route must be provided."))
    }
}

My custom transformer that is passed to the constructor of SaveRouteInteractor:

class IOCompletableTransformer(private val mainThreadScheduler: Scheduler) : CompletableTransformer {

    override fun apply(upstream: Completable): CompletableSource {
        return upstream.subscribeOn(Schedulers.io()).observeOn(mainThreadScheduler)
    }
}

And implementation of RouteRepository method:

override fun saveRoute(route: Route): Completable {
        return localRouteSource.saveRoute(route)
            .flatMap { localID ->
                route.routeId = localID
                remoteRouteSource.saveRoute(route)
            }
            .flatMapCompletable { localRouteSource.updateRouteID(route.routeId, it) }
    }

I'm using Room as my local source so after calling save interactor in my ViewModel I'm getting IlligalStateException telling me that I'm not allowed to access database on the main thread.

Maybe I'm missing something but it seems that transform function is ignored. I debugged this method and it is applying subscribeOn and observeOn to the upstream.

Thanks for help in advance,
Pace!

Body:
It's hard to tell you where the issue is because the code is partial.

For example here:

    return localRouteSource.saveRoute(route)
        .flatMap { localID ->
            route.routeId = localID
            remoteRouteSource.saveRoute(route)
        }
        .flatMapCompletable { localRouteSource.updateRouteID(route.routeId, it) }

I suppose the localRouteSource.saveRoute() is using the interactor you show us but it is not clear how remoteRouteSource.saveRoute() or localRouteSource.updateRouteID() are implemented.

they also need to be subscribed on the IO thread.

As a rule of thumb you should switch thread when you KNOW that you need it.

In other words, you should use subscribeOn() in places where you know you are doing IO as close as possible to the actual job. ObserveOn instead is to be used when you know you need to obtain those results in the UI thread and that you might get in some other thread.

in your example there's absolutely no need to keep using observeOn(MAIN_THREAD), the only time you do need it (I suppose) is when you want to show the result.

A couple of other things:

This code

override fun createCompletable(data: Map<String, Any>?): Completable {
    val routeEntity = data?.get(PARAM_ROUTE)

    routeEntity?.let {
        return routeRepository.saveRoute(routeEntity as Route)
    } ?: return Completable.error(IllegalArgumentException("Argument @route must be provided."))
}

it is evaluated at the time when the method is called rather then when the completable  is subscribed.

In other words it break the Rx contract and compute data?.get(PARAM_ROUTE) when you call the method. If it is immutable there's no much difference, but if it can change value during execution it should be wrapped in a Completable.defer { }

Finally, here

        .flatMap { localID ->
            route.routeId = localID
            remoteRouteSource.saveRoute(route)
        }

you are modyfing something outside the chain (route.routeId = localID), this is called a side effect.

be careful with those kind of stuff, Rx is build in a way that is safer to be used with immutable objects.

I personally wouldn't mind too much as long as you understand what's going on and when it could create issues.


问:
How to convert/change date format from MM/DD/YYYY to Month Date, Year?
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

```<code>var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);
</code>```

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:

答: it's because there are many div's with same class name, which when $('.class-name').html() you do, it'll change all the div's with the same class name. you can try giving different classes or change the contents of json when you get the data from server.

Body:
I'm trying to convert/change my blog date from MM/DD/YYYY to Month Date, Year. For example, this date 11/12/2018 convert to November 12, 2018. Is there a way to do this correctly?

I've tried a code that suppose to work. However, the code converted/changed every blog posts' date to recent published posts' (date).

I tried this code:

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var data = $('.date-text').text();
var arr = data.split('/');
$(".date-text").html(months[parseInt(arr[0]) - 1] + " " + arr[1] + ", " + arr[2]);

and code converted all dates to recent published posts' date, which is now displayed as November 12, 2018 11.

Working editor: https://jsfiddle.net/s1b2fenk/

Website's image after date changed:


问:
angular and RxJS/switchMap
Hello I'm new to RxJS and I'm just getting to know operators. I want to show in console next 6 numbers in one-second time interval after button click. I want to reset that counter after next click using switchMap.

I've been trying to do with switchMap, but counter is not reseting.

```<code>obsSwitchMap: Observable<any>;

this.obsSwitchMap = of(null).pipe(
  switchMap(x => from([1, 2, 3]).pipe(
    concatMap(item => of(item).pipe(delay(300)))
    )
  )
)

onSwitchMapBtnClick() {
  this.obsSwitchMap.subscribe(x => {
    console.log(x)
  })
}
</code>```

Numbers are displaying independently of each other

答:
Although you want to learn, I think you should learn with the best practices from the start.

And it means you can do it very simply without switchMap :

const newInterval = () => rxjs.timer(0, 1000).pipe(
  rxjs.operators.map(nb => new Array(6).fill(nb).map((v, i) => v + i + 1))
);

let subscription;

function resetTimer() {
  subscription && subscription.unsubscribe();
  subscription = newInterval().subscribe(v => console.log(v));
}

resetTimer();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

<button onclick="resetTimer()">Reset timer</button></code>```

EDIT

Here is a switchMap example :

const horsemen = [
  { id: 1, name: 'Death' },
  { id: 2, name: 'Famine' },
  { id: 3, name: 'War' },
  { id: 4, name: 'Conquest' },
];

// Fake HTTP call of 1 second
function getHorseman(id) {
  return rxjs
    .of(horsemen.find(h => h.id === id))
    .pipe(rxjs.operators.delay(1000));
}

const query = document.querySelector('input');
const result = document.querySelector('div.result');

// Listen to input
rxjs.fromEvent(query, 'input')
  .pipe(
    rxjs.operators.map(event => +event.target.value), // Get ID
    rxjs.operators.switchMap(id => getHorseman(id)) // Get Horseman
  ).subscribe(horseman => {
    let content;
    if (horseman) content = `Horseman = ${horseman.name}`;
    else content = `Horseman unknown`;
    result.innerText = content;
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

<input type="text" placeholder="Input an ID here (1-4)">

<div class="result"></div></code>```

Title: angular and RxJS/switchMap

Body:
Hello I'm new to RxJS and I'm just getting to know operators. I want to show in console next 6 numbers in one-second time interval after button click. I want to reset that counter after next click using switchMap.

I've been trying to do with switchMap, but counter is not reseting.

obsSwitchMap: Observable<any>;

this.obsSwitchMap = of(null).pipe(
  switchMap(x => from([1, 2, 3]).pipe(
    concatMap(item => of(item).pipe(delay(300)))
    )
  )
)

onSwitchMapBtnClick() {
  this.obsSwitchMap.subscribe(x => {
    console.log(x)
  })
}

Numbers are displaying independently of each other

Body:
Although you want to learn, I think you should learn with the best practices from the start.

And it means you can do it very simply without switchMap :

const newInterval = () => rxjs.timer(0, 1000).pipe(
  rxjs.operators.map(nb => new Array(6).fill(nb).map((v, i) => v + i + 1))
);

let subscription;

function resetTimer() {
  subscription && subscription.unsubscribe();
  subscription = newInterval().subscribe(v => console.log(v));
}

resetTimer();

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

<button onclick="resetTimer()">Reset timer</button>

EDIT

Here is a switchMap example :

const horsemen = [
  { id: 1, name: 'Death' },
  { id: 2, name: 'Famine' },
  { id: 3, name: 'War' },
  { id: 4, name: 'Conquest' },
];

// Fake HTTP call of 1 second
function getHorseman(id) {
  return rxjs
    .of(horsemen.find(h => h.id === id))
    .pipe(rxjs.operators.delay(1000));
}

const query = document.querySelector('input');
const result = document.querySelector('div.result');

// Listen to input
rxjs.fromEvent(query, 'input')
  .pipe(
    rxjs.operators.map(event => +event.target.value), // Get ID
    rxjs.operators.switchMap(id => getHorseman(id)) // Get Horseman
  ).subscribe(horseman => {
    let content;
    if (horseman) content = `Horseman = ${horseman.name}`;
    else content = `Horseman unknown`;
    result.innerText = content;
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

<input type="text" placeholder="Input an ID here (1-4)">

<div class="result"></div>


问:
The selector "my-app" did not match any elements
The problem is when I run my app, it works fine. But when I refresh it, most of the time I get below msg.

The selector "my-app" did not match any elements

But the strange thing is that many times when I refresh my app it works  also.

So ultimately I have a strange behavior of my app and unable to figure this out.

Sometimes it works sometimes doesn't...

Any suggestion, can't come up with code???

Note : I don't have complex structure or components yet but simple implementation.

答:
Non of the above answers resolved my issue .This is how solve the same kind of error.
You shouldn't have more than one component as Bootstarp component .So, Bootstrap array should have only one component .By mistake I put 4 components in bootstrap array.I removed those 4 components from there and put in  entryComponents array(as shown in the code below).This helped me.</p>

```<code>@NgModule({
 declarations: [
AppComponent,
SanackBarBodyComponent,
SuccessNavBarComponent,
AlertNavBarComponent,
NormalNavBarComponent
],
entryComponents:[
SanackBarBodyComponent,
SuccessNavBarComponent,
AlertNavBarComponent,
NormalNavBarComponent
],

imports: [
BrowserModule,
BrowserAnimationsModule
],
 providers: [],
 bootstrap: [AppComponent
]
})
export class AppModule { }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Non of the above answers resolved my issue .This is how solve the same kind of error.
You shouldn't have more than one component as Bootstarp component .So, Bootstrap array should have only one component .By mistake I put 4 components in bootstrap array.I removed those 4 components from there and put in  entryComponents array(as shown in the code below).This helped me.

@NgModule({
 declarations: [
AppComponent,
SanackBarBodyComponent,
SuccessNavBarComponent,
AlertNavBarComponent,
NormalNavBarComponent
],
entryComponents:[
SanackBarBodyComponent,
SuccessNavBarComponent,
AlertNavBarComponent,
NormalNavBarComponent
],

imports: [
BrowserModule,
BrowserAnimationsModule
],
 providers: [],
 bootstrap: [AppComponent
]
})
export class AppModule { }


问:
How to set specific data from database in fields when launch through activity shortcut?
I am developing an android based note taking application with categories.I am  supposed to create notes shortcuts on home screen. When user click on the shortcut the relevant activity should be open and the specific data should be set in Edit-texts i.e Its title and description.I unable to understand the logic to do that.

I tried all possible solutions that come into my mind. I passed Id of note in shortcut intent but when it launch from shortcut the fields are still empty.
This is my snippet of code to create shortcut:

Function to create shortcut:

```<code> private void createShortcutOfActivity() {

        Intent shortcutIntent = new Intent(getApplicationContext(),
                TextNotes.class);
        shortcutIntent.setAction(Intent.ACTION_MAIN);

        Intent addIntent = new Intent();
        addIntent
                .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, editTitle.getText().toString());
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(getApplicationContext(),
                        R.mipmap.ic_launcher));
        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        addIntent.putExtra("duplicate", false);  //may it's already there so   don't duplicate
        getApplicationContext().sendBroadcast(addIntent);
    }
</code>```

This function is called when user click on option to create shortcut.

In Menifest use permission:

```<code><uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
</code>```

Also add intent filter and exported property in non launching activity:

```<code><activity
            android:name=".TextNotes"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>
</code>```

The activity receive data from intent when open a note from another activity:

```<code>Intent newInt=getIntent();
        isDoubleClicked=newInt.getBooleanExtra("Chk",false);
        Cat=newInt.getStringExtra("Category");
        Id=newInt.getIntExtra("Id",0);

        String title=newInt.getStringExtra("Message");
        String description=newInt.getStringExtra("Message2");
        check=newInt.getStringExtra("Check");

        editTitle.setText(title);
        editText.setText(description);
</code>```

I also tried to use this id in the shortcut intent of the function but having no change in result.

```<code>shortcutIntent.putExtra("key_primary",Id);
</code>```

I want to keep the data when open using shortcut.For example for different note shortcut the rspected data should be set in fields just like in whatsapp the chat shortcuts of different contacts can be craeted . But unfortunately I am unable to understand that how should it be done because everytime I open using shortcut its fields become empty. Where should I pass id and how to set data when it launch from shortcut.

答:
If you use shortcutIntent.putExtra("key_primary",Id); then you need to retrieve it using

```<code>Id=newInt.getIntExtra("key_primary",0);
</code>```

That is the first parameter (key_primary) is the key that is used to identify the specific Intent Extra. Thus, the key value must match the key value used when putting the Intent Extra for a value (other than the default) to be retrieved.

As such coding Id=newInt.getIntExtra("Id",0); without using the matching/paired shortcutIntent.putExtra("Id",Id); will always result in 0 as the Intent Extra doesn't exist so the default value is returned.

Body:
I am developing an android based note taking application with categories.I am  supposed to create notes shortcuts on home screen. When user click on the shortcut the relevant activity should be open and the specific data should be set in Edit-texts i.e Its title and description.I unable to understand the logic to do that.

I tried all possible solutions that come into my mind. I passed Id of note in shortcut intent but when it launch from shortcut the fields are still empty.
This is my snippet of code to create shortcut:

Function to create shortcut:

 private void createShortcutOfActivity() {

        Intent shortcutIntent = new Intent(getApplicationContext(),
                TextNotes.class);
        shortcutIntent.setAction(Intent.ACTION_MAIN);

        Intent addIntent = new Intent();
        addIntent
                .putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, editTitle.getText().toString());
        addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(getApplicationContext(),
                        R.mipmap.ic_launcher));
        addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        addIntent.putExtra("duplicate", false);  //may it's already there so   don't duplicate
        getApplicationContext().sendBroadcast(addIntent);
    }

This function is called when user click on option to create shortcut.

In Menifest use permission:

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

Also add intent filter and exported property in non launching activity:

<activity
            android:name=".TextNotes"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

The activity receive data from intent when open a note from another activity:

Intent newInt=getIntent();
        isDoubleClicked=newInt.getBooleanExtra("Chk",false);
        Cat=newInt.getStringExtra("Category");
        Id=newInt.getIntExtra("Id",0);

        String title=newInt.getStringExtra("Message");
        String description=newInt.getStringExtra("Message2");
        check=newInt.getStringExtra("Check");

        editTitle.setText(title);
        editText.setText(description);

I also tried to use this id in the shortcut intent of the function but having no change in result.

shortcutIntent.putExtra("key_primary",Id);

I want to keep the data when open using shortcut.For example for different note shortcut the rspected data should be set in fields just like in whatsapp the chat shortcuts of different contacts can be craeted . But unfortunately I am unable to understand that how should it be done because everytime I open using shortcut its fields become empty. Where should I pass id and how to set data when it launch from shortcut.

Body:
If you use shortcutIntent.putExtra("key_primary",Id); then you need to retrieve it using

Id=newInt.getIntExtra("key_primary",0);

That is the first parameter (key_primary) is the key that is used to identify the specific Intent Extra. Thus, the key value must match the key value used when putting the Intent Extra for a value (other than the default) to be retrieved.

As such coding Id=newInt.getIntExtra("Id",0); without using the matching/paired shortcutIntent.putExtra("Id",Id); will always result in 0 as the Intent Extra doesn't exist so the default value is returned.


问:
SQL Retrieve data from first table based on search criteria in second table
i Have 2 tables i want to get data from the first table based on where condition applied on the second table.

```<code>PHARMASTOCK(1)      Pharma Products(2)
ID                  ProductID
ProductID           GenericName
TradeName           TradeName
MRP                 Supplier
Rate                Manufacturer
Stock               PurchasePTR
Batch               UnitRate
Expiry              MRP
StockSection
</code>```

This is the SQL stored procedure that i have written but it is not working
as expected!

```<code>@StockSupplier varchar(50), @StockManufacturer Varchar(50)
AS

SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
    Full JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like + @StockSupplier + '%' and Manufacturer  like + @StockManufacturer + '%'
order by Manufacturer asc
</code>```

答:
```<code>SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
INNER JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like  @StockSupplier + '%' and Manufacturer  like  @StockManufacturer + '%'
order by Manufacturer asc
</code>```

Body:
i Have 2 tables i want to get data from the first table based on where condition applied on the second table.

PHARMASTOCK(1)      Pharma Products(2)
ID                  ProductID
ProductID           GenericName
TradeName           TradeName
MRP                 Supplier
Rate                Manufacturer
Stock               PurchasePTR
Batch               UnitRate
Expiry              MRP
StockSection

This is the SQL stored procedure that i have written but it is not working
as expected!

@StockSupplier varchar(50), @StockManufacturer Varchar(50)
AS

SELECT  PharmaStock.ProductID,PharmaStock.TradeName,PharmaStock.MRP,Rate,Batch,Expiry,StockSection,Stock,Supplier,Manufacturer
from PharmaStock
    Full JOIN PharmaProducts ON PharmaStock.ProductID = PharmaProducts.ProductID
where Supplier  like + @StockSupplier + '%' and Manufacturer  like + @StockManufacturer + '%'
order by Manufacturer asc


问:
How Android-studio layout preview tool deal with '@+id' and '@id' exactly?
Surely I used @id after declared @+id and my App runs well with my code, what confused me is that when I preview my xml files, the reference @id seems not work at all and the layout was in my library project not main,which was dependenced by aar.

If I change the layout_below="@id/tv_1 to layout_below="@+id/tv_1, the preview will work well.
Or I declare it in id.xml files id my library proj,and use @id/tv_1, preview works well too.

all solutions above seems make no difference after I run my main project,they all works well. I just can't understand why preview has problems,and how the '+' works when preview a xml file.

Examples:

```<code><RelativeLayout ..>
<TextView android:id="@+id/tv_1" ../>

<EditText android:id="@+id/et_1"
android:layout_below="@id/tv_1" ../>

</RelativeLayout>
</code>```

答:
@+id creates a new entry to R.java class which stores and identify assets.

@id simply refers to the previous created assest.

Body:
Surely I used @id after declared @+id and my App runs well with my code, what confused me is that when I preview my xml files, the reference @id seems not work at all and the layout was in my library project not main,which was dependenced by aar.

If I change the layout_below="@id/tv_1 to layout_below="@+id/tv_1, the preview will work well.
Or I declare it in id.xml files id my library proj,and use @id/tv_1, preview works well too.

all solutions above seems make no difference after I run my main project,they all works well. I just can't understand why preview has problems,and how the '+' works when preview a xml file.

Examples:

<RelativeLayout ..>
<TextView android:id="@+id/tv_1" ../>

<EditText android:id="@+id/et_1"
android:layout_below="@id/tv_1" ../>

</RelativeLayout>


问:
How to associate a Class with more than one behavior with other Class?
I have some objects that need two types of behavior at the same time when are associated with a Game Class. How is the best way to do this? I'm not seeing any of the GoF Patterns here to help but maybe i'm just with my brain overloaded.

```<code>interface Actor {}

class Man implements Actor {}

class Woman implements Actor {}

class Game {
    private Map<Actor> actors;
}
</code>```

How to include Player, Referee or LineJudge behavior to this code?

Example:

Game 1, Actor 1 Woman and Referee, Actor 2 Woman and Player

Game 2, Actor 1 Woman and Player, Actor 2 Man and Player

Game 3, Actor 1 Man and Player, Actor 2 Man and Referee, Actor 3 Woman and LineJudge

...

答:
There are several possible solutions. I will give the options I think will most likely match your requirements, but there are more possible solutions. What is best in your situation, depends on the exact functionality you need to implement.

One collection in Game, two attributes in Actor

You may define a class Actor with two attributes, one of type Person, which can be Man or Woman and another of type Participant, which can be Player, Referee or LineJudge.

Three collections in Game

Instead of one, you may define three collections of Actors in class Game, one for each role an actor plays in the game. Well, if there's only one Referee, then that is not really a collection.

Body:
I have some objects that need two types of behavior at the same time when are associated with a Game Class. How is the best way to do this? I'm not seeing any of the GoF Patterns here to help but maybe i'm just with my brain overloaded.

interface Actor {}

class Man implements Actor {}

class Woman implements Actor {}

class Game {
    private Map<Actor> actors;
}

How to include Player, Referee or LineJudge behavior to this code?

Example:

Game 1, Actor 1 Woman and Referee, Actor 2 Woman and Player

Game 2, Actor 1 Woman and Player, Actor 2 Man and Player

Game 3, Actor 1 Man and Player, Actor 2 Man and Referee, Actor 3 Woman and LineJudge

...


问:
Calling a phone number in swift
I'm trying to call a number not using specific numbers but a number that is being called in a variable or at least tell it to pull up the number in your phone. This number that is being called in a variable is a number that I retrieved by using a parser or grabbing from a website sql. I made a button trying to call the phone number stored in the variable with a function but to no avail. Anything will help thanks!</p>

```<code>    func callSellerPressed (sender: UIButton!){
 //(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)

 // This is the code I'm using but its not working
 UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)

        }
</code>```

答:
```<code>let formatedNumber = phone.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: "")
print("calling \(formatedNumber)")
let phoneUrl = "tel://\(formatedNumber)"
let url:URL = URL(string: phoneUrl)!
UIApplication.shared.openURL(url)
</code>```

Title: Calling a phone number in swift

Body:
I'm trying to call a number not using specific numbers but a number that is being called in a variable or at least tell it to pull up the number in your phone. This number that is being called in a variable is a number that I retrieved by using a parser or grabbing from a website sql. I made a button trying to call the phone number stored in the variable with a function but to no avail. Anything will help thanks!

    func callSellerPressed (sender: UIButton!){
 //(This is calls a specific number)UIApplication.sharedApplication().openURL(NSURL(string: "tel://######")!)

 // This is the code I'm using but its not working
 UIApplication.sharedApplication().openURL(NSURL(scheme: NSString(), host: "tel://", path: busPhone)!)

        }


问:
How to edit jupyter lab theme
As described in a previous question, it is now possible to edit the Jupyter Lab theme. However, this theme has a few issues for me personally. For example, it makes plot axes hard to read, since their default color is black. Other users have had similar problems. Consequently, I would like to fork the existing theme and make plot display cells a light grey colour. How does one do this?

I tried to find the corresponding .css file, but all I could find was /usr/local/share/jupyter/lab/themes/@jupyterlab/theme-dark-extension/. I understand that I could edit the index.css to achieve what I want, but how do I instead fork that theme and edit it? How do I let Jupyter Lab know about my custom theme?

答:
we are using version 0.35.x ...
the following steps worked for me ... it will create a clone of the light theme, would install it in jupyter lab and you would be able to select that from settings menu. you can customize this theme, build it and have the effect in jupyter lab

install miniconda from here https://docs.conda.io/en/latest/miniconda.html (chose python3.7 one)

open Anaconda Terminal, [in windows goto search type Anaconda, select the terminal]

then run this conda create -n jupyterlab-ext -c conda-forge --override-channels nodejs jupyterlab cookiecutter git

clone jupyterlab from here https://github.com/jupyterlab/jupyterlab.git

switch branch with git checkout 0.35.x

then    jlpm install
jlpm build
npm run create:theme

copy the theme folder to your chosen local theme folder for extension development. Replace tsconfig.json content with the following

{ "compilerOptions":
          { "declaration": true,
           "lib": ["es2015", "dom"],
            "module": "commonjs",
            "moduleResolution": "node",
            "noEmitOnError": true,
            "noUnusedLocals": true,
            "outDir": "lib",
            "rootDir": "src",
            "strict": true,
            "strictNullChecks": false,
             "target": "es2015",
             "types": []
           },
          "include": ["src/*"]
        }

[created by the steps here https://jupyterlab.readthedocs.io/en/stable/developer/xkcd_extension_tutorial.html#xkcd-extension-tutorial]

inside the theme folder ..

run the following commands jlpm install, jlpm run build , jlpm run build:webpack

open another conda terminal, there go to repo folder and run conda activate jupyterlab-ext then jupyter labextension install .

in a conda terminal conda activate jupyterlab-ext then, jupyter lab --watch

For version 1.0 , this cookie cutter could be used ... https://github.com/jupyterlab/theme-cookiecutter

Title: How to edit jupyter lab theme


问:
Java Hashtable .containsKey(String key) is returning true even when the strings and hashcodes are different... How?
I'm currently having some issues with my Hashtable in java, where FEightPuzzle is a class which I've created.

Inside my class I have a String which is storing the key for each instance. Now during my program when I check inside the Hashtable for duplicate instances I sometimes "find" some when really the found ones are different.

Take for example when I call bol.containsKey(current.key) where bol is a HT and current is an FEightPuzzle.

When this is true I check the values of the keys and they are

```<code>current.key =
"8 14 11 0 6 12 13 1 10 4 5 9 15 2 3 7"

bol.get(current.key).key =
"12 8 4 0 13 9 5 1 14 10 6 2 15 11 7 3"
</code>```

with values

```<code>current.key.hashCode() = -950607924

bol.get(current.key).key.hashCode() = -1856769042
</code>```

I'm sorry to bother you but this problem is really getting to me, and it was the last thing I expected tonight to be honest (don't you love that)... Any hints or answers would be greatly appreciated!

答:
I've reread your question, and as I understand it you have the following problem:

You do

```<code>bol.containsKey(current.key)
</code>```

to check if current is already in bol.

When it returns true, you expect that the value mapped to by current.key should indeed be current, but as your hash-codes indicate, it's not.

The problem is likely to be one of the following:

You didn't put the puzzle object in the hashtable correctly in the first place.

You should do

```<code>bol.put(somePuzzle.key, somePuzzle)
</code>```

You changed the key when the puzzle was in the map. THIS IS NOT ALLOWED.

After you've added the entry in the map, you may not change the key without removing / reinserting the mapping.

The Hashtable will look for the object, based on the key you provided when inserting.

You've accidentally provided the same key for multiple different puzzle objects (in which case, one put will override a previous one)

One suggestion would be to let FEightPuzzle override hashCode and equals and use a HashSet instead of a Hashtable.

Body:
I'm currently having some issues with my Hashtable in java, where FEightPuzzle is a class which I've created.

Inside my class I have a String which is storing the key for each instance. Now during my program when I check inside the Hashtable for duplicate instances I sometimes "find" some when really the found ones are different.

Take for example when I call bol.containsKey(current.key) where bol is a HT and current is an FEightPuzzle.

When this is true I check the values of the keys and they are

current.key =
"8 14 11 0 6 12 13 1 10 4 5 9 15 2 3 7"

bol.get(current.key).key =
"12 8 4 0 13 9 5 1 14 10 6 2 15 11 7 3"

with values

current.key.hashCode() = -950607924

bol.get(current.key).key.hashCode() = -1856769042

I'm sorry to bother you but this problem is really getting to me, and it was the last thing I expected tonight to be honest (don't you love that)... Any hints or answers would be greatly appreciated!

Body:
I've reread your question, and as I understand it you have the following problem:

You do

bol.containsKey(current.key)

to check if current is already in bol.

When it returns true, you expect that the value mapped to by current.key should indeed be current, but as your hash-codes indicate, it's not.

The problem is likely to be one of the following:

You didn't put the puzzle object in the hashtable correctly in the first place.

You should do

bol.put(somePuzzle.key, somePuzzle)

You changed the key when the puzzle was in the map. THIS IS NOT ALLOWED.

After you've added the entry in the map, you may not change the key without removing / reinserting the mapping.

The Hashtable will look for the object, based on the key you provided when inserting.

You've accidentally provided the same key for multiple different puzzle objects (in which case, one put will override a previous one)

One suggestion would be to let FEightPuzzle override hashCode and equals and use a HashSet instead of a Hashtable.


问:
Datatables issue with invalid JSON primitive draw
I have seen this question: Jquery Datatables Error: Invalid JSON primitive: draw

It could not help me solve the issue.

I am using Datatables, I get an error for the AJAX call. Here is the JS code:

```<code>function loadparttrackings() {
    // Call the datatable on the overview div and link back to server side
    $('#overviewFilteredPartTrackings').DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "orderMulti": false,
        "ajax": {
            "url": window.applicationPath + "/Launches/GetFilteredPartTrackingRecords",
            "type": "POST",
            "data": function (d) {
                d.partNumber = $('#FilterPartNumber').val();
                d.segment = $('#FilterSegment').val();
                d.commodity = $('#FilterCommodity').val();
            }
        },
        // This is needed to hide the ID field and make it not searchable
        "columnDefs":
        [{
                "targets": [1],
                "visible": false,
                "searchable": false
        }],
        "columns": [

            {
                "render": function (data, type, full, meta) { return '<a class="btn btn-info" href="#" onclick=EditRecord("' + row.ID + '"); >Edit</a>'; }
            },
            // more columns omitted
    });
}
</code>```

The issue came up when I added the "type": "POST", to the AJAX part of the function. Now I get the error invalid json primitive draw.

Here is the code for the controller method:

```<code>[HttpPost]
    public ActionResult GetFilteredPartTrackingRecords(DataTableAjaxPostModel model, string partNumber, string commodity, string segment)
    {
        // Getting the data and such

        return Json(new
        {
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = 1000, // TODO CHANGE
            recordsFiltered = 1000, // TODO CHANGE
            data = result
        });
    }
</code>```

And here is the code for the model that I use:

```<code>public class DataTableAjaxPostModel
{
    // properties are not capital due to json mapping
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Column> columns { get; set; }
    public Search search { get; set; }
    public List<Order> order { get; set; }
}

public class Column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public Search search { get; set; }
}

public class Search
{
    public string value { get; set; }
    public string regex { get; set; }
}

public class Order
{
    public int column { get; set; }
    public string dir { get; set; }
}
</code>```

答:
Try this

```<code>"data":JSON.stringify({

            partNumber: $('#FilterPartNumber').val();
            segment: $('#FilterSegment').val();
            commodity: $('#FilterCommodity').val();
   })
</code>```

And add the contentType: "application/json; charset=UTF-8" in ajax options.

Body:
I have seen this question: Jquery Datatables Error: Invalid JSON primitive: draw

It could not help me solve the issue.

I am using Datatables, I get an error for the AJAX call. Here is the JS code:

function loadparttrackings() {
    // Call the datatable on the overview div and link back to server side
    $('#overviewFilteredPartTrackings').DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "orderMulti": false,
        "ajax": {
            "url": window.applicationPath + "/Launches/GetFilteredPartTrackingRecords",
            "type": "POST",
            "data": function (d) {
                d.partNumber = $('#FilterPartNumber').val();
                d.segment = $('#FilterSegment').val();
                d.commodity = $('#FilterCommodity').val();
            }
        },
        // This is needed to hide the ID field and make it not searchable
        "columnDefs":
        [{
                "targets": [1],
                "visible": false,
                "searchable": false
        }],
        "columns": [

            {
                "render": function (data, type, full, meta) { return 'Edit'; }
            },
            // more columns omitted
    });
}

The issue came up when I added the "type": "POST", to the AJAX part of the function. Now I get the error invalid json primitive draw.

Here is the code for the controller method:

[HttpPost]
    public ActionResult GetFilteredPartTrackingRecords(DataTableAjaxPostModel model, string partNumber, string commodity, string segment)
    {
        // Getting the data and such

        return Json(new
        {
            // this is what datatables wants sending back
            draw = model.draw,
            recordsTotal = 1000, // TODO CHANGE
            recordsFiltered = 1000, // TODO CHANGE
            data = result
        });
    }

And here is the code for the model that I use:

public class DataTableAjaxPostModel
{
    // properties are not capital due to json mapping
    public int draw { get; set; }
    public int start { get; set; }
    public int length { get; set; }
    public List<Column> columns { get; set; }
    public Search search { get; set; }
    public List<Order> order { get; set; }
}

public class Column
{
    public string data { get; set; }
    public string name { get; set; }
    public bool searchable { get; set; }
    public bool orderable { get; set; }
    public Search search { get; set; }
}

public class Search
{
    public string value { get; set; }
    public string regex { get; set; }
}

public class Order
{
    public int column { get; set; }
    public string dir { get; set; }
}

Body:
Try this

"data":JSON.stringify({

            partNumber: $('#FilterPartNumber').val();
            segment: $('#FilterSegment').val();
            commodity: $('#FilterCommodity').val();
   })

And add the contentType: "application/json; charset=UTF-8" in ajax options.


问:
Retrying firebase token in Swift
I come bringing a query about Firebase in Swift. My app configures Firebase and thus gets the firebase token upon launching. I store the token with no issues and go ahead.

But... What happens if the user launches the app when his device is offline? The app tries to retrieve the token, but fails because there's no internet connection. It tries up to five time and then stops trying.
The app is also locked in the login screen because to be logged you need to have Internet.

Imagine if after the five tries, the device finally gets a connection, and the user logins and enters the app. But I don't have a firebase token and I can't send notifications to the user until he restarts the app!

Can I somehow retry the firebase registration if the user logins without a token?

Thanks a lot in advance.

答:
After googling more further, I've found that calling InstanceID.instanceID().token() does trigger a new retry to get a FCM token if your current token is empty, and returns your current token if you have one.
I've added that call when the user successfully logins, so that the app can atleast try to get a FCM token again.

Title: Retrying firebase token in Swift


问:
Match Multiple Columns In Two Files - Output Only Those That Match Fully
File 1:

```<code>1075908|2178412|brown_eyeshorty@att.net|Claude|Desmangles
175908|2178412|naim.kazi@webtv.net|Naim|Kazi
175972|212946872418|gil_maynard@hotmail.com|Munster|Herman
175972|212946872418|meghanj4@lycos.com|Meghan|Judge
175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
176086|2480881|lourdsneil@gmail.com|Lourds|Herman
</code>```

File 2:

```<code>89129090|Sadiq|Islam
212946872418|Anna|Balint
255875|Charlene|Johnson
89234902|Bob|Brown
09123789|Fabio|Vanetti
</code>```

I would like to extract lines where ALL values match on the following basis:

Column 2 in File 1 matches with Column 1 in File 2.

Column 4 in File 1 matches with Column 2 in File 2.

Column 5 in File 1 matches with Column 3 in File 2.

The expected output for the example is:

```<code>175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
</code>```

The two inputs I'm working with are both very large (11Gb and 3Gb respectively).

The only potential (messy) workaround I can think of is to combine the values to be joined into a single additional column and then use Join (I'm very new to this).

答:
Could you please try following.

```<code>awk -F'|' '
FNR==NR{
    a[$2,$4,$5]=(a[$2,$4,$5]?a[$2,$4,$5] ORS:"")$0
    next
}
(($1,$2,$3) in a){
    print a[$1,$2,$3]
}' Input_file1   Input_file2
</code>```

Output will be as follows.

```<code>175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
</code>```

Body:
File 1:

1075908|2178412|brown_eyeshorty@att.net|Claude|Desmangles
175908|2178412|naim.kazi@webtv.net|Naim|Kazi
175972|212946872418|gil_maynard@hotmail.com|Munster|Herman
175972|212946872418|meghanj4@lycos.com|Meghan|Judge
175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson
176086|2480881|lourdsneil@gmail.com|Lourds|Herman

File 2:

89129090|Sadiq|Islam
212946872418|Anna|Balint
255875|Charlene|Johnson
89234902|Bob|Brown
09123789|Fabio|Vanetti

I would like to extract lines where ALL values match on the following basis:

Column 2 in File 1 matches with Column 1 in File 2.

Column 4 in File 1 matches with Column 2 in File 2.

Column 5 in File 1 matches with Column 3 in File 2.

The expected output for the example is:

175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson

The two inputs I'm working with are both very large (11Gb and 3Gb respectively).

The only potential (messy) workaround I can think of is to combine the values to be joined into a single additional column and then use Join (I'm very new to this).

Body:
Could you please try following.

awk -F'|' '
FNR==NR{
    a[$2,$4,$5]=(a[$2,$4,$5]?a[$2,$4,$5] ORS:"")$0
    next
}
(($1,$2,$3) in a){
    print a[$1,$2,$3]
}' Input_file1   Input_file2

Output will be as follows.

175972|212946872418|quenchia@gmail.com|Anna|Balint
176046|255875|keion@netscape.net|Charlene|Johnson
176046|255875|keion112@netscape.net|Charlene|Johnson


问:
Protractor typescript finding first element from list of elements
Here I am trying to locate it by using xpath as .//div[@class="pq-select-menu"]//span[contains(text(), "filecaseone")]/parent::label/input
 and code snippet is as following

<input type="checkbox">Select All

<input type="text" class="pq-select-search-input" autocomplete="off">

<input type="checkbox">abc1203

<input type="checkbox">abc123

<input type="checkbox">CRdemoCase

<input type="checkbox">exportCase

<input type="checkbox">hdfhdfhdfdfgdfgdfgd

<input type="checkbox">Quinccasenewone1002

<input type="checkbox">Quinccasenewone1003

<input type="checkbox">Quinccasenewone1004

<input type="checkbox">Quinccasenewone1006

<input type="checkbox">Quinccasenewone1007

<input type="checkbox">Quinccasenewone1100

<input type="checkbox">Quinccasenewone1101
<input type="checkbox">testCase

```
</div>
</div>
</p>

<p>In typescript protractor I am finding multiple elements with same label ,how i can find first one </p>

<p>I tried loop as well as .first</p>

```let inputEle = element.all(by.xpath('.//div[@class="pq-select-menu"]//span[contains(text(), "filecaseone")]/parent::label/input'));
for (i=0; i < inputEle.count; i++){
  valueInList= await inputEle.[0].isSelected());
}

element.all(locator).first()

let val=await inputEle.first().isSelected();
```

答:
Try the below

```<code>const list = element.all(by.css('span.pq-left-input'));

await ele.get(0);
</code>```

Hope it helps you

Body:
Here I am trying to locate it by using xpath as .//div[@class="pq-select-menu"]//span[contains(text(), "filecaseone")]/parent::label/input
 and code snippet is as following

<input type="checkbox">Select All

<input type="text" class="pq-select-search-input" autocomplete="off">

<input type="checkbox">abc1203

<input type="checkbox">abc123

<input type="checkbox">CRdemoCase

<input type="checkbox">exportCase

<input type="checkbox">hdfhdfhdfdfgdfgdfgd

<input type="checkbox">Quinccasenewone1002

<input type="checkbox">Quinccasenewone1003

<input type="checkbox">Quinccasenewone1004

<input type="checkbox">Quinccasenewone1006

<input type="checkbox">Quinccasenewone1007

<input type="checkbox">Quinccasenewone1100

<input type="checkbox">Quinccasenewone1101
<input type="checkbox">testCase

In typescript protractor I am finding multiple elements with same label ,how i can find first one

I tried loop as well as .first

let inputEle = element.all(by.xpath('.//div[@class="pq-select-menu"]//span[contains(text(), "filecaseone")]/parent::label/input'));
for (i=0; i < inputEle.count; i++){
  valueInList= await inputEle.[0].isSelected());
}

element.all(locator).first()

let val=await inputEle.first().isSelected();

Body:
Try the below

const list = element.all(by.css('span.pq-left-input'));

await ele.get(0);

Hope it helps you


问:
Unable to create an object of type '[DBContext's Name]'. For the different patterns supported at design time
I'm following one of Mosh Hamedani Course on ASP.NET MVC in Udemy.

I came across one error while designing my Database using code-first (Entity Framework).

At first, I got the error of " No DbContext was found in assembly". After resolving this problem another one surged from nowhere.

The image below will show you the error found while adding a migration. I've already searched for the same error but in vain. I'm struggling for the past two hours but nothing is solved till now.

Please, someone, help me. Thanks

unable to create an object of type 'Vidly_Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Similar problem after adding own DbContext constructor with (2) parameters. App was ok, but migrations stopped working.
Fixed by 1st updating EF (3.1.5 used for strange reason when working with 5) using info from Dotnet tool @xspdf and replacing mentioned constructor by method + hardcoded default connection string if not set.

```<code>dotnet tool update --global dotnet-ef

// following command show the most during migration build/run in cmd
// mind current dir is Migrations folder of (VS) startup project here
dotnet ef --startup-project ../ --verbose migrations add test
</code>```

3.1.5 & context activation Error

```<code>The Entity Framework tools version '3.1.5' is older than that of the runtime '5.0.0'. Update the tools for the latest features and bug fixes.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly '...'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext '...Context'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type '...Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate '...'. (my additional parameter)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type '...Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
</code>```

答:
I ran into this issue when using EF Core code-first migrations in a .NET Core 3 solution that contained both an MVC project and a Blazor project.

If I have the solution's startup project set to the Blazor project I get the error when using add-migration, but I don't if I have the startup project set to the MVC project.

From reading the documentation page linked to by the error message and comparing the code in the startup.cs files for both projects I'm not sure why that would be, but temporarily switching the startup project to the MVC project fixes it for me.

Body:
I'm following one of Mosh Hamedani Course on ASP.NET MVC in Udemy.

I came across one error while designing my Database using code-first (Entity Framework).

At first, I got the error of " No DbContext was found in assembly". After resolving this problem another one surged from nowhere.

The image below will show you the error found while adding a migration. I've already searched for the same error but in vain. I'm struggling for the past two hours but nothing is solved till now.

Please, someone, help me. Thanks

unable to create an object of type 'Vidly_Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Similar problem after adding own DbContext constructor with (2) parameters. App was ok, but migrations stopped working.
Fixed by 1st updating EF (3.1.5 used for strange reason when working with 5) using info from Dotnet tool @xspdf and replacing mentioned constructor by method + hardcoded default connection string if not set.

dotnet tool update --global dotnet-ef

// following command show the most during migration build/run in cmd
// mind current dir is Migrations folder of (VS) startup project here
dotnet ef --startup-project ../ --verbose migrations add test

3.1.5 & context activation Error

The Entity Framework tools version '3.1.5' is older than that of the runtime '5.0.0'. Update the tools for the latest features and bug fixes.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider in assembly '...'...
Finding Microsoft.Extensions.Hosting service provider...
No static method 'CreateHostBuilder(string[])' was found on class 'Program'.
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext '...Context'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type '...Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
 ---> System.InvalidOperationException: Unable to resolve service for type 'System.String' while attempting to activate '...'. (my additional parameter)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_4.<FindContextTypes>b__13()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type '...Context'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728


问:
VHDL equivalent to Verilog "10'h234"
I just need to know how to translate constant values from Verilog to VHDL. I wonder if I could still indicate the range and if it is hex, oct, binary, etc., just like in Verilog:
14'h1 -> I do not want to type anything like X"00000000000001"
Thanks!</p>

答:
The answer depends on what VHDL standard you use.

Before VHDL 2008, hex constants could only be directly expressed when the number of binary digits was a multiple of 4 (the length of an hex nibble).

x"0001" is a 16-bit constant.

With VHDL 2008, you can specify the bit length of the constant:

x"0001" is still a 16-bit constant, whereas 14x"0001" is what you want: a 14 bit constant.

If you are working with an earlier standard, you must work around this limitation like this:

std_logic_vector(resize("1", 14)) or (0 => '1', others => '0')

Title: VHDL equivalent to Verilog "10'h234"


问:
Comparing two columns and if it matches both the columns should be highlighted
I have two columns J and L.

If the value of J column matches with the corresponding value of L column, both the cells should be highlighted in red.

I am new to this Excel. I am not able to develop this macro.

I tried the below code but it is highlighting J, K and L column if it matches I want only the J and K column to be highlighted and also this macro should start checking from J11 and L11

```<code>Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1 & ":L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub
</code>```

答:
check if is this what u want

```<code>Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J11" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 10 & ":J" & i + 10).Interior.Color = vbRed
                .Range("L" & i + 10 & ":L" & i + 10).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub
</code>```

it starts checking from line 11

Body:
I have two columns J and L.

If the value of J column matches with the corresponding value of L column, both the cells should be highlighted in red.

I am new to this Excel. I am not able to develop this macro.

I tried the below code but it is highlighting J, K and L column if it matches I want only the J and K column to be highlighted and also this macro should start checking from J11 and L11

Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J2" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 1 & ":L" & i + 1).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub

Body:
check if is this what u want

Sub test()
    Dim LastRow As Long, i As Long
    Dim arr As Variant

    With ThisWorkbook.Worksheets("Sheet1")
        LastRow = .Cells(.Rows.Count, "J").End(xlUp).Row
        arr = .Range("J11" & ":L" & LastRow)

        For i = LBound(arr) To UBound(arr)
            If arr(i, 1) = arr(i, 3) Then
                .Range("J" & i + 10 & ":J" & i + 10).Interior.Color = vbRed
                .Range("L" & i + 10 & ":L" & i + 10).Interior.Color = vbRed
            End If
        Next i
    End With
End Sub

it starts checking from line 11


问:
Using encoded target value
I have a pandas dataframe and one column of it is my target value which is categorical.

I used get_dummies for encoding my target value. Now, I have my encoded target value in 5 encoded column because my target value has 5 categories.

My question is that how can I consider all of these 5 columns in linear regression method?

I have x_dummies as my dependent values dataframe and y_dummies as my target value data frame with 5 columns of encoded values.

I have never had a target value in more than one column!
Is this correct?

Link to Assingment:
https://www.cs.waikato.ac.nz/~eibe/pubs/ordinal_tech_report.pdf

regr = linear_model.LinearRegression()
regr.fit( x_dummies_training, y_dummies_training)
```

答:
If your target is categorical you may want to use a classifier , not a regressor.

You may read this article to understand the difference if you want .

So in your case you would want to use a classifier and keep your y target as one variable instead of one hot encoding it.

If you want a mathematical model that's easy to interpret ( i guessed that from your use of Linear Regression) you may want a multinomial logistic regression:

```<code>from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0, solver='lbfgs',
    multi_class='multinomial').fit(X, y)
</code>```

You may want to check the sklearn documentation .

You could also try the wildly popular boosting trees methods that should give you better results : check catboost as an example .

Title: Using encoded target value

Body:
If your target is categorical you may want to use a classifier , not a regressor.

You may read this article to understand the difference if you want .

So in your case you would want to use a classifier and keep your y target as one variable instead of one hot encoding it.

If you want a mathematical model that's easy to interpret ( i guessed that from your use of Linear Regression) you may want a multinomial logistic regression:

from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(random_state=0, solver='lbfgs',
    multi_class='multinomial').fit(X, y)

You may want to check the sklearn documentation .

You could also try the wildly popular boosting trees methods that should give you better results : check catboost as an example .


问:
user defined exceptions
Are there user-defined exceptions in tsql ?</p>

答:
You can define your own, custom error messages and use those when calling RAISERROR

SQL Server doesn't really have a concept of "exceptions" per se - but you can raise your own customer errors as shown above.

Title: user defined exceptions


问:
How to get columns that are repeating in different tables in a database inside SQL Server
I've a database with huge number of tables. From these tables I want to list out all the column names that are appearing in more than one table along with the their table names.

I tried google search to find any suitable article that can explain how to achieve the results that I've described in the problem section.

No code snippets

No error messages.

答:
The query below will return the column name along with the number of its occurences in the current database tables:

```<code>SELECT c.NAME AS 'ColumnName', COUNT(*) AS Occurences
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
GROUP BY c.NAME
HAVING COUNT(*) > 1
</code>```

This query below will help to identify the specific column name is placed in which tables:

```<code>-- Find column name in all the tables
SELECT c.NAME AS 'ColumnName', t.NAME AS 'TableName'
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.NAME LIKE '%columnname%' -- to be searchable column name
ORDER BY TableName, ColumnName;
</code>```

Body:
The query below will return the column name along with the number of its occurences in the current database tables:

SELECT c.NAME AS 'ColumnName', COUNT(*) AS Occurences
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
GROUP BY c.NAME
HAVING COUNT(*) > 1

This query below will help to identify the specific column name is placed in which tables:

-- Find column name in all the tables
SELECT c.NAME AS 'ColumnName', t.NAME AS 'TableName'
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.NAME LIKE '%columnname%' -- to be searchable column name
ORDER BY TableName, ColumnName;


问:
Sort the rows of a data frame
I have the following data frame (adjusted_RFC_df):

```<code>     Node               Feature Indicator  Scaled     Class    Direction True_False
0       0                   km        <=   0.181   class_4      0 -> 1         NA
125   125                  gini         =   0.000   class_2    0 -> 126       FALSE
1       1                   WPS        <=   0.074   class_5      1 -> 2        TRUE
52     52                  gini         =   0.000   class_2     1 -> 53       FALSE
105   105                  gini         =   0.492   class_3  102 -> 106       FALSE
102   102           weird_words        <=   0.042   class_4  102 -> 103        TRUE
104   104                  gini         =   0.488   class_4  103 -> 105       FALSE
103   103              funktion        <=   0.290   class_4  103 -> 104        TRUE
107   107                  gini         =   0.000   class_5  106 -> 108       FALSE
106   106           Nb_of_verbs        <=   0.094   class_5  106 -> 107        TRUE
110   110                  gini         =   0.000   class_4  109 -> 111       FALSE
109   109                signal        <=   0.320   class_4  109 -> 110        TRUE
112   112          Flesch_Index        <=   0.627   class_1  112 -> 113        TRUE
115   115                  gini         =   0.000   class_3  112 -> 116       FALSE
114   114                  gini         =   0.000   class_1  113 -> 115       FALSE
113   113       Nb_of_auxiliary        <=   0.714   class_1  113 -> 114        TRUE
..    ...                   ...       ...     ...       ...          ...        ...
</code>```

I am trying to sort the rows based on the value in the 'Direction' column (0 -> 1, means I am trying to sort based on the first number 0). I am trying to do this by using:

```<code>   ## Sort rows based on first int of Direction column ##
   # create a column['key'] to sort df
   adjusted_RFC_df['key'] = Adjusted_RFC_df['Direction'].apply(lambda    x: x.split()[0])

   # Create new Dataframe with sorted values based on first number of 'Direction' col
   class_determiner_df = Adjusted_RFC_df.sort_values('key')
</code>```

This works in sorting by the first value before the '->' (the left hand side), however I need the sorting to keep order with the number on the right side of the '->'

So it should look like this:

```<code>     Node               Feature Indicator  Scaled     Class    Direction True_False
0       0                   km        <=   0.181   class_4      0 -> 1         NA
125   125                  gini         =   0.000   class_2    0 -> 126       FALSE
1       1                   WPS        <=   0.074   class_5      1 -> 2        TRUE
52     52                  gini         =   0.000   class_2     1 -> 53       FALSE
105   105           weird_words         =   0.492   class_3  102 -> 103       FALSE
102   102                  gini        <=   0.042   class_4  102 -> 103        TRUE
104   104              funktion         =   0.488   class_4  103 -> 104       FALSE
103   103                  gini        <=   0.290   class_4  103 -> 105        TRUE
107   107           Nb_of_verbs         =   0.000   class_5  106 -> 107       FALSE
106   106                  gini        <=   0.094   class_5  106 -> 108        TRUE
110   110                signal         =   0.000   class_4  109 -> 110       FALSE
109   109                  gini        <=   0.320   class_4  109 -> 111        TRUE
112   112          Flesch_Index        <=   0.627   class_1  112 -> 113        TRUE
115   115                  gini         =   0.000   class_3  112 -> 116       FALSE
114   114        Nb_of_auxiliary        =   0.000   class_1  113 -> 114       FALSE
113   113                  gini        <=   0.714   class_1  113 -> 115        TRUE
..    ...                   ...       ...     ...       ...          ...        ...
</code>```

It is confusing me as sometimes it does keep the order between the right hand side numbers however most off the time it doesn't.

I thought that maybe it was a problem with sorting strings as the direction col is of type string. So I tried to do the following:

```<code>adjusted_RFC_df['key'] = adjusted_RFC_df['key'].astype(np.int64)
</code>```

However this causes the following error:

```<code>ValueError: invalid literal for int() with base 10: 'NA'
</code>```

So it seems like it is trying to convert the ['TRUE/FALSE'] column to int as well as just the ['key'] column.

Is it likely a problem with the Direction col being type string?

Or is there a way of sorting based on the first number before the '->' whilst ensuring the the second number is also in order (sorted from smallest to biggest)?

答:
If Direction is always of type string and has also this format int space '->' space int like 1 -> 2 then you can get another key to the sorting

```<code>df['key1'] = df['Direction'].apply(lambda x: x.split()[0])
df['key2'] = df['Direction'].apply(lambda x: x.split()[2])
</code>```

and then sort based on these 2 keys

```<code>df.sort_values(['key1', 'key2'])
</code>```

edit:
Here is another way to get key1 and 'key2'

```<code>df['key1'] = df['Direction'].apply(lambda x: int(x.split('->')[0]))
df['key2'] = df['Direction'].apply(lambda x: int(x.split('->')[1]))
</code>```

Title: Sort the rows of a data frame

Body:
I have the following data frame (adjusted_RFC_df):

     Node               Feature Indicator  Scaled     Class    Direction True_False
0       0                   km        <=   0.181   class_4      0 -> 1         NA
125   125                  gini         =   0.000   class_2    0 -> 126       FALSE
1       1                   WPS        <=   0.074   class_5      1 -> 2        TRUE
52     52                  gini         =   0.000   class_2     1 -> 53       FALSE
105   105                  gini         =   0.492   class_3  102 -> 106       FALSE
102   102           weird_words        <=   0.042   class_4  102 -> 103        TRUE
104   104                  gini         =   0.488   class_4  103 -> 105       FALSE
103   103              funktion        <=   0.290   class_4  103 -> 104        TRUE
107   107                  gini         =   0.000   class_5  106 -> 108       FALSE
106   106           Nb_of_verbs        <=   0.094   class_5  106 -> 107        TRUE
110   110                  gini         =   0.000   class_4  109 -> 111       FALSE
109   109                signal        <=   0.320   class_4  109 -> 110        TRUE
112   112          Flesch_Index        <=   0.627   class_1  112 -> 113        TRUE
115   115                  gini         =   0.000   class_3  112 -> 116       FALSE
114   114                  gini         =   0.000   class_1  113 -> 115       FALSE
113   113       Nb_of_auxiliary        <=   0.714   class_1  113 -> 114        TRUE
..    ...                   ...       ...     ...       ...          ...        ...

I am trying to sort the rows based on the value in the 'Direction' column (0 -> 1, means I am trying to sort based on the first number 0). I am trying to do this by using:

   ## Sort rows based on first int of Direction column ##
   # create a column['key'] to sort df
   adjusted_RFC_df['key'] = Adjusted_RFC_df['Direction'].apply(lambda    x: x.split()[0])

   # Create new Dataframe with sorted values based on first number of 'Direction' col
   class_determiner_df = Adjusted_RFC_df.sort_values('key')

This works in sorting by the first value before the '->' (the left hand side), however I need the sorting to keep order with the number on the right side of the '->'

So it should look like this:

     Node               Feature Indicator  Scaled     Class    Direction True_False
0       0                   km        <=   0.181   class_4      0 -> 1         NA
125   125                  gini         =   0.000   class_2    0 -> 126       FALSE
1       1                   WPS        <=   0.074   class_5      1 -> 2        TRUE
52     52                  gini         =   0.000   class_2     1 -> 53       FALSE
105   105           weird_words         =   0.492   class_3  102 -> 103       FALSE
102   102                  gini        <=   0.042   class_4  102 -> 103        TRUE
104   104              funktion         =   0.488   class_4  103 -> 104       FALSE
103   103                  gini        <=   0.290   class_4  103 -> 105        TRUE
107   107           Nb_of_verbs         =   0.000   class_5  106 -> 107       FALSE
106   106                  gini        <=   0.094   class_5  106 -> 108        TRUE
110   110                signal         =   0.000   class_4  109 -> 110       FALSE
109   109                  gini        <=   0.320   class_4  109 -> 111        TRUE
112   112          Flesch_Index        <=   0.627   class_1  112 -> 113        TRUE
115   115                  gini         =   0.000   class_3  112 -> 116       FALSE
114   114        Nb_of_auxiliary        =   0.000   class_1  113 -> 114       FALSE
113   113                  gini        <=   0.714   class_1  113 -> 115        TRUE
..    ...                   ...       ...     ...       ...          ...        ...

It is confusing me as sometimes it does keep the order between the right hand side numbers however most off the time it doesn't.

I thought that maybe it was a problem with sorting strings as the direction col is of type string. So I tried to do the following:

adjusted_RFC_df['key'] = adjusted_RFC_df['key'].astype(np.int64)

However this causes the following error:

ValueError: invalid literal for int() with base 10: 'NA'

So it seems like it is trying to convert the ['TRUE/FALSE'] column to int as well as just the ['key'] column.

Is it likely a problem with the Direction col being type string?

Or is there a way of sorting based on the first number before the '->' whilst ensuring the the second number is also in order (sorted from smallest to biggest)?

Body:
If Direction is always of type string and has also this format int space '->' space int like 1 -> 2 then you can get another key to the sorting

df['key1'] = df['Direction'].apply(lambda x: x.split()[0])
df['key2'] = df['Direction'].apply(lambda x: x.split()[2])

and then sort based on these 2 keys

df.sort_values(['key1', 'key2'])

edit:
Here is another way to get key1 and 'key2'

df['key1'] = df['Direction'].apply(lambda x: int(x.split('->')[0]))
df['key2'] = df['Direction'].apply(lambda x: int(x.split('->')[1]))


问:
Efficient algorithm to produce the n-way intersection of sorted arrays in C
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

```<code>while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j
</code>```

I am working with C, and I am after a clear explanation rather than code.

答: You can probably parallelize the computation as the intersection operation is commutative and associative. Have each thread compute the intersection of two arrays, that will reduce the number of array by two at each steps.</p>

Body:
I need to produce the intersection between some sorted arrays of integers in C. I know how to find the intersection between two sorted arrays, but I need to do this for more than two arrays, efficiently and without prior knowledge of the number of arrays. I can impose a sensible limit on the maximum number - let's say ten for now. These arrays could be anywhere from a few items to a couple of hundred thousand items long, and are by no means necessarily the same length.

Pseudo-code for producing the intersection of two sorted arrays:

while i < m and j < n do:
    if array1[i] < array2[j]:
        increment i
    else if array1[i] > array2[j]:
        increment j
    else
        add array1[i] to intersection(array1, array2)
        increment i
        increment j

I am working with C, and I am after a clear explanation rather than code.


问:
how to do pagination in GridView (Flutter)
I want to implement pagination in GridView I use GridView.builder I want to download 10 by 10 items when the user reaches the last row

答:
You can do this using a NotificationListener. As a simple demonstration it will increase the length of your GridView whenever it reaches end of page :

```<code>    var items_number = 10 ;

    return NotificationListener<ScrollNotification>(
         onNotification: (scrollNotification){
              if(scrollNotification.metrics.pixels == scrollNotification.metrics.maxScrollExtent){
                 setState(() {
                    items_number += 10 ;
                 });
              }
         },
         child: GridView.builder(
                    itemCount: items_number,
                    itemBuilder: (context, index) {
                      //.... the reminder of your code
                    }
                ),
    );
</code>```

Body:
You can do this using a NotificationListener. As a simple demonstration it will increase the length of your GridView whenever it reaches end of page :

    var items_number = 10 ;

    return NotificationListener<ScrollNotification>(
         onNotification: (scrollNotification){
              if(scrollNotification.metrics.pixels == scrollNotification.metrics.maxScrollExtent){
                 setState(() {
                    items_number += 10 ;
                 });
              }
         },
         child: GridView.builder(
                    itemCount: items_number,
                    itemBuilder: (context, index) {
                      //.... the reminder of your code
                    }
                ),
    );


问:
Automatically pull from another repo (when pushed) then update
Problem:

I have two repo's, one (repo A) contains scss files (folder named scss) that I would like to use in repo B.

In repo B I would like to add the scss folder as a subdirectory, and when I make a push to repo A, the scss folder should automatically pull in the contents and make a push.

Basically I need the folders to have the exactly the same contents at all times, Im presuming above is the only way to do so?

Tried:

Thought about git hooks for this but I'm under the impression that they're best used on a server, and currently they are two local repo's sitting on my computer.

Any suggestions greatly appreciated.

答:
A quick Google search came up with an interesting tool called GitHubSync
 that might help you synchronize specific files and folders across different Github repositories. It doesn't seem to work for other platforms so you will need to look for a different solution if you repositories are not hosted on Github.

Edit: Also take a look at this answer that talks about Git submodules that does exactly what you want to do using references, and the official Git documentation about submodules.


问:
Can't import rest_framework in Django
I'm trying to stand up a Django site and I am attempting to setup Report_builder with that. I just got the front end of report builder to work but it is not returning any data. I suspect the problem is with my rest framework. The settings did not auto create and now when I try to import it to create a serializer restframework is not recognized at all.

Here is my settings page:

```<code>  REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.SessionAuthentication',
     ),

 }
</code>```

Did I possibly install rest framework in the wrong place or??

I have the latest version.

答:
Recently I faced the same problem and that is not only for the rest_framework. The answer for me is answered above but not fully how to check for beginners.

Make sure that you have initialized the framework to the settings.py
You should have it under INSTALLED_APPS and REST_FRAMEWORK

The main problem you might face is the environments of python you have. For checking if you have it already installed run:
python and import rest_framework
That most likely will return you an error of ImportError: No module named rest_framework.
So the fix for that is running it with python3.

In case you do not have it run pip install djangorestframework

Side note to that: check which version of djangorestframework you have as depending on the python you are running, as versions of rest_framework 1.9 onwards wont work with Python3

Title: Can't import rest_framework in Django

Body:
I'm trying to stand up a Django site and I am attempting to setup Report_builder with that. I just got the front end of report builder to work but it is not returning any data. I suspect the problem is with my rest framework. The settings did not auto create and now when I try to import it to create a serializer restframework is not recognized at all.

Here is my settings page:

  REST_FRAMEWORK = {
     'DEFAULT_AUTHENTICATION_CLASSES': (
         'rest_framework.authentication.SessionAuthentication',
     ),

 }

Did I possibly install rest framework in the wrong place or??

I have the latest version.


问:
Exporting a laravel blog content to wordpress
I have a blog built in laravel , but I want to move all the content to an existing blog built in wordpress, I have tried exporting the database as a CSV file to import on my wordpress database but its not in the same table format , any idea on how to import the contents</p>

答:
It is less likely to work the direct import since the table structures will be different. So what we can do is to

Connect to the Laravel Database from your WordPress installation.

Select the Laravel db data using wpdb query (https://codex.wordpress.org/Class_Reference/wpdb)

Insert into our WordPress site using wp_insert_post (https://developer.wordpress.org/reference/functions/wp_insert_post/)

If there are pictures attached to the Laravel Blog you must query it as well and upload it and attach to the WordPress as well. (https://codex.wordpress.org/Function_Reference/wp_insert_attachment)

You must take WordPress DB backup before doing this.

Sample code will be something like this.

```<code>$mydb = new wpdb('username','password','laravel_database','localhost');
$rows = $mydb->get_results("select title, content from laravle_blogs_table");

foreach ($rows as $obj) :
   // Create post object
$my_post = array(
  'post_title'    => wp_strip_all_tags( $obj->title ),
  'post_content'  => $obj->content,
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array( 8,39 )
);

// Insert the post into the database
wp_insert_post( $my_post );
endforeach;
</code>```

You must change the field names as per your database.

This code can be put in any of the active theme files may be header.php or footer.php or other template and just load the page from your browser. If there are a huge number of posts put a limit to the select query and insert step by step.

Body:
It is less likely to work the direct import since the table structures will be different. So what we can do is to

Connect to the Laravel Database from your WordPress installation.

Select the Laravel db data using wpdb query (https://codex.wordpress.org/Class_Reference/wpdb)

Insert into our WordPress site using wp_insert_post (https://developer.wordpress.org/reference/functions/wp_insert_post/)

If there are pictures attached to the Laravel Blog you must query it as well and upload it and attach to the WordPress as well. (https://codex.wordpress.org/Function_Reference/wp_insert_attachment)

You must take WordPress DB backup before doing this.

Sample code will be something like this.

$mydb = new wpdb('username','password','laravel_database','localhost');
$rows = $mydb->get_results("select title, content from laravle_blogs_table");

foreach ($rows as $obj) :
   // Create post object
$my_post = array(
  'post_title'    => wp_strip_all_tags( $obj->title ),
  'post_content'  => $obj->content,
  'post_status'   => 'publish',
  'post_author'   => 1,
  'post_category' => array( 8,39 )
);

// Insert the post into the database
wp_insert_post( $my_post );
endforeach;

You must change the field names as per your database.

This code can be put in any of the active theme files may be header.php or footer.php or other template and just load the page from your browser. If there are a huge number of posts put a limit to the select query and insert step by step.