问:
How to output Django queryset as JSON?
I want to serialize my queryset, and I want it in a format as this view outputs:

```<code>class JSONListView(ListView):
    queryset = Users.objects.all()

    def get(self, request, *args, **kwargs):
        return HttpResponse(json.dumps({'data': [['bar','foo','bar','foo'],['foo','bar','foo','bar']]}, indent=4), content_type='application/json')
</code>```

I simply don't know how to output the queryset instead of the manual data in the example.

I've tried

```<code>json.dumps({"data": self.get_queryset()})
</code>```

and

```<code>serializers.serialize("json", {'data': self.get_queryset()})
</code>```

but it won't work. What am I doing wrong? Do I need to make a custom JSON Encoder?

答:
If the goal is to build an API that allow you to access your models in JSON format I recommend you to use the django-restframework that is an enormously popular package within the Django community to achieve this type of tasks.

Django Rest Framework Website

Github

It include useful features such as Pagination, Defining Serializers, Nested models/relations and more. Even if you only want to do minor Javascript tasks and Ajax calls I would still suggest you to build a proper API using the Django Rest Framework instead of manually defining the JSON response.

Title: How to output Django queryset as JSON?

Body:
I want to serialize my queryset, and I want it in a format as this view outputs:

class JSONListView(ListView):
    queryset = Users.objects.all()

    def get(self, request, *args, **kwargs):
        return HttpResponse(json.dumps({'data': [['bar','foo','bar','foo'],['foo','bar','foo','bar']]}, indent=4), content_type='application/json')

I simply don't know how to output the queryset instead of the manual data in the example.

I've tried

json.dumps({"data": self.get_queryset()})

and

serializers.serialize("json", {'data': self.get_queryset()})

but it won't work. What am I doing wrong? Do I need to make a custom JSON Encoder?


来源: stackexchange

问:
Scala: How to multiply a List of Lists by value
Now studying Scala and working with list of lists. Want to multiply array by an element(for example, 1).

However I get the following error:

identifier expected but integer constant found

Current code:

```<code>def multiply[A](listOfLists:List[List[A]]):List[List[A]] =
if (listOfLists == Nil) Nil
else -1 * listOfLists.head :: multiply(listOfLists.tail)
val tt = multiply[List[3,4,5,6];List[4,5,6,7,8]]
print(tt);;
</code>```

答:
To make numeric operations available to type A, you can use context bound to associate A with scala.math.Numeric which provides methods such as times and fromInt to carry out the necessary multiplication in this use case:

```<code>def multiply[A: Numeric](listOfLists: List[List[A]]): List[List[A]] = {
  val num = implicitly[Numeric[A]]
  import num._
  if (listOfLists == Nil) Nil else
    listOfLists.head.map(times(_, fromInt(-1))) :: multiply(listOfLists.tail)
}

multiply( List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)) )
// res1: List[List[Int]] = List(List(-3, -4, -5, -6), List(-4, -5, -6, -7, -8))

multiply( List(List(3.0, 4.0), List(5.0, 6.0, 7.0)) )
// res2: List[List[Double]] = List(List(-3.0, -4.0), List(-5.0, -6.0, -7.0))
</code>```

For more details about context bound, here's a relevant SO link.

ContentLicense: CC BY-SA 3.0

Body:
Now studying Scala and working with list of lists. Want to multiply array by an element(for example, 1).

However I get the following error:

identifier expected but integer constant found

Current code:

def multiply[A](listOfLists:List[List[A]]):List[List[A]] =
if (listOfLists == Nil) Nil
else -1 * listOfLists.head :: multiply(listOfLists.tail)
val tt = multiply[List[3,4,5,6];List[4,5,6,7,8]]
print(tt);;

Body:
To make numeric operations available to type A, you can use context bound to associate A with scala.math.Numeric which provides methods such as times and fromInt to carry out the necessary multiplication in this use case:

def multiply[A: Numeric](listOfLists: List[List[A]]): List[List[A]] = {
  val num = implicitly[Numeric[A]]
  import num._
  if (listOfLists == Nil) Nil else
    listOfLists.head.map(times(_, fromInt(-1))) :: multiply(listOfLists.tail)
}

multiply( List(List(3, 4, 5, 6), List(4, 5, 6, 7, 8)) )
// res1: List[List[Int]] = List(List(-3, -4, -5, -6), List(-4, -5, -6, -7, -8))

multiply( List(List(3.0, 4.0), List(5.0, 6.0, 7.0)) )
// res2: List[List[Double]] = List(List(-3.0, -4.0), List(-5.0, -6.0, -7.0))

For more details about context bound, here's a relevant SO link.


问:
sencha touch add row of list that has been removed to different index of list
I really need some idea on this. Basically, i'm working to sort list by click a button. If i click up button, the list will go up which the index of selected list will reduced by one. And when i click down button, the list will go down which the index of selected list will increased by one. I used the approach to remove the selected list for a temporary, then insert the list to the different index according to user. i have settled the remove part but i have no idea on insert part. Please help.

These are the code to remove selected list.

var removeSelectedItems = Ext.getCmp('SearchRefSlipMain_List').getSelection()[0];                            Ext.getCmp('SearchRefSlipMain_List').getStore().remove(removeSelectedItems);

What left is only to insert the row of list that i have been removed to another row (different index) according to user.

答:
the button:

```<code>        {
          xtype: 'button',
          iconCls: 'arrow_down',
          handler: function () {
               RowDown();

             }
         }
</code>```

This is the function:

```<code>function RowDown(){

var direction = 1   // 1 or -1
var record = Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getSelection()[0];   //list id

if (!record) {
    return;
}
var index = Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().indexOf(record);

if (direction < 0) {
    index--;
    if (index < 0) {
        return;
    }
} else {
    index++;
    if (index >= Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().getCount()) {

        return;
    }
}

Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().remove(record);
Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().insert(index, record);

 }
</code>```

***if move the selected list up, change the direction =  -1
*  https://www.sencha.com/forum/showthread.php?48472-how-to-move-the-grid-s-row-up-and-down (i got the solution from here, just change a bit according to Sencha Touch)

Body:
the button:

        {
          xtype: 'button',
          iconCls: 'arrow_down',
          handler: function () {
               RowDown();

             }
         }

This is the function:

function RowDown(){

var direction = 1   // 1 or -1
var record = Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getSelection()[0];   //list id

if (!record) {
    return;
}
var index = Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().indexOf(record);

if (direction < 0) {
    index--;
    if (index < 0) {
        return;
    }
} else {
    index++;
    if (index >= Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().getCount()) {

        return;
    }
}

Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().remove(record);
Ext.getCmp('Settings_SetTreatmentList_TreatmentDetail_List').getStore().insert(index, record);

 }

***if move the selected list up, change the direction =  -1
*  https://www.sencha.com/forum/showthread.php?48472-how-to-move-the-grid-s-row-up-and-down (i got the solution from here, just change a bit according to Sencha Touch)


问:
Inline style using asset pipeline in rails

<%= link_to root_path do %>

        <div style="background-image:<%= image_tag " image1.png "%>">

Title

Paragraph

<% end %>```

I want to pull the image from the asset pipeline to put as my background.
I could do it in .sass file.  But I made a template for each one and think it would be easier to input each photo in.

<div style="background-image:<%= image_tag "image1.png"%>">
 This is the line that I'm sure about the syntax about.

答:
Replace image_path which would give you an img tag, for something to give you the path for the image1 file, try with image_path:

```<code><div style="background-image: <%= image_path 'image1' %>"></div>
</code>```

Body:
<%= link_to root_path do %>

        <div style="background-image:<%= image_tag " image1.png "%>">

Title

Paragraph

<% end %>

I want to pull the image from the asset pipeline to put as my background.
I could do it in .sass file.  But I made a template for each one and think it would be easier to input each photo in.

<div style="background-image:<%= image_tag "image1.png"%>">
 This is the line that I'm sure about the syntax about.

Body:
Replace image_path which would give you an img tag, for something to give you the path for the image1 file, try with image_path:

<div style="background-image: <%= image_path 'image1' %>"></div>


问:
Getting rid of ANSI escape characters when viewing ri in (Mac)Vim
I'm having trouble viewing ri documentation within gvim and MacVim (tried it on both) Some of the ri documentation includes text decorations that look fine when viewed in a terminal window, but include ANSI escape characters when viewing in gvim/MacVim. For example, the following ri snippet from $ri class looks like this in the terminal:

Returns the class of obj, now
  preferred over Object#type

And this in gvim:

Returns the class of [4mobj[m, now preferred over [7mObject#type[m,

It'd be great to be able to reference legible ri docs within gvim. Any ideas on where to begin looking to fix this?

答:
These two scripts seem to have been written to address that problem. They don't appear to be perfect solutions. One of them apparently requires a patch to vi, or did at one point. I can't quite tell what the other one does but I think it renders your window, interpreting the codes, when you use a specific command.

There is also some advice on existing vi commands.

See:

http://www.vim.org/scripts/script.php?script_id=302

http://www.vim.org/scripts/script.php?script_id=1127

ContentLicense: CC BY-SA 2.5


问:
AttributeError: 'str' object has no attribute 'remove', how to fix?
I have created a function that returns the following error:

```<code>original_alphabet.remove(value)
AttributeError: 'str' object has no attribute 'remove'
</code>```

I'm not how to fix the error, any help is appreciated. This is my code:

```<code>def keyword_cipher_alphabet(keyword):
 original_alphabet = "abcdefghijklmnopqrstuvwxyz"

 for value in original_alphabet:
  if value in keyword:
   original_alphabet.remove(value)

 keyword_alphabet = ""
 for value in original_alphabet:
  keyword_alphabet += value

 user_keyword = ""
 for value in keyword:
  user_keyword += value

 result = user_keyword + keyword_alphabet

 return result.upper()
</code>```

答:
The error is caused because strings don't have a method remove.  You might try replace instead:

```<code>$> my_str = 'abc'
$> my_str = my_str.replace('b', '')
$> my_str
'ac'
</code>```

Body:
I have created a function that returns the following error:

original_alphabet.remove(value)
AttributeError: 'str' object has no attribute 'remove'

I'm not how to fix the error, any help is appreciated. This is my code:

def keyword_cipher_alphabet(keyword):
 original_alphabet = "abcdefghijklmnopqrstuvwxyz"

 for value in original_alphabet:
  if value in keyword:
   original_alphabet.remove(value)

 keyword_alphabet = ""
 for value in original_alphabet:
  keyword_alphabet += value

 user_keyword = ""
 for value in keyword:
  user_keyword += value

 result = user_keyword + keyword_alphabet

 return result.upper()

Body:
The error is caused because strings don't have a method remove.  You might try replace instead:

$> my_str = 'abc'
$> my_str = my_str.replace('b', '')
$> my_str
'ac'


问:
Getting links to surround the audio button
Code 1:

Do you see how after you Click on the image the audio button appears and plays, and there are no links surrounding it. On Code 1 how do I enable the links surrounding the audio button?

https://jsfiddle.net/7ux1s23j/29/

Links

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

  <svg class="play hide " style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

<audio id="player" preload="none">
  <source src="http://hi5.1980s.fm/;" type="audio/mpeg">
  </source>
</audio>

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

<p><strong>Code 2:</strong></p>

<p>On this one I have links surrounding it after you click on the image. </p>

<p>https://jsfiddle.net/0yxvpa09/19/</p>

<p><img src="https://i.stack.imgur.com/ExDJP.png" alt="Screenshot"></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>
  .cover {
    width: 260px;
    height: 168px;
    cursor: pointer;
    background-image: linear-gradient( to right, transparent, transparent 83px, #0059dd 83px, #0059dd 86px, transparent 86px, transparent 174px, #0059dd 174px, #0059dd 177px, transparent 177px, transparent 260px), url("https://i.imgur.com/BBYxKcf.jpg");
    border: 3px solid #0059dd;
    font-family: Tahoma;
    font-weight: bold;
    font-size: 30px;
    color: #0059dd;
    cursor: pointer;
    line-height: 100px;
    text-align: center;
  }

  .links div {
    margin: 0 0 12px 0;
  }

  .links a {
    display: block;
    width: 50px;
    height: 50px;
    background-color: green;
    margin: -50px 0 0;
    transition: 0.5s ease-in-out;
  }

  a.x1 {
    margin: 0
  }

  a.x2 {
    margin-left: 54px
  }

  a.x3 {
    margin-left: 108px
  }

  a.x4 {
    margin-left: 162px
  }

  a.x5 {
    margin-left: 216px
  }

  .links a:hover,
  .links a:active,
  .links a:focus {
    background: blue;
  }

  .scrl a:visited {
    background: orange;
    color: #000000;
  }

  .scrl a:hover {
    background: red;
  }

  .hide {
    display: none;
  }

  .links div:last-child {
    margin-bottom: 0;
  }
  .playButton {
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: #000000;
    fill: #aaff00;
    margin: -112px 0 0 108px;
  }

  .playButton.playing {
    background-color: #000000;
  }
</style>

<div class="cover">Links</div>

<div class="test hide">

  <div class="links    ">
    <div>

    </div>

    <div>

    </div>

    <div>

    </div>
  </div>
</div>

<div class="playButton hide">

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>
</div>

<script>
  (function iife() {
    "use strict";

    function hideClickedElement(evt) {
      var target = evt.target;
      target.classList.add("hide");
      document.querySelector(".test").classList.remove("hide");
      document.querySelector(".playButton").classList.remove("hide");
    }
    var cover = document.querySelector(".cover");
    cover.addEventListener("click", hideClickedElement, false);
  }());

</script></code>```

On Code 1 how do I enable the links surrounding the audio button?

答:
Here you go. This is a workaround solution for you

I just fix as follows

```<code>.playButton.playing {
  ....
  margin: -112px 0 0 108px;
  ....
}
</code>```

And then you need to control the linksDiv at what condition will display.
document.getElementById("myLinkDiv").style.display='none';

or

document.getElementById("myLinkDiv").classList.add("hide");

Body:
Code 1:

Do you see how after you Click on the image the audio button appears and plays, and there are no links surrounding it. On Code 1 how do I enable the links surrounding the audio button?

https://jsfiddle.net/7ux1s23j/29/

Links

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

  <svg class="play hide " style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

<audio id="player" preload="none">
  <source src="http://hi5.1980s.fm/;" type="audio/mpeg">
  </source>
</audio>

Code 2:

On this one I have links surrounding it after you click on the image.

https://jsfiddle.net/0yxvpa09/19/

Links

  <svg class="play" style="margin:5px 9px;" width="38" height="40" viewbox="0 0 85 100">
    <path d="M81 44.6c5 3 5 7.8 0 10.8L9 98.7c-5 3-9 .7-9-5V6.3c0-5.7 4-8 9-5l72 43.3z"></path>
  </svg>

  <svg class="pause" style="display: none;margin:5px 7px;" width="36" height="40" viewbox="0 0 60 100">
    <path d="M0 8c0-5 3-8 8-8s9 3 9 8v84c0 5-4 8-9 8s-8-3-8-8V8zm43 0c0-5 3-8 8-8s8 3 8 8v84c0 5-3 8-8 8s-8-3-8-8V8z"></path>
  </svg>

On Code 1 how do I enable the links surrounding the audio button?

Body:
Here you go. This is a workaround solution for you

I just fix as follows

.playButton.playing {
  ....
  margin: -112px 0 0 108px;
  ....
}

And then you need to control the linksDiv at what condition will display.
document.getElementById("myLinkDiv").style.display='none';

or

document.getElementById("myLinkDiv").classList.add("hide");


问:
iOS 11 navigation bar height customizing
Now in iOS 11, the sizeThatFits method is not called from UINavigationBar subclasses. Changing the frame of UINavigationBar causes glitches and wrong insets.
So, any ideas how to customize navbar height now?

答:
I was doubling the height of my navigation bar so I could add a row of status icons above the default navigation controls, by subclassing UINavigationBar and using sizeThatFits to override the height. Fortunately this has the same effect, and is simpler, with fewer side effects. I tested it with iOS 8 through 11. Put this in your view controller:</p>

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.navigationController) {
        self.navigationItem.prompt = @" "; // this adds empty space on top
    }
}
</code>```

Body:
I was doubling the height of my navigation bar so I could add a row of status icons above the default navigation controls, by subclassing UINavigationBar and using sizeThatFits to override the height. Fortunately this has the same effect, and is simpler, with fewer side effects. I tested it with iOS 8 through 11. Put this in your view controller:

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.navigationController) {
        self.navigationItem.prompt = @" "; // this adds empty space on top
    }
}


问:
Exception while using Hbase custom filter
I have written a Hbase custom Filter extending FilterBase and converted into JAR. The filter looks like this :

```<code>public class MyFilter1 extends FilterBase implements Serializable{
boolean filterRow= true;
String srh;

public MyFilter1(String str) {
    this.srh= str;
}

@Override
public ReturnCode filterKeyValue(Cell c) throws IOException {
    String str= Bytes.toString(c.getValue());

    if(str.contains(str)) {
        filterRow= false;
        return ReturnCode.INCLUDE;
    }

    filterRow= true;
    return ReturnCode.SKIP;
}

@Override
public  boolean filterRow() {
    return filterRow;
}

@Override
public byte[] toByteArray() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(this);
    return out.toByteArray();
}

public static MyFilter1 parseFrom(final byte[] data) {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    MyFilter1 ans= null;
    ObjectInputStream is;
    try {
        is = new ObjectInputStream(in);
        ans= (MyFilter1)is.readObject();;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ans;
}
</code>```

}

After making the JAR file (i.e. MyFilter.jar) I put it in /use/local/HBase/lib/filters directory. Then I set

export HBASE_CLASSPATH="/usr/local/Hbase/lib/filters/MyFilter.jar"

in hbase-env.sh filter and restarted the hbase server. Then I used the custom filter from java program :

```<code>public static void main(String argv[]) throws IOException {
        Configuration conf= HBaseConfiguration.create();
        Connection con= ConnectionFactory.createConnection(conf);

        Table table= con.getTable(TableName.valueOf("stud"));

        Filter fl= new MyFilter("uc");

        Scan sc= new Scan();
        sc.setFilter(fl);

        ResultScanner rs= table.getScanner(sc);

        for(Result r : rs)
            System.out.println(Bytes.toString(r.getValue(Bytes.toBytes("perData"), Bytes.toBytes("name"))));
    }
</code>```

But getting following exception

```<code>Exception in thread "main" org.apache.hadoop.hbase.DoNotRetryIOException: org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.reflect.InvocationTargetException
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1478)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toScan(ProtobufUtil.java:993)
at org.apache.hadoop.hbase.regionserver.RSRpcServices.scan(RSRpcServices.java:2396)
at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ClientService$2.callBlockingMethod(ClientProtos.java:33648)
at org.apache.hadoop.hbase.ipc.RpcServer.call(RpcServer.java:2180)
at org.apache.hadoop.hbase.ipc.CallRunner.run(CallRunner.java:112)
at org.apache.hadoop.hbase.ipc.RpcExecutor.consumerLoop(RpcExecutor.java:133)
at org.apache.hadoop.hbase.ipc.RpcExecutor$1.run(RpcExecutor.java:108)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1474)
... 8 more
Caused by: org.apache.hadoop.hbase.exceptions.DeserializationException: parseFrom called on base Filter, but should be called on derived type
at org.apache.hadoop.hbase.filter.Filter.parseFrom(Filter.java:270)
... 13 more

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106)
at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:95)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.getRemoteException(ProtobufUtil.java:329)
at org.apache.hadoop.hbase.client.ScannerCallable.openScanner(ScannerCallable.java:408)
at org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:204)
at org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:65)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries(RpcRetryingCaller.java:210)
at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas$RetryingRPC.call(ScannerCallableWithReplicas.java:364)
at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas$RetryingRPC.call(ScannerCallableWithReplicas.java:338)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:136)
at org.apache.hadoop.hbase.client.ResultBoundedCompletionService$QueueingFuture.run(ResultBoundedCompletionService.java:65)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.hadoop.hbase.ipc.RemoteWithExtrasException(org.apache.hadoop.hbase.DoNotRetryIOException): org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.reflect.InvocationTargetException
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1478)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toScan(ProtobufUtil.java:993)
at org.apache.hadoop.hbase.regionserver.RSRpcServices.scan(RSRpcServices.java:2396)
at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ClientService$2.callBlockingMethod(ClientProtos.java:33648)
at org.apache.hadoop.hbase.ipc.RpcServer.call(RpcServer.java:2180)
at org.apache.hadoop.hbase.ipc.CallRunner.run(CallRunner.java:112)
at org.apache.hadoop.hbase.ipc.RpcExecutor.consumerLoop(RpcExecutor.java:133)
at org.apache.hadoop.hbase.ipc.RpcExecutor$1.run(RpcExecutor.java:108)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1474)
... 8 more
Caused by: org.apache.hadoop.hbase.exceptions.DeserializationException: parseFrom called on base Filter, but should be called on derived type
at org.apache.hadoop.hbase.filter.Filter.parseFrom(Filter.java:270)
... 13 more

at org.apache.hadoop.hbase.ipc.RpcClientImpl.call(RpcClientImpl.java:1267)
at org.apache.hadoop.hbase.ipc.AbstractRpcClient.callBlockingMethod(AbstractRpcClient.java:227)
at org.apache.hadoop.hbase.ipc.AbstractRpcClient$BlockingRpcChannelImplementation.callBlockingMethod(AbstractRpcClient.java:336)
at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ClientService$BlockingStub.scan(ClientProtos.java:34094)
at org.apache.hadoop.hbase.client.ScannerCallable.openScanner(ScannerCallable.java:400)
... 10 more
</code>```

Can any one please help me with this...

答:
Just to add a (perhaps important) detail to the answers from Abhishek Kumar above. It seems the serializer toByteArray() and deserializer parseFrom(byte[] rawBytes) must be implemented via Google Protocol Buffers 2. Below is an example implementation.

AFilter.java

```<code>// whatever fields you need for the AFilter
long fieldA;
long fieldB;

/**
* Transform this {@code AFilter} instance to a byte array for serialization.
* @return raw bytes of this instance
*/
@Override
public byte[] toByteArray() {
    final FilterProtos.AFilter.Builder builder = FilterProtos.AFilter.newBuilder();
    builder.setFieldA(fieldA);
    builder.setFieldB(fieldB);

    return builder.build().toByteArray();
}

/**
 * De-serialize {@code AFilter} from {@code rawBytes}.
 *
 * @param rawBytes raw bytes of the filter
 * @return AFilter object
 * @throws DeserializationException
 */
public static AFilter parseFrom(final byte[] rawBytes)
        throws DeserializationException {

    try {
        FilterProtos.AFilter proto;
        proto = FilterProtos.AFilter.parseFrom(rawBytes);

        return new AFilter(proto.getFieldA(), proto.getFieldB());
    } catch (InvalidProtocolBufferException ex) {
        throw new DeserializationException(
                ex);
    }
}
</code>```

Filters.proto

```<code>option java_package = "my.java.package";
option java_outer_classname = "FilterProtos";
option java_generic_services = true;
option java_generate_equals_and_hash = true;
option optimize_for = SPEED;

message AFilter{
    required uint64 fieldA = 1;
    required uint64 fieldB = 2;
}
</code>```

Body:
I have written a Hbase custom Filter extending FilterBase and converted into JAR. The filter looks like this :

public class MyFilter1 extends FilterBase implements Serializable{
boolean filterRow= true;
String srh;

public MyFilter1(String str) {
    this.srh= str;
}

@Override
public ReturnCode filterKeyValue(Cell c) throws IOException {
    String str= Bytes.toString(c.getValue());

    if(str.contains(str)) {
        filterRow= false;
        return ReturnCode.INCLUDE;
    }

    filterRow= true;
    return ReturnCode.SKIP;
}

@Override
public  boolean filterRow() {
    return filterRow;
}

@Override
public byte[] toByteArray() throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ObjectOutputStream os = new ObjectOutputStream(out);
    os.writeObject(this);
    return out.toByteArray();
}

public static MyFilter1 parseFrom(final byte[] data) {
    ByteArrayInputStream in = new ByteArrayInputStream(data);
    MyFilter1 ans= null;
    ObjectInputStream is;
    try {
        is = new ObjectInputStream(in);
        ans= (MyFilter1)is.readObject();;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ans;
}

}

After making the JAR file (i.e. MyFilter.jar) I put it in /use/local/HBase/lib/filters directory. Then I set

export HBASE_CLASSPATH="/usr/local/Hbase/lib/filters/MyFilter.jar"

in hbase-env.sh filter and restarted the hbase server. Then I used the custom filter from java program :

public static void main(String argv[]) throws IOException {
        Configuration conf= HBaseConfiguration.create();
        Connection con= ConnectionFactory.createConnection(conf);

        Table table= con.getTable(TableName.valueOf("stud"));

        Filter fl= new MyFilter("uc");

        Scan sc= new Scan();
        sc.setFilter(fl);

        ResultScanner rs= table.getScanner(sc);

        for(Result r : rs)
            System.out.println(Bytes.toString(r.getValue(Bytes.toBytes("perData"), Bytes.toBytes("name"))));
    }

But getting following exception

Exception in thread "main" org.apache.hadoop.hbase.DoNotRetryIOException: org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.reflect.InvocationTargetException
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1478)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toScan(ProtobufUtil.java:993)
at org.apache.hadoop.hbase.regionserver.RSRpcServices.scan(RSRpcServices.java:2396)
at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ClientService$2.callBlockingMethod(ClientProtos.java:33648)
at org.apache.hadoop.hbase.ipc.RpcServer.call(RpcServer.java:2180)
at org.apache.hadoop.hbase.ipc.CallRunner.run(CallRunner.java:112)
at org.apache.hadoop.hbase.ipc.RpcExecutor.consumerLoop(RpcExecutor.java:133)
at org.apache.hadoop.hbase.ipc.RpcExecutor$1.run(RpcExecutor.java:108)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1474)
... 8 more
Caused by: org.apache.hadoop.hbase.exceptions.DeserializationException: parseFrom called on base Filter, but should be called on derived type
at org.apache.hadoop.hbase.filter.Filter.parseFrom(Filter.java:270)
... 13 more

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.apache.hadoop.ipc.RemoteException.instantiateException(RemoteException.java:106)
at org.apache.hadoop.ipc.RemoteException.unwrapRemoteException(RemoteException.java:95)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.getRemoteException(ProtobufUtil.java:329)
at org.apache.hadoop.hbase.client.ScannerCallable.openScanner(ScannerCallable.java:408)
at org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:204)
at org.apache.hadoop.hbase.client.ScannerCallable.call(ScannerCallable.java:65)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithoutRetries(RpcRetryingCaller.java:210)
at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas$RetryingRPC.call(ScannerCallableWithReplicas.java:364)
at org.apache.hadoop.hbase.client.ScannerCallableWithReplicas$RetryingRPC.call(ScannerCallableWithReplicas.java:338)
at org.apache.hadoop.hbase.client.RpcRetryingCaller.callWithRetries(RpcRetryingCaller.java:136)
at org.apache.hadoop.hbase.client.ResultBoundedCompletionService$QueueingFuture.run(ResultBoundedCompletionService.java:65)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.hadoop.hbase.ipc.RemoteWithExtrasException(org.apache.hadoop.hbase.DoNotRetryIOException): org.apache.hadoop.hbase.DoNotRetryIOException: java.lang.reflect.InvocationTargetException
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1478)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toScan(ProtobufUtil.java:993)
at org.apache.hadoop.hbase.regionserver.RSRpcServices.scan(RSRpcServices.java:2396)
at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ClientService$2.callBlockingMethod(ClientProtos.java:33648)
at org.apache.hadoop.hbase.ipc.RpcServer.call(RpcServer.java:2180)
at org.apache.hadoop.hbase.ipc.CallRunner.run(CallRunner.java:112)
at org.apache.hadoop.hbase.ipc.RpcExecutor.consumerLoop(RpcExecutor.java:133)
at org.apache.hadoop.hbase.ipc.RpcExecutor$1.run(RpcExecutor.java:108)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.hadoop.hbase.protobuf.ProtobufUtil.toFilter(ProtobufUtil.java:1474)
... 8 more
Caused by: org.apache.hadoop.hbase.exceptions.DeserializationException: parseFrom called on base Filter, but should be called on derived type
at org.apache.hadoop.hbase.filter.Filter.parseFrom(Filter.java:270)
... 13 more

at org.apache.hadoop.hbase.ipc.RpcClientImpl.call(RpcClientImpl.java:1267)
at org.apache.hadoop.hbase.ipc.AbstractRpcClient.callBlockingMethod(AbstractRpcClient.java:227)
at org.apache.hadoop.hbase.ipc.AbstractRpcClient$BlockingRpcChannelImplementation.callBlockingMethod(AbstractRpcClient.java:336)
at org.apache.hadoop.hbase.protobuf.generated.ClientProtos$ClientService$BlockingStub.scan(ClientProtos.java:34094)
at org.apache.hadoop.hbase.client.ScannerCallable.openScanner(ScannerCallable.java:400)
... 10 more

Can any one please help me with this...

Body:
Just to add a (perhaps important) detail to the answers from Abhishek Kumar above. It seems the serializer toByteArray() and deserializer parseFrom(byte[] rawBytes) must be implemented via Google Protocol Buffers 2. Below is an example implementation.

AFilter.java

// whatever fields you need for the AFilter
long fieldA;
long fieldB;

/**
* Transform this {@code AFilter} instance to a byte array for serialization.
* @return raw bytes of this instance
*/
@Override
public byte[] toByteArray() {
    final FilterProtos.AFilter.Builder builder = FilterProtos.AFilter.newBuilder();
    builder.setFieldA(fieldA);
    builder.setFieldB(fieldB);

    return builder.build().toByteArray();
}

/**
 * De-serialize {@code AFilter} from {@code rawBytes}.
 *
 * @param rawBytes raw bytes of the filter
 * @return AFilter object
 * @throws DeserializationException
 */
public static AFilter parseFrom(final byte[] rawBytes)
        throws DeserializationException {

    try {
        FilterProtos.AFilter proto;
        proto = FilterProtos.AFilter.parseFrom(rawBytes);

        return new AFilter(proto.getFieldA(), proto.getFieldB());
    } catch (InvalidProtocolBufferException ex) {
        throw new DeserializationException(
                ex);
    }
}

Filters.proto

option java_package = "my.java.package";
option java_outer_classname = "FilterProtos";
option java_generic_services = true;
option java_generate_equals_and_hash = true;
option optimize_for = SPEED;

message AFilter{
    required uint64 fieldA = 1;
    required uint64 fieldB = 2;
}


问:
Core Data Query, most recent car per year?
In my model I have a Car entity.

Car
 year
 createDate
 name

I want to run a fetch that returns all most recent cars per year where name is not nil (name can be nil).

So, if I have 3 cars with year 2000 and 5 cars with year 2010, I want to get a total of 2 cars out of the fetch request (the most recent for year 2000 and the most recent for year 2010).

I am not sure how to write the proper predicate to achieve this. I looked in the returnsDistinctResults option, but I am not sure that is the right path go go down and it also said that it only works with NSDictionaryResultType which does not work for me.

What would be the proper query/predicate to get this done?

答:
You would be better off simply running over each record, with an algorithm.

Allowing for your Car class, define the following.

```<code>struct C {
    var year: Int
    var created: Date
    var name: String?
}

var cars = [C(year: 2009, created: Date(), name: nil), C(year: 2009, created: Date(), name: "Green"), C(year: 2010, created: Date(), name: "Green"), C(year: 2010, created: Date(), name: "Orange"), C(year: 2010, created: Date(), name: "Orange")]

var carsPerYear = [Int: [String: Int]]()

for car in cars {
    if let name = car.name {
        var info: [String: Int]? = nil
        if carsPerYear.keys.contains(car.year) {
            info = carsPerYear[car.year]
        } else {
            info  = [String: Int]()
        }
        if !info!.keys.contains(name) {
            info![name] = 0
        }
        info![name] = info![name]! + 1
        carsPerYear[car.year] = info
    }
}

for year in carsPerYear.keys {
    let info = carsPerYear[year]!
    let sorted = info.keys.sorted{ info[$0]! > info[$1]! }
    print(year, sorted.first!)
}
</code>```

Gives output

```<code>2009 Green
2010 Orange
</code>```

Sometimes SQL or CoreData cannot solve the problems easily, it's best to just write sort algorithm.

Body:
You would be better off simply running over each record, with an algorithm.

Allowing for your Car class, define the following.

struct C {
    var year: Int
    var created: Date
    var name: String?
}

var cars = [C(year: 2009, created: Date(), name: nil), C(year: 2009, created: Date(), name: "Green"), C(year: 2010, created: Date(), name: "Green"), C(year: 2010, created: Date(), name: "Orange"), C(year: 2010, created: Date(), name: "Orange")]

var carsPerYear = [Int: [String: Int]]()

for car in cars {
    if let name = car.name {
        var info: [String: Int]? = nil
        if carsPerYear.keys.contains(car.year) {
            info = carsPerYear[car.year]
        } else {
            info  = [String: Int]()
        }
        if !info!.keys.contains(name) {
            info![name] = 0
        }
        info![name] = info![name]! + 1
        carsPerYear[car.year] = info
    }
}

for year in carsPerYear.keys {
    let info = carsPerYear[year]!
    let sorted = info.keys.sorted{ info[$0]! > info[$1]! }
    print(year, sorted.first!)
}

Gives output

2009 Green
2010 Orange

Sometimes SQL or CoreData cannot solve the problems easily, it's best to just write sort algorithm.


问:
Alamofire post request return 404 in Swift
I am going to post a request via alamofire. I can post request with Postman. Response return true (201 code). However when I am try with Alamofire returns 404 code. What's wrong?

My codes:

```<code>     let headers: HTTPHeaders = [
    "Authorization": "Basic xxxxxxxxxxxx",
    "content-type": "application/json"
     ]
        let parameters:[String:Any] = [
        "xxx":123,
        "yyy":"test",
        "zzz":"iphone"
        ]

    Alamofire.request(myUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response -> Void in

        switch response.result {
        case .success:
            print(response.response?.statusCode)

            break
        case .failure(let error):

            print(error)
        }
    }
</code>```

Return this message :

```<code>success {
message = "No HTTP resource was found that matches the request URI 'https://xxxxx/PostErrorFeedBack'.";
</code>```

}

答:
Try this one hope it may help you !!</p>
```<code>let headers = [
    "Authorization": "Basic xxxxxxxxxxxx"
]
let parameters = [

]

Alamofire.request(.POST, "url", parameters: parameters, headers: headers, encoding: .JSON)
        .validate(contentType: ["application/json"])
        .responseJSON { response in
            if response.response?.statusCode == 200 {
                print("Success with JSON: \(response.result.value)")

            }
            else {
                let error = response.result.value as! NSDictionary
                let errorMessage = error.objectForKey("message") as! String
                print(errorMessage)
                failure(errorMessage)
            }

    }
</code>```

Body:
I am going to post a request via alamofire. I can post request with Postman. Response return true (201 code). However when I am try with Alamofire returns 404 code. What's wrong?

My codes:

     let headers: HTTPHeaders = [
    "Authorization": "Basic xxxxxxxxxxxx",
    "content-type": "application/json"
     ]
        let parameters:[String:Any] = [
        "xxx":123,
        "yyy":"test",
        "zzz":"iphone"
        ]

    Alamofire.request(myUrl, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response -> Void in

        switch response.result {
        case .success:
            print(response.response?.statusCode)

            break
        case .failure(let error):

            print(error)
        }
    }

Return this message :

success {
message = "No HTTP resource was found that matches the request URI 'https://xxxxx/PostErrorFeedBack'.";

}

Body:
Try this one hope it may help you !!

let headers = [
    "Authorization": "Basic xxxxxxxxxxxx"
]
let parameters = [

]

Alamofire.request(.POST, "url", parameters: parameters, headers: headers, encoding: .JSON)
        .validate(contentType: ["application/json"])
        .responseJSON { response in
            if response.response?.statusCode == 200 {
                print("Success with JSON: \(response.result.value)")

            }
            else {
                let error = response.result.value as! NSDictionary
                let errorMessage = error.objectForKey("message") as! String
                print(errorMessage)
                failure(errorMessage)
            }

    }

ContentLicense: CC BY-SA 4.0


问:
Post action option for SQL*Loader
In my project, we are using SQL*Loader for loading a set of data. If this load is successful we want to execute another SQL instruction. Does SQL*Loader have any option for that?</p>

答: An alternate approach could be to use an external table instead of SQL Loader. Then you could write the whole logic in PL/SQL.</p>

Title: Post action option for SQL*Loader


问:
document.body not working in IE
I am trying to create a simple on click function, but IE isn't cooperating.
This works when I use it in chrome. When I call this function in IE, the function doesn't execute.
IE version: 11

```<code><script language="JavaScript">
AJS.$(document).ready(function($) {

AJS.$(document.body).on("click", "#Test-button", function() {

    });

});
</script>
</code>```

Thanks in advance.

答:
Making a wild assumtion here.
AJS.$ is your jQuery

```<code>AJS.$(document).find('body').on("click", "#Test-button", function() {
</code>```

Title: document.body not working in IE

Body:
I am trying to create a simple on click function, but IE isn't cooperating.
This works when I use it in chrome. When I call this function in IE, the function doesn't execute.
IE version: 11

Thanks in advance.

Body:
Making a wild assumtion here.
AJS.$ is your jQuery

AJS.$(document).find('body').on("click", "#Test-button", function() {


问:
Dynamodb query operations
Is it possible to work with "OR" , "AND " Query operations in DynamoDB?

I need to know if DynamoDB has something like "where fname = xxxx OR lname = xxxx" from SQL queries? in Rails

Thanks.

答:
Although there is no such thing as "OR", "AND", but you can still simulate sql queries using scan and filterexpression.

But remember that if you are using scan, then it means whole table will be fetched and then processed, also scan doesn't always scan whole table in one iteration. so you might miss out some items. so this method is generally avoided as it is very costly. but here is piece of python3 code using boto3 api that can simulate the sql query you want

```<code>response = table.scan(
FilterExpression=Attr('fname').eq('xxxxx') | Attr('lname').eq('xxxxx'))
</code>```

filterexpression also different operatiors like &,~

Title: Dynamodb query operations

Body:
Although there is no such thing as "OR", "AND", but you can still simulate sql queries using scan and filterexpression.

But remember that if you are using scan, then it means whole table will be fetched and then processed, also scan doesn't always scan whole table in one iteration. so you might miss out some items. so this method is generally avoided as it is very costly. but here is piece of python3 code using boto3 api that can simulate the sql query you want

response = table.scan(
FilterExpression=Attr('fname').eq('xxxxx') | Attr('lname').eq('xxxxx'))

filterexpression also different operatiors like &,~


问:
C++ printing a function's result?
why is that when I print a result from my function, it prints out 0? I tried using a prototype, and followed an example from my teacher, but no dice. Pretty lost here. </p>

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

double energie_cinetique(double m, double v) {
    double resultat;
     resultat = 1 / 2 * m * (v * v);
    return resultat;
}

int main(void) {
    double reponse;
    reponse = energie_cinetique(10, 5);
    printf("Energie pour m=10 kg et v=5 m/s: %d", reponse);
    system("pause");
    return EXIT_SUCCESS;
}
</code>```

答:
Integer division with 1/2 = 0 so your result will be zero.

Change the half to 0.5 and you should be golden for the math part (also, multiplication is faster so use it instead of division when possible).

%d in the printf is for int types, use %f instead for a double.

After that it should work.

Title: C++ printing a function's result?

Body:
why is that when I print a result from my function, it prints out 0? I tried using a prototype, and followed an example from my teacher, but no dice. Pretty lost here.

#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

double energie_cinetique(double m, double v) {
    double resultat;
     resultat = 1 / 2 * m * (v * v);
    return resultat;
}

int main(void) {
    double reponse;
    reponse = energie_cinetique(10, 5);
    printf("Energie pour m=10 kg et v=5 m/s: %d", reponse);
    system("pause");
    return EXIT_SUCCESS;
}


问:
How to format a phone number using PhoneNumberUtils?
How can I format a phone number using PhoneNumberUtils?

E.g.: 1234567890 → (123) 456-7890

答:
Standalone solution for format raw phone number, if you don`t know your country and need support on pre-lollipop.</p>

```<code>fun formatNumberCompat(rawPhone: String?, countryIso: String = ""): String {
    if (rawPhone == null) return ""

    var countryName = countryIso
    if (countryName.isBlank()) {
        countryName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Resources.getSystem().configuration.locales[0].country
        } else {
            Resources.getSystem().configuration.locale.country
        }
    }

    return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        PhoneNumberUtils.formatNumber(rawPhone)
    } else {
        PhoneNumberUtils.formatNumber(rawPhone, countryName)
    }
}
</code>```

Body:
Standalone solution for format raw phone number, if you don`t know your country and need support on pre-lollipop.

fun formatNumberCompat(rawPhone: String?, countryIso: String = ""): String {
    if (rawPhone == null) return ""

    var countryName = countryIso
    if (countryName.isBlank()) {
        countryName = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Resources.getSystem().configuration.locales[0].country
        } else {
            Resources.getSystem().configuration.locale.country
        }
    }

    return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        PhoneNumberUtils.formatNumber(rawPhone)
    } else {
        PhoneNumberUtils.formatNumber(rawPhone, countryName)
    }
}


问:
c++ multithread optimization
in my code I have 2/4 threads performing montecarlo simulations. Each of them runs a number of experiments and they all collect the results into a stl vector.
My question is this: suppose each thread runs 1000 experiments sequentially. Is is better to store the result into the shared vector one at the time, or every once in a while? If they wait until they have some consistent amount of data, writing into the vector will take longer, so I'm not sure whether the second solution is necessarily better than the first one.

PS each experiment is numerical computation, so no IO operations.

Thanks

答:
a singly linked list may be a better choice than vector here.

If there is only one thread reading and one thread writing to a fifo .. you don't need any synchronization . The trick is to keep at least one 'dummy' element always in the list, and fifo is empty if head == tail . The head and tail pointers can be manipulated for push and pop, such that there is no need for synchronization..

Using this .. you can make several Q's .. which will not need any synchronization
If new/delete is taking time .. you can have Q's to hold reusable elements.

best of luck .

remember .. Exactly one reader, and Exactly one writer .. no more, no less .
the trick is createa LOT of Q's like this , Q to recycle objects also .. and
you'll not need any thread synchronization stuff ...

If your Q's do run empty .. just a sleep() / wakeup() functionality is needed.

and in case i haven't already said .. Exactly one reader, and Exactly one writer.

Title: c++ multithread optimization


问:
Calculate remaining time in handler
I've got function which waits "syncingIntervalsInt" amount of time and then does the code. How can I create countdown? For example when syncingIntervalsInt is set to 10 seconds, I want to set one TextView to this countdown 10,9,8 etc.

Here is my function:

```<code>public void refreshRecycler()
{
    countingTillSync = syncingIntervalsInt;

    timerHandler = new Handler();

    timerRunnable = new Runnable() {

        @Override
        public void run() {

           //some code here
           countingTillSync--;

        }

        timerHandler.postDelayed(this, syncingIntervalsInt*1000); //run every second
    }

    timerHandler.postDelayed(timerRunnable, syncingIntervalsInt*1000); //Start timer after 1 sec

}
</code>```

This code above only decrements after syncingIntervalsInt*1000 amount of time which is not what I expect.

答:
You can try this .

1.Add CountDownTimerUtils

```<code>public class CountDownTimerUtils extends CountDownTimer {

private TextView mTextView;

/**
 * @param textView          The TextView
 * @param millisInFuture    The number of millis in the future from the call
 *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
 *                          is called.
 * @param countDownInterval The interval along the way to receiver
 *                          {@link #onTick(long)} callbacks.
 */
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    this.mTextView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
    mTextView.setText(millisUntilFinished / 1000 + "sec");
    mTextView.setClickable(false);
}
@Override
public void onFinish() {
    mTextView.setText("retry");
    mTextView.setClickable(true);
    mTextView.setFocusable(true);
}
}
</code>```

2.Set in your code like this .

```<code>// 1 param yourTextView was TextView you want to set
// 2 param  10 * 1000 was the number of millis in the future from the call
// 3 param 1000 was the interval along the way to receiver
CountDownTimerUtils mTimerUtils = new CountDownTimerUtils(yourTextView, 10 * 1000, 1000);
mTimerUtils.start();
</code>```

Title: Calculate remaining time in handler

Body:
I've got function which waits "syncingIntervalsInt" amount of time and then does the code. How can I create countdown? For example when syncingIntervalsInt is set to 10 seconds, I want to set one TextView to this countdown 10,9,8 etc.

Here is my function:

public void refreshRecycler()
{
    countingTillSync = syncingIntervalsInt;

    timerHandler = new Handler();

    timerRunnable = new Runnable() {

        @Override
        public void run() {

           //some code here
           countingTillSync--;

        }

        timerHandler.postDelayed(this, syncingIntervalsInt*1000); //run every second
    }

    timerHandler.postDelayed(timerRunnable, syncingIntervalsInt*1000); //Start timer after 1 sec

}

This code above only decrements after syncingIntervalsInt*1000 amount of time which is not what I expect.

Body:
You can try this .

1.Add CountDownTimerUtils

public class CountDownTimerUtils extends CountDownTimer {

private TextView mTextView;

/**
 * @param textView          The TextView
 * @param millisInFuture    The number of millis in the future from the call
 *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
 *                          is called.
 * @param countDownInterval The interval along the way to receiver
 *                          {@link #onTick(long)} callbacks.
 */
public CountDownTimerUtils(TextView textView, long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    this.mTextView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
    mTextView.setText(millisUntilFinished / 1000 + "sec");
    mTextView.setClickable(false);
}
@Override
public void onFinish() {
    mTextView.setText("retry");
    mTextView.setClickable(true);
    mTextView.setFocusable(true);
}
}

2.Set in your code like this .

// 1 param yourTextView was TextView you want to set
// 2 param  10 * 1000 was the number of millis in the future from the call
// 3 param 1000 was the interval along the way to receiver
CountDownTimerUtils mTimerUtils = new CountDownTimerUtils(yourTextView, 10 * 1000, 1000);
mTimerUtils.start();


问:
Scala Spark - convert DenseVector with nulls to SparseVector
I have quite big vector of around 20k Doubles most of which are null. Is it possible to convert it to the SparseVector and how?</p>

答:
org.apache.spark.ml.linalg.Vector provides toSparse and toDense methods which can be used to change the representation.

However it shouldn't possible to have Vector (or any other collection like object) of scala.Double containing nulls in the first place.


问:
Which one is better about PHP class for query?
I have PHP class that contain function for query data from database. The first one is

```<code>class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    $this->var1 = $row['var1'];
    $this->var2 = $row['var2'];
  }

}
</code>```

and another on is

```<code>class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    return $row;
  }

}
</code>```

two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.

I would like to know about performance of two class, which one is better. and which one is good for programming or any idea?

Regards.

答:
```<code>class x{

  public $row;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    this->$row = mysq;_fetch_assoc($sql);

  }

}
</code>```

My suggestion is this. You have encapsulation incorprated properly and its dynamic accomodating future requirements too.

Perhaps you can add getter function also.

Body:
I have PHP class that contain function for query data from database. The first one is

class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    $this->var1 = $row['var1'];
    $this->var2 = $row['var2'];
  }

}

and another on is

class x{

  public $var1;
  public $var2;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    $row = mysq;_fetch_assoc($sql);
    return $row;
  }

}

two class has some difference on function getX(). The first class put data from database to class variables but the second one return whole data from database via array.

I would like to know about performance of two class, which one is better. and which one is good for programming or any idea?

Regards.

Body:
class x{

  public $row;

  function __construct(){ }

  function getX($primkey){
    $sql = mysql_qyery("SELECT * FROM x_table WHERE primkey='$primkey'");
    this->$row = mysq;_fetch_assoc($sql);

  }

}

My suggestion is this. You have encapsulation incorprated properly and its dynamic accomodating future requirements too.

Perhaps you can add getter function also.


问:
Django permission belongs to group, but user on that group has no group's permission
I decided to not use django-guardian because If my customer delete/create Group I have to add more overhead on my ModelManager to transfer the existing permissions to new group. Therefore let the instances got filtered by filter_queryset through Django REST is fine for my case.

FailedTestCase:

```<code>from django.contrib.auth.models import User

from poinkbackend.apps.companies.models import Company
from poinkbackend.apps.roles.models import Role
from poinkbackend.apps.userroles.models import UserRole
from poinkbackend.apps.commons.tests import companies, userprofiles, branches

def test_support_view_userprofile(companies, userprofiles):
    company = Company.objects.get(name='Singh')
    support = Role.objects.add_support('firstsupport', company)
    user = User.objects.get(username='notty')
    UserRole.objects.create(user=user, role=support)
    user.refresh_from_db()
    import pdb; pdb.set_trace()
    assert True is user.has_perm('view_userprofile')
</code>```

```<code>-> assert True is user.has_perm('view_userprofile')
(Pdb) user.groups.first()
<Group: firstsupport-Singh>
(Pdb) g1 = user.groups.first()
(Pdb) g1.permissions.all()
<QuerySet [<Permission: userprofiles | user profile | View UserProfile>]>
(Pdb) user.has_perm('view_userprofile')
False
</code>```

Question:

Where am I wrong?

Update 16 Nov 2017 10:30 GMT+7 Add 4th url
Gists:

Company : https://gist.github.com/elcolie/684ba34391d0a94df7ca98855cea765b

Role : https://gist.github.com/elcolie/64a3a3daf22240b2072e113eb10164e2

UserRole: https://gist.github.com/elcolie/d28e7fcf54334a9f13df5fff1b7d9fe0

BusinessPermisson: https://gist.github.com/elcolie/bbeb00f41db0c7884cee34c6bccaf5f9

References:

Django user has_perm returning false even though group has permission

Django user not getting the assigned group's permissions

django group permission

答:
Although I found the root cause of the error. I have updated my question according to @Adam Dobrawy comment.

The problem is I mixed up the command of guardian. django-guardign syntax can use without app_label in front of it. In my case it is userprofiles

I have to replace the line user.has_perm('view_userprofile') with user.has_perm('userprofiles.view_userprofile')

Again. Thank you very much Adam for your time and effort reading my question.

Body:
I decided to not use django-guardian because If my customer delete/create Group I have to add more overhead on my ModelManager to transfer the existing permissions to new group. Therefore let the instances got filtered by filter_queryset through Django REST is fine for my case.

FailedTestCase:

from django.contrib.auth.models import User

from poinkbackend.apps.companies.models import Company
from poinkbackend.apps.roles.models import Role
from poinkbackend.apps.userroles.models import UserRole
from poinkbackend.apps.commons.tests import companies, userprofiles, branches

def test_support_view_userprofile(companies, userprofiles):
    company = Company.objects.get(name='Singh')
    support = Role.objects.add_support('firstsupport', company)
    user = User.objects.get(username='notty')
    UserRole.objects.create(user=user, role=support)
    user.refresh_from_db()
    import pdb; pdb.set_trace()
    assert True is user.has_perm('view_userprofile')

-> assert True is user.has_perm('view_userprofile')
(Pdb) user.groups.first()
<Group: firstsupport-Singh>
(Pdb) g1 = user.groups.first()
(Pdb) g1.permissions.all()
<QuerySet [<Permission: userprofiles | user profile | View UserProfile>]>
(Pdb) user.has_perm('view_userprofile')
False

Question:

Where am I wrong?

Update 16 Nov 2017 10:30 GMT+7 Add 4th url
Gists:

Company : https://gist.github.com/elcolie/684ba34391d0a94df7ca98855cea765b

Role : https://gist.github.com/elcolie/64a3a3daf22240b2072e113eb10164e2

UserRole: https://gist.github.com/elcolie/d28e7fcf54334a9f13df5fff1b7d9fe0

BusinessPermisson: https://gist.github.com/elcolie/bbeb00f41db0c7884cee34c6bccaf5f9

References:

Django user has_perm returning false even though group has permission

Django user not getting the assigned group's permissions

django group permission


问:
How to change app display name in Xcode 8 to add a space
I am trying to put a space in my app name (standalone sticker pack) in Xcode 8. The solutions I've seen on here are to change the Product Name (in packaging) or to change the "Bundle Display Name".

I've changed the product name and that hasn't worked (I cleaned, rebuilt, reset content and settings in simulator and logged out of xcode, logged back in and rebuilt app).

I can't see "Bundle Display Name" anywhere. Should I add it and if so, how do I do that?

I've read the thread How to change the name of an iOS app? and done the suggestions, but it's still showing in simulator and testflight without the space. Have I missed something?

答:
Change the Bundle Display Name (CFBundleDisplayName) in your Info.plist file

Check if you have any localization (InfoPlist.strings) files, and change the corresponding CFBundleDisplayName values in those files to the localized values.

That's it.


问:
java recursion a to user defined input
How do you stop recursion from printing A to lowercase letters?
 Expected output(
 input d returns abcd
 input D returns ABCD)

```<code>Public static void main(String[] args){
    printLettersForward('D');
    System.out.println();
    printLettersForward('d');
    System.out.println()
}

public static void printLettersForward(char c) {

    if (c >= 'a'||c >= 'z') {
        printLettersForward((char) (c - 1));
        System.out.print(c+" ");

    }else if(c >= 'A'||c >= 'Z') {
        printLettersForward((char) (c - 1));
        System.out.print(c+" ");

    }else {
        System.out.println();
    }

}
</code>```

output:
A B C D

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d

let me know how to ask better questions.

答:
Your conditions are incorrect.

Fix as follows:

```<code>public static void main(String[] args) {
    printLettersForward('D');
    System.out.println();
    printLettersForward('d');
    System.out.println();
}

public static void printLettersForward(char c) {
    if (c >= 'a' && c <= 'z') {
        printLettersForward((char) (c - 1));
        System.out.print(c + " ");
    } else if (c >= 'A' && c <= 'Z') {
        printLettersForward((char) (c - 1));
        System.out.print(c + " ");
    } else {
        System.out.println();
    }
}
</code>```

Title: java recursion a to user defined input

Body:
How do you stop recursion from printing A to lowercase letters?
 Expected output(
 input d returns abcd
 input D returns ABCD)

Public static void main(String[] args){
    printLettersForward('D');
    System.out.println();
    printLettersForward('d');
    System.out.println()
}

public static void printLettersForward(char c) {

    if (c >= 'a'||c >= 'z') {
        printLettersForward((char) (c - 1));
        System.out.print(c+" ");

    }else if(c >= 'A'||c >= 'Z') {
        printLettersForward((char) (c - 1));
        System.out.print(c+" ");

    }else {
        System.out.println();
    }

}

output:
A B C D

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z [ \ ] ^ _ ` a b c d

let me know how to ask better questions.

Body:
Your conditions are incorrect.

Fix as follows:

public static void main(String[] args) {
    printLettersForward('D');
    System.out.println();
    printLettersForward('d');
    System.out.println();
}

public static void printLettersForward(char c) {
    if (c >= 'a' && c <= 'z') {
        printLettersForward((char) (c - 1));
        System.out.print(c + " ");
    } else if (c >= 'A' && c <= 'Z') {
        printLettersForward((char) (c - 1));
        System.out.print(c + " ");
    } else {
        System.out.println();
    }
}


问:
How does C++ char distinguish ASCII and UNICODE
I am currently programming with c++ a program that handles both alphabets and Korean characters.

However I learned that the size of char in c++ is only 1 bytes. This meant that in order to handle foreign characters or UNICODE, it needs to use two chars for one character.

```<code>string s = string("a가b나c다");
cout<< s.length();
</code>```

prints 9

but my question is how does the c++ execution distinguish between the two different type of characters?

for example if I make a char array the size of 9, How does it know whether its 9 ascii characters or 4 unicode + 1 ascii ??

and then i figured out this :

```<code>    char c;
    int a;
    char* cp = "가나다라마바사아";
    for (int i = 0; i < 20; i++) {
        c = a = cp[i];
        cout << "\n c val : " << c;
        cout << "\n a val : " << a;
    }
</code>```

ONLY prints out negative values for a.

```<code> c val :
 a val : -80
 c val :
 a val : -95
 c val :
 a val : -77
 c val :
 a val : -86
 c val :
 a val : -76
 c val :
 a val : -39
</code>```

Which i can infer that for non ascii characters it only uses negative values? but isn't this quite a waste ?

My question in summary: Do c++ distinguish ascii chars and unicode chars only by looking if they are negative ?

Answer in summary : the parser decides whether to consider 1~4 char as 1 glyph by looking up the first few bits of the char, so to some extent my assumption was valid.

答:
how does the c++ execution distinguish between the two different type of characters?

It doesn't.  The compiler decided to encode your string as Unicode at compile-time.  In this case, it appears to have chosen UTF-8.

How does it know whether its 9 ascii characters or 4 unicode + 1 ascii ??

Again, it doesn't.  Your string contains 9 char values (excluding any termination character).  The number of actual "characters" (or "glyphs") that represents can only be determined by parsing the string.  If you know it's UTF-8, you parse it accordingly.

Which i can infer that for non ascii characters it only uses negative values? but isn't this quite a waste ?

No.  Well, sort of.  If you're interested, read a primer on Unicode (specifically UTF-8).  You could read the actual standard, but it's enormous.  Wikipedia should be sufficient for a better understanding.

You'll see that multi-byte strings have the high-bit set.  This makes it possible to parse multi-byte values correctly.  It's not really that wasteful, because the standard is arranged such that wider encodings are generally reserved for less common values.

The reason it output negatives is that you are using signed char types.  If you cast as unsigned, you'll see the values are simply greater than 127.  When you read more about how UTF-8 is encoded, you'll understand why.

My question in summary: Do c++ distinguish ascii chars and unicode chars only by looking if they are negative ?

My answer in summary: No.  "Negative" is a numeric system.  You are probably accustomed to 2's-complement.  Encode, or encode not: there is no "negative".

Body:
I am currently programming with c++ a program that handles both alphabets and Korean characters.

However I learned that the size of char in c++ is only 1 bytes. This meant that in order to handle foreign characters or UNICODE, it needs to use two chars for one character.

string s = string("a가b나c다");
cout<< s.length();

prints 9

but my question is how does the c++ execution distinguish between the two different type of characters?

for example if I make a char array the size of 9, How does it know whether its 9 ascii characters or 4 unicode + 1 ascii ??

and then i figured out this :

    char c;
    int a;
    char* cp = "가나다라마바사아";
    for (int i = 0; i < 20; i++) {
        c = a = cp[i];
        cout << "\n c val : " << c;
        cout << "\n a val : " << a;
    }

ONLY prints out negative values for a.

 c val :
 a val : -80
 c val :
 a val : -95
 c val :
 a val : -77
 c val :
 a val : -86
 c val :
 a val : -76
 c val :
 a val : -39

Which i can infer that for non ascii characters it only uses negative values? but isn't this quite a waste ?

My question in summary: Do c++ distinguish ascii chars and unicode chars only by looking if they are negative ?

Answer in summary : the parser decides whether to consider 1~4 char as 1 glyph by looking up the first few bits of the char, so to some extent my assumption was valid.


问:
Image array. Uncaught TypeError: Cannot set property 'src' of null
First time messing with arrays. Trying to cycle through an image array, getting "Uncaught TypeError: Cannot set property 'src' of null" when clicking the next button. I thought it would be something simple like an id not matching up, but I can't spot any issues like that.

var target = document.getElementById('target');

var counter = 0;

var imageArray = [
 "megatron.png",
 "starscream.jpg",
 "soundwave.jpg",
 "shockwave.jpg",
 "devastator.jpg",
 "astrotrain.jpg",
 "blitzwing.jpg",
 "thrust.jpg",
 "rumble.png",
 "ravage.jpg",
 "laserbeak.jpg",
 "reflector.jpg"
];

function next() {
 counter = counter + 1;
 if (counter > imageArray.length -1) {
  counter = 0;
 }
 target.src = imageArray[counter];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code></!DOCTYPE html>
<html>
<head>
 <title>Image Array</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="./image-array.css">
 <script src="image-array.js"></script>
</head>
<body>
<h1 class="center">Image Array</h1>
<div id="page" class="center">
 <div id="socket" class="center">
  <img src="megatron.png" id="target">
 </div>
 <div id="switchplate" class="center">
   <button onclick="next()" id="next">Next</button>
 </div>
</div>
</body>
</html></code>```

答:
The issue is because of the loading of  is in the head tag.

When the above script is loaded it will run through this statement

```<code>var target = document.getElementById('target');
</code>```

At that time the DOM is not ready and there is no element with id target

So it is throwing the error.

Remove the script tag and add it before closing body tag

```<code><body>
  // rest of the DOM
<script src="image-array.js"></script>
</body>
</code>```

Body:
First time messing with arrays. Trying to cycle through an image array, getting "Uncaught TypeError: Cannot set property 'src' of null" when clicking the next button. I thought it would be something simple like an id not matching up, but I can't spot any issues like that.

var target = document.getElementById('target');

var counter = 0;

var imageArray = [
 "megatron.png",
 "starscream.jpg",
 "soundwave.jpg",
 "shockwave.jpg",
 "devastator.jpg",
 "astrotrain.jpg",
 "blitzwing.jpg",
 "thrust.jpg",
 "rumble.png",
 "ravage.jpg",
 "laserbeak.jpg",
 "reflector.jpg"
];

function next() {
 counter = counter + 1;
 if (counter > imageArray.length -1) {
  counter = 0;
 }
 target.src = imageArray[counter];
}

</!DOCTYPE html>

 <title>Image Array</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <meta charset="utf-8">
 <link rel="stylesheet" type="text/css" href="./image-array.css">

Image Array

   <button onclick="next()" id="next">Next</button>

Body:
The issue is because of the loading of <script src="image-array.js"></script> is in the head tag.

When the above script is loaded it will run through this statement

var target = document.getElementById('target');

At that time the DOM is not ready and there is no element with id target

So it is throwing the error.

Remove the script tag and add it before closing body tag

<body>
  // rest of the DOM
<script src="image-array.js"></script>
</body>


问:
FileUpload not working in update panel(modal popup extender)
i am developing web application and contain modal popup extender in which update panel made and it contain file upload control but file upload control not working in it.

This is my modal popup which contain fileupload control

and my modal popup source code

```<code> <cc1:ModalPopupExtender ID="AddNews" runat="server" PopupControlID="pnlPopUp1" BehaviorID="AddNews"
    TargetControlID="btnNews" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
<asp:Panel ID="pnlPopUp1" runat="server" CssClass="modalPopup" Height="450px" Width="660px"
    Style="display:none; z-index: 100000">

    <asp:UpdatePanel ID="Upanel1" runat="server">

        <ContentTemplate>
            <div>
                <table cellpadding="0" cellspacing="0" width="100%">
                    <tr style="height: 35px;">
                        <td style="width:170px">
                        </td>
                        <td style="text-align: center">
                            <h1>
                                Add News</h1>
                        </td>
                        <td style="text-align: right">
                            <asp:ImageButton ID="ImageButton2" AlternateText="Close Image" runat="server" ImageUrl="~/images/delete_32i.GIF"
                                OnClientClick="return closePopup('News')" />
                        </td>
                    </tr>
                    <tr>
                    <td colspan="2">
                    <asp:Label ID="lblAddNewsError" runat="server" Text="" ForeColor="Red"></asp:Label>
                    </td>
                    </tr>
                    <tr>
                    <td>News Title:</td><td>
                        <asp:TextBox ID="txtNewTitle" Width="250px" runat="server" MaxLength="500"></asp:TextBox>
                    </td><td>
                            <asp:RequiredFieldValidator ID="rfvNewsTitle" runat="server"
                                ControlToValidate="txtNewTitle" ErrorMessage="*" ToolTip="Enter news title"
                                ValidationGroup="AddNews"></asp:RequiredFieldValidator>
                        </td>
                    </tr>
                    <tr>
                    <td>Upload News Video</td><td>
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    </td><td><asp:RegularExpressionValidator ID="RegularExpressionValidator1"
                                runat="server" ControlToValidate="FileUpload1"
                                ErrorMessage="Invalid video File"
                                ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.avi|.AVI|.wmv|.WMV|.flv|.FLV|.mpg|.MPG|.mp4|.MP4)$"
                                ToolTip="Only allow avi, wmv, flv, mpg, mp4 formats video files"
                                ValidationGroup="AddNews"></asp:RegularExpressionValidator></td>
                    </tr>
                    <tr style="height: 5px">
                        <td>
                        </td>
                    </tr>
                </table>
                 <div>
                <table cellpadding="0" cellspacing="0" width="100%">
                    <tr>
                        <td style="width: 675px">
                            <FCKeditorV2:FCKeditor ID="FCKAddNewsContent" basepath="~/fckeditor/" runat="server" Height="300px"></FCKeditorV2:FCKeditor>
                        </td>
                        <td valign="top">

                        </td>
                    </tr>
                    <tr>
                    <td style="text-align:right">
                        <asp:Button ID="btnAddNews" runat="server" Text="Add News"
                            onclick="btnAddNews_Click" ValidationGroup="AddNews" />
                                <asp:Button ID="btnClose"
                            runat="server" Text="Close" OnClientClick="return closePopup('News')"
                            CausesValidation="False" /></td><td></td>
                    </tr>
                    </table>
                    </div>
            </div>

        </ContentTemplate>
        <Triggers>
        <asp:PostBackTrigger ControlID="btnAddNews" />
        </Triggers>
    </asp:UpdatePanel>
</asp:Panel>
</code>```

as you see my one button also mentioned in postback trigger as i click on this button the result which i got is

can anyone help me out from this problem.

答:
You can set Triggers on update panel. After that you can get file at server side.

```<code>    <Triggers>
        <ajax:PostBackTrigger ControlID="btnAddNews" />
    </Triggers>
</code>```

Hope it will help.

Body:
i am developing web application and contain modal popup extender in which update panel made and it contain file upload control but file upload control not working in it.

This is my modal popup which contain fileupload control

and my modal popup source code

 <cc1:ModalPopupExtender ID="AddNews" runat="server" PopupControlID="pnlPopUp1" BehaviorID="AddNews"
    TargetControlID="btnNews" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
<asp:Panel ID="pnlPopUp1" runat="server" CssClass="modalPopup" Height="450px" Width="660px"
    Style="display:none; z-index: 100000">

    <asp:UpdatePanel ID="Upanel1" runat="server">

        <ContentTemplate>

                                Add News

                            <asp:ImageButton ID="ImageButton2" AlternateText="Close Image" runat="server" ImageUrl="~/images/delete_32i.GIF"
                                OnClientClick="return closePopup('News')" />

                    <asp:Label ID="lblAddNewsError" runat="server" Text="" ForeColor="Red"></asp:Label>

                    News Title:
                        <asp:TextBox ID="txtNewTitle" Width="250px" runat="server" MaxLength="500"></asp:TextBox>

                            <asp:RequiredFieldValidator ID="rfvNewsTitle" runat="server"
                                ControlToValidate="txtNewTitle" ErrorMessage="*" ToolTip="Enter news title"
                                ValidationGroup="AddNews"></asp:RequiredFieldValidator>

                    Upload News Video
                        <asp:FileUpload ID="FileUpload1" runat="server" />
                    	<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
                                runat="server" ControlToValidate="FileUpload1"
                                ErrorMessage="Invalid video File"
                                ValidationExpression="^([0-9a-zA-Z_\-~ :\\])+(.avi|.AVI|.wmv|.WMV|.flv|.FLV|.mpg|.MPG|.mp4|.MP4)$"
                                ToolTip="Only allow avi, wmv, flv, mpg, mp4 formats video files"
                                ValidationGroup="AddNews"></asp:RegularExpressionValidator>

                            <FCKeditorV2:FCKeditor ID="FCKAddNewsContent" basepath="~/fckeditor/" runat="server" Height="300px"></FCKeditorV2:FCKeditor>

                        <asp:Button ID="btnAddNews" runat="server" Text="Add News"
                            onclick="btnAddNews_Click" ValidationGroup="AddNews" />
                                <asp:Button ID="btnClose"
                            runat="server" Text="Close" OnClientClick="return closePopup('News')"
                            CausesValidation="False" />

        </ContentTemplate>
        <Triggers>
        <asp:PostBackTrigger ControlID="btnAddNews" />
        </Triggers>
    </asp:UpdatePanel>
</asp:Panel>

as you see my one button also mentioned in postback trigger as i click on this button the result which i got is

can anyone help me out from this problem.

Body:
You can set Triggers on update panel. After that you can get file at server side.

    <Triggers>
        <ajax:PostBackTrigger ControlID="btnAddNews" />
    </Triggers>

Hope it will help.


问:
Package Manager Console stopped working in Visual Studo
Yesterday Package Management Console was working fine.
Today when I open it I receive the error

File C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\PROFESSIONAL\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\NUGET\Modules\NuGet\profile.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.

I went to the Microsoft link but I have not changed anything with Powershell.
What happened and how do I fix it?

答: Restarting Visual Studio seemed to fix it.</p>