问:
Issue with RCT_EXTERN_METHOD while converting React Native app with Objective-C to Swift
We have an existing React Native app that was written using Objective-C. I have been tasked with converting the Objective-C syntax to Swift.

Part of the work has been ensuring that the React Native bridge is encapsulated in one place and references external methods in Swift "Manager" classes.

Previously, we had a file called "CameraManager", which was exposed to React Native and had the following method:

RCT_REMAP_METHOD(takePicture, imageSaved:(RCTPromiseresolveBlock)resolve failedSavingImage:(RCTPromiseRejectBlock)reject) { ... }
```

<p>I want to convert that to something like</p>

<pre class="lang-c prettyprint-override"><code>@interface RCT_EXTERN_MODULE(CameraViewManager, NSObject)

RCT_EXTERN_METHOD(takePicture: imageSaved:(RCTPromiseResolveBlock *)resolve failedSavingImage:(RCTPromiseRejectBlock *)reject)

@end
</code>```

This compiles fine, but when the call is made in the application to takePicture, the following exception is thrown.

Exception: 'takePicture::failedSavingImage: is not a recognized Objective-C method'. was thrown while invoking takePicture on target CameraViewManager with params ( ... )

In my CameraViewManager.swift file I have the following:

@objc
func takePicture(imageSaved resolve: @escaping RCTPromiseResolveBlock, failedSavingImage reject: RCTPromiseRejectBlock) -> Void { ... }
```

My overall familiarity with React Native is still a little less than optimal, so I'm not sure exactly what it's going to take to satisfy this.

Any ideas?

答:
So the issue turns out to be that, despite exposing the method with the imageSaved parameter name, it's not looking for that name. It's looking for

```<code>@objc
func takePicture(_ resolve: @escaping RCTPromiseResolveBlock, failedSavingImage reject: RCTPromiseRejectBlock) -> Void { ... }
</code>```

I have also changed my export in the bridge to:

```<code>RCT_EXTERN_METHOD(takePicture: (RCTPromiseResolveBlock *)resolve failedSavingImage:(RCTPromiseRejectBlock *)reject)
</code>```

Body:
We have an existing React Native app that was written using Objective-C. I have been tasked with converting the Objective-C syntax to Swift.

Part of the work has been ensuring that the React Native bridge is encapsulated in one place and references external methods in Swift "Manager" classes.

Previously, we had a file called "CameraManager", which was exposed to React Native and had the following method:

RCT_REMAP_METHOD(takePicture, imageSaved:(RCTPromiseresolveBlock)resolve failedSavingImage:(RCTPromiseRejectBlock)reject) { ... }

I want to convert that to something like

@interface RCT_EXTERN_MODULE(CameraViewManager, NSObject)

RCT_EXTERN_METHOD(takePicture: imageSaved:(RCTPromiseResolveBlock *)resolve failedSavingImage:(RCTPromiseRejectBlock *)reject)

@end

This compiles fine, but when the call is made in the application to takePicture, the following exception is thrown.

Exception: 'takePicture::failedSavingImage: is not a recognized Objective-C method'. was thrown while invoking takePicture on target CameraViewManager with params ( ... )

In my CameraViewManager.swift file I have the following:

@objc
func takePicture(imageSaved resolve: @escaping RCTPromiseResolveBlock, failedSavingImage reject: RCTPromiseRejectBlock) -> Void { ... }

My overall familiarity with React Native is still a little less than optimal, so I'm not sure exactly what it's going to take to satisfy this.

Any ideas?

Body:
So the issue turns out to be that, despite exposing the method with the imageSaved parameter name, it's not looking for that name. It's looking for

@objc
func takePicture(_ resolve: @escaping RCTPromiseResolveBlock, failedSavingImage reject: RCTPromiseRejectBlock) -> Void { ... }

I have also changed my export in the bridge to:

RCT_EXTERN_METHOD(takePicture: (RCTPromiseResolveBlock *)resolve failedSavingImage:(RCTPromiseRejectBlock *)reject)


来源: stackexchange

问:
Size of file names on tabs in Notepad++
In notepad++, the names of the files I have open that appear on each tab are in a tiny font that's unreadable (using a large screen at low resolution).  Is there a way to change the size of the font that's used on those tabs?  Thanks!</p>

答:
First; in Preferences => General untick the reduce check box as well as the darken tab checkbox.
This will have an immediate impact.

Next, in Preferences => Style Configurator => General Styles => Inactive tabs;
Click on the foreground color and change it to black.

I have attempted to change the font size in the tabs by doing the following, but it does not appear to have an affect.

Open the stylers.xml file in your Notepad++ folder and I have not found this to work with 64bit Notepad++.

do a search in stylers.xml for tab, not tabs. You will find four lines beginning with WidgetStyle

```<code>    <WidgetStyle name="Active tab focused indicator" styleID="0" fgColor="FAAA3C" />
    <WidgetStyle name="Active tab unfocused indicator" styleID="0" fgColor="FFCAB0" />
    <WidgetStyle name="Active tab text" styleID="0" fgColor="000000" />
    <WidgetStyle name="Inactive tabs" styleID="0" fgColor="000000" bgColor="C0C0C0" />

    <WidgetStyle name="Active tab focused indicator" styleID="0" fgColor="FAAA3C" fontSize="14" />
    <WidgetStyle name="Active tab unfocused indicator" styleID="0" fgColor="FFCAB0" fontSize="14" />
    <WidgetStyle name="Active tab text" styleID="0" fgColor="000000" fontSize="14" />
    <WidgetStyle name="Inactive tabs" styleID="0" fgColor="000000" bgColor="C0C0C0" fontSize="14" />
</code>```

It would be good for users in general if programs were designed so that the user can change the font size of the GUI. Microsoft's nonsensical increase font size panel doesn't actually help users as that increase also increases the size of everything on the desktop and most people will be served quite nicely with only a larger font size.

Who knows, maybe the developers of Notepad++ will see this and make sure the font size in the tabs will change based on the stylers.xml settings.

ContentLicense: CC BY-SA 3.0

Title: Size of file names on tabs in Notepad++

Body:
First; in Preferences => General untick the reduce check box as well as the darken tab checkbox.
This will have an immediate impact.

Next, in Preferences => Style Configurator => General Styles => Inactive tabs;
Click on the foreground color and change it to black.

I have attempted to change the font size in the tabs by doing the following, but it does not appear to have an affect.

Open the stylers.xml file in your Notepad++ folder and I have not found this to work with 64bit Notepad++.

do a search in stylers.xml for tab, not tabs. You will find four lines beginning with WidgetStyle

    <WidgetStyle name="Active tab focused indicator" styleID="0" fgColor="FAAA3C" />
    <WidgetStyle name="Active tab unfocused indicator" styleID="0" fgColor="FFCAB0" />
    <WidgetStyle name="Active tab text" styleID="0" fgColor="000000" />
    <WidgetStyle name="Inactive tabs" styleID="0" fgColor="000000" bgColor="C0C0C0" />

    <WidgetStyle name="Active tab focused indicator" styleID="0" fgColor="FAAA3C" fontSize="14" />
    <WidgetStyle name="Active tab unfocused indicator" styleID="0" fgColor="FFCAB0" fontSize="14" />
    <WidgetStyle name="Active tab text" styleID="0" fgColor="000000" fontSize="14" />
    <WidgetStyle name="Inactive tabs" styleID="0" fgColor="000000" bgColor="C0C0C0" fontSize="14" />

It would be good for users in general if programs were designed so that the user can change the font size of the GUI. Microsoft's nonsensical increase font size panel doesn't actually help users as that increase also increases the size of everything on the desktop and most people will be served quite nicely with only a larger font size.

Who knows, maybe the developers of Notepad++ will see this and make sure the font size in the tabs will change based on the stylers.xml settings.

ContentLicense: CC BY-SA 4.0


问:
Google Ads not showing in div?
Hey, i don't understand why, but i have an ad box below the lightbulb on the page (view the source) and I don't see anything. I understand google take about 10 minutes to process ads and show things, but i have tried this for about a day using multiple test ad boxes but nothing seems to work.

tl;dr- I dont know how to use javascript and i can't figure out whats wrong on my ads

It should be in the information box below the lightbulb.

http://atomicpool.com/play.php?id=1

anyone have any ideas?

答:
about javascript...here you have to just copy-paste ads code which is given by google.....
and its run properly...
and you have to configure size of div as google ads require...</p>

Title: Google Ads not showing in div?


问:
Flowable from Cache and other Flowable for DataSource using RxJava
I am pretty new to RxJava and I need to create repository with several datasources. It is complex to me because there are several smaller subtasks which I don't know how to implement with RxJava.

I have Dao which provides Flowable<Item> in some range to DataSource class. This data source has local cache which can be invalidated at any time. When repository asks DataSource for some range (which can be out of DataSourse bounds, bounds are unknown until fully cached) it must produce an error (or notify Repository in other way).

I want to create Flowable<Item> method for DataSource which will emit items from cache, and if needed concatenate them with Flowable<Item> dao.getRange(...), meanwhile caching new items, which come from dao. Also I need to do stuff with errors coming from dao, they must be handled or converted to higher level errors.

DataSource.class:

```<code>List<Item> cache;

Flowable<Item> getRange(int start, int amount) {

    final int cacheSize = cache.size();
    final int canLoadFromCache = cacheSize - start;
    final int loadFromDao = amount - canLoadFromCache;

    if (isCorrupted) return Flowable.fromCallable(() -> {
        throw new Exception("CorruptedDatasource");
    });

    Flowable<Item> cacheFlow = null;
    Flowable<Item> daoFlow = null;

    if (canLoadFromCache > 0) {
        cacheFlow = Flowable.fromIterable(
                cache.subList(start, canLoadFromCache)
        );

        daoFlow = dao.getRange(
                uri,
                cacheSize, //start
                loadFromDao //amount
        );
    } else {
        if (isFullyCached) return Flowable.fromCallable(() -> {
            throw new Exception("OutOfBounds");
        });

        //To not deal with gaps load and cache data between;
        //Or replace it with data structure which can handle for us;
        daoFlow = dao.getRange(
                uri,
                cacheSize,
                start - cacheSize + amount);
        //all these items should be cached;
        //other cached and put downstream;
        //Dao errs should be converted to higher lever exceptions,
        //Or set flags in DataSource;
    }
    // return concatenated flowable;
}
</code>```

At the higher level repository concatenates data coming from several DataSources, so there must be a way to cancatinate ranges coming from several sources in a way if one haven't enought then range from next one should be added.

Please help me!

答:
Try concat or concatEager which concatenates two observables. Also doOnNext() or doOnError() can help you caching and error handlings

```<code>List<Item> cache;

Flowable<Item> getRange(int start, int amount) {

    ...
        if (isFullyCached) return Flowable.fromCallable(() -> {
            throw new Exception("OutOfBounds");
        });

        //To not deal with gaps load and cache data between;
        //Or replace it with data structure which can handle for us;
        daoFlow = dao.getRange(
                uri,
                cacheSize,
                start - cacheSize + amount);
        //all these items should be cached;
        //other cached and put downstream;
            .doOnNext(result -> /* insert caching logic here */)
        //Dao errs should be converted to higher lever exceptions,
        //Or set flags in DataSource;
            .doOnError(error -> /* handle error here */)
            .onErrorReturn(/* and/or return some empty item */)
    }
    // return concatenated flowable;
    return cacheFlow.concat(daoFlow);
}
</code>```

Body:
I am pretty new to RxJava and I need to create repository with several datasources. It is complex to me because there are several smaller subtasks which I don't know how to implement with RxJava.

I have Dao which provides Flowable<Item> in some range to DataSource class. This data source has local cache which can be invalidated at any time. When repository asks DataSource for some range (which can be out of DataSourse bounds, bounds are unknown until fully cached) it must produce an error (or notify Repository in other way).

I want to create Flowable<Item> method for DataSource which will emit items from cache, and if needed concatenate them with Flowable<Item> dao.getRange(...), meanwhile caching new items, which come from dao. Also I need to do stuff with errors coming from dao, they must be handled or converted to higher level errors.

DataSource.class:

List<Item> cache;

Flowable<Item> getRange(int start, int amount) {

    final int cacheSize = cache.size();
    final int canLoadFromCache = cacheSize - start;
    final int loadFromDao = amount - canLoadFromCache;

    if (isCorrupted) return Flowable.fromCallable(() -> {
        throw new Exception("CorruptedDatasource");
    });

    Flowable<Item> cacheFlow = null;
    Flowable<Item> daoFlow = null;

    if (canLoadFromCache > 0) {
        cacheFlow = Flowable.fromIterable(
                cache.subList(start, canLoadFromCache)
        );

        daoFlow = dao.getRange(
                uri,
                cacheSize, //start
                loadFromDao //amount
        );
    } else {
        if (isFullyCached) return Flowable.fromCallable(() -> {
            throw new Exception("OutOfBounds");
        });

        //To not deal with gaps load and cache data between;
        //Or replace it with data structure which can handle for us;
        daoFlow = dao.getRange(
                uri,
                cacheSize,
                start - cacheSize + amount);
        //all these items should be cached;
        //other cached and put downstream;
        //Dao errs should be converted to higher lever exceptions,
        //Or set flags in DataSource;
    }
    // return concatenated flowable;
}

At the higher level repository concatenates data coming from several DataSources, so there must be a way to cancatinate ranges coming from several sources in a way if one haven't enought then range from next one should be added.

Please help me!

Body:
Try concat or concatEager which concatenates two observables. Also doOnNext() or doOnError() can help you caching and error handlings

List<Item> cache;

Flowable<Item> getRange(int start, int amount) {

    ...
        if (isFullyCached) return Flowable.fromCallable(() -> {
            throw new Exception("OutOfBounds");
        });

        //To not deal with gaps load and cache data between;
        //Or replace it with data structure which can handle for us;
        daoFlow = dao.getRange(
                uri,
                cacheSize,
                start - cacheSize + amount);
        //all these items should be cached;
        //other cached and put downstream;
            .doOnNext(result -> /* insert caching logic here */)
        //Dao errs should be converted to higher lever exceptions,
        //Or set flags in DataSource;
            .doOnError(error -> /* handle error here */)
            .onErrorReturn(/* and/or return some empty item */)
    }
    // return concatenated flowable;
    return cacheFlow.concat(daoFlow);
}


问:
Listener for property value changes in a Javascript object
Going through Javascript documentation, I found the following two functions on a Javascript object looks interesting:

.watch - Watches for a property to be assigned a value and runs a function when that occurs.

.unwatch - Removes a watchpoint set with the watch method.

UPDATE: Deprecation warning

Do not use watch() and unwatch()! These two
methods were implemented only in Firefox prior to version 58, they're
deprecated and removed in Firefox 58+

Sample usage:

```<code>o = { p: 1 };
o.watch("p", function (id,oldval,newval) {
    console.log("o." + id + " changed from " + oldval + " to " + newval)
    return newval;
});
</code>```

Whenever we change the property value of "p", this function gets triggered.

```<code>o.p = 2;   //logs: "o.p changed from 1 to 2"
</code>```

I am working on Javascript for the past few years and never used these functions.

Can someone please throw some good use cases where these functions will come in handy?

答:
Object.defineProperty

Promise

remove Promise and keep callback only if Promise is not supported in your target browser

Important:

1) Be aware of async behaviour on using promise.

2) Object.defineProperty doesn't trigger the callback, only assign operator '=' does

```<code>Object.onPropertySet = function onPropertySet(obj, prop, ...callback_or_once){
    let callback, once;
    for(let arg of callback_or_once){
        switch(typeof arg){
        case "function": callback = arg; break;
        case "boolean": once = arg; break;
        }
    }

    let inner_value = obj[prop];
    let p = new Promise(resolve => Object.defineProperty(obj, prop, {
        configurable: true,
        // enumerable: true,
        get(){ return inner_value; },
        set(v){
            inner_value = v;
            if(once){
                Object.defineProperty(obj, prop, {
                    configurable: true,
                    // enumerable: true,
                    value: v,
                    writable: true,
                });
            }
            (callback || resolve)(v);
        }
    }));
    if(!callback) return p;
};

// usage
let a = {};
function sayHiValue(v){ console.log(`Hi "${v}"`); return v; }

// do
Object.onPropertySet(a, "b", sayHiValue);
a.b = 2; // Hi "2"
a.b = 5; // Hi "5"

// or
Object.onPropertySet(a, "c", true).then(sayHiValue).then(v => {
    console.log(a.c); // 4 // because a.c is set immediatly after a.c = 3
    console.log(v); // 3 // very important: v != a.c if a.c is reassigned immediatly
    a.c = 2; // property "c" of object "a" is re-assignable by '=' operator
    console.log(a.c === 2); // true
});
a.c = 3; // Hi "3"
a.c = 4; // (Nothing)
</code>```

Body:
Going through Javascript documentation, I found the following two functions on a Javascript object looks interesting:

.watch - Watches for a property to be assigned a value and runs a function when that occurs.

.unwatch - Removes a watchpoint set with the watch method.

UPDATE: Deprecation warning

Do not use watch() and unwatch()! These two
methods were implemented only in Firefox prior to version 58, they're
deprecated and removed in Firefox 58+

Sample usage:

o = { p: 1 };
o.watch("p", function (id,oldval,newval) {
    console.log("o." + id + " changed from " + oldval + " to " + newval)
    return newval;
});

Whenever we change the property value of "p", this function gets triggered.

o.p = 2;   //logs: "o.p changed from 1 to 2"

I am working on Javascript for the past few years and never used these functions.

Can someone please throw some good use cases where these functions will come in handy?

Body:
Object.defineProperty

Promise

remove Promise and keep callback only if Promise is not supported in your target browser

Important:

1) Be aware of async behaviour on using promise.

2) Object.defineProperty doesn't trigger the callback, only assign operator '=' does

Object.onPropertySet = function onPropertySet(obj, prop, ...callback_or_once){
    let callback, once;
    for(let arg of callback_or_once){
        switch(typeof arg){
        case "function": callback = arg; break;
        case "boolean": once = arg; break;
        }
    }

    let inner_value = obj[prop];
    let p = new Promise(resolve => Object.defineProperty(obj, prop, {
        configurable: true,
        // enumerable: true,
        get(){ return inner_value; },
        set(v){
            inner_value = v;
            if(once){
                Object.defineProperty(obj, prop, {
                    configurable: true,
                    // enumerable: true,
                    value: v,
                    writable: true,
                });
            }
            (callback || resolve)(v);
        }
    }));
    if(!callback) return p;
};

// usage
let a = {};
function sayHiValue(v){ console.log(`Hi "${v}"`); return v; }

// do
Object.onPropertySet(a, "b", sayHiValue);
a.b = 2; // Hi "2"
a.b = 5; // Hi "5"

// or
Object.onPropertySet(a, "c", true).then(sayHiValue).then(v => {
    console.log(a.c); // 4 // because a.c is set immediatly after a.c = 3
    console.log(v); // 3 // very important: v != a.c if a.c is reassigned immediatly
    a.c = 2; // property "c" of object "a" is re-assignable by '=' operator
    console.log(a.c === 2); // true
});
a.c = 3; // Hi "3"
a.c = 4; // (Nothing)


问:
MongoDB doesn't start
A few days ago I decided to use mongodb for a project. but I still don't make it work.

If I'm try to start mongodb with the following command:

```<code>  sudo mongod --config=/etc/mongod.conf
</code>```

This is the result:

```<code>  about to fork child process, waiting until server is ready for connections.
  forked process: 4539
  child process started successfully, parent exiting
</code>```

this is my mongod.conf:

```<code>  # mongod.conf
  systemLog:
     path: "/var/log/mongodb/mongod.log"
     destination: file
     timeStampFormat: iso8601-utc
     logAppend: true
     logRotate: reopen

  net:
     bindIp: 127.0.0.1
     port: 27017
     wireObjectCheck: true
     serviceExecutor: adaptive

  storage:
     dbPath: "/home/juny/nodeBox/data/db"

  processManagement:
     fork: true
     pidFilePath: "/run/mongod.pid"

  security:
     authorization: enabled

  operationProfiling:
     mode: slowOp
</code>```

If I try to start mongod as service, the terminal display this:

```<code>   ● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2019-05-27 14:22:31 AST; 8s ago
      Docs: https://docs.mongodb.org/manual
   Process: 4861 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=1/FAILURE)
   Main PID: 4861 (code=exited, status=1/FAILURE)

   May 27 14:22:31 LAPTOP-CJFC94N systemd[1]: Started MongoDB Database Server.
   May 27 14:22:31  mongod[4861]: about to fork child process, waiting until server is ready for connections.
   May 27 14:22:31  mongod[4861]: forked process: 4863
   May 27 14:22:31  systemd[1]: mongod.service: Main process exited, code=exited, status=1/FAILURE
   May 27 14:22:31  systemd[1]: mongod.service: Unit entered failed state.
   May 27 14:22:31  systemd[1]: mongod.service: Failed with result 'exit-code'.
</code>```

And finally, this is a few lines on my log file:

```<code>   2019-05-27T18:14:16.257Z I RECOVERY [initandlisten] WiredTiger recoveryTimestamp. Ts: Timestamp(0, 0)
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten]
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten]
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten] **        We suggest setting it to 'never'
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten]
   2019-05-27T18:14:16.530Z I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/home/juny/nodeBox/data/db/diagnostic.data'
   2019-05-27T18:14:16.531Z I EXECUTOR [initandlisten] No thread count configured for executor. Using number of cores / 2: 2
   2019-05-27T18:14:16.531Z I EXECUTOR [worker-1] Started new database worker thread 1
   2019-05-27T18:14:16.531Z I EXECUTOR [worker-2] Started new database worker thread 2
   2019-05-27T18:14:16.531Z I NETWORK  [initandlisten] waiting for connections on port 27017
   2019-05-27T18:28:02.535Z I NETWORK  [listener] connection accepted from 127.0.0.1:48610 #1 (1 connection now open)
   2019-05-27T18:28:02.535Z I NETWORK  [conn1] Error receiving request from client: ProtocolError: Client sent an HTTP request over a native MongoDB connection. Ending connection from 127.0.0.1:48610 (connection id: 1)
   2019-05-27T18:28:02.535Z I NETWORK  [worker-2] end connection 127.0.0.1:48610 (0 connections now open)
   2019-05-27T18:28:02.585Z I NETWORK  [listener] connection accepted from 127.0.0.1:48612 #2 (1 connection now open)
   2019-05-27T18:28:02.585Z I NETWORK  [conn2] Error receiving request from client: ProtocolError: Client sent an HTTP request over a native MongoDB connection. Ending connection from 127.0.0.1:48612 (connection id: 2)
   2019-05-27T18:28:02.585Z I NETWORK  [worker-1] end connection 127.0.0.1:48612 (0 connections now open)
</code>```

答: Ok Ok, it works if I type the following command: mongo</p>

Title: MongoDB doesn't start

Body:
A few days ago I decided to use mongodb for a project. but I still don't make it work.

If I'm try to start mongodb with the following command:

  sudo mongod --config=/etc/mongod.conf

This is the result:

  about to fork child process, waiting until server is ready for connections.
  forked process: 4539
  child process started successfully, parent exiting

this is my mongod.conf:

  # mongod.conf
  systemLog:
     path: "/var/log/mongodb/mongod.log"
     destination: file
     timeStampFormat: iso8601-utc
     logAppend: true
     logRotate: reopen

  net:
     bindIp: 127.0.0.1
     port: 27017
     wireObjectCheck: true
     serviceExecutor: adaptive

  storage:
     dbPath: "/home/juny/nodeBox/data/db"

  processManagement:
     fork: true
     pidFilePath: "/run/mongod.pid"

  security:
     authorization: enabled

  operationProfiling:
     mode: slowOp

If I try to start mongod as service, the terminal display this:

   ● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Mon 2019-05-27 14:22:31 AST; 8s ago
      Docs: https://docs.mongodb.org/manual
   Process: 4861 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=1/FAILURE)
   Main PID: 4861 (code=exited, status=1/FAILURE)

   May 27 14:22:31 LAPTOP-CJFC94N systemd[1]: Started MongoDB Database Server.
   May 27 14:22:31  mongod[4861]: about to fork child process, waiting until server is ready for connections.
   May 27 14:22:31  mongod[4861]: forked process: 4863
   May 27 14:22:31  systemd[1]: mongod.service: Main process exited, code=exited, status=1/FAILURE
   May 27 14:22:31  systemd[1]: mongod.service: Unit entered failed state.
   May 27 14:22:31  systemd[1]: mongod.service: Failed with result 'exit-code'.

And finally, this is a few lines on my log file:

   2019-05-27T18:14:16.257Z I RECOVERY [initandlisten] WiredTiger recoveryTimestamp. Ts: Timestamp(0, 0)
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten]
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten]
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten] **        We suggest setting it to 'never'
   2019-05-27T18:14:16.437Z I CONTROL  [initandlisten]
   2019-05-27T18:14:16.530Z I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory '/home/juny/nodeBox/data/db/diagnostic.data'
   2019-05-27T18:14:16.531Z I EXECUTOR [initandlisten] No thread count configured for executor. Using number of cores / 2: 2
   2019-05-27T18:14:16.531Z I EXECUTOR [worker-1] Started new database worker thread 1
   2019-05-27T18:14:16.531Z I EXECUTOR [worker-2] Started new database worker thread 2
   2019-05-27T18:14:16.531Z I NETWORK  [initandlisten] waiting for connections on port 27017
   2019-05-27T18:28:02.535Z I NETWORK  [listener] connection accepted from 127.0.0.1:48610 #1 (1 connection now open)
   2019-05-27T18:28:02.535Z I NETWORK  [conn1] Error receiving request from client: ProtocolError: Client sent an HTTP request over a native MongoDB connection. Ending connection from 127.0.0.1:48610 (connection id: 1)
   2019-05-27T18:28:02.535Z I NETWORK  [worker-2] end connection 127.0.0.1:48610 (0 connections now open)
   2019-05-27T18:28:02.585Z I NETWORK  [listener] connection accepted from 127.0.0.1:48612 #2 (1 connection now open)
   2019-05-27T18:28:02.585Z I NETWORK  [conn2] Error receiving request from client: ProtocolError: Client sent an HTTP request over a native MongoDB connection. Ending connection from 127.0.0.1:48612 (connection id: 2)
   2019-05-27T18:28:02.585Z I NETWORK  [worker-1] end connection 127.0.0.1:48612 (0 connections now open)


问:
ReactJS can not rerender Component by onClick
i make simple app with react.js that suggestion random place every time click on Button
the problem can not re-render component after one click
how can i get new place each time click on button

place.js where fetch API to get data

```<code>state = { loading: true, person: null };
  async componentDidMount() {
    let Xyurl = "https://cors-anywhere.herokuapp.com/";
    let url =
      "https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";

    let response = await fetch(Xyurl + url);
    let data = await response.json();
    this.setState({ place: data, loading: false });

  }
  render() {
    return (
      <div>
        <div>
          {this.state.loading || !this.state.place ? (
            <div>loading......</div>
          ) : (
            <div className="PlcseContiner">
              <img alt="description" src= .
              {this.state.place.image[0]} />
                {this.state.place.name}

        </div>
      </div>
    );
</code>```

Suggestion where from button can render places

```<code>class Suggestion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    };
    this.handleClicked = this.handleClicked.bind(this);
  }
  handleClicked(event) {
    event.preventDefault();
    this.setState({
      visible: true
    });
  }

  generateplace() {
    if (this.state.visible) {
      return <Place />;
    }
    return null;
  }

  render() {
    return (
      <div className="main-button">
        <Button onClick={this.handleClicked} color="warning" className="Btn">
          suggestion
        </Button>
        {this.generateplace()}
      </div>
    );
  }
</code>```

}

答:
You can control of it from parent with componentWillUpdate
so you need to add props to Place component

Suggestion:

```<code>class Suggestion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      refresh: 1
    };
    this.handleClicked = this.handleClicked.bind(this);
  }
  handleClicked(event) {
    event.preventDefault();
    this.setState({
      visible: true,
      refresh: this.state.refresh + 1
    });
  }

  generateplace() {
    if (this.state.visible) {
      return <Place refresh={this.state.refresh} />;
    }
    return null;
  }

  render() {
    return (
      <div className="main-button">
        <Button onClick={this.handleClicked} color="warning" className="Btn">
          suggestion
        </Button>
        {this.generateplace()}
      </div>
    );
  }
</code>```

You need to separate the action to functions like this :

Place:

```<code>componentDidMount() {
    this.getPlace()
}

componentWillUpdate(nextProps, nextState) {
    this.getPlace();
}

getPlace = async() => {
    let Xyurl = "https://cors-anywhere.herokuapp.com/";
    let url =
          "https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";

    let response = await fetch(Xyurl + url);
    let data = await response.json();
    this.setState({ place: data, loading: false });
}
</code>```

Body:
i make simple app with react.js that suggestion random place every time click on Button
the problem can not re-render component after one click
how can i get new place each time click on button

place.js where fetch API to get data

state = { loading: true, person: null };
  async componentDidMount() {
    let Xyurl = "https://cors-anywhere.herokuapp.com/";
    let url =
      "https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";

    let response = await fetch(Xyurl + url);
    let data = await response.json();
    this.setState({ place: data, loading: false });

  }
  render() {
    return (

          {this.state.loading || !this.state.place ? (

loading......

          ) : (

                {this.state.place.name}

    );

Suggestion where from button can render places

class Suggestion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    };
    this.handleClicked = this.handleClicked.bind(this);
  }
  handleClicked(event) {
    event.preventDefault();
    this.setState({
      visible: true
    });
  }

  generateplace() {
    if (this.state.visible) {
      return <Place />;
    }
    return null;
  }

  render() {
    return (

        <Button onClick={this.handleClicked} color="warning" className="Btn">
          suggestion
        </Button>
        {this.generateplace()}

    );
  }

}

Body:
You can control of it from parent with componentWillUpdate
so you need to add props to Place component

Suggestion:

class Suggestion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      refresh: 1
    };
    this.handleClicked = this.handleClicked.bind(this);
  }
  handleClicked(event) {
    event.preventDefault();
    this.setState({
      visible: true,
      refresh: this.state.refresh + 1
    });
  }

  generateplace() {
    if (this.state.visible) {
      return <Place refresh={this.state.refresh} />;
    }
    return null;
  }

  render() {
    return (
      <div className="main-button">
        <Button onClick={this.handleClicked} color="warning" className="Btn">
          suggestion
        </Button>
        {this.generateplace()}
      </div>
    );
  }

You need to separate the action to functions like this :

Place:

componentDidMount() {
    this.getPlace()
}

componentWillUpdate(nextProps, nextState) {
    this.getPlace();
}

getPlace = async() => {
    let Xyurl = "https://cors-anywhere.herokuapp.com/";
    let url =
          "https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value";

    let response = await fetch(Xyurl + url);
    let data = await response.json();
    this.setState({ place: data, loading: false });
}


问:
The best way to run npm install for nested folders?
What is the most correct way to install npm packages in nested sub folders?

```<code>my-app
  /my-sub-module
  package.json
package.json
</code>```

What is the best way to have packages in /my-sub-module be installed automatically when npm install run in my-app?

答:
Use Case 1: If you want be able to run npm commands from within each subdirectory (where each package.json is), you will need to use postinstall.

As I often use npm-run-all anyway, I use it to keep it nice and short (the part in the postinstall):

```<code>{
    "install:demo": "cd projects/demo && npm install",
    "install:design": "cd projects/design && npm install",
    "install:utils": "cd projects/utils && npm install",

    "postinstall": "run-p install:*"
}
</code>```

This has the added benefit that I can install all at once, or individually. If you don't need this or don't want npm-run-all as a dependency, check out demisx's answer (using subshells in postinstall).

Use Case 2: If you will be running all npm commands from the root directory (and, for example, won't be using npm scripts in subdirectories), you could simply install each subdirectory like you would any dependecy:

```<code>npm install path/to/any/directory/with/a/package-json
</code>```

In the latter case, don't be surprised that you don't find any node_modules or package-lock.json file in the sub-directories - all packages will be installed in the root node_modules, which is why you won't be able to run your npm commands (that require dependencies) from any of your subdirectories.

If you're not sure, use case 1 always works.

Body:
What is the most correct way to install npm packages in nested sub folders?

my-app
  /my-sub-module
  package.json
package.json

What is the best way to have packages in /my-sub-module be installed automatically when npm install run in my-app?

Body:
Use Case 1: If you want be able to run npm commands from within each subdirectory (where each package.json is), you will need to use postinstall.

As I often use npm-run-all anyway, I use it to keep it nice and short (the part in the postinstall):

{
    "install:demo": "cd projects/demo && npm install",
    "install:design": "cd projects/design && npm install",
    "install:utils": "cd projects/utils && npm install",

    "postinstall": "run-p install:*"
}

This has the added benefit that I can install all at once, or individually. If you don't need this or don't want npm-run-all as a dependency, check out demisx's answer (using subshells in postinstall).

Use Case 2: If you will be running all npm commands from the root directory (and, for example, won't be using npm scripts in subdirectories), you could simply install each subdirectory like you would any dependecy:

npm install path/to/any/directory/with/a/package-json

In the latter case, don't be surprised that you don't find any node_modules or package-lock.json file in the sub-directories - all packages will be installed in the root node_modules, which is why you won't be able to run your npm commands (that require dependencies) from any of your subdirectories.

If you're not sure, use case 1 always works.


问:
TCPConnectWrap.afterConnect - node can't get data from mysql when are in docker compose
I'm trying to connect node with mysql through dokcer-compose. I can access mysql with workbench but when I try to connect with node I get the error:

```<code>Error: connect ECONNREFUSED 127.0.0.1:3306
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js: 1054: 14))
</code>```

Does anyone know what is going on?

docker-compose.yml

```<code>version: '3'

services:

  #App Service
  app:
    image: "node:alpine"
    container_name: cms-node
    restart: unless-stopped
    tty: true
    working_dir: /app
    environment:
      - NODE_ENV=production
    ports:
      - 1234:1234
    volumes:
      - ./:/app
    links:
      - db
    depends_on:
      - db

  #Mysql Service
  db:
    image: mysql:latest
    container_name: cms-mysql
    restart: unless-stopped
    # command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_DATABASE: CMS
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    ports:
      - 3306:3306
</code>```

node create connection

```<code>const db: Connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'CMS',
});

export default db;
</code>```

node try to connect

```<code>db.connect((err) => {
            if (err) {
                throw err;
            }
            console.log('Connected!');
        });
</code>```

答:
You should use the link name (by default, the name of the linked service) as the hostname to connect to. See the docker-compose.yml documentation for details.

So just use host: 'db' instead of host: 'localhost'

Body:
I'm trying to connect node with mysql through dokcer-compose. I can access mysql with workbench but when I try to connect with node I get the error:

Error: connect ECONNREFUSED 127.0.0.1:3306
     at TCPConnectWrap.afterConnect [as oncomplete] (net.js: 1054: 14))

Does anyone know what is going on?

docker-compose.yml

version: '3'

services:

  #App Service
  app:
    image: "node:alpine"
    container_name: cms-node
    restart: unless-stopped
    tty: true
    working_dir: /app
    environment:
      - NODE_ENV=production
    ports:
      - 1234:1234
    volumes:
      - ./:/app
    links:
      - db
    depends_on:
      - db

  #Mysql Service
  db:
    image: mysql:latest
    container_name: cms-mysql
    restart: unless-stopped
    # command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_DATABASE: CMS
      MYSQL_USER: root
      MYSQL_PASSWORD: root
      MYSQL_ROOT_PASSWORD: root
    ports:
      - 3306:3306

node create connection

const db: Connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'CMS',
});

export default db;

node try to connect

db.connect((err) => {
            if (err) {
                throw err;
            }
            console.log('Connected!');
        });


问:
Change the color of a TextInput placeholder with Styled Components in React Native
How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`
</code>```

2.

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`
</code>```

答:
You cannot style the placeholder color with styled-components directly, but you can pass the placeholderTextColor property to your styled Textinput.

Example:

```<code>const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

`
</code>```

and then inside your render function:

```<code><Input placeholder="hello" placeholderTextColor="green" />
</code>```

Output:

Working example:

https://snack.expo.io/rybp-nKaE

Body:
How do you set the color of TextInput its placeholder with Styled Components in React Native?

I tried the following without any luck:

1.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   ::placeholder {
       color: green;
   }
`

2.

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

   &::placeholder {
       color: green;
   }
`

Body:
You cannot style the placeholder color with styled-components directly, but you can pass the placeholderTextColor property to your styled Textinput.

Example:

const Input = styled.TextInput`
   border: 1px solid green;
   display: block;
   margin: 0 0 1em;

`

and then inside your render function:

<Input placeholder="hello" placeholderTextColor="green" />

Output:

Working example:

https://snack.expo.io/rybp-nKaE


问:
Sequelize cast column to integer in where clause
Trying to cast a column inside a where clause to search for a query against. Have a difficult time finding reliable documentation on how to do this. Any ideas?</p>

```<code>return await User.findAndCountAll({
      where: {
        [Op.or]: {
          'email': { [Op.iLike]: `%${query}%` },
          '$id::text$': { [Op.iLike]: `%${query}%` } // id is int but needs to be string for searching
        }
      },
      limit,
      offset: page * limit,
      order: [[sortBy, sortOrder.toUpperCase()]],
      raw: true,
      logging: console.log
    });
</code>```

答:
As @leogoesger's answer didn't work for JSONB fields in Postgres, I tried this:

```<code>    where: {
        ["data.createdAt::timestamp"]: {
            [Op.lt]: "now() - interval '3 days'"
        }
    }
</code>```

Lo and behold, it produced:

WHERE CAST(("User"."data"#>>'{createdAt}') AS TIMESTAMP) < now() - interval '3 days'

Using Sequelize 5.1.0.

Body:
Trying to cast a column inside a where clause to search for a query against. Have a difficult time finding reliable documentation on how to do this. Any ideas?

return await User.findAndCountAll({
      where: {
        [Op.or]: {
          'email': { [Op.iLike]: `%${query}%` },
          '$id::text$': { [Op.iLike]: `%${query}%` } // id is int but needs to be string for searching
        }
      },
      limit,
      offset: page * limit,
      order: [[sortBy, sortOrder.toUpperCase()]],
      raw: true,
      logging: console.log
    });

Body:
As @leogoesger's answer didn't work for JSONB fields in Postgres, I tried this:

    where: {
        ["data.createdAt::timestamp"]: {
            [Op.lt]: "now() - interval '3 days'"
        }
    }

Lo and behold, it produced:

WHERE CAST(("User"."data"#>>'{createdAt}') AS TIMESTAMP) < now() - interval '3 days'

Using Sequelize 5.1.0.


问:
How to show message when Task fails due to Timeout
I need a clean way for this example to print("ERROR") when the task ends due to the timeout.

```<code>func getUserDataService() -> Bool{
    var getDataStatus = false

    //Create the url with NSURL
    let url = URL(string: "http://someurl")! //change the url

    //Create the session object
    let session = URLSession.shared

    //Now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.timeoutInterval = 15

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                if let httpResponse = response as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {

                        getDataStatus = true

                    } else {

                    }
                }
            }
        } catch let error {
            print(error)
        }
    })
    task.resume()
    return getDataStatus
}
</code>```

It prints the following when it fails, but I'm not sure where to control this.

2019-05-27 13:53:58.501322-0400 AppName[60195:841789] Task <AB410EF3-5520-44AD-A458-DD75D1F6AD09>.<3> finished with error - code: -1001

  2019-05-27 13:53:58.505525-0400 AppName[60195:842001] Task <AB410EF3-5520-44AD-A458-DD75D1F6AD09>.<3> HTTP load failed (error code: -999 [1:89])

答:
Please read the documentation URL Loading System Error Codes. The timeout error is -1001 aka NSURLErrorTimedOut

The error is returned in the completion handler of the data task. Handle it!

```<code>let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    if let nserror = error as NSError?,
      nserror.code == NSURLErrorTimedOut {
      // do something
      return
    }
</code>```

Apart from that you cannot return a Bool value from that method, you have to add a completion handler

```<code>func getUserDataService(completion: @escaping (Bool) -> Void) {

...
</code>```

And call

```<code>completion(true)
</code>```

and delete

```<code>return getDataStatus
</code>```

Body:
I need a clean way for this example to print("ERROR") when the task ends due to the timeout.

func getUserDataService() -> Bool{
    var getDataStatus = false

    //Create the url with NSURL
    let url = URL(string: "http://someurl")! //change the url

    //Create the session object
    let session = URLSession.shared

    //Now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.timeoutInterval = 15

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                if let httpResponse = response as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {

                        getDataStatus = true

                    } else {

                    }
                }
            }
        } catch let error {
            print(error)
        }
    })
    task.resume()
    return getDataStatus
}

It prints the following when it fails, but I'm not sure where to control this.

2019-05-27 13:53:58.501322-0400 AppName[60195:841789] Task <AB410EF3-5520-44AD-A458-DD75D1F6AD09>.<3> finished with error - code: -1001

  2019-05-27 13:53:58.505525-0400 AppName[60195:842001] Task <AB410EF3-5520-44AD-A458-DD75D1F6AD09>.<3> HTTP load failed (error code: -999 [1:89])

Body:
Please read the documentation URL Loading System Error Codes. The timeout error is -1001 aka NSURLErrorTimedOut

The error is returned in the completion handler of the data task. Handle it!

let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    if let nserror = error as NSError?,
      nserror.code == NSURLErrorTimedOut {
      // do something
      return
    }

Apart from that you cannot return a Bool value from that method, you have to add a completion handler

func getUserDataService(completion: @escaping (Bool) -> Void) {

...

And call

completion(true)

and delete

return getDataStatus


答:
One approach is to use left join and mark the entries where the timestamp falls between begin and end. If the join sizes are going to be an issue, joins can be done individually for each carId.</p>

```<code>df = consEx %>%
  left_join(alertsEx, by="carId") %>%
  mutate(AlertEntry = ifelse(timestamp>= begin & timestamp<=end, "Yes", "No")) %>%
  filter(AlertEntry == "Yes") %>%
  group_by(carId, tripId, type) %>%
  summarise(Total = n(),
            Mean = mean(additionalInfo1))

# Create Summary
df_summary = df %>%
  group_by(carId, tripId) %>%
  gather(key, value, -c(carId, tripId, type), na.rm=T) %>%
  unite(newType, type, key) %>%
  spread(newType, value, fill=0)
</code>```

Title: Fastest way of joining 2 data tables while summarising the data in one of them

Body:
Problem

I have 2 data tables,

Movement:

  library(data.table)

  consEx = data.table(
  begin = as.POSIXct(c("2019-04-01 00:00:10"," 2019-04-07 10:00:00","2019-04-10 23:00:00","2019-04-12 20:00:00","2019-04-15 10:00:00",
                       "2019-04-20 10:00:00","2019-04-22 13:30:00","2019-04-10 15:30:00","2019-04-12 21:30:00","2019-04-15 20:00:00")),

  end = as.POSIXct(c("2019-04-01 20:00:00","2019-04-07 15:00:00","2019-04-11 10:00:00", "2019-04-12 23:30:00","2019-04-15 15:00:00",
                     "2019-04-21 12:00:00","2019-04-22 17:30:00","2019-04-10 20:00:00","2019-04-13 05:00:00", "2019-04-15 12:30:00")),

  carId = c(1,1,1,2,2,3,3,4,4,5),
  tripId = c(1:10)
)

And Alerts:

alertsEx = data.table(
  timestamp = as.POSIXct(c("2019-04-01 10:00:00","2019-04-01 10:30:00","2019-04-01 15:00:00","2019-04-15 13:00:00","2019-04-22 14:00:00",
                "2019-04-22 15:10:00","2019-04-22 15:40:00","2019-04-10 16:00:00","2019-04-10 17:00:00","2019-04-13 04:00:00")),
  type = c("T1","T2","T1",'T3',"T1","T1","T3","T2","T2","T1"),
  carId = c(1,1,1,2,3,3,3,4,4,4),
  additionalInfo1 = rnorm(10,mean=10,sd=4)
)

The movement table records a period begin - end at which a car was moving. The alerts table shows when an alert happened to the car, containing the type, timestamp and carId

I need to join those 2 tables, summarising the alerts data by type. When there are multiple alerts of the same type during the same period I need to aggregate additionalInfo1 by taking it's mean.

Current Approach

I'm currently doing this by looping through consEx and applying a function to each row that returns a list with the calculations I need

findAlerts = function(begin,end,carId_2){
  saida = alertsEx[timestamp >= begin & timestamp <= end & carId == carId_2,]
  totals = nrow(saida)

  saida = split(saida,by="type")

  resultsList = list(
    "totals" = 0,
    "t1Count" = 0,
    "t1Mean" = 0,
    "t2Count" = 0,
    "t2Mean" = 0,
    "t3Count" = 0,
    "t3Mean" = 0)
  resultsList[["totals"]] = totals

  types = names(saida)
  if("T1" %in% types){
    resultsList[["t1Count"]] = nrow(saida[["T1"]])
    resultsList[["t1Mean"]] = mean(saida[["T1"]]$additionalInfo1)
  }

  if("T2" %in% types){
    resultsList[["t2Count"]] = nrow(saida[["T2"]])
    resultsList[["t2Mean"]] = mean(saida[["T2"]]$additionalInfo1)
  }

  if("T3" %in% types){
    resultsList[["t3Count"]] = nrow(saida[["T3"]])
    resultsList[["t3Mean"]] = mean(saida[["T3"]]$additionalInfo1)
  }

  return(resultsList)
}

for(i in 1:nrow(consEx)){
  aux = findAlerts(consEx$begin[i],consEx$end[i],consEx$carId[i])
  consEx[i,names(aux) := aux]

}

Expected Output

Which gives the expected output:

                 begin                 end carId tripId totals t1Count    t1Mean t2Count    t2Mean t3Count    t3Mean
 1: 2019-04-01 00:00:10 2019-04-01 20:00:00     1      1      3       2 10.123463       1 14.479288       0  0.000000
 2: 2019-04-07 10:00:00 2019-04-07 15:00:00     1      2      0       0  0.000000       0  0.000000       0  0.000000
 3: 2019-04-10 23:00:00 2019-04-11 10:00:00     1      3      0       0  0.000000       0  0.000000       0  0.000000
 4: 2019-04-12 20:00:00 2019-04-12 23:30:00     2      4      0       0  0.000000       0  0.000000       0  0.000000
 5: 2019-04-15 10:00:00 2019-04-15 15:00:00     2      5      1       0  0.000000       0  0.000000       1  6.598062
 6: 2019-04-20 10:00:00 2019-04-21 12:00:00     3      6      0       0  0.000000       0  0.000000       0  0.000000
 7: 2019-04-22 13:30:00 2019-04-22 17:30:00     3      7      3       2  7.610410       0  0.000000       1 10.218593
 8: 2019-04-10 15:30:00 2019-04-10 20:00:00     4      8      2       0  0.000000       2  9.703278       0  0.000000
 9: 2019-04-12 21:30:00 2019-04-13 05:00:00     4      9      1       1  7.095564       0  0.000000       0  0.000000
10: 2019-04-15 20:00:00 2019-04-15 12:30:00     5     10      0       0  0.000000       0  0.000000       0  0.000000

But this is too slow for my original data, which has 13M rows in consEx and 2M in alerts. There are also several different types, where I need to calculate the mean, minimum and maximum for 2 metrics.

Is there a faster way to write the function or the loop?

Additionally, would writing virtually the same code in python give a better result? I'm considering rewriting it, but it would take a long time and I'm not sure it would solve the issue

Thanks

PS: Another approach I tried was looping through alerts and assigning each of them a tripId from consEx and then aggregating the resulting table, but this seems to be even slower.

Body:
One approach is to use left join and mark the entries where the timestamp falls between begin and end. If the join sizes are going to be an issue, joins can be done individually for each carId.

df = consEx %>%
  left_join(alertsEx, by="carId") %>%
  mutate(AlertEntry = ifelse(timestamp>= begin & timestamp<=end, "Yes", "No")) %>%
  filter(AlertEntry == "Yes") %>%
  group_by(carId, tripId, type) %>%
  summarise(Total = n(),
            Mean = mean(additionalInfo1))

# Create Summary
df_summary = df %>%
  group_by(carId, tripId) %>%
  gather(key, value, -c(carId, tripId, type), na.rm=T) %>%
  unite(newType, type, key) %>%
  spread(newType, value, fill=0)


问:
Call C++ DLL function in Delphi 7
I have a DLL written in C++. I want to call a function in it from Delphi 7.

I only have an example written in VB.NET.

I have tried converting the code myself before posting here.

The problem is when I call the function, it gives me wrong output in binary, which obviously means I am doing something wrong with the input.

Here is the original code in VB.NET:

Private Shared Declare Unicode Function Read_Write Lib "Subway.dll" (obej As IntPtr, Data_in As Byte(), in_siz As Integer, <Out()> ByRef Data_out As IntPtr, ByRef out_siz As Integer) As Integer

Dim obej As IntPtr = IntPtr.Zero
Dim Data_out As IntPtr = 0
Dim out_siz As Integer = 0
Dim Res As Integer = -1

Res = Read_Write(obej, Encoding.[Default].GetBytes(Mystr), Mystr.Length, Data_out, out_siz)
```

<p>And my converted code in Delphi:</p>

<pre class="lang-pascal prettyprint-override"><code>function Read_Write(obej: Pointer; Data_in: TByteDynArray; in_siz:Cardinal; var Data_out: TByteDynArray; var out_siz: Cardinal): Integer; stdcall; external 'Subway.dll';

var
  tx, rx: TByteDynArray;
  obej: pointer;
  s:string;
  Res: Integer;
  out_siz: Integer;

SetLength(tx, Length(s));
Move(s[1], tx[0], Length(s));
Res := Read_Write(obej, tx, length(s), rx, out_siz);
</code>```

Orignal call (C language):

```<code>int __stdcall Read_Write(void *u_arg, const unsigned char  *p_data_in, unsigned int  data_in_len, unsigned char  **pp_data_out, unsigned int  *p_data_out_len);
</code>```

答:
Your Delphi declaration of Read_Write() does not match the VB.NET declaration. You are not taking into account how .NET marshals parameters to unmanaged languages. Also, TByteDynArray is a Delphi-specific type that you can't pass as-is to other languages, particularly in output parameters.

Try something more like this instead:

function Read_Write(obej: Pointer; Data_in: PByte; in_siz: Integer, var Data_out: Pointer; var out_siz: Integer): Integer; stdcall; external 'Subway.dll';

var
  obej: Pointer;
  Data_out: Pointer;
  out_siz: Integer;
  Res: Integer;
  MyStr: AnsiString;
  buf: TByteDynArray;
begin
  ...

  obej := nil;
  Data_out := nil;
  out_siz := 0;

  MyStr := ...;
  SetLength(buf, Length(MyStr));
  Move(PAnsiChar(MyStr)^, PByte(buf)^, Length(MyStr));

  Res := Read_Write(obej, PByte(buf), Length(buf), Data_out, out_siz);
  // use Data_out up to out_siz bytes as needed...
  // free Data_out as needed...

  ...
end;
```

<p>Alternatively, you can omit the <code>TByteDynArray</code> and just past the <code>AnsiString</code> data directly:</p>

<pre class="lang-pascal prettyprint-override"><code>Res := Read_Write(obej, PByte(PAnsiChar(MyStr)), Length(MyStr), Data_out, out_siz);
</code>```

Title: Call C++ DLL function in Delphi 7

Body:
I have a DLL written in C++. I want to call a function in it from Delphi 7.

I only have an example written in VB.NET.

I have tried converting the code myself before posting here.

The problem is when I call the function, it gives me wrong output in binary, which obviously means I am doing something wrong with the input.

Here is the original code in VB.NET:

Private Shared Declare Unicode Function Read_Write Lib "Subway.dll" (obej As IntPtr, Data_in As Byte(), in_siz As Integer, <Out()> ByRef Data_out As IntPtr, ByRef out_siz As Integer) As Integer

Dim obej As IntPtr = IntPtr.Zero
Dim Data_out As IntPtr = 0
Dim out_siz As Integer = 0
Dim Res As Integer = -1

Res = Read_Write(obej, Encoding.[Default].GetBytes(Mystr), Mystr.Length, Data_out, out_siz)

And my converted code in Delphi:

function Read_Write(obej: Pointer; Data_in: TByteDynArray; in_siz:Cardinal; var Data_out: TByteDynArray; var out_siz: Cardinal): Integer; stdcall; external 'Subway.dll';

var
  tx, rx: TByteDynArray;
  obej: pointer;
  s:string;
  Res: Integer;
  out_siz: Integer;

SetLength(tx, Length(s));
Move(s[1], tx[0], Length(s));
Res := Read_Write(obej, tx, length(s), rx, out_siz);

Orignal call (C language):

int __stdcall Read_Write(void *u_arg, const unsigned char  *p_data_in, unsigned int  data_in_len, unsigned char  **pp_data_out, unsigned int  *p_data_out_len);

Body:
Your Delphi declaration of Read_Write() does not match the VB.NET declaration. You are not taking into account how .NET marshals parameters to unmanaged languages. Also, TByteDynArray is a Delphi-specific type that you can't pass as-is to other languages, particularly in output parameters.

Try something more like this instead:

function Read_Write(obej: Pointer; Data_in: PByte; in_siz: Integer, var Data_out: Pointer; var out_siz: Integer): Integer; stdcall; external 'Subway.dll';

var
  obej: Pointer;
  Data_out: Pointer;
  out_siz: Integer;
  Res: Integer;
  MyStr: AnsiString;
  buf: TByteDynArray;
begin
  ...

  obej := nil;
  Data_out := nil;
  out_siz := 0;

  MyStr := ...;
  SetLength(buf, Length(MyStr));
  Move(PAnsiChar(MyStr)^, PByte(buf)^, Length(MyStr));

  Res := Read_Write(obej, PByte(buf), Length(buf), Data_out, out_siz);
  // use Data_out up to out_siz bytes as needed...
  // free Data_out as needed...

  ...
end;

Alternatively, you can omit the TByteDynArray and just past the AnsiString data directly:

Res := Read_Write(obej, PByte(PAnsiChar(MyStr)), Length(MyStr), Data_out, out_siz);


问:
Four different versions of typescript?
I'm trying to teach myself Angular and while updating my versions (node, angular-cli, ...) I stumbled upon 4 different versions of Typescript. Could anyone tell me the difference?

On the left side of the following screenshot is vscode. The upper part is the result of "ng version". The data cut-off from the screenshot was:

```<code> - Angular CLI: 7.3.9
 - Node: 10.15.3
 - OS: win32 x64
 - Angular: 7.1.4
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router
</code>```

On the right-side a cmd prompt which I opened in my user location.

I'll try to give my own explanation, please correct me :)

3.1.6 I would say that this is the Typescript version which I am using in my project

3.2.2 Then this might be my global version (the one currently installed in %AppData%\Roaming\npm)

3.4.5... no idea about this one. I just looked it up and it is actually the newest available version at the moment of this post. This is higher than what Angular 7.1.4 supports (3.3 is supported by Angular 8.0.0-beta.9 as I found out here... it's a breaking change so this shouldn't work at all as far as I understand). I wonder if this is number is not displaying something else than Typescript (but what?)

3.2.4 this one puzzles me, I have no clue where it is coming from

I also ran npm list typescript locally and globally. Not sure what this means (as I said, I'm still trying to learn...) but this is the result:

答:
That's a pretty neat analysis and you have almost got it right in your own explanation. As for the missing pieces, check the explanation below:

3.1.6 as you have rightly noted is the one used installed in your project

3.2.2 is the one that you have installed globally.

3.2.4 is the typescript installed by angular-cli.

3.4.5 is the latest version which is supported by your current version of Visual Code. The intellisense provided by Visual Code will use this version.

To the best of my knowledge your Angular project will run on TSC version 3.1.6 since it's referenced locally. (Correct me if I get this wrong)

You need not worry about having breaking changes since version 3.4.5 is meant only for VS Code to provide intelli-sense.

Title: Four different versions of typescript?

Body:
I'm trying to teach myself Angular and while updating my versions (node, angular-cli, ...) I stumbled upon 4 different versions of Typescript. Could anyone tell me the difference?

On the left side of the following screenshot is vscode. The upper part is the result of "ng version". The data cut-off from the screenshot was:

 - Angular CLI: 7.3.9
 - Node: 10.15.3
 - OS: win32 x64
 - Angular: 7.1.4
... common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

On the right-side a cmd prompt which I opened in my user location.

I'll try to give my own explanation, please correct me :)

3.1.6 I would say that this is the Typescript version which I am using in my project

3.2.2 Then this might be my global version (the one currently installed in %AppData%\Roaming\npm)

3.4.5... no idea about this one. I just looked it up and it is actually the newest available version at the moment of this post. This is higher than what Angular 7.1.4 supports (3.3 is supported by Angular 8.0.0-beta.9 as I found out here... it's a breaking change so this shouldn't work at all as far as I understand). I wonder if this is number is not displaying something else than Typescript (but what?)

3.2.4 this one puzzles me, I have no clue where it is coming from

I also ran npm list typescript locally and globally. Not sure what this means (as I said, I'm still trying to learn...) but this is the result:


问:
How to capture close event in EXT-GWT (GXT) window
I have this Window:

```<code>Window window = new Window();
window.setMaximizable(true);
window.setMinimizable(true);
window.setClosable(true);
</code>```

And the event listener for minimize event.

```<code>window.addWindowListener(new WindowListener() {
        public void windowMinimize(WindowEvent e) {
            //...
            }
}
</code>```

I tried:

```<code>window.addListener(Events.Close, new Listener<ComponentEvent>() {
      public void handleEvent(ComponentEvent be) {
      //...
      }
});
</code>```

To capture close event (the close button)

And other events such us

windowHide() (WindowListener) or Events.Detach (Listener)

Either i press minimize or close button it captures both of them.

I need one separate event for the minimize and the close button.

答: Have you tried listening to Hide event?

Body:
I have this Window:

Window window = new Window();
window.setMaximizable(true);
window.setMinimizable(true);
window.setClosable(true);

And the event listener for minimize event.

window.addWindowListener(new WindowListener() {
        public void windowMinimize(WindowEvent e) {
            //...
            }
}

I tried:

window.addListener(Events.Close, new Listener<ComponentEvent>() {
      public void handleEvent(ComponentEvent be) {
      //...
      }
});

To capture close event (the close button)

And other events such us

windowHide() (WindowListener) or Events.Detach (Listener)

Either i press minimize or close button it captures both of them.

I need one separate event for the minimize and the close button.

Body: Have you tried listening to Hide event?


问:
Uncaught Error Attempting to use a disconnected port object in Vue CLI App?
I've created a VueCLI App and once it runs on any web browser, the console shows following error when any action performed on a page, like a scroll down or up and click  anywhere on the page,

Uncaught Error: Attempting to use a disconnected port object
    at w.k.fa (content.js:16)

any help?

答: As this thread says, I disabled some plugins on browser, and re-run it. Then this error didn't rise.</p>


问:
Game server - high latency
I'm trying to host a Spigot Minecraft 1.12.2 Server using Ubuntu, The server has been properly set up and is working properly, The ping however isn't really great, I am playing from India and the server VM instance region has been set to Germany-Frankfurt, I should be getting anywhere between 130-200ms latency but It's always above 300 or even 1000 at times, I did tracert using windows CMD terminal and the packets seem to go to U.S.A first and then to Germany, I asked several of my friends to ping the server and they all get the same result. How can I fix this? Is there any way to route packets straight to Germany Instead of going to the U.S first?

Made a new Instance in Mumbai Region, India, which is where I live, I'm getting 3 Ping while on the server select menu, but upon joining it jumps to 200.

I expect around 130-160 ping, which is what I get on other servers on that region, Other players who live near Germany are getting high pings, I can't make this server public with a major issue like this.

答:
Have a look at the network map on this page: https://cloud.google.com/about/locations/#network-tab

As you can see, Google's network is not connected between Europe and India - therefore traffic has to take a detour around the other side of the world through Asia and the US.

Within a region, so from Germany to Germany and from India to India, you should however achieve low latency.

Title: Game server - high latency


问:
Corrupt rows written to __HIVE_DEFAULT_PARTITION__ when attempting to overwrite Hive partition
I am seeing some very odd behaviour when attempting to overwrite a partition in a Hive table using Spark 2.3

Firstly I am setting the following setting when building my SparkSession:

```<code>.config("spark.sql.sources.partitionOverwriteMode", "dynamic")
</code>```

I am then copying some data into  new table and partitioning by the date_id column.

```<code>ds
  .write
  .format("parquet")
  .option("compression", "snappy")
  .option("auto.purge", "true")
  .mode(saveMode)
  .partitionBy("date_id")
  .saveAsTable("tbl_copy")
</code>```

I can see in HDFS that the relevant date_id directories have been created.

I then create a DataSet containing data for the partition I wish to overwrite which contains data for a single date_id and insert into Hive as follows:

```<code>  ds
    .write
    .mode(SaveMode.Overwrite)
    .insertInto("tbl_copy")
</code>```

As a sanity check I write the same Dataset to a new table.

```<code>      ds
        .write
        .format("parquet")
        .option("compression", "snappy")
        .option("auto.purge", "true")
        .mode(SaveMode.Overwrite)
        .saveAsTable("tmp_tbl")
</code>```

The data in tmp_tbl is exactly as expected.

However when I look at tbl_copy I see a new HDFS directory `date_id=HIVE_DEFAULT_PARTITION

Querying tbl_cpy

```<code>SELECT * from tbl_copy WHERE date_id IS NULL
</code>```

I see the rows that should have been inserted into partition date_id=20180523 however the date_id column is null and an unrelated row_changed column has been populated with value 20180523.

It appears the insert into Hive is somehow causing my data to get mangled. Writing the same Dataset into a new table causes no issues.

Could anyone shed any light on this?

答:
Yes, this is a tricky behavior, explain in doc:

https://spark.apache.org/docs/2.1.2/api/java/org/apache/spark/sql/DataFrameWriter.html#insertInto(java.lang.String)

Unlike saveAsTable, insertInto ignores the column names and just uses
  position-based resolution. For example:

```<code>    scala> Seq((1, 2)).toDF("i", "j").write.mode("overwrite").saveAsTable("t1")
    scala> Seq((3, 4)).toDF("j", "i").write.insertInto("t1")
    scala> Seq((5, 6)).toDF("a", "b").write.insertInto("t1")
    scala> sql("select * from t1").show
    +---+---+
    |  i|  j|
    +---+---+
    |  5|  6|
    |  3|  4|
    |  1|  2|
    +---+---+
</code>```

Body:
I am seeing some very odd behaviour when attempting to overwrite a partition in a Hive table using Spark 2.3

Firstly I am setting the following setting when building my SparkSession:

.config("spark.sql.sources.partitionOverwriteMode", "dynamic")

I am then copying some data into  new table and partitioning by the date_id column.

ds
  .write
  .format("parquet")
  .option("compression", "snappy")
  .option("auto.purge", "true")
  .mode(saveMode)
  .partitionBy("date_id")
  .saveAsTable("tbl_copy")

I can see in HDFS that the relevant date_id directories have been created.

I then create a DataSet containing data for the partition I wish to overwrite which contains data for a single date_id and insert into Hive as follows:

  ds
    .write
    .mode(SaveMode.Overwrite)
    .insertInto("tbl_copy")

As a sanity check I write the same Dataset to a new table.

      ds
        .write
        .format("parquet")
        .option("compression", "snappy")
        .option("auto.purge", "true")
        .mode(SaveMode.Overwrite)
        .saveAsTable("tmp_tbl")

The data in tmp_tbl is exactly as expected.

However when I look at tbl_copy I see a new HDFS directory `date_id=HIVE_DEFAULT_PARTITION

Querying tbl_cpy

SELECT * from tbl_copy WHERE date_id IS NULL

I see the rows that should have been inserted into partition date_id=20180523 however the date_id column is null and an unrelated row_changed column has been populated with value 20180523.

It appears the insert into Hive is somehow causing my data to get mangled. Writing the same Dataset into a new table causes no issues.

Could anyone shed any light on this?

Body:
Yes, this is a tricky behavior, explain in doc:

https://spark.apache.org/docs/2.1.2/api/java/org/apache/spark/sql/DataFrameWriter.html#insertInto(java.lang.String)

Unlike saveAsTable, insertInto ignores the column names and just uses
  position-based resolution. For example:

    scala> Seq((1, 2)).toDF("i", "j").write.mode("overwrite").saveAsTable("t1")
    scala> Seq((3, 4)).toDF("j", "i").write.insertInto("t1")
    scala> Seq((5, 6)).toDF("a", "b").write.insertInto("t1")
    scala> sql("select * from t1").show
    +---+---+
    |  i|  j|
    +---+---+
    |  5|  6|
    |  3|  4|
    |  1|  2|
    +---+---+


问:
'function' object has no attribute 'columns'
I tried to encode columns as categories.

I can not work on my data frame because all columns are dtypes: object.

My code is:

categorize_column = lambda x: x.astype('category')

df.columns = df.columns.apply(categorize_column, axis=0)

I get an error:

'function' object has no attribute 'columns'

答:
According to the docs:

All columns in a DataFrame can be batch converted to categorical
  either during or after construction.

This can be done during construction by specifying dtype="category" in
  the DataFrame constructor:

So you have two options:

specify dtype='category' during the DataFrame construction df = pd.DataFrame(data, dtype='category')

convert existing DataFrame columns to dtype "category" df = df.astype('category')

df.columns in your example normally return a pandas.core.indexes.base.Index which you can think of as a list of column headers. It does not have an .apply method (pd.Series and pd.DataFrame do) and it has nothing to do with the values in your DataFrame.

Also, it seems that you accidentally assigned a function to df. If you want to try the second method, you will need to re-create your DataFrame before you do.


问:
how to generate video thumbnail in node.js?
I am building an app with node.js, I successfully uploaded the video, but I need to generate a video thumbnail for it. Currently I use node exec to execute a system command of ffmpeg to make the thumbnail.

```<code>   exec("C:/ffmpeg/bin/ffmpeg -i Video/" + Name  + " -ss 00:01:00.00 -r 1 -an -vframes 1 -f mjpeg Video/" + Name  + ".jpg")
</code>```

This code is coming from a tutorial from http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-resumable-video-uploade-in-node-js/

the code above did generate a jpg file but it's not a thumbnail but a video screen shot, I wonder is there any other method to generate video thumbnail, or how to exec the ffmpeg command to make a real thumbnail (resized), and I prefer png file.

答:
Using media-thumbnail, you can easily generate thumbnails from your videos. The module basically wraps the ffmpeg thumbnail functionality.

```<code>const mt = require('media-thumbnail')

mt.forVideo(
  './path/to/video.mp4',
  './path/to/thumbnail.png', {
    width: 200
  })
  .then(() => console.log('Success'), err => console.error(err))
</code>```

You can also create thumbnails from your images using this package.

Body:
I am building an app with node.js, I successfully uploaded the video, but I need to generate a video thumbnail for it. Currently I use node exec to execute a system command of ffmpeg to make the thumbnail.

   exec("C:/ffmpeg/bin/ffmpeg -i Video/" + Name  + " -ss 00:01:00.00 -r 1 -an -vframes 1 -f mjpeg Video/" + Name  + ".jpg")

This code is coming from a tutorial from http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-a-resumable-video-uploade-in-node-js/

the code above did generate a jpg file but it's not a thumbnail but a video screen shot, I wonder is there any other method to generate video thumbnail, or how to exec the ffmpeg command to make a real thumbnail (resized), and I prefer png file.

Body:
Using media-thumbnail, you can easily generate thumbnails from your videos. The module basically wraps the ffmpeg thumbnail functionality.

const mt = require('media-thumbnail')

mt.forVideo(
  './path/to/video.mp4',
  './path/to/thumbnail.png', {
    width: 200
  })
  .then(() => console.log('Success'), err => console.error(err))

You can also create thumbnails from your images using this package.


问:
Saving timestamp in mysql table using php
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

```<code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')
</code>```

答:
Some things to clarify:

MySQL timestamp field type doesn't store unix timestamps but rather a datetime-kind value.

UNIX timestamp is a number of a regular int type.

The timestamp you're talking about is not a regular unix timestamp but a timestamp with milliseconds.

therefore the correct answer would be

```<code>$timestamp = '1299762201428';
$date = date('Y-m-d H:i:s', substr($timestamp, 0, -3));
</code>```

Body:
I have a field in a MySQL table which has a timestamp data type. I am saving data into that table. But when I pass the timestamp (1299762201428) to the record, it automatically saves the value 0000-00-00 00:00:00 into that table.

How can I store the timestamp in a MySQL table?

Here is my INSERT statement:

INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
       (2,5,9,'2',1299762201428,5,10,20,'1')

Body:
Some things to clarify:

MySQL timestamp field type doesn't store unix timestamps but rather a datetime-kind value.

UNIX timestamp is a number of a regular int type.

The timestamp you're talking about is not a regular unix timestamp but a timestamp with milliseconds.

therefore the correct answer would be

$timestamp = '1299762201428';
$date = date('Y-m-d H:i:s', substr($timestamp, 0, -3));


问:
Can Someone Explain How the ball went forward from the camera?

private void Update()
{
    Ball.transform.position = PlayerCamera.transform.position +
                              PlayerCamera.transform.forward * DistanceBall;
}
```

答:
This is a pretty unclear question, but....

I will assume that you are trying to understandd better how the ball moves from the code you have given.

It looks like you are setting the ball's position to be the player's camera position plus the amount they have moved forward multiplied by the constant ball distance.

So whenever you move forward the PlayerCamera.transform.forward changes and so that adds or subtracts from the Ball.transform.position.


问:
Command Cool-down not recognizing ctx
Okay so basically, I wrote this code and it is saying

```<code>File "C:\Users\jellis\Desktop\Suggestion Bot\bot.py", line 28, in <module>
    @commands.cooldown(1, 1500, ctx)
NameError: name 'ctx' is not defined
</code>```

I've tried moving @commands.cooldown(1,1500 ctx) to after the async def suggest(ctx, *args) but it gave the same error.

@bot.command(pass_context = True)
@commands.cooldown(1, 1500, ctx)
async def suggest(ctx, *args):

    mesg = ' '.join(str(*args))
    embed = discord.Embed(title='New Suggestion', description='-----------', color=0x4C4CE7)

    if chatFilter in mesg:
        await bot.say(':x: Suggestion Could Not Be Sent.')
    elif chatFilter not in mesg:
        embed.add_field(name='{}'.format(ctx.message.author.display_name), value='{}'.format(mesg))
        await bot.send_message(discord.Object(id=suggestionsChannelID), embed=embed)

        white_check_mark = get(bot.get_all_emojis(), name='white_check_mark')
        await bot.add_reaction(message, white_check_mark)

        x = get(bot.get_all_emojis(), name='x')
        await bot.add_reaction(message, x)
        suggestionCount = suggestionCount + 1
    else:
        raise error

@bot.error
async def bot_error(error, member: discord.Member, ctx):
    if isinstance(error, commands.CommandOnCooldown):
        msg = ':x: {member} This command on cooldown, please try again in `{:.2f}s`'.format(error.retry_after)
        await bot.send_message(ctx.message.channel, msg)
    else:
        raise error
```

I expected it to detect that the command is on cooldown and then run the @bot.error event.

答:
Your cooldown will never be activated and will always run into an Error.
Because, since ctx is the Context-Container of your Bot and must not go there as Property.

The @commands.cooldown is specified as follows:

```<code>discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)
</code>```

You have to pass an Enum with the Bucket you want to use instead of the Context-Container (ctx).

Usable Buckets you can use are:

```<code>BucketType.default for a global basis.

BucketType.user for a per-user basis.

BucketType.guild for a per-guild basis.

BucketType.channel for a per-channel basis.

BucketType.member for a per-member basis.

BucketType.category for a per-category basis.
</code>```

For further Information you can find the Discord Documentation here.

Title: Command Cool-down not recognizing ctx

Body:
Okay so basically, I wrote this code and it is saying

File "C:\Users\jellis\Desktop\Suggestion Bot\bot.py", line 28, in <module>
    @commands.cooldown(1, 1500, ctx)
NameError: name 'ctx' is not defined

I've tried moving @commands.cooldown(1,1500 ctx) to after the async def suggest(ctx, *args) but it gave the same error.

@bot.command(pass_context = True)
@commands.cooldown(1, 1500, ctx)
async def suggest(ctx, *args):

    mesg = ' '.join(str(*args))
    embed = discord.Embed(title='New Suggestion', description='-----------', color=0x4C4CE7)

    if chatFilter in mesg:
        await bot.say(':x: Suggestion Could Not Be Sent.')
    elif chatFilter not in mesg:
        embed.add_field(name='{}'.format(ctx.message.author.display_name), value='{}'.format(mesg))
        await bot.send_message(discord.Object(id=suggestionsChannelID), embed=embed)

        white_check_mark = get(bot.get_all_emojis(), name='white_check_mark')
        await bot.add_reaction(message, white_check_mark)

        x = get(bot.get_all_emojis(), name='x')
        await bot.add_reaction(message, x)
        suggestionCount = suggestionCount + 1
    else:
        raise error

@bot.error
async def bot_error(error, member: discord.Member, ctx):
    if isinstance(error, commands.CommandOnCooldown):
        msg = ':x: {member} This command on cooldown, please try again in `{:.2f}s`'.format(error.retry_after)
        await bot.send_message(ctx.message.channel, msg)
    else:
        raise error

I expected it to detect that the command is on cooldown and then run the @bot.error event.

Body:
Your cooldown will never be activated and will always run into an Error.
Because, since ctx is the Context-Container of your Bot and must not go there as Property.

The @commands.cooldown is specified as follows:

discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)

You have to pass an Enum with the Bucket you want to use instead of the Context-Container (ctx).

Usable Buckets you can use are:

BucketType.default for a global basis.

BucketType.user for a per-user basis.

BucketType.guild for a per-guild basis.

BucketType.channel for a per-channel basis.

BucketType.member for a per-member basis.

BucketType.category for a per-category basis.

For further Information you can find the Discord Documentation here.


问:
How can I rename my project properly in Android Studio?
While renaming my project using Appendix: Utilities in Android studio, I'm having an error message on installing and running app on my android device. It shows me this
Error message.
Tell me how can I resolve this problem.</p>

答: Check your AndroidManifest.xml file and make sure the package in there is correct package.


问:
How to fix 'Post with this User already exists' error on Django while trying to add a new post?
I have a create_post view through which I try to add a new post to the blog I am working on. However, when I hit 'Submit' after filling out the form which includes User(a dropdown menu of all of the registered Users), Title, and Text, I get Post with this User already exists. As can be seen below, post.user has a foreignkey, User. Isn't suppose to mean that one Post can have only one user(author), and A User may have many posts. Why am I not allowed to add another post the same user?

Also, how do I utilize Django's built-in components to display a message such as 'Posting as {{user.username}} or Commenting as {{user.username}}' if user is authenticated.

Instead of having to write down a username in a textbox while leaving a comment, I would like to fetch username if user's logged in and not ask user to write a username in a textbox for I believe it makes no sense. I am thinking I may need to use widgets in forms.py and use HiddenInputs() maybe?

I apologize if I violate any community rules since I have recently joined this community and am still trying to figure out the norms and rules.

models.py

```<code>class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    published_date = models.DateTimeField(auto_now=True)

    def summary(self):
        """Return a summary for very long posts to
        get a glimpse from admin panel"""
        return self.text[:100]

    def pub_date_pretty(self):
        return self.published_date.strftime('%b %e, %Y')

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"pk": self.pk})

    class Meta:
        ordering = ['-published_date']
        unique_together = ('user',)
</code>```

forms.py

```<code>from django import forms
from .models import Post, Comment

class PostForm(forms.ModelForm):
    class Meta():
        model = Post
        fields = ['user', 'title', 'text',]

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('user', 'text',)
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .models import Post, Comment
from django.utils import timezone
from django.views.generic import ListView, DetailView
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404

@login_required
def create_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST)

        if post_form.is_valid():
            post = post_form.save(request)
            post.save()
        else:
            print(post_form.errors)
    else:
            post_form = PostForm()

    context = {
        'post_form': post_form,
    }

    return render(request, 'blog/addpost.html', context )

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post-detail', pk=pk)

    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form,
                                                             })

</code>```

答:
In Post.Meta you have defined a unique_together constraint with just user in it. This should  be removed

```<code>class Meta:
    ordering = ['-published_date']
    unique_together = ('user',)  # This line here
</code>```

Body:
I have a create_post view through which I try to add a new post to the blog I am working on. However, when I hit 'Submit' after filling out the form which includes User(a dropdown menu of all of the registered Users), Title, and Text, I get Post with this User already exists. As can be seen below, post.user has a foreignkey, User. Isn't suppose to mean that one Post can have only one user(author), and A User may have many posts. Why am I not allowed to add another post the same user?

Also, how do I utilize Django's built-in components to display a message such as 'Posting as {{user.username}} or Commenting as {{user.username}}' if user is authenticated.

Instead of having to write down a username in a textbox while leaving a comment, I would like to fetch username if user's logged in and not ask user to write a username in a textbox for I believe it makes no sense. I am thinking I may need to use widgets in forms.py and use HiddenInputs() maybe?

I apologize if I violate any community rules since I have recently joined this community and am still trying to figure out the norms and rules.

models.py

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    published_date = models.DateTimeField(auto_now=True)

    def summary(self):
        """Return a summary for very long posts to
        get a glimpse from admin panel"""
        return self.text[:100]

    def pub_date_pretty(self):
        return self.published_date.strftime('%b %e, %Y')

    def __str__(self):
        """String representation"""
        return self.title

    def get_absolute_url(self):
        """Returns the url to access a detailed post"""
        return reverse('post-detail', kwargs={"pk": self.pk})

    class Meta:
        ordering = ['-published_date']
        unique_together = ('user',)

forms.py

from django import forms
from .models import Post, Comment

class PostForm(forms.ModelForm):
    class Meta():
        model = Post
        fields = ['user', 'title', 'text',]

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('user', 'text',)

views.py

from django.shortcuts import render, redirect
from django.views.generic import TemplateView
from .models import Post, Comment
from django.utils import timezone
from django.views.generic import ListView, DetailView
from .forms import PostForm, CommentForm
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404

@login_required
def create_post(request):
    if request.method == 'POST':
        post_form = PostForm(request.POST)

        if post_form.is_valid():
            post = post_form.save(request)
            post.save()
        else:
            print(post_form.errors)
    else:
            post_form = PostForm()

    context = {
        'post_form': post_form,
    }

    return render(request, 'blog/addpost.html', context )

def add_comment_to_post(request, pk):
    post = get_object_or_404(Post, pk=pk)
    if request.method == 'POST':
        form = CommentForm(request.POST)

        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('post-detail', pk=pk)

    else:
        form = CommentForm()
    return render(request, 'blog/add_comment_to_post.html', {'form': form,
                                                             })

Body:
In Post.Meta you have defined a unique_together constraint with just user in it. This should  be removed

class Meta:
    ordering = ['-published_date']
    unique_together = ('user',)  # This line here


答:
Version 3.1.6

You are right, this is your local version of Typescript which is specific to your project.

Version 3.2.2

This is the global version of Typescript. That's why it is not changing in both location when you type tsc --version

There are some packages that requires specific versions of other libraries to work properly

Version 3.2.4

It is the dependency of @angular/cli i.e. when you'll install @angular/cli, it will automatically install this version of typescript as a dependency to work property.

Version 3.4.5

It is displaying in the right corner of VS code. Vs code comes with its own version of Typescript which it uses internally because  the editor is written in Typescript.

Title: Four different versions of typescript?


问:
What characters are allowed in MariaDB Full Text Search IN BOOLEAN MODE?
I want to pass user input through PHP to an SQL query on a MariaDB 10.1.37 InnoDB table to do a search. I want to protect against building invalid SQL queries. Currently I am removing the known operator characters like this:

```<code>preg_replace('/[\+\-\<\>\(\)\~\*\"]/', ' ', $user_input)
</code>```

Then I append a * character to each word. So if the user input is foo bar the query will be:

```<code>SELECT columnname, MATCH(columnname) AGAINST('foo* bar*' IN BOOLEAN MODE) AS score
FROM tablename;
</code>```

Unfortunately there are other characters that a user can input that will break the query. For example, if the user inputs % the query will be AGAINST('%*' IN BOOLEAN MODE) which gives the error: syntax error, unexpected $end, expecting FTS_TERM or FTS_NUMB or '*' .

I could try to filter out characters that cause problems (a blacklist) or I could try to whitelist characters that I know are ok.

I can't find anything in the documentation to define what characters are allowed or disallowed.

Is there a known set of characters that is either allowed or disallowed?

答:
Take the opposite approach?  Decide what characters to allow.

```<code>$x = preg_replace("/[^-'a-zA-Z0-9]/", ' ', $user_input);
$x = trim($x, '-');
</code>```

Keep:

Dash for hyphenated words

Apostrophe for contractions

Trim off things that might cause trouble

Remove:

Plus and asterisk -- because of FT syntax

Slash and double-quote -- PHP syntax

Then use double-quotes, not apostrophe, in

```<code>AGAINST("foo* bar*" IN BOOLEAN MODE)
</code>```

(See also the Comments, below.)

Body:
I want to pass user input through PHP to an SQL query on a MariaDB 10.1.37 InnoDB table to do a search. I want to protect against building invalid SQL queries. Currently I am removing the known operator characters like this:

preg_replace('/[\+\-\<\>\(\)\~\*\"]/', ' ', $user_input)

Then I append a * character to each word. So if the user input is foo bar the query will be:

SELECT columnname, MATCH(columnname) AGAINST('foo* bar*' IN BOOLEAN MODE) AS score
FROM tablename;

Unfortunately there are other characters that a user can input that will break the query. For example, if the user inputs % the query will be AGAINST('%*' IN BOOLEAN MODE) which gives the error: syntax error, unexpected $end, expecting FTS_TERM or FTS_NUMB or '*' .

I could try to filter out characters that cause problems (a blacklist) or I could try to whitelist characters that I know are ok.

I can't find anything in the documentation to define what characters are allowed or disallowed.

Is there a known set of characters that is either allowed or disallowed?

Body:
Take the opposite approach?  Decide what characters to allow.

$x = preg_replace("/[^-'a-zA-Z0-9]/", ' ', $user_input);
$x = trim($x, '-');

Keep:

Dash for hyphenated words

Apostrophe for contractions

Trim off things that might cause trouble

Remove:

Plus and asterisk -- because of FT syntax

Slash and double-quote -- PHP syntax

Then use double-quotes, not apostrophe, in

AGAINST("foo* bar*" IN BOOLEAN MODE)

(See also the Comments, below.)