问:
How do I test angular2 services that use moment?
I am trying to test an Angular (angular2) service I wrote that uses momentJS, but since moment lives in the browser I keep getting reference errors. Is there anyway to tell karma/jasmine how to use moment in a unit test? Here is the error I get:

```<code>ReferenceError: Can't find variable: moment in karma-test-shim.js (line 33814)
</code>```

Here are my tests:

```<code>describe('isDateBeforeToday', () => {
        it('should return true if date is before today', () => {
            let past = new Date(2016, 1, 1);
            expect(UnitService.isDateBeforeToday(past)).toEqual(true);

            past = new Date();
            past.setDate(past.getDate() - 1);
            past.setHours(23);
            expect(UnitService.isDateBeforeToday(past)).toEqual(true);
        });

        it('should return false if date is today', () => {
            let today = new Date();
            expect(UnitService.isDateBeforeToday(today)).toEqual(false);
        });

        it('should return false if date is in future', () => {
            let future = new Date();
            future.setDate(future.getDate() + 1);
            expect(UnitService.isDateBeforeToday(future)).toEqual(false);
        });
    });
</code>```

Here is the function I'm trying to test:

```<code>static isDateBeforeToday(date: Date) {
        let momentDate = moment(date);
        let now = moment();
        return (momentDate.diff(now, 'days') < 0);
    }
</code>```

karma-test-shim.js (based on angular examples):

```<code>Error.stackTraceLimit = Infinity;

require('core-js/es6');
require('core-js/es7/reflect');

require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

require('moment');

var appContext = require.context('../__tests__', true, /\.spec\.ts/);

appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());
</code>```

karma.conf.js:

```<code>var webpackConfig = require('./webpack.test');

module.exports = function (config) {
  var _config = {
    basePath: '',
    browserNoActivityTimeout: 20000, // had to increase this for component unit tests to work

    frameworks: ['jasmine'],

    files: [
      {pattern: './karma-test-shim.js', watched: false}
    ],

    preprocessors: {
      './karma-test-shim.js': ['webpack', 'sourcemap']
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      stats: 'errors-only'
    },

    webpackServer: {
      noInfo: true
    },

    reporters: ['progress','kjhtml'], //leave coverage reporter in for now, even though coverage not working

    coverageReporter: {
        type: 'html',
        dir: '../coverage/'
    },

    browsers: ['phantomJS_without_security'],
    customLaunchers: {
        chrome_without_security: {
            base: 'Chrome',
            flags: ['--disable-web-security']
        },
        phantomJS_without_security: {
            base:'PhantomJS',
            options: {
                windowName: 'Portal-tests',
                settings: {
                    webSecurityEnabled: false
                }
            }
        }
    },

    phantomjsLauncher: {
        // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
        exitOnResourceError: true
    },

    client: {
        captureConsole: true
    },

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    singleRun: true
  };

  config.set(_config);
};
</code>```

答:
For me the resolution was to import MomentModule in my TestBed

```<code>import { MomentModule } from 'angular2-moment';
    ...
    beforeEach(async(() => {
    TestBed.configureTestingModule({
    declarations: [MyComponent],
    imports: [MomentModule],
    ...
</code>```

taken from https://github.com/urish/ngx-moment/issues/165

Body:
I am trying to test an Angular (angular2) service I wrote that uses momentJS, but since moment lives in the browser I keep getting reference errors. Is there anyway to tell karma/jasmine how to use moment in a unit test? Here is the error I get:

ReferenceError: Can't find variable: moment in karma-test-shim.js (line 33814)

Here are my tests:

describe('isDateBeforeToday', () => {
        it('should return true if date is before today', () => {
            let past = new Date(2016, 1, 1);
            expect(UnitService.isDateBeforeToday(past)).toEqual(true);

            past = new Date();
            past.setDate(past.getDate() - 1);
            past.setHours(23);
            expect(UnitService.isDateBeforeToday(past)).toEqual(true);
        });

        it('should return false if date is today', () => {
            let today = new Date();
            expect(UnitService.isDateBeforeToday(today)).toEqual(false);
        });

        it('should return false if date is in future', () => {
            let future = new Date();
            future.setDate(future.getDate() + 1);
            expect(UnitService.isDateBeforeToday(future)).toEqual(false);
        });
    });

Here is the function I'm trying to test:

static isDateBeforeToday(date: Date) {
        let momentDate = moment(date);
        let now = moment();
        return (momentDate.diff(now, 'days') < 0);
    }

karma-test-shim.js (based on angular examples):

Error.stackTraceLimit = Infinity;

require('core-js/es6');
require('core-js/es7/reflect');

require('zone.js/dist/zone');
require('zone.js/dist/long-stack-trace-zone');
require('zone.js/dist/proxy');
require('zone.js/dist/sync-test');
require('zone.js/dist/jasmine-patch');
require('zone.js/dist/async-test');
require('zone.js/dist/fake-async-test');

require('moment');

var appContext = require.context('../__tests__', true, /\.spec\.ts/);

appContext.keys().forEach(appContext);

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(browser.BrowserDynamicTestingModule, browser.platformBrowserDynamicTesting());

karma.conf.js:

var webpackConfig = require('./webpack.test');

module.exports = function (config) {
  var _config = {
    basePath: '',
    browserNoActivityTimeout: 20000, // had to increase this for component unit tests to work

    frameworks: ['jasmine'],

    files: [
      {pattern: './karma-test-shim.js', watched: false}
    ],

    preprocessors: {
      './karma-test-shim.js': ['webpack', 'sourcemap']
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      stats: 'errors-only'
    },

    webpackServer: {
      noInfo: true
    },

    reporters: ['progress','kjhtml'], //leave coverage reporter in for now, even though coverage not working

    coverageReporter: {
        type: 'html',
        dir: '../coverage/'
    },

    browsers: ['phantomJS_without_security'],
    customLaunchers: {
        chrome_without_security: {
            base: 'Chrome',
            flags: ['--disable-web-security']
        },
        phantomJS_without_security: {
            base:'PhantomJS',
            options: {
                windowName: 'Portal-tests',
                settings: {
                    webSecurityEnabled: false
                }
            }
        }
    },

    phantomjsLauncher: {
        // Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
        exitOnResourceError: true
    },

    client: {
        captureConsole: true
    },

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: false,
    singleRun: true
  };

  config.set(_config);
};

Body:
For me the resolution was to import MomentModule in my TestBed

import { MomentModule } from 'angular2-moment';
    ...
    beforeEach(async(() => {
    TestBed.configureTestingModule({
    declarations: [MyComponent],
    imports: [MomentModule],
    ...

taken from https://github.com/urish/ngx-moment/issues/165


来源: stackexchange

问:
Unable to write dataframe into Hive partitioned parquet table using pyspark
I am trying to write my data frame into Partitioned hive table .Hive table format is parquet .

But i am unable to write the df to Hive table.

I am trying to write my data frame into Partitioned hive table .Hive table format is parquet .

But i am unable to write the df to Hive table.

Spark2.3 and Partitioned hive table

When i tried to load my finaldf into hive partitioned table i getting the below error

```<code>finaldf.write.mode("overwrite").format("parquet").partitionBy("mis_dt","country_codfe").saveAsTable("FinalTable")
</code>```

Error : u'Cannot overwrite table schema.Offertablethat is also being read from;'

When i google for the above error they have sugessted to load df into temp table and load into final hive table . I tried that option and again it failed with different error .

```<code>finaldf.createOrReplaceTempView('tmpTable')
final= spark.read.table('tmpTable')
final.write.mode("overwrite").insertInto("Finaltable")
</code>```

Error : Number of partitions created is 7004 which is more than 1000 .

But i do not think that we have that many partitions .

finaldf.write.mode("overwrite").format("parquet").partitionBy("mis_dt","country_codfe").saveAsTable("FinalTable")

2nd option :

```<code>finaldf.createOrReplaceTempView('tmpTable')
final= spark.read.table('tmpTable')
final.write.mode("overwrite").insertInto("Finaltable")
</code>```

I am looking to write the data into hive parquet file format table using spark 2.3

```<code>finaldf.write.mode("overwrite").format("parquet").partitionBy("mis_dt","cntry_cde").saveAsTable("finaltable")
</code>```

答:
spark.sql.sources.partitionOverwriteMode is introduced in Spark >= 2.3

```<code>sparkConf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
sparkConf.set("hive.exec.dynamic.partition", "true")
sparkConf.set("hive.exec.dynamic.partition.mode", "nonstrict")
</code>```

Use below code -

```<code>final.write.mode(SaveMode.Overwrite).insertInto("table")
</code>```

Note: The table should be created in Hive with partition.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write my data frame into Partitioned hive table .Hive table format is parquet .

But i am unable to write the df to Hive table.

I am trying to write my data frame into Partitioned hive table .Hive table format is parquet .

But i am unable to write the df to Hive table.

Spark2.3 and Partitioned hive table

When i tried to load my finaldf into hive partitioned table i getting the below error

finaldf.write.mode("overwrite").format("parquet").partitionBy("mis_dt","country_codfe").saveAsTable("FinalTable")

Error : u'Cannot overwrite table schema.Offertablethat is also being read from;'

When i google for the above error they have sugessted to load df into temp table and load into final hive table . I tried that option and again it failed with different error .

finaldf.createOrReplaceTempView('tmpTable')
final= spark.read.table('tmpTable')
final.write.mode("overwrite").insertInto("Finaltable")

Error : Number of partitions created is 7004 which is more than 1000 .

But i do not think that we have that many partitions .

finaldf.write.mode("overwrite").format("parquet").partitionBy("mis_dt","country_codfe").saveAsTable("FinalTable")

2nd option :

finaldf.createOrReplaceTempView('tmpTable')
final= spark.read.table('tmpTable')
final.write.mode("overwrite").insertInto("Finaltable")

I am looking to write the data into hive parquet file format table using spark 2.3

finaldf.write.mode("overwrite").format("parquet").partitionBy("mis_dt","cntry_cde").saveAsTable("finaltable")

Body:
spark.sql.sources.partitionOverwriteMode is introduced in Spark >= 2.3

sparkConf.set("spark.sql.sources.partitionOverwriteMode", "dynamic")
sparkConf.set("hive.exec.dynamic.partition", "true")
sparkConf.set("hive.exec.dynamic.partition.mode", "nonstrict")

Use below code -

final.write.mode(SaveMode.Overwrite).insertInto("table")

Note: The table should be created in Hive with partition.


问:
HomeBrew: Error- /usr/local/Cellar is not writable
When I run the following command in my terminal:

usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I get an error:

```<code>/usr/local/Cellar is not writable. You should change the
ownership and permissions of /usr/local/Cellar back to your
user account:
sudo chown -R $(whoami) /usr/local/Cellar
</code>```

Failed during: /usr/local/bin/brew update --force

I went through similar posts on S.O and all of them had the following commands as answer,so I ran the following commands in the terminal:

sudo chown -R $tejas /usr/local/Cellar

sudo chown -R $tejas:admin /usr/local/Cellar

sudo chown -R $tejas /usr/local

sudo chown -R $tejas:admin /usr/local

I ran the installation command after all above four command but it still gives me the error. Can someone please help me fix this. Thank you.

答:
As said in the comments, just do (without any substitution):</p>

```<code>sudo chown -R $(whoami) /usr/local/Cellar
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I run the following command in my terminal:

usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

I get an error:

/usr/local/Cellar is not writable. You should change the
ownership and permissions of /usr/local/Cellar back to your
user account:
sudo chown -R $(whoami) /usr/local/Cellar

Failed during: /usr/local/bin/brew update --force

I went through similar posts on S.O and all of them had the following commands as answer,so I ran the following commands in the terminal:

sudo chown -R $tejas /usr/local/Cellar

sudo chown -R $tejas:admin /usr/local/Cellar

sudo chown -R $tejas /usr/local

sudo chown -R $tejas:admin /usr/local

I ran the installation command after all above four command but it still gives me the error. Can someone please help me fix this. Thank you.

Body:
As said in the comments, just do (without any substitution):

sudo chown -R $(whoami) /usr/local/Cellar


问:
How to enumurate values from a list and then sum in a function?
I'm trying to create a function that uses the value and the index of the value, starting from 1 to put the values in a function and sums the whole list.

In other words I'm trying to get the present value of a list of cashflows that are not the same, therefor have to calculate the present value of each cash flow and sum them.

This is what I have tried.

```<code>cash = [10,10,10,10, 10, 10, 11, 10]
DiscoutRate = 0.12
    for (period, value) in enumerate(cash, start=1):
        PV = value/((1+DiscountRate)**period)
        print(PV)
</code>```

But I see that the results are not correct, any thoughts?

答:
You can also use python's map function for comprehensiveness.</p>

```<code>cash = [10,10,10,10, 10, 10, 11, 10]

def get_pv(ele):
    discount_rate = 0.12
    period, value = ele

    return value / ( (1+discount_rate) ** period )

out = list(map(get_pv, enumerate(cash, start=1)))
print(sum(out))
</code>```

Body:
I'm trying to create a function that uses the value and the index of the value, starting from 1 to put the values in a function and sums the whole list.

In other words I'm trying to get the present value of a list of cashflows that are not the same, therefor have to calculate the present value of each cash flow and sum them.

This is what I have tried.

cash = [10,10,10,10, 10, 10, 11, 10]
DiscoutRate = 0.12
    for (period, value) in enumerate(cash, start=1):
        PV = value/((1+DiscountRate)**period)
        print(PV)

But I see that the results are not correct, any thoughts?

Body:
You can also use python's map function for comprehensiveness.

cash = [10,10,10,10, 10, 10, 11, 10]

def get_pv(ele):
    discount_rate = 0.12
    period, value = ele

    return value / ( (1+discount_rate) ** period )

out = list(map(get_pv, enumerate(cash, start=1)))
print(sum(out))


问:
i have a project where i need to make special routing how i can make my own rule?
in my own site i need a thing that page are known by #topic.

it's need to look like

mywebsite.com#google [are this possible i need to pass google as parameter]
OR
mywebsite.com/#google [if first can not be done then how i can use it]

how i can apply this thing in my website. the thing i need to done that

if anyone open the site mywebsite.com#google that the content genrate dynamically through [passing google as parameter]

can anyone show how i can make routing for this

答:
You have the route table at Global.asax. Add this on the method RegisterRoutes. I am not so sure if it will work as I didn't test but that can give you a good start.</p>

```<code>        routes.MapRoute(
            "RouteWithSharp",
            "#{page}",
            new { controller = "Home", action = "Index", page = "" }  // Parameter defaults
        );
</code>```

OwnerDisplayName: delete my account

Body:
You have the route table at Global.asax. Add this on the method RegisterRoutes. I am not so sure if it will work as I didn't test but that can give you a good start.

        routes.MapRoute(
            "RouteWithSharp",
            "#{page}",
            new { controller = "Home", action = "Index", page = "" }  // Parameter defaults
        );


问:
How a basic if-statement works in Python?
I am starting with python and facing a basic issue with this nesting exercise:

```<code>bird_names="eagle", "pigeon", "colibri", "seagull"

bird_guess=input("Guess the bird: ")

if bird_guess in bird_names == False:
    print("Try again")
    bird_guess2=input("Guess the Bird: ")

    if bird_guess2 in birds == False:
        print("Try again")
        bird_guess3=input("Guess the Bird: ")

        if bird_guess3 in birds == False:
            print("Sorry out of tries")
        else:
            print("Yes 3rd try")
    else:
        print("Yes 2rd try")
else:
    print("Great, 1st try")
</code>```

When I run it and assing to bird_guess the value d for example, the code outputs direct Great, 1st try instead of going through all the other if statemnts.

Any idea where is my error?

答:
Starting out with a new language is great! Besides learning the language details, become also aware on how to write extendable code.

What happens, if you'd like to gave the user 5 instead of 3 guesses? You'll end up with 5 levels of ifs. An alternative to the nested ifs is a loop:

```<code>max_tries = 3
bird_names = ["eagle", "pigeon", "colibri", "seagull"]

for current_try in range(max_tries):
    guess = input("Guess the bird: ")
    if guess in bird_names:
        print(f"Yes, {current_try+1}. try!")
        break
    elif current_try < max_tries-1:
        print("Try again")
    else:
        print("Sorry, out of tries")
</code>```

Body:
I am starting with python and facing a basic issue with this nesting exercise:

bird_names="eagle", "pigeon", "colibri", "seagull"

bird_guess=input("Guess the bird: ")

if bird_guess in bird_names == False:
    print("Try again")
    bird_guess2=input("Guess the Bird: ")

    if bird_guess2 in birds == False:
        print("Try again")
        bird_guess3=input("Guess the Bird: ")

        if bird_guess3 in birds == False:
            print("Sorry out of tries")
        else:
            print("Yes 3rd try")
    else:
        print("Yes 2rd try")
else:
    print("Great, 1st try")

When I run it and assing to bird_guess the value d for example, the code outputs direct Great, 1st try instead of going through all the other if statemnts.

Any idea where is my error?

Body:
Starting out with a new language is great! Besides learning the language details, become also aware on how to write extendable code.

What happens, if you'd like to gave the user 5 instead of 3 guesses? You'll end up with 5 levels of ifs. An alternative to the nested ifs is a loop:

max_tries = 3
bird_names = ["eagle", "pigeon", "colibri", "seagull"]

for current_try in range(max_tries):
    guess = input("Guess the bird: ")
    if guess in bird_names:
        print(f"Yes, {current_try+1}. try!")
        break
    elif current_try < max_tries-1:
        print("Try again")
    else:
        print("Sorry, out of tries")


问:
column not allowed here
```<code>CREATE OR REPLACE TRIGGER update_QOH
BEFORE INSERT ON ORDERLINE
FOR EACH ROW
DECLARE
    QOH_PRODUCT PRODUCT.QOH%TYPE;
    ORD_NO ORDERS.ORDER_NO%TYPE;
BEGIN
    SELECT QOH INTO QOH_PRODUCT FROM PRODUCT
    WHERE :old.product_no = :new.product_no;

    SELECT ORDER_NO INTO ORD_NO FROM ORDERLINE
    WHERE :old.order_no = :new.order_no;

    IF (:new.QTY <= QOH_PRODUCT) THEN
        UPDATE PRODUCT SET QOH = QOH_PRODUCT - :new.QTY;
    ELSE
        send_email(ord_no, 'Backorder');

        INSERT INTO BACKORDER
        VALUES (backorder_no_seq.NEXTVAL, :new.product_no, :new.qty, SYSDATE);

        INSERT INTO PRODVENDOR
        VALUES (po_no_seq.NEXTVAL, vendor_no, :new.product_no, vend_qty,
            shipping_method, SYSDATE, NULL, NULL, NULL);
    END IF;
END;
/
-------------------------------------------------------------------------------
Error(13,3): PL/SQL: SQL Statement ignored

Error(13,91): PL/SQL: ORA-00984: column not allowed here
--------------------------------------------------------------------------------
</code>```

Product table (P_no, QOH, etc)

Orderline table (OL_no, QTY, etc)

Backorder table (B_no, B_QTY, etc)

Vendor table (V_no, etc)

I need to make sure that when a customer buys a product, there is enough QOH in product table, if there is, QOH in Product should be decreased (updated). If not, send email to customer, update the backorder table and the product should be ordered  from the vendor.

答:
Firstly, consider putting the insert into a procedure instead of a trigger. (And a more helpful name, maybe). Inserting to or updating other tables from here could get messy if they get their own triggers later, and it's hard to keep track of what's going on where and when.

Secondly, this looks like it won't handle concurrent inserts very well - two new ORDERLINE inserts for the same product at the same time will try to update the product QOH with probably unexpected, or undesirable, results - QOH can go negative, for example. You're also potentially going to get multiple orders to the vendor; every order line that requests an out-of-stock product is going to make a new order to the vendor, even if each order line quantity is 1 and you order 100 at a time from the vendor.

Thirdly, various code errors; I'll start with a couple of more obvious ones:

a) You're selecting from PRODUCT and ORDERLINE with WHERE :old.product_no = :new.product_no. I'm not sure :OLD is even set in a before-insert trigger, but if it is it will be the same as :NEW or null, so you're possibly going to get ORA-02112 or ORA-01403 errors as it'll find all rows, or maybe none.

b) Your select from ORDERLINE will return no rows on the first order line and multiple rows from the third onwards anyway, so again you'll get ORA-01403 and ORA-02112 errors. But it's pointless as you're just selecting the value you're querying on. You can just use the :NEW value in the email call.

c) Your update of PRODUCT has no WHERE clause, so all QOH values will be updated.

```<code>CREATE OR REPLACE TRIGGER update_QOH
BEFORE INSERT ON ORDERLINE
FOR EACH ROW
DECLARE
    QOH_PRODUCT PRODUCT.QOH%TYPE;
BEGIN
    SELECT QOH INTO QOH_PRODUCT FROM PRODUCT
    WHERE product_no = :new.product_no;

    IF (:new.QTY <= QOH_PRODUCT) THEN
        UPDATE PRODUCT SET QOH = QOH_PRODUCT - :new.QTY;
        WHERE product_no = :new.product_no;
    ELSE
        send_email(:new.order_no, 'Backorder');

        INSERT INTO BACKORDER
        VALUES (backorder_no_seq.NEXTVAL, :new.product_no, :new.qty, SYSDATE);

        INSERT INTO PRODVENDOR
        VALUES (po_no_seq.NEXTVAL, vendor_no, :new.product_no, vend_qty,
            shipping_method, SYSDATE, NULL, NULL, NULL);
    END IF;
END;
/
</code>```

d) Where are vend_no, vend_qty and shipping_method coming from in the insert to PRODVENDOR? This is the only obvious compilation error that jumps out.

e) You aren't specifying the table columns in the inserts. This will cause a compilation error if you have the values in the wrong order, or any missing, but you can't tell just by looking at the code. (You haven't said what the 'so may' errors are after @WW's change, so don't know if this is relevant). And if another column is added later, this trigger will become invalid, so it's generally a good idea to list the columns explicitly.

Functionally you seem to be sending an email saying the whole order is on back-order, rather than just this product; and there don't seem to be any links between the current order and what you're putting in to BACKORDER and PRODVENDOR.

Title: column not allowed here

Body:
CREATE OR REPLACE TRIGGER update_QOH
BEFORE INSERT ON ORDERLINE
FOR EACH ROW
DECLARE
    QOH_PRODUCT PRODUCT.QOH%TYPE;
    ORD_NO ORDERS.ORDER_NO%TYPE;
BEGIN
    SELECT QOH INTO QOH_PRODUCT FROM PRODUCT
    WHERE :old.product_no = :new.product_no;

    SELECT ORDER_NO INTO ORD_NO FROM ORDERLINE
    WHERE :old.order_no = :new.order_no;

    IF (:new.QTY <= QOH_PRODUCT) THEN
        UPDATE PRODUCT SET QOH = QOH_PRODUCT - :new.QTY;
    ELSE
        send_email(ord_no, 'Backorder');

        INSERT INTO BACKORDER
        VALUES (backorder_no_seq.NEXTVAL, :new.product_no, :new.qty, SYSDATE);

        INSERT INTO PRODVENDOR
        VALUES (po_no_seq.NEXTVAL, vendor_no, :new.product_no, vend_qty,
            shipping_method, SYSDATE, NULL, NULL, NULL);
    END IF;
END;
/
-------------------------------------------------------------------------------
Error(13,3): PL/SQL: SQL Statement ignored

Error(13,91): PL/SQL: ORA-00984: column not allowed here
--------------------------------------------------------------------------------

Product table (P_no, QOH, etc)

Orderline table (OL_no, QTY, etc)

Backorder table (B_no, B_QTY, etc)

Vendor table (V_no, etc)

I need to make sure that when a customer buys a product, there is enough QOH in product table, if there is, QOH in Product should be decreased (updated). If not, send email to customer, update the backorder table and the product should be ordered  from the vendor.

Body:
Firstly, consider putting the insert into a procedure instead of a trigger. (And a more helpful name, maybe). Inserting to or updating other tables from here could get messy if they get their own triggers later, and it's hard to keep track of what's going on where and when.

Secondly, this looks like it won't handle concurrent inserts very well - two new ORDERLINE inserts for the same product at the same time will try to update the product QOH with probably unexpected, or undesirable, results - QOH can go negative, for example. You're also potentially going to get multiple orders to the vendor; every order line that requests an out-of-stock product is going to make a new order to the vendor, even if each order line quantity is 1 and you order 100 at a time from the vendor.

Thirdly, various code errors; I'll start with a couple of more obvious ones:

a) You're selecting from PRODUCT and ORDERLINE with WHERE :old.product_no = :new.product_no. I'm not sure :OLD is even set in a before-insert trigger, but if it is it will be the same as :NEW or null, so you're possibly going to get ORA-02112 or ORA-01403 errors as it'll find all rows, or maybe none.

b) Your select from ORDERLINE will return no rows on the first order line and multiple rows from the third onwards anyway, so again you'll get ORA-01403 and ORA-02112 errors. But it's pointless as you're just selecting the value you're querying on. You can just use the :NEW value in the email call.

c) Your update of PRODUCT has no WHERE clause, so all QOH values will be updated.

CREATE OR REPLACE TRIGGER update_QOH
BEFORE INSERT ON ORDERLINE
FOR EACH ROW
DECLARE
    QOH_PRODUCT PRODUCT.QOH%TYPE;
BEGIN
    SELECT QOH INTO QOH_PRODUCT FROM PRODUCT
    WHERE product_no = :new.product_no;

    IF (:new.QTY <= QOH_PRODUCT) THEN
        UPDATE PRODUCT SET QOH = QOH_PRODUCT - :new.QTY;
        WHERE product_no = :new.product_no;
    ELSE
        send_email(:new.order_no, 'Backorder');

        INSERT INTO BACKORDER
        VALUES (backorder_no_seq.NEXTVAL, :new.product_no, :new.qty, SYSDATE);

        INSERT INTO PRODVENDOR
        VALUES (po_no_seq.NEXTVAL, vendor_no, :new.product_no, vend_qty,
            shipping_method, SYSDATE, NULL, NULL, NULL);
    END IF;
END;
/

d) Where are vend_no, vend_qty and shipping_method coming from in the insert to PRODVENDOR? This is the only obvious compilation error that jumps out.

e) You aren't specifying the table columns in the inserts. This will cause a compilation error if you have the values in the wrong order, or any missing, but you can't tell just by looking at the code. (You haven't said what the 'so may' errors are after @WW's change, so don't know if this is relevant). And if another column is added later, this trigger will become invalid, so it's generally a good idea to list the columns explicitly.

Functionally you seem to be sending an email saying the whole order is on back-order, rather than just this product; and there don't seem to be any links between the current order and what you're putting in to BACKORDER and PRODVENDOR.


问:
SSH to Google Compute instance using NodeJS, without gcloud
I'm trying to create a SSH tunnel into a compute instance, from an environment that doesn't have gcloud installed (App Engine Standard NodeJS Environment).

What are the steps needed to do that? How does gcloud compute ssh command does it? Is there a NodeJS library that already does it?

答:
In general, you'd need to reserve & assign a static external IP address to begin with (unless trying to SSH from within the same network). And a firewall rule needs to be defined for port tcp/22, which then can be applied as a "label" to the network interface, which has that external IP assigned.

The other way around works with gcloud app instances ssh:

SSH into the VM of an App Engine Flexible instance

which might be less effort & cost to setup, because a GCP VM usually has gcloud installed.


问:
Fitting a string into a predetermined pattern?
I have a dataframe column that looks like:

```<code>A002
A0011
A0001
A0001A
A2
A3A
A02
</code>```

and need to fit it into the format A00XXY
i.e.:

```<code>A0002
A0011
A0001
A0001A
A0002
A0003A
A0002
</code>```

I currently have

```<code>df.col.str.lstrip('A0')
for x in df.col.str.contains(r'[0-9]\w{1}$'):
    if x:
        df.col = 'A000' + df.col
    else:
        df.col = 'A00' + df.col
</code>```

But this becomes recursive? What would be the best method to do this?

答:
To completely generalize this, so it will work in all cases, I will take some extra steps and regex to come to your expected output:

```<code>df['Start_letter'] = df['Col'].str.extract('(^[A-Za-z])').fillna('')              # Extract the first letter
df['End_letter'] = df['Col'].str.extract('([A-Za-z]$)').fillna('')                # Extract the last letter
df['Nums'] = df['Col'].str.replace('[A-Za-z]', '').apply(lambda x: x.zfill(4))    # Extract the numbers between the letters
df['Col'] = df['Start_letter'] + df['Nums'] + df['End_letter']

df = df.iloc[:, :1]
</code>```

```<code>      Col
0   A0002
1   A0011
2   A0001
3  A0001A
4   A0002
5  A0003A
6   A0002
</code>```

Body:
I have a dataframe column that looks like:

A002
A0011
A0001
A0001A
A2
A3A
A02

and need to fit it into the format A00XXY
i.e.:

A0002
A0011
A0001
A0001A
A0002
A0003A
A0002

I currently have

df.col.str.lstrip('A0')
for x in df.col.str.contains(r'[0-9]\w{1}$'):
    if x:
        df.col = 'A000' + df.col
    else:
        df.col = 'A00' + df.col

But this becomes recursive? What would be the best method to do this?

Body:
To completely generalize this, so it will work in all cases, I will take some extra steps and regex to come to your expected output:

df['Start_letter'] = df['Col'].str.extract('(^[A-Za-z])').fillna('')              # Extract the first letter
df['End_letter'] = df['Col'].str.extract('([A-Za-z]$)').fillna('')                # Extract the last letter
df['Nums'] = df['Col'].str.replace('[A-Za-z]', '').apply(lambda x: x.zfill(4))    # Extract the numbers between the letters
df['Col'] = df['Start_letter'] + df['Nums'] + df['End_letter']

df = df.iloc[:, :1]

      Col
0   A0002
1   A0011
2   A0001
3  A0001A
4   A0002
5  A0003A
6   A0002


问:
Display multiple lines within a Jlist cell
How can I display multiple lines within a single cell of a JList. In jtable, it is achieved by adding a JTextarea to the table cell renderer. Similiarly, Is there any code to add a custom cell renderer for a JList that holds a textarea? If yes, can you please give me a code snippet for the same?

Or do you think there is any other better method to display multiple lines within the cell of Jlist instead of using a textarea? please help me!!

答:
Try with html.</p>

```<code>"line one <br/> linetwo"
</code>```

Body:
Try with html.

"line one <br/> linetwo"


问:
keep the returned matrix after indexing as a vector
I followed a tutorial https://www.datamentor.io/r-programming/matrix/ about R language on how to keep the returned matrix after indexing a matrix, instead of a vector. However, it does not work and the class of the returned matrix is still a vector

I tried to use one comma, then two comma like it was shown in the tutorial.

```<code>[1] 3 6 9
> class(x[x%%3==0])
[1] "integer"
> x[x%%3==0, drop=FALSE]
[1] 3 6 9
> class(x[x%%3==0, drop=FALSE])
[1] "integer"
> x[x%%3==0,, drop=FALSE]
Error in x[x%%3 == 0, , drop = FALSE] :
  (subscript) logical subscript too long
> x[x%%3==0,,.drop=FALSE]
Error in x[x%%3 == 0, , .drop = FALSE] : incorrect number of dimensions
> x[x%%3==0,,drop=FALSE]
Error in x[x%%3 == 0, , drop = FALSE] :
  (subscript) logical subscript too long
> class(x[x%%3==0, drop=FALSE])
[1] "integer"
</code>```

The class is still integer, instead of matrix, which is what the drop=FALSE is suppose to do

答:
The output of

```<code>x %% 3==0
#     A     B     C
#X FALSE FALSE FALSE
#Y FALSE FALSE FALSE
#Z  TRUE  TRUE  TRUE
</code>```

is a logical matrix

Subsetting the initial matrix using logical matrix gives the elements based on the position of TRUE

```<code>which(x%%3 == 0)
#[1] 3 6 9
</code>```

Those are the same values in the matrix we got from extraction and this doesn't differentiate any rows, e.g.

```<code>x > 3
#     A    B    C
#X FALSE TRUE TRUE
#Y FALSE TRUE TRUE
#Z FALSE TRUE TRUE

x[x > 3]
#[1] 4 5 6 7 8 9
</code>```

In order to extract the row as such, we may need to get a logical vector.  One option is rowSums and compare with the number of columns

```<code>x[rowSums(x %%3 == 0) == ncol(x),, drop = FALSE]
#  A B C
#Z 3 6 9
</code>```

data

```<code>x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))
</code>```

Body:
I followed a tutorial https://www.datamentor.io/r-programming/matrix/ about R language on how to keep the returned matrix after indexing a matrix, instead of a vector. However, it does not work and the class of the returned matrix is still a vector

I tried to use one comma, then two comma like it was shown in the tutorial.

[1] 3 6 9
> class(x[x%%3==0])
[1] "integer"
> x[x%%3==0, drop=FALSE]
[1] 3 6 9
> class(x[x%%3==0, drop=FALSE])
[1] "integer"
> x[x%%3==0,, drop=FALSE]
Error in x[x%%3 == 0, , drop = FALSE] :
  (subscript) logical subscript too long
> x[x%%3==0,,.drop=FALSE]
Error in x[x%%3 == 0, , .drop = FALSE] : incorrect number of dimensions
> x[x%%3==0,,drop=FALSE]
Error in x[x%%3 == 0, , drop = FALSE] :
  (subscript) logical subscript too long
> class(x[x%%3==0, drop=FALSE])
[1] "integer"

The class is still integer, instead of matrix, which is what the drop=FALSE is suppose to do

Body:
The output of

x %% 3==0
#     A     B     C
#X FALSE FALSE FALSE
#Y FALSE FALSE FALSE
#Z  TRUE  TRUE  TRUE

is a logical matrix

Subsetting the initial matrix using logical matrix gives the elements based on the position of TRUE

which(x%%3 == 0)
#[1] 3 6 9

Those are the same values in the matrix we got from extraction and this doesn't differentiate any rows, e.g.

x > 3
#     A    B    C
#X FALSE TRUE TRUE
#Y FALSE TRUE TRUE
#Z FALSE TRUE TRUE

x[x > 3]
#[1] 4 5 6 7 8 9

In order to extract the row as such, we may need to get a logical vector.  One option is rowSums and compare with the number of columns

x[rowSums(x %%3 == 0) == ncol(x),, drop = FALSE]
#  A B C
#Z 3 6 9

data

x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))


问:
Hazelcast node not discovering other node when use docker stack deploy
I need to setup a hazelcast for web application with multiple replication factors in docker environment and using docker swarm to deploy the app in multi host using overlay network.

I am facing the problem that service are not able to discover the other node in swarm mode, however working fine in docker compose. I am using below config for hazelcast configuration.

```<code><port auto-increment="true">5701</port>
<join>
  <multicast enabled="false">
    <multicast-group>224.2.2.3</multicast-group>
    <multicast-port>54327</multicast-port>
  </multicast>
  <tcp-ip enabled="true">
    <member>hazelcast-master</member>
  </tcp-ip>

</join>
</code>```

here hazelcast-master is my service name in docker.

Any help would be appreciated

答: How did you configure your docker network? Is hazelcast-master in your DNS server? By default docker uses the same DNS as the host, but if you for example put hazelcast-master in /etc/hosts, your docker guest will not see it and won't be able to use it. Either use IP address of the host, put full host domain name (from DNS) or use --add-host when running docker container.</p>

Body:
I need to setup a hazelcast for web application with multiple replication factors in docker environment and using docker swarm to deploy the app in multi host using overlay network.

I am facing the problem that service are not able to discover the other node in swarm mode, however working fine in docker compose. I am using below config for hazelcast configuration.

<port auto-increment="true">5701</port>
<join>
  <multicast enabled="false">
    <multicast-group>224.2.2.3</multicast-group>
    <multicast-port>54327</multicast-port>
  </multicast>
  <tcp-ip enabled="true">
    <member>hazelcast-master</member>
  </tcp-ip>

</join>

here hazelcast-master is my service name in docker.

Any help would be appreciated


问:
How to convert an array?
I need to reformat an array from one type to another using library "Lodash".

I initially have such an array:

```<code>[{
    "language": {
      "displayName": {
        "en": "English"
      },
      "id": 1
    },
    "level": {
      "id": 1,
      "displayName": {
        "en": "Intermediate"
      }
    }
  }, {
    "language": {
      "displayName": {
        "en": "Russian"
      },
      "id": 2
    },
    "level": {
      "id": 1
      "displayName": {
        "en": "Fluent"
      }
    }
  }]
</code>```

How to convert an array in this format:

```<code>[{
    "language": 1, // it is language.id
    "level": 1 // it is level.id
  }, {
    "language": 2, // it is language.id
    "level": 2 // it is level.id
}]
</code>```

答:
You could use map like this:

const input=[{language:{displayName:{en:"English"},id:1},level:{id:1,displayName:{en:"Intermediate"}}},{language:{displayName:{en:"Russian"},id:2},level:{id:1,displayName:{en:"Fluent"}}}];

const output = input.map(o => ({ language: o.language.id, level: o.level.id }))

console.log(output)```

Title: How to convert an array?

Body:
I need to reformat an array from one type to another using library "Lodash".

I initially have such an array:

[{
    "language": {
      "displayName": {
        "en": "English"
      },
      "id": 1
    },
    "level": {
      "id": 1,
      "displayName": {
        "en": "Intermediate"
      }
    }
  }, {
    "language": {
      "displayName": {
        "en": "Russian"
      },
      "id": 2
    },
    "level": {
      "id": 1
      "displayName": {
        "en": "Fluent"
      }
    }
  }]

How to convert an array in this format:

[{
    "language": 1, // it is language.id
    "level": 1 // it is level.id
  }, {
    "language": 2, // it is language.id
    "level": 2 // it is level.id
}]


问:
How to convert snapshot in typescript code for firebase cloud functions into string to use for notification?
I have the bellow code for cloud functions which is meant to, on creation of a new follower, send a notification to the user. The issue is that I dont know how to convert the snap into a string so that I can fix the error message included bellow.

```<code> function sendNewFollowNotificationFunc(uuid: string, newFollower: string) {
  // const userRef = admin.database().ref('PeopleWhoFollowMe').child(uuid)
  // const fetchAndUpdate = userRef.once('value')
  console.log('User to send notification', uuid);

  admin.database().ref(`UsersFireTokens`).child(uuid).child("token").once('value')
  .then(snap => {
    const token = snap.val//I dont know how, from here I should be handling this inorder to get the value at this location which is the token
    // This registration token comes from the client FCM SDKs.
    var registrationToken = token;

    var message = {
      data: {
        text: 'This is a test',
        time: '2:45'
      },
      token: registrationToken
    };

    // Send a message to the device corresponding to the provided
    // registration token.
    admin.messaging().send(message)//error here
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
      })
      .catch((error) => {
        console.log('Error sending message:', error);
      });
  })
  .catch(error => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
</code>```

The problem is I am getting many errors such as:

Argument of type '{ data: { text: string; time: string; }; token: string | null; }' is not assignable to parameter of type 'Message'.
    Type '{ data: { text: string; time: string; }; token: string | null; }' is not assignable to type 'TokenMessage'.
      Types of property 'token' are incompatible.
        Type 'string | null' is not assignable to type 'string'.
          Type 'null' is not assignable to type 'string'.ts(2345)

What am I doing wrong and how can I fix it?

Update:

This is my code:

```<code>function sendNewFollowNotificationFunc(uuid: string, newFollower: string) {
  // const userRef = admin.database().ref('PeopleWhoFollowMe').child(uuid)
  // const fetchAndUpdate = userRef.once('value')
  console.log('User to send notification', uuid);

  admin.database().ref(`UsersFireTokens`).child(uuid).child("token").once('value')
  .then(snap => {
    //What should I be doing here and how?
console.log('token value', snap.val);//doing this returns a strange function thing in the logs

  })
  .catch(error => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
}
</code>```

答:
The long and convoluted tsc message tells you that your message variable has the type:

{ data: { text: string; time: string; }; token: string | null; }

but send expects a TokenMessage. It is impossible to know all about the TokenMessage type from your code, but it appears that it contains a token field of type string. Your message, on the other hand, has a token field with type string | null. Therefore, types not match: your message may not have a token, while send expects something that is guaranteed to have a token string.

What am I doing wrong and how can I fix it?

You need to call send with some value that complies with the TokenMessage type.

To do so, one way is to cast message to tokenMessage:

```<code> admin.messaging().send(message as Message)
</code>```

(tldr: the above like will probably fix your issue)

Sometimes, two types are too incompatibles to be casted. In such cases, you cannot force it as in the above line. You can still cast to any and then to your desired type:

admin.messaging().send(message as any as Message)

Said so, this is not always that you should do:

Typescript is complaining about message maybe not having a token. That's neat. usually, you can avoid those tsc warnings by making assertions over your variables:

```<code>function getToken(): string | null {
    return 'f00';
}

function test(s: string) {

}

const t = getToken();

test(t); // error

if (t) {
    test(t); // safe, no error
    // this is great because force you to handle potential null stuff at developing time
}
</code>```

But this doesn't seem to work with object fields:

```<code>function getToken(): string | null {
    return 'f00';
}

interface Message{
    token: string;
}

function send(m: Message) {

}

const t = getToken();

const message = {
    token: t,
}

send(message); // error

if (t) {
    send(message); // error
}

if (message.token) {
    send(message); // still an error, this puzzles me a lot. At this point tsc should now that message complies with Message. There is something I don't have clear at this point.
}

send(message as Message); // valid
</code>```

In general, it is better an safer to check for nulls via if blocks rather than casting types manually. But sometimes there is no other way around.

Body:
I have the bellow code for cloud functions which is meant to, on creation of a new follower, send a notification to the user. The issue is that I dont know how to convert the snap into a string so that I can fix the error message included bellow.

 function sendNewFollowNotificationFunc(uuid: string, newFollower: string) {
  // const userRef = admin.database().ref('PeopleWhoFollowMe').child(uuid)
  // const fetchAndUpdate = userRef.once('value')
  console.log('User to send notification', uuid);

  admin.database().ref(`UsersFireTokens`).child(uuid).child("token").once('value')
  .then(snap => {
    const token = snap.val//I dont know how, from here I should be handling this inorder to get the value at this location which is the token
    // This registration token comes from the client FCM SDKs.
    var registrationToken = token;

    var message = {
      data: {
        text: 'This is a test',
        time: '2:45'
      },
      token: registrationToken
    };

    // Send a message to the device corresponding to the provided
    // registration token.
    admin.messaging().send(message)//error here
      .then((response) => {
        // Response is a message ID string.
        console.log('Successfully sent message:', response);
      })
      .catch((error) => {
        console.log('Error sending message:', error);
      });
  })
  .catch(error => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })

The problem is I am getting many errors such as:

Argument of type '{ data: { text: string; time: string; }; token: string | null; }' is not assignable to parameter of type 'Message'.
    Type '{ data: { text: string; time: string; }; token: string | null; }' is not assignable to type 'TokenMessage'.
      Types of property 'token' are incompatible.
        Type 'string | null' is not assignable to type 'string'.
          Type 'null' is not assignable to type 'string'.ts(2345)

What am I doing wrong and how can I fix it?

Update:

This is my code:

function sendNewFollowNotificationFunc(uuid: string, newFollower: string) {
  // const userRef = admin.database().ref('PeopleWhoFollowMe').child(uuid)
  // const fetchAndUpdate = userRef.once('value')
  console.log('User to send notification', uuid);

  admin.database().ref(`UsersFireTokens`).child(uuid).child("token").once('value')
  .then(snap => {
    //What should I be doing here and how?
console.log('token value', snap.val);//doing this returns a strange function thing in the logs

  })
  .catch(error => {
    console.log("Error in catch: "+error)
    response.status(500).send(error)
  })
}

Body:
The long and convoluted tsc message tells you that your message variable has the type:

{ data: { text: string; time: string; }; token: string | null; }

but send expects a TokenMessage. It is impossible to know all about the TokenMessage type from your code, but it appears that it contains a token field of type string. Your message, on the other hand, has a token field with type string | null. Therefore, types not match: your message may not have a token, while send expects something that is guaranteed to have a token string.

What am I doing wrong and how can I fix it?

You need to call send with some value that complies with the TokenMessage type.

To do so, one way is to cast message to tokenMessage:

 admin.messaging().send(message as Message)

(tldr: the above like will probably fix your issue)

Sometimes, two types are too incompatibles to be casted. In such cases, you cannot force it as in the above line. You can still cast to any and then to your desired type:

admin.messaging().send(message as any as Message)

Said so, this is not always that you should do:

Typescript is complaining about message maybe not having a token. That's neat. usually, you can avoid those tsc warnings by making assertions over your variables:

function getToken(): string | null {
    return 'f00';
}

function test(s: string) {

}

const t = getToken();

test(t); // error

if (t) {
    test(t); // safe, no error
    // this is great because force you to handle potential null stuff at developing time
}

But this doesn't seem to work with object fields:

function getToken(): string | null {
    return 'f00';
}

interface Message{
    token: string;
}

function send(m: Message) {

}

const t = getToken();

const message = {
    token: t,
}

send(message); // error

if (t) {
    send(message); // error
}

if (message.token) {
    send(message); // still an error, this puzzles me a lot. At this point tsc should now that message complies with Message. There is something I don't have clear at this point.
}

send(message as Message); // valid

In general, it is better an safer to check for nulls via if blocks rather than casting types manually. But sometimes there is no other way around.


问:
Fs2 Stream.Compiler is not found (could not find implicit value Compiler[[x]F[x],G])
I am trying to compile the stream, but somehow Compiler is not in scope, what context bound is needed for bringing it in scope?

```<code>import cats.Monad

def compilingStream[F[_]: Monad]: F[List[Int]] = {
  val stream: fs2.Stream[F, Int] = fs2.Stream.emit(1).covary[F]
  stream.head.compile.toList
}

error: could not find implicit value for parameter compiler: fs2.Stream.Compiler[[x]F[x],G]
         stream.head.compile.toList
                     ^

</code>```

答:
Fs2 Stream#compile now requires a Sync[F] (see this):

  import cats.effect.Sync

  def compilingStream[F[_]: Sync]: F[List[Int]] = {
    val stream: fs2.Stream[F, Int] = fs2.Stream.emit(1).covary[F]
    stream.head.compile.toList
  }
```

This is communicated by the library maintainer:

fs2 Stream#compile now requires a Sync[F]. Even on completely pure streams. Because of resource management. Sad. Panda.

Daniel Spiewak

Body:
I am trying to compile the stream, but somehow Compiler is not in scope, what context bound is needed for bringing it in scope?

import cats.Monad

def compilingStream[F[_]: Monad]: F[List[Int]] = {
  val stream: fs2.Stream[F, Int] = fs2.Stream.emit(1).covary[F]
  stream.head.compile.toList
}

error: could not find implicit value for parameter compiler: fs2.Stream.Compiler[[x]F[x],G]
         stream.head.compile.toList
                     ^

Body:
Fs2 Stream#compile now requires a Sync[F] (see this):

  import cats.effect.Sync

  def compilingStream[F[_]: Sync]: F[List[Int]] = {
    val stream: fs2.Stream[F, Int] = fs2.Stream.emit(1).covary[F]
    stream.head.compile.toList
  }

This is communicated by the library maintainer:

fs2 Stream#compile now requires a Sync[F]. Even on completely pure streams. Because of resource management. Sad. Panda.

Daniel Spiewak


问:
allowOverlap property for Highcharts JS v3.0.10
In my project, we are using the highchart version: Highcharts JS v3.0.10.

What should be equivalent code or property which is suitable for allowOverlap = false according to the newer version?

How to achieve alloOverlap= false in the older version?

Link: https://api.highcharts.com/highcharts/series.timeline.dataLabels.allowOverlap

答:
The code that is responsible for hiding the overlapping data labels is currently in Highcharts core: https://code.highcharts.com/highcharts.src.js, but previously it was a separate module: https://code.highcharts.com/5/modules/overlapping-datalabels.src.js

However, to make it work you would have to make many changes in your code. I think using the plugin below will be the best solution for you:

```<code>(function(H) {

    var each = H.each,
        extend = H.extend;

    /**
     * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
     * visual imression.
     */
    H.Series.prototype.hideOverlappingDataLabels = function() {

        var points = this.points,
            len = points.length,
            i,
            j,
            label1,
            label2,
            intersectRect = function(pos1, pos2, size1, size2) {
                return !(
                    pos2.x > pos1.x + size1.width ||
                    pos2.x + size2.width < pos1.x ||
                    pos2.y > pos1.y + size1.height ||
                    pos2.y + size2.height < pos1.y
                );
            };

        // Mark with initial opacity
        each(points, function(point, label) {
            label = point.dataLabel;
            if (label) {
                label.oldOpacity = label.opacity;
                label.newOpacity = 1;
            }
        });

        // Detect overlapping labels
        for (i = 0; i < len - 1; ++i) {
            label1 = points[i].dataLabel;

            for (j = i + 1; j < len; ++j) {
                label2 = points[j].dataLabel;
                if (label1 && label2 && label1.newOpacity !== 0 && label2.newOpacity !== 0 &&
                    intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) {
                    (points[i].labelrank < points[j].labelrank ? label1 : label2).newOpacity = 0;
                }
            }
        }

        // Hide or show
        each(points, function(point, label) {
            label = point.dataLabel;
            if (label) {
                if (label.oldOpacity !== label.newOpacity) {
                    label[label.isOld ? 'animate' : 'attr'](extend({
                        opacity: label.newOpacity
                    }, label.alignAttr));
                }
                label.isOld = true;
            }
        });
    };

    H.wrap(H.Series.prototype, 'drawDataLabels', function(proceed) {
        proceed.call(this);
        this.hideOverlappingDataLabels();
    });
}(Highcharts));
</code>```

Live demo: http://jsfiddle.net/BlackLabel/6s5ycrwa/

Body:
The code that is responsible for hiding the overlapping data labels is currently in Highcharts core: https://code.highcharts.com/highcharts.src.js, but previously it was a separate module: https://code.highcharts.com/5/modules/overlapping-datalabels.src.js

However, to make it work you would have to make many changes in your code. I think using the plugin below will be the best solution for you:

(function(H) {

    var each = H.each,
        extend = H.extend;

    /**
     * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
     * visual imression.
     */
    H.Series.prototype.hideOverlappingDataLabels = function() {

        var points = this.points,
            len = points.length,
            i,
            j,
            label1,
            label2,
            intersectRect = function(pos1, pos2, size1, size2) {
                return !(
                    pos2.x > pos1.x + size1.width ||
                    pos2.x + size2.width < pos1.x ||
                    pos2.y > pos1.y + size1.height ||
                    pos2.y + size2.height < pos1.y
                );
            };

        // Mark with initial opacity
        each(points, function(point, label) {
            label = point.dataLabel;
            if (label) {
                label.oldOpacity = label.opacity;
                label.newOpacity = 1;
            }
        });

        // Detect overlapping labels
        for (i = 0; i < len - 1; ++i) {
            label1 = points[i].dataLabel;

            for (j = i + 1; j < len; ++j) {
                label2 = points[j].dataLabel;
                if (label1 && label2 && label1.newOpacity !== 0 && label2.newOpacity !== 0 &&
                    intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) {
                    (points[i].labelrank < points[j].labelrank ? label1 : label2).newOpacity = 0;
                }
            }
        }

        // Hide or show
        each(points, function(point, label) {
            label = point.dataLabel;
            if (label) {
                if (label.oldOpacity !== label.newOpacity) {
                    label[label.isOld ? 'animate' : 'attr'](extend({
                        opacity: label.newOpacity
                    }, label.alignAttr));
                }
                label.isOld = true;
            }
        });
    };

    H.wrap(H.Series.prototype, 'drawDataLabels', function(proceed) {
        proceed.call(this);
        this.hideOverlappingDataLabels();
    });
}(Highcharts));

Live demo: http://jsfiddle.net/BlackLabel/6s5ycrwa/


问:
Overiding placholders in django cms?
Hey im using the placeholder fields from django cms in some of my custom cms apps.  Basically what im trying to achieve is specific styles and filters for the same placeholder fields being used in different templates.

for example if i have a model for vacancies that looks something like this:

```<code>from django.db import models
from cms.models.fields import PlaceholderField

# Create your models here.
class Vaccancy(models.Model):
    title =  models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique = True)
    ref_number = models.CharField(max_length=255)
    info = PlaceholderField('info')
    active = models.BooleanField(default=True, verbose_name="posistion active?")
</code>```

and another model that also utilizes the placeholder field in a similar way.  What i hoped i could do is overide the tex.html template then have some conditional logic to detect the name of the placeholder  like so
{% ifequal placeholder "info" %}
    {{ body|truncatewords:200|safe }}
{% endifequal %} the aim of this is so i can specify different filters like truncatewords etc as i dont want to apply this to every placeholder that uses a text plugin!

hope that was clear enough! cheers for any help!

答: If you use placeholder fields, you have to check for placeholder.slot, also note that {% if placeholder.slot == "info" %} seems a bit nicer than ifequal :D

Title: Overiding placholders in django cms?

Body:
Hey im using the placeholder fields from django cms in some of my custom cms apps.  Basically what im trying to achieve is specific styles and filters for the same placeholder fields being used in different templates.

for example if i have a model for vacancies that looks something like this:

from django.db import models
from cms.models.fields import PlaceholderField

# Create your models here.
class Vaccancy(models.Model):
    title =  models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique = True)
    ref_number = models.CharField(max_length=255)
    info = PlaceholderField('info')
    active = models.BooleanField(default=True, verbose_name="posistion active?")

and another model that also utilizes the placeholder field in a similar way.  What i hoped i could do is overide the tex.html template then have some conditional logic to detect the name of the placeholder  like so
{% ifequal placeholder "info" %}
    {{ body|truncatewords:200|safe }}
{% endifequal %} the aim of this is so i can specify different filters like truncatewords etc as i dont want to apply this to every placeholder that uses a text plugin!

hope that was clear enough! cheers for any help!


问:
List operations of a TFLite model
I'm having trouble trying to list the operations of a TFLite model. I know operations can be listed given a frozen graph, but what about a TFLite .tflite model? Can operations be listed?

答:
As mentioned in the TensorFlow Lite docs, you need to use a tf.lite.Interpreter to parse a .tflite model.

```<code># Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()
</code>```

Then use the get_tensor_details method to get the list of Tensors.

```<code>interpreter.get_tensor_details()
</code>```

As per the docs,

Gets tensor details for every tensor with valid tensor details.
  Tensors where required information about the tensor is not found are not added to the list. This includes temporary tensors without a name.

Returns: A list of dictionaries containing tensor information.

Title: List operations of a TFLite model

Body:
As mentioned in the TensorFlow Lite docs, you need to use a tf.lite.Interpreter to parse a .tflite model.

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

Then use the get_tensor_details method to get the list of Tensors.

interpreter.get_tensor_details()

As per the docs,

Gets tensor details for every tensor with valid tensor details.
  Tensors where required information about the tensor is not found are not added to the list. This includes temporary tensors without a name.

Returns: A list of dictionaries containing tensor information.


问:
Create an empty data frame with index from another data frame
I've got a data frame df1 with multiple columns and rows. Simple example:

```<code>    TIME T1  T2
       1 10 100
       2 20 200
       3 30 300
</code>```

I'd like to create an empty data frame df2 and later on, add new columns with the calculation results.

For this moment my code looks like this:

```<code>     df1=pd.read_csv("1.txt",index_col="TIME")

     df2=df1.copy()[[]] #copy df1 and erase all columns
</code>```

...adding two new columns:

```<code>     df2["results1"],df2["results2"]=df1["T1"]*df["T2"]*3,df1["T2"]+100
</code>```

Is there any better/safer/faster way to do this ?
Is it possible to create an empty data frame df2 and only copy index from df1 ?

答:
You can use this short code:

df2=df1[[]].copy()

Body:
I've got a data frame df1 with multiple columns and rows. Simple example:

    TIME T1  T2
       1 10 100
       2 20 200
       3 30 300

I'd like to create an empty data frame df2 and later on, add new columns with the calculation results.

For this moment my code looks like this:

     df1=pd.read_csv("1.txt",index_col="TIME")

     df2=df1.copy()[[]] #copy df1 and erase all columns

...adding two new columns:

     df2["results1"],df2["results2"]=df1["T1"]*df["T2"]*3,df1["T2"]+100

Is there any better/safer/faster way to do this ?
Is it possible to create an empty data frame df2 and only copy index from df1 ?


问:
Get traffic returned from social login providers to create a local account on my .net core 2.2 web app
I've always used a mix of home baked plus 3rd party packages to accomplish social logins (Google, Facebook, and Twitter specifically).  With me in full control, I could specify the return method and then capture the response data from the social provider, map the fields I wanted (name, email address, and 3rd party ID) to my own local model to create a local user account and then specify what type of account that is (admin, regular user etc).

With .net core 2.2, everything seems to happen behind the scenes and I can't figure out how to capture the traffic when it comes back after the call to /me for example in facebook.  That behind the scenes call returns a JSON response that my local app is then mapping to the claims to log me in.  That's all great, but I also want to capture that data and create a local user account in my own data store.

I can see it all happening in fiddler so I know it's still doing the work, I just don't know how to tap into it to extract what I need at that stage during the process.  Sticking with facebook for my example here, I thought I could change the facebookOptions.CallbackPath property in my startup.cs file, then add that callback as an accepted callback in the facebook app, wire up a method on a controller that matches that path and get the data from there.  I'd be ok with having the work out the rest of the process by hand, but all that did was move the behind the scenes work that .net core is doing to that "location".

I suppose I could just do a check every time a user hits a page on the site when they're authenticated to see if I need to add or update their local session, but that seems overly ghetto to me.  I want to be able to do this once per session as soon as they log in.  I'll be the first to admit that my skills with Identity are pretty weak so maybe I'm missing something there?

any guidance or suggestions would be greatly appreciated.

TIA

答:
I figured out a way to do this but I"m not sure if this is the best approach or not.  I created a helper class with a static method that I invoke inside of the Options.Events.OnCreatingTicket event inside my AddAuthentication() inside startup.cs.

From here, I can loop over my claims list, save the user to my local datastore and either create or update local user information.

If this is not the best way to handle this, I'd love some better direction.

TIA

```<code>            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                options =>
                {
                    options.LoginPath = new PathString("/account");
                })
            .AddFacebook(facebookOptions =>
                {
                    facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
                    facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                    facebookOptions.CallbackPath = new PathString("/account/facebook");
                    facebookOptions.Events.OnCreatingTicket = ctx =>
                    {
                        ExternalLoginProviderHelper.LoginLocally(ctx.Principal);
                        return Task.CompletedTask;
                    };
                })
            .AddGoogle(options =>
                {
                    options.ClientId = Configuration["Authentication:Google:ClientId"];
                    options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
                    options.Events.OnCreatingTicket = ctx =>
                    {
                        ExternalLoginProviderHelper.LoginLocally(ctx.Principal);
                        return Task.CompletedTask;
                    };
        });
</code>```

and my helper class:

```<code>public class ExternalLoginProviderHelper
{
    public static void LoginLocally(ClaimsPrincipal claimsPrincipal)
    {
        foreach(Claim claim in claimsPrincipal.Claims)
        {
            // extract the claim information here (ID, Email address, name (surname, given name) etc)
            // make repository call to save information to the datastore and get a local user ID
        }
        // also set other claims for local user id, user type (admin, regular user) etc.
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)claimsPrincipal.Identity;
        claimsIdentity.AddClaim(new Claim("usertype", "admin")); // this is just an example N/V pair
    }
}
</code>```

Body:
I figured out a way to do this but I"m not sure if this is the best approach or not.  I created a helper class with a static method that I invoke inside of the Options.Events.OnCreatingTicket event inside my AddAuthentication() inside startup.cs.

From here, I can loop over my claims list, save the user to my local datastore and either create or update local user information.

If this is not the best way to handle this, I'd love some better direction.

TIA

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                options =>
                {
                    options.LoginPath = new PathString("/account");
                })
            .AddFacebook(facebookOptions =>
                {
                    facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"];
                    facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
                    facebookOptions.CallbackPath = new PathString("/account/facebook");
                    facebookOptions.Events.OnCreatingTicket = ctx =>
                    {
                        ExternalLoginProviderHelper.LoginLocally(ctx.Principal);
                        return Task.CompletedTask;
                    };
                })
            .AddGoogle(options =>
                {
                    options.ClientId = Configuration["Authentication:Google:ClientId"];
                    options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
                    options.Events.OnCreatingTicket = ctx =>
                    {
                        ExternalLoginProviderHelper.LoginLocally(ctx.Principal);
                        return Task.CompletedTask;
                    };
        });

and my helper class:

public class ExternalLoginProviderHelper
{
    public static void LoginLocally(ClaimsPrincipal claimsPrincipal)
    {
        foreach(Claim claim in claimsPrincipal.Claims)
        {
            // extract the claim information here (ID, Email address, name (surname, given name) etc)
            // make repository call to save information to the datastore and get a local user ID
        }
        // also set other claims for local user id, user type (admin, regular user) etc.
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)claimsPrincipal.Identity;
        claimsIdentity.AddClaim(new Claim("usertype", "admin")); // this is just an example N/V pair
    }
}


问:
Does Firestore already support search?
Just wandering if Firestore already support full-text search or does it still relay on Algolia? Documentation form my experience is not always up to date and I'm trying to use as less third party plugins as possible. If not, have you got this feature on your todo list?</p>

答:
Just wandering if Firestore already support full text search or does it still relay on Algolia.

No, it does not support full-text search.

Documentation form my experience is not always up to date

The official documentation regarding the full-text search in Cloud Firestore, is up to date and stands for Algolia.

For Android, please see my answer from the following question:

Is it possible to use Algolia query in FirestoreRecyclerOptions?

Edit:

Acording to the offical documentation regarding mobile search:

We offer front end components for iOS, Android and mobile web. Each flavor respects the specific concepts, coding patterns and UX/UI best practices of its framework, so developers can quickly build state-of-the-art, mobile search and discovery experiences.

Title: Does Firestore already support search?


问:
Queue page transitions in React Router
I have a web project, based on React, where I'm using React Router 4 to handle my routing. I've been doing some baby steps with React Router together with "react-transition-group", adding a fade transition based on CSSTransition component's classes, ie fade-enter, fade-enter-active etc...

Anyhow - this works all good and everything, but if I click the browser buttons back and forth quickly to change route, then the transitions get interrupted and will be more jumping into the "new state of transition".

Is there a way to queue the changed route so that if the user change to a different route while a transition is already in progress, then wait for the first transition to complete, and then handle the "new route". I don't want the location/url to be stopped or anything just the transition to work more smooth..?

Thanks

答:
I made a library to solve this problem.

npm: react-queue-router

document: https://tokky0425.github.io/react-queue-router/

This is probably what you want.

(If something does not work well, please post an issue on github.)

Basically, the problem here is that you cannot cancel or stop (like e.preventDecault) the change of location.pathname when the user clicks the browser buttons back and forth.

One solution is to implement a routing not based on location.pathname but based on other value you stored somewhere manually.

In the case of the library I mentioned above, the history of location.pathname will be  queued in an array, and component's mount will be executed one after another based on the value of the array

This makes it possible to wait for the end of the transition animation.
 (Because the change of location.pathname just means that the pathname will be queued in the array.)

It seems it's difficult for React Router to do the job as long as it's routing is implemented based on location.pathname.

Title: Queue page transitions in React Router


问:
How to manually call TreeCell#updateItem for a CheckBoxTreeItem so we can apply CSS?
I am having a standard TreeView in JavaFX with CheckBoxTreeItem in it. I've installed a listener to see when someone checks/ unchecks a checkbox. But I want that when someone check/unchecks a checkbox I trigger that checkboxitem's parent updateItem method and change his CSS ( for example if 3 or more childs are selected for a parent then change his color to red, otherwise green).

How can I do that?

```<code>rootItem.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), e -> {
        if (e.getTreeItem().isLeaf()) {
            TreeItem<String> treeItem = (TreeItem) e.getTreeItem();
            CheckBoxTreeItem<String> parentItem = (CheckBoxTreeItem<String>) treeItem.getParent();
            // how to call repaint for the parentItem????
        }
    });

treeView.setCellFactory(p -> new CheckBoxTreeCell<>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        // toggle the parent's CSS here
    }
});
</code>```

答:
You don't need to change it manually, you can use a PseudoClass:

```<code>private PseudoClass threeChildrenClass = PseudoClass.getPseudoClass("three-children");

tree.setCellFactory(param -> new CheckBoxTreeCell<String>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || empty) {
            setText(null);
            setGraphic(null);
        } else {
            setText(item);
            // Change the class based on the number of parent items
            pseudoClassStateChanged(threeChildrenClass, hasThreeChildren(item));
        }
    }
});
</code>```

In your CSS file:

```<code>.check-box-tree-cell:three-children {
    -fx-background-color: red;
}
</code>```

It looks like CheckBoxTreeCell doesn't have a built-in "checked" pseudo-class, you can add a "checked" PseudoClass and apply it when the tree cell is checked. Then you can call it like this:

```<code>.check-box-tree-cell:three-children:checked {
    -fx-background-color: green;
}
</code>```

Body:
I am having a standard TreeView in JavaFX with CheckBoxTreeItem in it. I've installed a listener to see when someone checks/ unchecks a checkbox. But I want that when someone check/unchecks a checkbox I trigger that checkboxitem's parent updateItem method and change his CSS ( for example if 3 or more childs are selected for a parent then change his color to red, otherwise green).

How can I do that?

rootItem.addEventHandler(CheckBoxTreeItem.checkBoxSelectionChangedEvent(), e -> {
        if (e.getTreeItem().isLeaf()) {
            TreeItem<String> treeItem = (TreeItem) e.getTreeItem();
            CheckBoxTreeItem<String> parentItem = (CheckBoxTreeItem<String>) treeItem.getParent();
            // how to call repaint for the parentItem????
        }
    });

treeView.setCellFactory(p -> new CheckBoxTreeCell<>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        // toggle the parent's CSS here
    }
});

Body:
You don't need to change it manually, you can use a PseudoClass:

private PseudoClass threeChildrenClass = PseudoClass.getPseudoClass("three-children");

tree.setCellFactory(param -> new CheckBoxTreeCell<String>() {
    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);
        if (item == null || empty) {
            setText(null);
            setGraphic(null);
        } else {
            setText(item);
            // Change the class based on the number of parent items
            pseudoClassStateChanged(threeChildrenClass, hasThreeChildren(item));
        }
    }
});

In your CSS file:

.check-box-tree-cell:three-children {
    -fx-background-color: red;
}

It looks like CheckBoxTreeCell doesn't have a built-in "checked" pseudo-class, you can add a "checked" PseudoClass and apply it when the tree cell is checked. Then you can call it like this:

.check-box-tree-cell:three-children:checked {
    -fx-background-color: green;
}


答:
You can use map. In the map call back function you can access individual object & each object will have language & level as key.Key id is nested inside language and level key. So to retrieve value of id you need item.language.id & item.level.id where item is current object

let data = [{
  "language": {
    "displayName": {
      "en": "English"
    },
    "id": 1
  },
  "level": {
    "id": 1,
    "displayName": {
      "en": "Intermediate"
    }
  }
}, {
  "language": {
    "displayName": {
      "en": "Russian"
    },
    "id": 2
  },
  "level": {
    "id": 1,
    "displayName": {
      "en": "Fluent"
    }
  }
}];

let newData = data.map(function(item) {
  return {
    language: item.language.id,
    level: item.level.id
  }

});

console.log(newData)```

Title: How to convert an array?


问:
TypeScript class extends JavaScript function
I wanted to create a new class extending from an existing class-like JavaScript function

```<code>function MyFunctionClass() { }

MyFunctionClass.prototype.myMethod = function(str) {
  console.log(str);
};
</code>```

I wrote this simple piece of code

```<code>class Test extends MyFunctionClass {
    constructor() {
        super();
    }
}

let t = new Test();
t.myMethod('Test');
</code>```

And surprisingly it does work, as it prints Test and no runtime errors are raised.

However, the TypeScript playground tells me

Type '() => void' is not a constructor function type.

Can I safely ignore this error and use that code in production?

答:
To do that, you'd create a TypeScript declaration file (mumble.d.ts) to provide TypeScript with the information about the class, for instance:

```<code>// In a .d.ts file associated with the project
declare class MyFunctionClass {
  myMethod(str: string): void;
}
</code>```

That way, not only does TypeScript know that MyFunctionClass is a class, it also knows that myMethod expects a string and doesn't have a return value.

And surprisingly it does work...

It's not surprising. :-) Remember that TypeScript compiles to JavaScript. If you're targeting ES5, TypeScript's class construct compiles to a JavaScript constructor function and associated prototype, which TypeScript can hook up in an inheritance relationship with the JavaScript MyFunctionClass. If you're targeting ES2015+, TypeScript's class compiles to a ES2015+ class, and ES2015+ class can use an ES5-style constructor function in the extends clause.

Body:
I wanted to create a new class extending from an existing class-like JavaScript function

function MyFunctionClass() { }

MyFunctionClass.prototype.myMethod = function(str) {
  console.log(str);
};

I wrote this simple piece of code

class Test extends MyFunctionClass {
    constructor() {
        super();
    }
}

let t = new Test();
t.myMethod('Test');

And surprisingly it does work, as it prints Test and no runtime errors are raised.

However, the TypeScript playground tells me

Type '() => void' is not a constructor function type.

Can I safely ignore this error and use that code in production?

Body:
To do that, you'd create a TypeScript declaration file (mumble.d.ts) to provide TypeScript with the information about the class, for instance:

// In a .d.ts file associated with the project
declare class MyFunctionClass {
  myMethod(str: string): void;
}

That way, not only does TypeScript know that MyFunctionClass is a class, it also knows that myMethod expects a string and doesn't have a return value.

And surprisingly it does work...

It's not surprising. :-) Remember that TypeScript compiles to JavaScript. If you're targeting ES5, TypeScript's class construct compiles to a JavaScript constructor function and associated prototype, which TypeScript can hook up in an inheritance relationship with the JavaScript MyFunctionClass. If you're targeting ES2015+, TypeScript's class compiles to a ES2015+ class, and ES2015+ class can use an ES5-style constructor function in the extends clause.


问:
Set default value to option select menu
I want to bind a custom attribute to an option select menu.
The <option> tag would simply have an attribute of selected="selected"

```<code><template>
  <div>
    <select>
      <option v-for="" v-bind:selected="[condition ? selected : notSelected]" value="">{{ resource.xprm_name }}</option>
    </select>
  </div>
</template>

data: {
  selected: "selected",
  notSelected: ""
}
</code>```

This does not work, but if I change v-bind:selected to v-bind:class then it receives the appropriate class, so the logic is working, but not with the selected attribute.

Any way to make it work with such custom attributes?

答:
html:

    <select v-model="selectedValue">
        <option v-for="listValue in valuesList" :value="listValue">
            {{listValue}}
        </option>
    </select>
    Chosen item: {{ selectedValue }}

```

<p>js:</p>

<pre class="lang-js prettyprint-override"><code>var app = new Vue({
    el: '#myComponent',
    data: {
        selectedValue: 'Two',
        valuesList: ['One', 'Two', 'Three']
    },
</code>```

Title: Set default value to option select menu

Body:
I want to bind a custom attribute to an option select menu.
The <option> tag would simply have an attribute of selected="selected"

<template>

    <select>
      <option v-for="" v-bind:selected="[condition ? selected : notSelected]" value="">{{ resource.xprm_name }}</option>
    </select>

</template>

data: {
  selected: "selected",
  notSelected: ""
}

This does not work, but if I change v-bind:selected to v-bind:class then it receives the appropriate class, so the logic is working, but not with the selected attribute.

Any way to make it work with such custom attributes?

Body:
html:

<div id="myComponent">
    <select v-model="selectedValue">
        <option v-for="listValue in valuesList" :value="listValue">
            {{listValue}}
        </option>
    </select>
    <span>Chosen item: {{ selectedValue }}</span>
</div>

js:

var app = new Vue({
    el: '#myComponent',
    data: {
        selectedValue: 'Two',
        valuesList: ['One', 'Two', 'Three']
    },


问:
How to link my herokuapp to a domain - www.mypersonalwebsite.com?
Recently i have purchased the domain for example - www.mypersonalwebsite.com.
I wanted to link my heroku app - https://sampleapp.herokuapp.com to the www.mypersonalwebsite.com.

It should not redirect to herokuapp url rather it should work as like it  hosted in www.mypersonalwebsite.com.

Example:
The url https://sampleapp.herokuapp.com/supplier/list must be accessed as

```<code>    www.mypersonalwebsite.com/supplier/list
</code>```

How to link the domain to herokuapp?

答: You need to add-on like pointDNS and then add your domain to custom domain.finally adding ND issued by pointDNS needs to be updated on domain registrar.</p>

Body:
Recently i have purchased the domain for example - www.mypersonalwebsite.com.
I wanted to link my heroku app - https://sampleapp.herokuapp.com to the www.mypersonalwebsite.com.

It should not redirect to herokuapp url rather it should work as like it  hosted in www.mypersonalwebsite.com.

Example:
The url https://sampleapp.herokuapp.com/supplier/list must be accessed as

    www.mypersonalwebsite.com/supplier/list

How to link the domain to herokuapp?


问:
Services and Control points using libupnp SDK for ubuntu 12.04
How to make a service or control point using libupnp SDK?!

I didn't understand the documentation attached with this SDK, I don't know from where to start ?!

Can you help me in that and refer me to some helping tutorials ?!

Thanks!

答:
Yes I know, this is a very old question but still had no answer. I came here from google because I also was looking for an entry to use the libupnp SDK aka Portable SDK for UPnP* Devices, but without success. So I will share how I  got it with some effort to find things.

I'm using Debian Stretch. So first I installed:

```<code>~$ sudo apt install libupnp6 libupnp6-dev libupnp6-doc
</code>```

Then have a look at the documentation (of course ;) in /usr/share/doc/libupnp6-doc/html/modules.html. One of the problems was that I wasn't able to find this document online. With the UPnP API I started with this simple program, that searches for upnp devices on the local network. Just set INTERFACE[] and SEARCH_DURATION_SECONDS for what you need.

```<code>#include <string>
#include <iostream>
#include <thread>
#include <chrono>
#include <upnp/upnp.h>

constexpr char INTERFACE[] = "eth0";
constexpr int SEARCH_DURATION_SECONDS = 5;

int callback_event_handler(Upnp_EventType event_type, void* event, void* cookie)
{
    std::string str;

    switch (event_type) {
        case UPNP_DISCOVERY_SEARCH_RESULT:
            str = "UPNP_DISCOVERY_SEARCH_RESULT";
            break;
        case UPNP_DISCOVERY_SEARCH_TIMEOUT:
            str = "UPNP_DISCOVERY_SEARCH_TIMEOUT";
            break;
        default:
            std::cout << "Called callback_event_handler with ignored event" << std::endl;
            return 0;
    }
    std::cout << "Executing callback_event_handler with event type " << str << std::endl;
    std::cout << (char*)cookie << std::endl;
    return 0;
}

int main()
{
    constexpr char cookie[] = "Free custom data, usable in the callback function.";
    UpnpClient_Handle client_handle = -1;

    UpnpInit2(INTERFACE, 0);
    UpnpRegisterClient(callback_event_handler, &cookie, &client_handle);
    UpnpSearchAsync(client_handle, SEARCH_DURATION_SECONDS, "upnp:rootdevice", cookie);
    std::this_thread::sleep_for(std::chrono::seconds(SEARCH_DURATION_SECONDS + 1));
    UpnpFinish();
}
</code>```

The search target (ST) upnp:rootdevice at UpnpSearchAsync(..) determins what to search. For other search targets look at UPnP Device Architecture 1.0, chapter 1.2.2 Discovery: Search: Request with M-SEARCH.

I compiled the program with:

```<code>~$ g++ -std=c++11 -pedantic-errors -Wall -lpthread -lupnp upnpsearch.cpp -o upnpsearch
</code>```

If you execute it and you have UPnP devices on your local network you should get an output something like this:

```<code>Executing callback_event_handler with event type UPNP_DISCOVERY_SEARCH_RESULT
Free custom data, usable in the callback function.
Called callback_event_handler with ignored event
Called callback_event_handler with ignored event
Executing callback_event_handler with event type UPNP_DISCOVERY_SEARCH_RESULT
Free custom data, usable in the callback function.
Executing callback_event_handler with event type UPNP_DISCOVERY_SEARCH_TIMEOUT
Free custom data, usable in the callback function.
</code>```

Here you see that two UPnP devices are online.

Body:
Yes I know, this is a very old question but still had no answer. I came here from google because I also was looking for an entry to use the libupnp SDK aka Portable SDK for UPnP* Devices, but without success. So I will share how I  got it with some effort to find things.

I'm using Debian Stretch. So first I installed:

~$ sudo apt install libupnp6 libupnp6-dev libupnp6-doc

Then have a look at the documentation (of course ;) in /usr/share/doc/libupnp6-doc/html/modules.html. One of the problems was that I wasn't able to find this document online. With the UPnP API I started with this simple program, that searches for upnp devices on the local network. Just set INTERFACE[] and SEARCH_DURATION_SECONDS for what you need.

#include <string>
#include <iostream>
#include <thread>
#include <chrono>
#include <upnp/upnp.h>

constexpr char INTERFACE[] = "eth0";
constexpr int SEARCH_DURATION_SECONDS = 5;

int callback_event_handler(Upnp_EventType event_type, void* event, void* cookie)
{
    std::string str;

    switch (event_type) {
        case UPNP_DISCOVERY_SEARCH_RESULT:
            str = "UPNP_DISCOVERY_SEARCH_RESULT";
            break;
        case UPNP_DISCOVERY_SEARCH_TIMEOUT:
            str = "UPNP_DISCOVERY_SEARCH_TIMEOUT";
            break;
        default:
            std::cout << "Called callback_event_handler with ignored event" << std::endl;
            return 0;
    }
    std::cout << "Executing callback_event_handler with event type " << str << std::endl;
    std::cout << (char*)cookie << std::endl;
    return 0;
}

int main()
{
    constexpr char cookie[] = "Free custom data, usable in the callback function.";
    UpnpClient_Handle client_handle = -1;

    UpnpInit2(INTERFACE, 0);
    UpnpRegisterClient(callback_event_handler, &cookie, &client_handle);
    UpnpSearchAsync(client_handle, SEARCH_DURATION_SECONDS, "upnp:rootdevice", cookie);
    std::this_thread::sleep_for(std::chrono::seconds(SEARCH_DURATION_SECONDS + 1));
    UpnpFinish();
}

The search target (ST) upnp:rootdevice at UpnpSearchAsync(..) determins what to search. For other search targets look at UPnP Device Architecture 1.0, chapter 1.2.2 Discovery: Search: Request with M-SEARCH.

I compiled the program with:

~$ g++ -std=c++11 -pedantic-errors -Wall -lpthread -lupnp upnpsearch.cpp -o upnpsearch

If you execute it and you have UPnP devices on your local network you should get an output something like this:

Executing callback_event_handler with event type UPNP_DISCOVERY_SEARCH_RESULT
Free custom data, usable in the callback function.
Called callback_event_handler with ignored event
Called callback_event_handler with ignored event
Executing callback_event_handler with event type UPNP_DISCOVERY_SEARCH_RESULT
Free custom data, usable in the callback function.
Executing callback_event_handler with event type UPNP_DISCOVERY_SEARCH_TIMEOUT
Free custom data, usable in the callback function.

Here you see that two UPnP devices are online.


问:
What to watch out for when converting a std::string to a char* for C function?
I have read many posts asking the question on how to convert a C++ std::string or const std::string& to a char* to pass it to a C function and it seems there is quite a few caveat's in regards to doing this.  One has to beware about the string being contiguous and a lot of other things.  The point is that I've never really understood all the points one needs to be aware of and why?

I wondered if someone could sum up the caveats and downfalls about doing a conversion from a std::string to a char* that is needed to pass to a C function?

This when the std::string is a const reference and when it's just a non-const reference, and when the C function will alter the char* and when it will not alter it.

答:
std:string can store zero bytes. This means that when passed to C function it can be truncated prematurely, as C functions will stop on first zero byte. This can have security implications, if you try to use C function for example to filter out or escape unwanted characters.

A result of std::string::c_str() will sometimes be invalidated by operations changing a string (non-const member functions). It will cause very hard to diagnose bugs ("Heisenbugs") if you try to use this pointer after you first use c_str() and then modify a string.

Do not use const_cast, ever. goto is less troublesome.


问:
How can I combine n-number of boolean indexes to filter Pandas DataFrame?
Pandas boolean indexes are commonly combined with logical operators:

```<code>vdf = (df1['status'] == 'DENIED') | (df1['status'] == 'VOIDED') | (df1['void?'] == True)
</code>```

I'm processing various DF tables. A table may have zero or many columns which I want to filter. When I say 'filter', I mean drop rows where a condition is true. If a transaction is voided, I want to drop it. If a transaction matches a specific category, I want to drop it.

How can I combine n-boolean indexes?

```<code>table = [('2019-01-01', 10.00, False, 'CAPTURED'),
         ('2019-01-04', 10.00, False, 'CAPTURED'),
         ('2019-01-05', 10.00, False, 'DENIED'),
         ('2019-01-06', 10.00, True, 'VOIDED'),
cols = ['date', 'amount', 'void?', 'status']
df1 = pd.DataFrame.from_records(table, columns=cols)

filter_headers = ['void?', 'status']
status_vals = ['VOIDED', 'DENIED']

try:
    if filter_headers:
        vdfs = []
        for fcol in filter_headers:
            if df1[fcol].dtype == 'bool':
                vdfs.append(df1[fcol] == True)
            elif df1[fcol].dtype == 'object':
                vdfs.append(df1[fcol].isin(status_vals))
            else:
                print("Unhandled type.")
        # Obviously wrong...
        df2 = df1[~sum(vdfs)]
    else:
        df2 = df1
except Exception as e:
    print("(%s) Filter Headers produced no results." % e)
    pass
</code>```

答:
If I understood correctly what you want to achieve, DataFrame.loc is what you are looking for. It selects rows where the index is True:

```<code>bindex = [not v and s not in status_vals for v, s in zip(df1['void?'], df1['status'])]
df2 = df1.loc[bindex]
</code>```

bindex is a list of boolean, length equal to the number of rows in your dataframe. Is False if df1['void?'] is True and df1['status'] is not inside status_val. These two lines replace all your try except block.

Using de Morgan laws, bindex can also be rewritten as:

```<code>bindex = [not (v or s in status_vals) for v, s in zip(df1['void?'], df1['status'])]
</code>```

Using the sample dataframe you posted, the result df2 is:

```<code>         date  amount  void?    status
0  2019-01-01    10.0  False  CAPTURED
1  2019-01-04    10.0  False  CAPTURED
</code>```

Body:
Pandas boolean indexes are commonly combined with logical operators:

vdf = (df1['status'] == 'DENIED') | (df1['status'] == 'VOIDED') | (df1['void?'] == True)

I'm processing various DF tables. A table may have zero or many columns which I want to filter. When I say 'filter', I mean drop rows where a condition is true. If a transaction is voided, I want to drop it. If a transaction matches a specific category, I want to drop it.

How can I combine n-boolean indexes?

table = [('2019-01-01', 10.00, False, 'CAPTURED'),
         ('2019-01-04', 10.00, False, 'CAPTURED'),
         ('2019-01-05', 10.00, False, 'DENIED'),
         ('2019-01-06', 10.00, True, 'VOIDED'),
cols = ['date', 'amount', 'void?', 'status']
df1 = pd.DataFrame.from_records(table, columns=cols)

filter_headers = ['void?', 'status']
status_vals = ['VOIDED', 'DENIED']

try:
    if filter_headers:
        vdfs = []
        for fcol in filter_headers:
            if df1[fcol].dtype == 'bool':
                vdfs.append(df1[fcol] == True)
            elif df1[fcol].dtype == 'object':
                vdfs.append(df1[fcol].isin(status_vals))
            else:
                print("Unhandled type.")
        # Obviously wrong...
        df2 = df1[~sum(vdfs)]
    else:
        df2 = df1
except Exception as e:
    print("(%s) Filter Headers produced no results." % e)
    pass

Body:
If I understood correctly what you want to achieve, DataFrame.loc is what you are looking for. It selects rows where the index is True:

bindex = [not v and s not in status_vals for v, s in zip(df1['void?'], df1['status'])]
df2 = df1.loc[bindex]

bindex is a list of boolean, length equal to the number of rows in your dataframe. Is False if df1['void?'] is True and df1['status'] is not inside status_val. These two lines replace all your try except block.

Using de Morgan laws, bindex can also be rewritten as:

bindex = [not (v or s in status_vals) for v, s in zip(df1['void?'], df1['status'])]

Using the sample dataframe you posted, the result df2 is:

         date  amount  void?    status
0  2019-01-01    10.0  False  CAPTURED
1  2019-01-04    10.0  False  CAPTURED


问:
How to run a program in python using pycharm
I made a program

```<code>FN=int(raw_input("Enter a number"))
SN = int(raw_input("Enter a number"))
TN = FN+SN
PRINT (TN)
</code>```

Please someone tell me how to run it in pycharm

also the error it showing is :
    Cannot run program "C:\
Users\Lenovo\PyCharmProjects\Untitled\venv\Scripts\python.exe"(in directory"C:\Users\Lenovo\PyCharmProjects\untitled"): Create process error = 2. The System cannot find the file specified

答:
I see you solved your problem so I'm here to help you write a clearer code.
I would write it like this:

def summer():

    FN = int(input("Enter a number: "))
    SN = int(input("Enter a number: "))
    TN = FN + SN
    print(TN)

if __name__ == "__main__":
    summer()
```

For instance you wrote FN=int... and then SN = int..., keep in mind that PEP8 (Python style guide) want you to be consistend throughout your code with the spacing and there should always be a space when you assign a value to a variable.

Body:
I made a program

FN=int(raw_input("Enter a number"))
SN = int(raw_input("Enter a number"))
TN = FN+SN
PRINT (TN)

Please someone tell me how to run it in pycharm

also the error it showing is :
    Cannot run program "C:\
Users\Lenovo\PyCharmProjects\Untitled\venv\Scripts\python.exe"(in directory"C:\Users\Lenovo\PyCharmProjects\untitled"): Create process error = 2. The System cannot find the file specified

Body:
I see you solved your problem so I'm here to help you write a clearer code.
I would write it like this:

def summer():

    FN = int(input("Enter a number: "))
    SN = int(input("Enter a number: "))
    TN = FN + SN
    print(TN)

if __name__ == "__main__":
    summer()

For instance you wrote FN=int... and then SN = int..., keep in mind that PEP8 (Python style guide) want you to be consistend throughout your code with the spacing and there should always be a space when you assign a value to a variable.