问:
How to get image file size in Swift?
I am using

```<code>UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate
</code>```

these delegates for choosing image from my gallery or my camera. So, how can I get image file size after choosing an image?

I want to use this:

```<code>let filePath = "your path here"
    var fileSize : UInt64 = 0

    do {
        let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)

        if let _attr = attr {
            fileSize = _attr.fileSize();
            print(fileSize)
        }
    } catch {
    }
</code>```

but here I need a path, but how can I get without a path, just by image file?

答:
Swift 3/4:

```<code>if let imageData = UIImagePNGRepresentation(image) {
     let bytes = imageData.count
     let kB = Double(bytes) / 1000.0 // Note the difference
     let KB = Double(bytes) / 1024.0 // Note the difference
}
</code>```

Please note the difference between kB and KB. Answering here because in my case we had an issue while we considered kilobyte as 1024 bytes but server side considered it as 1000 bytes which caused an issue. Link to learn more.

PS. Almost sure you'll go with  kB (1000).

Title: How to get image file size in Swift?

Body:
I am using

UIImagePickerControllerDelegate,
UINavigationControllerDelegate,
UIPopoverControllerDelegate

these delegates for choosing image from my gallery or my camera. So, how can I get image file size after choosing an image?

I want to use this:

let filePath = "your path here"
    var fileSize : UInt64 = 0

    do {
        let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(filePath)

        if let _attr = attr {
            fileSize = _attr.fileSize();
            print(fileSize)
        }
    } catch {
    }

but here I need a path, but how can I get without a path, just by image file?

Body:
Swift 3/4:

if let imageData = UIImagePNGRepresentation(image) {
     let bytes = imageData.count
     let kB = Double(bytes) / 1000.0 // Note the difference
     let KB = Double(bytes) / 1024.0 // Note the difference
}

Please note the difference between kB and KB. Answering here because in my case we had an issue while we considered kilobyte as 1024 bytes but server side considered it as 1000 bytes which caused an issue. Link to learn more.

PS. Almost sure you'll go with  kB (1000).


来源: stackexchange

问:
Back Button for "Previous Page"
Is there a way to set the onClick to return to the previous page, rather than a specific page?

I have a print friendly page that is linked to by multiple pages. It would be nice if when users click "Back" they are returned to the page they just came from.

答:
Absolutely, here is a function that you can add to your client script file and call from any widget event handler:

/**
 * Navigates user to a previous page.
 */
function goBack() {
  window.history.back();
}
```

ContentLicense: CC BY-SA 3.0

Title: Back Button for "Previous Page"


问:
Dictionary initialization syntax
```<code>def __init__(self, devices, queue):
    '''
    '''
    self.devices = devices
    self.queue = queue

    values = {k:0 for k in devices.keys()}
    values[0xbeef] = len(values) # the number of devices
    super(CallbackDataBlock, self).__init__(values)
</code>```

Can someone help me explain the following two lines:

values = {k:0 for k in devices.keys()}

What does k:0 do?

values[0xbeef] = len(values) # the number of devices

Does this mean that new item {0xbeef: length} is appended in the dict?

答:
in python documentation you can see List Comprehensions

this pattern is important :

```<code>expression  for  item  in  list  if  conditional else
</code>```

or for simple usage :

```<code>expression  for  item  in  list
</code>```

in list data type we can use :

```<code>list = [0,1,2,3,4,5]
a = [x for x in list]
print (a)
</code>```

printed :

```<code>[1,2,3,4,5]
</code>```

and we have :

```<code>a = [x*2 for x in list]
print (a)
</code>```

printed :

```<code>[2,4,6,8,10]
</code>```

and for dictionary

in dictionary we have this syntax:

```<code>{key1:value1, key2:value2, . . .}
</code>```

and example :

```<code>list = [0,1,2,3,4,5]
d = [k:0 for k in list]
print (d)
</code>```

in example k:0 maens : put 0 for value of each k

printed :

```<code>{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
</code>```

one more thing :

python dictionary have to Helpful method:dict.keys(),dict.values()

when we use dict.keys, python return a list of dict's keys

```<code>d = {"name":"sam", "job":"programer", "salary":"25000"}
print(d.keys())
print(d.values())
</code>```

printed :

```<code>expression  for  item  in  list
</code>```0

for add a new object in a dictionary we use :

```<code>expression  for  item  in  list
</code>```1

for example :

```<code>expression  for  item  in  list
</code>```2

printed :

```<code>'mary'
</code>```

now your answer :

in your code

1) k:0 maens : put 0 for value of each k

2) 0xbeef is a hex code == 48879 in decimal

```<code>    values[48879] = len(values)
</code>```

its fill by length of list.

Title: Dictionary initialization syntax

Body:
def __init__(self, devices, queue):
    '''
    '''
    self.devices = devices
    self.queue = queue

    values = {k:0 for k in devices.keys()}
    values[0xbeef] = len(values) # the number of devices
    super(CallbackDataBlock, self).__init__(values)

Can someone help me explain the following two lines:

values = {k:0 for k in devices.keys()}

What does k:0 do?

values[0xbeef] = len(values) # the number of devices

Does this mean that new item {0xbeef: length} is appended in the dict?

Body:
in python documentation you can see List Comprehensions

this pattern is important :

expression  for  item  in  list  if  conditional else

or for simple usage :

expression  for  item  in  list

in list data type we can use :

list = [0,1,2,3,4,5]
a = [x for x in list]
print (a)

printed :

[1,2,3,4,5]

and we have :

a = [x*2 for x in list]
print (a)

printed :

[2,4,6,8,10]

and for dictionary

in dictionary we have this syntax:

{key1:value1, key2:value2, . . .}

and example :

list = [0,1,2,3,4,5]
d = [k:0 for k in list]
print (d)

in example k:0 maens : put 0 for value of each k

printed :

{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}

one more thing :

python dictionary have to Helpful method:dict.keys(),dict.values()

when we use dict.keys, python return a list of dict's keys

d = {"name":"sam", "job":"programer", "salary":"25000"}
print(d.keys())
print(d.values())

printed :

['name','job','salary']
['sam','programer','25000']

for add a new object in a dictionary we use :

d[newkey]= newValue

for example :

d[10] = 'mary'
print(d[10])

printed :

'mary'

now your answer :

in your code

1) k:0 maens : put 0 for value of each k

2) 0xbeef is a hex code == 48879 in decimal

    values[48879] = len(values)

its fill by length of list.


问:
Memory error with python 64bit
I have added the code and the error message.
I have installed python3 64bit and anaconda 3.5 and I am facing memory error when I am extracting features from text file that result in a 2D array of 264,549 X21,000 . I am using Windows 10 64bit and 16GB Ram.
when I check the python version I have this is the result:
Python 3.6.2 |Anaconda, Inc.| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)] on win32

is it a problem with python? or the array cannot be fitted into the memory?

This is the error I have:

extracting the list of bow from training data...
  Traceback (most recent call last):
    File "tweet_fea_bow.py", line 27, in
      train_bow=vect.fit_transform(training).toarray()
    File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 964, in toarray
      return self.tocoo(copy=False).toarray(order=order, out=out)
    File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\coo.py", line 252, in toarray
      B = self._process_toarray_args(order, out)
    File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 1039, in _process_toarray_args
      return np.zeros(self.shape, dtype=self.dtype, order=order)
  MemoryError

```<code>import sys,os,traceback
import numpy as np
import sklearn
from sklearn.feature_extraction.text import CountVectorizer

print(sys.argv)
if len(sys.argv) == 2:
  print( "Reading data from file " + (sys.argv[1]))
  query_file_name = sys.argv[1]
  tf_num = int(sys.argv[1])
else:
  print ('Number of arguments = %d, expecting 1 arguments, program     terminated.') % (len(sys.argv) - 1)
sys.exit (1)

training=open('../training_data.txt','r').read().splitlines()
print('extracting bow from training data...')
vect=CountVectorizer(min_df=tf_num, ngram_range=(2,2))
train_bow=vect.fit_transform(training).toarray()
print('training matrix size:',train_bow.shape)
print('writing the training matrix...')
outfile=(path+'../bow_bi_gram_%s.npy'%(tf_num))
try:
   np.save(outfile,train_bow)
except:
   print('error')
   e=sys.exc_info()
   print(e)
print('extracting bow from testing data..')
testing=open('../testing_red_len_remove_@andurl.txt','r')
.read().splitlines()
test_bow=vect.transform(testing).toarray()
print('size of testing matrix:',test_bow.shape)
print('writing the testing matrix...')
outfile=('../testing_bow_bi_gram_%s.npy'%(tf_num))
np.save(outfile,test_bow)
</code>```

答:
Just make the operation yourself : 264,549 * 21,000  * size of  a cell = ?

Generally such data must be treated chunk by chunk.

Title: Memory error with python 64bit

Body:
I have added the code and the error message.
I have installed python3 64bit and anaconda 3.5 and I am facing memory error when I am extracting features from text file that result in a 2D array of 264,549 X21,000 . I am using Windows 10 64bit and 16GB Ram.
when I check the python version I have this is the result:
Python 3.6.2 |Anaconda, Inc.| (default, Sep 19 2017, 08:03:39) [MSC v.1900 64 bit (AMD64)] on win32

is it a problem with python? or the array cannot be fitted into the memory?

This is the error I have:

extracting the list of bow from training data...
  Traceback (most recent call last):
    File "tweet_fea_bow.py", line 27, in
      train_bow=vect.fit_transform(training).toarray()
    File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\compressed.py", line 964, in toarray
      return self.tocoo(copy=False).toarray(order=order, out=out)
    File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\coo.py", line 252, in toarray
      B = self._process_toarray_args(order, out)
    File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\sparse\base.py", line 1039, in _process_toarray_args
      return np.zeros(self.shape, dtype=self.dtype, order=order)
  MemoryError

import sys,os,traceback
import numpy as np
import sklearn
from sklearn.feature_extraction.text import CountVectorizer

print(sys.argv)
if len(sys.argv) == 2:
  print( "Reading data from file " + (sys.argv[1]))
  query_file_name = sys.argv[1]
  tf_num = int(sys.argv[1])
else:
  print ('Number of arguments = %d, expecting 1 arguments, program     terminated.') % (len(sys.argv) - 1)
sys.exit (1)

training=open('../training_data.txt','r').read().splitlines()
print('extracting bow from training data...')
vect=CountVectorizer(min_df=tf_num, ngram_range=(2,2))
train_bow=vect.fit_transform(training).toarray()
print('training matrix size:',train_bow.shape)
print('writing the training matrix...')
outfile=(path+'../bow_bi_gram_%s.npy'%(tf_num))
try:
   np.save(outfile,train_bow)
except:
   print('error')
   e=sys.exc_info()
   print(e)
print('extracting bow from testing data..')
testing=open('../testing_red_len_remove_@andurl.txt','r')
.read().splitlines()
test_bow=vect.transform(testing).toarray()
print('size of testing matrix:',test_bow.shape)
print('writing the testing matrix...')
outfile=('../testing_bow_bi_gram_%s.npy'%(tf_num))
np.save(outfile,test_bow)


问:
Replace two buttons with a toggle switch
I have the following code:

```<code><img id="v1" src="pic1.jpg"><br>
<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>
<br>
<img id="v2" src="pic3.jpg"><br>
<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>
<br>
</code>```

However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:

```<code><label class="switchBA">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</code>```

In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.

Thanks in advance.

P.S: I would like to do with only with JS. No need for jQuery or other frameworks.

答:
First of all you should never execute code in a handler the way you do. It's doable but in terms of readibility and maintainability it sucks, the handlers should only be used to fire a function.

It's fairly simple to achieve what you want.
put the toggle code inside a div and put the image and the newly created div inside a container div.
The div holding the toggle should include "display:none" in the css from the beginning so it is not shown, once you click on the button, you just need to hide the image and show the toggle switch div by changing "display:none" to "display:block";
Something like

```<code><div class="container">
        <img id="image1"src="https://openclipart.org/download/216413/coniglio_rabbit_small.svg" alt="">
        <div id="toggle">
          <img id="image2"src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png" alt="">
        </div>
        <button onclick="Change()">Click me</button>
      </div>
</code>```

https://codepen.io/anon/pen/rYGMYx

Body:
I have the following code:

<button onclick="document.getElementById('v1').src='pic1.jpg'">Before</button>
<button onclick="document.getElementById('v1').src='pic2.jpg'">After</button>

<button onclick="document.getElementById('v2').src='pic3.jpg'">Before</button>
<button onclick="document.getElementById('v2').src='pic4.jpg'">After</button>

However, I would like to replace these 'Before' and 'After' buttons with a toggle switch (already made) in the form of a checkbox:

<input type="checkbox" checked>

In a way that each time it's clicked it switches between the two functions. I guess this needs to be done inline since these are just two of many comparisons.

Thanks in advance.

P.S: I would like to do with only with JS. No need for jQuery or other frameworks.

Body:
First of all you should never execute code in a handler the way you do. It's doable but in terms of readibility and maintainability it sucks, the handlers should only be used to fire a function.

It's fairly simple to achieve what you want.
put the toggle code inside a div and put the image and the newly created div inside a container div.
The div holding the toggle should include "display:none" in the css from the beginning so it is not shown, once you click on the button, you just need to hide the image and show the toggle switch div by changing "display:none" to "display:block";
Something like

<div class="container">
        <img id="image1"src="https://openclipart.org/download/216413/coniglio_rabbit_small.svg" alt="">
        <div id="toggle">
          <img id="image2"src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/256/sign-check-icon.png" alt="">
        </div>
        <button onclick="Change()">Click me</button>
      </div>

https://codepen.io/anon/pen/rYGMYx


问:
val and fadeOut not working on click
i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:

```<code>$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});
</code>```

Nothing happens when i click on .close. in addition to this below does not work either.

```<code>$('#sign_in').val('Logger ind...');
</code>```

Full Code

```<code><form id="sign_in">
        <div class="form-group">
            <input type="text" name="username" id="username" class="form-control" placeholder="Email">
        </div>
        <div class="form-group">
            <input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
        </div>
        <a href="#">
            <small>Forgot password?</small>
        </a>
        <div class="form-group text-center add_top_20">
            <input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
            <input type="hidden" name="next" value="{{ next }}" />
        </div>
</form>

<div class="alert alert-error alert-danger" style="display: none;">
    <a class="close" href="#">×</a>
    Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
</code>```

jquery

```<code>$("#sign_in").submit(function (event) {
    // Change sign in button text
    $('#sign_in').val('Logger ind...');

    // post request
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: "/account/login/auth/",
        type: "POST",
        dataType : 'json',
        contentType: 'application/json',
        data: {
            'username': username,
            'password': password
        }, success: function (data) {

            if (data.success) {
                alert('success');
            } else {
                showAlert()
            }
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }, error: function(error){
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }
    });
});

function showAlert(){
    if(!$('.alert').is(':visible'))
    {
        $('.alert').fadeIn()
        $('.alert').delay(4000).fadeOut()
    }
}
$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});
</code>```

and all of this is wrapped in $(document).ready(function () {

答:
Mmm, your event is launching but you need to use clearQueue in order to launch your fadeOut animation again interrupting the previous one.</p>

```<code>$(".alert a").click(function(e) {
   $('.alert').clearQueue();
   $('.alert').fadeOut();
});
</code>```

Title: val and fadeOut not working on click

Body:
i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:

$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});

Nothing happens when i click on .close. in addition to this below does not work either.

$('#sign_in').val('Logger ind...');

Full Code

<form id="sign_in">

            <input type="text" name="username" id="username" class="form-control" placeholder="Email">

            <input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">

            Forgot password?

            <input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
            <input type="hidden" name="next" value="{{ next }}" />

</form>

    ×
    Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.

jquery

$("#sign_in").submit(function (event) {
    // Change sign in button text
    $('#sign_in').val('Logger ind...');

    // post request
    event.preventDefault();
    var username = $('#username').val();
    var password = $('#password').val();
    $.ajax({
        url: "/account/login/auth/",
        type: "POST",
        dataType : 'json',
        contentType: 'application/json',
        data: {
            'username': username,
            'password': password
        }, success: function (data) {

            if (data.success) {
                alert('success');
            } else {
                showAlert()
            }
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }, error: function(error){
            // Change sign in text back
            $('#sign_in').val('Log ind');
        }
    });
});

function showAlert(){
    if(!$('.alert').is(':visible'))
    {
        $('.alert').fadeIn()
        $('.alert').delay(4000).fadeOut()
    }
}
$(".alert a").click(function(e) {
    $('.alert').fadeOut();
});

and all of this is wrapped in $(document).ready(function () {

Body:
Mmm, your event is launching but you need to use clearQueue in order to launch your fadeOut animation again interrupting the previous one.

$(".alert a").click(function(e) {
   $('.alert').clearQueue();
   $('.alert').fadeOut();
});


问:
MVC3 Plugin architecture recommendations
I am trying to find some more information on approaches to creating a plugin architecture.

I've seen some good articles on MEF and MVC2 and Phil Haack mentioned some new extensibilty hooks available in MVC3 (http://haacked.com/archive/2010/05/16/three-hidden-extensibility-gems-in-asp-net-4.aspx)

Has anyone seen some good references on creating a plugin architecture for a MVC3 project?

I'd prefer to use technologies specific to MVC3, not to just hack a MVC2 solution in to the MVC2 framework.

Any ideas and suggestions would be greatly appreciated!

答:
What makes you think all the techniques that were valid for MVC 1 and 2 are now "hacks" for 3?

There are probably 10 different architectures listed in these search results that would accomplish what you are looking for:

http://stackoverflow.com/search?q=[asp.net-mvc]+plugins

ContentLicense: CC BY-SA 2.5


问:
Maximum width and height for ImageView in Android
So I have an ImageView set with

```<code>android:maxHeight="100px"
android:maxWidth="250px"
android:minHeight="100px"
android:minWidth="250px"
android:scaleType="centerInside"
</code>```

This image view is used to show a picture that is obtained from the gallery or camera. In both cases, the image is not resized to fit inside the imageview, it just stretches its space as much as it needs.

Any idea how to make it stay inside those bounds?

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><EditText
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:id="@+id/txtDescription"
    android:layout_below="@+id/txtSubject"
    android:inputType="textMultiLine"
    android:height="80px"
    android:hint="@string/description"></EditText>

<EditText
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtDescription"
    android:layout_width="fill_parent"
    android:id="@+id/txtMorada"
    android:hint="@string/address" />

<ImageButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@+id/txtMorada"
    android:id="@+id/btGPS"
    android:layout_alignParentLeft="true"
    android:src="@drawable/ic_menu_compass"></ImageButton>

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@+id/btGPS"
    android:layout_marginTop="25px"
    android:id="@+id/imgPoint"
    android:src="@drawable/google_logo_small"
    android:maxHeight="100px"
    android:maxWidth="250px"
    android:minHeight="100px"
    android:minWidth="250px"
    android:scaleType="centerInside"></ImageView>

<ImageButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_toRightOf="@+id/imgPoint"
    android:id="@+id/btGallery"
    android:layout_below="@+id/btCamera"
    android:src="@drawable/ic_menu_gallery"
    android:layout_alignParentRight="true"></ImageButton>

<Button
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_marginTop="10px"
    android:id="@+id/btSubmit"
    android:layout_below="@+id/btGallery"
    android:text="@string/submit"></Button>

<ImageButton
    android:layout_height="wrap_content"
    android:id="@+id/btMap"
    android:layout_below="@+id/txtMorada"
    android:layout_width="wrap_content"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_menu_mapmode"></ImageButton>

<TextView
    android:layout_below="@+id/txtMorada"
    android:layout_width="wrap_content"
    android:layout_toLeftOf="@+id/btMap"
    android:layout_height="wrap_content"
    android:id="@+id/lblNewPointLatitude"
    android:text="Latitude"></TextView>

<TextView
    android:layout_width="wrap_content"
    android:layout_toLeftOf="@+id/btMap"
    android:layout_height="wrap_content"
    android:id="@+id/lblNewPointLongitude"
    android:layout_below="@+id/lblNewPointLatitude"
    android:text="Longitude"></TextView>

<ImageButton
    android:layout_below="@+id/btMap"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_toRightOf="@+is/imgPoint"
    android:id="@+id/btCamera"
    android:layout_marginTop="25px"
    android:src="@drawable/ic_menu_camera"
    android:layout_alignParentRight="true"></ImageButton>

<Spinner
    android:layout_height="wrap_content"
    android:id="@+id/spCategoria"
    android:layout_width="fill_parent"
    android:prompt="@string/spCategoriaPrompt"></Spinner>

<Spinner
    android:layout_height="wrap_content"
    android:id="@+id/spSubcategoria"
    android:layout_below="@+id/spCategoria"
    android:layout_width="fill_parent"
    android:prompt="@string/spSubcategoriaPrompt"></Spinner>

<EditText
    android:layout_height="wrap_content"
    android:layout_below="@+id/spSubcategoria"
    android:layout_width="fill_parent"
    android:id="@+id/txtSubject"
    android:hint="@string/subject"></EditText>

  </RelativeLayout>
</ScrollView>
</code>```

答:
Try including this: xmlns:android="http://schemas.android.com/apk/res/android"
Example :

```<code><ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="400dp"
    android:adjustViewBounds="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:src="@drawable/background_img"
    />
</code>```

Body:
So I have an ImageView set with

android:maxHeight="100px"
android:maxWidth="250px"
android:minHeight="100px"
android:minWidth="250px"
android:scaleType="centerInside"

This image view is used to show a picture that is obtained from the gallery or camera. In both cases, the image is not resized to fit inside the imageview, it just stretches its space as much as it needs.

Any idea how to make it stay inside those bounds?

<?xml version="1.0" encoding="utf-8"?>

<EditText
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:id="@+id/txtDescription"
    android:layout_below="@+id/txtSubject"
    android:inputType="textMultiLine"
    android:height="80px"
    android:hint="@string/description"></EditText>

<EditText
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtDescription"
    android:layout_width="fill_parent"
    android:id="@+id/txtMorada"
    android:hint="@string/address" />

<ImageButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@+id/txtMorada"
    android:id="@+id/btGPS"
    android:layout_alignParentLeft="true"
    android:src="@drawable/ic_menu_compass"></ImageButton>

<ImageView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_below="@+id/btGPS"
    android:layout_marginTop="25px"
    android:id="@+id/imgPoint"
    android:src="@drawable/google_logo_small"
    android:maxHeight="100px"
    android:maxWidth="250px"
    android:minHeight="100px"
    android:minWidth="250px"
    android:scaleType="centerInside"></ImageView>

<ImageButton
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_toRightOf="@+id/imgPoint"
    android:id="@+id/btGallery"
    android:layout_below="@+id/btCamera"
    android:src="@drawable/ic_menu_gallery"
    android:layout_alignParentRight="true"></ImageButton>

<Button
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:layout_marginTop="10px"
    android:id="@+id/btSubmit"
    android:layout_below="@+id/btGallery"
    android:text="@string/submit"></Button>

<ImageButton
    android:layout_height="wrap_content"
    android:id="@+id/btMap"
    android:layout_below="@+id/txtMorada"
    android:layout_width="wrap_content"
    android:layout_alignParentRight="true"
    android:src="@drawable/ic_menu_mapmode"></ImageButton>

<TextView
    android:layout_below="@+id/txtMorada"
    android:layout_width="wrap_content"
    android:layout_toLeftOf="@+id/btMap"
    android:layout_height="wrap_content"
    android:id="@+id/lblNewPointLatitude"
    android:text="Latitude"></TextView>

<TextView
    android:layout_width="wrap_content"
    android:layout_toLeftOf="@+id/btMap"
    android:layout_height="wrap_content"
    android:id="@+id/lblNewPointLongitude"
    android:layout_below="@+id/lblNewPointLatitude"
    android:text="Longitude"></TextView>

<ImageButton
    android:layout_below="@+id/btMap"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_toRightOf="@+is/imgPoint"
    android:id="@+id/btCamera"
    android:layout_marginTop="25px"
    android:src="@drawable/ic_menu_camera"
    android:layout_alignParentRight="true"></ImageButton>

<Spinner
    android:layout_height="wrap_content"
    android:id="@+id/spCategoria"
    android:layout_width="fill_parent"
    android:prompt="@string/spCategoriaPrompt"></Spinner>

<Spinner
    android:layout_height="wrap_content"
    android:id="@+id/spSubcategoria"
    android:layout_below="@+id/spCategoria"
    android:layout_width="fill_parent"
    android:prompt="@string/spSubcategoriaPrompt"></Spinner>

<EditText
    android:layout_height="wrap_content"
    android:layout_below="@+id/spSubcategoria"
    android:layout_width="fill_parent"
    android:id="@+id/txtSubject"
    android:hint="@string/subject"></EditText>

  </RelativeLayout>
</ScrollView>

Body:
Try including this: xmlns:android="http://schemas.android.com/apk/res/android"
Example :

<ImageView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxHeight="400dp"
    android:adjustViewBounds="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:src="@drawable/background_img"
    />


问:
How can I oscillate numbers in a list?
Question: How can I make these oscillate as such that the first digits or expression is + the next is - the one after is + and so on and so forth for the lists provided below (without using a specially made function for oscillation if one even exists).

I'm currently getting output as shown below:

```<code>    x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880
1. {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69,
73, 77, 81, 85, 89}
</code>```

Expected output:

```<code>x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880
2. {1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}

Sum[x^j/Factorial[j], {j, 1, 9, 2}];
myOsc = Table[i, {i, 1, 89, 4}];
</code>```

Title: How can I oscillate numbers in a list?

Body:
Question: How can I make these oscillate as such that the first digits or expression is + the next is - the one after is + and so on and so forth for the lists provided below (without using a specially made function for oscillation if one even exists).

I'm currently getting output as shown below:

    x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880
1. {1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61, 65, 69,
73, 77, 81, 85, 89}

Expected output:

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880
2. {1, -5, 9, -13, 17, -21, 25, -29, 33, -37, 41, -45, 49, -53, 57, -61, 65, -69, 73, -77, 81, -85, 89}

Sum[x^j/Factorial[j], {j, 1, 9, 2}];
myOsc = Table[i, {i, 1, 89, 4}];

Body:
s = -1; Map[(s *= -1) # &, x + x^3/6 + x^5/120 + x^7/5040 + x^9/362880]

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880

note of caution mathematica will put your expression in canonical order for you first. So for example if you key it in like this:

s = -1; Map[(s *= -1) # &,x^3/6 + x  + x^5/120 + x^7/5040 + x^9/362880]

you get the same result

x - x^3/6 + x^5/120 - x^7/5040 + x^9/362880


问:
@Output in angular 2 doesn't work
I'm using Angular 2. So children component is

```<code>import { Component, OnInit,  Output, EventEmitter } from '@angular/core';
...
    export class EnterComponent implements OnInit {

        @Output() isClosedChange = new EventEmitter<boolean>();
        public isClosed: boolean;

        constructor() {
            let isClose = true;
         }

        Close() {
            this.isClosed = false;
            this.isClosedChange.emit(this.isClosed);
        }
    }
</code>```

my parent componet is

```<code>export class AppComponent {

    public isClosedinMain: boolean;

    constructor() {
        this.isClosedinMain = true;

    }
}
</code>```

and html:

```<code><app-header (isClosedChange) = "isClosedinMain"></app-header>
</code>```

It is very simple but isClosedinMain doesn't receive anything

答:
When you are binding to events use functions:

```<code><app-header (isClosedChange) = "ClosedInMainFN($event)"></app-header>
</code>```

and the in main component ts write function

```<code>ClosedInMainFN(event: boolean) {

this.isClosedinMain = event;

}
</code>```

Title: @Output in angular 2 doesn't work

Body:
I'm using Angular 2. So children component is

import { Component, OnInit,  Output, EventEmitter } from '@angular/core';
...
    export class EnterComponent implements OnInit {

        @Output() isClosedChange = new EventEmitter<boolean>();
        public isClosed: boolean;

        constructor() {
            let isClose = true;
         }

        Close() {
            this.isClosed = false;
            this.isClosedChange.emit(this.isClosed);
        }
    }

my parent componet is

export class AppComponent {

    public isClosedinMain: boolean;

    constructor() {
        this.isClosedinMain = true;

    }
}

and html:

<app-header (isClosedChange) = "isClosedinMain"></app-header>

It is very simple but isClosedinMain doesn't receive anything

Body:
When you are binding to events use functions:

<app-header (isClosedChange) = "ClosedInMainFN($event)"></app-header>

and the in main component ts write function

ClosedInMainFN(event: boolean) {

this.isClosedinMain = event;

}


答:
The simplest way to do this is to set the image as the background image of an element and then toggle that CSS setting by toggling the class that defines it:

document.querySelector("input[type=checkbox]").addEventListener("click", function(){
  document.querySelector(".slider").classList.toggle("otherImage");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  width:150px;
  height:150px;
  background-size:contain;
  border:1px solid black;
}

/* This will be the default style used because the class is defined in the HTML */
.slider {
  background-image:url("http://aws-cdn-01.shemazing.ie/wp-content/uploads/2015/09/disappointed-but-relieved-face.png");
}

/* This will be toggled on and off by the clicking of the checkbox. When it is
   toggled on, it will override the previous background-image value. */
.otherImage {
  background-image:url("https://au.res.keymedia.com/files/image/emoji.jpg");
}</code>```

<input type="checkbox" checked>

```

Title: Replace two buttons with a toggle switch

Body:
The simplest way to do this is to set the image as the background image of an element and then toggle that CSS setting by toggling the class that defines it:

document.querySelector("input[type=checkbox]").addEventListener("click", function(){
  document.querySelector(".slider").classList.toggle("otherImage");
});

div {
  width:150px;
  height:150px;
  background-size:contain;
  border:1px solid black;
}

/* This will be the default style used because the class is defined in the HTML */
.slider {
  background-image:url("http://aws-cdn-01.shemazing.ie/wp-content/uploads/2015/09/disappointed-but-relieved-face.png");
}

/* This will be toggled on and off by the clicking of the checkbox. When it is
   toggled on, it will override the previous background-image value. */
.otherImage {
  background-image:url("https://au.res.keymedia.com/files/image/emoji.jpg");
}

<label class="switchBA">
<input type="checkbox" checked>
<div class="slider"></div>
</label>


问:
Python gamepad input?
Is there any good alternative to pygame for gamepad input?
Crossplatform would be nice too.</p>

答: There's gamepad support in myro. I've dealt with the robotic functionality of the library, but not directly with the gamepad stuff. My encounters and the documentation indicate that myro is supported on windows, mac, and linux distributions.

Title: Python gamepad input?


问:
Oracle select data by contiguous date blocks
I am using an Oracle database and I have a table that has 2 columns with data like so:

```<code>HASH | DATE
-----------------
abcd | 2017-11-01
abcd | 2017-11-02
abcd | 2017-11-03
wxyz | 2017-11-04
wxyz | 2017-11-05
abcd | 2017-11-06
wxyz | 2017-11-07
abcd | 2017-11-08
abcd | 2017-11-09
lmno | 2017-11-10
lmno | 2017-11-11
</code>```

I want to know the windows of time that each hash is seen. So like

```<code>hash | start      | end
------------------------------
abcd | 2017-11-01 | 2017-11-03
wxyz | 2017-11-04 | 2017-11-05
abcd | 2017-11-06 | 2017-11-06
wxyz | 2017-11-07 | 2017-11-07
abcd | 2017-11-08 | 2017-11-09
lmno | 2017-11-10 | 2017-11-11
</code>```

What I have so far is basically this:

```<code>SELECT HASH, MIN(DATE) ST, MAX(DATE) ED
FROM HASH_TABLE
GROUP BY HASH
ORDER BY 3 DESC
</code>```

And this almost works but it will give me like "abcd" as a start of 2017-11-01 and an end of 2017-11-09 which "hides" the fact that it switched in the middle.

Is there some way to group these results by contiguous date/time "blocks"?

答:
It looks like "gaps and islands" problem:

```<code>WITH cte("hash","date") AS (
    SELECT 'abcd',  DATE'2017-11-01' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-02' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-03' FROM dual UNION ALL
    SELECT 'wxyz',  DATE'2017-11-04' FROM dual UNION ALL
    SELECT 'wxyz',  DATE'2017-11-05' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-06' FROM dual UNION ALL
    SELECT 'wxyz',  DATE'2017-11-07' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-08' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-09' FROM dual UNION ALL
    SELECT 'lmno',  DATE'2017-11-10' FROM dual UNION ALL
    SELECT 'lmno',  DATE'2017-11-11' FROM dual
)
select "hash"
      ,min("date") as startdate
      ,max("date") as enddate
from (
    select "date","hash"
         , row_number() over (order by "date")
         - row_number() over (partition by "hash" order by "date") as grp
    from cte
) A
group by "hash", grp
ORDER BY startdate;
</code>```

DBFiddle Demo

Body:
I am using an Oracle database and I have a table that has 2 columns with data like so:

HASH | DATE
-----------------
abcd | 2017-11-01
abcd | 2017-11-02
abcd | 2017-11-03
wxyz | 2017-11-04
wxyz | 2017-11-05
abcd | 2017-11-06
wxyz | 2017-11-07
abcd | 2017-11-08
abcd | 2017-11-09
lmno | 2017-11-10
lmno | 2017-11-11

I want to know the windows of time that each hash is seen. So like

hash | start      | end
------------------------------
abcd | 2017-11-01 | 2017-11-03
wxyz | 2017-11-04 | 2017-11-05
abcd | 2017-11-06 | 2017-11-06
wxyz | 2017-11-07 | 2017-11-07
abcd | 2017-11-08 | 2017-11-09
lmno | 2017-11-10 | 2017-11-11

What I have so far is basically this:

SELECT HASH, MIN(DATE) ST, MAX(DATE) ED
FROM HASH_TABLE
GROUP BY HASH
ORDER BY 3 DESC

And this almost works but it will give me like "abcd" as a start of 2017-11-01 and an end of 2017-11-09 which "hides" the fact that it switched in the middle.

Is there some way to group these results by contiguous date/time "blocks"?

Body:
It looks like "gaps and islands" problem:

WITH cte("hash","date") AS (
    SELECT 'abcd',  DATE'2017-11-01' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-02' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-03' FROM dual UNION ALL
    SELECT 'wxyz',  DATE'2017-11-04' FROM dual UNION ALL
    SELECT 'wxyz',  DATE'2017-11-05' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-06' FROM dual UNION ALL
    SELECT 'wxyz',  DATE'2017-11-07' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-08' FROM dual UNION ALL
    SELECT 'abcd',  DATE'2017-11-09' FROM dual UNION ALL
    SELECT 'lmno',  DATE'2017-11-10' FROM dual UNION ALL
    SELECT 'lmno',  DATE'2017-11-11' FROM dual
)
select "hash"
      ,min("date") as startdate
      ,max("date") as enddate
from (
    select "date","hash"
         , row_number() over (order by "date")
         - row_number() over (partition by "hash" order by "date") as grp
    from cte
) A
group by "hash", grp
ORDER BY startdate;

DBFiddle Demo


问:
How to return values from Array using Google sheets script
I am recording the difference between the current currency value and yesterdays close on an hour by hour basis, using scripts in Google Sheets to automatically add new rows each hour with the new values.

For the most part this works fine, however the Google Finance formula for Historic data displays the data in a 2x2 array.

```<code>=GOOGLEFINANCE("CURRENCY:USDGBP", "close", TODAY()-1, TODAY())
</code>```

Using scripts I need to reference the Close value returned in Column 2, Row 2 of the array for further calculations.

```<code>var CloseVal = sheet.getRange("$I$13").getDisplayValue();
console.log(posNeg);
sheet.getRange(numRows + 1,3).setValue(CloseVal);
</code>```

However when I try to reference the results of the array using scripts as above, it returns a null value. It suggests that while the value is displayed in this cell, it doesn't actually exist there.

I've tried using getDisplayValue and also referencing the formula cell to no available.

Does anyone know how I can get the value to return?

答:
It is not possible to access the values returned by GOOGLEFINANCE function via App script. This feature was disabled by Google [link]  around Sep 2016.

We want to make you aware of a small change to the GOOGLEFINANCE
  function, which makes it easy to pull current or historical securities
  information directly into your spreadsheets in Google Sheets. Starting
  today, it will not be possible to download historical data or access
  it outside of Sheets using Apps Script or an API.

If you have a spreadsheet with historical data generated from the
  GOOGLEFINANCE function and you try to download it or access it via
  Apps Script or an API, the corresponding cells will show “#N/A.”

Body:
I am recording the difference between the current currency value and yesterdays close on an hour by hour basis, using scripts in Google Sheets to automatically add new rows each hour with the new values.

For the most part this works fine, however the Google Finance formula for Historic data displays the data in a 2x2 array.

=GOOGLEFINANCE("CURRENCY:USDGBP", "close", TODAY()-1, TODAY())

Using scripts I need to reference the Close value returned in Column 2, Row 2 of the array for further calculations.

var CloseVal = sheet.getRange("$I$13").getDisplayValue();
console.log(posNeg);
sheet.getRange(numRows + 1,3).setValue(CloseVal);

However when I try to reference the results of the array using scripts as above, it returns a null value. It suggests that while the value is displayed in this cell, it doesn't actually exist there.

I've tried using getDisplayValue and also referencing the formula cell to no available.

Does anyone know how I can get the value to return?


问:
Testing user input is mirrored from one input to another with Selenium + Python
I am trying to write a test in Selenium that ensures text entered into one input is mirrored in another input. I keep getting this error below.

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]"}
</code>```

This is the code I'm using currently:

```<code>class inputMirror(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://foo.bar")

def test_mirror_input(self):
#Ensures text from the first input is mirrored into the second input box
    driver = self.driver
    userInput = "Howdy"
    inputBoxOneXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]')
    inputBoxTwoXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[2]')
    inputBoxOneXpath.clear()
    inputBoxOneXpath.send_keys(userInput)
    driver.implicitly_wait(10)
    assert inputBoxTwoXpath.text == userInput
    driver.close()
</code>```

HTML code:

<input type="text" placeholder="Enter text here..." value="">
<input class="textbox" placeholder="Enter text here..." value="" maxlength="80" required="true">```

答:
With the provided html, you could do:</p>

```<code>userInput = "Howdy"
driver.find_element_by_xpath("//input[@type='text' and @placeholder='Enter text here...']").send_keys(userInput)
driver.find_element_by_xpath("//input[@class='textbox' and @placeholder='Enter text here...']").send_keys(userInput)
</code>```

Body:
I am trying to write a test in Selenium that ensures text entered into one input is mirrored in another input. I keep getting this error below.

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]"}

This is the code I'm using currently:

class inputMirror(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Chrome()
    self.driver.get("https://foo.bar")

def test_mirror_input(self):
#Ensures text from the first input is mirrored into the second input box
    driver = self.driver
    userInput = "Howdy"
    inputBoxOneXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[1]')
    inputBoxTwoXpath = driver.find_element_by_xpath('/html/body/div/div[2]/div/div/div/div[2]/div[1]/input[2]')
    inputBoxOneXpath.clear()
    inputBoxOneXpath.send_keys(userInput)
    driver.implicitly_wait(10)
    assert inputBoxTwoXpath.text == userInput
    driver.close()

HTML code:

<input type="text" placeholder="Enter text here..." value="">
<input class="textbox" placeholder="Enter text here..." value="" maxlength="80" required="true">

Body:
With the provided html, you could do:

userInput = "Howdy"
driver.find_element_by_xpath("//input[@type='text' and @placeholder='Enter text here...']").send_keys(userInput)
driver.find_element_by_xpath("//input[@class='textbox' and @placeholder='Enter text here...']").send_keys(userInput)


问:
Javascript equivalents for Java Streams API
I like the Java 8's streaming API. There are plenty of useful intermediate and terminal methods to transform and collect the stream. I'm talking about intermediate methods like distinct() or terminal methods like collect(). I find the Collector API especially useful, to reduce the stream to deep grouping maps.

What is the javascript equivalent for the Java streaming API? I know there're basic functions like map, filter and reduce, but don't find any more generalized interfaces provided by javascript native to query or group the data in collection. Are there some production ready libraries to match the Java Streaming API?

答:
java 8 stream() is the same as lodash chain()

java 8 collect() is the same as lodash value()

java 8 distinct() is the same as lodash uniq()

java 8 map() is the same as lodash map()

lodash is more comprehensive, since it has been around longer.


问:
jqGrid pager problem after adding a row with addRowData
```<code>var index = 'id';
var ajaxResponse = [{id: 1, name: 'John', email: 'john@doe.co.uk'}, {id: 2, name: 'Michael', email: 'michael@example.com'}];
$('#grid').addRowData(index, ajaxResponse);
</code>```

After adding multiple rows one by one the pager doesn't stick to the per page limitation, also the pager reports page 1 of 0.

After i hit the refresh button from the footer of the grid, i see the correct number of rows per page, and the correct number of pages.

Any ideas on how to fix?

Thanks.

答: Call refresh after add row jQuery("#grid").trigger("reloadGrid");

Body:
var index = 'id';
var ajaxResponse = [{id: 1, name: 'John', email: 'john@doe.co.uk'}, {id: 2, name: 'Michael', email: 'michael@example.com'}];
$('#grid').addRowData(index, ajaxResponse);

After adding multiple rows one by one the pager doesn't stick to the per page limitation, also the pager reports page 1 of 0.

After i hit the refresh button from the footer of the grid, i see the correct number of rows per page, and the correct number of pages.

Any ideas on how to fix?

Thanks.


问:
hibernate two way mapping insert and delete beginner
Today I did some experiments with hibernate. Unfortunately it seems if I’m misunderstanding something about the sessions.
I have three entities (book “buch”, user “benutzer” and rent “leihstellung”).
Each book knows about the rents, it’s concerned by. Each rent knows about the associated book. Furthermore each rent knows about the fitting user and of course each user knows the associated rents.

I explicitly want to have this two way mappings.

Now I wrote a small tester which inserts some data. The insert progress works as expected. After inserting some data I would like to delete a user.
If I do this before the commit, hibernate gives me an error, because the user will be reinserted be the rents it belongs to (that even happens, if I manually delete the user from this rents). Here I don’t really understand why that happens.

Everything works fine, if I do a session.close and open a new session for deleting the user.

I guess, that there is a smarter way to do this within one session. But unfortunately I don’t know how this can be done.
Any explanation is welcome.

```<code>public class Worker implements Iworker{

    private Sessiongetter sg;

    private MainMenu mm;

    public void work(File datei)
    {
        sg = new Sessiongetter();
        Session session = sg.getSesseion();
        WlBuchart wlBuchart = new WlBuchart(1, "Sachbuch");

        Buch buch = new Buch("test", "ich", 1);
        buch.setWlBuchart(wlBuchart);
        Buch buch2 = new Buch("versuch", "du",2);
        buch2.setWlBuchart(wlBuchart);
        session.beginTransaction();
        session.save(wlBuchart);
        session.save(buch);
          session.save(buch2);

        Benutzer benutzer = new Benutzer("hans", "dampf", "Lehrer", "versuch");
        session.save(benutzer);

        Leihstellung leihstellung = new Leihstellung(benutzer, buch);
        Leihstellung leihstellung2 = new Leihstellung(benutzer, buch2);
        session.save(leihstellung);
        session.save(leihstellung2);

        benutzer.addLeihstellung(leihstellung);
        benutzer.addLeihstellung(leihstellung2);
        session.update(benutzer);

        buch.addLeihstellung(leihstellung);
        buch2.addLeihstellung(leihstellung2);
        session.update(buch);
        session.update(buch2);
        session.remove(benutzer);

        session.flush();
        session.getTransaction().commit();

        session.close();

        System.out.println("fertig");
    }

package code.logik;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.Session;

@Entity
@Table(name="benutzer")
public class Benutzer {

    @Column(nullable=false)
    private String vorname, nachname, gruppe;
    @Id
    private String kennung;
    private boolean admin;
    @Column(nullable=true)
    private String kennwort;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="benutzer")
    private List<Leihstellung>leihstellungs;

    public String getKennwort() {
        return kennwort;
    }

    public void setKennwort(String kennwort) {
        this.kennwort = kennwort;
    }

    public Benutzer(String vorname, String nachname, String gruppe, String kennung) {
        this.vorname=vorname;
        this.nachname=nachname;
        this.gruppe=gruppe;
        this.kennung=kennung;
        this.leihstellungs= new ArrayList<>();

    }

    public Benutzer() {
        // TODO Auto-generated constructor stub
    }

    public String getVorname() {
        return vorname;
    }

    public String getNachname() {
        return nachname;
    }

    public String getGruppe() {
        return gruppe;
    }

    public String getKennung() {
        return kennung;
    }

    public boolean isAdmin() {
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    public List<Leihstellung> getLeihstellungs() {
        return leihstellungs;
    }

    public void addLeihstellung(Leihstellung leihstellung)
    {
        leihstellungs.add(leihstellung);
    }

    public int compare(Benutzer other)
    {
        if (this.getNachname().compareTo(other.getNachname())!=0)
        {
            return this.getNachname().compareTo(other.getNachname());
        }
        return this.getVorname().compareTo(other.getVorname());
    }

}

package code.logik;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.ManyToAny;

@Entity
@Table(name="buch")
public class Buch {

    @Column(nullable=false)
    private String titel;
    private String autor;

    @ManyToOne
    private WlBuchart wlBuchart;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="buch")
    private List<Leihstellung>leihstellungs;

    public WlBuchart getWlBuchart() {
        return wlBuchart;
    }

    public void setWlBuchart(WlBuchart wlBuchart) {
        this.wlBuchart = wlBuchart;
    }

    @Id
    private int nummer;

    public Buch(String titel, String autor,int nummer) {
        this.titel=titel;
        this.autor=autor;
        this.nummer=nummer;
        leihstellungs = new ArrayList<>();
    }

    public Buch() {
        // TODO Auto-generated constructor stub
    }

    public String getTitel() {
        return titel;
    }

    public String getAutor() {
        return autor;
    }

    public int getNummer() {
        return nummer;
    }

    public List<Leihstellung> getLeihstellungs() {
        return leihstellungs;
    }

    public void addLeihstellung(Leihstellung leihstellung)
    {
        leihstellungs.add(leihstellung);
    }

}

package code.logik;

import java.time.LocalDate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="leihstellung")
public class Leihstellung {

    @ManyToOne
    private Benutzer benutzer;

    @Id @GeneratedValue
    private int id;

    @Column(nullable=false)
    private LocalDate von;

    private LocalDate bis;

    @ManyToOne
    private Buch buch;

    public Leihstellung(Benutzer benutzer, Buch buch) {
        this.benutzer=benutzer;
        this.buch=buch;
        this.von = LocalDate.now();
    }

    public Leihstellung() {
        // TODO Auto-generated constructor stub
    }

    public void setAbgegeben()
    {
        bis = LocalDate.now();
    }

    public Benutzer getBenutzer() {
        return benutzer;
    }

    public int getId() {
        return id;
    }

    public LocalDate getVon() {
        return von;
    }

    public LocalDate getBis() {
        return bis;
    }

    public Buch getBuch() {
        return buch;
    }

}
</code>```

答:
Found the solution myself. I had to delete the references from the connected rents and books.
Now everything works find. </p>

Body:
Today I did some experiments with hibernate. Unfortunately it seems if I’m misunderstanding something about the sessions.
I have three entities (book “buch”, user “benutzer” and rent “leihstellung”).
Each book knows about the rents, it’s concerned by. Each rent knows about the associated book. Furthermore each rent knows about the fitting user and of course each user knows the associated rents.

I explicitly want to have this two way mappings.

Now I wrote a small tester which inserts some data. The insert progress works as expected. After inserting some data I would like to delete a user.
If I do this before the commit, hibernate gives me an error, because the user will be reinserted be the rents it belongs to (that even happens, if I manually delete the user from this rents). Here I don’t really understand why that happens.

Everything works fine, if I do a session.close and open a new session for deleting the user.

I guess, that there is a smarter way to do this within one session. But unfortunately I don’t know how this can be done.
Any explanation is welcome.

public class Worker implements Iworker{

    private Sessiongetter sg;

    private MainMenu mm;

    public void work(File datei)
    {
        sg = new Sessiongetter();
        Session session = sg.getSesseion();
        WlBuchart wlBuchart = new WlBuchart(1, "Sachbuch");

        Buch buch = new Buch("test", "ich", 1);
        buch.setWlBuchart(wlBuchart);
        Buch buch2 = new Buch("versuch", "du",2);
        buch2.setWlBuchart(wlBuchart);
        session.beginTransaction();
        session.save(wlBuchart);
        session.save(buch);
          session.save(buch2);

        Benutzer benutzer = new Benutzer("hans", "dampf", "Lehrer", "versuch");
        session.save(benutzer);

        Leihstellung leihstellung = new Leihstellung(benutzer, buch);
        Leihstellung leihstellung2 = new Leihstellung(benutzer, buch2);
        session.save(leihstellung);
        session.save(leihstellung2);

        benutzer.addLeihstellung(leihstellung);
        benutzer.addLeihstellung(leihstellung2);
        session.update(benutzer);

        buch.addLeihstellung(leihstellung);
        buch2.addLeihstellung(leihstellung2);
        session.update(buch);
        session.update(buch2);
        session.remove(benutzer);

        session.flush();
        session.getTransaction().commit();

        session.close();

        System.out.println("fertig");
    }

package code.logik;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.Session;

@Entity
@Table(name="benutzer")
public class Benutzer {

    @Column(nullable=false)
    private String vorname, nachname, gruppe;
    @Id
    private String kennung;
    private boolean admin;
    @Column(nullable=true)
    private String kennwort;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="benutzer")
    private List<Leihstellung>leihstellungs;

    public String getKennwort() {
        return kennwort;
    }

    public void setKennwort(String kennwort) {
        this.kennwort = kennwort;
    }

    public Benutzer(String vorname, String nachname, String gruppe, String kennung) {
        this.vorname=vorname;
        this.nachname=nachname;
        this.gruppe=gruppe;
        this.kennung=kennung;
        this.leihstellungs= new ArrayList<>();

    }

    public Benutzer() {
        // TODO Auto-generated constructor stub
    }

    public String getVorname() {
        return vorname;
    }

    public String getNachname() {
        return nachname;
    }

    public String getGruppe() {
        return gruppe;
    }

    public String getKennung() {
        return kennung;
    }

    public boolean isAdmin() {
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    public List<Leihstellung> getLeihstellungs() {
        return leihstellungs;
    }

    public void addLeihstellung(Leihstellung leihstellung)
    {
        leihstellungs.add(leihstellung);
    }

    public int compare(Benutzer other)
    {
        if (this.getNachname().compareTo(other.getNachname())!=0)
        {
            return this.getNachname().compareTo(other.getNachname());
        }
        return this.getVorname().compareTo(other.getVorname());
    }

}

package code.logik;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.ManyToAny;

@Entity
@Table(name="buch")
public class Buch {

    @Column(nullable=false)
    private String titel;
    private String autor;

    @ManyToOne
    private WlBuchart wlBuchart;

    @OneToMany(cascade=CascadeType.ALL, mappedBy="buch")
    private List<Leihstellung>leihstellungs;

    public WlBuchart getWlBuchart() {
        return wlBuchart;
    }

    public void setWlBuchart(WlBuchart wlBuchart) {
        this.wlBuchart = wlBuchart;
    }

    @Id
    private int nummer;

    public Buch(String titel, String autor,int nummer) {
        this.titel=titel;
        this.autor=autor;
        this.nummer=nummer;
        leihstellungs = new ArrayList<>();
    }

    public Buch() {
        // TODO Auto-generated constructor stub
    }

    public String getTitel() {
        return titel;
    }

    public String getAutor() {
        return autor;
    }

    public int getNummer() {
        return nummer;
    }

    public List<Leihstellung> getLeihstellungs() {
        return leihstellungs;
    }

    public void addLeihstellung(Leihstellung leihstellung)
    {
        leihstellungs.add(leihstellung);
    }

}

package code.logik;

import java.time.LocalDate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="leihstellung")
public class Leihstellung {

    @ManyToOne
    private Benutzer benutzer;

    @Id @GeneratedValue
    private int id;

    @Column(nullable=false)
    private LocalDate von;

    private LocalDate bis;

    @ManyToOne
    private Buch buch;

    public Leihstellung(Benutzer benutzer, Buch buch) {
        this.benutzer=benutzer;
        this.buch=buch;
        this.von = LocalDate.now();
    }

    public Leihstellung() {
        // TODO Auto-generated constructor stub
    }

    public void setAbgegeben()
    {
        bis = LocalDate.now();
    }

    public Benutzer getBenutzer() {
        return benutzer;
    }

    public int getId() {
        return id;
    }

    public LocalDate getVon() {
        return von;
    }

    public LocalDate getBis() {
        return bis;
    }

    public Buch getBuch() {
        return buch;
    }

}


问:
Will `Object.keys(x)` ever throw?
How can I know for sure if

Object.keys(x) will ever throw an error?

where x is anything.

答:
As per documentation MDN

In ES5, if the argument to this method is not an object (a primitive),
  then it will cause a TypeError. In ES2015, a non-object argument will
  be coerced to an object.

Title: Will `Object.keys(x)` ever throw?


问:
Making 10 it write 1.0*10 with javascript
In this code that I wrote I want to show the words like this :
if we put 10000 it write 1.0*104
but it is not working.
In this code, we  write the number to the input file and after that we should click on the button it must show us the new number with that kind of thing.
but this code has a problem but I don't know where is it.
How can I solve the problem?

function check() {
  var K = 9 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10;
  var q1 = document.getElementById('q1').value;
  var q2 = document.getElementById('q2').value;
  var r = document.getElementById('r').value;
  var F = K * (q1 * q2) / (r * r);

  if (F >= 0) || (F <= 9) {
    document.getElementById('end2').innerHTML = F;
  }
  if
  else(F >= 10) || (F <= 99) {
    document.getElementById('end2').innerHTML = F / 10 + " * 10";
  }
  if
  else(F >= 100) || (F <= 999) {
    document.getElementById('end2').innerHTML = F / 100 + " * 102";
  }
  if
  else(F >= 1000) || (F <= 9999) {
    document.getElementById('end2').innerHTML = F / 1000 + " * 103";
  }
  if
  else(F >= 10000) || (F <= 99999) {
    document.getElementById('end2').innerHTML = F / 10000 + " * 104";
  }
  if
  else(F >= 100000) || (F <= 999999) {
    document.getElementById('end2').innerHTML = F / 100000 + " * 105";
  }
  if
  else(F >= 1000000) || (F <= 9999999) {
    document.getElementById('end2').innerHTML = F / 1000000 + " * 106";
  }
  if
  else(F >= 10000000) || (F <= 99999999) {
    document.getElementById('end2').innerHTML = F / 10000000 + " * 107";
  }
  if
  else(F >= 100000000) || (F <= 999999999) {
    document.getElementById('end2').innerHTML = F / 100000000 + " * 108";
  }
  if
  else(F >= 1000000000) || (F <= 9999999999) {
    document.getElementById('end2').innerHTML = F / 1000000000 + " * 109";
  }
  if
  else(F >= 10000000000) || (F <= 99999999999) {
    document.getElementById('end2').innerHTML = F / 10000000000 + " * 1010";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="q1" placeholder="q1">
<input type="text" id="q2" placeholder="q2">
<input type="text" id="r" placeholder="r">
<input type="submit" onClick="check()">
<p id="end2"></p></code>```

答:
Another way of achieving this without writing so many conditions would be using toExponential() method, which returns a string with scientific notation. And then use replace() method to replace the 'e' character. </p>

```<code>function check()
        {
            var K = 9*10*10*10*10*10*10*10*10*10;
            var q1 = document.getElementById('q1').value;
            var q2 = document.getElementById('q2').value;
            var r = document.getElementById('r').value;
            var F = K*(q1*q2)/(r*r);

            var num = F;
            var n = num.toExponential();
            n = n.replace(/e\+/g, '*10<sup>');
            n = n.replace(/e\-/g, '*10<sup>-');
            n+='</sup>';

            document.getElementById('end2').innerHTML = n;
        }
</code>```

Body:
In this code that I wrote I want to show the words like this :
if we put 10000 it write 1.0*104
but it is not working.
In this code, we  write the number to the input file and after that we should click on the button it must show us the new number with that kind of thing.
but this code has a problem but I don't know where is it.
How can I solve the problem?

function check() {
  var K = 9 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10;
  var q1 = document.getElementById('q1').value;
  var q2 = document.getElementById('q2').value;
  var r = document.getElementById('r').value;
  var F = K * (q1 * q2) / (r * r);

  if (F >= 0) || (F <= 9) {
    document.getElementById('end2').innerHTML = F;
  }
  if
  else(F >= 10) || (F <= 99) {
    document.getElementById('end2').innerHTML = F / 10 + " * 10";
  }
  if
  else(F >= 100) || (F <= 999) {
    document.getElementById('end2').innerHTML = F / 100 + " * 102";
  }
  if
  else(F >= 1000) || (F <= 9999) {
    document.getElementById('end2').innerHTML = F / 1000 + " * 103";
  }
  if
  else(F >= 10000) || (F <= 99999) {
    document.getElementById('end2').innerHTML = F / 10000 + " * 104";
  }
  if
  else(F >= 100000) || (F <= 999999) {
    document.getElementById('end2').innerHTML = F / 100000 + " * 105";
  }
  if
  else(F >= 1000000) || (F <= 9999999) {
    document.getElementById('end2').innerHTML = F / 1000000 + " * 106";
  }
  if
  else(F >= 10000000) || (F <= 99999999) {
    document.getElementById('end2').innerHTML = F / 10000000 + " * 107";
  }
  if
  else(F >= 100000000) || (F <= 999999999) {
    document.getElementById('end2').innerHTML = F / 100000000 + " * 108";
  }
  if
  else(F >= 1000000000) || (F <= 9999999999) {
    document.getElementById('end2').innerHTML = F / 1000000000 + " * 109";
  }
  if
  else(F >= 10000000000) || (F <= 99999999999) {
    document.getElementById('end2').innerHTML = F / 10000000000 + " * 1010";
  }
}

<input type="text" id="q1" placeholder="q1">
<input type="text" id="q2" placeholder="q2">
<input type="text" id="r" placeholder="r">
<input type="submit" onClick="check()">

Body:
Another way of achieving this without writing so many conditions would be using toExponential() method, which returns a string with scientific notation. And then use replace() method to replace the 'e' character.

function check()
        {
            var K = 9*10*10*10*10*10*10*10*10*10;
            var q1 = document.getElementById('q1').value;
            var q2 = document.getElementById('q2').value;
            var r = document.getElementById('r').value;
            var F = K*(q1*q2)/(r*r);

            var num = F;
            var n = num.toExponential();
            n = n.replace(/e\+/g, '*10<sup>');
            n = n.replace(/e\-/g, '*10<sup>-');
            n+='</sup>';

            document.getElementById('end2').innerHTML = n;
        }


问:
Trying to use PHP DateTime Class with Yii2 receiving class not found errors
Hello I am trying to create my own custom helper class to use with Yii2.  It is going to handle times so I'll be working with PHP's DateTime class.  I have

```<code><?php

namespace yii\helpers;

use Yii;

class Time
{
    public static function getTime()
    {
    $time = new DateTime('now', new DateTimeZone('UTC'));
    return $time->format('m-d-Y H:i:s');
    }
}
</code>```

To test it I added
    use yii\helpers\Time;
to a view file and called Time::getTime(); but Yii2 throws an ErrorException saying Class 'yii\helpers\DateTime' not found.

The php DateTime object works fine if I place the code directly into a view file and execute it so I'm not sure what my problem is.

答:
Add use for DateTime:

```<code>use Yii;
use DateTime;
</code>```

See use "global-namespace";

Body:
Hello I am trying to create my own custom helper class to use with Yii2.  It is going to handle times so I'll be working with PHP's DateTime class.  I have

<?php

namespace yii\helpers;

use Yii;

class Time
{
    public static function getTime()
    {
    $time = new DateTime('now', new DateTimeZone('UTC'));
    return $time->format('m-d-Y H:i:s');
    }
}

To test it I added
    use yii\helpers\Time;
to a view file and called Time::getTime(); but Yii2 throws an ErrorException saying Class 'yii\helpers\DateTime' not found.

The php DateTime object works fine if I place the code directly into a view file and execute it so I'm not sure what my problem is.

Body:
Add use for DateTime:

use Yii;
use DateTime;

See use "global-namespace";


问:
Handling reply.view with @types/hapi
I have been using hapi with typescript. I was able to write this:

```<code>export function displaySignupForm(request: Hapi.Request, reply: Hapi.IReply) {
  reply.view("users/signup");
}
</code>```

This worked.

The latest update of @types/hapi is 16.1.6, which has backward incompatible changes. The above code doesn't work. I understand now there is ReplyWithContinue and ReplyNoContinue. But I couldn't find a type that includes reply.view.

Which type in the latest @types/hapi has reply.view?

答: You have the wrong reply interface. It's Hapi.ReplyNoContinue

Title: Handling reply.view with @types/hapi

Body:
I have been using hapi with typescript. I was able to write this:

export function displaySignupForm(request: Hapi.Request, reply: Hapi.IReply) {
  reply.view("users/signup");
}

This worked.

The latest update of @types/hapi is 16.1.6, which has backward incompatible changes. The above code doesn't work. I understand now there is ReplyWithContinue and ReplyNoContinue. But I couldn't find a type that includes reply.view.

Which type in the latest @types/hapi has reply.view?


问:
Microsoft Access Database Engine 2016 Redistributable is not working
Why Microsoft Access Database Engine 2016 Redistributable is not working using the connection string

```<code>*string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Driver={Microsoft Access Driver (*.mdb,
*.accdb)};DBQ=path to mdb/accdb file;Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";*
</code>```

It throws an error

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the
local machine."

and after installing "2007 Office System Driver: Data Connectivity Components"
it works fine.

答: Most likely your application is running in 32 bit mode and you installed 64 bit driver</p>

ContentLicense: CC BY-SA 4.0

Body:
Why Microsoft Access Database Engine 2016 Redistributable is not working using the connection string

*string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Driver={Microsoft Access Driver (*.mdb,
*.accdb)};DBQ=path to mdb/accdb file;Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";*

It throws an error

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the
local machine."

and after installing "2007 Office System Driver: Data Connectivity Components"
it works fine.


问:
Cell range issue to create a chart using VBA code
I have cell Range(A2:C12) for creating charts. And using,

```<code>.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A2:C12")
</code>```

... code in VBA to create line chart.

But I need that instead of  providing cell Range("A2:C12") in vba, i want to define my cell range in excel itself. For e.g., in cell A14, I will type A2:C12. Finally Vba must fetch the data from cell a14.

答:
You can use a cell reference's value just as easily as a string literal:</p>

```<code>.Chart.SetSourceData Source:=Sheets("Sheet1").Range(Sheets("Sheet1").Range("A14").Text)
</code>```

Body:
I have cell Range(A2:C12) for creating charts. And using,

.Chart.SetSourceData Source:=Sheets("Sheet1").Range("A2:C12")

... code in VBA to create line chart.

But I need that instead of  providing cell Range("A2:C12") in vba, i want to define my cell range in excel itself. For e.g., in cell A14, I will type A2:C12. Finally Vba must fetch the data from cell a14.

Body:
You can use a cell reference's value just as easily as a string literal:

.Chart.SetSourceData Source:=Sheets("Sheet1").Range(Sheets("Sheet1").Range("A14").Text)


问:
Querying a Pandas dataframe
I am still very new to  Pandas and hence this might be very silly.I have Pandas data frame as follows:

```<code>>>> data_frame
     median quarter status  change
0     240   2015-1     BV     NaN
1     300   2015-2     BV    0.25
2     300   2015-1   CORR    0.00
3     240   2015-2   CORR   -0.20
</code>```

Now i need only the quarter 2015-2,so i perform the query

```<code>>>> data_frame.query('quarter == "2015-2"')
     median quarter status  change
 1     300  2015-2     BV    0.25
 2     240  2015-2   CORR   -0.20
</code>```

That works fine.However if I need to search via a variable name,it does not work.

```<code>>>> completed_quarter = '2015-2'
>>> data_frame.query('quarter == "completed_quarter"')
Empty DataFrame
Columns: [median, quarter, status, change]
Index: []
</code>```

I tried a few other combinations with single quotes, no quotes etc but nothing works.What am I doing wrong ? Is there any other way in Pandas through which I can accomplish the same thing ?

答:
You can access the value of the variable like this

```<code>completed_quarter = '2015-2'
data_frame.query('quarter == @completed_quarter')
</code>```

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html

Title: Querying a Pandas dataframe

Body:
I am still very new to  Pandas and hence this might be very silly.I have Pandas data frame as follows:

>>> data_frame
     median quarter status  change
0     240   2015-1     BV     NaN
1     300   2015-2     BV    0.25
2     300   2015-1   CORR    0.00
3     240   2015-2   CORR   -0.20

Now i need only the quarter 2015-2,so i perform the query

>>> data_frame.query('quarter == "2015-2"')
     median quarter status  change
 1     300  2015-2     BV    0.25
 2     240  2015-2   CORR   -0.20

That works fine.However if I need to search via a variable name,it does not work.

>>> completed_quarter = '2015-2'
>>> data_frame.query('quarter == "completed_quarter"')
Empty DataFrame
Columns: [median, quarter, status, change]
Index: []

I tried a few other combinations with single quotes, no quotes etc but nothing works.What am I doing wrong ? Is there any other way in Pandas through which I can accomplish the same thing ?

Body:
You can access the value of the variable like this

completed_quarter = '2015-2'
data_frame.query('quarter == @completed_quarter')

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html


问:
Checking if animation on exact button / texview / has ended
I would like to know, if there is a possibility to check if exact animation on button or textview has finished ?
I have a problem with simple menu animations with 6 widgets (2 buttons, 2 edittexts, 2 textviews).
I'm using AnimationListener but it works to all animations in the same time.
Problem shows up when one "fadeIn" animation is called in different times.
You can see that  "fadeIn" AnimationListener is called two times (first time when "fadeOut" animation has started, and second time when it's gone).

Sequence should be like that:
(1). registration_bt & login_bt -> fadeOut, (same time) email_tv & password_tv -> fadeIn (2). When registration_bt & login_b are gone, email_et & password_et -> fadeIn, (same time) email_tv & password_tv are visible. (3). email_et & email_tv & password_et & password_tv are visible.

Thanks for any advices!
AnimationListener screen.

答:
There is this way (from here): Will work but I would also like to see a better solution. GL

```<code>login_bt.animate().alpha(0).setDuration(2000).withEndAction(new Runnable() {
    @Override
        public void run() {
            email_tv.animate().alpha(1).setDuration(2000).withEndAction(new Runnable() ...
        }
    });
</code>```

Body:
There is this way (from here): Will work but I would also like to see a better solution. GL

login_bt.animate().alpha(0).setDuration(2000).withEndAction(new Runnable() {
    @Override
        public void run() {
            email_tv.animate().alpha(1).setDuration(2000).withEndAction(new Runnable() ...
        }
    });


问:
Is there a cleaner way to set null fields to "N/A"?
I have 5 plus elements in a view. Is there a cleaner way to check for nulls and set the values if they are before saving in my controller? For example:</p>

```<code>string FN = viewModel.FirstName;
if (String.IsNullOrEmpty(FN))
{
    FN = "N/A";
}
//copy and paste for lastname
//copy and paste for address
//etc
</code>```

答:
First and simplest way is: using ternary operator

```<code>string fristName = String.IsNullOrEmpty(viewModel.FirstName) ? "N/A" : viewModel.FirstName;
</code>```

Another option is using custom model binder:
ASP.NET Model Binder

Body:
I have 5 plus elements in a view. Is there a cleaner way to check for nulls and set the values if they are before saving in my controller? For example:

string FN = viewModel.FirstName;
if (String.IsNullOrEmpty(FN))
{
    FN = "N/A";
}
//copy and paste for lastname
//copy and paste for address
//etc

Body:
First and simplest way is: using ternary operator

string fristName = String.IsNullOrEmpty(viewModel.FirstName) ? "N/A" : viewModel.FirstName;

Another option is using custom model binder:
ASP.NET Model Binder


问:
What is the top bar height of iPhone X?
I would like to know exact height of top bar of iPhone X.
Could you please mention the status bar and navigation bar height of iPhone X.
Please help me.

答: Nav bar is 44pt as usual (when no large titles) and the status bar has increased from 20pt to 44pt.  Here's what you can type in the debugger to verify it:

Title: What is the top bar height of iPhone X?


问:
Sort model relationship date
I have two tables:

```<code>Discussion:
╔════╦════════════════╗
║ id ║     name       ║
╠════╬════════════════╣
║  1 ║ Stackoverflow  ║
║  2 ║ Stackoverflow2 ║
╚════╩════════════════╝

Message:
╔════╦════════════════╦═══════════╦════════════╗
║ id ║ discussion_id  ║  content  ║    date    ║
╠════╬════════════════╬═══════════╬════════════╣
║  1 ║       1        ║ message 1 ║  jan 2011  ║
║  2 ║       1        ║ message 2 ║  jan 2012  ║
║  3 ║       2        ║ message 3 ║  jan 2013  ║
║  4 ║       2        ║ message 4 ║  jan 2014  ║
╚════╩════════════════╩═══════════╩════════════╝
</code>```

The results of Discussion::find() should be sorted like this:

```<code>Stackoverflow2
Stackoverflow
</code>```

Because "Stackoverflow2" is more recent than "Stackoverflow" according to the dates in the Message table.

Do you have an idea?

答:
Your query must be like following,

select discussion.id, discussion.name from Discussion join message on message.discussion_id = Discussion.id order by message.date

Title: Sort model relationship date

Body:
I have two tables:

Discussion:
╔════╦════════════════╗
║ id ║     name       ║
╠════╬════════════════╣
║  1 ║ Stackoverflow  ║
║  2 ║ Stackoverflow2 ║
╚════╩════════════════╝

Message:
╔════╦════════════════╦═══════════╦════════════╗
║ id ║ discussion_id  ║  content  ║    date    ║
╠════╬════════════════╬═══════════╬════════════╣
║  1 ║       1        ║ message 1 ║  jan 2011  ║
║  2 ║       1        ║ message 2 ║  jan 2012  ║
║  3 ║       2        ║ message 3 ║  jan 2013  ║
║  4 ║       2        ║ message 4 ║  jan 2014  ║
╚════╩════════════════╩═══════════╩════════════╝

The results of Discussion::find() should be sorted like this:

Stackoverflow2
Stackoverflow

Because "Stackoverflow2" is more recent than "Stackoverflow" according to the dates in the Message table.

Do you have an idea?


答:
Create an extension method as such:

```<code>static class Helper
{
       public static string NotApplicableIfNullOrEmpty(this string str) => String.IsNullOrEmpty(str) ? "N/A" : str;
}
</code>```

then do something like:

```<code>string firstName = viewModel.FirstName.NotApplicableIfNullOrEmpty();
string lastName = viewModel.LastName.NotApplicableIfNullOrEmpty();
string address = viewModel.Address.NotApplicableIfNullOrEmpty();
</code>```

Title: Is there a cleaner way to set null fields to "N/A"?

Body:
Create an extension method as such:

static class Helper
{
       public static string NotApplicableIfNullOrEmpty(this string str) => String.IsNullOrEmpty(str) ? "N/A" : str;
}

then do something like:

string firstName = viewModel.FirstName.NotApplicableIfNullOrEmpty();
string lastName = viewModel.LastName.NotApplicableIfNullOrEmpty();
string address = viewModel.Address.NotApplicableIfNullOrEmpty();


问:
Java program on name Initials
I am writing a program that will give the Initials of the name(String) user gives as input.
I want to use the Space function while writing the name as the basis of the algorithm.
For eg:

```<code><Firstname><space><Lastname>
</code>```

taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before.
Can someone tell me how to implement this?
I'm trying this but getting one error.

Any help is dearly appreaciated..
P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding

```<code>public class Initials {
    public static void main(String[] args) {
        String name = new String();
        System.out.println("Enter your name: ");
        Scanner input = new Scanner(System.in);
        name = input.nextLine();

        System.out.println("You entered : " + name);
        String temp = new String(name.toUpperCase());

        System.out.println(temp);

        char c = name.charAt(0);
        System.out.println(c);

        for (int i = 1; i < name.length(); i++) {
            char c = name.charAt(i);

            if (c == '') {
                System.out.println(name.charAt(i - 1));
            }

        }
    }
}
</code>```

EDIT:
Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..

```<code>for (int i = 1; i < temp.length(); i++) {
    char c1 = temp.charAt(i);

    if (c1 == ' ') {
        System.out.print(temp.charAt(i + 1));
        System.out.print(".");
    }
}
</code>```

Thanks a lot guys :)

答:
Simply use a regex:

keep only characters that are following a whitespace

remove all remaining whitespace and finally

make it upper case:

" Foo Bar moo ".replaceAll("([^\\s])[^\\s]+", "$1").replaceAll("\\s", "").toUpperCase();

=> FBM

Title: Java program on name Initials

Body:
I am writing a program that will give the Initials of the name(String) user gives as input.
I want to use the Space function while writing the name as the basis of the algorithm.
For eg:

<Firstname><space><Lastname>

taking the char once in a for loop and checking if there is a space in between, if there is it will print the charecter that was just before.
Can someone tell me how to implement this?
I'm trying this but getting one error.

Any help is dearly appreaciated..
P.S- i am new to java and finding it a lot intresting. Sorry if there is a big blunder in the coding

public class Initials {
    public static void main(String[] args) {
        String name = new String();
        System.out.println("Enter your name: ");
        Scanner input = new Scanner(System.in);
        name = input.nextLine();

        System.out.println("You entered : " + name);
        String temp = new String(name.toUpperCase());

        System.out.println(temp);

        char c = name.charAt(0);
        System.out.println(c);

        for (int i = 1; i < name.length(); i++) {
            char c = name.charAt(i);

            if (c == '') {
                System.out.println(name.charAt(i - 1));
            }

        }
    }
}

EDIT:
Ok Finally got it. The algorithm is a lot fuzzy but its working and will try to do it next time with Substring..

for (int i = 1; i < temp.length(); i++) {
    char c1 = temp.charAt(i);

    if (c1 == ' ') {
        System.out.print(temp.charAt(i + 1));
        System.out.print(".");
    }
}

Thanks a lot guys :)


问:
getting error on sql query in asp.net using c#
I am using this sql query in c#

```<code>select t.testname,t.totalque,r.testdate,r.score
from test t, result r
where t.testid=r.testid
  and r.login='vsdep980'
</code>```

but it shows an error that is

invalid column name 'vsdep980'

now here vsdep980 is the value which is stored in the column login but why it shows this type of error.

now my code is

```<code>SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score from test t, result r where t.testid=r.testid and r.login=vsdep980", con);
con.Open();
int c = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (c > 0)
{
    Response.Write("<br><br><h1 class='head1'> You have not given any quiz</h1>");
    Response.End();
}
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow dr = null;
Response.Write("<table border='1' align='center'><tr class='style2'><td width='300'>Test Name </td><td> Total<br> Question </td><td> Date </td><td> Score </td></tr>");
foreach (DataRow dr1 in dt.Rows)
{
    dr = dr1;
    Response.Write("<tr class='style8'><td> "+dr[0]+" </td><td align='center'> "+dr[1]+" </td><td align='center'> "+dr[2]+" </td><td align='center'>"+dr[3]+" </td></tr>");
}
Response.Write("</table>");
</code>```

image of error msg

Please help me.

Thanks.

答:
You're executing a query that returns multiple columns (and, I'm assuming multiple rows) with a call to ExecuteScalar().  This method is primarily used for retrieving a single value from SQL Server (it returns the value from the first column of the first row of your data).  I expect that the first value of t.testname is not convertable to an Int32.

From your code, it looks like you're trying to check to see if any rows are returned from your query.  If that is the case, you should do something like this instead:

```<code>SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score from test t, result r where t.testid=r.testid and r.login='vsdep980'", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count == 0)
{
    Response.Write("<br><br><h1 class='head1'> You have not given any quiz</h1>");
    Response.End();
}
</code>```

Body:
I am using this sql query in c#

select t.testname,t.totalque,r.testdate,r.score
from test t, result r
where t.testid=r.testid
  and r.login='vsdep980'

but it shows an error that is

invalid column name 'vsdep980'

now here vsdep980 is the value which is stored in the column login but why it shows this type of error.

now my code is

SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score from test t, result r where t.testid=r.testid and r.login=vsdep980", con);
con.Open();
int c = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (c > 0)
{
    Response.Write("

 You have not given any quiz
");
    Response.End();
}
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow dr = null;
Response.Write("

Test Name 	 Total
 Question 	 Date 	 Score
");
foreach (DataRow dr1 in dt.Rows)
{
    dr = dr1;
    Response.Write("
 "+dr[0]+" 	 "+dr[1]+" 	 "+dr[2]+" 	"+dr[3]+"
");
}
Response.Write("
");

image of error msg

Please help me.

Thanks.

Body:
You're executing a query that returns multiple columns (and, I'm assuming multiple rows) with a call to ExecuteScalar().  This method is primarily used for retrieving a single value from SQL Server (it returns the value from the first column of the first row of your data).  I expect that the first value of t.testname is not convertable to an Int32.

From your code, it looks like you're trying to check to see if any rows are returned from your query.  If that is the case, you should do something like this instead:

SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score from test t, result r where t.testid=r.testid and r.login='vsdep980'", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count == 0)
{
    Response.Write("<br><br><h1 class='head1'> You have not given any quiz</h1>");
    Response.End();
}


问:
special characters french accents
We are fetching data from csv file through php, and trying to compare data to insert the right data in our database but php comparison is not working as data in file is with french accents.

Here is a piece of code we are working with.

```<code>if($data[0]=='Expression' && $data[1]=='Domaine (Domain)' &&  utf8_decode($data[2])==utf8_decode('DŽfinition (Definition)') && $data[3]=='Commentaire (Commentary)' && $data[4]=='Voir aussiÉ (See also É)' && $data[5]=='ƒquivalent anglais (English equivalent)' && $data[6]=='En contexte / exemple(s) É (In context / examples)' && $data[7]=='Source' )
     {
                 echo "<tr>
                      <td>".$data['0']."</td>
                      <td>".$data['1']."</td>
                      <td>".$data['2']."</td>
                      <td>".$data['3']."</td>
                      <td>".$data['4']."</td>
                      <td>".$data['5']."</td>
                      <td>".$data['6']."</td>
                      <td>".$data['7']."</td>
                      <td><i class='fa fa-close text-navy'></i></td>
                    </tr>";
         return true;
     }
     else
     {
         echo "invalid data";
         exit;
     }
</code>```

We have tried with this as well.

```<code>function convert($data)
{
    $value = utf8_encode($data);
    $value = iconv('UTF-8', 'ASCII//TRANSLIT', $value);
    return $value;
}
</code>```

Header is already placed output is fine

```<code>header('Content-Type: text/html; charset=iso-8859-1');
</code>```

We have tried with several php functions like utf_decode,html entities, html special char, htmlspecialchar_decode but nothing is working.

```<code>echo print_r(utf8_decode($data[2]));
</code>```

output is as following:

D?finition (Definition)1invalid data

Actual word is : DŽfinition (Definition)'

We are working on french dictionary and need to do real time searching on the data as well, please help with mysql as well, like which functions are needed to be called before insertion for decoding and which functions are needed to be called before showing data back to user encoding!

Hope my question is bit clear.

Thanks in advance

答:
To save the CSV in UTF8, open it in notepad.

And Go to File - Save As

Change the Encoding to UTF-8.

or with Libre Office :

https://csvimproved.com/support/questions-and-answers/916-save-a-csv-file-as-utf-8

Hope it ll help

Title: special characters french accents

Body:
We are fetching data from csv file through php, and trying to compare data to insert the right data in our database but php comparison is not working as data in file is with french accents.

Here is a piece of code we are working with.

if($data[0]=='Expression' && $data[1]=='Domaine (Domain)' &&  utf8_decode($data[2])==utf8_decode('DŽfinition (Definition)') && $data[3]=='Commentaire (Commentary)' && $data[4]=='Voir aussiÉ (See also É)' && $data[5]=='ƒquivalent anglais (English equivalent)' && $data[6]=='En contexte / exemple(s) É (In context / examples)' && $data[7]=='Source' )
     {
                 echo "

                      ".$data['0']."
                      ".$data['1']."
                      ".$data['2']."
                      ".$data['3']."
                      ".$data['4']."
                      ".$data['5']."
                      ".$data['6']."
                      ".$data['7']."

";
         return true;
     }
     else
     {
         echo "invalid data";
         exit;
     }

We have tried with this as well.

function convert($data)
{
    $value = utf8_encode($data);
    $value = iconv('UTF-8', 'ASCII//TRANSLIT', $value);
    return $value;
}

Header is already placed output is fine

header('Content-Type: text/html; charset=iso-8859-1');

We have tried with several php functions like utf_decode,html entities, html special char, htmlspecialchar_decode but nothing is working.

echo print_r(utf8_decode($data[2]));

output is as following:

D?finition (Definition)1invalid data

Actual word is : DŽfinition (Definition)'

We are working on french dictionary and need to do real time searching on the data as well, please help with mysql as well, like which functions are needed to be called before insertion for decoding and which functions are needed to be called before showing data back to user encoding!

Hope my question is bit clear.

Thanks in advance


问:
Loop method without freezing the GUI?
I am currently working on a small program that collects a list of match-ups from a website which I feed into a jList for my GUI.

I wanted to loop a method that refreshes the Elements of the List so that a match-up doesn't show up in the list once it is finished. For this I need to have the loop running all the time but this leads to the GUI freezing.

I tried to find a way around it and read something about a Timer which didn't quite work for me and creating a new Thread but this didn't work with my list as it got out of bounds after the first loop.

I checked that it has nothing to do with the method that I call so the method that needs to be looped isn't the problem.

Does anyone have an idea how I can loop a method without freezing the whole GUI. Something like this

```<code>while (true) {
   dlm.removeAllElements(); //To remove all elements from the List
   getMatches(); //Adds the matches to dlm whic
    sleep(6000); //wait 6 seconds to refresh
}
</code>```

This is the code which I used to test a loop that doesn't crash.

```<code>new Thread(new Runnable() {
   public void run() {
      while (true) {
         dlm.removeAllElements(); //To remove all elements from the List
         getMatches(); //Adds the matches to dlm whic
         sleep(6000); //wait 6 seconds to refresh
      }
    };
 }).start();
</code>```

答:
First have a look at Concurrency in Swing, in particular the section in Worker Threads.

Based on the limited code, I’d also recommend having a look at How to use Swing Timers

Remember, Swing is NOT thread safe and IS single threaded.  This means (as you've discovered) that you should not perform long running or blocking operations within the context of the Event Dispatching Thread AND you should not update the UI from outside the context of the Event Dispatching Thread.

Both solutions (SwingWorker and Swing Timer) provide means to allow you to wait for some period of time before updating the UI, which you use will ultimately depend on your overall problem

Title: Loop method without freezing the GUI?

Body:
I am currently working on a small program that collects a list of match-ups from a website which I feed into a jList for my GUI.

I wanted to loop a method that refreshes the Elements of the List so that a match-up doesn't show up in the list once it is finished. For this I need to have the loop running all the time but this leads to the GUI freezing.

I tried to find a way around it and read something about a Timer which didn't quite work for me and creating a new Thread but this didn't work with my list as it got out of bounds after the first loop.

I checked that it has nothing to do with the method that I call so the method that needs to be looped isn't the problem.

Does anyone have an idea how I can loop a method without freezing the whole GUI. Something like this

while (true) {
   dlm.removeAllElements(); //To remove all elements from the List
   getMatches(); //Adds the matches to dlm whic
    sleep(6000); //wait 6 seconds to refresh
}

This is the code which I used to test a loop that doesn't crash.

new Thread(new Runnable() {
   public void run() {
      while (true) {
         dlm.removeAllElements(); //To remove all elements from the List
         getMatches(); //Adds the matches to dlm whic
         sleep(6000); //wait 6 seconds to refresh
      }
    };
 }).start();