问:
Pro-C buffer types compatible with a CLOB
I'm attempting to use a CLOB in Pro-C, but pretty much no matter what I try for a buffer data type, the preprocessor tells me it's not compatible.

The message is

```<code>PCC-S-02428, Buffer type is incompatible with LOB type,
</code>```

and it's on a line that reads:

```<code>EXEC SQL LOB READ :amount FROM :clob into :buffer;
</code>```

This code is my attempt to modify code that works with a BLOB to instead work with a CLOB.  I altered the declaration of the locator from OCIBlobLocator to OCIClobLocator, and then have beat my brains out trying to figure out what I need to declare the buffer as (unsigned char buffer[ BUFFSIZ ] worked for the BLOB).

As it sits right now:

clob is declared as follows:

```<code>OCIClobLocator *clob;
</code>```

and buffer is:

```<code>#define BUFFSIZ 1000000
unsigned char buffer[ BUFFSIZ ];
</code>```

I've tried char, int, double, long. ulong_varchar, short, utext, uvarchar, varchar in various combinations of pointers (e.g.,, short *buffer), sized array declarations, straight declarations (e.g., uvarchar buffer), and both signed and unsigned.  For all cases where the buffer declaration is itself legal, the READ INTO statement fails to compile with this message.

Actually entering the text of the message into google leads me to an Oracle page that simply restates the message (rather than being so helpful as to actually list compatible types).  The Oracle tutorials all focus on BLOBs, no example is of a CLOB.

The closest thing I found to an answer was here on Stack Overflow (kudos!).  This question: Selecting CLOB in Oracle using C and embedded SQL

was from someone else having the same issue.  He claims to have solved it by removing the CHAR_SET=STRING parameter from his command line invocation of PRO-C.  The problem is, Pro-C here doesn't even recognize that such an option exists...so I can't remove it, because I'm not using it.  (I tried to point this out there, not realizing I was misusing this forum and it was (justly) deleted...my apologies to whomever had to clean up my mess.)

My version of Pro*C/C++ is 11.2.0.1.0

The options I am running are

```<code>PARSE=NONE CODE=CPP CPP_SUFFIX=cpp MODE=ORACLE LINES=YES THREADS=YES
</code>```

And as I mentioned earlier, the exact same thing (except for declaring an OCIBlobLocator and renaming various variables from blob_something to clob_something does compile and function.

I unfortunately cannot post the code because it's on an airgapped system and permission for a file transfer would take a writ from a much higher power than me.

答:
Found out what the problem was:

I had done a

EXEC SQL VAR buffer IS RAW( BUFFSIZ );

which is fine when buffer is for interfacing to a blob, but not for a clob.  Apparently it doesn't matter (much) what you declare the buffer as, but you don't want to make it RAW with this call.

Incidentally if you declare "buffer" in one method dealing with a BLOB, it's still in Pro-C scope in subsequent methods, including the IS RAW call--so I had to use a different name in the subsequent method I wrote for dealing with CLOBs.

Body:
I'm attempting to use a CLOB in Pro-C, but pretty much no matter what I try for a buffer data type, the preprocessor tells me it's not compatible.

The message is

PCC-S-02428, Buffer type is incompatible with LOB type,

and it's on a line that reads:

EXEC SQL LOB READ :amount FROM :clob into :buffer;

This code is my attempt to modify code that works with a BLOB to instead work with a CLOB.  I altered the declaration of the locator from OCIBlobLocator to OCIClobLocator, and then have beat my brains out trying to figure out what I need to declare the buffer as (unsigned char buffer[ BUFFSIZ ] worked for the BLOB).

As it sits right now:

clob is declared as follows:

OCIClobLocator *clob;

and buffer is:

#define BUFFSIZ 1000000
unsigned char buffer[ BUFFSIZ ];

I've tried char, int, double, long. ulong_varchar, short, utext, uvarchar, varchar in various combinations of pointers (e.g.,, short *buffer), sized array declarations, straight declarations (e.g., uvarchar buffer), and both signed and unsigned.  For all cases where the buffer declaration is itself legal, the READ INTO statement fails to compile with this message.

Actually entering the text of the message into google leads me to an Oracle page that simply restates the message (rather than being so helpful as to actually list compatible types).  The Oracle tutorials all focus on BLOBs, no example is of a CLOB.

The closest thing I found to an answer was here on Stack Overflow (kudos!).  This question: Selecting CLOB in Oracle using C and embedded SQL

was from someone else having the same issue.  He claims to have solved it by removing the CHAR_SET=STRING parameter from his command line invocation of PRO-C.  The problem is, Pro-C here doesn't even recognize that such an option exists...so I can't remove it, because I'm not using it.  (I tried to point this out there, not realizing I was misusing this forum and it was (justly) deleted...my apologies to whomever had to clean up my mess.)

My version of Pro*C/C++ is 11.2.0.1.0

The options I am running are

PARSE=NONE CODE=CPP CPP_SUFFIX=cpp MODE=ORACLE LINES=YES THREADS=YES

And as I mentioned earlier, the exact same thing (except for declaring an OCIBlobLocator and renaming various variables from blob_something to clob_something does compile and function.

I unfortunately cannot post the code because it's on an airgapped system and permission for a file transfer would take a writ from a much higher power than me.


来源: stackexchange

问:
Error connecting to VPN within Docker container
I have an Ubuntu docker container with openvpn installed, and a config.ovpn file.

I try doing:
openvpn --config config.ovpn

and get the following error:

ERROR: Cannot ioctl TUNSETIFF tun: Operation not permitted (errno=1)

Some googling seems to suggest that this is because of not running with sudo but does root not already have sudo permissions? (For what it's worth - running sudo openvpn makes no difference).

答: Adding --privileged flag to docker run solved the problem.

ContentLicense: CC BY-SA 3.0


问:
Node.Js in Erlang style?
I am a complete noob when it comes to both Node.Js and Erlang.
But wouldn't it be possible to build a Node.js app that emulates Erlang behavior?

e.g. you pass json messages across an distributed node.js server park and even pass new code to those servers w/o going offline, just like erlang.

If you have a message handler callback that is activated when a message is received, then this message handler could check if the message is a code update message and thus replace itself(the current handler) with the new code.

So it should be possible to have Node.Js servers with no downtime for code updates w/o too much fuss, right?

答:
I assume With script module you could execute javascript without reloading the server.

supervisor

A little supervisor script for nodejs.
  It runs your program, and watches for
  code changes, so you can have hot-code
  reloading-ish behavior, without
  worrying about memory leaks and making
  sure you clean up all the inter-module
  references, and without a whole new
  require system.

But then again it will reload(very short time offline) when it detects file changes.

ContentLicense: CC BY-SA 2.5

Title: Node.Js in Erlang style?


问:
Command line to remove an environment variable from the OS level configuration
Windows has the setx command:

```<code>Description:
    Creates or modifies environment variables in the user or system
    environment.
</code>```

So you can set a variable like this:

```<code>setx FOOBAR 1
</code>```

And you can clear the value like this:

```<code>setx FOOBAR ""
</code>```

However, the variable does not get removed. It stays in the registry:

So how would you actually remove the variable?

答:
```<code>setx FOOBAR ""
</code>```

just causes the value of FOOBAR to be a null string. (Although, it shows with the set command with the "" so maybe double-quotes is the string.)

I used:

```<code>set FOOBAR=
</code>```

and then FOOBAR was no longer listed in the set command. (Log-off was not required.)

Windows 7 32 bit, using the command prompt, non-administrator is what I used. (Not cmd or Windows + R, which might be different.)

BTW, I did not see the variable I created anywhere in the registry after I created it. I'm using RegEdit not as administrator.

OwnerDisplayName: anon

ContentLicense: CC BY-SA 4.0

Body:
Windows has the setx command:

Description:
    Creates or modifies environment variables in the user or system
    environment.

So you can set a variable like this:

setx FOOBAR 1

And you can clear the value like this:

setx FOOBAR ""

However, the variable does not get removed. It stays in the registry:

So how would you actually remove the variable?

Body:
setx FOOBAR ""

just causes the value of FOOBAR to be a null string. (Although, it shows with the set command with the "" so maybe double-quotes is the string.)

I used:

set FOOBAR=

and then FOOBAR was no longer listed in the set command. (Log-off was not required.)

Windows 7 32 bit, using the command prompt, non-administrator is what I used. (Not cmd or Windows + R, which might be different.)

BTW, I did not see the variable I created anywhere in the registry after I created it. I'm using RegEdit not as administrator.


问:
ideas on quadrangle/rectangle detection using convolutional neural networks
I'v been trying to do quadrangle detection and localization for weeks, my goal is to have a robust way of getting the 4 points of an quadrangle(rectangle), so I can apply projective transform to an Image then attach it to the source image. I have try the classic opencv contour method, and also using hough transform to find lines then calculate intersections, those two methods is unusable when apply it to real life images.

So I turn to CNN for help, but currently i haven't find any one try to use CNN to solve this simple problem.

My first attempt is to use state-of-art object detection and localization methods to get quadrangle's bounding box so i can narrow the search of 4 points, then use image processing & computer vision methods to further the search for 4 points. but after trying YOLOv2 and Faster-RCNN, the prediction accuracy is not ideal.

So I'm wondering if there is any idea i can do this end to end, training and feedforward all using a single neural network. it also must be able to deal with occlusion reasonably well.

Currently my idea is to remove the fc-layers and make a huge activation map that has the same width and height as the first input layer(eg. 448x448) then optimize the 4 most highly activated areas, using argmax to get the position. but this method only works for one quadrangle it doesn't work well with corner occlusions as well.

I'll be appreciated if anyone can provide any suggestions. Thanks a lot!

答:
You are absolutely right about the first methods you mentioned. Hough transform like methods are old and not useful for images in the wild. And of course, computer vision field turned its face to object detection and recognition with rise of deep learning.

However, there is a very nice discussion came up recently.
Have we forgotten about Geometry in Computer Vision?

My suggestion would be contour detection and then apply Hough transform(use state of the art) methods to detect rectangles you want, about  the occlusion, you can set parameters for Hough transform to be more forgiving for missing edge pixels with parameters.
 You can for example check most recent contour detection methods as in recent CVPR paper.


问:
From WPF Control to Silverlight Control
we have biuld a complex custom control for WPF.
Now we are going to port our control to Silverlight.

Me and my collaborator, never work with silverlight! :)

Is there some best practice to follow to make a porting activity from WPF to Silverlight?

答:
I find the next post as nice to be read: (2 parts)

Porting from WPF to Silverlight: The Missing Pieces, Part 1

Porting from WPF to Silverlight: The Missing Pieces, Part 2

Title: From WPF Control to Silverlight Control


问:
Return Value After Filter method is not filtering correctly
Been Trying to filter out the thumbnail values that equal to 'self' or default, but its still not working , is there any other way other than filter ?</p>

```<code> $(document).ready(function(){
   $('button').on('click', function(event){
    event.preventDefault();
    $('#result').empty();
    var userInput = $('input').val()
        $.ajax({
        method:"GET",
        url:"https://www.reddit.com/r/" + userInput + ".json?jsonp",
        success:success
    })
    })

function success(response){
    var result ="";
    $.each(response, function(index, value){
        var list = response.data.children
        $.each(list.filter(function(item){
            return item.data.thumbnail !== "self" || "default"
        }),
            function(index,value){
                var thumbnail = value.data.thumbnail
                var author = value.data.author
                result += "<li>" +
                            "<img src='" + thumbnail + "' class='reddit-image'/>"

                result += "<p class='reddit-author'>" + author + "</p>"
                result += "</li>"
                $('#result').html(result)
            })
        })
    }
})
</code>```

答:
Your return statement says if the value isn't 'self' return the string 'default'

The string 'default' is truthy

You need to compare the variable to both strings

```<code> return item.data.thumbnail !== "self" || item.data.thumbnail !== "default"
</code>```

Body:
Been Trying to filter out the thumbnail values that equal to 'self' or default, but its still not working , is there any other way other than filter ?

 $(document).ready(function(){
   $('button').on('click', function(event){
    event.preventDefault();
    $('#result').empty();
    var userInput = $('input').val()
        $.ajax({
        method:"GET",
        url:"https://www.reddit.com/r/" + userInput + ".json?jsonp",
        success:success
    })
    })

function success(response){
    var result ="";
    $.each(response, function(index, value){
        var list = response.data.children
        $.each(list.filter(function(item){
            return item.data.thumbnail !== "self" || "default"
        }),
            function(index,value){
                var thumbnail = value.data.thumbnail
                var author = value.data.author
                result += "
" +
                            ""

                result += "
" + author + "
"
                result += "
"
                $('#result').html(result)
            })
        })
    }
})

Body:
Your return statement says if the value isn't 'self' return the string 'default'

The string 'default' is truthy

You need to compare the variable to both strings

 return item.data.thumbnail !== "self" || item.data.thumbnail !== "default"


问:
How to ssr to replace all string in kdb?
table dd

```<code>dd:([]a:("account=abcde;cash=123";"account=abc;cash=345");1 2)
</code>```

result:

```<code>"account=abcde;cash=123"    1
"account=abc;cash=345"      2
</code>```

I want to replace everything in account:
so the result should be

```<code>"replace;cash=123"  1
"replace;cash=345"  2
</code>```

I tried this

```<code>update ssr[;"account=* ;";""] each a from dd
</code>```

but it didn't work.

答:
You can also try the following if you want to explicitly use ssr:

```<code>update {ssr[first "=" vs x;"account";"replace",";",last ";" vs x]} each a from dd

a                  x
--------------------
"replace;cash=123" 1
"replace;cash=345" 2
</code>```

Body:
table dd

dd:([]a:("account=abcde;cash=123";"account=abc;cash=345");1 2)

result:

"account=abcde;cash=123"    1
"account=abc;cash=345"      2

I want to replace everything in account:
so the result should be

"replace;cash=123"  1
"replace;cash=345"  2

I tried this

update ssr[;"account=* ;";""] each a from dd

but it didn't work.

Body:
You can also try the following if you want to explicitly use ssr:

update {ssr[first "=" vs x;"account";"replace",";",last ";" vs x]} each a from dd

a                  x
--------------------
"replace;cash=123" 1
"replace;cash=345" 2


问:
Can I remove the default SSH key of an Elastic Beanstalk instance?
I'm looking to lock down security on my AWS Elastic Beanstalk instances. I actually manage my beanstalk instances with Chef, and I use that to deploy individual developer SSH keys to the instances.

I no longer need the key that beanstalk put on the server. Can I safely remove it from the authorized keys file? I can't find any documentation from Amazon about whether this will interfere with deployments or changing out Environment Properties.

答:
It seems that it is safe to remove the key that beanstalk puts on the instance. For testing, I went ahead and removed it on some test environments: one is a NodeJS beanstalk app and another is a Tomcat/Java app.

From my very first login, I ran lastlog to see who's logged in. I've truncated the list to isolate the relevant ones:

```<code>$ lastlog
Username         Port     From             Latest
root             pts/0                     Mon Jun  5 16:27:42 -0400 2017
ec2-user                                   **Never logged in**
xray                                       Thu May 18 03:10:54 -0400 2017
apache                                     **Never logged in**
healthd                                    Thu May 18 03:11:02 -0400 2017
nodejs                                     Thu May 18 03:17:18 -0400 2017
my-custom-user   pts/0    10.10.x.x        Mon Jun  5 16:27:39 -0400 2017
</code>```

I updated an Environment Properties, and even deployed a new version. That ec2-user still shows as **Never logged in**

It looks like Beanstalk's automation is using a nodejs or tomcat user, depending on the beanstalk app type, for it's tasks. Here is what I see in /var/log/secure:

```<code>Jun  5 16:53:40 node-name su: pam_unix(su:session): session closed for user nodejs
Jun  5 16:53:54 node-name su: pam_unix(su:session): session opened for user nodejs by (uid=0)
Jun  5 16:53:54 node-name su: pam_lastlog(su:session): unable to open /var/log/btmp: No such file or directory
</code>```

Body:
It seems that it is safe to remove the key that beanstalk puts on the instance. For testing, I went ahead and removed it on some test environments: one is a NodeJS beanstalk app and another is a Tomcat/Java app.

From my very first login, I ran lastlog to see who's logged in. I've truncated the list to isolate the relevant ones:

$ lastlog
Username         Port     From             Latest
root             pts/0                     Mon Jun  5 16:27:42 -0400 2017
ec2-user                                   **Never logged in**
xray                                       Thu May 18 03:10:54 -0400 2017
apache                                     **Never logged in**
healthd                                    Thu May 18 03:11:02 -0400 2017
nodejs                                     Thu May 18 03:17:18 -0400 2017
my-custom-user   pts/0    10.10.x.x        Mon Jun  5 16:27:39 -0400 2017

I updated an Environment Properties, and even deployed a new version. That ec2-user still shows as **Never logged in**

It looks like Beanstalk's automation is using a nodejs or tomcat user, depending on the beanstalk app type, for it's tasks. Here is what I see in /var/log/secure:

Jun  5 16:53:40 node-name su: pam_unix(su:session): session closed for user nodejs
Jun  5 16:53:54 node-name su: pam_unix(su:session): session opened for user nodejs by (uid=0)
Jun  5 16:53:54 node-name su: pam_lastlog(su:session): unable to open /var/log/btmp: No such file or directory


问:
Getting the required output in SQL server
I have an issue in getting the required output for below scenario.

```<code>name | provider  | visit_dt    | rd | rn
 A   | 100000    | 06/05/'17   | 1  |  1
 A   | 100001    | 06/04/'17   | 1  |  0
 A   | 100001    | 06/03/'17   | 1  |  0
 B   | 100000    | 06/05/'17   | 1  |  0
 B   | 100001    | 06/05/'17   | 1  |  1
 C   | 100000    | 06/05/'17   | 1  |  0
 C   | 100001    | 06/04/'17   | 1  |  0
 C   | 100001    | 06/03/'17   | 1  |  1
 D   | 100001    | 06/05/'17   | 1  |  0
 D   | 100001    | 06/04/'17   | 1  |  0
</code>```

There are 4 different scenarios here:

If the most recent has rd = 1 and rn = 1 then pull the most recent visit(person A)

Get the most recent visit for each person with rn = 1 (person C)

If rn = 0, then pull the most recent RD (person D)

If both the visits for a person are with different providers on the same date, then pull both the providers irrespective of rd and rn values (person B)

So the expected output should be as below.

```<code>name | provider  | visit_dt    | rd | rn
A    | 100000    | 06/05/'17   | 1  |  1
B    | 100000    | 06/05/'17   | 1  |  0
B    | 100001    | 06/05/'17   | 1  |  1
C    | 100001    | 06/03/'17   | 1  |  1
D    | 100001    | 06/05/'17   | 1  |  0
</code>```

It would be great if anyone could help me to solve this issue.

Any suggestion would be appreciable.

Thank you in advance.

答:
Looks like you have some contradictory conditions here is my approach:</p>

```<code>Select * from (
    Select *, Con1 = Row_Number() over(Partition by [name] order by visit_dt desc) ,
            Con2 = Row_Number() over(partition by [name],[rn] order by visit_dt desc)
    from yourVisits
    ) a
    Where  (a.Con1 = 1 and rd =1 and rn = 1)
        or (a.Con2 = 1 and rn=1)
        or (a.Con2 = 1 and rn=0)
</code>```

Body:
I have an issue in getting the required output for below scenario.

name | provider  | visit_dt    | rd | rn
 A   | 100000    | 06/05/'17   | 1  |  1
 A   | 100001    | 06/04/'17   | 1  |  0
 A   | 100001    | 06/03/'17   | 1  |  0
 B   | 100000    | 06/05/'17   | 1  |  0
 B   | 100001    | 06/05/'17   | 1  |  1
 C   | 100000    | 06/05/'17   | 1  |  0
 C   | 100001    | 06/04/'17   | 1  |  0
 C   | 100001    | 06/03/'17   | 1  |  1
 D   | 100001    | 06/05/'17   | 1  |  0
 D   | 100001    | 06/04/'17   | 1  |  0

There are 4 different scenarios here:

If the most recent has rd = 1 and rn = 1 then pull the most recent visit(person A)

Get the most recent visit for each person with rn = 1 (person C)

If rn = 0, then pull the most recent RD (person D)

If both the visits for a person are with different providers on the same date, then pull both the providers irrespective of rd and rn values (person B)

So the expected output should be as below.

name | provider  | visit_dt    | rd | rn
A    | 100000    | 06/05/'17   | 1  |  1
B    | 100000    | 06/05/'17   | 1  |  0
B    | 100001    | 06/05/'17   | 1  |  1
C    | 100001    | 06/03/'17   | 1  |  1
D    | 100001    | 06/05/'17   | 1  |  0

It would be great if anyone could help me to solve this issue.

Any suggestion would be appreciable.

Thank you in advance.

Body:
Looks like you have some contradictory conditions here is my approach:

Select * from (
    Select *, Con1 = Row_Number() over(Partition by [name] order by visit_dt desc) ,
            Con2 = Row_Number() over(partition by [name],[rn] order by visit_dt desc)
    from yourVisits
    ) a
    Where  (a.Con1 = 1 and rd =1 and rn = 1)
        or (a.Con2 = 1 and rn=1)
        or (a.Con2 = 1 and rn=0)


问:
Using C FILE stream in C sockets programming
Am back with a question on using C File stream in sockets programming. I was reading about it and saw mixed reviews - some people say it's not reliable (ie leaky abstraction?).

Has any one got a view about using C File stream in sockets programming?

答:
Yes. Don't.

The TCP and UDP protocols have too many semantics to be easily mapped to your usual file stream APIs. That's not to say it's impossible or even difficult, but there are likely to be lots and lots of gotchas and edge cases that will give you wildly unpredictable behaviour. I also cannot think off the top of my head of any applications where you might want to treat a socket as an ordinary file.

At the end of the day, once you've dealt with binding and listening and accepting, none of which you can do with C File streams, and wrapped the resultant file descripter in a File stream type, all you are going to do is use fread() and fwrite(), maybe fgetc(), so you may as well leave it as an ordinary file descriptor and use recv(), and send() and save yourself the hassle of wrapping. You may save yourself the hassle of dealing with buffering, but having control of the buffering allows you to tune your buffer to the application's requirements and save yourself some network overhead and speed.


问:
onMeasure call to getMeasuredWidth or Height return 0 for children
I'm trying to dynamically add items to the my CustomView and make the final height the size of all the children added together. The only problem is the child.getMeasuredHeight or child.getMeasuredWidth always returns a value of 0 during run time. When I'm debugging it will randomly 1 out of 10 times seem to actually contain the data I was actually expecting with a value of 192. If I also hard code a value into the layout parameter instead of using WRAP_CONTENT it still shows a value of 0. Is there something that I'm doing wrong.

xml file

```<code><CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_marginTop="80dp"
    android:orientation="vertical"
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:id="@+id/custom_layout"
    android:background="@drawable/custom_shape"/>
</CustomLayout>
</code>```

Here's a part of my CustomLayout.java class

```<code>public class CustomLayout extends LinearLayout {

public CustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CustomLayout(Context context) {
    super(context);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();

    int maxHeight = 0;
    int maxWidth = 0;

    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    for(int i=0; i <count; i++) {
        final View child = getChildAt(i);
        if(child.getVisibility() != GONE) {

            maxHeight +=  child.getMeasuredHeight();

        }
    }

    setMeasuredDimension(widthSize,maxHeight);
}
</code>```

In a part of my main activity

```<code> Button b = new Button(this);
        b.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        b.setText("Sample Test");
        b.setTextSize(14);
        mCustomView.addView(b);
</code>```

答:
You will need to ask each child of the ViewGroup to measure itself before you can access its dimensions. This is done with a call to [measureChild](https://developer.android.coma/reference/android/view/ViewGroup.html#measureChild(android.view.View, int, int)) or [measureChildWithMargins](https://developer.android.coma/reference/android/view/ViewGroup.html#measureChild(android.view.View, int, int)).

Take a look at the developer guide for ViewGroup to see how the child measurements are obtained.

```<code>// Iterate through all children, measuring them and computing our dimensions
// from their size.
for (int i = 0; i < count; i++) {
    final View child = getChildAt(i);
    if (child.getVisibility() != GONE) {
        // Measure the child.
        measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

        // Update our size information based on the layout params.  Children
        // that asked to be positioned on the left or right go in those gutters.
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (lp.position == LayoutParams.POSITION_LEFT) {
            mLeftWidth += Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
        } else if (lp.position == LayoutParams.POSITION_RIGHT) {
            mRightWidth += Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
        } else {
            maxWidth = Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
        }
        maxHeight = Math.max(maxHeight,
                child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
        childState = combineMeasuredStates(childState, child.getMeasuredState());
    }
}
</code>```

Body:
I'm trying to dynamically add items to the my CustomView and make the final height the size of all the children added together. The only problem is the child.getMeasuredHeight or child.getMeasuredWidth always returns a value of 0 during run time. When I'm debugging it will randomly 1 out of 10 times seem to actually contain the data I was actually expecting with a value of 192. If I also hard code a value into the layout parameter instead of using WRAP_CONTENT it still shows a value of 0. Is there something that I'm doing wrong.

xml file

<CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_marginTop="80dp"
    android:orientation="vertical"
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:id="@+id/custom_layout"
    android:background="@drawable/custom_shape"/>
</CustomLayout>

Here's a part of my CustomLayout.java class

public class CustomLayout extends LinearLayout {

public CustomLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CustomLayout(Context context) {
    super(context);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int count = getChildCount();

    int maxHeight = 0;
    int maxWidth = 0;

    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    for(int i=0; i <count; i++) {
        final View child = getChildAt(i);
        if(child.getVisibility() != GONE) {

            maxHeight +=  child.getMeasuredHeight();

        }
    }

    setMeasuredDimension(widthSize,maxHeight);
}

In a part of my main activity

 Button b = new Button(this);
        b.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        b.setText("Sample Test");
        b.setTextSize(14);
        mCustomView.addView(b);

Body:
You will need to ask each child of the ViewGroup to measure itself before you can access its dimensions. This is done with a call to [measureChild](https://developer.android.coma/reference/android/view/ViewGroup.html#measureChild(android.view.View, int, int)) or [measureChildWithMargins](https://developer.android.coma/reference/android/view/ViewGroup.html#measureChild(android.view.View, int, int)).

Take a look at the developer guide for ViewGroup to see how the child measurements are obtained.

// Iterate through all children, measuring them and computing our dimensions
// from their size.
for (int i = 0; i < count; i++) {
    final View child = getChildAt(i);
    if (child.getVisibility() != GONE) {
        // Measure the child.
        measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

        // Update our size information based on the layout params.  Children
        // that asked to be positioned on the left or right go in those gutters.
        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        if (lp.position == LayoutParams.POSITION_LEFT) {
            mLeftWidth += Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
        } else if (lp.position == LayoutParams.POSITION_RIGHT) {
            mRightWidth += Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
        } else {
            maxWidth = Math.max(maxWidth,
                    child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
        }
        maxHeight = Math.max(maxHeight,
                child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
        childState = combineMeasuredStates(childState, child.getMeasuredState());
    }
}


问:
How to scale proportionally this flexbox tiles grid
I'm preparing the hero element for my website using some tiles with flexbox. The hero element has some variants, to the configuration is flexible: nesting the tiles I can obtain the variant I need. This is one variant and I cannot understand why when I resize the browser the image on the right, the vertical tile, lose the proportion. How can I scale the entire grid proportionally?
And btw why I can remove the blue gap between the elements? It's something related to the height of the righe tile.

Here is the HTML

```<code><div class="cover">
  <div class="tile is-ancestor">
    <div class="tile is-vertical is-2">
      <div class="tile is-child">
        <img src="https://s1.postimg.org/ga0s55bxr/cover1.jpg" />
      </div>
      <div class="tile is-child">
        <img src="https://s8.postimg.org/xnsnrs4x1/cover2.jpg" />
      </div>
    </div>
    <div class="tile">
      <img src="https://s1.postimg.org/n35qf5s4v/cover3.jpg" />
    </div>
  </div>
</div>
</code>```

And here the compiled css

```<code>.cover {
  max-width: 1080px;
  background-color: blue;
  margin: 0;
}
@media screen and (min-width: 1351px) {
  .cover {
    max-width: 1350px;
    margin: 0 -135px;
  }
}
.cover .tile {
  align-items: stretch;
  display: block;
  flex-basis: 0;
  flex-grow: 1;
  flex-shrink: 1;
  min-height: min-content;
}
.cover .tile.is-child {
  margin: 0 !important;
}
.cover .tile.is-vertical {
  flex-direction: column;
}
@media screen and (min-width: 769px) {
  .cover .tile:not(.is-child) {
    display: flex;
  }
  .cover .tile.is-1 {
    flex: none;
    width: 33.33333%;
  }
  .cover .tile.is-2 {
    flex: none;
    width: 66.66667%;
  }
  .cover .tile.is-3 {
    flex: none;
    width: 100%;
  }
}
</code>```

I create also a codepen

答:
THis is how i would make it all happen..

You simply have to define the widths of the IMG and make sure to change the flex direction.

Everything can be flexboxed..

In your case it is the img so you need to flex one above from the img

```<code>    .container {
    display:flex;

    }

    .container_left {display: flex;
                        flex: 1;
                        flex-direction:column}

    .left {
        flex:2;
        display: flex;
        align-items: stretch;
            }

.left img {max-width: 100%}
.right img {max-width: 100%}

    .right {
        flex:1;
    }

@media (max-width:768px) {
    .container{
        flex-direction: column

    }
}
</code>```

The html i used.. You can apply it to your code..

```<code>    <div class="container">

    <div class="container_left">
            <div class="left"><img src="https://s1.postimg.org/ga0s55bxr/cover1.jpg" /></div>
            <div class="left"> <img src="https://s8.postimg.org/xnsnrs4x1/cover2.jpg" /></div>
        </div>

        <div class="right"> <img src="https://s1.postimg.org/n35qf5s4v/cover3.jpg" /></div>

    </div>
</code>```

Here it is on codepen for you

https://codepen.io/maffas/pen/zzxMxO

Body:
I'm preparing the hero element for my website using some tiles with flexbox. The hero element has some variants, to the configuration is flexible: nesting the tiles I can obtain the variant I need. This is one variant and I cannot understand why when I resize the browser the image on the right, the vertical tile, lose the proportion. How can I scale the entire grid proportionally?
And btw why I can remove the blue gap between the elements? It's something related to the height of the righe tile.

Here is the HTML

And here the compiled css

.cover {
  max-width: 1080px;
  background-color: blue;
  margin: 0;
}
@media screen and (min-width: 1351px) {
  .cover {
    max-width: 1350px;
    margin: 0 -135px;
  }
}
.cover .tile {
  align-items: stretch;
  display: block;
  flex-basis: 0;
  flex-grow: 1;
  flex-shrink: 1;
  min-height: min-content;
}
.cover .tile.is-child {
  margin: 0 !important;
}
.cover .tile.is-vertical {
  flex-direction: column;
}
@media screen and (min-width: 769px) {
  .cover .tile:not(.is-child) {
    display: flex;
  }
  .cover .tile.is-1 {
    flex: none;
    width: 33.33333%;
  }
  .cover .tile.is-2 {
    flex: none;
    width: 66.66667%;
  }
  .cover .tile.is-3 {
    flex: none;
    width: 100%;
  }
}

I create also a codepen

Body:
THis is how i would make it all happen..

You simply have to define the widths of the IMG and make sure to change the flex direction.

Everything can be flexboxed..

In your case it is the img so you need to flex one above from the img

    .container {
    display:flex;

    }

    .container_left {display: flex;
                        flex: 1;
                        flex-direction:column}

    .left {
        flex:2;
        display: flex;
        align-items: stretch;
            }

.left img {max-width: 100%}
.right img {max-width: 100%}

    .right {
        flex:1;
    }

@media (max-width:768px) {
    .container{
        flex-direction: column

    }
}

The html i used.. You can apply it to your code..

    <div class="container">

    <div class="container_left">
            <div class="left"><img src="https://s1.postimg.org/ga0s55bxr/cover1.jpg" /></div>
            <div class="left"> <img src="https://s8.postimg.org/xnsnrs4x1/cover2.jpg" /></div>
        </div>

        <div class="right"> <img src="https://s1.postimg.org/n35qf5s4v/cover3.jpg" /></div>

    </div>

Here it is on codepen for you

https://codepen.io/maffas/pen/zzxMxO


问:
Yii2 translating findBySql query to QueryBuilder query
I have the following query using findbysql:

```<code>$query = Users::findBySql('select a.user_id, a.last_name,a.first_name, a.emp_id, ar.role_id from auth_users a, auth_user_roles AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
                where AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
                AND D.DEPT_GROUP_ID = :dept_group_id AND (ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)
                UNION
                SELECT DISTINCT a.user_id, a.last_name, a.first_name, a.emp_id, NULL AS role_id FROM auth_users a, AUTH_USER_ROLES AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
                WHERE AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
                AND D.DEPT_GROUP_ID = :dept_group_id AND
                AR.ACCESS_END_DATE < SYSDATE AND AR.USER_ID NOT IN (select USER_ID from auth_user_roles where ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)', [':dept_group_id' => $dept_group_id ]);
</code>```

This query does exactly what I want it to, but the problem is when I try to put it into a gridview it does not sort. According to Sort and search column when I'm querying with findbysql in yii2 it seems like I need to use query builder instead.

So I was trying to do that with the first part of my query (before the union), and it looks like so:

```<code>    $query1 = (new \yii\db\Query())
        ->select(['user_id', 'last_name', 'first_name', 'emp_id'])
        ->from('AUTH_USERS');
    $query2 = (new \yii\db\Query())
        ->select('USER_ID')
        ->from('AUTH_USER_ROLES')
        ->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
    $query = $query1->innerJoin('AUTH_USER_DEPTS', 'AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id')->innerJoin('DEPARTMENTS', 'AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id');
   $query->innerJoin('AUTH_USER_ROLES', 'AUTH_USER_ROLES.USER_ID = auth_users.USER_ID')->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
</code>```

However, my query comes out like this in yii and apparently oracle is not accepting the double quotes around the column names:

```<code>SELECT "user_id", "last_name", "first_name", "emp_id" FROM "AUTH_USERS"
INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id
INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id
INNER JOIN "AUTH_USER_ROLES" ON AUTH_USER_ROLES.USER_ID = auth_users.USER_ID
WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL
</code>```

I know the query might be incorrect here already but I cant even get the double quotes to go away. Tried defining the select statements multiple ways suggested by the yii docs already with no success:

```<code>select(['user_id', 'last_name', 'first_name', 'emp_id'])
select('user_id', 'last_name', 'first_name', 'emp_id')
select("user_id, last_name,first_name,emp_id")
</code>```

I have also tried joining the queries like this from the docs: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html

```<code>$query = $query1->innerJoin(['u' => $query2], 'u.user_id = user_id');
</code>```

but it also complains that it doesnèt recognize u and the query instead comes out like so in yii:

```<code>SELECT COUNT(*) FROM "AUTH_USERS" INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id INNER JOIN (SELECT "USER_ID" FROM "AUTH_USER_ROLES" WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL) "u" ON u.user_id = auth_users.user_id
</code>```

At this point im just looking for the easiest way to build this query (whether it be using querybuilder or some other way) so that I can pass the query to my gridview and sort it.

答:
I would recommend you first create all the data models you need from the tables you need for the query, using Gii it should be easy and it even creates the relationships you will need.

After that, you can do something like the following:

```<code>$query = Users::find()
    ->joinWith('theRelation1Name')
    ->joinWith('theRelation2Name')
    ->joinWith('theRelation3Name')
    ...
</code>```

This way you don't need to give tables aliases or add the conditions needed for the relations to work.

Body:
I have the following query using findbysql:

$query = Users::findBySql('select a.user_id, a.last_name,a.first_name, a.emp_id, ar.role_id from auth_users a, auth_user_roles AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
                where AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
                AND D.DEPT_GROUP_ID = :dept_group_id AND (ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)
                UNION
                SELECT DISTINCT a.user_id, a.last_name, a.first_name, a.emp_id, NULL AS role_id FROM auth_users a, AUTH_USER_ROLES AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
                WHERE AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
                AND D.DEPT_GROUP_ID = :dept_group_id AND
                AR.ACCESS_END_DATE < SYSDATE AND AR.USER_ID NOT IN (select USER_ID from auth_user_roles where ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)', [':dept_group_id' => $dept_group_id ]);

This query does exactly what I want it to, but the problem is when I try to put it into a gridview it does not sort. According to Sort and search column when I'm querying with findbysql in yii2 it seems like I need to use query builder instead.

So I was trying to do that with the first part of my query (before the union), and it looks like so:

    $query1 = (new \yii\db\Query())
        ->select(['user_id', 'last_name', 'first_name', 'emp_id'])
        ->from('AUTH_USERS');
    $query2 = (new \yii\db\Query())
        ->select('USER_ID')
        ->from('AUTH_USER_ROLES')
        ->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
    $query = $query1->innerJoin('AUTH_USER_DEPTS', 'AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id')->innerJoin('DEPARTMENTS', 'AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id');
   $query->innerJoin('AUTH_USER_ROLES', 'AUTH_USER_ROLES.USER_ID = auth_users.USER_ID')->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');

However, my query comes out like this in yii and apparently oracle is not accepting the double quotes around the column names:

SELECT "user_id", "last_name", "first_name", "emp_id" FROM "AUTH_USERS"
INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id
INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id
INNER JOIN "AUTH_USER_ROLES" ON AUTH_USER_ROLES.USER_ID = auth_users.USER_ID
WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL

I know the query might be incorrect here already but I cant even get the double quotes to go away. Tried defining the select statements multiple ways suggested by the yii docs already with no success:

select(['user_id', 'last_name', 'first_name', 'emp_id'])
select('user_id', 'last_name', 'first_name', 'emp_id')
select("user_id, last_name,first_name,emp_id")

I have also tried joining the queries like this from the docs: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html

$query = $query1->innerJoin(['u' => $query2], 'u.user_id = user_id');

but it also complains that it doesnèt recognize u and the query instead comes out like so in yii:

SELECT COUNT(*) FROM "AUTH_USERS" INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id INNER JOIN (SELECT "USER_ID" FROM "AUTH_USER_ROLES" WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL) "u" ON u.user_id = auth_users.user_id

At this point im just looking for the easiest way to build this query (whether it be using querybuilder or some other way) so that I can pass the query to my gridview and sort it.

Body:
I would recommend you first create all the data models you need from the tables you need for the query, using Gii it should be easy and it even creates the relationships you will need.

After that, you can do something like the following:

$query = Users::find()
    ->joinWith('theRelation1Name')
    ->joinWith('theRelation2Name')
    ->joinWith('theRelation3Name')
    ...

This way you don't need to give tables aliases or add the conditions needed for the relations to work.


问:
AWS Device Farm send requests to server
I struggle with an issue for a few days/weeks now and decided to ask the community help.
I use AWS device farm to run my automation tests. For the test framework I use Appium + Python.
The app tested has mobile native clients and a web app. I'm using the requests library from Python to send requests to the web app in order to find out if the info sent from the mobile clients is ok.

On local environment everything works. But on AWS Host I receive the following error when r = session.get(self.url) is executed:

ConnectTimeout: HTTPConnectionPool(host='my_adress', port=myPort): Max
  retries exceeded with url: / (Caused by
  ConnectTimeoutError(, 'Connection to my address timed out.
  (connect timeout=100)'))

More info:
The server is running on another AWS Host inside a private network, but with public subnet available.

Any ideas about how to fix this?

答:
I work for the AWS Device Farm team.

You mentioned that your expected Appium server is on another AWS host. Assuming you did not mean AWS Device Farm instance to which the device is connected when you said AWS host, this will be a case of VPC support. In this case today VPC support is not in place. We are looking at how to support it though.

Device Farm has its own instance of Appium server that the tests are run against. This is the same as the Appium that you would have run locally when the device is also connected to the same machine and not on another host.

If you want to use the Device Farm Appium server you should use http://127.0.0.1/4723/wdhub as the url of the server.

Hope that helps.

Title: AWS Device Farm send requests to server


问:
Iterate through list for number
I'm trying to search a list to find the value closest to 50%. I track the index of that value, using that to find the median value in another list.  My code isn't working:

def find_median(percent_list, avg_lst):
    closeValueIndex = []
    count = 0
    med_num = 50
    for i in percent_list:
        diff = abs(percent_list - med_num)
        minDiffValue = min(diff)
        if i == minDiffValue:
            closeValueIndex.append(count)
        count+= 1
    med = avg_lst[count]
    return med
    ```

答:
You should use enumerate. It's MADE for tracking indices and elements of a list at the same time.

You can also use a key function of min to get all this at the same time!

```<code>def find_median(percent_list, avg_list):
    count, _ = min(enumerate(percent_list), key=lambda ie: abs(ie[1]-50))
    return avg_list[count]
</code>```

This admittedly obfuscate code uses a lambda (which is just an anonymous function) to pull out the value from the (index, value) pairs you're feeding into it, and selects the minimal element. You could just as easily write:

```<code>def find_median(percent_list, avg_list):
    min_idx = 0
    min_diff = abs(percent_list[0] - 50)
    for i, val in enumerate(percent_list):
        diff = abs(val - 50)
        if diff < min_diff:
            min_idx, min_diff = i, diff
    return avg_list[min_idx]
</code>```

Or just tersely name your otherwise anonymous function.

```<code>def diff_from_50(tup):
    _, v = tup  # ignore the first element
    return abs(50 - v)

i, _ = min(enumerate(percent_list), key=diff_from_50)
result = avg_list[i]
</code>```

Title: Iterate through list for number

Body:
You should use enumerate. It's MADE for tracking indices and elements of a list at the same time.

You can also use a key function of min to get all this at the same time!

def find_median(percent_list, avg_list):
    count, _ = min(enumerate(percent_list), key=lambda ie: abs(ie[1]-50))
    return avg_list[count]

This admittedly obfuscate code uses a lambda (which is just an anonymous function) to pull out the value from the (index, value) pairs you're feeding into it, and selects the minimal element. You could just as easily write:

def find_median(percent_list, avg_list):
    min_idx = 0
    min_diff = abs(percent_list[0] - 50)
    for i, val in enumerate(percent_list):
        diff = abs(val - 50)
        if diff < min_diff:
            min_idx, min_diff = i, diff
    return avg_list[min_idx]

Or just tersely name your otherwise anonymous function.

def diff_from_50(tup):
    _, v = tup  # ignore the first element
    return abs(50 - v)

i, _ = min(enumerate(percent_list), key=diff_from_50)
result = avg_list[i]


问:
SQL update column twice
I have a string column (Col1) in table (Tab1). I want to write a script that removes '%' or '&' characters from the string values.

The select for this is the following:

```<code>SELECT REPLACE( Tab1.Col1, '&', ''),
       REPLACE(Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'
</code>```

Does this seem correct? If it is how would I convert this to any update statement? I tried the following:

```<code>UPDATE Tab1
SET Tab1.Col1 =  REPLACE( Tab1.Col1, '&', ''),
    Tab1.Col1 = REPLACE (Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'
</code>```

This doesn't work as you cant update column twice in SET.
Is there any other way I can do this? I know I'm probably doing something silly here so apologies for my ignorance.

Thanks in advance.

答:
This should work.  Replace returns a string which you can again pass to another replace function.</p>

```<code>UPDATE Tab1
    SET Tab1.Col1 =  REPLACE(REPLACE( Tab1.Col1, '&', ''), '%', '')
    FROM Table1 Tab1
    WHERE Tab1.Col1 like '%[&]%' OR Tab1.Col1 like '%[%]%'
</code>```

Title: SQL update column twice

Body:
I have a string column (Col1) in table (Tab1). I want to write a script that removes '%' or '&' characters from the string values.

The select for this is the following:

SELECT REPLACE( Tab1.Col1, '&', ''),
       REPLACE(Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'

Does this seem correct? If it is how would I convert this to any update statement? I tried the following:

UPDATE Tab1
SET Tab1.Col1 =  REPLACE( Tab1.Col1, '&', ''),
    Tab1.Col1 = REPLACE (Tab1.Col1, '%', '')
FROM Table1 Tab1
WHERE Tab1.Col1 like '%[&]%'
      OR Tab1.Col1 like '%[%]%'

This doesn't work as you cant update column twice in SET.
Is there any other way I can do this? I know I'm probably doing something silly here so apologies for my ignorance.

Thanks in advance.

Body:
This should work.  Replace returns a string which you can again pass to another replace function.

UPDATE Tab1
    SET Tab1.Col1 =  REPLACE(REPLACE( Tab1.Col1, '&', ''), '%', '')
    FROM Table1 Tab1
    WHERE Tab1.Col1 like '%[&]%' OR Tab1.Col1 like '%[%]%'


问:
Android .key to .jks - old
I'm re taking some old app that has been in the Play Store for more than 5 years. However now that all my code is migrated to AST, everything is working and I'm ready to make a new update, I've come to realize that the key for signing the app has a diferent extension name. Now Android Studio ask for a file .jks but my old app used to use a .key file. I haven't find anything online.</p>

答: The same file will work for Android Studio</p>

Title: Android .key to .jks - old


问:
Place text inside a circle. d3.js
I am trying to modify a code, and in the modifications that I have made, I have not been able to put a text in the middle of a circle. I've tried many things, and I've seen several examples but it does not work for me. How can I do it?
I know it should be done in this piece, and I add a text tag but it does not work.

```<code>bubbles.enter().append('circle')
.classed('bubble', true)
.attr('r', 0)
.attr('fill', function (d) {  return  fillColor(d.group); })
.attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker();
 })
.attr('stroke-width', 2)
.on('mouseover', function(){})
.on('mouseout', function(){});
</code>```

http://plnkr.co/edit/2BCVxQ5n07Rd9GYIOz1c?p=preview

答:
Create another selection for the texts:

```<code>var bubblesText = svg.selectAll('.bubbleText')
    .data(nodes, function(d) {
        return d.id;
    });

bubblesText.enter().append('text')
    .attr("text-anchor", "middle")
    .classed('bubble', true)
    .text(function(d) {
        return d.name
    })
</code>```

And move them inside the tick function.

Here is the updated plunker: http://plnkr.co/edit/UgDjqNhzbvukTWU6J9Oy?p=preview

PS: This is a very generic answer, just showing you how to display the texts. This answer doesn't deal with details like size or transitions, which are out of the scope of the question and that you'll have to implement yourself.

Title: Place text inside a circle. d3.js

Body:
I am trying to modify a code, and in the modifications that I have made, I have not been able to put a text in the middle of a circle. I've tried many things, and I've seen several examples but it does not work for me. How can I do it?
I know it should be done in this piece, and I add a text tag but it does not work.

bubbles.enter().append('circle')
.classed('bubble', true)
.attr('r', 0)
.attr('fill', function (d) {  return  fillColor(d.group); })
.attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker();
 })
.attr('stroke-width', 2)
.on('mouseover', function(){})
.on('mouseout', function(){});

http://plnkr.co/edit/2BCVxQ5n07Rd9GYIOz1c?p=preview

Body:
Create another selection for the texts:

var bubblesText = svg.selectAll('.bubbleText')
    .data(nodes, function(d) {
        return d.id;
    });

bubblesText.enter().append('text')
    .attr("text-anchor", "middle")
    .classed('bubble', true)
    .text(function(d) {
        return d.name
    })

And move them inside the tick function.

Here is the updated plunker: http://plnkr.co/edit/UgDjqNhzbvukTWU6J9Oy?p=preview

PS: This is a very generic answer, just showing you how to display the texts. This answer doesn't deal with details like size or transitions, which are out of the scope of the question and that you'll have to implement yourself.


问:
Error: $injector:unpr Unknown Provider when try delete a record
I am going to delete a record in my asp.net mvc project by using angular js 1.3.13.

```<code> <tr ng-repeat="emp in employees track by $index">
            <td>
                <a href="#" class="btn btn-default btn-sm">
                    <i class="glyphicon glyphicon-edit"></i>
                </a>
            </td>
            <td>
                {{emp.EmployeeId}}
            </td>
            <td>
                {{emp.EmployeeName}}
            </td>
            <td>
                {{emp.Address}}
            </td>
            <td>
                {{emp.EmailId}}
            </td>
            <td>
                <a href="#"
                   ng-click="delFn($index)"
                   class="btn btn-default btn-sm">
                    <i class="glyphicon glyphicon-trash"></i>
                </a>
            </td>
        </tr>
</code>```

My controller.js code

```<code>app.controller("EmpCtrl", function ($scope, EmployeeService) {

GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
}
    $scope.delFn = function (index) {
        var response = confirm('Delete this Employee?');
        if (response) {
           $scope.employees.splice(index, 1);
           EmployeeService.deleteEmployee(index);
        }
     }
});
</code>```

In my service.js, I have

```<code>    app.service("EmployeeService", function ($http,id) {
    this.getEmployee = function () {
        return $http.get("/Employee/GetAllEmployee");
    };

    this.deleteEmployee = function () {
        var url = "/Employee/DeleteEmployee/" + id;
        $http.delete(url)
            .success(function (result) {
                alert("Delete Successfully");
            })
            .error(function () {
                alert("Something wrong!");
            })
            .then(function () {
                window.location = '#/';
            })
    }
});
</code>```

In my asp.net controller, I Have the delete method

```<code> [HttpDelete]
    public void DeleteEmployee(int id)
    {
       // blah
    }
</code>```

But I get the error when debugging it in chrome.

angular.min.js:102 Error: [$injector:unpr] http://errors.angularjs.org/1.3.13/$injector/unpr?p0=idProvider%20%3C-%20id%20%3C-%20EmployeeService

So would you please advise me what is wrong?

答:
```<code>app.controller("EmpCtrl", ['$scope', 'EmployeeService', function ($scope, EmployeeService) {
//do stuff here
}]);
</code>```

according to angular documentation, your service injection is not done correctly. Try to change controller to the above and see if the error is gone

Body:
I am going to delete a record in my asp.net mvc project by using angular js 1.3.13.

                {{emp.EmployeeId}}

                {{emp.EmployeeName}}

                {{emp.Address}}

                {{emp.EmailId}}

My controller.js code

app.controller("EmpCtrl", function ($scope, EmployeeService) {

GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
}
    $scope.delFn = function (index) {
        var response = confirm('Delete this Employee?');
        if (response) {
           $scope.employees.splice(index, 1);
           EmployeeService.deleteEmployee(index);
        }
     }
});

In my service.js, I have

    app.service("EmployeeService", function ($http,id) {
    this.getEmployee = function () {
        return $http.get("/Employee/GetAllEmployee");
    };

    this.deleteEmployee = function () {
        var url = "/Employee/DeleteEmployee/" + id;
        $http.delete(url)
            .success(function (result) {
                alert("Delete Successfully");
            })
            .error(function () {
                alert("Something wrong!");
            })
            .then(function () {
                window.location = '#/';
            })
    }
});

In my asp.net controller, I Have the delete method

 [HttpDelete]
    public void DeleteEmployee(int id)
    {
       // blah
    }

But I get the error when debugging it in chrome.

angular.min.js:102 Error: [$injector:unpr] http://errors.angularjs.org/1.3.13/$injector/unpr?p0=idProvider%20%3C-%20id%20%3C-%20EmployeeService

So would you please advise me what is wrong?

Body:
app.controller("EmpCtrl", ['$scope', 'EmployeeService', function ($scope, EmployeeService) {
//do stuff here
}]);

according to angular documentation, your service injection is not done correctly. Try to change controller to the above and see if the error is gone


问:
how to solve error in inline assembly in C: 'can't find a register in class 'GENERAL_REGS' while reloading 'asm''
This is a part of implementation of lightweight cryptography PRESENT algorithm, optimized for speed, 8 bit, implemented by C, related to pLayer of the algorithm that implemented by inline assembly.

```<code>//  ****************** pLayer ******************************
        asm volatile("clr %0                \n"
                     "clr %1                \n"
                     "clr %2                \n"
                     "clr %3                \n"
                     "clr %4                \n"
                     "clr %5                \n"
                     "clr %6                \n"
                     "clr %7                \n"
                     "sbrc %8,0             \n"
                     "sbr  %0,1             \n"
                     "sbrc %8,1             \n"
                     "sbr  %2,1             \n"
                     "sbrc %8,2             \n"
                     "sbr  %4,1             \n"
                     "sbrc %8,3             \n"
                     "sbr  %6,1             \n"
                     "sbrc %8,4             \n"
                     "sbr  %0,2             \n"
                     "sbrc %8,5             \n"
                     "sbr  %2,2             \n"
                     "sbrc %8,6             \n"
                     "sbr  %4,2             \n"
                     "sbrc %8,7             \n"
                     "sbr  %6,2             \n"

                     "sbrc %9,0             \n"
                     "sbr  %0,4             \n"
                     "sbrc %9,1             \n"
                     "sbr  %2,4             \n"
                     "sbrc %9,2             \n"
                     "sbr  %4,4             \n"
                     "sbrc %9,3             \n"
                     "sbr  %6,4             \n"
                     "sbrc %9,4             \n"
                     "sbr  %0,8             \n"
                     "sbrc %9,5             \n"
                     "sbr  %2,8             \n"
                     "sbrc %9,6             \n"
                     "sbr  %4,8             \n"
                     "sbrc %9,7             \n"
                     "sbr  %6,8             \n"

                     "sbrc %10,0            \n"
                     "sbr  %0,16            \n"
                     "sbrc %10,1            \n"
                     "sbr  %2,16            \n"
                     "sbrc %10,2            \n"
                     "sbr  %4,16            \n"
                     "sbrc %10,3            \n"
                     "sbr  %6,16            \n"
                     "sbrc %10,4            \n"
                     "sbr  %0,32            \n"
                     "sbrc %10,5            \n"
                     "sbr  %2,32            \n"
                     "sbrc %10,6            \n"
                     "sbr  %4,32            \n"
                     "sbrc %10,7            \n"
                     "sbr  %6,32            \n"

                     "sbrc %11,0            \n"
                     "sbr  %0,64            \n"
                     "sbrc %11,1            \n"
                     "sbr  %2,64            \n"
                     "sbrc %11,2            \n"
                     "sbr  %4,64            \n"
                     "sbrc %11,3            \n"
                     "sbr  %6,64            \n"
                     "sbrc %11,4            \n"
                     "sbr  %0,128           \n"
                     "sbrc %11,5            \n"
                     "sbr  %2,128           \n"
                     "sbrc %11,6            \n"
                     "sbr  %4,128           \n"
                     "sbrc %11,7            \n"
                     "sbr  %6,128           \n"

                     "sbrc %12,0            \n"
                     "sbr  %1,1             \n"
                     "sbrc %12,1            \n"
                     "sbr  %3,1             \n"
                     "sbrc %12,2            \n"
                     "sbr  %5,1             \n"
                     "sbrc %12,3            \n"
                     "sbr  %7,1             \n"
                     "sbrc %12,4            \n"
                     "sbr  %1,2             \n"
                     "sbrc %12,5            \n"
                     "sbr  %3,2             \n"
                     "sbrc %12,6            \n"
                     "sbr  %5,2             \n"
                     "sbrc %12,7            \n"
                     "sbr  %7,2             \n"

                     "sbrc %13,0            \n"
                     "sbr  %1,4             \n"
                     "sbrc %13,1            \n"
                     "sbr  %3,4             \n"
                     "sbrc %13,2            \n"
                     "sbr  %5,4             \n"
                     "sbrc %13,3            \n"
                     "sbr  %7,4             \n"
                     "sbrc %13,4            \n"
                     "sbr  %1,8             \n"
                     "sbrc %13,5            \n"
                     "sbr  %3,8             \n"
                     "sbrc %13,6            \n"
                     "sbr  %5,8             \n"
                     "sbrc %13,7            \n"
                     "sbr  %7,8             \n"

                     "sbrc %14,0            \n"
                     "sbr  %1,16            \n"
                     "sbrc %14,1            \n"
                     "sbr  %3,16            \n"
                     "sbrc %14,2            \n"
                     "sbr  %5,16            \n"
                     "sbrc %14,3            \n"
                     "sbr  %7,16            \n"
                     "sbrc %14,4            \n"
                     "sbr  %1,32            \n"
                     "sbrc %14,5            \n"
                     "sbr  %3,32            \n"
                     "sbrc %14,6            \n"
                     "sbr  %5,32            \n"
                     "sbrc %14,7            \n"
                     "sbr  %7,32            \n"

                     "sbrc %15,0            \n"
                     "sbr  %1,64            \n"
                     "sbrc %15,1            \n"
                     "sbr  %3,64            \n"
                     "sbrc %15,2            \n"
                     "sbr  %5,64            \n"
                     "sbrc %15,3            \n"
                     "sbr  %7,64            \n"
                     "sbrc %15,4            \n"
                     "sbr  %1,128           \n"
                     "sbrc %15,5            \n"
                     "sbr  %3,128           \n"
                     "sbrc %15,6            \n"
                     "sbr  %5,128           \n"
                     "sbrc %15,7            \n"
                     "sbr  %7,128           \n"

                    :"=&r"  (temp_pLayer[0]),"=&r"  (temp_pLayer[1]),"=&r"  (temp_pLayer[2]),"=&r"  (temp_pLayer[3]),"=&r"  (temp_pLayer[4]),"=&r"  (temp_pLayer[5]),"=&r"  (temp_pLayer[6]),"=&r"  (temp_pLayer[7])
                    :"r"    (state[0]),"r"  (state[1]),"r"  (state[2]),"r"  (state[3]),"r"  (state[4]),"r"  (state[5]),"r"  (state[6]),"r"  (state[7])
        );
</code>```

in compiling of the code this error occurred:
"can't find a register in class 'GENERAL_REGS' while reloading 'asm'"

I searched about it and the reason and found some data, but didn't get how to solve this problem.

Is there any solution to define some registers for compiler or some especial syntax to correct the current code. some way except rewrite the code in another way?

thanks for your help.

答:
how to solve error in inline assembly in C: 'can't find a register in class 'GENERAL_REGS' while reloading 'asm''

And:

```<code>asm volatile("clr %0                \n"
             "clr %1                \n"
             "clr %2                \n"
             ...
         :"=&r"  (temp_pLayer[0]),"=&r"  (temp_pLayer[1]),"=&r"  (temp_pLayer[2]),"=&r"  (temp_pLayer[3]),
          "=&r"  (temp_pLayer[4]),"=&r"  (temp_pLayer[5]),"=&r"  (temp_pLayer[6]),"=&r"  (temp_pLayer[7])
         :"r"    (state[0]),"r"  (state[1]),"r"  (state[2]),"r"  (state[3]),
          "r"  (state[4]),"r"  (state[5]),"r"  (state[6]),"r"  (state[7])
    );
</code>```

I'm going to hazard a guess and say you ran out of general purpose registers.

Maybe you can use g rather than r in some places. According to Machine Constraints | Simple Constraints, g is described as:

Any register, memory or immediate integer operand is allowed, except
  for registers that are not general registers.

Sometimes rm works too.

Body:
This is a part of implementation of lightweight cryptography PRESENT algorithm, optimized for speed, 8 bit, implemented by C, related to pLayer of the algorithm that implemented by inline assembly.

//  ****************** pLayer ******************************
        asm volatile("clr %0                \n"
                     "clr %1                \n"
                     "clr %2                \n"
                     "clr %3                \n"
                     "clr %4                \n"
                     "clr %5                \n"
                     "clr %6                \n"
                     "clr %7                \n"
                     "sbrc %8,0             \n"
                     "sbr  %0,1             \n"
                     "sbrc %8,1             \n"
                     "sbr  %2,1             \n"
                     "sbrc %8,2             \n"
                     "sbr  %4,1             \n"
                     "sbrc %8,3             \n"
                     "sbr  %6,1             \n"
                     "sbrc %8,4             \n"
                     "sbr  %0,2             \n"
                     "sbrc %8,5             \n"
                     "sbr  %2,2             \n"
                     "sbrc %8,6             \n"
                     "sbr  %4,2             \n"
                     "sbrc %8,7             \n"
                     "sbr  %6,2             \n"

                     "sbrc %9,0             \n"
                     "sbr  %0,4             \n"
                     "sbrc %9,1             \n"
                     "sbr  %2,4             \n"
                     "sbrc %9,2             \n"
                     "sbr  %4,4             \n"
                     "sbrc %9,3             \n"
                     "sbr  %6,4             \n"
                     "sbrc %9,4             \n"
                     "sbr  %0,8             \n"
                     "sbrc %9,5             \n"
                     "sbr  %2,8             \n"
                     "sbrc %9,6             \n"
                     "sbr  %4,8             \n"
                     "sbrc %9,7             \n"
                     "sbr  %6,8             \n"

                     "sbrc %10,0            \n"
                     "sbr  %0,16            \n"
                     "sbrc %10,1            \n"
                     "sbr  %2,16            \n"
                     "sbrc %10,2            \n"
                     "sbr  %4,16            \n"
                     "sbrc %10,3            \n"
                     "sbr  %6,16            \n"
                     "sbrc %10,4            \n"
                     "sbr  %0,32            \n"
                     "sbrc %10,5            \n"
                     "sbr  %2,32            \n"
                     "sbrc %10,6            \n"
                     "sbr  %4,32            \n"
                     "sbrc %10,7            \n"
                     "sbr  %6,32            \n"

                     "sbrc %11,0            \n"
                     "sbr  %0,64            \n"
                     "sbrc %11,1            \n"
                     "sbr  %2,64            \n"
                     "sbrc %11,2            \n"
                     "sbr  %4,64            \n"
                     "sbrc %11,3            \n"
                     "sbr  %6,64            \n"
                     "sbrc %11,4            \n"
                     "sbr  %0,128           \n"
                     "sbrc %11,5            \n"
                     "sbr  %2,128           \n"
                     "sbrc %11,6            \n"
                     "sbr  %4,128           \n"
                     "sbrc %11,7            \n"
                     "sbr  %6,128           \n"

                     "sbrc %12,0            \n"
                     "sbr  %1,1             \n"
                     "sbrc %12,1            \n"
                     "sbr  %3,1             \n"
                     "sbrc %12,2            \n"
                     "sbr  %5,1             \n"
                     "sbrc %12,3            \n"
                     "sbr  %7,1             \n"
                     "sbrc %12,4            \n"
                     "sbr  %1,2             \n"
                     "sbrc %12,5            \n"
                     "sbr  %3,2             \n"
                     "sbrc %12,6            \n"
                     "sbr  %5,2             \n"
                     "sbrc %12,7            \n"
                     "sbr  %7,2             \n"

                     "sbrc %13,0            \n"
                     "sbr  %1,4             \n"
                     "sbrc %13,1            \n"
                     "sbr  %3,4             \n"
                     "sbrc %13,2            \n"
                     "sbr  %5,4             \n"
                     "sbrc %13,3            \n"
                     "sbr  %7,4             \n"
                     "sbrc %13,4            \n"
                     "sbr  %1,8             \n"
                     "sbrc %13,5            \n"
                     "sbr  %3,8             \n"
                     "sbrc %13,6            \n"
                     "sbr  %5,8             \n"
                     "sbrc %13,7            \n"
                     "sbr  %7,8             \n"

                     "sbrc %14,0            \n"
                     "sbr  %1,16            \n"
                     "sbrc %14,1            \n"
                     "sbr  %3,16            \n"
                     "sbrc %14,2            \n"
                     "sbr  %5,16            \n"
                     "sbrc %14,3            \n"
                     "sbr  %7,16            \n"
                     "sbrc %14,4            \n"
                     "sbr  %1,32            \n"
                     "sbrc %14,5            \n"
                     "sbr  %3,32            \n"
                     "sbrc %14,6            \n"
                     "sbr  %5,32            \n"
                     "sbrc %14,7            \n"
                     "sbr  %7,32            \n"

                     "sbrc %15,0            \n"
                     "sbr  %1,64            \n"
                     "sbrc %15,1            \n"
                     "sbr  %3,64            \n"
                     "sbrc %15,2            \n"
                     "sbr  %5,64            \n"
                     "sbrc %15,3            \n"
                     "sbr  %7,64            \n"
                     "sbrc %15,4            \n"
                     "sbr  %1,128           \n"
                     "sbrc %15,5            \n"
                     "sbr  %3,128           \n"
                     "sbrc %15,6            \n"
                     "sbr  %5,128           \n"
                     "sbrc %15,7            \n"
                     "sbr  %7,128           \n"

                    :"=&r"  (temp_pLayer[0]),"=&r"  (temp_pLayer[1]),"=&r"  (temp_pLayer[2]),"=&r"  (temp_pLayer[3]),"=&r"  (temp_pLayer[4]),"=&r"  (temp_pLayer[5]),"=&r"  (temp_pLayer[6]),"=&r"  (temp_pLayer[7])
                    :"r"    (state[0]),"r"  (state[1]),"r"  (state[2]),"r"  (state[3]),"r"  (state[4]),"r"  (state[5]),"r"  (state[6]),"r"  (state[7])
        );

in compiling of the code this error occurred:
"can't find a register in class 'GENERAL_REGS' while reloading 'asm'"

I searched about it and the reason and found some data, but didn't get how to solve this problem.

Is there any solution to define some registers for compiler or some especial syntax to correct the current code. some way except rewrite the code in another way?

thanks for your help.

Body:
how to solve error in inline assembly in C: 'can't find a register in class 'GENERAL_REGS' while reloading 'asm''

And:

asm volatile("clr %0                \n"
             "clr %1                \n"
             "clr %2                \n"
             ...
         :"=&r"  (temp_pLayer[0]),"=&r"  (temp_pLayer[1]),"=&r"  (temp_pLayer[2]),"=&r"  (temp_pLayer[3]),
          "=&r"  (temp_pLayer[4]),"=&r"  (temp_pLayer[5]),"=&r"  (temp_pLayer[6]),"=&r"  (temp_pLayer[7])
         :"r"    (state[0]),"r"  (state[1]),"r"  (state[2]),"r"  (state[3]),
          "r"  (state[4]),"r"  (state[5]),"r"  (state[6]),"r"  (state[7])
    );

I'm going to hazard a guess and say you ran out of general purpose registers.

Maybe you can use g rather than r in some places. According to Machine Constraints | Simple Constraints, g is described as:

Any register, memory or immediate integer operand is allowed, except
  for registers that are not general registers.

Sometimes rm works too.


问:
How to used an attribute in a SqlDataReader context ?
I'm trying to buid a generic SQL executor.

It's working if my DTO class attributes have the same name than my SQL table column.

To increase the generic part of my code, I add an attribute to my DTO in order to separate my DTO attribute to SQL column.

But it's not working

my DTO class :

```<code>public class CarModels
{
    [DbColumn("ca_id")] //column name
    public string Id { get; set; }

    [DbColumn("ca_label")]  //column name
    public string Label { get; set; }
}
</code>```

my generic method :

```<code>    public List<T> ExecuteSQLSELECTCommand<T>(string SQLcommand) where T : new()
    {
        IDictionary<string, string> databaseMappings = new Dictionary<string, string>(); ;

        Get_Connection();
        using (MySqlCommand cmd = new MySqlCommand())
        {

            cmd.Connection = connection;
            cmd.CommandText = string.Format(SQLcommand);
            List<T> res = new List<T>();
            try
            {
                MySqlDataReader reader = cmd.ExecuteReader();

                 while (reader.Read())
                  {
                    T t = new T();

                    for (int inc = 0; inc < reader.FieldCount; inc++)
                    {

                            Type type = t.GetType();
                         //how to get attribute link to current FiedCount ?
                            PropertyInfo prop = type.GetProperty(reader.GetName(inc));
                            prop.SetValue(t, reader.GetValue(inc), null);

                    }
                    res.Add(t);
                }

                reader.Close();
            }
            catch (Exception e)
            {

            }
            return res;
        }
    }
</code>```

and my call :

```<code>List<CarModels> carTest = db.ExecuteSQLCommand<CarModels>("SELECT ca_id, ca_label from cartracker.ca_cars");
</code>```

my question, how can I recover value of the attribute in order to build a PropertyInfo in a MySqlDataReader context?

Thanks.

答:
You can use a class like this.  Can you please tell me if it helps:</p>

```<code>public class AnEntity<T> where T : class, new()
{
    public T AnEntity(string[] token, ref int i, out TokenEnum tokenEnum,
                                        out string tokenException)
    {
       ...
        PropertyInfo[] properties = typeof(T).GetProperties();
        try
        {
            foreach (PropertyInfo property in properties)
            {
                ...
                    if (property.Name == "AName")
                    {
                        break;
                    }
...
</code>```

Body:
I'm trying to buid a generic SQL executor.

It's working if my DTO class attributes have the same name than my SQL table column.

To increase the generic part of my code, I add an attribute to my DTO in order to separate my DTO attribute to SQL column.

But it's not working

my DTO class :

public class CarModels
{
    [DbColumn("ca_id")] //column name
    public string Id { get; set; }

    [DbColumn("ca_label")]  //column name
    public string Label { get; set; }
}

my generic method :

    public List<T> ExecuteSQLSELECTCommand<T>(string SQLcommand) where T : new()
    {
        IDictionary<string, string> databaseMappings = new Dictionary<string, string>(); ;

        Get_Connection();
        using (MySqlCommand cmd = new MySqlCommand())
        {

            cmd.Connection = connection;
            cmd.CommandText = string.Format(SQLcommand);
            List<T> res = new List<T>();
            try
            {
                MySqlDataReader reader = cmd.ExecuteReader();

                 while (reader.Read())
                  {
                    T t = new T();

                    for (int inc = 0; inc < reader.FieldCount; inc++)
                    {

                            Type type = t.GetType();
                         //how to get attribute link to current FiedCount ?
                            PropertyInfo prop = type.GetProperty(reader.GetName(inc));
                            prop.SetValue(t, reader.GetValue(inc), null);

                    }
                    res.Add(t);
                }

                reader.Close();
            }
            catch (Exception e)
            {

            }
            return res;
        }
    }

and my call :

List<CarModels> carTest = db.ExecuteSQLCommand<CarModels>("SELECT ca_id, ca_label from cartracker.ca_cars");

my question, how can I recover value of the attribute in order to build a PropertyInfo in a MySqlDataReader context?

Thanks.

Body:
You can use a class like this.  Can you please tell me if it helps:

public class AnEntity<T> where T : class, new()
{
    public T AnEntity(string[] token, ref int i, out TokenEnum tokenEnum,
                                        out string tokenException)
    {
       ...
        PropertyInfo[] properties = typeof(T).GetProperties();
        try
        {
            foreach (PropertyInfo property in properties)
            {
                ...
                    if (property.Name == "AName")
                    {
                        break;
                    }
...


问:
HTML - CSS: Styling <object>?
If my div container has this:

```<code><div id="container"><img src...
</code>```

I can style the image by this:

```<code>CSS
#container img{ ... }
</code>```

For object tag

```<code><div id="container"><object ...
</code>```

How do I address it? I tried this:

```<code>CSS
#container object{ width: 100px; }
</code>```

But it does not work.

Assume the I cant define "id" or "class" for the object tag

I am using tinymce to embed to youtube video. And the code will be rendered like this:

```<code><div id="container">
...

    <div id="content">
      <p>
      <object width="435" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/l9caxMr9RgY">
      <param value="http://www.youtube.com/v/XXXXXX" name="src"></object>
      </p>
    </div>
</div>
</code>```

答:
You already add size and width to the object style="width: 100px; height: 100px;"

Example

Title: HTML - CSS: Styling <object>?

Body:
If my div container has this:

<img src...

I can style the image by this:

CSS
#container img{ ... }

For object tag

<object ...

How do I address it? I tried this:

CSS
#container object{ width: 100px; }

But it does not work.

Assume the I cant define "id" or "class" for the object tag

I am using tinymce to embed to youtube video. And the code will be rendered like this:

...

      <object width="435" height="350" type="application/x-shockwave-flash" data="http://www.youtube.com/v/l9caxMr9RgY">
      <param value="http://www.youtube.com/v/XXXXXX" name="src"></object>


问:
Apache Kafka order of messages with multiple partitions
As per Apache Kafka documentation, the order of the messages can be achieved within the partition or one partition in a topic. In this case, what is the parallelism benefit we are getting and it is equivalent to traditional MQs, isn't it?</p>

答:
In kafka Messages with the same key, from the same Producer, are delivered to the Consumer in order

another thing on top of that is, Data within a Partition will be stored in the order in which it is written therefore, data read from a Partition will be read in order for that partition

So if you want to get your messages in order across multi partitions, then you really need to group your messages with a key, so that messages with same key goes to same partition and with in that partition the messages are ordered.

In a nutshell, you will need to design a two level solution like above logically to get the messages ordered across multi partition.


问:
Are debug versions of (or symbol files for) the ATI/NVIDIA drivers available?
I don't even care if they are true "debug" versions, all I really want are the symbol files so that my callstack isn't rendered invalid when I break into the debugger.</p>

答:
AMD now publishes symbols for their drivers:
http://gpuopen.com/amd-driver-symbol-server/</p>


问:
What "private property" means on ES6 classes?
I am a bit lost with ES6 privacy on Classes. I have this Class:

```<code>class Whatever {

        constructor(value) {
            this._value = Number(value);
        }

        total() {
            return this._value * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance._value  );     // 1000
</code>```

I am trying to learn how Symbol() works to keep data private (see link), and after reading the documentation I am trying to make a simple example about it, but does not seem to have any difference:

```<code>const _value = Symbol('value');

    class Whatever {

        constructor(value) {
            this[_value] = Number(value);
        }

        total() {
            return this[_value] * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance[_value]  );    // 1000
</code>```

Could someone explain me on a comprehensive way, what does privacy mean on this case, and why my idea of privatizing data (making data unaccesible from outside the Class) is wrong? I have not much experience on OOP.

Thank you.

答:
No real difference in your example, assuming you don't loop through the enumerable properties of the class.

Consider the following:

```<code>function MyFunction () {
  const _private = new Symbol();

  this[_private] = 5;
  this.public = 10;
}

const thing = new MyFunction();

for (let key in thing) { // prints 10
  console.log(thing[key]);
}

console.log(thing.public); // prints 10
console.log(thing._private); // undefined
</code>```

Properties named by symbols are not enumerable, so in a sense they're not "exposed". Another benefit of symbols is that they're guaranteed to create unique keys, so there's no worry of key name collisions.

I chose to illustrate it with a function rather than a class for simplicity sake. For a class you could do the following (it's all about scope for "protecting" the symbol):

```<code>const MyClass = (function () {
  const _value = Symbol();
  return class _MyClass {
    constructor() {
      this[_value] = 5;
    }
  }
})();
</code>```

Disclaimer: It's not "true" privacy, since there are still ways to enumerate the symbols. I think the biggest advantage is for the name collisions.

Body:
I am a bit lost with ES6 privacy on Classes. I have this Class:

class Whatever {

        constructor(value) {
            this._value = Number(value);
        }

        total() {
            return this._value * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance._value  );     // 1000

I am trying to learn how Symbol() works to keep data private (see link), and after reading the documentation I am trying to make a simple example about it, but does not seem to have any difference:

const _value = Symbol('value');

    class Whatever {

        constructor(value) {
            this[_value] = Number(value);
        }

        total() {
            return this[_value] * 2;
        }
    }

    let instance = new Whatever('1000');
    console.log(instance.total() );     // 2000
    console.log(instance[_value]  );    // 1000

Could someone explain me on a comprehensive way, what does privacy mean on this case, and why my idea of privatizing data (making data unaccesible from outside the Class) is wrong? I have not much experience on OOP.

Thank you.

Body:
No real difference in your example, assuming you don't loop through the enumerable properties of the class.

Consider the following:

function MyFunction () {
  const _private = new Symbol();

  this[_private] = 5;
  this.public = 10;
}

const thing = new MyFunction();

for (let key in thing) { // prints 10
  console.log(thing[key]);
}

console.log(thing.public); // prints 10
console.log(thing._private); // undefined

Properties named by symbols are not enumerable, so in a sense they're not "exposed". Another benefit of symbols is that they're guaranteed to create unique keys, so there's no worry of key name collisions.

I chose to illustrate it with a function rather than a class for simplicity sake. For a class you could do the following (it's all about scope for "protecting" the symbol):

const MyClass = (function () {
  const _value = Symbol();
  return class _MyClass {
    constructor() {
      this[_value] = 5;
    }
  }
})();

Disclaimer: It's not "true" privacy, since there are still ways to enumerate the symbols. I think the biggest advantage is for the name collisions.


答:
You've confused some of your own concepts, and you're misusing min.  Let's look at the code:

```<code>for i in percent_list:
    diff = abs(percent_list - med_num)
</code>```

You're doing okay so far; i becomes each member of percent_list, one at a time.  For each of those, diff is the absolute difference from 50.  However, the next line is a logical error:

```<code>    minDiffValue = min(diff)
</code>```

This won't do anything useful: diff is only a single value, so this must return that value.

```<code>    if i = minDiffValue:
</code>```

This is another logical error, but in albegra.  i is the list element; minDiffValue is its distance from 50.  The only way this will be True is for the value 25.  The meaning of this is useless to your program.

Instead, you need to remember the position of the least element.  Try the combined iteration

```<code>for i, value in enumerate(percent_list):
    diff = abs(percent_list - med_num)
    if diff < minDiffValue:
        # Remember the minimum difference and its position
        minDiffValue = diff
        minIndex = i
</code>```

With this, once you finish the loop, you have the minimum discrepancy and its position ready to use.

```<code>return avg_lst[minIndex]
</code>```

There are more "Pythonic" ways to do this, but I think this one is likely best suited to your current level of programming.

Title: Iterate through list for number

Body:
I'm trying to search a list to find the value closest to 50%. I track the index of that value, using that to find the median value in another list.  My code isn't working:

def find_median(percent_list, avg_lst):
    closeValueIndex = []
    count = 0
    med_num = 50
    for i in percent_list:
        diff = abs(percent_list - med_num)
        minDiffValue = min(diff)
        if i == minDiffValue:
            closeValueIndex.append(count)
        count+= 1
    med = avg_lst[count]
    return med

Body:
You've confused some of your own concepts, and you're misusing min.  Let's look at the code:

for i in percent_list:
    diff = abs(percent_list - med_num)

You're doing okay so far; i becomes each member of percent_list, one at a time.  For each of those, diff is the absolute difference from 50.  However, the next line is a logical error:

    minDiffValue = min(diff)

This won't do anything useful: diff is only a single value, so this must return that value.

    if i = minDiffValue:

This is another logical error, but in albegra.  i is the list element; minDiffValue is its distance from 50.  The only way this will be True is for the value 25.  The meaning of this is useless to your program.

Instead, you need to remember the position of the least element.  Try the combined iteration

for i, value in enumerate(percent_list):
    diff = abs(percent_list - med_num)
    if diff < minDiffValue:
        # Remember the minimum difference and its position
        minDiffValue = diff
        minIndex = i

With this, once you finish the loop, you have the minimum discrepancy and its position ready to use.

return avg_lst[minIndex]

There are more "Pythonic" ways to do this, but I think this one is likely best suited to your current level of programming.


问:
Disabling/enabled textbox in GridViewRow
I have a checkbox and a textbox in a GridView (for every row), and I'd like to be able to write some javascript that would enable and disable the textbox depending on the state of the checkbox (checked or unchecked). I guess I'd have to give JS the row index somehow. Is this possible?</p>

答:
Yes this is absolutely possible.

To implement this you need to do the following:

Write a generic JavaScript function to handle the enabling/disabling of a Text-Box based on the state of the Check-Box;

Example :-

function ManageControlEnabling(sourceCheckBoxId, affectingControlId)

{

var sourceCheckBox = document.getElementById(sourceCheckBoxId);

var affectingControl = document.getElementById(affectingControlId);

var shouldEnable = false;

if (sourceCheckBox && affectingControl)

{

    shouldEnable = sourceCheckBox.checked;

```<code>if(shouldEnable)
    affectingControl.disabled = false;
else
    affectingControl.disabled = true;
</code>```

}

}

Handle the Row-Data-Bound event of the Grid-View. Implement a similar functionality in your .Net code, to handle the enabling/disabling of the text-box (for each row) based on the state of the check-box. And also add the JavaScript function to the check-box;

Example :-

```<code>CheckBox checkSource;
TextBox textAffecting;

checkSource = e.Row.FindControl("cbSource") as CheckBox;
textAffecting = e.Row.FindControl("tbAffecting") as TextBox;

if(checkSource != null)
{
    textAffecting.Enabled = checkSource.Checked;
}

checkSource.Attributes.Add("onclick", "ManageControlEnabling('" + checkSource.ClientID + "', '" + textAffecting.ClientID + "', true);");
</code>```

Please see if this helps.

Thanks.

Body:
Yes this is absolutely possible.

To implement this you need to do the following:

Write a generic JavaScript function to handle the enabling/disabling of a Text-Box based on the state of the Check-Box;

Example :-

function ManageControlEnabling(sourceCheckBoxId, affectingControlId)

{

var sourceCheckBox = document.getElementById(sourceCheckBoxId);

var affectingControl = document.getElementById(affectingControlId);

var shouldEnable = false;

if (sourceCheckBox && affectingControl)

{

    shouldEnable = sourceCheckBox.checked;

if(shouldEnable)
    affectingControl.disabled = false;
else
    affectingControl.disabled = true;

}

}

Handle the Row-Data-Bound event of the Grid-View. Implement a similar functionality in your .Net code, to handle the enabling/disabling of the text-box (for each row) based on the state of the check-box. And also add the JavaScript function to the check-box;

Example :-

CheckBox checkSource;
TextBox textAffecting;

checkSource = e.Row.FindControl("cbSource") as CheckBox;
textAffecting = e.Row.FindControl("tbAffecting") as TextBox;

if(checkSource != null)
{
    textAffecting.Enabled = checkSource.Checked;
}

checkSource.Attributes.Add("onclick", "ManageControlEnabling('" + checkSource.ClientID + "', '" + textAffecting.ClientID + "', true);");

Please see if this helps.

Thanks.