问:
Select first value and its related rows out of two values based on column condition otherwise select second value and its related rows
I have the Oracle SQL shown below

```<code>select *
from a
where a.description in ('Rebook All (1)', 'Created stock identifier')
    and a.date between '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
    and a.unit = '38240007294677'
</code>```

Now result can have both description multiple times like below for a Unit number or can have 1 of the description.  When it has both description for a Unit number, I need to select only 'Rebook all (1)' (this description can be there many times/many rows as shows below in results) description not 'Created stock identifier' and its related details from table a. When it has only 1 description out of these 2 then if 'Rebook All (1)' is not there, select 'Created stock identifier' and vice versa.

How do I select it?

```<code>  Date                                         Description

3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)
</code>```

I need results like below when there are both description ('Rebook All (1)', 'Created stock identifier') for a Unit number then should get only ('Rebook All (1)') and all its rows, BUT when have only 1 description out of ('Rebook All (1)', 'Created stock identifier') for a Unit number then get that description -

When have both description ('Rebook All (1)', 'Created stock identifier') for a unit number then get only ('Rebook All (1)') like below -

```<code>3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)
</code>```

If have only 1 description 'Created stock identifier' for a unit number then get that 'Created stock identifier' only -

```<code>3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
</code>```

答:
This is one way of achieving your requirement. I used RANK() OVER window function to rank the unit records based on their description in the DESC order.

```<code>SELECT *
FROM (
  SELECT UNIT
    , DESCRIPTION
    , RANK() OVER (PARTITION BY UNIT ORDER BY DESCRIPTION DESC) RN
  FROM MY_TABLE A
  WHERE A.DESCRIPTION IN ('Rebook all (1)'
                          , 'Created stock identifier')
    AND A.DATE BETWEEN '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
    --AND A.UNIT = '38240007294677'
)
WHERE RN = 1
</code>```

Body:
I have the Oracle SQL shown below

select *
from a
where a.description in ('Rebook All (1)', 'Created stock identifier')
    and a.date between '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
    and a.unit = '38240007294677'

Now result can have both description multiple times like below for a Unit number or can have 1 of the description.  When it has both description for a Unit number, I need to select only 'Rebook all (1)' (this description can be there many times/many rows as shows below in results) description not 'Created stock identifier' and its related details from table a. When it has only 1 description out of these 2 then if 'Rebook All (1)' is not there, select 'Created stock identifier' and vice versa.

How do I select it?

  Date                                         Description

3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)

I need results like below when there are both description ('Rebook All (1)', 'Created stock identifier') for a Unit number then should get only ('Rebook All (1)') and all its rows, BUT when have only 1 description out of ('Rebook All (1)', 'Created stock identifier') for a Unit number then get that description -

When have both description ('Rebook All (1)', 'Created stock identifier') for a unit number then get only ('Rebook All (1)') like below -

3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)

If have only 1 description 'Created stock identifier' for a unit number then get that 'Created stock identifier' only -

3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier

Body:
This is one way of achieving your requirement. I used RANK() OVER window function to rank the unit records based on their description in the DESC order.

SELECT *
FROM (
  SELECT UNIT
    , DESCRIPTION
    , RANK() OVER (PARTITION BY UNIT ORDER BY DESCRIPTION DESC) RN
  FROM MY_TABLE A
  WHERE A.DESCRIPTION IN ('Rebook all (1)'
                          , 'Created stock identifier')
    AND A.DATE BETWEEN '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
    --AND A.UNIT = '38240007294677'
)
WHERE RN = 1


来源: stackexchange

问:
unable to install a patched version of GraphicsMagick 1.3.25 on Redhat 6.8
After successfully applying the patch to GraphicsMagick using gnu "patch" i do a configure, make , make install , and use fpm to create the rpm, which i install on a clean VM, but getting error:

$gm -version
gm: error while loading shared libraries: libtiff.so.5: cannot open shared object file: No such file or directory

build steps:

```<code>./configure --prefix=/usr --with-modules=yes --with-png --with-tiff --with-jpeg --with-gslib=/usr/local/share/ghostscript/9.20/lib --enable-shared=no --enable-static=no

make

make DESTDIR=/home/ec2-user/GM/tmp/project/ install

fpm -s dir -t rpm -C tmp/project --name GraphicsMagick --version 1.3.25 --iteration 4 --description "GraphicsMagick 1.3.25 on redhat 6.8" .
</code>```

then, scp the rpm to another clean VM and install it as:

```<code>sudo rpm -ivh GraphicsMagick-1.3.25-4.x86_64.rpm
</code>```

Also, do I also need to build all the required libs like tiff, png jpeg?

which also makes me want to ask: Does GraphicsMagick 1.3.25 support libtiff 4.0.7 ?

```<code>$ ldd /usr/bin/gm
    linux-vdso.so.1 =>  (0x00007ffdc5bef000)
    libtiff.so.5 => not found
    libjpeg.so.9 => not found
    libxml2.so.2 => /usr/lib64/libxml2.so.2 (0x0000003b90c00000)
    libz.so.1 => /lib64/libz.so.1 (0x00000033e9000000)
    libm.so.6 => /lib64/libm.so.6 (0x00000033e9400000)
    libgomp.so.1 => /usr/lib64/libgomp.so.1 (0x00000035f9400000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00000033e8400000)
    libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00000033eac00000)
    libc.so.6 => /lib64/libc.so.6 (0x00000033e8000000)
    librt.so.1 => /lib64/librt.so.1 (0x00000033e8c00000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00000033e8800000)
    /lib64/ld-linux-x86-64.so.2 (0x00000033e7c00000)
</code>```

答:
If you built this on rhel/centos 6, it is transportable via this method to another rhel/centos 6 box.  You problem is probably dependencies, correctly using fpm's '-d' flag repetitively, and install with yum (not rpm).

Use rpm -q --whatprovides on your build box to back track and figure out what rpm's provide that library. Example:

```<code>rpm -q --whatprovides /usr/lib64/libxml2.so.2
libxml2-2.7.6-21.el6_8.1.x86_64
</code>```

So I know that I should have added -d libxml2 to my fpm line

Then do that again for all those image library dependencies.

ContentLicense: CC BY-SA 3.0

Body:
After successfully applying the patch to GraphicsMagick using gnu "patch" i do a configure, make , make install , and use fpm to create the rpm, which i install on a clean VM, but getting error:

$gm -version
gm: error while loading shared libraries: libtiff.so.5: cannot open shared object file: No such file or directory

build steps:

./configure --prefix=/usr --with-modules=yes --with-png --with-tiff --with-jpeg --with-gslib=/usr/local/share/ghostscript/9.20/lib --enable-shared=no --enable-static=no

make

make DESTDIR=/home/ec2-user/GM/tmp/project/ install

fpm -s dir -t rpm -C tmp/project --name GraphicsMagick --version 1.3.25 --iteration 4 --description "GraphicsMagick 1.3.25 on redhat 6.8" .

then, scp the rpm to another clean VM and install it as:

sudo rpm -ivh GraphicsMagick-1.3.25-4.x86_64.rpm

Also, do I also need to build all the required libs like tiff, png jpeg?

which also makes me want to ask: Does GraphicsMagick 1.3.25 support libtiff 4.0.7 ?

$ ldd /usr/bin/gm
    linux-vdso.so.1 =>  (0x00007ffdc5bef000)
    libtiff.so.5 => not found
    libjpeg.so.9 => not found
    libxml2.so.2 => /usr/lib64/libxml2.so.2 (0x0000003b90c00000)
    libz.so.1 => /lib64/libz.so.1 (0x00000033e9000000)
    libm.so.6 => /lib64/libm.so.6 (0x00000033e9400000)
    libgomp.so.1 => /usr/lib64/libgomp.so.1 (0x00000035f9400000)
    libpthread.so.0 => /lib64/libpthread.so.0 (0x00000033e8400000)
    libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00000033eac00000)
    libc.so.6 => /lib64/libc.so.6 (0x00000033e8000000)
    librt.so.1 => /lib64/librt.so.1 (0x00000033e8c00000)
    libdl.so.2 => /lib64/libdl.so.2 (0x00000033e8800000)
    /lib64/ld-linux-x86-64.so.2 (0x00000033e7c00000)

Body:
If you built this on rhel/centos 6, it is transportable via this method to another rhel/centos 6 box.  You problem is probably dependencies, correctly using fpm's '-d' flag repetitively, and install with yum (not rpm).

Use rpm -q --whatprovides on your build box to back track and figure out what rpm's provide that library. Example:

rpm -q --whatprovides /usr/lib64/libxml2.so.2
libxml2-2.7.6-21.el6_8.1.x86_64

So I know that I should have added -d libxml2 to my fpm line

Then do that again for all those image library dependencies.


问:
JSON Schema Multiple Affiliations
I have an attorney that has multiple affiliations that I want to mark up with JSON schema. What is the best way to do this?...

Option #1:

```<code>"affiliation": "Example 1, Example 2",
</code>```

Option #2

```<code>"affiliation": "Example 1",
"affiliation": "Example 2",
</code>```

Or, is there another way to do this that I haven't considered?

答:
Try this:</p>

```<code>"affiliations":[ "Example 1", "Example 2", "Example 3" ]
</code>```

Title: JSON Schema Multiple Affiliations

Body:
I have an attorney that has multiple affiliations that I want to mark up with JSON schema. What is the best way to do this?...

Option #1:

"affiliation": "Example 1, Example 2",

Option #2

"affiliation": "Example 1",
"affiliation": "Example 2",

Or, is there another way to do this that I haven't considered?

Body:
Try this:

"affiliations":[ "Example 1", "Example 2", "Example 3" ]


问:
Create a new column to a dataframe based on the values of another dataframe
I have a dataframe like this:

```<code>name
Google
Amazon
Google
Yahoo
Google
Yahoo
</code>```

And another one like this:

```<code>name   stock_name
Google  stockA
Amazon  stockB
Yahoo   stockC
</code>```

The final result I would like to take from the merge of these 2 dataframes:

```<code>name stock_name
Google stockA
Amazon stockB
Google stockA
Yahoo  stockC
Google stockA
Yahoo  stockC
</code>```

Using the merge it is not possible to make it. Any hind on how could make it?

答:
if you call your data frames df1 and df2 you could do </p>

```<code> df1$stock_name <- df2$stock_name[match(df1$name, df2$name)]
</code>```

Body:
I have a dataframe like this:

name
Google
Amazon
Google
Yahoo
Google
Yahoo

And another one like this:

name   stock_name
Google  stockA
Amazon  stockB
Yahoo   stockC

The final result I would like to take from the merge of these 2 dataframes:

name stock_name
Google stockA
Amazon stockB
Google stockA
Yahoo  stockC
Google stockA
Yahoo  stockC

Using the merge it is not possible to make it. Any hind on how could make it?

Body:
if you call your data frames df1 and df2 you could do

 df1$stock_name <- df2$stock_name[match(df1$name, df2$name)]


问:
Naming a workbook with a password
I am trying to figure out how to add a password to my workbook. The code does save it when I remove the password part ("sp17"), but I get a syntax error while its there. How would I correct this error?</p>

```<code>  ActiveWorkbook.SaveAs fileLocation degreeArray(criteria) & " " & format(Date, "MMM-YY") & ".xlsx", 51, "sp17"
</code>```

答:
I made a small change and now it works. The Format was written incorrectly. Thought about deleting my question but it was hard to find out how to do this so i'll leave it for any one who needs it. This was the right way to write it:</p>

```<code>     ActiveWorkbook.SaveAs fileLocation & degreeArray(criteria) & " " & Format(Date, "MMM-YY") & ".xlsx", 51, Password:="sp17"
</code>```

Title: Naming a workbook with a password

Body:
I am trying to figure out how to add a password to my workbook. The code does save it when I remove the password part ("sp17"), but I get a syntax error while its there. How would I correct this error?

  ActiveWorkbook.SaveAs fileLocation degreeArray(criteria) & " " & format(Date, "MMM-YY") & ".xlsx", 51, "sp17"

Body:
I made a small change and now it works. The Format was written incorrectly. Thought about deleting my question but it was hard to find out how to do this so i'll leave it for any one who needs it. This was the right way to write it:

     ActiveWorkbook.SaveAs fileLocation & degreeArray(criteria) & " " & Format(Date, "MMM-YY") & ".xlsx", 51, Password:="sp17"


问:
Where can I find the Angular 2 CDN or source code?
I've been trying to download the source code from angular 2, but I was unable to find it. I looked in their github repository, but couldn't identify the correct one. Can someone point me the one or a working CDN so I can download it?

Edit: I need to get the source without using Node.Js and NPM.

答:
You can use unpkg.com:

https://unpkg.com/@angular/core@4.0.1/bundles/core.umd.js

https://unpkg.com/@angular/platform-browser-dynamic@4.0.1/bundles/platform-browser-dynamic.umd.js

and so on.

Here is jsFiddle Example

let { Component, NgModule } = ng.core;

@Component({
  selector: 'my-app',
  template: `

Hello, {{ name }}

    <button (click)="increment()">Click {{ counter }}</button>
  `,
})
class HomeComponent {
    counter = 0;
    name = 'Angular 2'

    increment() {
        this.counter++;
    }
}

const { BrowserModule } = ng.platformBrowser;

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ HomeComponent ],
  bootstrap:    [ HomeComponent ]
})
class AppModule { }
```

If you don't want to use typescript then here is

Plunker Example Angular es5

Body:
You can use unpkg.com:

https://unpkg.com/@angular/core@4.0.1/bundles/core.umd.js

https://unpkg.com/@angular/platform-browser-dynamic@4.0.1/bundles/platform-browser-dynamic.umd.js

and so on.

Here is jsFiddle Example

let { Component, NgModule } = ng.core;

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello, {{ name }}</h1>
    <button (click)="increment()">Click {{ counter }}</button>
  `,
})
class HomeComponent {
    counter = 0;
    name = 'Angular 2'

    increment() {
        this.counter++;
    }
}

const { BrowserModule } = ng.platformBrowser;

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ HomeComponent ],
  bootstrap:    [ HomeComponent ]
})
class AppModule { }

If you don't want to use typescript then here is

Plunker Example Angular es5


问:
Oracle 11g: How to dynamically select multiple columns into BULK COLLECT
I have a query like the example below where I want to dynamically bulk collect 2 columns using a join into  from a table that has 4 columns, but I keep getting the error that 'variable not in select list'. I believe this is because it is because the query has less columns than the table, but I don't know how to get around it.

```<code>DECLARE
    TYPE test_table_type IS TABLE OF TEST_PRODUCTS%ROWTYPE;
    BULK_COLLECTOR test_table_type;
BEGIN
    EXECUTE IMMEDIATE
    'SELECT tp.PRODUCT AS PRODUCT, td.ALT_DESCRIPTION AS DESCRIPTION
    FROM TEST_PRODUCTS tp
    JOIN ALT_DESCRIPTIONS td ON tp.ALT_DESCRIPTION_ID = td.ALT_DESCRIPTION_ID'
    BULK COLLECT INTO BULK_COLLECTOR;
END;
</code>```

Here are examples of the tables:

```<code>CREATE TABLE TEST_PRODUCTS
(
    PRODUCT_ID NUMBER,
    PRODUCT VARCHAR2(50),
    DESCRIPTION VARCHAR2(255)
    ALT_DESCRIPTION_ID NUMBER,
    INVENTORY_CODE VARCHAR2(100)
);

CREATE TABLE ALT_DESCRIPTIONS
(
    ALT_DESCRIPTION_ID NUMBER,
    ALT_DESCRIPTION VARCHAR2(255)
);
</code>```

答:
You are selecting from two different tables and trying to put it into a rowtype of one table.

You might want to take a different approach - something like this:

```<code>DECLARE
TYPE test_record IS RECORD
(
  PRODUCT VARCHAR2(50),
  ALT_DESCRIPTION VARCHAR2(255)
);
type test_tab is table of test_record;
BULK_COLLECTOR test_tab;
BEGIN
   EXECUTE IMMEDIATE
   'SELECT tp.PRODUCT AS PRODUCT, td.ALT_DESCRIPTION AS DESCRIPTION
   FROM TEST_PRODUCTS tp
   JOIN ALT_DESCRIPTIONS td ON tp.ALT_DESCRIPTION_ID = td.ALT_DESCRIPTION_ID'
   BULK COLLECT INTO BULK_COLLECTOR;
END;
</code>```

Body:
I have a query like the example below where I want to dynamically bulk collect 2 columns using a join into  from a table that has 4 columns, but I keep getting the error that 'variable not in select list'. I believe this is because it is because the query has less columns than the table, but I don't know how to get around it.

DECLARE
    TYPE test_table_type IS TABLE OF TEST_PRODUCTS%ROWTYPE;
    BULK_COLLECTOR test_table_type;
BEGIN
    EXECUTE IMMEDIATE
    'SELECT tp.PRODUCT AS PRODUCT, td.ALT_DESCRIPTION AS DESCRIPTION
    FROM TEST_PRODUCTS tp
    JOIN ALT_DESCRIPTIONS td ON tp.ALT_DESCRIPTION_ID = td.ALT_DESCRIPTION_ID'
    BULK COLLECT INTO BULK_COLLECTOR;
END;

Here are examples of the tables:

CREATE TABLE TEST_PRODUCTS
(
    PRODUCT_ID NUMBER,
    PRODUCT VARCHAR2(50),
    DESCRIPTION VARCHAR2(255)
    ALT_DESCRIPTION_ID NUMBER,
    INVENTORY_CODE VARCHAR2(100)
);

CREATE TABLE ALT_DESCRIPTIONS
(
    ALT_DESCRIPTION_ID NUMBER,
    ALT_DESCRIPTION VARCHAR2(255)
);

Body:
You are selecting from two different tables and trying to put it into a rowtype of one table.

You might want to take a different approach - something like this:

DECLARE
TYPE test_record IS RECORD
(
  PRODUCT VARCHAR2(50),
  ALT_DESCRIPTION VARCHAR2(255)
);
type test_tab is table of test_record;
BULK_COLLECTOR test_tab;
BEGIN
   EXECUTE IMMEDIATE
   'SELECT tp.PRODUCT AS PRODUCT, td.ALT_DESCRIPTION AS DESCRIPTION
   FROM TEST_PRODUCTS tp
   JOIN ALT_DESCRIPTIONS td ON tp.ALT_DESCRIPTION_ID = td.ALT_DESCRIPTION_ID'
   BULK COLLECT INTO BULK_COLLECTOR;
END;


问:
SQL Server Convert case for letter that comes after - (hyphen)
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

```<code>Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123
</code>```

to

```<code>Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123
</code>```

Please help!

答:
You can use upper and ParseName

```<code>select concat(parsename(Replace(v,' - ', '.'),2), ' - ', Upper(substring(parsename(Replace(v,' - ', '.'),1),1,1)), substring(parsename(Replace(v,' - ', '.'),1),2,len(parsename(Replace(v,' - ', '.'),1))))
    from #yourtext
</code>```

Your Input table:

```<code>create table #yourtext (v varchar(100))

insert into #yourtext (v) values
 ('Aaa - aaa')
,('Bbb - bbb')
,('Ccc - ccc')
</code>```

Body:
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123

to

Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123

Please help!

Body:
You can use upper and ParseName

select concat(parsename(Replace(v,' - ', '.'),2), ' - ', Upper(substring(parsename(Replace(v,' - ', '.'),1),1,1)), substring(parsename(Replace(v,' - ', '.'),1),2,len(parsename(Replace(v,' - ', '.'),1))))
    from #yourtext

Your Input table:

create table #yourtext (v varchar(100))

insert into #yourtext (v) values
 ('Aaa - aaa')
,('Bbb - bbb')
,('Ccc - ccc')


问:
Issue on SIPML5 plugin integration on AWS with Asterisks server- 13 using WebRTC
I have faced an issue on integrating the demo of SIPML5 plugin on the Asterisks server. The Asterisks server version is "Asterisk 13.14.0". The new version of the asterisks server supports SRTP module.
The plugin demo files are taken from Doubango's github repository. The demo integration files are placed on the root folder of our AWS server account.

```<code>Ref: https://github.com/DoubangoTelecom/sipml5/
</code>```

The contents of the different configuration files for Asterisks server are as follows:

http.conf

```<code>[general]
enabled=yes
bindaddr=0.0.0.0
bindport=8088
tlsenable=yes
tlsbindaddr=0.0.0.0:8089
tlscertfile=/etc/asterisk/keys/asterisk.pem
tlsprivatekey=/etc/asterisk/keys/asterisk.pem
</code>```

rtp.conf

```<code>[general]
rtpstart=10000
rtpend=20000
icesupport=yes
stunaddr=stun.l.google.com:19302
</code>```

extensions.conf

```<code>[default]
exten => 100,1,Dial(SIP/1060)
exten => 101,1,Dial(SIP/1061)
exten => 102,1,Playback(1-for-am-2-for-pm)
exten => 205,1,Answer
exten => 205,2,Wait(2)
exten => 205,3,Record(asterisk-recording%d:ulaw)
exten => 205,4,Wait(2)
exten => 205,5,Playback(${RECORDED_FILE})
exten => 205,6,Wait(2)
exten => 205,7,Hangup

[from-internal]
exten => 1000,1,Answer()
same => n,Playback(demo-congrats)
same => n,Hangup()
</code>```

sip.conf

```<code>[general]
udpbindaddr=0.0.0.0:5060
realm=x.x.x.x ;replace with your Asterisk server public IP address or host
transport=udp,ws,wss
externaddr=x.x.x.x ;replace with your Server's Public IP Address
websocket_enabled=true

[6001]
host=dynamic
secret=****
context=from-internal
type=friend
encryption=yes
avpf=yes
force_avp=yes
icesupport=yes
directmedia=no
disallow=all
allow=ulaw
dtlsenable=yes
dtlsverify=fingerprint
dtlscertfile=/etc/asterisk/keys/asterisk.pem
dtlscafile=/etc/asterisk/keys/ca.crt
dtlssetup=actpass
</code>```

The filed values set for the expert.htm page for the demo is as follows:-

```<code>WebSocket Server URL : wss://X.X.X.X:8088/ws
SIP outbound Proxy URL: udp://X.X.X.X:5060
ICE servers: [{ url: ‘stun:stun.l.google.com:19302’}]
</code>```

The filed values set for the call.htm page for the demo is as follows:-

```<code>Display name: Rusty WEBRTC
Private identity: 6001
Public identity: sip:6001@X.X.X.X
Password; ****
Realm: X.X.X.X
</code>```

Where X.X.X.X is my Asterisks server IP.

When click on the "Log in" button on the call.htm page an error message is displayed like

```<code>Disconnected: Failed to connect to the server
</code>```

The linphone plugin is installed on the project right now. Due to the withdrawal of NPAPI support by Chrome/Mozilla browsers, the VoIP feature is completely outdated on the project. Now I want to replace the feature with SipML5 plugin which supports the WebRTC protocol. I need to check the registration, login, audio call features of the SIPML5 plugin. But all these functionalities can be implemented once i got connected to the server.

The Asterisks CLI is not displayed any error message. The console history of Chrome and Mozilla browsers are not displayed any vulnerable error messages. So I'm completely stuck on the project.

The demo files were worked fine on the Asterisks 11.8.1 server. But the SRTP module was not installed on the server so that the audio feature was not worked fine. Our supporting team is installed the library now and reinstalled the asterisks server with version 13. The firewall is open for the AWS server and the ports are open now.

Can anybody help me to fix the issue so that i can go further with the plug in integration to my project.Please let me know if any other details needed

答:
Possible debugging steps:
1. Check if asterisk is actually listening on 8089. You can use netstat for that.
2. If you are loading your client/browser in https mode then you need to trust your client on asterisk. This can be done through: http://X.X.X.X:8089/httpstatus and select trust.</p>

Body:
I have faced an issue on integrating the demo of SIPML5 plugin on the Asterisks server. The Asterisks server version is "Asterisk 13.14.0". The new version of the asterisks server supports SRTP module.
The plugin demo files are taken from Doubango's github repository. The demo integration files are placed on the root folder of our AWS server account.

Ref: https://github.com/DoubangoTelecom/sipml5/

The contents of the different configuration files for Asterisks server are as follows:

http.conf

[general]
enabled=yes
bindaddr=0.0.0.0
bindport=8088
tlsenable=yes
tlsbindaddr=0.0.0.0:8089
tlscertfile=/etc/asterisk/keys/asterisk.pem
tlsprivatekey=/etc/asterisk/keys/asterisk.pem

rtp.conf

[general]
rtpstart=10000
rtpend=20000
icesupport=yes
stunaddr=stun.l.google.com:19302

extensions.conf

[default]
exten => 100,1,Dial(SIP/1060)
exten => 101,1,Dial(SIP/1061)
exten => 102,1,Playback(1-for-am-2-for-pm)
exten => 205,1,Answer
exten => 205,2,Wait(2)
exten => 205,3,Record(asterisk-recording%d:ulaw)
exten => 205,4,Wait(2)
exten => 205,5,Playback(${RECORDED_FILE})
exten => 205,6,Wait(2)
exten => 205,7,Hangup

[from-internal]
exten => 1000,1,Answer()
same => n,Playback(demo-congrats)
same => n,Hangup()

sip.conf

[general]
udpbindaddr=0.0.0.0:5060
realm=x.x.x.x ;replace with your Asterisk server public IP address or host
transport=udp,ws,wss
externaddr=x.x.x.x ;replace with your Server's Public IP Address
websocket_enabled=true

[6001]
host=dynamic
secret=****
context=from-internal
type=friend
encryption=yes
avpf=yes
force_avp=yes
icesupport=yes
directmedia=no
disallow=all
allow=ulaw
dtlsenable=yes
dtlsverify=fingerprint
dtlscertfile=/etc/asterisk/keys/asterisk.pem
dtlscafile=/etc/asterisk/keys/ca.crt
dtlssetup=actpass

The filed values set for the expert.htm page for the demo is as follows:-

WebSocket Server URL : wss://X.X.X.X:8088/ws
SIP outbound Proxy URL: udp://X.X.X.X:5060
ICE servers: [{ url: ‘stun:stun.l.google.com:19302’}]

The filed values set for the call.htm page for the demo is as follows:-

Display name: Rusty WEBRTC
Private identity: 6001
Public identity: sip:6001@X.X.X.X
Password; ****
Realm: X.X.X.X

Where X.X.X.X is my Asterisks server IP.

When click on the "Log in" button on the call.htm page an error message is displayed like

Disconnected: Failed to connect to the server

The linphone plugin is installed on the project right now. Due to the withdrawal of NPAPI support by Chrome/Mozilla browsers, the VoIP feature is completely outdated on the project. Now I want to replace the feature with SipML5 plugin which supports the WebRTC protocol. I need to check the registration, login, audio call features of the SIPML5 plugin. But all these functionalities can be implemented once i got connected to the server.

The Asterisks CLI is not displayed any error message. The console history of Chrome and Mozilla browsers are not displayed any vulnerable error messages. So I'm completely stuck on the project.

The demo files were worked fine on the Asterisks 11.8.1 server. But the SRTP module was not installed on the server so that the audio feature was not worked fine. Our supporting team is installed the library now and reinstalled the asterisks server with version 13. The firewall is open for the AWS server and the ports are open now.

Can anybody help me to fix the issue so that i can go further with the plug in integration to my project.Please let me know if any other details needed


问:
Sequelize Query to find all records that falls in between date range
I have a model with columns:

```<code>from: { type: Sequelize.DATE }
to: { type: Sequelize.DATE }
</code>```

I want to query all records whose either from OR to falls in between the date ranges : [startDate, endDate]

Tried Something Like:

```<code>const where = {
    $or: [{
        from: {
            $lte: startDate,
            $gte: endDate,
        },
        to: {
            $lte: startDate,
            $gte: endDate,
        },
    }],
};
</code>```

Something Like:

```<code>SELECT * from MyTable WHERE (startDate <= from <= endDate) OR (startDate <= to <= endDate
</code>```

答:
The solution which works for me is this:-

```<code>// here startDate and endDate are Date objects
const where = {
    from: {
        $between: [startDate, endDate]
    }
};
</code>```

For reference to know more about operators:- http://docs.sequelizejs.com/en/latest/docs/querying/#operators

Note:
In MYSQL between comparison operator is inclusive, which means it is equivalent to the expression (startDate <= from AND from <= endDate).

ContentLicense: CC BY-SA 4.0

Body:
I have a model with columns:

from: { type: Sequelize.DATE }
to: { type: Sequelize.DATE }

I want to query all records whose either from OR to falls in between the date ranges : [startDate, endDate]

Tried Something Like:

const where = {
    $or: [{
        from: {
            $lte: startDate,
            $gte: endDate,
        },
        to: {
            $lte: startDate,
            $gte: endDate,
        },
    }],
};

Something Like:

SELECT * from MyTable WHERE (startDate <= from <= endDate) OR (startDate <= to <= endDate

Body:
The solution which works for me is this:-

// here startDate and endDate are Date objects
const where = {
    from: {
        $between: [startDate, endDate]
    }
};

For reference to know more about operators:- http://docs.sequelizejs.com/en/latest/docs/querying/#operators

Note:
In MYSQL between comparison operator is inclusive, which means it is equivalent to the expression (startDate <= from AND from <= endDate).


问:
Pass an input variable to PHP using AJAX, but not with POST
My form is like the one above:

```<code><form id="calculator">
<input type="text" name="height" id="height"/>
<input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
<button type="button" onclick="calculatePanels();">
</form>
</code>```

Jquery script is the next one:

```<code>function calculatePanels() {
     var Height = document.forms["calculator"]["height"].value;

     $.ajax({
                url: "includes/inferiorPanel.php",
                success: function(result){
            $("#inferiorPanel").val(result);
            }});
}
</code>```

And PHP code from inferiorPanel.php is:

```<code><?php
$height = ????;

        switch ($height) {

            case ($height > 0 && $height <= 1845):
            echo 615;
            break;

            case ($height > 1845 && $height <= 1980):
            echo 495;
            break;

            case ($height > 1980 && $height <= 2100):
            echo 495;
            break;

            case ($height > 2100 && $height <= 2220):
            echo 495;
            break;

            case ($height > 2220 && $height <= 2340):
            echo 615;
            break;

            case ($height > 2340 && $height <= 2460):
            echo 615;
            break;

            case ($height > 2460 && $height <= 2475):
            echo 495;
            break;

            case ($height > 2475 && $height <= 2595):
            echo 615;
            break;

            case ($height > 2595 && $height <= 2715):
            echo 615;
            break;

            case ($height > 2715 && $height <= 2835):
            echo 615;
            break;

            case ($height > 2835 && $height <= 2955):
            echo 615;
            break;

            case ($height > 2955 && $height <= 3000):
            echo 615;
            break;
}
</code>```

My question is:
How to pass the variable height in PHP without using POST on Ajax, in order to show the result in input inferiorPanel?

I do not want to use <input type="submit" /> because will refresh the page

答:
Page refreshes not because you use $_POST, but because your code is incomplete.

Here what you need to do (you have jquery, so use it):

Remove onclick from button, remove <button>, add submit:

```<code><form id="calculator">
    <input type="text" name="height" id="height"/>
    <input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
    <input type="submit" name="Name" value="Value">
</form>
</code>```

Bind a handler to submit event of your form

```<code>$( "#calculator" ).submit(function() {
    var Height = $( "#height" ).val();

    $.ajax({
        url: "includes/inferiorPanel.php",
        data: { height: Height},
        type: "POST",
        success: function(result){
            $("#inferiorPanel").val(result);
        }
    });

    // simple way to prevent default action of form submission:
    return false;
} );
</code>```

On server side:

```<code><?php
$height = $_POST['height'];
switch ($height) {
    // run your switch here
}
?>
</code>```

Body:
My form is like the one above:

<form id="calculator">
<input type="text" name="height" id="height"/>
<input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
<button type="button" onclick="calculatePanels();">
</form>

Jquery script is the next one:

function calculatePanels() {
     var Height = document.forms["calculator"]["height"].value;

     $.ajax({
                url: "includes/inferiorPanel.php",
                success: function(result){
            $("#inferiorPanel").val(result);
            }});
}

And PHP code from inferiorPanel.php is:

<?php
$height = ????;

        switch ($height) {

            case ($height > 0 && $height <= 1845):
            echo 615;
            break;

            case ($height > 1845 && $height <= 1980):
            echo 495;
            break;

            case ($height > 1980 && $height <= 2100):
            echo 495;
            break;

            case ($height > 2100 && $height <= 2220):
            echo 495;
            break;

            case ($height > 2220 && $height <= 2340):
            echo 615;
            break;

            case ($height > 2340 && $height <= 2460):
            echo 615;
            break;

            case ($height > 2460 && $height <= 2475):
            echo 495;
            break;

            case ($height > 2475 && $height <= 2595):
            echo 615;
            break;

            case ($height > 2595 && $height <= 2715):
            echo 615;
            break;

            case ($height > 2715 && $height <= 2835):
            echo 615;
            break;

            case ($height > 2835 && $height <= 2955):
            echo 615;
            break;

            case ($height > 2955 && $height <= 3000):
            echo 615;
            break;
}

My question is:
How to pass the variable height in PHP without using POST on Ajax, in order to show the result in input inferiorPanel?

I do not want to use <input type="submit" /> because will refresh the page

Body:
Page refreshes not because you use $_POST, but because your code is incomplete.

Here what you need to do (you have jquery, so use it):

Remove onclick from button, remove <button>, add submit:

<form id="calculator">
    <input type="text" name="height" id="height"/>
    <input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
    <input type="submit" name="Name" value="Value">
</form>

Bind a handler to submit event of your form

$( "#calculator" ).submit(function() {
    var Height = $( "#height" ).val();

    $.ajax({
        url: "includes/inferiorPanel.php",
        data: { height: Height},
        type: "POST",
        success: function(result){
            $("#inferiorPanel").val(result);
        }
    });

    // simple way to prevent default action of form submission:
    return false;
} );

On server side:

<?php
$height = $_POST['height'];
switch ($height) {
    // run your switch here
}
?>


问:
SOAP for a newbie using PHP
There is a SOAP web service I need to connect to but I am having a hard time wrapping my head around how SOAP works. I just recently learned the basics of using REST, which was pretty easy, and I am also taking my first steps in programming (PHP).

According to the documentation the first thing I need to do is write this header.

```<code><soap:Header>

<wsse:Security soap:mustUnderstand="1">

<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78">

<wsse:Username>ws.test</wsse:Username>

<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">test</wsse:Password>

</wsse:UsernameToken>

</wsse:Security>

</soap:Header>
</code>```

I tried to search for a way to do this with php and I might be able to do something similar but I don't understand what I am doing though.

The documentation tells me to use WSE 2.0, but I read online that WSE is obsolete. Should I then not use that? And to be honest, I don't even know what WSE is. Is that something I should be downloading or is that something that is on the server?

If anyone can shed any light on this or suggest simple up to date instructions for a SOAP beginner, I'd be very grateful.

答: wsdltophp.com was my solution. It's great for someone who just needs a quick fix, but perhaps not the best if you really want to learn how to use SOAP.</p>

Title: SOAP for a newbie using PHP

Body:
There is a SOAP web service I need to connect to but I am having a hard time wrapping my head around how SOAP works. I just recently learned the basics of using REST, which was pretty easy, and I am also taking my first steps in programming (PHP).

According to the documentation the first thing I need to do is write this header.

<soap:Header>

<wsse:Security soap:mustUnderstand="1">

<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-24ada6f8-4626-4269-b786-a22361bfde78">

<wsse:Username>ws.test</wsse:Username>

<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">test</wsse:Password>

</wsse:UsernameToken>

</wsse:Security>

</soap:Header>

I tried to search for a way to do this with php and I might be able to do something similar but I don't understand what I am doing though.

The documentation tells me to use WSE 2.0, but I read online that WSE is obsolete. Should I then not use that? And to be honest, I don't even know what WSE is. Is that something I should be downloading or is that something that is on the server?

If anyone can shed any light on this or suggest simple up to date instructions for a SOAP beginner, I'd be very grateful.


问:
How can I programmatically change the background in Mac OS X?
How would I go about programmatically changing the desktop background in Mac OS X?  I'd like to use python, but I'm interested in any way possible.  Could I hook up to Terminal and call a certain command?</p>

答:
From python, if you have appscript installed (sudo easy_install appscript), you can simply do

```<code>from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))
</code>```

Otherwise, this applescript will change the desktop background

```<code>tell application "Finder"
    set desktop picture to POSIX file "/your/filename.jpg"
end tell
</code>```

You can run it from the command line using osascript, or from Python using something like

```<code>import subprocess

SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""

def set_desktop_background(filename):
    subprocess.Popen(SCRIPT%filename, shell=True)
</code>```

OwnerDisplayName: stalepretzel

Body:
From python, if you have appscript installed (sudo easy_install appscript), you can simply do

from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))

Otherwise, this applescript will change the desktop background

tell application "Finder"
    set desktop picture to POSIX file "/your/filename.jpg"
end tell

You can run it from the command line using osascript, or from Python using something like

import subprocess

SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""

def set_desktop_background(filename):
    subprocess.Popen(SCRIPT%filename, shell=True)

OwnerDisplayName: dF

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dF


问:
FIND_IN_SET problem
I have this MySql query:

```<code>SELECT * FROM `tbl_prods`
WHERE `id` IN ('58', '169', '166', '496', '24', '28')
ORDER BY FIND_IN_SET(`id`, '58, 169, 166, 496, 24, 28')
</code>```

the result is weird:

```<code>24
28
166
169
496
58
</code>```

I can't figure out how to return the exact order by my FIND_IN_SET

any ideas where I am doing wrong?

Title: FIND_IN_SET problem

Body:
I have this MySql query:

SELECT * FROM `tbl_prods`
WHERE `id` IN ('58', '169', '166', '496', '24', '28')
ORDER BY FIND_IN_SET(`id`, '58, 169, 166, 496, 24, 28')

the result is weird:

24
28
166
169
496
58

I can't figure out how to return the exact order by my FIND_IN_SET

any ideas where I am doing wrong?

Body:
You should not have spaces in

'58, 169, 166, 496, 24, 28'

Change it to

'58,169,166,496,24,28'


问:
Received odd RVM error in workspace, now rails commands aren't working
I just logged into my Ubuntu workspace on Cloud9. Upon logging in I saw an error.

```<code>RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does
that too, you can ignore these warnings with 'rvm rvmrc warning ignore
/home/ubuntu/workspace/Simutronix/Gemfile'. To ignore the warning for
all files run 'rvm rvmrc warning ignore allGemfiles'.
</code>```

Which I've not seen before and wasn't occurring when I last used the workspace. I then attempted to run the Rails server.

```<code>rails server -b $IP -p $PORT
</code>```

I got an error message back.

```<code>bash: rails: command not found
</code>```

I then tried to run bundle install which also came back with command not found.

ruby -v returns ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux].

What's likely to have happened to cause this to happen in between logins and what can I do to fix it?

答:
Looks like Ubuntu can't find your Rails installation. Make sure you have Rails installed on your workspace by typing:

```<code>rails -v
</code>```

If it is properly installed, It should return something like

```<code>Rails 5.0.2
</code>```

(depending upon your Rails version.)

If you don't have Rails installed, you can install it by typing

```<code>gem install rails
</code>```

You can append --no-doc to the above command if you don't want it to install documentation, thereby speeding up the installation process (That's totally up to you, though. It won't affect your installation in any other way. I promise!)

If this doesn't solve your problem, please update your answer with your Gemfile.

Body:
I just logged into my Ubuntu workspace on Cloud9. Upon logging in I saw an error.

RVM used your Gemfile for selecting Ruby, it is all fine - Heroku does
that too, you can ignore these warnings with 'rvm rvmrc warning ignore
/home/ubuntu/workspace/Simutronix/Gemfile'. To ignore the warning for
all files run 'rvm rvmrc warning ignore allGemfiles'.

Which I've not seen before and wasn't occurring when I last used the workspace. I then attempted to run the Rails server.

rails server -b $IP -p $PORT

I got an error message back.

bash: rails: command not found

I then tried to run bundle install which also came back with command not found.

ruby -v returns ruby 2.4.1p111 (2017-03-22 revision 58053) [x86_64-linux].

What's likely to have happened to cause this to happen in between logins and what can I do to fix it?

Body:
Looks like Ubuntu can't find your Rails installation. Make sure you have Rails installed on your workspace by typing:

rails -v

If it is properly installed, It should return something like

Rails 5.0.2

(depending upon your Rails version.)

If you don't have Rails installed, you can install it by typing

gem install rails

You can append --no-doc to the above command if you don't want it to install documentation, thereby speeding up the installation process (That's totally up to you, though. It won't affect your installation in any other way. I promise!)

If this doesn't solve your problem, please update your answer with your Gemfile.


问:
Data structure to store HashMap in Druid
I am newbie in Druid. My problem is that how to store and query HashMap in Druid using java to interact.
I have network table as follow:

```<code>Network    f1    f1    f3  .... fn
value       1    3      2  ..... 2
</code>```

Additional, I have range-time table

```<code>time             impression
2016-08-10-00      1000
2016-08-10-00      3000
2016-08-10-00      4000
2016-08-10-00      2000
2016-08-10-00      8000
</code>```

In Druid can I store range-time table as a HashMap and query both of the tables above with the statement:

```<code>Filter f1 = 1 and f2 = 1 and range-time between [t1, t2].
</code>```

Can anyone help me ? Thanks so much.

答:
@VanThaoNguye,

Yes you can store the hashmaps in druid and you can query with bound filters.

You can read more about bound filters here: http://druid.io/docs/latest/querying/filters.html#bound-filter

Body:
I am newbie in Druid. My problem is that how to store and query HashMap in Druid using java to interact.
I have network table as follow:

Network    f1    f1    f3  .... fn
value       1    3      2  ..... 2

Additional, I have range-time table

time             impression
2016-08-10-00      1000
2016-08-10-00      3000
2016-08-10-00      4000
2016-08-10-00      2000
2016-08-10-00      8000

In Druid can I store range-time table as a HashMap and query both of the tables above with the statement:

Filter f1 = 1 and f2 = 1 and range-time between [t1, t2].

Can anyone help me ? Thanks so much.


问:
debugging simple LISP functions.
I am very new to lisp, and am having a hard time even getting my feet wet. I'm sure once, I have a few functions working, I'll be able to build upon them and work on higher order functions, and more complex problems.

Can someone point out my errors in the following code.

```<code>(defun indeHelper(A L N)
 (cond (Null N) nil)
 ((= A (first L) (cons N (indeHelper A (rest L) (+ 1 N)))))
 (t (indeHelper A (rest L) (+ 1 N))))

(defun inde(A L)
  (funcall indeHelper(A L 1)))
</code>```

Also how would I call this? I have one function I think is working ok, but I can't get the syntax for calling it.  Thanks for any help.

答:
You have a number of syntax issues.

The syntax of COND is:

```<code>(cond (test1 body1...)
      (test2 body2...)
      ...)
</code>```

Your test1 is supposed to be (null n), and body1 should be nil, but you didn't wrap them in a level of parentheses. Then your other tests and bodies are outside cond, as should be apparent from the indentation.

It should be:

```<code>(defun indeHelper(A L N)
  (cond ((Null N) nil)
        ((= A (first L) (cons N (indeHelper A (rest L) (+ 1 N)))))
        (t (indeHelper A (rest L) (+ 1 N)))))
</code>```

In the second function, you don't need to use funcall. That's used when you're calling a dynamically-determined function (e.g. when writing higher-order functions), but you're just calling a known function. It should just be:

```<code>(defun inde(A L)
  (indeHelper A L 1))
</code>```

If you did need to use funcall, the syntax is:

```<code>(funcall someVariable A L 1)
</code>```

When using funcall, the arguments aren't put into a nested list, they're just ordinary arguments to funcall.

Title: debugging simple LISP functions.

Body:
I am very new to lisp, and am having a hard time even getting my feet wet. I'm sure once, I have a few functions working, I'll be able to build upon them and work on higher order functions, and more complex problems.

Can someone point out my errors in the following code.

(defun indeHelper(A L N)
 (cond (Null N) nil)
 ((= A (first L) (cons N (indeHelper A (rest L) (+ 1 N)))))
 (t (indeHelper A (rest L) (+ 1 N))))

(defun inde(A L)
  (funcall indeHelper(A L 1)))

Also how would I call this? I have one function I think is working ok, but I can't get the syntax for calling it.  Thanks for any help.

Body:
You have a number of syntax issues.

The syntax of COND is:

(cond (test1 body1...)
      (test2 body2...)
      ...)

Your test1 is supposed to be (null n), and body1 should be nil, but you didn't wrap them in a level of parentheses. Then your other tests and bodies are outside cond, as should be apparent from the indentation.

It should be:

(defun indeHelper(A L N)
  (cond ((Null N) nil)
        ((= A (first L) (cons N (indeHelper A (rest L) (+ 1 N)))))
        (t (indeHelper A (rest L) (+ 1 N)))))

In the second function, you don't need to use funcall. That's used when you're calling a dynamically-determined function (e.g. when writing higher-order functions), but you're just calling a known function. It should just be:

(defun inde(A L)
  (indeHelper A L 1))

If you did need to use funcall, the syntax is:

(funcall someVariable A L 1)

When using funcall, the arguments aren't put into a nested list, they're just ordinary arguments to funcall.


问:
fetch data from server using xamarin with realm
I am trying to create mobile app using Xamarin and Realm. I am trying to pull data from server and load it into objects extended by RealmObjects.

code to fetch data from server

public async void getCompanyMaster() {
    var uri = new Uri(string.Format(URL, string.Empty));

    try
    {
        getConnection();
        var response = await client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            Company company = JsonConvert.DeserializeObject<Company>(content);

            Debug.WriteLine("Company List " );
        }
    }
    catch (Exception e)
    {
        Debug.WriteLine("Error {0}", e.Message);

    }
}
```

<p>realm model company </p>

<pre class="lang-cs prettyprint-override"><code>namespace DesignModel.Model.Master
{
    public class Company : RealmObject
    {
        public string errorMessage { get; set; }
        public string status { get; set; }

        [JsonProperty(PropertyName = "companyMaster")]
        IList<CompanyMaster> companyMaster { get; }
    }
}
</code>```

realm model for company master

namespace DesignModel.Model.Master
{
    public class CompanyMaster : RealmObject
    {
        public string companyAddress { get; set; }
        public string companyId { get; set; }
        public string companyName { get; set; }

        public string companyPhoneNumber { get; set; }
    }
}
```

<p>now the issue is at following line in <code>getCompanyMaster</code> function</p>

<pre class="lang-cs prettyprint-override"><code>Company company = JsonConvert.DeserializeObject<Company>(content);
</code>```

it raises an exception

Error Error setting value to 'errorMessage' on
  'DesignModel.Model.Master.Company'.

if i do not extend my class from RealmObject then it works fine but when i add RealObject it doesn't work.

the above approach does work in android native but do not know why it doesn't work in xamarin.

sample json

{
  "errorMessage": "",
  "status": "Ok",
  "companyMaster": [
    {
      "companyAddress": "123 Coffee Street\nSuite 300\nRedmond, WA 98052\nUSA",
      "companyId": "cec",
      "companyName": "Contoso Entertainment Systems",
      "companyPhoneNumber": "425-555-0156"
    }]
}
```

complete stack  trace

[0:] Error Newtonsoft.Json.JsonSerializationException: Error setting
  value to 'errorMessage' on 'DesignModel.Model.Master.Company'. --->
  System.PlatformNotSupportedException: The PCL build of Realm is being
  linked which probably means you need to use NuGet or otherwise link a
  platform-specific Realm.dll to your main application.

答:
Adding a note from documentation found here

https://realm.io/docs/xamarin/latest/

under Getting Started - Prerequisites

Important note for PCL users - this works via the NuGet Bait and Switch
  Trick. You
  have to install the Realm NuGet package into every PCL that uses Realm
  as well as each of your platform-specific projects, e.g.: your final
  app for iOS and Android. If you are using shared projects, you only
  have to install the NuGet into each platform-specific project.

Body:
I am trying to create mobile app using Xamarin and Realm. I am trying to pull data from server and load it into objects extended by RealmObjects.

code to fetch data from server

public async void getCompanyMaster() {
    var uri = new Uri(string.Format(URL, string.Empty));

    try
    {
        getConnection();
        var response = await client.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            Company company = JsonConvert.DeserializeObject<Company>(content);

            Debug.WriteLine("Company List " );
        }
    }
    catch (Exception e)
    {
        Debug.WriteLine("Error {0}", e.Message);

    }
}

realm model company

namespace DesignModel.Model.Master
{
    public class Company : RealmObject
    {
        public string errorMessage { get; set; }
        public string status { get; set; }

        [JsonProperty(PropertyName = "companyMaster")]
        IList<CompanyMaster> companyMaster { get; }
    }
}

realm model for company master

namespace DesignModel.Model.Master
{
    public class CompanyMaster : RealmObject
    {
        public string companyAddress { get; set; }
        public string companyId { get; set; }
        public string companyName { get; set; }

        public string companyPhoneNumber { get; set; }
    }
}

now the issue is at following line in getCompanyMaster function

Company company = JsonConvert.DeserializeObject<Company>(content);

it raises an exception

Error Error setting value to 'errorMessage' on
  'DesignModel.Model.Master.Company'.

if i do not extend my class from RealmObject then it works fine but when i add RealObject it doesn't work.

the above approach does work in android native but do not know why it doesn't work in xamarin.

sample json

{
  "errorMessage": "",
  "status": "Ok",
  "companyMaster": [
    {
      "companyAddress": "123 Coffee Street\nSuite 300\nRedmond, WA 98052\nUSA",
      "companyId": "cec",
      "companyName": "Contoso Entertainment Systems",
      "companyPhoneNumber": "425-555-0156"
    }]
}

complete stack  trace

[0:] Error Newtonsoft.Json.JsonSerializationException: Error setting
  value to 'errorMessage' on 'DesignModel.Model.Master.Company'. --->
  System.PlatformNotSupportedException: The PCL build of Realm is being
  linked which probably means you need to use NuGet or otherwise link a
  platform-specific Realm.dll to your main application.


问:
ASP.NET DATA TABLE Traverse Problem
I am getting the Data table a output from my DataAccess Layer.

In My Datatable I am getting users Name,Number,Qualification

I want to assign a users name,number,qualification to a textbox for a particular user id,

How can i do that.

Help

答:
Suppose you got datatable dt from the DAL

Then

```<code>var row = from t in dt
          where t["userId"]='userid'
          select t;

since you got row related to a user now you can use it to assign to the textboxs

 txtName.Text = row["Name"]
</code>```

Title: ASP.NET DATA TABLE Traverse Problem

Body:
Suppose you got datatable dt from the DAL

Then

var row = from t in dt
          where t["userId"]='userid'
          select t;

since you got row related to a user now you can use it to assign to the textboxs

 txtName.Text = row["Name"]


问:
Swift TimeInterval to Date
I've extended Date to return a string like so:

```<code>extension Date {
    func timeAgoDisplay() -> String {
        print("Date RIGHT NOW: \(self)")
        let secondsAgo = Int(Date().timeIntervalSince(self))

        if secondsAgo >= 86400 * 2 {
            return "\(((secondsAgo / 60) / 60) / 24) days ago"
        } else if secondsAgo >= 86400 {
            return "\(((secondsAgo / 60) / 60) / 24) day ago"
        } else if secondsAgo > 7200 {
            return "\((secondsAgo / 60) / 60) hours ago"
        } else if secondsAgo >= 3600 {
            return "\((secondsAgo / 60) / 60) Hour ago"
        } else if secondsAgo < 60 {
            return "\(secondsAgo) seconds ago"
        } else if secondsAgo > 119 {
            return "\(secondsAgo / 60) minutes ago"
        }

        return "\(secondsAgo / 60) minute ago"
    }
}
</code>```

I have a timeInterval in a database for every post a user makes but I want to know how to make this extension work to the TimeInterval of the post.

答:
It looks like you're almost there! You're already calculating a TimeInterval and simply need to make that the type extended instead:

```<code>extension TimeInterval {
    func timeAgoDisplay() -> String {
        let secondsAgo = Int(self)

        if secondsAgo >= 86400 * 2 {
            return "\(((secondsAgo / 60) / 60) / 24) days ago"
        } else if secondsAgo >= 86400 {
            return "\(((secondsAgo / 60) / 60) / 24) day ago"
        } else if secondsAgo > 7200 {
            return "\((secondsAgo / 60) / 60) hours ago"
        } else if secondsAgo >= 3600 {
            return "\((secondsAgo / 60) / 60) Hour ago"
        } else if secondsAgo < 60 {
            return "\(secondsAgo) seconds ago"
        } else if secondsAgo > 119 {
            return "\(secondsAgo / 60) minutes ago"
        }

        return "\(secondsAgo / 60) minute ago"
    }
}
</code>```

Title: Swift TimeInterval to Date

Body:
I've extended Date to return a string like so:

extension Date {
    func timeAgoDisplay() -> String {
        print("Date RIGHT NOW: \(self)")
        let secondsAgo = Int(Date().timeIntervalSince(self))

        if secondsAgo >= 86400 * 2 {
            return "\(((secondsAgo / 60) / 60) / 24) days ago"
        } else if secondsAgo >= 86400 {
            return "\(((secondsAgo / 60) / 60) / 24) day ago"
        } else if secondsAgo > 7200 {
            return "\((secondsAgo / 60) / 60) hours ago"
        } else if secondsAgo >= 3600 {
            return "\((secondsAgo / 60) / 60) Hour ago"
        } else if secondsAgo < 60 {
            return "\(secondsAgo) seconds ago"
        } else if secondsAgo > 119 {
            return "\(secondsAgo / 60) minutes ago"
        }

        return "\(secondsAgo / 60) minute ago"
    }
}

I have a timeInterval in a database for every post a user makes but I want to know how to make this extension work to the TimeInterval of the post.

Body:
It looks like you're almost there! You're already calculating a TimeInterval and simply need to make that the type extended instead:

extension TimeInterval {
    func timeAgoDisplay() -> String {
        let secondsAgo = Int(self)

        if secondsAgo >= 86400 * 2 {
            return "\(((secondsAgo / 60) / 60) / 24) days ago"
        } else if secondsAgo >= 86400 {
            return "\(((secondsAgo / 60) / 60) / 24) day ago"
        } else if secondsAgo > 7200 {
            return "\((secondsAgo / 60) / 60) hours ago"
        } else if secondsAgo >= 3600 {
            return "\((secondsAgo / 60) / 60) Hour ago"
        } else if secondsAgo < 60 {
            return "\(secondsAgo) seconds ago"
        } else if secondsAgo > 119 {
            return "\(secondsAgo / 60) minutes ago"
        }

        return "\(secondsAgo / 60) minute ago"
    }
}


问:
How to deploy an Office VSTO add-in using Visual Studio 2017
I've created an Outlook add-in, debugged and works fine. I want to be able to package it up for distribution.  This is for a very limited audience 5-10 people. What are the steps to doing so?

I tried Build | Publish which appears to work (using options of local filename and CDROM install location), but creates a massive 1.5MB setup.exe file and when it is executed, takes forever (it appears trying to contact some remote server and times out and pops an error, although the add-in appears to be registered).

Looking online, I found references to creating a SetupProject or using InstallShield Limited addition, but none of those appear to apply to Visual Studio 2017.

I'd be happy if I could just provide my DLL and a .reg file -- this is for a small set of 5-10 power users.

What is the simplest way to deploy this add-in?

答: The easiest way is Build | Publish. Just disable any online activities if you don't want it. You can do that in Project -> Settings -> Publish. Check your "Updates" settings for example.</p>


问:
Converting Java 1.8 lambdas to Java 1.7 on gs-uploading-files Spring Boot example
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

```<code>@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}
</code>```

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

```<code>import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}
</code>```

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

```<code>@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}
</code>```

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

```<code>import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}
</code>```

package java.util.stream does not exist

答:
The lambdas are in fact single-method interfaces, called functional interfaces. You can easily convert most of lambda expression to interface simply by following your IDE code completions. For example, let's take a filter method:

```<code>filter(Predicate<? super T> predicate)
</code>```

As you can see, filter method simply accepts an instance of Predicate interface, which has test method that looks like this:

```<code>boolean test(T t)

Evaluates this predicate on the given argument.

Parameters:
    t - the input argument
Returns:
    true if the input argument matches the predicate, otherwise false
</code>```

You can easily create your own Predicate implementation and use it while iterating your examples. For instance, you can create your own generic filter method which takes a Collection and your predicate strategy which will be applied for every element. You can also use Guava Function interfaces, which were used before Java 8. Here you have some explanation how to use it: https://github.com/google/guava/wiki/FunctionalExplained.

To sum it up - you can use Guava or create your own wrappers for every example. You can simulate streams simply by iterating your collections. Converting lambdas is a no-brainer, since you realize they are just single-method interfaces.

Body:
I am running through some exercises on https://spring.io/ Spring Boot.

Doing example https://spring.io/guides/gs/uploading-files/ and it works fine when I use Java 8, but unfortunately the code I am wrapping in a web service requires Java 7.  I have listed all of the erroring code, can someone help me convert the lambdas to 1.7 compliant code and replace the new libraries (java.util.stream.Stream and java.util.stream.Collectors).

Application.java

@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return (args) -> {
            storageService.deleteAll();
            storageService.init();
        };
    }
}

return (args) -> errors out saying "use source -8 or higher to enable
  lambda expressions"

FileUploadController.java

import java.util.stream.Collectors

//..

@GetMapping("/")
public String listUploadedFiles(Model model) throws IOException {

    model.addAttribute("files", storageService
            .loadAll()
            .map(path ->
                    MvcUriComponentsBuilder
                            .fromMethodName(FileUploadController.class, "serveFile", path.getFileName().toString())
                            .build().toString())
            .collect(Collectors.toList()));

    return "uploadForm";
}

package java.util.stream does not exist

type loadAll() is erroneous

errors out saying "use source -8 or higher to enable
  lambda expressions"

FileSystemStorageService.java

@Override
public Stream<Path> loadAll() {
    try {
        return Files.walk(this.rootLocation, 1)
                .filter(path -> !path.equals(this.rootLocation))
                .map(path -> this.rootLocation.relativize(path));
    } catch (IOException e) {
        throw new StorageException("Failed to read stored files", e);
    }

}

cannot find symbol walk

errors out saying "use source -8 or higher to enable
  lambda expressions"

StorageService.java

import java.util.stream.Stream;

public interface StorageService {

    void init();

    void store(MultipartFile file);

    Stream<Path> loadAll();

    Path load(String filename);

    Resource loadAsResource(String filename);

    void deleteAll();

}

package java.util.stream does not exist

Body:
The lambdas are in fact single-method interfaces, called functional interfaces. You can easily convert most of lambda expression to interface simply by following your IDE code completions. For example, let's take a filter method:

filter(Predicate<? super T> predicate)

As you can see, filter method simply accepts an instance of Predicate interface, which has test method that looks like this:

boolean test(T t)

Evaluates this predicate on the given argument.

Parameters:
    t - the input argument
Returns:
    true if the input argument matches the predicate, otherwise false

You can easily create your own Predicate implementation and use it while iterating your examples. For instance, you can create your own generic filter method which takes a Collection and your predicate strategy which will be applied for every element. You can also use Guava Function interfaces, which were used before Java 8. Here you have some explanation how to use it: https://github.com/google/guava/wiki/FunctionalExplained.

To sum it up - you can use Guava or create your own wrappers for every example. You can simulate streams simply by iterating your collections. Converting lambdas is a no-brainer, since you realize they are just single-method interfaces.


答:
you can use POST without refreshing the page

```<code> $.ajax({
     url: "includes/inferiorPanel.php",
     method: "POST",
     data : {'height' : Height},
     success: function(result){
         $("#inferiorPanel").val(result);
     }
 });
</code>```

and in php :

```<code><?php
    $height = $_POST['height'];
?>
</code>```

Title: Pass an input variable to PHP using AJAX, but not with POST

Body:
My form is like the one above:

<form id="calculator">
<input type="text" name="height" id="height"/>
<input type="text" name="inferiorPanel" id="inferiorPanel" readonly />
<button type="button" onclick="calculatePanels();">
</form>

Jquery script is the next one:

function calculatePanels() {
     var Height = document.forms["calculator"]["height"].value;

     $.ajax({
                url: "includes/inferiorPanel.php",
                success: function(result){
            $("#inferiorPanel").val(result);
            }});
}

And PHP code from inferiorPanel.php is:

<?php
$height = ????;

        switch ($height) {

            case ($height > 0 && $height <= 1845):
            echo 615;
            break;

            case ($height > 1845 && $height <= 1980):
            echo 495;
            break;

            case ($height > 1980 && $height <= 2100):
            echo 495;
            break;

            case ($height > 2100 && $height <= 2220):
            echo 495;
            break;

            case ($height > 2220 && $height <= 2340):
            echo 615;
            break;

            case ($height > 2340 && $height <= 2460):
            echo 615;
            break;

            case ($height > 2460 && $height <= 2475):
            echo 495;
            break;

            case ($height > 2475 && $height <= 2595):
            echo 615;
            break;

            case ($height > 2595 && $height <= 2715):
            echo 615;
            break;

            case ($height > 2715 && $height <= 2835):
            echo 615;
            break;

            case ($height > 2835 && $height <= 2955):
            echo 615;
            break;

            case ($height > 2955 && $height <= 3000):
            echo 615;
            break;
}

My question is:
How to pass the variable height in PHP without using POST on Ajax, in order to show the result in input inferiorPanel?

I do not want to use <input type="submit" /> because will refresh the page

Body:
you can use POST without refreshing the page

 $.ajax({
     url: "includes/inferiorPanel.php",
     method: "POST",
     data : {'height' : Height},
     success: function(result){
         $("#inferiorPanel").val(result);
     }
 });

and in php :

<?php
    $height = $_POST['height'];
?>


问:
Trouble with TensorFlow in Jupyter Notebook
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. The Anaconda install works, but I need to preface any call to python with "source activate tensorflow". And the pip install works nicely, if start python the standard way (in the terminal) then tensorflow loads just fine.

My question is: how can I also have it work in the Jupyter notebooks?

This leads me to a more general question: it seems that my python kernel in Jupyter/Anaconda is separate from the python kernel (or environment? not sure about the terminology here) used system wide. It would be nice if these coincided, so that if I install a new python library, it becomes accessible to all the varied ways I have of running python.

答:
I had a similar issue when using a custom Ubuntu 16 image. The problem was related to an existing version of numpy that was already installed on my system.

I initially tried

```<code>sudo pip3 install tensorflow
</code>```

This resulted in the following exception:

Exception:
  Traceback (most recent call last):
    File "/anaconda/envs/py35/lib/python3.5/shutil.py", line 538, in move
      os.rename(src, real_dst)
  PermissionError: [Errno 13] Permission denied: '/anaconda/envs/py35/lib/python3.5/site-packages/numpy' -> '/tmp/pip-co73r3hm-uninstall/anaconda/envs/py35/lib/python3.5/site-packages/numpy'

The docs advise that if you encounter any issues with this command to try the following:

```<code>sudo pip3 install --upgrade \
https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.1-cp35-cp35m-linux_x86_64.whl
</code>```

However, my system was unable to locate pip3

sudo: pip3 command not found

The ulitmate solution was to create a symlink for pip3

```<code>sudo ln -s /anaconda/envs/py35/bin/pip3.5 /usr/local/bin/pip3
</code>```

Finally, the following command worked without trouble

```<code>sudo /usr/local/bin/pip3 install --upgrade \
https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.1-cp35-cp35m-linux_x86_64.whl
</code>```

I verified the installation in the terminal and also verified a successful import in my Jupyter Notebook

```<code>import tensorflow as tf
</code>```

Body:
I had a similar issue when using a custom Ubuntu 16 image. The problem was related to an existing version of numpy that was already installed on my system.

I initially tried

sudo pip3 install tensorflow

This resulted in the following exception:

Exception:
  Traceback (most recent call last):
    File "/anaconda/envs/py35/lib/python3.5/shutil.py", line 538, in move
      os.rename(src, real_dst)
  PermissionError: [Errno 13] Permission denied: '/anaconda/envs/py35/lib/python3.5/site-packages/numpy' -> '/tmp/pip-co73r3hm-uninstall/anaconda/envs/py35/lib/python3.5/site-packages/numpy'

The docs advise that if you encounter any issues with this command to try the following:

sudo pip3 install --upgrade \
https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.1-cp35-cp35m-linux_x86_64.whl

However, my system was unable to locate pip3

sudo: pip3 command not found

The ulitmate solution was to create a symlink for pip3

sudo ln -s /anaconda/envs/py35/bin/pip3.5 /usr/local/bin/pip3

Finally, the following command worked without trouble

sudo /usr/local/bin/pip3 install --upgrade \
https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.1-cp35-cp35m-linux_x86_64.whl

I verified the installation in the terminal and also verified a successful import in my Jupyter Notebook

import tensorflow as tf


问:
Hello World Google App Engine not working
I'm following this simple tutorial to create a hello world app, but on testing ("Starting the development server") it fails to run. When I click on "logs" in the launcher, I have

```<code>in "C:\...\app.yaml", line 1, column 14
2013-07-13 19:48:38 (Process exited with code 1)
</code>```

The 14th line in the .yaml file is version: "2.5.2". Can it cause the problem?

Thanks!

答:
Even i faced issues regarding the same while running my Hello_world app

the solution was finally in app.yaml file (as is the case most of the time)

error:application: hello_world

solution: application: hello-world (underscore sign replaced)

Body:
I'm following this simple tutorial to create a hello world app, but on testing ("Starting the development server") it fails to run. When I click on "logs" in the launcher, I have

in "C:\...\app.yaml", line 1, column 14
2013-07-13 19:48:38 (Process exited with code 1)

The 14th line in the .yaml file is version: "2.5.2". Can it cause the problem?

Thanks!


问:
define a function alias in VBA, possible?
I am using VBA behind MS Access
Say I have global methods foo1 and foo2 that gets the same arguments but do different things.
I know that in C++ I can assign a function an alias. Something like:
instead of:

```<code>If (term) then
   foo1 arg1, arg2, arg3
else
   foo2 arg1, arg2, arg3
End If
</code>```

I want to write:

```<code>Var new_func = Iff (term, foo1,foo2)
new_func arg1, arg2, arg3
</code>```

Can I do this on vba?

答:
If the 2 functions were implemented in 2 different class modules you could give them the same name & call them across an interface. That's about as close as you can get. (and its not very close)</p>

```<code>'empty interface class, name: IFoo
Public Function TheFunc(i As Integer) As Long
'
End Function
</code>```

```<code>'class clsFoo1
Implements IFoo

Private Function IFoo_TheFunc(i As Integer) As Long
MsgBox "I'm clsFoo1"
End Function
</code>```

```<code>'class clsFoo2
Implements IFoo

Private Function IFoo_TheFunc(i As Integer) As Long
MsgBox "I'm clsFoo2"
End Function
</code>```

```<code>'module code;
Dim myFoo As IFoo
If var = 1 Then
    Set myFoo = New clsFoo1
Else
    Set myFoo = New clsFoo2
End If

myFoo.TheFunc 12345
</code>```

Body:
I am using VBA behind MS Access
Say I have global methods foo1 and foo2 that gets the same arguments but do different things.
I know that in C++ I can assign a function an alias. Something like:
instead of:

If (term) then
   foo1 arg1, arg2, arg3
else
   foo2 arg1, arg2, arg3
End If

I want to write:

Var new_func = Iff (term, foo1,foo2)
new_func arg1, arg2, arg3

Can I do this on vba?

Body:
If the 2 functions were implemented in 2 different class modules you could give them the same name & call them across an interface. That's about as close as you can get. (and its not very close)

'empty interface class, name: IFoo
Public Function TheFunc(i As Integer) As Long
'
End Function

'class clsFoo1
Implements IFoo

Private Function IFoo_TheFunc(i As Integer) As Long
MsgBox "I'm clsFoo1"
End Function

'class clsFoo2
Implements IFoo

Private Function IFoo_TheFunc(i As Integer) As Long
MsgBox "I'm clsFoo2"
End Function

'module code;
Dim myFoo As IFoo
If var = 1 Then
    Set myFoo = New clsFoo1
Else
    Set myFoo = New clsFoo2
End If

myFoo.TheFunc 12345


问:
How to make a datetime object aware (not naive)
What I need to do

I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.

What I've Tried

First, to demonstrate the problem:

```<code>Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
</code>```

First, I tried astimezone:

```<code>>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>
</code>```

It's not terribly surprising this failed, since it's actually trying to do a conversion.  Replace seemed like a better choice (as per How do I get a value of datetime.today() in Python that is "timezone aware"?):

```<code>>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>
</code>```

But as you can see, replace seems to set the tzinfo, but not make the object aware.  I'm getting ready to fall back to doctoring the input string to have a timezone before parsing it (I'm using dateutil for parsing, if that matters), but that seems incredibly kludgy.

Also, I've tried this in both Python 2.6 and Python 2.7, with the same results.

Context

I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I've already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I'm prepared to accept the risk of defaulting to that in this case.

答:
I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object.  This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour.  It is therefore useless. Do not use this!

localize is the correct function to use. Example:

```<code>localdatetime_aware = tz.localize(datetime_nonaware)
</code>```

Or a more complete example:

```<code>import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())
</code>```

gives me a timezone aware datetime value of the current local time:

```<code>datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)
</code>```

Body:
What I need to do

I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.

What I've Tried

First, to demonstrate the problem:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes

First, I tried astimezone:

>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>

It's not terribly surprising this failed, since it's actually trying to do a conversion.  Replace seemed like a better choice (as per How do I get a value of datetime.today() in Python that is "timezone aware"?):

>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>

But as you can see, replace seems to set the tzinfo, but not make the object aware.  I'm getting ready to fall back to doctoring the input string to have a timezone before parsing it (I'm using dateutil for parsing, if that matters), but that seems incredibly kludgy.

Also, I've tried this in both Python 2.6 and Python 2.7, with the same results.

Context

I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I've already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I'm prepared to accept the risk of defaulting to that in this case.

Body:
I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object.  This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour.  It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)


问:
Are 'raise a,b,c,' and 'raise (a,b,c)' same in Python 2.7
Can somebody please explain if why or why not 'raise a,b,c,' and 'raise (a,b,c)' are same in Python 2.7.

I tried to find information on how Tuples are treated from here and here but I couldn't establish if I could use the above expressions in place of one another.

Here is some background.
I have a Python 2 code which is having a lot of following statements

```<code>raise e,v,t
</code>```

Python 3 gives error on this syntax.
Converting it to following gets away the Python 3 compiler error but I wanted to verify if intent remains same in both Python 2 as well as Python 3.

```<code>raise (e,v,t)
</code>```

答:
Never pass a tuple to raise. It won't do what you expect.

On both Python 2 and Python 3, raise is documented to not accept a tuple. However, Python 2 has a weird code path in the raise implementation where if the first (or only) argument to raise is a tuple, it will be repeatedly replaced with its first element until Python reaches something that isn't a tuple. I have no idea why this is a thing, but it means that something like

```<code>raise ((Exception,), "other", "tuple", "items", "get", "ignored")
</code>```

gets treated like

```<code>raise Exception
</code>```

Here's a demo. Python 3 behaves more sensibly, erroring out because a tuple isn't an exception.

The syntax for raising exceptions changed on Python 3. The Python 2 statement

```<code>raise ExceptionType, value, traceback
</code>```

is now

```<code>raise ExceptionType(value).with_traceback(traceback)
</code>```

or, if value is an instance of ExceptionType,

```<code>raise value.with_traceback(traceback)
</code>```

Unfortunately, these syntaxes are incompatible to the degree that you can't even write both and pick which one to run based on your Python version. You'll get a syntax error before your code even runs.

The easiest way to fix this is with a compatibility library. For example, with six.reraise:

```<code>six.reraise(ExceptionType, value, traceback)
</code>```

Body:
Can somebody please explain if why or why not 'raise a,b,c,' and 'raise (a,b,c)' are same in Python 2.7.

I tried to find information on how Tuples are treated from here and here but I couldn't establish if I could use the above expressions in place of one another.

Here is some background.
I have a Python 2 code which is having a lot of following statements

raise e,v,t

Python 3 gives error on this syntax.
Converting it to following gets away the Python 3 compiler error but I wanted to verify if intent remains same in both Python 2 as well as Python 3.

raise (e,v,t)

Body:
Never pass a tuple to raise. It won't do what you expect.

On both Python 2 and Python 3, raise is documented to not accept a tuple. However, Python 2 has a weird code path in the raise implementation where if the first (or only) argument to raise is a tuple, it will be repeatedly replaced with its first element until Python reaches something that isn't a tuple. I have no idea why this is a thing, but it means that something like

raise ((Exception,), "other", "tuple", "items", "get", "ignored")

gets treated like

raise Exception

Here's a demo. Python 3 behaves more sensibly, erroring out because a tuple isn't an exception.

The syntax for raising exceptions changed on Python 3. The Python 2 statement

raise ExceptionType, value, traceback

is now

raise ExceptionType(value).with_traceback(traceback)

or, if value is an instance of ExceptionType,

raise value.with_traceback(traceback)

Unfortunately, these syntaxes are incompatible to the degree that you can't even write both and pick which one to run based on your Python version. You'll get a syntax error before your code even runs.

The easiest way to fix this is with a compatibility library. For example, with six.reraise:

six.reraise(ExceptionType, value, traceback)


问:
UI blocked when writing into textEdit
I've an application witch update execute commands on a database. I've a function witch execute that commands and in the in this function I display some messages to the user.

My problem is that the texts written into the textEdit are displayed at the end of the function work.

I've tried to use QThread but it does'nt resolve the problem

```<code>this->moveToThread(&threadText);
connect(&threadText, SIGNAL(started()), this, SLOT(writeTexte()));
threadText.start();
</code>```

Does anyone have an idea how to proceed to write into textEdit and not block the UI ?

答:
In Qt you never need threads in standard UI applications! That is because Qt uses something called event loops that process events smoothly without ever blocking. If you experience blocking, that is a sign that you have a bug somewhere in your code. For any beginner there are some pitfalls. The official documentation on the subject is quite good.

It is hard to tell what your exact bug is because there is littel code to look at. I suggest you post more of your code, especially the naive approach that did not work before you added threads to the mix.

On a side note, using threads in Qt is of course possible and has it's usages, however it can be un-intuitive. I have found this article to be a really good starting point to understand how threads is used best in Qt.

Title: UI blocked when writing into textEdit

Body:
I've an application witch update execute commands on a database. I've a function witch execute that commands and in the in this function I display some messages to the user.

My problem is that the texts written into the textEdit are displayed at the end of the function work.

I've tried to use QThread but it does'nt resolve the problem

this->moveToThread(&threadText);
connect(&threadText, SIGNAL(started()), this, SLOT(writeTexte()));
threadText.start();

Does anyone have an idea how to proceed to write into textEdit and not block the UI ?


问:
php MySql 2 column as index and 1 as another index?
I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.

they both must be varchar.

i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.

fetch all for first varchar column.

insert if not exist for both values.

I'm hoping to do it in the most efficient way.

what is the best way to insert without checking with another query if exist?

what is the best way other then:

```<code>SELECT * FROM table WHERE id = id
</code>```

to fetch when the column needed is varchar?

答:
I think you want to implement a composite primary key.

A composite primary key tells MySQL that you want your primary key to be a combination of fields.

More info here: Why use multiple columns as primary keys (composite primary key)

I don't know of a better option for your query, although I can advise, if possible:

Define columns to be NOT NULL. This gives you faster processing and requires less storage. It will also simplify queries sometimes because you don't need to check for NULL as a special case.

And with variable-length rows, you get more fragmentation in tables where you perform many deletes or updates due to the differing sizes of the records. You'll need to run OPTIMIZE TABLE periodically to maintain performance.

Body:
I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.

they both must be varchar.

i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.

fetch all for first varchar column.

insert if not exist for both values.

I'm hoping to do it in the most efficient way.

what is the best way to insert without checking with another query if exist?

what is the best way other then:

SELECT * FROM table WHERE id = id

to fetch when the column needed is varchar?


问:
CondtionalBean in depending on jvm arguments
I can use Condtional Bean in connection with application.properties. However, I consider is it possible to do the same thing, but using jvm arguments.

答:
As @Ralph posted in his answer, you can use Spring EL expressions to refer to systemProperties bean and thus accessing JVM args.

E.g. refer as #{systemProperties.test} for -Dtest="hallo welt"


问:
Pass index of apply function to FUN in R or should I do something different?
I am currently trying to loop through my data frame called "test" and get the sum of each of the numbers in each column. ex. sum(test$colname1 = 4) would return 1 because of only one 4 occurrence in the first column. I cannot use count because I have 7 specific numbers I want saved (1-7) even if there were 0 occurrences for a number. Count only returns numbers that have occurred and doesn't show 0 values. My plan is to use the apply function to loop through my columns and do the sum of each of the 7 numbers and save the sums into a value and then return those combined values into a data frame where I can do further calculations. Apply requires a function so I decided to do something like this:

```<code>final_results <- cbind(final_results, apply(test, 2, applyFunction(indexOfApply))

applyFunction <- function(indexofApply) {
temp <- c(sum(indexofApply == 1), sum(indexofApply == 2),
sum(indexofApply == 3), sum(indexofApply == 4),
sum(indexofApply == 5), sum(indexofApply == 6), sum(indexofApply == 7))

return(temp)
}
</code>```

I want my result to look something like this:

 My original data frame looks like this
(column names are confidential)

Is there a way to pass the index of the apply function to my own function like I want to do or is there some much easier way to do this? I am new at R and it feels like there should be a better way to do this. Please explain any answers you give so I can learn. Thank you.

答:
You can check the tabulate function.
It will do exactly what your applyFunction can do

For example, if I use the following sample:

```<code>test
   a b c d e
1  1 1 1 7 4
2  6 2 7 7 1
3  1 4 5 3 7
4  3 7 4 7 7
5  2 7 5 1 2
6  1 4 2 1 2
7  1 1 5 2 1
8  3 5 4 2 4
9  6 6 6 3 1
10 4 1 1 5 2
11 6 5 7 1 6
12 1 1 5 4 7
</code>```

Then use sapply function, which is same as apply(x,2,fun):

```<code>result = as.data.frame(sapply(test, tabulate, 7))
</code>```

You can get:

```<code>result
  a b c d e
1 5 4 2 3 3
2 1 1 1 2 3
3 2 0 0 2 0
4 1 2 2 1 2
5 0 2 4 1 0
6 3 1 1 0 1
7 0 2 2 3 3
</code>```

The disadvantage of tabulate is that it can only deal with positive integers. If your category name is not strictly 1 to 7, then you can convert the column into factor and then use table to deal with it. Here is my code:

```<code>result2 <- data.frame(sapply(test, function(x) table(factor(x,levels=1:7))))
</code>```

result2 is same as result, but you can change category names by assigning it to levels

Body:
I am currently trying to loop through my data frame called "test" and get the sum of each of the numbers in each column. ex. sum(test$colname1 = 4) would return 1 because of only one 4 occurrence in the first column. I cannot use count because I have 7 specific numbers I want saved (1-7) even if there were 0 occurrences for a number. Count only returns numbers that have occurred and doesn't show 0 values. My plan is to use the apply function to loop through my columns and do the sum of each of the 7 numbers and save the sums into a value and then return those combined values into a data frame where I can do further calculations. Apply requires a function so I decided to do something like this:

final_results <- cbind(final_results, apply(test, 2, applyFunction(indexOfApply))

applyFunction <- function(indexofApply) {
temp <- c(sum(indexofApply == 1), sum(indexofApply == 2),
sum(indexofApply == 3), sum(indexofApply == 4),
sum(indexofApply == 5), sum(indexofApply == 6), sum(indexofApply == 7))

return(temp)
}

I want my result to look something like this:

 My original data frame looks like this
(column names are confidential)

Is there a way to pass the index of the apply function to my own function like I want to do or is there some much easier way to do this? I am new at R and it feels like there should be a better way to do this. Please explain any answers you give so I can learn. Thank you.

Body:
You can check the tabulate function.
It will do exactly what your applyFunction can do

For example, if I use the following sample:

test
   a b c d e
1  1 1 1 7 4
2  6 2 7 7 1
3  1 4 5 3 7
4  3 7 4 7 7
5  2 7 5 1 2
6  1 4 2 1 2
7  1 1 5 2 1
8  3 5 4 2 4
9  6 6 6 3 1
10 4 1 1 5 2
11 6 5 7 1 6
12 1 1 5 4 7

Then use sapply function, which is same as apply(x,2,fun):

result = as.data.frame(sapply(test, tabulate, 7))

You can get:

result
  a b c d e
1 5 4 2 3 3
2 1 1 1 2 3
3 2 0 0 2 0
4 1 2 2 1 2
5 0 2 4 1 0
6 3 1 1 0 1
7 0 2 2 3 3

The disadvantage of tabulate is that it can only deal with positive integers. If your category name is not strictly 1 to 7, then you can convert the column into factor and then use table to deal with it. Here is my code:

result2 <- data.frame(sapply(test, function(x) table(factor(x,levels=1:7))))

result2 is same as result, but you can change category names by assigning it to levels