问:
Stack can't find libgfortran-3.dll when trying to build with hmatrix
I am trying to setup hmatrix on my Windows 10 machine with GHC 8.0.2.
I was following the answer here but when I try to build it says that it cannot find libgfortran-3.dll although I am sure I added it to the bin folder in the BLAS directory.
My code is in here
I run stack build and this is what I get:

```<code>hmatrix-0.18.0.0: configure
Progress: 1/2
--  While building package hmatrix-0.18.0.0 using:
      C:\sr\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe --builddir=.stack-work\dist\ca59d0ab configure "--with-ghc=C:\\Program Files\\Haskell Platform\\8.0.2\\bin\\ghc.EXE" "--with-ghc-pkg=C:\\Program Files\\Haskell Platform\\8.0.2\\bin\\ghc-pkg.EXE" --user --package-db=clear --package-db=global --package-db=C:\sr\snapshots\b201cfe6\pkgdb --package-db=D:\Haskell\networks\.stack-work\install\65995373\pkgdb --libdir=D:\Haskell\networks\.stack-work\install\65995373\lib --bindir=D:\Haskell\networks\.stack-work\install\65995373\bin --datadir=D:\Haskell\networks\.stack-work\install\65995373\share --libexecdir=D:\Haskell\networks\.stack-work\install\65995373\libexec --sysconfdir=D:\Haskell\networks\.stack-work\install\65995373\etc --docdir=D:\Haskell\networks\.stack-work\install\65995373\doc\hmatrix-0.18.0.0 --htmldir=D:\Haskell\networks\.stack-work\install\65995373\doc\hmatrix-0.18.0.0 --haddockdir=D:\Haskell\networks\.stack-work\install\65995373\doc\hmatrix-0.18.0.0 --dependency=array=array-0.5.1.1 --dependency=base=base-4.9.1.0 --dependency=binary=binary-0.8.3.0 --dependency=bytestring=bytestring-0.10.8.1 --dependency=deepseq=deepseq-1.4.2.0 --dependency=random=random-1.1-9tceXaeYIMZ4JrKq20Egog --dependency=split=split-0.2.3.1-FWyXC6nhV0H3AfM8IzrEFk --dependency=storable-complex=storable-complex-0.2.2-G9QzpmZTKvgKKVagrcRWdL --dependency=vector=vector-0.11.0.0-HhutbadagxHIONIkSRJEug -fopenblas --extra-include-dirs=C:\OpenBLAS-v0.2.19-Win64-int32\include --extra-include-dirs=C:\Users\Yotam\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\include --extra-lib-dirs=C:\OpenBLAS-v0.2.19-Win64-int32\bin --extra-lib-dirs=C:\Users\Yotam\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\lib
    Process exited with code: ExitFailure 1
    Logs have been written to: D:\Haskell\networks\.stack-work\logs\hmatrix-0.18.0.0.log

    Configuring hmatrix-0.18.0.0...
    Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe: Missing dependency on a foreign
    library:
    * Missing C library: libgfortran-3
    This problem can usually be solved by installing the system package that
    provides this library (you may need the "-dev" version). If the library is
    already installed but in a non-standard location then you can use the flags
    --extra-include-dirs= and --extra-lib-dirs= to specify where it is.
</code>```

D:\OpenBLAS-v0.2.19-Win64-int32\bin includes both libopenblas.dll and libgfortran-3.dll and the blas directory was taken from this url

Thanks for any help

答:
I've managed to install it as follows.

In yourpath\to\stack\x86_64-windows\msys2-20150512, open a msys2 shell by double-clicking on msys2_shell.bat.

In the shell, type:

```<code>pacman -S mingw-w64-x86_64-toolchain
</code>```

Then add these "extra" in stack.yaml:

```<code>extra-include-dirs:
- yourpath\to\OpenBLAS\include
extra-lib-dirs:
- yourpath\to\OpenBLAS\lib
- yourpath\to\stack\x86_64-windows\msys2-20150512\usr\lib\gcc\x86_64-pc-msys\6.3.0
- yourpath\to\stack\x86_64-windows\msys2-20150512\mingw64\bin
</code>```

Body:
I am trying to setup hmatrix on my Windows 10 machine with GHC 8.0.2.
I was following the answer here but when I try to build it says that it cannot find libgfortran-3.dll although I am sure I added it to the bin folder in the BLAS directory.
My code is in here
I run stack build and this is what I get:

hmatrix-0.18.0.0: configure
Progress: 1/2
--  While building package hmatrix-0.18.0.0 using:
      C:\sr\setup-exe-cache\x86_64-windows\Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe --builddir=.stack-work\dist\ca59d0ab configure "--with-ghc=C:\\Program Files\\Haskell Platform\\8.0.2\\bin\\ghc.EXE" "--with-ghc-pkg=C:\\Program Files\\Haskell Platform\\8.0.2\\bin\\ghc-pkg.EXE" --user --package-db=clear --package-db=global --package-db=C:\sr\snapshots\b201cfe6\pkgdb --package-db=D:\Haskell\networks\.stack-work\install\65995373\pkgdb --libdir=D:\Haskell\networks\.stack-work\install\65995373\lib --bindir=D:\Haskell\networks\.stack-work\install\65995373\bin --datadir=D:\Haskell\networks\.stack-work\install\65995373\share --libexecdir=D:\Haskell\networks\.stack-work\install\65995373\libexec --sysconfdir=D:\Haskell\networks\.stack-work\install\65995373\etc --docdir=D:\Haskell\networks\.stack-work\install\65995373\doc\hmatrix-0.18.0.0 --htmldir=D:\Haskell\networks\.stack-work\install\65995373\doc\hmatrix-0.18.0.0 --haddockdir=D:\Haskell\networks\.stack-work\install\65995373\doc\hmatrix-0.18.0.0 --dependency=array=array-0.5.1.1 --dependency=base=base-4.9.1.0 --dependency=binary=binary-0.8.3.0 --dependency=bytestring=bytestring-0.10.8.1 --dependency=deepseq=deepseq-1.4.2.0 --dependency=random=random-1.1-9tceXaeYIMZ4JrKq20Egog --dependency=split=split-0.2.3.1-FWyXC6nhV0H3AfM8IzrEFk --dependency=storable-complex=storable-complex-0.2.2-G9QzpmZTKvgKKVagrcRWdL --dependency=vector=vector-0.11.0.0-HhutbadagxHIONIkSRJEug -fopenblas --extra-include-dirs=C:\OpenBLAS-v0.2.19-Win64-int32\include --extra-include-dirs=C:\Users\Yotam\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\include --extra-lib-dirs=C:\OpenBLAS-v0.2.19-Win64-int32\bin --extra-lib-dirs=C:\Users\Yotam\AppData\Local\Programs\stack\x86_64-windows\msys2-20150512\mingw64\lib
    Process exited with code: ExitFailure 1
    Logs have been written to: D:\Haskell\networks\.stack-work\logs\hmatrix-0.18.0.0.log

    Configuring hmatrix-0.18.0.0...
    Cabal-simple_Z6RU0evB_1.24.2.0_ghc-8.0.2.exe: Missing dependency on a foreign
    library:
    * Missing C library: libgfortran-3
    This problem can usually be solved by installing the system package that
    provides this library (you may need the "-dev" version). If the library is
    already installed but in a non-standard location then you can use the flags
    --extra-include-dirs= and --extra-lib-dirs= to specify where it is.

D:\OpenBLAS-v0.2.19-Win64-int32\bin includes both libopenblas.dll and libgfortran-3.dll and the blas directory was taken from this url

Thanks for any help

Body:
I've managed to install it as follows.

In yourpath\to\stack\x86_64-windows\msys2-20150512, open a msys2 shell by double-clicking on msys2_shell.bat.

In the shell, type:

pacman -S mingw-w64-x86_64-toolchain

Then add these "extra" in stack.yaml:

extra-include-dirs:
- yourpath\to\OpenBLAS\include
extra-lib-dirs:
- yourpath\to\OpenBLAS\lib
- yourpath\to\stack\x86_64-windows\msys2-20150512\usr\lib\gcc\x86_64-pc-msys\6.3.0
- yourpath\to\stack\x86_64-windows\msys2-20150512\mingw64\bin


来源: stackexchange

问:
how to set session variable and validation both together on same button in php
I'm a newbie in php. I want to validate a form and set the form data to the session variables so as to use them onto next page.
here is the code,

```<code><?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function val(){
    var n=document.f.cname.value;
    if(n==""||n==null){
        alert("Please enter name field.");
        return false;
    }
}
</script>
</head>
<body>
<form method="post" action="<?php $_Php_SELF?>" onsubmit="return val()">
name : <input type="text" name="cname" />
<input type="Submit" name="submit" value="Sub"/>
</form>
<?php
if(isset($_POST['submit'])){
    $_SESSION['caname']=$_POST['cname'];
    header("location:sessiontest2.php");
}
?>
</body>
</html>
</code>```

The second page just echos the session variable.
Without validation it works fine.

答:
The

```<code>if(isset($_POST['submit'])){
    $_SESSION['caname']=$_POST['cname'];
    header("location:sessiontest2.php");
}
</code>```

has to be at the top of the page after the session_start(), because the header function must be called before html is printed out.

Other than that it looks fine.

ContentLicense: CC BY-SA 3.0

Body:
I'm a newbie in php. I want to validate a form and set the form data to the session variables so as to use them onto next page.
here is the code,

<?php
session_start();
?>

<form method="post" action="<?php $_Php_SELF?>" onsubmit="return val()">
name : <input type="text" name="cname" />
<input type="Submit" name="submit" value="Sub"/>
</form>
<?php
if(isset($_POST['submit'])){
    $_SESSION['caname']=$_POST['cname'];
    header("location:sessiontest2.php");
}
?>

The second page just echos the session variable.
Without validation it works fine.

Body:
The

if(isset($_POST['submit'])){
    $_SESSION['caname']=$_POST['cname'];
    header("location:sessiontest2.php");
}

has to be at the top of the page after the session_start(), because the header function must be called before html is printed out.

Other than that it looks fine.


问:
Div bottom of div

div.div1 {
  border: 1px solid red;
  height: 100px;
}
div.div2 {
  border: 1px solid yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div></code>```

I use the above code to make a big div contain two smallers. The first one should be on the top and the second on the bottom. The top part works good but for the second div I can't make it to be on the bottom of the bigger div... What should I use?

答:
You can make the parent a flex column and use justify-content: space-between to separate the children.

div.div1 {
  border: 1px solid red;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
div.div2 {
  border: 1px solid yellow;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div></code>```

Title: Div bottom of div

Body:
div.div1 {
  border: 1px solid red;
  height: 100px;
}
div.div2 {
  border: 1px solid yellow;
}

Test1

Test2

I use the above code to make a big div contain two smallers. The first one should be on the top and the second on the bottom. The top part works good but for the second div I can't make it to be on the bottom of the bigger div... What should I use?

Body:
You can make the parent a flex column and use justify-content: space-between to separate the children.

div.div1 {
  border: 1px solid red;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
div.div2 {
  border: 1px solid yellow;
}

<div class = "div1">
  <div class = "div2">Test1</div>
  <div class = "div2">Test2</div>
</div>


问:
Can't set adapter of ListView because the ListView has a null object reference
I am trying to make a TabLayout with a ViewPager, but whenever I leave the app (Don't close it, just switch to another app and back) the fragments kind of get killed. I don't know that for sure, but the fragment's need to reCreate, and then fail.

The code for creating the TabLayout, TabLayoutAdapter and the ViewPager:

```<code>    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
    MyTabLayoutAdapter tabLayoutAdapter;
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

    tabLayout.addTab(tabLayout.newTab().setText("-2"));
    tabLayout.addTab(tabLayout.newTab().setText("-1"));
    tabLayout.addTab(tabLayout.newTab().setText("0"));
    tabLayout.addTab(tabLayout.newTab().setText("1"));
    tabLayout.addTab(tabLayout.newTab().setText("2"));

    tabLayoutAdapter = new MyTabLayoutAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(tabLayoutAdapter);
    viewPager.setOffscreenPageLimit(3);
    tabLayout.setupWithViewPager(viewPager);
    viewPager.setCurrentItem(2);
</code>```

The code of my TabLayoutAdapter:

```<code>public class MyTabLayoutAdapter extends FragmentStatePagerAdapter {
    private MyFragment fragmentOne;
    private MyFragment fragmentTwo;
    private MyFragment fragmentDefault;
    private MyFragment fragmentFour;
    private MyFragment fragmentFive;
    private int numberOfTabs;

    public MyTabLayoutAdapter(FragmentManager fragmentManager, int numberOfTabs) {
        super(fragmentManager);
        fragmentOne = new MyFragment();
        fragmentTwo = new MyFragment();
        fragmentDefault = new MyFragment();
        fragmentFour = new MyFragment();
        fragmentFive = new MyFragment();
        this.numberOfTabs = numberOfTabs;
    }

    @Override
    public MyFragment getItem(int position) {
        switch (position) {
            case 0:
                return fragmentOne;
            case 1:
                return fragmentTwo;
            case 2:
                return fragmentDefault;
            case 3:
                return fragmentFour;
            case 4:
                return fragmentFive;
            default:
                return fragmentDefault;
        }
    }

    @Override
    public int getCount() {
        return numberOfTabs;
    }
}
</code>```

The MyFragment fragment:

```<code>public class MyFragment extends Fragment {
    private View currentView;
    private ListView listView;

    public MyFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        currentView = LayoutInflater.from(getContext()).inflate(R.layout.my_fragment_layout, container, false);
        listView = (ListView) currentView.findViewById(R.id.listview);
        return currentView;
    }

    //This line throws a NullPointer when I resume the app
    public void populateListView(MyListAdapter myListAdapter) {
        listView.setAdapter(myListAdapter);
    }
}
</code>```

Whenever I call

```<code>MyListAdapter myListAdapter = new MyListAdapter(this, R.layout.my_item, justSomeStringArray);
tabLayoutAdapter.getItem(0).populateListView(myListAdapter);
</code>```

I get a NullPointerException saying that it can't set a adapter on a null object reference.

Anyone any idea how I can fix this?

答:
onCreateView() is not called on a fragment until the fragment is being added to a FragmentManager. Your final code snippet will only work, at best, if it is called sometime after fragmentOne is added to a FragmentManager. Otherwise, the fragment's ListView will not exist yet.

In general, having code outside of a fragment attempt to manipulate the widgets inside that fragment — as you are doing here — is a bad idea.

Body:
I am trying to make a TabLayout with a ViewPager, but whenever I leave the app (Don't close it, just switch to another app and back) the fragments kind of get killed. I don't know that for sure, but the fragment's need to reCreate, and then fail.

The code for creating the TabLayout, TabLayoutAdapter and the ViewPager:

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
    MyTabLayoutAdapter tabLayoutAdapter;
    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);

    tabLayout.addTab(tabLayout.newTab().setText("-2"));
    tabLayout.addTab(tabLayout.newTab().setText("-1"));
    tabLayout.addTab(tabLayout.newTab().setText("0"));
    tabLayout.addTab(tabLayout.newTab().setText("1"));
    tabLayout.addTab(tabLayout.newTab().setText("2"));

    tabLayoutAdapter = new MyTabLayoutAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(tabLayoutAdapter);
    viewPager.setOffscreenPageLimit(3);
    tabLayout.setupWithViewPager(viewPager);
    viewPager.setCurrentItem(2);

The code of my TabLayoutAdapter:

public class MyTabLayoutAdapter extends FragmentStatePagerAdapter {
    private MyFragment fragmentOne;
    private MyFragment fragmentTwo;
    private MyFragment fragmentDefault;
    private MyFragment fragmentFour;
    private MyFragment fragmentFive;
    private int numberOfTabs;

    public MyTabLayoutAdapter(FragmentManager fragmentManager, int numberOfTabs) {
        super(fragmentManager);
        fragmentOne = new MyFragment();
        fragmentTwo = new MyFragment();
        fragmentDefault = new MyFragment();
        fragmentFour = new MyFragment();
        fragmentFive = new MyFragment();
        this.numberOfTabs = numberOfTabs;
    }

    @Override
    public MyFragment getItem(int position) {
        switch (position) {
            case 0:
                return fragmentOne;
            case 1:
                return fragmentTwo;
            case 2:
                return fragmentDefault;
            case 3:
                return fragmentFour;
            case 4:
                return fragmentFive;
            default:
                return fragmentDefault;
        }
    }

    @Override
    public int getCount() {
        return numberOfTabs;
    }
}

The MyFragment fragment:

public class MyFragment extends Fragment {
    private View currentView;
    private ListView listView;

    public MyFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        currentView = LayoutInflater.from(getContext()).inflate(R.layout.my_fragment_layout, container, false);
        listView = (ListView) currentView.findViewById(R.id.listview);
        return currentView;
    }

    //This line throws a NullPointer when I resume the app
    public void populateListView(MyListAdapter myListAdapter) {
        listView.setAdapter(myListAdapter);
    }
}

Whenever I call

MyListAdapter myListAdapter = new MyListAdapter(this, R.layout.my_item, justSomeStringArray);
tabLayoutAdapter.getItem(0).populateListView(myListAdapter);

I get a NullPointerException saying that it can't set a adapter on a null object reference.

Anyone any idea how I can fix this?


问:
iOS/Swift - Hide/Show UITabBarController when scrolling down/up
I'm quite new to iOS development. Right now i'm trying to hide my tabbar when I scroll down and when scrolling up the tabbar should appear. I would like to have this animated in the same way like the navigation bar. For the navigation bar I simply clicked the option in the Attributes Inspector. I saw some examples for the toolbar, but I cant adopt it the tabbar.

self.tabBarController?.tabBar.hidden = true just hides my tabbar, but its not animated like the navigation controller.

答:
Building on Ariel's answer, I have updated the code for Swift3. This worked great on my collection views.

```<code>override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0 {
            changeTabBar(hidden: true, animated: true)
        }else{
            changeTabBar(hidden: false, animated: true)
        }

    }

func changeTabBar(hidden:Bool, animated: Bool){
        let tabBar = self.tabBarController?.tabBar
        if tabBar!.isHidden == hidden{ return }
        let frame = tabBar?.frame
        let offset = (hidden ? (frame?.size.height)! : -(frame?.size.height)!)
        let duration:TimeInterval = (animated ? 0.5 : 0.0)
        tabBar?.isHidden = false
        if frame != nil
        {
            UIView.animate(withDuration: duration,
                                       animations: {tabBar!.frame = frame!.offsetBy(dx: 0, dy: offset)},
                                       completion: {
                                        print($0)
                                        if $0 {tabBar?.isHidden = hidden}
            })
        }
    }
</code>```

Body:
Building on Ariel's answer, I have updated the code for Swift3. This worked great on my collection views.

override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView.panGestureRecognizer.translation(in: scrollView).y < 0 {
            changeTabBar(hidden: true, animated: true)
        }else{
            changeTabBar(hidden: false, animated: true)
        }

    }

func changeTabBar(hidden:Bool, animated: Bool){
        let tabBar = self.tabBarController?.tabBar
        if tabBar!.isHidden == hidden{ return }
        let frame = tabBar?.frame
        let offset = (hidden ? (frame?.size.height)! : -(frame?.size.height)!)
        let duration:TimeInterval = (animated ? 0.5 : 0.0)
        tabBar?.isHidden = false
        if frame != nil
        {
            UIView.animate(withDuration: duration,
                                       animations: {tabBar!.frame = frame!.offsetBy(dx: 0, dy: offset)},
                                       completion: {
                                        print($0)
                                        if $0 {tabBar?.isHidden = hidden}
            })
        }
    }


问:
CSS: wrapping around text inside a drawn circle using CSS
I am using this CSS code to draw circles:

```<code>circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 100px;
    margin:5px;
}
</code>```

Using this in html I can draw 3 circles side-by-side with text inside them:

```<code> <circle>Text1</circle>
 <circle>Text2</circle>
 <circle>Text3</circle>
</code>```

which looks like this:

Now if I want to add more text in side the middle circle this is what happens:

```<code><circle>Text1</circle>
<circle>Text2 and more</circle>
<circle>Text3</circle>
</code>```

whoever, I want 'Text2 and more` to stay inside the second circle and just wraps around. How can I achieve that?

NOTE: I don't want to use display: table-cell as it doesn't work nicely on responsive sites and does not let circles wrap around and stay on top of each other if the view page is very narrow.

答:
This may suit your needs better, line-height is your man issue, but this will center your text properly, you may want to adjust the height/width/padding, padding should be 25% of the height

```<code><div class="circle">
  <div class="text">
    hello world i am a circle
   </div>
</div>
<div class="circle">
  <div class="text">
    hello world
   </div>
</div>
<div class="circle">
  <div class="text">
    hello superman i am a red sun
   </div>
</div>
</code>```

```<code>.circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    margin:5px;
    overflow:hidden;
    padding:25px;
    position:relative;
}
.text{
  transform:translate(-50%,-50%);
  position:absolute;
  top:50%;
  left:50%;
}
</code>```

Body:
I am using this CSS code to draw circles:

circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    line-height: 100px;
    margin:5px;
}

Using this in html I can draw 3 circles side-by-side with text inside them:

 <circle>Text1</circle>
 <circle>Text2</circle>
 <circle>Text3</circle>

which looks like this:

Now if I want to add more text in side the middle circle this is what happens:

<circle>Text1</circle>
<circle>Text2 and more</circle>
<circle>Text3</circle>

whoever, I want 'Text2 and more` to stay inside the second circle and just wraps around. How can I achieve that?

NOTE: I don't want to use display: table-cell as it doesn't work nicely on responsive sites and does not let circles wrap around and stay on top of each other if the view page is very narrow.

Body:
This may suit your needs better, line-height is your man issue, but this will center your text properly, you may want to adjust the height/width/padding, padding should be 25% of the height

<div class="circle">
  <div class="text">
    hello world i am a circle
   </div>
</div>
<div class="circle">
  <div class="text">
    hello world
   </div>
</div>
<div class="circle">
  <div class="text">
    hello superman i am a red sun
   </div>
</div>

.circle {
    background: #f00;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    display: inline-block;
    text-align: center;
    margin:5px;
    overflow:hidden;
    padding:25px;
    position:relative;
}
.text{
  transform:translate(-50%,-50%);
  position:absolute;
  top:50%;
  left:50%;
}


问:
TextView inside an ImageView
I have this picture which is the template for an italian license plate:

My app manages vehicles. I've thought to display all user's vehicles in a RecyclerView with CardView, where each CardView contains an ImageView (which displays the previous image) and a TextView, which contains the license plate. But how could I do to put the TextView in the correct position compared to the image displayed in the ImageView? And, the worst thing I think, how could I do to place the TextView correctly for all screens resolutions?

答: The best way to overlap two view is using a FrameLayout as parent than use layout_gravity and margin attributes on FrameLayout children to set their position</p>

Title: TextView inside an ImageView


问:
Recognize Text in images using Canny Edge detection in Opencv
I'm trying to extract text from colored background images. One approach that I'm trying is edge detection. Using that I convert the original image to a image that I can work with. This will eliminate all the color in the image leaving only the edges.

I use this code to get the edged Image

```<code>import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg',0)
edges = cv2.Canny(img,100,200)
</code>```

My problem is after I get these images how can I track the Letters in those images? Any help would be great. Thank you guys

These are the original and edge detected Images

Original Image

Edge Detected Image

答:
Using edge detection on this image is premature, because the edges of the character will get polluted by the edges of the background.

Here is what you can get by selecting the pixels close to white:

Interestingly, many people who post about similar problems believe edge detection to be the panacea. In my opinion it is quite often a waste and region segmentation is much more appropriate.

Body:
I'm trying to extract text from colored background images. One approach that I'm trying is edge detection. Using that I convert the original image to a image that I can work with. This will eliminate all the color in the image leaving only the edges.

I use this code to get the edged Image

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg',0)
edges = cv2.Canny(img,100,200)

My problem is after I get these images how can I track the Letters in those images? Any help would be great. Thank you guys

These are the original and edge detected Images

Original Image

Edge Detected Image


问:
make a file with the space in its name inaccessible in the cpanel using bash command
I'm installing a watcher system for my server, this will basically watch my directories for any change/delete/modify/create ... so I can call a .sh file in the watcher when those events occur so I have these in my watcher.sh file

```<code> #!/bin/bash
LOGFILE=/etc/watcher.log
chmod 000 -R $1
chown root $1
echo "$(date +%Y-%m-%d);$(date +%H:%M:%S);$1;$3;$2;watcher.sh" >> $LOGFILE
</code>```

It works fine when I upload a file called a.txt but if I upload a file with space in their names nothing happens. In the log file I have

```<code>2017-06-04;18:37:34;/home/domain/public_html/upload/a b.txt;IN_CREATE;128;watcher.sh
chmod: cannot access `/home/domain/public_html/upload/a': No such file or directory
chmod: cannot access `b.txt': No such file or directory
chown: cannot access `/home/domain/public_html/upload/a': No such file or directory
chown: cannot access `b.txt': No such file or directory
</code>```

the space in the name is messing this up. How can I fix this? Also why can I still delete the newly uploaded file from cpanel I tough by changing ownership to root it would be inaccessible in the cpanel.

答:
You may place quote characters around the parameters such as:

```<code>chmod 000 -R "$1"
chown root "$1"
</code>```

The quotes should resolve the issue with the spaces via the parameters in the shell script.

Body:
I'm installing a watcher system for my server, this will basically watch my directories for any change/delete/modify/create ... so I can call a .sh file in the watcher when those events occur so I have these in my watcher.sh file

 #!/bin/bash
LOGFILE=/etc/watcher.log
chmod 000 -R $1
chown root $1
echo "$(date +%Y-%m-%d);$(date +%H:%M:%S);$1;$3;$2;watcher.sh" >> $LOGFILE

It works fine when I upload a file called a.txt but if I upload a file with space in their names nothing happens. In the log file I have

2017-06-04;18:37:34;/home/domain/public_html/upload/a b.txt;IN_CREATE;128;watcher.sh
chmod: cannot access `/home/domain/public_html/upload/a': No such file or directory
chmod: cannot access `b.txt': No such file or directory
chown: cannot access `/home/domain/public_html/upload/a': No such file or directory
chown: cannot access `b.txt': No such file or directory

the space in the name is messing this up. How can I fix this? Also why can I still delete the newly uploaded file from cpanel I tough by changing ownership to root it would be inaccessible in the cpanel.

Body:
You may place quote characters around the parameters such as:

chmod 000 -R "$1"
chown root "$1"

The quotes should resolve the issue with the spaces via the parameters in the shell script.


问:
Find() Method MongoDB with Nodejs
I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.

When I try to run this I get:
 "TypeError: Cannot read property 'find' of undefined" error return.

If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.

```<code>module.exports = function(app, db) {

app.get('/foo', (req, res)=>{

db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        }
    });
 });
};
</code>```

Thanks

答:
db.collection('barCollection') is returning null for some reason.  You'll need to figure out why,  it's probably somewhere else in your code since you don't have the setup logic here.

I'd look at whether mongodb was connected properly (i.e. is the db instance you're passing that function actually connected to the database), is mongodb running and available on the port you configured it with, etc.

Title: Find() Method MongoDB with Nodejs

Body:
I'm currently trying to find all the documents that have a certain value of 'bar' in the key 'foo'. Using mongodb and nodejs.

When I try to run this I get:
 "TypeError: Cannot read property 'find' of undefined" error return.

If I try using findOne() it'll just return the first document that has the document with the value "bar" for the key "foo", however there are 3.

module.exports = function(app, db) {

app.get('/foo', (req, res)=>{

db.collection('barCollection').find({foo: {$all: ['bar']}}
,(err, item)=>{
 if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(item);
        }
    });
 });
};

Thanks


问:
What is Visual Studio 2010 going to look like?
I have heard several podcasters (most recently the guys on DotNetRocks) say that the look and feel of Visual Studio 2010 has been completely redesigned and Visual Studio rewritten in WPF.

I have been watching some demos on channel9 of the Visual Studio 2010 CTP and the only thing that looks different to me is the opening screen.

I read the notice on MSDN, but it doesn't say anything about the look/design of Visual Studio.

Has Microsoft reversed direction on this or are there going to be major changes made to UI of the final product?

答:
Highlights from the PDC Keynote #1 on Day 2 (see: PDC website)

Multi-monitor support for the IDE via
WPF.

Building classes from test classes.

Toggle TFS bugs over a code segment
in Debug mode.

Partial config files for debug,
release.

WYSIWYG Silverlight Designer.

OwnerDisplayName: Jim Anderson

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: alram


问:
error using apply.yearly inside xts package. How this works?
I have been using ts objects for a while but not too much xts, so i was trying to calculate mean, sum, last, first... (FUN) for every year in economic time series. When i try it i have weird result.

This is a quick example:
Considering x and y like monthly series, for two consecutive years:

```<code>x <- 1:12
y <- 1:12
serie <- c(x,y)
</code>```

Then i create a ts object

```<code>serie <- ts(serie,1990,,12)
</code>```

now i convert it to xts object

```<code>library(xts)

serie.xts <- as.xts(serie)

plot(serie.xts)
</code>```

as far i see, the series is properly  created

```<code>serie.xts
</code>```

The series looks ok

```<code>ene 1990    1
feb 1990    2
mar 1990    3
abr 1990    4
may 1990    5
jun 1990    6
jul 1990    7
ago 1990    8
sep 1990    9
oct 1990   10
nov 1990   11
dic 1990   12
ene 1991    1
feb 1991    2
mar 1991    3
abr 1991    4
may 1991    5
jun 1991    6
jul 1991    7
ago 1991    8
sep 1991    9
oct 1991   10
nov 1991   11
dic 1991   12
</code>```

Then comes my problem

for example, i try to get the last value for every year, as far i know this is what this function do:

```<code>apply.yearly(serie.xts,FUN = "last")
</code>```

but i get this:

```<code>ene 1990    1
ene 1991    1
dic 1991   12
</code>```

I was expecting this:
dic 1990   12
dic 1991   12

What am i doing wrong?
Is this the way this function works?
What this function do actually?

i don't understand what is this result.
Please help. And thanks for reading my question.

R 3.3.3
xts  0.9-7
zoo 1.8-0

答:
This is a bug in xts 0-9.7 that has been fixed in the development version. Run one of these commands to install from GitHub:

```<code>remotes::install_github("joshuaulrich/xts")
# or
devtools::install_github("joshuaulrich/xts")
</code>```

Then the apply.yearly call will work as you expect:

```<code>serie <- ts(c(1:12,1:12),1990,,12)
library(xts)
serie.xts <- as.xts(serie)
apply.yearly(serie.xts, last)
#          [,1]
# Dec 1990   12
# Dec 1991   12
</code>```

Body:
I have been using ts objects for a while but not too much xts, so i was trying to calculate mean, sum, last, first... (FUN) for every year in economic time series. When i try it i have weird result.

This is a quick example:
Considering x and y like monthly series, for two consecutive years:

x <- 1:12
y <- 1:12
serie <- c(x,y)

Then i create a ts object

serie <- ts(serie,1990,,12)

now i convert it to xts object

library(xts)

serie.xts <- as.xts(serie)

plot(serie.xts)

as far i see, the series is properly  created

serie.xts

The series looks ok

ene 1990    1
feb 1990    2
mar 1990    3
abr 1990    4
may 1990    5
jun 1990    6
jul 1990    7
ago 1990    8
sep 1990    9
oct 1990   10
nov 1990   11
dic 1990   12
ene 1991    1
feb 1991    2
mar 1991    3
abr 1991    4
may 1991    5
jun 1991    6
jul 1991    7
ago 1991    8
sep 1991    9
oct 1991   10
nov 1991   11
dic 1991   12

Then comes my problem

for example, i try to get the last value for every year, as far i know this is what this function do:

apply.yearly(serie.xts,FUN = "last")

but i get this:

ene 1990    1
ene 1991    1
dic 1991   12

I was expecting this:
dic 1990   12
dic 1991   12

What am i doing wrong?
Is this the way this function works?
What this function do actually?

i don't understand what is this result.
Please help. And thanks for reading my question.

R 3.3.3
xts  0.9-7
zoo 1.8-0

Body:
This is a bug in xts 0-9.7 that has been fixed in the development version. Run one of these commands to install from GitHub:

remotes::install_github("joshuaulrich/xts")
# or
devtools::install_github("joshuaulrich/xts")

Then the apply.yearly call will work as you expect:

serie <- ts(c(1:12,1:12),1990,,12)
library(xts)
serie.xts <- as.xts(serie)
apply.yearly(serie.xts, last)
#          [,1]
# Dec 1990   12
# Dec 1991   12


问:
Curses alternative for windows
Is there any alternative of the curses module for python to use in windows? I looked up in the python documentation, but there its mentioned that its for using in unix. I am not much familiar with these, so is there some way to use curses module in windows or is there some similar module specially for windows?
[I am using Python 3.3]</p>

答:
This is not a new solution, just an edit to a previous one.

In case the pip command is giving a 404 error you can try to download the packet from http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses
 and then write something like

```<code>pip install C:\..packetPath..\curses-2.2-cp35-none-win_amd64.whl
</code>```

Title: Curses alternative for windows

Body:
This is not a new solution, just an edit to a previous one.

In case the pip command is giving a 404 error you can try to download the packet from http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses
 and then write something like

pip install C:\..packetPath..\curses-2.2-cp35-none-win_amd64.whl


问:
How can I change the color of one letter in JavaScript?
I have a string and I want to change just one color letter in JavaScript.

HTML:

```<code><div id="lettersList">Hello</div>
</code>```

In my JavaScript file, I retrieve like this (normal)

```<code>var lettres = document.getElementById("lettersList");
</code>```

But I don't know how to change the color of just one word (the 'o' of "hello" for example).
If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.

答:
You can use the replace() method on the innerHTML property of the element:

const element = document.querySelector('#lettersList');
element.innerHTML = element.innerHTML.replace('o', 'o');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="lettersList">Hello</div></code>```

Body:
I have a string and I want to change just one color letter in JavaScript.

HTML:

Hello

In my JavaScript file, I retrieve like this (normal)

var lettres = document.getElementById("lettersList");

But I don't know how to change the color of just one word (the 'o' of "hello" for example).
If I change thanks to

for (var i=0; i<lettres.length; i++ { lettres[i].style.color = "yellow"; }

it changes all the text (of course). But I don't want that.

Body:
You can use the replace() method on the innerHTML property of the element:

const element = document.querySelector('#lettersList');
element.innerHTML = element.innerHTML.replace('o', '<span style="color: red;">o</span>');

<div id="lettersList">Hello</div>


问:
Java - TimeZone conversion issue with SQL timestamp
I am using MySQL database on the Server. My Web application Server is in US/Chicago but I want my DateTime values to be saved in Africa/Lagos time.

I got part of this code here from Stack Overflow but when I update a record it still shows Chicago time in the database record.
Please what am I doing wrong here?

```<code>public static boolean saveImageFileName(int id, String fileName) throws SQLException, IOException, IllegalArgumentException, ClassNotFoundException
{
    try(Connection conn = Config.getDatabaseConnection())
    {
        //Create a timezone object based on Africa/Lagos time zone
        SimpleTimeZone timeZone = new SimpleTimeZone(1, "Africa/Lagos");
        //Create a calendar object using the timezone object
        GregorianCalendar calendar = new GregorianCalendar(timeZone);
        //Create a timestamp object using the calendar's date and time
        Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
        //Create an SQL query String
        String sql = "UPDATE `requests` SET `filename` = ?, `uploaded_date` = ? WHERE `id` = ?";
        //Create a prepared statement object from database connection
        PreparedStatement pst = conn.prepareStatement(sql);
        //Set prepared statement parameters
        pst.setString(1, fileName);
        pst.setTimestamp(2, timestamp, calendar); //Set TimeStamp and Calendar
        pst.setInt(3, id);
        //Update the record
        int update = pst.executeUpdate();
        //return update result
        return update == 1;
    }
}
</code>```

答:
tl;dr

```<code>pst.setObject( 2 , Instant.now() ) ;  // Current moment in UTC.
</code>```

…and…

```<code>Instant instant = myResultSet.getObject( 2 , Instant.class ) ;  // Stored moment in UTC.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Lagos" ) ) ;   // Adjust from UTC to time zone. Same moment, same point on timeline, but different wall-clock time.
</code>```

Do not rely on toString

Apparently you are being confused by the output of the legacy date-time classes’ toString method. Among the many poor design decisions in those old classes was the anti-feature of applying the JVM’s current time zone while generating a String to textually represent the value of that date-time object. This creates the confusing illusion that the object has a time zone when it does not.

So you cannot use toString on those old classes as it does not faithfully represent the true value.

Using java.time

You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

```<code>ZoneId z = ZoneId.of( "Africa/Lagos" ) ) ;
ZonedDateTime zdt = ZonedDateTime.now( zdt ) ;
</code>```

But the time zone is irrelevant here as a java.sql.Timestamp is always in UTC. The equivalent is a Instant in java.time. You can extract an Instant from the ZonedDateTime or get the current moment in UTC as a Instant.

```<code>Instant instant = zdt.toInstant() ;  // Adjusting from a time zone to UTC.
</code>```

Or…

```<code>Instant instant = Instant.now() ;  // Current moment in UTC.
</code>```

If your JDBC driver complies with JDBC 4.2 or later, you can work directly with java.time types and forsake the legacy java.sql types. Call PreparedStatement::setObject and ResultSet::getObject.

If your JDBC has not yet been updated for java.time, convert to a java.sql.Timestamp using new methods added to the old classes.

```<code>java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;
</code>```

Going the other way, you can adjust an Instant into a particular time zone when you want to see that same moment through the lens of a particular region’s wall-clock time.

```<code>Instant instant = myResultSet.getObject( … , Instant.class )  // Or call: ts.toInstant()
ZonedDateTime zdt = instant.atZone( z ) ;
</code>```

As for generating String objects to represent textually the value of these java.time objects, you can rely on calling the toString methods. The java.time classes by default use the sensible practical formats defined in the ISO 8601 standard.

Body:
I am using MySQL database on the Server. My Web application Server is in US/Chicago but I want my DateTime values to be saved in Africa/Lagos time.

I got part of this code here from Stack Overflow but when I update a record it still shows Chicago time in the database record.
Please what am I doing wrong here?

public static boolean saveImageFileName(int id, String fileName) throws SQLException, IOException, IllegalArgumentException, ClassNotFoundException
{
    try(Connection conn = Config.getDatabaseConnection())
    {
        //Create a timezone object based on Africa/Lagos time zone
        SimpleTimeZone timeZone = new SimpleTimeZone(1, "Africa/Lagos");
        //Create a calendar object using the timezone object
        GregorianCalendar calendar = new GregorianCalendar(timeZone);
        //Create a timestamp object using the calendar's date and time
        Timestamp timestamp = new Timestamp(calendar.getTime().getTime());
        //Create an SQL query String
        String sql = "UPDATE `requests` SET `filename` = ?, `uploaded_date` = ? WHERE `id` = ?";
        //Create a prepared statement object from database connection
        PreparedStatement pst = conn.prepareStatement(sql);
        //Set prepared statement parameters
        pst.setString(1, fileName);
        pst.setTimestamp(2, timestamp, calendar); //Set TimeStamp and Calendar
        pst.setInt(3, id);
        //Update the record
        int update = pst.executeUpdate();
        //return update result
        return update == 1;
    }
}

Body:
tl;dr

pst.setObject( 2 , Instant.now() ) ;  // Current moment in UTC.

…and…

Instant instant = myResultSet.getObject( 2 , Instant.class ) ;  // Stored moment in UTC.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Lagos" ) ) ;   // Adjust from UTC to time zone. Same moment, same point on timeline, but different wall-clock time.

Do not rely on toString

Apparently you are being confused by the output of the legacy date-time classes’ toString method. Among the many poor design decisions in those old classes was the anti-feature of applying the JVM’s current time zone while generating a String to textually represent the value of that date-time object. This creates the confusing illusion that the object has a time zone when it does not.

So you cannot use toString on those old classes as it does not faithfully represent the true value.

Using java.time

You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

ZoneId z = ZoneId.of( "Africa/Lagos" ) ) ;
ZonedDateTime zdt = ZonedDateTime.now( zdt ) ;

But the time zone is irrelevant here as a java.sql.Timestamp is always in UTC. The equivalent is a Instant in java.time. You can extract an Instant from the ZonedDateTime or get the current moment in UTC as a Instant.

Instant instant = zdt.toInstant() ;  // Adjusting from a time zone to UTC.

Or…

Instant instant = Instant.now() ;  // Current moment in UTC.

If your JDBC driver complies with JDBC 4.2 or later, you can work directly with java.time types and forsake the legacy java.sql types. Call PreparedStatement::setObject and ResultSet::getObject.

If your JDBC has not yet been updated for java.time, convert to a java.sql.Timestamp using new methods added to the old classes.

java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;

Going the other way, you can adjust an Instant into a particular time zone when you want to see that same moment through the lens of a particular region’s wall-clock time.

Instant instant = myResultSet.getObject( … , Instant.class )  // Or call: ts.toInstant()
ZonedDateTime zdt = instant.atZone( z ) ;

As for generating String objects to represent textually the value of these java.time objects, you can rely on calling the toString methods. The java.time classes by default use the sensible practical formats defined in the ISO 8601 standard.


问:
jms server weblogic
In a recent interview, I was asked what JMS server were you using?I replied...we were using JMS server that ships with weblogic 9.x.
Is there a name for the server?I gather it is not ActiveMQ?</p>

答: No, it's the BEA implementation of the JMS standard.  They aren't using ActiveMQ.</p>

Title: jms server weblogic


问:
AWS CLI in Windows EC2 cannot use role to access S3
I am very new to AWS. I created an IAM role which has full access to S3. I assigned this role to a Windows Server EC2 instance. I then installed CLI on that instance. I then remoted into that instance using RDP, and started a CMD windows, and typed in

```<code>aws s3 ls
</code>```

It complained that

```<code>Unable to locate credentials. You can configure credentials by running "aws configure".
</code>```

Now that this EC2 has been assigned the role that has full access to S3, why can't I directly access S3?

答: To use AWS CLI with IAM Roles, you create a named profile. Instead of configuring this profile with credentials, you specify the ARN of the role and the name of the profile that has access to it.</p>

Body:
I am very new to AWS. I created an IAM role which has full access to S3. I assigned this role to a Windows Server EC2 instance. I then installed CLI on that instance. I then remoted into that instance using RDP, and started a CMD windows, and typed in

aws s3 ls

It complained that

Unable to locate credentials. You can configure credentials by running "aws configure".

Now that this EC2 has been assigned the role that has full access to S3, why can't I directly access S3?


问:
best way to copy an object of class in c++
if i have an object of class c1 suppose its name object1 and i want to make another object of the same class suppose object2 is it better to declare it like this:

```<code>c1 object2 = object1;
</code>```

or use the copy constructor

```<code>c1 object2 = c1(object1);
</code>```

i now that in C# it differs because in the first case it copies the reference of the object and in the second case it creates a new one, but i want to now if it is the same in c++

答: The two forms will do exactely the same thing (copy the object). It makes no difference.</p>

Body:
if i have an object of class c1 suppose its name object1 and i want to make another object of the same class suppose object2 is it better to declare it like this:

c1 object2 = object1;

or use the copy constructor

c1 object2 = c1(object1);

i now that in C# it differs because in the first case it copies the reference of the object and in the second case it creates a new one, but i want to now if it is the same in c++


问:
How should I handle importing third-party libraries within my setup.py script?
I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.

I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:

$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
  Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
        import appdirs
    ModuleNotFoundError: No module named 'appdirs'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\
```

<p>The reason is that I'm trying to import a third-party library <code>appdirs</code> in my <code>setup.py</code>, which is necessary for me to compute the <code>data_files</code> argument to <code>setup()</code>:</p>

<pre class="lang-py prettyprint-override"><code>try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import os
from collections import defaultdict

import appdirs
from <my-package>.version import __version__ as <my-package>_version

APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')

# ...

setup(
    # ...
    data_files=component_files,
)
</code>```

However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.

Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?

答:
I'm ignoring licensing issues in this answer. You definetly need to take these into account before you really do a release.

Is it acceptable to rely on third-party libraries like this in setup.py

Yes, it is acceptable but generally these should be minimized, especially if these are modules which have no obvious use for the end-user. Noone likes to have packages they don't need or use.

what is the recommended approach to using them?

There are basically 3 options:

Bootstrap them (for example use pip to programmatically install packages). For example setuptools provides an ez_setup.py file that can be used to bootstrap setuptools. Maybe that can be customized to download and install appdirs.

Include them (especially if it's a small package) in your project. For example appdirs is basically just a single file module. Pretty easy to copy and maintain in your project. Be very careful with licensing issues when you do that!

Fail gracefully when it's not possible to import them and let the user install them. For example:

```<code>try:
    import appdirs
except ImportError:
    raise ImportError('this package requires "appdirs" to be installed. '
                      'Install it first: "pip install appdirs".')
</code>```

Body:
I'm developing a Python application and in the process of branching off a release. I've got a PyPI server set up on a company server and I've copied a source distribution of my package onto it.

I checked that the package was being hosted on the server and then tried installing it on my local development machine. I ended up with this output:

$ pip3 install --trusted-host 172.16.1.92 -i http://172.16.1.92:5001/simple/ <my-package>
Collecting <my-package>
  Downloading http://172.16.1.92:5001/packages/<my-package>-0.2.0.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\setup.py", line 9, in <module>
        import appdirs
    ModuleNotFoundError: No module named 'appdirs'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\<me>\AppData\Local\Temp\pip-build-ubb3jkpr\<my-package>\

The reason is that I'm trying to import a third-party library appdirs in my setup.py, which is necessary for me to compute the data_files argument to setup():

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import os
from collections import defaultdict

import appdirs
from <my-package>.version import __version__ as <my-package>_version

APP_NAME = '<my-app>'
APP_AUTHOR = '<company>'
SYSTEM_COMPONENT_PLUGIN_DIR = os.path.join(appdirs.user_data_dir(APP_NAME, APP_AUTHOR), 'components')

# ...

setup(
    # ...
    data_files=component_files,
)

However, I don't have appdirs installed on my local dev machine and I don't expect the end users to have it either.

Is it acceptable to rely on third-party libraries like this in setup.py, and if so what is the recommended approach to using them? Is there a way I can ensure appdirs gets installed before it's imported in setup.py, or should I just document that appdirs is a required package to install my package?

Body:
I'm ignoring licensing issues in this answer. You definetly need to take these into account before you really do a release.

Is it acceptable to rely on third-party libraries like this in setup.py

Yes, it is acceptable but generally these should be minimized, especially if these are modules which have no obvious use for the end-user. Noone likes to have packages they don't need or use.

what is the recommended approach to using them?

There are basically 3 options:

Bootstrap them (for example use pip to programmatically install packages). For example setuptools provides an ez_setup.py file that can be used to bootstrap setuptools. Maybe that can be customized to download and install appdirs.

Include them (especially if it's a small package) in your project. For example appdirs is basically just a single file module. Pretty easy to copy and maintain in your project. Be very careful with licensing issues when you do that!

Fail gracefully when it's not possible to import them and let the user install them. For example:

try:
    import appdirs
except ImportError:
    raise ImportError('this package requires "appdirs" to be installed. '
                      'Install it first: "pip install appdirs".')


问:
jQuery draggable: distance and delay at same time does not work
I want to use the distance and delay parameter of a draggable at the same time. The goal is, that I do not need to move the mouse to start the drag effect, but it should start after 500ms to prevent unintentional moves.

This seems not to work. Here is an example for you to test:

```<code>$('.cube').draggable(
{
   distance: 0,
   delay: 500,
   start : function()
   {
    $('.cube').css('background', 'green');
   },
   stop: function()
   {
    $('.cube').css('background', 'red');
   }
});
</code>```

http://jsfiddle.net/MfegM/2392/

As it is, if you click without moving, it will not drag. When you remove the delay option, it will drag without moving but immediatly.

So is this a bug or a feature and is there any workaround?

Regards

Claus

答:
This occurred cause the delay not start all the function same time, I believe this a bug, however, you can use other function to increase your code.

```<code>$('.cube').mousedown(function()
{
        $(this).css('background', 'green');
})

$('.cube').mouseup(function()
{
        $(this).css('background', 'red');
})
</code>```

This work very well, I hope this code help you.

http://api.jqueryui.com/draggable/#option-delay

Body:
I want to use the distance and delay parameter of a draggable at the same time. The goal is, that I do not need to move the mouse to start the drag effect, but it should start after 500ms to prevent unintentional moves.

This seems not to work. Here is an example for you to test:

$('.cube').draggable(
{
   distance: 0,
   delay: 500,
   start : function()
   {
    $('.cube').css('background', 'green');
   },
   stop: function()
   {
    $('.cube').css('background', 'red');
   }
});

http://jsfiddle.net/MfegM/2392/

As it is, if you click without moving, it will not drag. When you remove the delay option, it will drag without moving but immediatly.

So is this a bug or a feature and is there any workaround?

Regards

Claus

Body:
This occurred cause the delay not start all the function same time, I believe this a bug, however, you can use other function to increase your code.

$('.cube').mousedown(function()
{
        $(this).css('background', 'green');
})

$('.cube').mouseup(function()
{
        $(this).css('background', 'red');
})

This work very well, I hope this code help you.

http://api.jqueryui.com/draggable/#option-delay


问:
if else with multiple conditions combined with AND and OR
I am looking for a way to create a new variable (1,0) with 1 for multiple conditions combined with AND and OR.

i.e. if

a > 3 AND b > 5

OR

c > 3 AND d > 5

OR

e > 3 AND f > 5

1

if not

0

I've tried coding it as;

```<code>df$newvar <- ifelse(df$a > 3 & df$b > 5 | df$c > 3 & df$d > 5 | df$e > 3 & df$f > 5,"1","0")
</code>```

But in my output many variables are coded as NA and the numbers do not seem to add up.

Does anyone have advice on a proper way to code this?

答:
We can subset the columns to evaluate for values greater than 3, get a list of logical vectors ('l1'), similarly for values greater than 5 ('l2'), then compare the corresponding elements of list using Map and Reduce it to a single vector.  With as.integer, we coerce the logical vector to binary

```<code>l1 <- lapply(df[c('a', 'c', 'e')] , function(x) x > 3 & !is.na(x))
l2 <- lapply(df[c('b', 'd', 'f')], function(x) x > 5 & !is.na(x))
df$newvar <- as.integer(Reduce(`|`, Map(`&`, l1, l2)))
df$newvar
#[1] 0 0 1 1 0 1 0 0 1 0
</code>```

Or using the OP's method

```<code>with(df, as.integer((a >3 & !is.na(a) & b > 5 & !is.na(b)) | (c > 3 & !is.na(c) &
        d > 5 & !is.na(d)) | (e > 3 & !is.na(e) & f > 5 & !is.na(f))))
#[1] 0 0 1 1 0 1 0 0 1 0
</code>```

data

```<code>set.seed(24)
df <- as.data.frame(matrix(sample(c(NA, 1:8), 6 * 10, replace = TRUE),
                ncol = 6, dimnames = list(NULL, letters[1:6])))
</code>```

Body:
I am looking for a way to create a new variable (1,0) with 1 for multiple conditions combined with AND and OR.

i.e. if

a > 3 AND b > 5

OR

c > 3 AND d > 5

OR

e > 3 AND f > 5

1

if not

0

I've tried coding it as;

df$newvar <- ifelse(df$a > 3 & df$b > 5 | df$c > 3 & df$d > 5 | df$e > 3 & df$f > 5,"1","0")

But in my output many variables are coded as NA and the numbers do not seem to add up.

Does anyone have advice on a proper way to code this?

Body:
We can subset the columns to evaluate for values greater than 3, get a list of logical vectors ('l1'), similarly for values greater than 5 ('l2'), then compare the corresponding elements of list using Map and Reduce it to a single vector.  With as.integer, we coerce the logical vector to binary

l1 <- lapply(df[c('a', 'c', 'e')] , function(x) x > 3 & !is.na(x))
l2 <- lapply(df[c('b', 'd', 'f')], function(x) x > 5 & !is.na(x))
df$newvar <- as.integer(Reduce(`|`, Map(`&`, l1, l2)))
df$newvar
#[1] 0 0 1 1 0 1 0 0 1 0

Or using the OP's method

with(df, as.integer((a >3 & !is.na(a) & b > 5 & !is.na(b)) | (c > 3 & !is.na(c) &
        d > 5 & !is.na(d)) | (e > 3 & !is.na(e) & f > 5 & !is.na(f))))
#[1] 0 0 1 1 0 1 0 0 1 0

data

set.seed(24)
df <- as.data.frame(matrix(sample(c(NA, 1:8), 6 * 10, replace = TRUE),
                ncol = 6, dimnames = list(NULL, letters[1:6])))


问:
How to create a list from another list according to a function?
I would like to create a list which has values which correspond to another list.
For example if I had:

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

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

```<code>listB = [1, 4, 9, 16,25, ...]
</code>```

I have already tried to do this by doing a while loop:

```<code>listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB
</code>```

But it just spits out an error message:

```<code>Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range
</code>```

Any advice?
Thanks

答:
You can try this, using a lambda function to apply whatever change you want to each element in the list. In this case, the function is squaring every value in the list:

```<code>listA = [1, 2, 3, 4, 5,...]

operation = lambda x:x**2

new_list = map(operation, listA)
</code>```

Also, you can perform the function operation in list comprehension:

```<code>new_list = [i**2 for i in listA]
</code>```

Body:
I would like to create a list which has values which correspond to another list.
For example if I had:

listA = [1, 2, 3, 4, 5,...]

and I would like to create another list which is the same, except all the values were varied according to x^2 (or any other function), giving:

listB = [1, 4, 9, 16,25, ...]

I have already tried to do this by doing a while loop:

listA = [1, 2, 3, 4]
listB = range(1, 4, 1)
i = 0
while i <= 4:
    listB [i] = (listA [i]) ** 2
    i = i + 1
print listA
print listB

But it just spits out an error message:

Traceback (most recent call last):
  File "/home/tim/Desktop/Python/test.py", line 5, in <module>
    listB [i] = (listA [i]) ** 2
IndexError: list assignment index out of range

Any advice?
Thanks

Body:
You can try this, using a lambda function to apply whatever change you want to each element in the list. In this case, the function is squaring every value in the list:

listA = [1, 2, 3, 4, 5,...]

operation = lambda x:x**2

new_list = map(operation, listA)

Also, you can perform the function operation in list comprehension:

new_list = [i**2 for i in listA]


问:
Separating Windows Forms and Classes C#
I am looking for a way to design a C# application. I understand 3-tier model, but idk how to apply this in a good C# design.

I have looked some asp.net mvc tutorials, but I am looking for a windows-form based tutorial.

is there any book or website to learn a way to implement this?

答:
the first you should know is that design patterns are not one-size-fits-all and therefore there is no such thing as a "Way to implement a design pattern".

If you only mean the 3 tier model then MVC is good choice because it clearly separates each layer from the other, for Windows forms development look for tutorials on Entity Framework (or just LINQ) which, along the classes that handle the logic of the application, becomes your model layer, all the forms, along the classes used to present the data, are your views and, or course, the user controllers are well... that, your controller.

I recommend you take a look at DoFactory website which has a great coverage on many design patterns.

Also I should point out that you may not find an implementation in doFactory, that's just a reference for a bunch of design patterns. JIC.

Title: Separating Windows Forms and Classes C#


问:
How to detect which dynamically created button inside a Fragment was clicked, from Activity?
I have a Fragment class that dynamically creates a grid of Buttons. An instance of that fragment is then created within the main activity which displays the grid. Here is my code:

Grid.java

```<code>public class Grid extends Fragment {

    LinearLayout myLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLayout = new LinearLayout(getActivity());
        LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        myLayout.setLayoutParams(lparams);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        for (int i = 0; i < 4; i++) {
            LinearLayout row = new LinearLayout(getActivity());
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btnTag = new Button(getActivity());
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btnTag.setLayoutParams(btnParams);
                btnTag.setText(" " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            myLayout.addView(row);
        }
        return myLayout;
    }
}
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }
}
</code>```

And in addition here is my content_mainactivity.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_mainactivity"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.owner.tables.MainActivity"
    tools:showIn="@layout/activity_mainactivity">

    <FrameLayout
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:id="@+id/grid"
        android:layout_centerHorizontal="true">
    </FrameLayout>

</RelativeLayout>
</code>```

So my question is, how can I detect if and which button was clicked in fragment from the Activity? Or if I can do this in the fragment, how to pass on the information to the activity?

答:
In MainActivity

```<code>public void doSomethingAtClick() {...}
</code>```

In fragment

```<code>((MainActivity)getActivity()).doSomethingAtClick()
</code>```

Body:
I have a Fragment class that dynamically creates a grid of Buttons. An instance of that fragment is then created within the main activity which displays the grid. Here is my code:

Grid.java

public class Grid extends Fragment {

    LinearLayout myLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLayout = new LinearLayout(getActivity());
        LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        myLayout.setLayoutParams(lparams);
        myLayout.setOrientation(LinearLayout.VERTICAL);

        for (int i = 0; i < 4; i++) {
            LinearLayout row = new LinearLayout(getActivity());
            LayoutParams rowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            row.setLayoutParams(rowParams);

            for (int j = 0; j < 4; j++) {
                final Button btnTag = new Button(getActivity());
                LayoutParams btnParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

                btnTag.setLayoutParams(btnParams);
                btnTag.setText(" " + (j + 1 + (i * 4)));
                btnTag.setId(j + 1 + (i * 4));
                row.addView(btnTag);
            }

            myLayout.addView(row);
        }
        return myLayout;
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_mainactivity);
        Grid grid = new Grid();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.grid, grid);
        transaction.commit();
    }
}

And in addition here is my content_mainactivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/content_mainactivity"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.owner.tables.MainActivity"
    tools:showIn="@layout/activity_mainactivity">

    <FrameLayout
        android:layout_width="320dp"
        android:layout_height="320dp"
        android:id="@+id/grid"
        android:layout_centerHorizontal="true">
    </FrameLayout>

</RelativeLayout>

So my question is, how can I detect if and which button was clicked in fragment from the Activity? Or if I can do this in the fragment, how to pass on the information to the activity?

Body:
In MainActivity

public void doSomethingAtClick() {...}

In fragment

((MainActivity)getActivity()).doSomethingAtClick()


答:
There is a smart syntax for building lists out of others:

```<code>listB = [x*x for x in listA]
</code>```

Edit: Never use range as a list directly, even if it makes a list in Python 2, because it spits out a range object in Python 3. Use list(range(...)) instead!

The popular numpy library provides a more concise syntax for doing such list operations, when the list would only consist out of numbers. It uses arrays that are faster in some circumstances like the element wise multiplication. The statement above can be rewritten as:

```<code>arrayB = arrayA * arrayA
</code>```

or

```<code>arrayB = arrayA ** 2
</code>```

or (not always recommended)

```<code>f = lambda a: a**2
arrayB = f(arrayA)
</code>```

The element wise multiplication is sometimes referred to as the hadamard product, that comes from vector arithmetics (there is also a@b in numpy). In numpy you have to create the arrays with np.array or np.arange. The last is similar to range in Python 2 in the way, that it creates an array directly.

Title: How to create a list from another list according to a function?

Body:
There is a smart syntax for building lists out of others:

listB = [x*x for x in listA]

Edit: Never use range as a list directly, even if it makes a list in Python 2, because it spits out a range object in Python 3. Use list(range(...)) instead!

The popular numpy library provides a more concise syntax for doing such list operations, when the list would only consist out of numbers. It uses arrays that are faster in some circumstances like the element wise multiplication. The statement above can be rewritten as:

arrayB = arrayA * arrayA

or

arrayB = arrayA ** 2

or (not always recommended)

f = lambda a: a**2
arrayB = f(arrayA)

The element wise multiplication is sometimes referred to as the hadamard product, that comes from vector arithmetics (there is also a@b in numpy). In numpy you have to create the arrays with np.array or np.arange. The last is similar to range in Python 2 in the way, that it creates an array directly.

ContentLicense: CC BY-SA 4.0


问:
django-phone-number-field error on get_or_create method
I am getting an error on get_or_create method of the Django model that contains PhoneNumberField(django-phonenumber-field==1.3.0) field.

It was working fine before, therefore I tried several older django-phonenumber-field(1.2.0, 1.1.0, 1.0.0) versions but the result was the same on all of them.

trying to do

TestModel.objects.get_or_create(name='Test name')

models.py

```<code>from django.utils.translation import get_language, ugettext_lazy as _
from phonenumber_field.modelfields import PhoneNumberField
from django.db import models

class TestModel(models.Model):
    name = models.CharField(max_length=20, blank=True,
                            null=True)
    phone = PhoneNumberField(
        _('Phone'), blank=True, unique=True, null=True,
          help_text=_('Enter phone number...')
    )
</code>```

traceback

```<code><ipython-input-3-03bfe9e47b71> in <module>()
----> 1 TestModel.objects.get_or_create(name='test')

/usr/local/lib/python3.5/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)
     83         def create_method(name, method):
     84             def manager_method(self, *args, **kwargs):
---> 85                 return getattr(self.get_queryset(), name)(*args, **kwargs)
     86             manager_method.__name__ = method.__name__
     87             manager_method.__doc__ = method.__doc__

/usr/local/lib/python3.5/site-packages/django/db/models/query.py in get_or_create(self, defaults, **kwargs)
    457         specifying whether an object was created.
    458         """
--> 459         lookup, params = self._extract_model_params(defaults, **kwargs)
    460         # The get() needs to be targeted at the write database in order
    461         # to avoid potential transaction consistency problems.

/usr/local/lib/python3.5/site-packages/django/db/models/query.py in _extract_model_params(self, defaults, **kwargs)
    519         params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}
    520         params.update(defaults)
--> 521         property_names = self.model._meta._property_names
    522         invalid_params = []
    523         for param in params:

/usr/local/lib/python3.5/site-packages/django/utils/functional.py in __get__(self, instance, cls)
     33         if instance is None:
     34             return self
---> 35         res = instance.__dict__[self.name] = self.func(instance)
     36         return res
     37

/usr/local/lib/python3.5/site-packages/django/db/models/options.py in _property_names(self)
    885         return frozenset({
    886             attr for attr in
--> 887             dir(self.model) if isinstance(getattr(self.model, attr), property)
    888         })

/usr/local/lib/python3.5/site-packages/django/db/models/options.py in <setcomp>(.0)
    885         return frozenset({
    886             attr for attr in
--> 887             dir(self.model) if isinstance(getattr(self.model, attr), property)
    888         })

/usr/local/lib/python3.5/site-packages/phonenumber_field/modelfields.py in __get__(self, instance, owner)
     31             raise AttributeError(
     32                 "The '%s' attribute can only be accessed from %s instances."
---> 33                 % (self.field.name, owner.__name__))
     34         return instance.__dict__[self.field.name]
     35

AttributeError: The 'phone' attribute can only be accessed from TestModel instances.
</code>```

答: Error occurs on Django version 1.11.2. Django 1.11.1 works fine.</p>

Body:
I am getting an error on get_or_create method of the Django model that contains PhoneNumberField(django-phonenumber-field==1.3.0) field.

It was working fine before, therefore I tried several older django-phonenumber-field(1.2.0, 1.1.0, 1.0.0) versions but the result was the same on all of them.

trying to do

TestModel.objects.get_or_create(name='Test name')

models.py

from django.utils.translation import get_language, ugettext_lazy as _
from phonenumber_field.modelfields import PhoneNumberField
from django.db import models

class TestModel(models.Model):
    name = models.CharField(max_length=20, blank=True,
                            null=True)
    phone = PhoneNumberField(
        _('Phone'), blank=True, unique=True, null=True,
          help_text=_('Enter phone number...')
    )

traceback

<ipython-input-3-03bfe9e47b71> in <module>()
----> 1 TestModel.objects.get_or_create(name='test')

/usr/local/lib/python3.5/site-packages/django/db/models/manager.py in manager_method(self, *args, **kwargs)
     83         def create_method(name, method):
     84             def manager_method(self, *args, **kwargs):
---> 85                 return getattr(self.get_queryset(), name)(*args, **kwargs)
     86             manager_method.__name__ = method.__name__
     87             manager_method.__doc__ = method.__doc__

/usr/local/lib/python3.5/site-packages/django/db/models/query.py in get_or_create(self, defaults, **kwargs)
    457         specifying whether an object was created.
    458         """
--> 459         lookup, params = self._extract_model_params(defaults, **kwargs)
    460         # The get() needs to be targeted at the write database in order
    461         # to avoid potential transaction consistency problems.

/usr/local/lib/python3.5/site-packages/django/db/models/query.py in _extract_model_params(self, defaults, **kwargs)
    519         params = {k: v for k, v in kwargs.items() if LOOKUP_SEP not in k}
    520         params.update(defaults)
--> 521         property_names = self.model._meta._property_names
    522         invalid_params = []
    523         for param in params:

/usr/local/lib/python3.5/site-packages/django/utils/functional.py in __get__(self, instance, cls)
     33         if instance is None:
     34             return self
---> 35         res = instance.__dict__[self.name] = self.func(instance)
     36         return res
     37

/usr/local/lib/python3.5/site-packages/django/db/models/options.py in _property_names(self)
    885         return frozenset({
    886             attr for attr in
--> 887             dir(self.model) if isinstance(getattr(self.model, attr), property)
    888         })

/usr/local/lib/python3.5/site-packages/django/db/models/options.py in <setcomp>(.0)
    885         return frozenset({
    886             attr for attr in
--> 887             dir(self.model) if isinstance(getattr(self.model, attr), property)
    888         })

/usr/local/lib/python3.5/site-packages/phonenumber_field/modelfields.py in __get__(self, instance, owner)
     31             raise AttributeError(
     32                 "The '%s' attribute can only be accessed from %s instances."
---> 33                 % (self.field.name, owner.__name__))
     34         return instance.__dict__[self.field.name]
     35

AttributeError: The 'phone' attribute can only be accessed from TestModel instances.


问:
JMeter JSON path extract value without array brackets []
I need the value out of an array, not the array brackets[ ].  Here is the JSON response I am trying to work with:

```<code>{
:   "@rpc":"1.0",
:   "@types":
:   [
:   :   "com.model.chart.PieChart",
:   :   "com.model.chart.PieChartData"
:   ],
:   "@data":
:   {
:   :   "@type":0,
:   :   "chartData":
:   :   [
:   :   :   {
:   :   :   :   "@type":1,
:   :   :   :   "data":0.0,
:   :   :   :   "name":"Yes"
:   :   :   },
:   :   :   {
:   :   :   :   "@type":1,
:   :   :   :   "data":13.0,
:   :   :   :   "name":"No"
:   :   :   }
:   :   ],
:   :   "subTitle":"Over Time Period",
:   :   "dataName":"MyData",
:   :   "title":"MyData Requirement"
:   }
}
</code>```

I am trying to get just the data for the yes and no.  So for no, I just want to get 13.0 but I continue getting [13.0] with the array brackets.  Here are the values of JSONPath Expressions I have tried:

$.@data.chartData..[?(@.name=='No')].data returns [13.0]

$.@data.chartData..[?(@.name=='No')].data[0] returns nothing

$.@data.chartData..[?(@.name=='No')][0].data returns nothing

$.@data.chartData[0]..[?(@.name=='No')].data returns nothing

I am using version 2.3 of the JSON plugin in my jmeter v 3.0.  Any help is greatly appreciated.

答: I came across the same issue and using JMeter (version 3.2), I didn't get the square [] brackets.  However, make sure you use "JSON Extractor" and not "jp@gc - JSON Path Extractor."</p>

Body:
I need the value out of an array, not the array brackets[ ].  Here is the JSON response I am trying to work with:

{
:   "@rpc":"1.0",
:   "@types":
:   [
:   :   "com.model.chart.PieChart",
:   :   "com.model.chart.PieChartData"
:   ],
:   "@data":
:   {
:   :   "@type":0,
:   :   "chartData":
:   :   [
:   :   :   {
:   :   :   :   "@type":1,
:   :   :   :   "data":0.0,
:   :   :   :   "name":"Yes"
:   :   :   },
:   :   :   {
:   :   :   :   "@type":1,
:   :   :   :   "data":13.0,
:   :   :   :   "name":"No"
:   :   :   }
:   :   ],
:   :   "subTitle":"Over Time Period",
:   :   "dataName":"MyData",
:   :   "title":"MyData Requirement"
:   }
}

I am trying to get just the data for the yes and no.  So for no, I just want to get 13.0 but I continue getting [13.0] with the array brackets.  Here are the values of JSONPath Expressions I have tried:

$.@data.chartData..[?(@.name=='No')].data returns [13.0]

$.@data.chartData..[?(@.name=='No')].data[0] returns nothing

$.@data.chartData..[?(@.name=='No')][0].data returns nothing

$.@data.chartData[0]..[?(@.name=='No')].data returns nothing

I am using version 2.3 of the JSON plugin in my jmeter v 3.0.  Any help is greatly appreciated.


问:
TextView inside an ImageView
I have this picture which is the template for an italian license plate:

My app manages vehicles. I've thought to display all user's vehicles in a RecyclerView with CardView, where each CardView contains an ImageView (which displays the previous image) and a TextView, which contains the license plate. But how could I do to put the TextView in the correct position compared to the image displayed in the ImageView? And, the worst thing I think, how could I do to place the TextView correctly for all screens resolutions?

答:
You could place both the views in a RelativeLayout and superimpose each other. For example,</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:padding="30dp">
     <ImageView
         android:layout_width="46dp"
         android:layout_height="46dp"
         android:layout_gravity="center"
         android:background="@drawable/your_numberplate_image" />
     <TextView
         android:layout_width="46dp"
         android:layout_height="46dp"
         android:layout_marginLeft="10dp"
         android:gravity="center"
         android:text="Number"
         android:textSize="25dp" />
</RelativeLayout>
</code>```

Title: TextView inside an ImageView

Body:
You could place both the views in a RelativeLayout and superimpose each other. For example,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:padding="30dp">
     <ImageView
         android:layout_width="46dp"
         android:layout_height="46dp"
         android:layout_gravity="center"
         android:background="@drawable/your_numberplate_image" />
     <TextView
         android:layout_width="46dp"
         android:layout_height="46dp"
         android:layout_marginLeft="10dp"
         android:gravity="center"
         android:text="Number"
         android:textSize="25dp" />
</RelativeLayout>


问:
Uglify, Cannot read property 'reset' of undefined
I used webpack2 to build my app, but when use uglify-js + uglifyjs-webpack-plugin.I have some problems:

```<code>ERROR in vendors.js from UglifyJs
TypeError: Cannot read property 'reset' of undefined
at F:\Github\Program\My-test\Webpack\www2\node_modules\_uglifyjs-webpack-plugin@0.4.3@uglifyjs-webpack-plugin\dist\index.js:99:22
at F:\Github\Program\My-test\Webpack\www2\node_modules\_uglifyjs-webpack-plugin@0.4.3@uglifyjs-webpack-plugin\dist\index.js:231:9
at Array.forEach (native)
at Compilation.<anonymous> (F:\Github\Program\My-test\Webpack\www2\node_modules\_uglifyjs-webpack-plugin@0.4.3@uglifyjs-webpack-plugin\dist\index.js:54:19)
at Compilation.applyPluginsAsyncSeries (F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:142:13)
at self.applyPluginsAsync.err (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:635:10)
at Compilation.applyPluginsAsyncSeries (F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:131:46)
at sealPart2 (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:631:9)
at Compilation.applyPluginsAsyncSeries (F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:131:46)
at Compilation.seal (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:579:8)
at F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compiler.js:493:16
at F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:225:11
at _addModuleChain (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:481:11)
at processModuleDependencies.err (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

The webpack config maybe give some help to you:

```<code>module.exports = {
    entry: {
        app: path.resolve(APP, 'index.js'),
        vendors: ['jquery', 'moment']
    },
    output: {
        path: BUILD,
        filename: 'bundle.js'
    },
    plugins: [
        new HTMLwebpackPlugin({
            title: 'Generate by webpack'
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors',
            filename: 'vendors.js'
        }),
        new UglifyJSPlugin({
            compress: true
        })
    ],
    module: {
        loaders: [
            {
                test: /\.scss$/,
                loaders: 'style-loader!css-loader?sourceMap!sass-loader?sourceMap',
                include: APP
            },
            {
                test: /\.(jpg|png)$/,
                loaders: 'url-loader?limit=40000'
            },
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                include: APP,
                query: {
                    presets: ['es2015', {"modules": false}]
                }
            }
        ]
    },
    devtool: 'eval-source-map'
}
</code>```

What's the 'reset' mean? I can't find answer in anywhere...
Thanks!

答:
works for me:

```<code>  npm install uglifyjs-webpack-plugin --save-dev

 plugins: [
    new webpack.optimize.UglifyJsPlugin()
]
</code>```

But this is not  work:

```<code>  new UglifyJSPlugin({
        compress: true
    })
</code>```

Same question was at Github, the answer was :

Currently using UglifyJS 3 breaks the plugin. It has a new API so the plugin has to change accordingly.

Body:
I used webpack2 to build my app, but when use uglify-js + uglifyjs-webpack-plugin.I have some problems:

ERROR in vendors.js from UglifyJs
TypeError: Cannot read property 'reset' of undefined
at F:\Github\Program\My-test\Webpack\www2\node_modules\_uglifyjs-webpack-plugin@0.4.3@uglifyjs-webpack-plugin\dist\index.js:99:22
at F:\Github\Program\My-test\Webpack\www2\node_modules\_uglifyjs-webpack-plugin@0.4.3@uglifyjs-webpack-plugin\dist\index.js:231:9
at Array.forEach (native)
at Compilation.<anonymous> (F:\Github\Program\My-test\Webpack\www2\node_modules\_uglifyjs-webpack-plugin@0.4.3@uglifyjs-webpack-plugin\dist\index.js:54:19)
at Compilation.applyPluginsAsyncSeries (F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:142:13)
at self.applyPluginsAsync.err (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:635:10)
at Compilation.applyPluginsAsyncSeries (F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:131:46)
at sealPart2 (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:631:9)
at Compilation.applyPluginsAsyncSeries (F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:131:46)
at Compilation.seal (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:579:8)
at F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compiler.js:493:16
at F:\Github\Program\My-test\Webpack\www2\node_modules\_tapable@0.2.6@tapable\lib\Tapable.js:225:11
at _addModuleChain (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:481:11)
at processModuleDependencies.err (F:\Github\Program\My-test\Webpack\www2\node_modules\_webpack@2.5.1@webpack\lib\Compilation.js:452:13)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

The webpack config maybe give some help to you:

module.exports = {
    entry: {
        app: path.resolve(APP, 'index.js'),
        vendors: ['jquery', 'moment']
    },
    output: {
        path: BUILD,
        filename: 'bundle.js'
    },
    plugins: [
        new HTMLwebpackPlugin({
            title: 'Generate by webpack'
        }),
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendors',
            filename: 'vendors.js'
        }),
        new UglifyJSPlugin({
            compress: true
        })
    ],
    module: {
        loaders: [
            {
                test: /\.scss$/,
                loaders: 'style-loader!css-loader?sourceMap!sass-loader?sourceMap',
                include: APP
            },
            {
                test: /\.(jpg|png)$/,
                loaders: 'url-loader?limit=40000'
            },
            {
                test: /\.jsx?$/,
                loader: 'babel-loader',
                include: APP,
                query: {
                    presets: ['es2015', {"modules": false}]
                }
            }
        ]
    },
    devtool: 'eval-source-map'
}

What's the 'reset' mean? I can't find answer in anywhere...
Thanks!

Body:
works for me:

  npm install uglifyjs-webpack-plugin --save-dev

 plugins: [
    new webpack.optimize.UglifyJsPlugin()
]

But this is not  work:

  new UglifyJSPlugin({
        compress: true
    })

Same question was at Github, the answer was :

Currently using UglifyJS 3 breaks the plugin. It has a new API so the plugin has to change accordingly.


问:
Loading BitMap Images - Xamarin.Andoird
I am performing a bitmap resize in my application. I have a folder called Bitmap Images which has the function initiating the bitmap resize. But in my adapter(this line of code), hold.Img.SetImageBitmap(BitmapImages.decodeSampledBitmapFromResource(getResources(),news[position].Image,100,100));, The first parameter getResource is raised as an error. What is missing?

```<code>public class MyAdapter : RecyclerView.Adapter

    {
        private JavaList<News> news;

        public MyAdapter(JavaList<News> news)
        {
            this.news = news;

        }

        //binding data to views
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            MyHolder hold = holder as MyHolder;
            hold.Comment.Text = news[position].Comment;
            //hold.Img.SetImageResource(news[position].Image);
            hold.Img.SetImageBitmap(BitmapImages.decodeSampledBitmapFromResource(getResources(),news[position].Image,100,100));

        }
</code>```

答:
The problem is you are not passing the Context. To access getResources() you have to pass Context. So modify your adapter class.

```<code>public class MyAdapter : RecyclerView.Adapter

{
    private JavaList<News> news;
    private Context context;

    public MyAdapter(JavaList<News> news, Context context)
    {
        this.news = news;
        this.context = context;
    }

   ......
 //Then in your OnBindViewHolder you can call getResources
  .....
   hold.Img.SetImageBitmap(BitmapImages.decodeSampledBitmapFromResource(context.getResources(),news[position].Image,100,100));
 }
</code>```

Title: Loading BitMap Images - Xamarin.Andoird

Body:
I am performing a bitmap resize in my application. I have a folder called Bitmap Images which has the function initiating the bitmap resize. But in my adapter(this line of code), hold.Img.SetImageBitmap(BitmapImages.decodeSampledBitmapFromResource(getResources(),news[position].Image,100,100));, The first parameter getResource is raised as an error. What is missing?

public class MyAdapter : RecyclerView.Adapter

    {
        private JavaList<News> news;

        public MyAdapter(JavaList<News> news)
        {
            this.news = news;

        }

        //binding data to views
        public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
        {
            MyHolder hold = holder as MyHolder;
            hold.Comment.Text = news[position].Comment;
            //hold.Img.SetImageResource(news[position].Image);
            hold.Img.SetImageBitmap(BitmapImages.decodeSampledBitmapFromResource(getResources(),news[position].Image,100,100));

        }

Body:
The problem is you are not passing the Context. To access getResources() you have to pass Context. So modify your adapter class.

public class MyAdapter : RecyclerView.Adapter

{
    private JavaList<News> news;
    private Context context;

    public MyAdapter(JavaList<News> news, Context context)
    {
        this.news = news;
        this.context = context;
    }

   ......
 //Then in your OnBindViewHolder you can call getResources
  .....
   hold.Img.SetImageBitmap(BitmapImages.decodeSampledBitmapFromResource(context.getResources(),news[position].Image,100,100));
 }


问:
SQL: how to alter column size
What SQL statement will resize a column in an Access MDB database?</p>

答:
ALTER TABLE tablename ALTER columnname is the command you want. Syntax may vary depending on your database system.

Edit: Ah Access. In that case, see http://msdn.microsoft.com/en-us/library/bb177883(v=office.12).aspx

Title: SQL: how to alter column size