问:
Users with different attributes
```<code>from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
type_choices = (
    ('A', 'User Type A'),
    ('B', 'User Type B'),
    ('C', 'User Type C'),
)
user_type = models.CharField(max_length=2,
                             choices=type_choices,
                             default='C')

class UserDetails(model.Model):
    type = models.OneToOneField('CustomUser')
    extra_info = models.CharField(max_length=200)
</code>```

How would I make it so that each user has different fields? Examples. One has a available hours field. Another has an address field.

Or Would I do something like this?

```<code>class BaseUser(AbstractUser):
# all the common fields go here, for example:
email = models.EmailField(max_length=10,unique=True)
name = models.CharField(max_length=120)

class StoreOwnerUser(BaseUser):
# All Store Owner specific attribute goes here
balance = models.some_balance_field()
stores_owned = models.some_stores_owned_field()

class Meta:
verbose_name = 'Store Owner'
</code>```

And if this is the way to do it then: What would be specified as AUTH_USER_MODEL? Also at the time of login: user = authenticate(username = username, password = password). From which table (CustomerUser or StoreOwnerUser) would the authenticate function check from? Its okay I can make seperate login pages for each, but then how would  that be handled?

答:
A simple solution could be adding a diferent class for each type of user. Each new class would be in a OneToOneField with your main user profile.

After creating a new user in your views.py you could create the appropiate class of user based on the choices presented.

```<code>new_user = CustomUser.objects.create(user_type='desired_type')
if new_user.user_type == 'typeA':
  user_A.objects.create(CustomerUser=new_user,) # add desired fields
elif new_user.user_type == 'typeB':
  user_B.objects.create(CustomerUser=new_user,) # add desired fields
</code>```

Title: Users with different attributes

Body:
from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
type_choices = (
    ('A', 'User Type A'),
    ('B', 'User Type B'),
    ('C', 'User Type C'),
)
user_type = models.CharField(max_length=2,
                             choices=type_choices,
                             default='C')

class UserDetails(model.Model):
    type = models.OneToOneField('CustomUser')
    extra_info = models.CharField(max_length=200)

How would I make it so that each user has different fields? Examples. One has a available hours field. Another has an address field.

Or Would I do something like this?

class BaseUser(AbstractUser):
# all the common fields go here, for example:
email = models.EmailField(max_length=10,unique=True)
name = models.CharField(max_length=120)

class StoreOwnerUser(BaseUser):
# All Store Owner specific attribute goes here
balance = models.some_balance_field()
stores_owned = models.some_stores_owned_field()

class Meta:
verbose_name = 'Store Owner'

And if this is the way to do it then: What would be specified as AUTH_USER_MODEL? Also at the time of login: user = authenticate(username = username, password = password). From which table (CustomerUser or StoreOwnerUser) would the authenticate function check from? Its okay I can make seperate login pages for each, but then how would  that be handled?

Body:
A simple solution could be adding a diferent class for each type of user. Each new class would be in a OneToOneField with your main user profile.

After creating a new user in your views.py you could create the appropiate class of user based on the choices presented.

new_user = CustomUser.objects.create(user_type='desired_type')
if new_user.user_type == 'typeA':
  user_A.objects.create(CustomerUser=new_user,) # add desired fields
elif new_user.user_type == 'typeB':
  user_B.objects.create(CustomerUser=new_user,) # add desired fields


来源: stackexchange

问:
Jupyter can't find keras' module
I have installed Tensorflow and Keras by Anaconda (on Windows 10), I have created an environment where I am using Python 3.5.2 (the original one in Anaconda was Python 3.6).
When I try to execute import keras as ks, I get ModuleNotFoundError: No module named 'keras'.

I have tried to solve this issue by sys.path.append(C:\\Users\\ ... \\Anaconda3\\python.exe)

with both notebook and console, but I continue to get the same error.

How could I solve this issue?

答:
Jupyter uses iPython under the hood, for python. So when you install Jupyter, it will also install iPython. There was one issue when I installed keras and Jupyter: I already have iPython installed in my root Anaconda environment. This is the output after I install Jupyter and keras:

```<code>In [2]: import sys; sys.path
Out[2]:
['/home/user/anaconda3/bin',
 '/home/user/anaconda3/lib/python36.zip',
 '/home/user/anaconda3/lib/python3.6',
 '/home/user/.ipython']
</code>```

Notice that even though I am inside my conda environment, it still looks for libraries in my root conda environment. And of course keras isn't there.

The step to fix is simply re-activate my environment, with:

source deactivate && source activate [my_env]

Then I am using a correct ipython:

```<code>Out[2]:
['/home/user/anaconda3/envs/ml3/bin',
 '/home/user/anaconda3/envs/ml3/lib/python36.zip',
 '/home/user/anaconda3/envs/ml3/lib/python3.6',
 '/home/user/.ipython']
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jupyter can't find keras' module

Body:
Jupyter uses iPython under the hood, for python. So when you install Jupyter, it will also install iPython. There was one issue when I installed keras and Jupyter: I already have iPython installed in my root Anaconda environment. This is the output after I install Jupyter and keras:

In [2]: import sys; sys.path
Out[2]:
['/home/user/anaconda3/bin',
 '/home/user/anaconda3/lib/python36.zip',
 '/home/user/anaconda3/lib/python3.6',
 '/home/user/.ipython']

Notice that even though I am inside my conda environment, it still looks for libraries in my root conda environment. And of course keras isn't there.

The step to fix is simply re-activate my environment, with:

source deactivate && source activate [my_env]

Then I am using a correct ipython:

Out[2]:
['/home/user/anaconda3/envs/ml3/bin',
 '/home/user/anaconda3/envs/ml3/lib/python36.zip',
 '/home/user/anaconda3/envs/ml3/lib/python3.6',
 '/home/user/.ipython']


问:
git: patch does not apply
I have a certain patch called my_pcc_branch.patch.

When I try to apply it, I get following message:

```<code>$ git apply --check my_pcc_branch.patch
warning: src/main/java/.../AbstractedPanel.java has type 100644, expected 100755
error: patch failed: src/main/java/.../AbstractedPanel.java:13
error: src/main/java/.../AbstractedPanel.java: patch does not apply
</code>```

What does it mean?

How can I fix this problem?

答:
It happens when you mix UNIX and Windows git clients because Windows doesn't really have the concept of the "x" bit so your checkout of a rw-r--r-- (0644) file under Windows is "promoted" by the msys POSIX layer to be rwx-r-xr-x (0755).  git considers that mode difference to be basically the same as a textual difference in the file, so your patch does not directly apply.  I think your only good option here is to set core.filemode to false (using git-config).

Here's a msysgit issue with some related info:  http://code.google.com/p/msysgit/issues/detail?id=164 (rerouted to archive.org's 3 Dec 2013 copy)

Title: git: patch does not apply

Body:
I have a certain patch called my_pcc_branch.patch.

When I try to apply it, I get following message:

$ git apply --check my_pcc_branch.patch
warning: src/main/java/.../AbstractedPanel.java has type 100644, expected 100755
error: patch failed: src/main/java/.../AbstractedPanel.java:13
error: src/main/java/.../AbstractedPanel.java: patch does not apply

What does it mean?

How can I fix this problem?


问:
JavaScript ReferenceError: x is not defined
I am trying to build a webpage to display some images and when clicked with pop-up a modal with thumbnail images at the bottom. I referenced w3Schools to create this and modified it a bit but now recieve a ReferenceError: currentImg is not defined in the console. When I click on an image the modal pops up but the image does not change when the arrows are clicked. Requesting help to understand the error and how to fix it. Please find below my code.

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showImgs(slideIndex);

function plusImg(n) {
  showImgs(slideIndex += n);
}

function plusImg(n) {
  showImgs(slideIndex = n);
}

function showImgs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > x.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = x.length;
  }
  alert(x.length)
  for (i = 0; i < x.length; i++) {
    alert(i)
    x[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
  }
  x[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " w3-opacity-off";
  captionText.innerHTML = dots[slideIndex - 1].alt;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.s4 img {
  height: 413px;
  width: 319px;
  margin: 0px;
  cursor: pointer;
}

#myModal span {
  cursor: pointer;
}

.w3-content {
  max-width: 1200px;
}

.w3-content .mySlides {
  width: 100%;
}

.w3-content .w3-col {
  padding: 5px;
}

.demo {
  width: 100%;
}</code>```

  <title>Commander, Carrier Strike Group ELEVEN (CCSG 11) Fact Sheet</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />

      ×

Page 1

            <
            >

```

答:
There are some issues in your javascript codes:

there is missing function for currentImg

```<code>    function currentImg(n) {
      console.log(n);
      showImgs(n);
    }
</code>```

there is duplicate plusImg function, please remove the 2nd one

there is error in showImgs function, please check my update js codes

```<code>    function openModal() {
      document.getElementById('myModal').style.display = "block";
    }

    function closeModal() {
      document.getElementById('myModal').style.display = "none";
    }

    var slideIndex = 1;
    showImgs(slideIndex);

    function plusImg(n) {
      showImgs(slideIndex += n);
    }

    function currentImg(n) {
      console.log(n);
      showImgs(n);
    }

    function showImgs(n) {
      var i;
      var x = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("demo");
      var captionText = document.getElementById("caption");

      if (!x.length) return;

      slideIndex = n;
      if (n > x.length) {
        slideIndex = 1;
      }
      if (n < 1) {
        slideIndex = x.length;
      }
      console.log(x.length)
      for (i = 0; i < x.length; i++) {
        console.log(i)
        x[i].style.display = "none";
      }
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
      }
      x[slideIndex - 1].style.display = "block";
      dots[slideIndex - 1].className += " w3-opacity-off";
      captionText.innerHTML = dots[slideIndex - 1].alt;
    }
</code>```

BTW, I changed alert to console.log for better debug experience. I also added the style

```<code>.mySlides {display:none}
</code>```

Please check. Hope above helps.

Body:
I am trying to build a webpage to display some images and when clicked with pop-up a modal with thumbnail images at the bottom. I referenced w3Schools to create this and modified it a bit but now recieve a ReferenceError: currentImg is not defined in the console. When I click on an image the modal pops up but the image does not change when the arrows are clicked. Requesting help to understand the error and how to fix it. Please find below my code.

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showImgs(slideIndex);

function plusImg(n) {
  showImgs(slideIndex += n);
}

function plusImg(n) {
  showImgs(slideIndex = n);
}

function showImgs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > x.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = x.length;
  }
  alert(x.length)
  for (i = 0; i < x.length; i++) {
    alert(i)
    x[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
  }
  x[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " w3-opacity-off";
  captionText.innerHTML = dots[slideIndex - 1].alt;
}

.s4 img {
  height: 413px;
  width: 319px;
  margin: 0px;
  cursor: pointer;
}

#myModal span {
  cursor: pointer;
}

.w3-content {
  max-width: 1200px;
}

.w3-content .mySlides {
  width: 100%;
}

.w3-content .w3-col {
  padding: 5px;
}

.demo {
  width: 100%;
}

  <title>Commander, Carrier Strike Group ELEVEN (CCSG 11) Fact Sheet</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />

      ×

Page 1

            <
            >

Body:
There are some issues in your javascript codes:

there is missing function for currentImg

    function currentImg(n) {
      console.log(n);
      showImgs(n);
    }

there is duplicate plusImg function, please remove the 2nd one

there is error in showImgs function, please check my update js codes

    function openModal() {
      document.getElementById('myModal').style.display = "block";
    }

    function closeModal() {
      document.getElementById('myModal').style.display = "none";
    }

    var slideIndex = 1;
    showImgs(slideIndex);

    function plusImg(n) {
      showImgs(slideIndex += n);
    }

    function currentImg(n) {
      console.log(n);
      showImgs(n);
    }

    function showImgs(n) {
      var i;
      var x = document.getElementsByClassName("mySlides");
      var dots = document.getElementsByClassName("demo");
      var captionText = document.getElementById("caption");

      if (!x.length) return;

      slideIndex = n;
      if (n > x.length) {
        slideIndex = 1;
      }
      if (n < 1) {
        slideIndex = x.length;
      }
      console.log(x.length)
      for (i = 0; i < x.length; i++) {
        console.log(i)
        x[i].style.display = "none";
      }
      for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
      }
      x[slideIndex - 1].style.display = "block";
      dots[slideIndex - 1].className += " w3-opacity-off";
      captionText.innerHTML = dots[slideIndex - 1].alt;
    }

BTW, I changed alert to console.log for better debug experience. I also added the style

.mySlides {display:none}

Please check. Hope above helps.


问:
error: RPC failed; result=22, HTTP code = 504.00 KiB/s
I have a problem with git push.
Its not working

```<code>Counting objects: 143, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (116/116), done.
error: RPC failed; result=22, HTTP code = 504.00 KiB/s
fatal: The remote end hung up unexpectedly| 11.00 KiB/s
Writing objects: 100% (120/120), 207.69 MiB | 7.03 MiB/s, done.
Total 120 (delta 32), reused 0 (delta 0)
fatal: The remote end hung up unexpectedly
Everything up-to-date
</code>```

It's not working can someone help me in this it took so much time to to push and after that it give me this result.

答:
It looks like your terminal just misprinted some characters. The actual error is:

```<code>error: RPC failed; result=22, HTTP code = 504
</code>```

HTTP 504 means the server timed out. Searching for this should find you better help!

Body:
I have a problem with git push.
Its not working

Counting objects: 143, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (116/116), done.
error: RPC failed; result=22, HTTP code = 504.00 KiB/s
fatal: The remote end hung up unexpectedly| 11.00 KiB/s
Writing objects: 100% (120/120), 207.69 MiB | 7.03 MiB/s, done.
Total 120 (delta 32), reused 0 (delta 0)
fatal: The remote end hung up unexpectedly
Everything up-to-date

It's not working can someone help me in this it took so much time to to push and after that it give me this result.

Body:
It looks like your terminal just misprinted some characters. The actual error is:

error: RPC failed; result=22, HTTP code = 504

HTTP 504 means the server timed out. Searching for this should find you better help!


问:
Unable to download file with special character from Amazon S3
I have been trying to download a file from Amazon S3 that ends with special character.

The file name ends with an "=" as a result of Base64 encoding. Now I am trying to download this file and I receive an error,

The specified key does not exist. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey;

I tried URL Encoding the string. So now the "=" becomes "%3D" and still I receive the same error.
But if I remove the "=" from the file name, I am being able to download the file without issues. But this is a common file and it is to be accessed form iOS as well.

NOTE: The iOS Amazon SDK works even when the file name has "=" in it.
The issue is faced only in Android SDK.

答:
The following characters in a key name may requiere additional code
  handling and will likely need to be URL encoded or referenced as
  HEX.

Some of these are non-printable characters and your browser may not handle them, which will also require special handling:

The best practices to ensure compatibility between applications defining Key names are using:

```<code>- Alphanumeric characters [0-9a-zA-Z]
- Special characters !, -, _, ., *, ', (, and )
</code>```

Using android you need to encode the file name, the character (commonly used as operator):

```<code>=
</code>```

to :

```<code>%3D
</code>```

Body:
The following characters in a key name may requiere additional code
  handling and will likely need to be URL encoded or referenced as
  HEX.

Some of these are non-printable characters and your browser may not handle them, which will also require special handling:

The best practices to ensure compatibility between applications defining Key names are using:

- Alphanumeric characters [0-9a-zA-Z]
- Special characters !, -, _, ., *, ', (, and )

Using android you need to encode the file name, the character (commonly used as operator):

=

to :

%3D


问:
Mercurial: Exclude django settings.py after intitial commit
In my Django project, I want the settings.py file to be included in the initial commit so that other developers can clone the repository and change the original settings to work with there local setup. But, after that I don't want to manually exclude the file at every commit, and the ignore file wont work because it's already tracked.

So, how can I get mercurial to automatically exclude the settings.py while maintaining the original file tracked?

Appreciate any help :)

答: The way this is most generally done with Mercurual is to commit a file called something like settings.py.template, and have the first step someone takes on a new clone be to copy that over to a settings.py file, which is listed in the .hgignore file. That way, if someone adds a new settings in the template people will still get it and can merge it into their local settings.  It's easy to automate the copying of template to actual in your start/deploy script or using a clone hook, though most folks don't bother.

ContentLicense: CC BY-SA 2.5


问:
Passing -ddump-splices to Stack script interpreter
I'm using Stack interpreter feature and having a code like this:

```<code>#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package yesod
     --package yesod-core
-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
{-# LANGUAGE TemplateHaskell   #-}
-- and the code goes on
</code>```

I want to pass the ddump-splices option to the stack interpreter to it. Is it possible ?

答:
Yes, you have to use -- before passing the actual ghc option. i.e:

```<code>#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package yesod
     --package yesod-core
     -- -ddump-splices
-}
</code>```

You can use ghc --show-options to see the kind of options you can pass. For more information, see here: https://github.com/commercialhaskell/stack/issues/650#issuecomment-123470879

ContentLicense: CC BY-SA 4.0

Body:
I'm using Stack interpreter feature and having a code like this:

#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package yesod
     --package yesod-core
-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
{-# LANGUAGE TemplateHaskell   #-}
-- and the code goes on

I want to pass the ddump-splices option to the stack interpreter to it. Is it possible ?

Body:
Yes, you have to use -- before passing the actual ghc option. i.e:

#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package yesod
     --package yesod-core
     -- -ddump-splices
-}

You can use ghc --show-options to see the kind of options you can pass. For more information, see here: https://github.com/commercialhaskell/stack/issues/650#issuecomment-123470879


问:
AttributeError: 'module' object has no attribute 'createFisherFaceRecognizer'
I'm using Ubuntu 16.04 (64bit) python2.7 Open-CV 3.1.0
I've followed the steps for downloading Repository for Open-CV extra modules to activate this function via
https://github.com/opencv/opencv_contrib,
However i got the same error, i also tried using the latest Open-CV 3.2.0 instead of 3.1.0 but i have got the same error:

```<code>AttributeError: 'module' object has no attribute 'createFisherFaceRecognizer'.
</code>```

The part of my code:

```<code>import numpy as np
import cv2
import sys
import os
class TrainFisherFaces:
    def __init__(self):
        cascPath = "haarcascade_frontalface_default.xml"
        self.face_cascade = cv2.CascadeClassifier(cascPath)
        self.face_dir = 'data'
        self.face_name = sys.argv[1]
        self.path = os.path.join(self.face_dir, self.face_name)
        if not os.path.isdir(self.path):
            os.mkdir(self.path)
        self.model = cv2.createFisherFaceRecognizer()
</code>```

答:
I followed the instructions here:
https://pypi.python.org/pypi/opencv-contrib-python

And simply has to do: pip install opencv-contrib-python

Also, I had to use cv2.face.FisherFaceRecognizer_create()

Body:
I'm using Ubuntu 16.04 (64bit) python2.7 Open-CV 3.1.0
I've followed the steps for downloading Repository for Open-CV extra modules to activate this function via
https://github.com/opencv/opencv_contrib,
However i got the same error, i also tried using the latest Open-CV 3.2.0 instead of 3.1.0 but i have got the same error:

AttributeError: 'module' object has no attribute 'createFisherFaceRecognizer'.

The part of my code:

import numpy as np
import cv2
import sys
import os
class TrainFisherFaces:
    def __init__(self):
        cascPath = "haarcascade_frontalface_default.xml"
        self.face_cascade = cv2.CascadeClassifier(cascPath)
        self.face_dir = 'data'
        self.face_name = sys.argv[1]
        self.path = os.path.join(self.face_dir, self.face_name)
        if not os.path.isdir(self.path):
            os.mkdir(self.path)
        self.model = cv2.createFisherFaceRecognizer()


问:
difference in default delimiter and field calculation in cut and awk
I am trying to cut out the time that a process starts.
This is the ps line. Is seems delimited by spaces.

```<code> casper@casperhost02 1065$ ps -ef | grep [t]xg casper  5345     1 34 16:40 ?        00:06:56 q /casper_apps/casper/reader/q/txg_dr.q -g 1 -w 80000 -p 3041 -taq /casper_apps/casper/data/fiofs/hdb0 -bin /casper_apps/casper/reader/q -t1 /casper_apps/casper/data/file -cmq /casper_apps/casper/common/q -ref /casper_apps/casper/static -prg txg_dr
</code>```

I wanted to just cut the time from the ps line and extract by field..
when I use cut and delimit by space, the time is in field ten.

```<code>casper@casperhost02 1075$ ps -ef | grep [t]xg | cut -d' ' -f10
</code>```

16:40

However when I use awk, which id default delimited by space, it is field 5.

```<code> casper@casperhost02 1076$ ps -ef | grep [t]xg | awk '{print $5}'
</code>```

16:40

What is the difference between the field delimiter in awk and cut?

答:
cut counts the spaces, awk counts the fields, treating all the contiguous white space as one delimiter by default.  Note that you don't need grep if you are already using awk

```<code> ... |  awk '/txg/{print $5}'
</code>```

you can also restrict the regex (or literal) match to the right field and eliminate false positives.

Body:
I am trying to cut out the time that a process starts.
This is the ps line. Is seems delimited by spaces.

 casper@casperhost02 1065$ ps -ef | grep [t]xg casper  5345     1 34 16:40 ?        00:06:56 q /casper_apps/casper/reader/q/txg_dr.q -g 1 -w 80000 -p 3041 -taq /casper_apps/casper/data/fiofs/hdb0 -bin /casper_apps/casper/reader/q -t1 /casper_apps/casper/data/file -cmq /casper_apps/casper/common/q -ref /casper_apps/casper/static -prg txg_dr

I wanted to just cut the time from the ps line and extract by field..
when I use cut and delimit by space, the time is in field ten.

casper@casperhost02 1075$ ps -ef | grep [t]xg | cut -d' ' -f10

16:40

However when I use awk, which id default delimited by space, it is field 5.

 casper@casperhost02 1076$ ps -ef | grep [t]xg | awk '{print $5}'

16:40

What is the difference between the field delimiter in awk and cut?

Body:
cut counts the spaces, awk counts the fields, treating all the contiguous white space as one delimiter by default.  Note that you don't need grep if you are already using awk

 ... |  awk '/txg/{print $5}'

you can also restrict the regex (or literal) match to the right field and eliminate false positives.


问:
PHP while command missing first entry

I am trying to use the while loop to print multiple entries from a MySQL database. Everywhere I do this it is missing the first item on the list and only manages to print from the second one on. </p>

```<code><?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>View</title>
        <link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">
    </head>
    <body>
        <div class="header">
            <h2>Results.</h2>
            <form action="watch.php" method='POST'><table>
                <?php
                    if($result->num_rows > 0){
                        while($row = $result->fetch_assoc()){
                            $vid = $row['vid'];
                            $source = "uploads/".$row['file_name'];
                            echo "<tr><td>".$row['vid']."</td>
<td>".$row['file_name']."</td>";
                            echo "<td><a href=watch.php?
source=$source>Play</a></td></tr>";
                        }
                    }else{
                    echo "0 results";
                    }
                ?>
                </table></form>
            <a href="profile.php"><button class="button-block">Home</button></a>
        </div>
    </body>
</code>```

<p>

I'd like it to print all matching criteria.

I'm getting only the entries after the first one. </p>

答:
```<code>        require 'db.php';
        $udate = $mysqli->escape_string($_POST['date']);
        $result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");

        /*
         This fetch_assoc will get your first row #0 of the query
         next fetch_assoc with your loop on the $result
         will start as you said from row #1
        */
        $user = $result->fetch_assoc(); //your missing row #0
        $_SESSION['file_name'] = $user['file_name'];
</code>```

Title: PHP while command missing first entry

Body:
I am trying to use the while loop to print multiple entries from a MySQL database. Everywhere I do this it is missing the first item on the list and only manages to print from the second one on.

<?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>View</title>
        <link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">

Results.

            <form action="watch.php" method='POST'>

                <?php
                    if($result->num_rows > 0){
                        while($row = $result->fetch_assoc()){
                            $vid = $row['vid'];
                            $source = "uploads/".$row['file_name'];
                            echo "
".$row['vid']."
".$row['file_name']."	";
                            echo "Play
";
                        }
                    }else{
                    echo "0 results";
                    }
                ?>

</form>
            <button class="button-block">Home</button>

I'd like it to print all matching criteria.

I'm getting only the entries after the first one.


问:
SSL certificates or other files not showing in Docker file structure
I have a Docker build for Gitlab, I created some ssl certificates and other files I need to pull in.  However when I exec into the container bash the files are not visible.</p>

```<code>gitlab:
  image: 'gitlab/gitlab-ce:9.1.0-ce.0'
  restart: always
  hostname: 'gitlab.example.com'
  links:
    - postgresql:postgresql
    - redis:redis
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      postgresql['enable'] = false
      gitlab_rails['db_username'] = "gitlab"
      gitlab_rails['db_password'] = "gitlab"
      gitlab_rails['db_host'] = "postgresql"
      gitlab_rails['db_port'] = "5432"
      gitlab_rails['db_database'] = "gitlabhq_production"
      gitlab_rails['db_adapter'] = 'postgresql'
      gitlab_rails['db_encoding'] = 'utf8'
      redis['enable'] = false
      gitlab_rails['redis_host'] = 'redis'
      gitlab_rails['redis_port'] = '6379'
      external_url 'https://gitlab.example.com:30080'
      nginx['ssl_certificate'] = '/etc/gitlab/trusted-certs/gitlab.example.com.crt'
      nginx['ssl_certificate_key'] = '/etc/gitlab/trusted-certs/gitlab.example.com.key'
  ports:
    - "30080:30080"
    - "30022:22"
postgresql:
  restart: always
  image: postgres:9.6.2-alpine
  environment:
    - POSTGRES_USER=gitlab
    - POSTGRES_PASSWORD=gitlab
    - POSTGRES_DB=gitlabhq_production
redis:
  restart: always
  image: redis:3.0.7-alpine
</code>```

答:
The certificates (self signed) are on my machine at the path referenced "/etc/gitlab/trusted-certs/gitlab.example.com.crt"

Your docker-compose.yml did not map any folders from your host into your container. Containers are nothing more than a namespaced process, and one of those namespaces is the filesystem. To map a directory from the host into the container, you can use a simple bind mount syntax:

```<code>gitlab:
  image: 'gitlab/gitlab-ce:9.1.0-ce.0'
  restart: always
  hostname: 'gitlab.example.com'
  volumes:
    - ./path/to/gitlab.example.com.crt:/etc/gitlab/trusted-certs/gitlab.example.com.crt:ro
  ...
</code>```

Note that this mounts from the host into the container, and the file will be configured as read-only with the :ro syntax to prevent processes inside the container from modifying your certificates. If your docker host is inside of a VM (including docker for windows/mac) or on a remote server, you'll need to make sure the files are accessible there (e.g. docker for win/mac has settings to share PC folders into the embedded VM).

Body:
I have a Docker build for Gitlab, I created some ssl certificates and other files I need to pull in.  However when I exec into the container bash the files are not visible.

gitlab:
  image: 'gitlab/gitlab-ce:9.1.0-ce.0'
  restart: always
  hostname: 'gitlab.example.com'
  links:
    - postgresql:postgresql
    - redis:redis
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      postgresql['enable'] = false
      gitlab_rails['db_username'] = "gitlab"
      gitlab_rails['db_password'] = "gitlab"
      gitlab_rails['db_host'] = "postgresql"
      gitlab_rails['db_port'] = "5432"
      gitlab_rails['db_database'] = "gitlabhq_production"
      gitlab_rails['db_adapter'] = 'postgresql'
      gitlab_rails['db_encoding'] = 'utf8'
      redis['enable'] = false
      gitlab_rails['redis_host'] = 'redis'
      gitlab_rails['redis_port'] = '6379'
      external_url 'https://gitlab.example.com:30080'
      nginx['ssl_certificate'] = '/etc/gitlab/trusted-certs/gitlab.example.com.crt'
      nginx['ssl_certificate_key'] = '/etc/gitlab/trusted-certs/gitlab.example.com.key'
  ports:
    - "30080:30080"
    - "30022:22"
postgresql:
  restart: always
  image: postgres:9.6.2-alpine
  environment:
    - POSTGRES_USER=gitlab
    - POSTGRES_PASSWORD=gitlab
    - POSTGRES_DB=gitlabhq_production
redis:
  restart: always
  image: redis:3.0.7-alpine

Body:
The certificates (self signed) are on my machine at the path referenced "/etc/gitlab/trusted-certs/gitlab.example.com.crt"

Your docker-compose.yml did not map any folders from your host into your container. Containers are nothing more than a namespaced process, and one of those namespaces is the filesystem. To map a directory from the host into the container, you can use a simple bind mount syntax:

gitlab:
  image: 'gitlab/gitlab-ce:9.1.0-ce.0'
  restart: always
  hostname: 'gitlab.example.com'
  volumes:
    - ./path/to/gitlab.example.com.crt:/etc/gitlab/trusted-certs/gitlab.example.com.crt:ro
  ...

Note that this mounts from the host into the container, and the file will be configured as read-only with the :ro syntax to prevent processes inside the container from modifying your certificates. If your docker host is inside of a VM (including docker for windows/mac) or on a remote server, you'll need to make sure the files are accessible there (e.g. docker for win/mac has settings to share PC folders into the embedded VM).


问:
hide() show() jquery
I'm using the following:

$('#info').click(function (){
$('#message').fadeIn(200).show();
return false;
});

How could I change my script so that it would dissapear once clicked apon again?

Tried .fadeout().hide()

But it only show/hide so fast it looks as though nothing is happening.

答:
```<code>$('#info').click( function(){
   $('#message').fadeToggle(200);
   return false;
});
</code>```

to make it fade in and out.

Title: hide() show() jquery

Body:
$('#info').click( function(){
   $('#message').fadeToggle(200);
   return false;
});

to make it fade in and out.


问:
Git diff to show only lines that have been modified
When I do a git diff, it shows lines that have been added:

```<code>+ this line is added
</code>```

lines that have been removed:

```<code>- this line is removed
</code>```

but it also shows many lines which are not modified:

```<code>this line is not modified
this line is also not modified
</code>```

This results in the actual git diff looking something like this:

```<code>+ this line is added
  this line is not modified
- this line is removed
  this line is not modified
</code>```

Can I ask git to show only lines that have been modified and ignore all other code which has not been modified? I have written a method which will remove all the lines which don't have a "+" or "-" sign in front of them, but I am sure there must be a simpler way to do this.

In my git diff, I am only interested in seeing the lines that have been modified.

答:
I think for simple cases the regex can be much shorter and easier to remember, with the caveat that this won't work if you have line changes where the line itself starts with + or -

```<code>$ git diff | grep '^[+-][^+-]'
</code>```

The regex says the line should start with + or -, and the immediately following character should be neither of those. I got the same results whether I escaped the + or not here, btw...

Example:

```<code>$ cat testfile
A
B
C
D
E
F
G
</code>```

Say I change C to X, E to Y, and G to Z.

```<code>$ git diff | grep '^[+-][^+-]'
-C
+X
-E
+Y
-G
+Z
</code>```

Like I said above, though, this is just for most cases. If you pipe that output to a file dout, then try the same regex, it won't work.

```<code>$ git diff dout | grep '^[+-][^+-]'
$
</code>```

Anyways, hope that helps in your case

Body:
When I do a git diff, it shows lines that have been added:

+ this line is added

lines that have been removed:

- this line is removed

but it also shows many lines which are not modified:

this line is not modified
this line is also not modified

This results in the actual git diff looking something like this:

+ this line is added
  this line is not modified
- this line is removed
  this line is not modified

Can I ask git to show only lines that have been modified and ignore all other code which has not been modified? I have written a method which will remove all the lines which don't have a "+" or "-" sign in front of them, but I am sure there must be a simpler way to do this.

In my git diff, I am only interested in seeing the lines that have been modified.

Body:
I think for simple cases the regex can be much shorter and easier to remember, with the caveat that this won't work if you have line changes where the line itself starts with + or -

$ git diff | grep '^[+-][^+-]'

The regex says the line should start with + or -, and the immediately following character should be neither of those. I got the same results whether I escaped the + or not here, btw...

Example:

$ cat testfile
A
B
C
D
E
F
G

Say I change C to X, E to Y, and G to Z.

$ git diff | grep '^[+-][^+-]'
-C
+X
-E
+Y
-G
+Z

Like I said above, though, this is just for most cases. If you pipe that output to a file dout, then try the same regex, it won't work.

$ git diff dout | grep '^[+-][^+-]'
$

Anyways, hope that helps in your case


问:
C# Programmatic created button - enable programmatically created textbox
Hoping you can help - I have programmatically created button & richtextbox.

```<code>// Button to Edit
Button butEditToDo = new Button();
butEditToDo.Location = new Point(285, 10);
butEditToDo.Size = new System.Drawing.Size(25, 25);
butEditToDo.BackColor = Color.Transparent;
butEditToDo.FlatStyle = FlatStyle.Flat;
butEditToDo.FlatAppearance.BorderSize = 0;
butEditToDo.FlatAppearance.MouseOverBackColor = Color.FromArgb(244, 244, 244);
butEditToDo.Cursor = Cursors.Hand;
butEditToDo.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.Edit_25));
pnlPendingNote.Controls.Add(butEditToDo);

// Pending Nane + Tag
RichTextBox rxtNotes = new RichTextBox();
rxtNotes.Size = new System.Drawing.Size(317, 68);
rxtNotes.Location = new Point(3, 37);
rxtNotes.Text = (read["notNote"].ToString());
rxtNotes.ReadOnly = true;
rxtNotes.BorderStyle = BorderStyle.None;
rxtNotes.DetectUrls = true;
rxtNotes.BackColor = Color.FromArgb(244, 244, 244);
pnlPendingNote.Controls.Add(rxtNotes);
</code>```

So when ever I click on ButEditToDo_Click - I can get the right button clicked.

So when I click on this button I would like to enable the RichTextbox - and when I click the button again - I would like to update the database.

Button Click:

```<code>private void ButEditToDo_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    for (int i = 1; i < pendingcounter; i++)
    {
        if (btn.Name == ("PenNote" + i))
        {
            break;
        }
    }
}
</code>```

Hope you can help please with enabling the button, I'm all good with the database.

Thank you.

Edit One

@Ed - thank you.
Please See Image.

What I would like to achieve - When i click on the tools icon - the RichTextBox will be enabled.
So if I click on the tools on first panel - then the R_TextBox will be enabled for me to edit the text.
Then the Icon will change and I will be able to click on it again to save to the database.

Hope that makes more sense for you Ed.

答:
Just give the button an event handler that does stuff. Use a lambda so you can reference the local reference to the RichTextBox.

```<code>    Button butEditToDo = new Button();
    //  ...snip...
    RichTextBox rxtNotes = new RichTextBox();
    //  ...snip...

    butEditToDo.Click += (sender, args) =>
    {
        CycleNoteState(rxtNotes);
    };
</code>```

And here's the guts of the event handler. You could put this all in the event handler, but the code's more readable this way. CycleNoteState isn't a very good name, but I'm not clear about the semantics of your program.

I may have misunderstood the logic for what the button does on successive clicks. If it's more complicated than this, you can introduce a state enum or something. Let me know and we'll get it figured out.

```<code>private void CycleNoteState(RichTextBox rtb)
{
    if (!rtb.Enabled)
    {
        rtb.Enabled = true;
    }
    else
    {
        //  Do save stuff here
    }
}
</code>```

Body:
Hoping you can help - I have programmatically created button & richtextbox.

// Button to Edit
Button butEditToDo = new Button();
butEditToDo.Location = new Point(285, 10);
butEditToDo.Size = new System.Drawing.Size(25, 25);
butEditToDo.BackColor = Color.Transparent;
butEditToDo.FlatStyle = FlatStyle.Flat;
butEditToDo.FlatAppearance.BorderSize = 0;
butEditToDo.FlatAppearance.MouseOverBackColor = Color.FromArgb(244, 244, 244);
butEditToDo.Cursor = Cursors.Hand;
butEditToDo.BackgroundImage = ((System.Drawing.Image)(Properties.Resources.Edit_25));
pnlPendingNote.Controls.Add(butEditToDo);

// Pending Nane + Tag
RichTextBox rxtNotes = new RichTextBox();
rxtNotes.Size = new System.Drawing.Size(317, 68);
rxtNotes.Location = new Point(3, 37);
rxtNotes.Text = (read["notNote"].ToString());
rxtNotes.ReadOnly = true;
rxtNotes.BorderStyle = BorderStyle.None;
rxtNotes.DetectUrls = true;
rxtNotes.BackColor = Color.FromArgb(244, 244, 244);
pnlPendingNote.Controls.Add(rxtNotes);

So when ever I click on ButEditToDo_Click - I can get the right button clicked.

So when I click on this button I would like to enable the RichTextbox - and when I click the button again - I would like to update the database.

Button Click:

private void ButEditToDo_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;

    for (int i = 1; i < pendingcounter; i++)
    {
        if (btn.Name == ("PenNote" + i))
        {
            break;
        }
    }
}

Hope you can help please with enabling the button, I'm all good with the database.

Thank you.

Edit One

@Ed - thank you.
Please See Image.

What I would like to achieve - When i click on the tools icon - the RichTextBox will be enabled.
So if I click on the tools on first panel - then the R_TextBox will be enabled for me to edit the text.
Then the Icon will change and I will be able to click on it again to save to the database.

Hope that makes more sense for you Ed.

Body:
Just give the button an event handler that does stuff. Use a lambda so you can reference the local reference to the RichTextBox.

    Button butEditToDo = new Button();
    //  ...snip...
    RichTextBox rxtNotes = new RichTextBox();
    //  ...snip...

    butEditToDo.Click += (sender, args) =>
    {
        CycleNoteState(rxtNotes);
    };

And here's the guts of the event handler. You could put this all in the event handler, but the code's more readable this way. CycleNoteState isn't a very good name, but I'm not clear about the semantics of your program.

I may have misunderstood the logic for what the button does on successive clicks. If it's more complicated than this, you can introduce a state enum or something. Let me know and we'll get it figured out.

private void CycleNoteState(RichTextBox rtb)
{
    if (!rtb.Enabled)
    {
        rtb.Enabled = true;
    }
    else
    {
        //  Do save stuff here
    }
}


问:
ACE_SOCK_Dgram::open() and errno
I tried to open already opened UDP port and ACE_SOCK_Dgram::open() failed.
As expected, strace shows that bind() failed and errno is set to EADDRINUSE.

To see what error happen, I used ACE_OS::last_error(), but it's not updated.

I'd like to give informative error to user that the port already in use, instead of some general error.

Bonus question - when ACE_OS::last_error() can be used?

Tnx

答:
It would have helped to if you provided more details. Which platform you were running your application on? What version of ACE library you are using? Was it a UDP port in a range 1-1024? Do you use broadcast UDP socket?

Let's assume that since you are checking "errno" not GetLastError() you are running on UNIX flavor such as Linux. Looking at OS_S_errno.inl you can find comments that describe the difference in behavior between different OS.

You are not asking why you getting EADDRINUSE for UDP socket in first place. Do you use SO_REUSEADDR option? If you do you should be aware that only last process that bound to the socket will be notified and behavior may vary between OS.

Is it possible that another system function call issued after bind() ? In that case error returned by bind() may be reset by system call that follow. As you can see from implementation of last_error() it is just sets "errno = ::GetLastError()" on windows and returns errno straight on UNIX.

Title: ACE_SOCK_Dgram::open() and errno


答:
cut accepts a single-character delimiter, and is suitable only for very simple text file formats.

Awk is much more versatile, and can handle somewhat more complex field delimiter definitions and even (in some dialects) a regular expression.  By default, Awk regards sequences of whitespace as a single delimiter.

Tangentially, you seem to be looking for the command pgrep.  If you have to reinvent it, keep in mind that grep x | awk '{y}' can almost always be written awk '/x/{y}'.

Title: difference in default delimiter and field calculation in cut and awk


问:
Tkinter text editor thats always on top
So i just want to make this window a text widget thats always on top. Im trying to add this widget but it keeps creating another window...</p>

```<code>import tkinter as tk
from tkinter import ttk

class App(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)

        self.pack()

        hello="hello"

        self.tb = tk.Text(self)
        self.tb.pack(expand=1, fill = tk.BOTH)
        self.tb.insert(tk.END, hello)

        topLevelWindow = tk.Toplevel(self)
        # Make topLevelWindow remain on top until destroyed, or attribute changes.
        topLevelWindow.attributes('-topmost', 'true')

if __name__ == "__main__":
    root = tk.Tk()
    main = App(root)
    root.mainloop()
</code>```

答:
If you want your text widget to be active you need to call this instead:

```<code>self.tb.focus_set()
</code>```

What you're doing is instead create a Toplevel widget, which is a window that stays topmost, as in above all windows in desktop, you should remove:

```<code>    topLevelWindow = tk.Toplevel(self)
    # Make topLevelWindow remain on top until destroyed, or attribute changes.
    topLevelWindow.attributes('-topmost', 'true')
</code>```

If you also want that your entire window you can do that for your root instead in your 'main' according to this answer:

```<code>root.call('wm', 'attributes', '.', '-topmost', '1')
</code>```

Finally to have:

```<code>import tkinter as tk
from tkinter import ttk

class App(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)

        self.pack()

        hello="hello"

        self.tb = tk.Text(self)
        self.tb.pack(expand=1, fill = tk.BOTH)
        self.tb.insert(tk.END, hello)

        self.tb.focus_set()

if __name__ == "__main__":
    root = tk.Tk()
    root.call('wm', 'attributes', '.', '-topmost', '1')
    main = App(root)
    root.mainloop()
</code>```

Also if you want to make other widgets unfocusable:

```<code>widget.config(takefocus=False)
</code>```

Title: Tkinter text editor thats always on top

Body:
So i just want to make this window a text widget thats always on top. Im trying to add this widget but it keeps creating another window...

import tkinter as tk
from tkinter import ttk

class App(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)

        self.pack()

        hello="hello"

        self.tb = tk.Text(self)
        self.tb.pack(expand=1, fill = tk.BOTH)
        self.tb.insert(tk.END, hello)

        topLevelWindow = tk.Toplevel(self)
        # Make topLevelWindow remain on top until destroyed, or attribute changes.
        topLevelWindow.attributes('-topmost', 'true')

if __name__ == "__main__":
    root = tk.Tk()
    main = App(root)
    root.mainloop()

Body:
If you want your text widget to be active you need to call this instead:

self.tb.focus_set()

What you're doing is instead create a Toplevel widget, which is a window that stays topmost, as in above all windows in desktop, you should remove:

    topLevelWindow = tk.Toplevel(self)
    # Make topLevelWindow remain on top until destroyed, or attribute changes.
    topLevelWindow.attributes('-topmost', 'true')

If you also want that your entire window you can do that for your root instead in your 'main' according to this answer:

root.call('wm', 'attributes', '.', '-topmost', '1')

Finally to have:

import tkinter as tk
from tkinter import ttk

class App(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)

        self.pack()

        hello="hello"

        self.tb = tk.Text(self)
        self.tb.pack(expand=1, fill = tk.BOTH)
        self.tb.insert(tk.END, hello)

        self.tb.focus_set()

if __name__ == "__main__":
    root = tk.Tk()
    root.call('wm', 'attributes', '.', '-topmost', '1')
    main = App(root)
    root.mainloop()

Also if you want to make other widgets unfocusable:

widget.config(takefocus=False)


问:
Javascript Geofire + Firebase react app - inconsitencies in instantiations/declarations in class based logic
Ok so I'm following example on setting up Geofire with Firebase as described in this example: https://github.com/firebase/geofire-js/blob/master/examples/html5Geolocation/js/html5Geolocation.js

If I do the following in a normal JS code file the geoFire variable is set fine:

```<code>import * as firebase from 'firebase';
import GeoFire from 'geofire';

const config = {
    // config stuff here
};
firebase.initializeApp(config);

let geoLocationRef = firebase.database().ref('users-geolocation').push();
let geoFire = new GeoFire(geoLocationRef);
console.log('GEOFIRE :::::: ', geoFire);
// output: GEOFIRE ::::::  GeoFire {ref: ƒ, set: ƒ, get: ƒ, remove: ƒ, query: ƒ}
</code>```

HOWEVER, if I try to do something similar in a GeoFireUtil.js class so that I can more easily include the GeoFire functionality where ever I want I am getting 'geoFire is undefined':

```<code>import firebase from './firebase-connection';
import GeoFire from 'geofire';

// geofire connection ##################

//let geoLocationRef = firebase.database().ref('users-geolocation').push();
// Create a new GeoFire key under users Firebase location
//let geoFire = new GeoFire(geoLocationRef.child('geofire'));

class GeoFireUtil {

    constructor(userId, username) {
        this.userId = userId;
        this.username = username;
        this.geoLocationRef = firebase.database().ref('users-geolocation').push();
        this.geoFire = new GeoFire(this.geoLocationRef);
        console.log('CLASS GEOFIRE ::::: ', this.geofire);
// output: CLASS GEOFIRE :::::  undefined
    }

....

}
</code>```

I have yet to master JS and some concepts still escape me...can someone point me in the right direction?

答: Never mind I had the wrong variable name in the class.</p>

Body:
Ok so I'm following example on setting up Geofire with Firebase as described in this example: https://github.com/firebase/geofire-js/blob/master/examples/html5Geolocation/js/html5Geolocation.js

If I do the following in a normal JS code file the geoFire variable is set fine:

import * as firebase from 'firebase';
import GeoFire from 'geofire';

const config = {
    // config stuff here
};
firebase.initializeApp(config);

let geoLocationRef = firebase.database().ref('users-geolocation').push();
let geoFire = new GeoFire(geoLocationRef);
console.log('GEOFIRE :::::: ', geoFire);
// output: GEOFIRE ::::::  GeoFire {ref: ƒ, set: ƒ, get: ƒ, remove: ƒ, query: ƒ}

HOWEVER, if I try to do something similar in a GeoFireUtil.js class so that I can more easily include the GeoFire functionality where ever I want I am getting 'geoFire is undefined':

import firebase from './firebase-connection';
import GeoFire from 'geofire';

// geofire connection ##################

//let geoLocationRef = firebase.database().ref('users-geolocation').push();
// Create a new GeoFire key under users Firebase location
//let geoFire = new GeoFire(geoLocationRef.child('geofire'));

class GeoFireUtil {

    constructor(userId, username) {
        this.userId = userId;
        this.username = username;
        this.geoLocationRef = firebase.database().ref('users-geolocation').push();
        this.geoFire = new GeoFire(this.geoLocationRef);
        console.log('CLASS GEOFIRE ::::: ', this.geofire);
// output: CLASS GEOFIRE :::::  undefined
    }

....

}

I have yet to master JS and some concepts still escape me...can someone point me in the right direction?


问:
Default font size across browser
Is 16px the default font size in all browser or are their outliers. I know user can change it but I am referring to the one provided by default by the browser.</p>

答:
Yes, it is 16px, according to this source:

If you haven't set the font size anywhere on the page, then it is the browser default, which is often 16px.

as well as this SO post.

Title: Default font size across browser


问:
How to set a ripple effect on textview or imageview on Android?
I want to set a ripple effect on textview and imageview in Android Studio. How can I do it?</p>

答:
In the case of the well voted solution posted by @Bikesh M Annur (here) doesn't work to you, try using:

```<code><TextView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />

<ImageView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />
</code>```

Also, when using android:clickable="true" add android:focusable="true" because:

"A widget that is declared to be clickable but not declared to be focusable is not accessible via the keyboard."

Body:
In the case of the well voted solution posted by @Bikesh M Annur (here) doesn't work to you, try using:

<TextView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />

<ImageView
...
android:background="?android:attr/selectableItemBackgroundBorderless"
android:clickable="true" />

Also, when using android:clickable="true" add android:focusable="true" because:

"A widget that is declared to be clickable but not declared to be focusable is not accessible via the keyboard."


问:
find the first duplicate number from an array for which the second occurrence has the minimal index
i am trying to write a javascript code to  find the first duplicate number from an arrayn for which the second occurrence has the minimal index.I have already written the function and it works fine for almost all given arrays except for the test case given below.

Input:
a: [1, 1, 2, 2, 1]
Output:
2
Expected Output:
1

The javascript code is given below

```<code>function firstDuplicate(a) {

  var firstIndex = "";
  var isMatch = false;
  for (var i = 0; i <= a.length; i++) {
    for (var j = i + 1; j <= a.length; j++) {
      alert(a[i] + "," + a[j]);
      if (a[i] === a[j]) {
        firstIndex = j;
        isMatch = true;
        break;
      }
    }

  }
  if (isMatch)
    return a[firstIndex];
  else
    return -1;

}
</code>```

the program is bugged using alert statement inside the second for loop.I found that the value of a[i] and a[j] is same in the first execution of the loop itself yet the if condition right below fails. I wonder how this happens and can anyone plaese explain me why this happens?

答:
You could take a single loop approach with using a hash table for indicating visited items.

function firstDuplicate(array) {
    var hash = Object.create(null),
        i = 0,
        l = array.length,
        item;

    while (i < l) {
        item = array[i];
        if (hash[item]) {
            return item;
        }
        hash[item] = true;
        i++;
    }
    return -1;
}

console.log(firstDuplicate([1, 1, 2, 2, 1]));    //  1
console.log(firstDuplicate([2, 3, 3, 1, 5, 2])); //  3
console.log(firstDuplicate([2, 4, 3, 5, 1]));    // -1```

Body:
i am trying to write a javascript code to  find the first duplicate number from an arrayn for which the second occurrence has the minimal index.I have already written the function and it works fine for almost all given arrays except for the test case given below.

Input:
a: [1, 1, 2, 2, 1]
Output:
2
Expected Output:
1

The javascript code is given below

function firstDuplicate(a) {

  var firstIndex = "";
  var isMatch = false;
  for (var i = 0; i <= a.length; i++) {
    for (var j = i + 1; j <= a.length; j++) {
      alert(a[i] + "," + a[j]);
      if (a[i] === a[j]) {
        firstIndex = j;
        isMatch = true;
        break;
      }
    }

  }
  if (isMatch)
    return a[firstIndex];
  else
    return -1;

}

the program is bugged using alert statement inside the second for loop.I found that the value of a[i] and a[j] is same in the first execution of the loop itself yet the if condition right below fails. I wonder how this happens and can anyone plaese explain me why this happens?


问:
How to add a custom event to a NativeScript UI plugin
What is required to define a custom event for a UI plugin in NativeScript?

What I'm trying to achieve is to trigger a foo event that works similar to the tap event on a Button and can be hooked into as follows:

<Page xmlns="http://schemas.nativescript.org/tns.xsd"
      xmlns:fooplugin="nativescript-foo-plugin">
  <StackLayout>
    <Button text="Tap Me!" tap="{{ onTap }}" />
    <fooplugin:FooPlugin foo="{{ onFoo }}" />
  </StackLayout>
</Page>
```

<p>What I've done essentially boils down to calling the <code>notify</code> function with the <code>eventName</code> value of <code>foo</code> from within the plugin code (ignoring memory leak considerations):</p>

<pre class="lang-js prettyprint-override"><code>import * as view from 'ui/core/view';

export class FooPlugin extends view.View {
  constructor() {
    super();

    setTimeout(() => {
      this.notify({
        eventName: 'foo',
        object: this,
      });

      // also tried this._emit('foo');
    }, 1000);
  }
}
</code>```

Is there something else that I'm missing and that I need to do to make this work?

答:
create a property of your Event public static fooEvent="foo". The name is important! It has to be eventname + "Event"

overload the on-function in your declaration file index.d.ts or FooPlugin.d.ts

// Needed when on method is overriden.
on(eventNames: string, callback: (data: EventData) => void, thisArg?: any);

Body:
What is required to define a custom event for a UI plugin in NativeScript?

What I'm trying to achieve is to trigger a foo event that works similar to the tap event on a Button and can be hooked into as follows:

<Page xmlns="http://schemas.nativescript.org/tns.xsd"
      xmlns:fooplugin="nativescript-foo-plugin">
  <StackLayout>
    <Button text="Tap Me!" tap="{{ onTap }}" />
    <fooplugin:FooPlugin foo="{{ onFoo }}" />
  </StackLayout>
</Page>

What I've done essentially boils down to calling the notify function with the eventName value of foo from within the plugin code (ignoring memory leak considerations):

import * as view from 'ui/core/view';

export class FooPlugin extends view.View {
  constructor() {
    super();

    setTimeout(() => {
      this.notify({
        eventName: 'foo',
        object: this,
      });

      // also tried this._emit('foo');
    }, 1000);
  }
}

Is there something else that I'm missing and that I need to do to make this work?


问:
Cannot open JSON file from Fragment Activity - Android Studio
The problem is that I cannot open a .json file from the /assets folder.

The function I used:

The call:
String json = readJSONFile("planner.json");

I mention that the Activity extends Fragment.

THE ERROR:
the is = manager.open(fileName); is null

Am I missing something?

EDIT:

Logs:

Which comes from:

It's normal, due to the fact that the manager.open(fileName) returns null;

答:
Try below code

```<code>JSONObject obj = new JSONObject(readJSONFromAsset("planner.json"));
public String readJSONFromAsset(String fileName) {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open(fileName);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}
</code>```

Updated

You making a asset folder in wrong way in wrong path make it proper and it will work

Body:
Try below code

JSONObject obj = new JSONObject(readJSONFromAsset("planner.json"));
public String readJSONFromAsset(String fileName) {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open(fileName);
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

Updated

You making a asset folder in wrong way in wrong path make it proper and it will work


问:
Processing large xml files
I am having a large xml file which contains many sub elements. I want to able to run some xpath queries. I tried using vtd-xml in java, but I get outofmemory error sometimes, because the xml is so large to fit into memory. Is there an alternative way of processing such large xml's.</p>

答: Did you use standard vtd or extended VTD-xml? If you use extended XML then you have the option of using memory mapping... did you try that?</p>

Title: Processing large xml files


问:
Android RecyclerView Scrolling Performance
I have created RecyclerView example basing on Creating Lists and Cards guide. My adapter have a pattern implementation only for inflate the layout.

The problem is the poor scrolling performance. This in a RecycleView with only 8 items.

In some tests I verified that in Android L this problem does not occurs. But in the KitKat version the decreasing of performance is evident.

答:
This helped me getting more smooth scrolling:

override the onFailedToRecycleView(ViewHolder holder) in the adapter

and stop any ongoing animations (if any)
    holder."animateview".clearAnimation();

remember to
return true;


答:
I assume that you want to get the object with maximum value y from data[0].values, since data itself is an array with only one element.

If you wanted to only get the max value of y (1.9), you could use Math.max, but if you want to get the whole object that has maximum y, you would need to iterate through the array again to find the object that has y == 1.9.

Instead you can do both at once using Array.prototype.reduce, which iterates through the array calling the callback on each element similarly to Array.prototype.forEach, except the value you return from the callback on each iteration is passed as an argument to the next iteration

data = [
    {
      values: [
        { x:'2017-01', y: 1.2 },
        { x:'2017-02', y: 1.3 },
        { x:'2017-03', y: 1.5 },
        { x:'2017-04', y: 1.6 },
        { x:'2017-05', y: 1.8 },
        { x:'2017-06', y: 1.9 },
        { x:'2017-07', y: 1.5 },
        { x:'2017-08', y: 1.7 },
        { x:'2017-09', y: 1.5 },
        { x:'2017-10', y: 0 }
      ]
    }
  ];

var max = data[0].values.reduce( function( maxSoFar, current ) {
    // If current.y is larger than maxSoFar.y, return current
    // so that it becomes maxSoFar for the next iteration
    return current.y > maxSoFar.y ? current : maxSoFar;
});

console.log( max );```

Title: get the hightest value of array

Body:
I would like to get the hightest value of array (only the 'y'), how can I do that?

I'm getting only the value of array setting into[] like values[0]

data = [
    {
      values: [
        { x:'2017-01', y: 1.2 },
        { x:'2017-02', y: 1.3 },
        { x:'2017-03', y: 1.5 },
        { x:'2017-04', y: 1.6 },
        { x:'2017-05', y: 1.8 },
        { x:'2017-06', y: 1.9 },
        { x:'2017-07', y: 1.5 },
        { x:'2017-08', y: 1.7 },
        { x:'2017-09', y: 1.5 },
        { x:'2017-10', y: 0 }
      ]
    }
  ];

  data.forEach(function(d) {
    console.log(Math.max(d.values[0].y));
  });


问:
GPU mxnetR windows10
I started GPU computing by mxnetR in windows 10.

Simple question is if mx.mlp with mx.gpu use multiple cores in GPU. I seems not...

Also as a test, I wrote a simple program of mx.mlp, with doParallel. But it seems not to run the program in multiple cores. only 1 core of GPU usage was increased.

Please give me your ideas on how to ue multiple cores in GPU to maximize a value of GPU computing by mx.mlp with mx.gpu.

答:
When running mxnet with GPU, mxnet will use many cores simultaneously by determining which math operations can be run in parallel.

A simple metric to reassure yourself that you're getting value-for-money from the GPU is to use the nvidia-smi command to watch GPU utilization.

Title: GPU mxnetR windows10


Title: get the hightest value of array

Body:
The values are a property of the 1st object (index 0) of the array - data[0].values. Get all y values using Array#map, and apply Math#max to get the maximum:

var data = [{"values":[{"x":"2017-01","y":1.2},{"x":"2017-02","y":1.3},{"x":"2017-03","y":1.5},{"x":"2017-04","y":1.6},{"x":"2017-05","y":1.8},{"x":"2017-06","y":1.9},{"x":"2017-07","y":1.5},{"x":"2017-08","y":1.7},{"x":"2017-09","y":1.5},{"x":"2017-10","y":0}]}];

var result = Math.max.apply(null, data[0].values.map(function(o) {
  return o.y;
}));

console.log(result);


问:
Sticky scrollview subview has incorrect frame after scrolling fast. Compilable example
I have spent the past 12 hours futzing with this and I'm going braindead.

view on bitbucket:
  https://bitbucket.org/burneraccount/scrollviewexample

git https: https://bitbucket.org/burneraccount/scrollviewexample.git

git ssh: git@bitbucket.org:burneraccount/scrollviewexample.git

^ That is a condensed, self-contained Xcode project that exemplifies the problem I'm having in my real work.

Summary

I am trying to achieve a static-image effect, where the image (a rock in the example) appears stuck to the screen while the lower content scrolls upwards appearing to go above the scrollview.

There's a screen-sized (UIScrollView*)mainScrollView. This scrollview has a (UIView*)contentView. contentView is ~1200 pts long and has two subviews: (UIScrollView*)imageScroller and (UITextView*)textView.

All works well until you scroll up a little bit, then scroll down really fast. The resulting position after movement stops is incorrect. It somehow doesn't update properly in the scrollviewDidScroll delegate method. The fast downward scroll (only after you've dragged up) behaves somewhat correctly, but still results in a misplaced view:

gently dragging does almost nothing, and the velocity of the scroll is directly related to the incorrect offset.

Here is the offending code:

```<code>- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.mainScrollView)
    {

        CGFloat mainOffset = self.mainScrollView.contentOffset.y;
        if (mainOffset > 0 && mainOffset < self.initialImageScrollerFrame.size.height)
        {
            CGRect imageFrame = self.imageScroller.frame;
            CGFloat offset = mainOffset-self.lastOffset;
            self.imageScroller.frame = CGRectMake(imageFrame.origin.x,
                                                  imageFrame.origin.y + offset, // scroll up
                                                  imageFrame.size.width,
                                                  imageFrame.size.height - offset); // hide the bottom of the image
            self.lastOffset = mainOffset;
        }

    }
}
</code>```

I've restructured this in almost every way I could imagine and it always has similar effects. The worst part is how the very simple and straightforward code fails to do what is seems like it's guaranteed to do.
Also odd is that the zoom-effect I use in my real project works fine using the same mechanism to size the same view element. It runs inside (contentOffset < 0) instead of (contentOffset > 0), so it only zoom in on the imageScroller when you're pulling the view below it's normal offset. That leads me to conspire that some data is lost as it crosses the contentOffset 0, but my conspiracies have been shot down all day.

This is example is a lot less complicated than the real project I'm working on, but it properly reproduces the problem. Please let me know if you can't open my project, or can't connect to the repo.

There is likely a largely obvious fix for this, but I am hours past the point of having any new perspective. I will be thoroughly amazed if I ever get this to work.

答:
The same issue but for add another functionality, button for left/right listing UIScrollView, after fast tapping on it, scroll view is broke my brain ;(

I think better scrolling without animation, it preventing glitches for UIScrollView content. May be it is not answer, but...

Body:
I have spent the past 12 hours futzing with this and I'm going braindead.

view on bitbucket:
  https://bitbucket.org/burneraccount/scrollviewexample

git https: https://bitbucket.org/burneraccount/scrollviewexample.git

git ssh: git@bitbucket.org:burneraccount/scrollviewexample.git

^ That is a condensed, self-contained Xcode project that exemplifies the problem I'm having in my real work.

Summary

I am trying to achieve a static-image effect, where the image (a rock in the example) appears stuck to the screen while the lower content scrolls upwards appearing to go above the scrollview.

There's a screen-sized (UIScrollView*)mainScrollView. This scrollview has a (UIView*)contentView. contentView is ~1200 pts long and has two subviews: (UIScrollView*)imageScroller and (UITextView*)textView.

All works well until you scroll up a little bit, then scroll down really fast. The resulting position after movement stops is incorrect. It somehow doesn't update properly in the scrollviewDidScroll delegate method. The fast downward scroll (only after you've dragged up) behaves somewhat correctly, but still results in a misplaced view:

gently dragging does almost nothing, and the velocity of the scroll is directly related to the incorrect offset.

Here is the offending code:

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.mainScrollView)
    {

        CGFloat mainOffset = self.mainScrollView.contentOffset.y;
        if (mainOffset > 0 && mainOffset < self.initialImageScrollerFrame.size.height)
        {
            CGRect imageFrame = self.imageScroller.frame;
            CGFloat offset = mainOffset-self.lastOffset;
            self.imageScroller.frame = CGRectMake(imageFrame.origin.x,
                                                  imageFrame.origin.y + offset, // scroll up
                                                  imageFrame.size.width,
                                                  imageFrame.size.height - offset); // hide the bottom of the image
            self.lastOffset = mainOffset;
        }

    }
}

I've restructured this in almost every way I could imagine and it always has similar effects. The worst part is how the very simple and straightforward code fails to do what is seems like it's guaranteed to do.
Also odd is that the zoom-effect I use in my real project works fine using the same mechanism to size the same view element. It runs inside (contentOffset < 0) instead of (contentOffset > 0), so it only zoom in on the imageScroller when you're pulling the view below it's normal offset. That leads me to conspire that some data is lost as it crosses the contentOffset 0, but my conspiracies have been shot down all day.

This is example is a lot less complicated than the real project I'm working on, but it properly reproduces the problem. Please let me know if you can't open my project, or can't connect to the repo.

There is likely a largely obvious fix for this, but I am hours past the point of having any new perspective. I will be thoroughly amazed if I ever get this to work.


问:
facebook-c#-sdk rendering unwanted html tags
I'm trying to get a simple facebook application to work, based on the downloaded example projects.  The code prints some javascript code which makes perfect sense.  The problem is it wraps it in a  tag, and also prints a body tag.  These things mess up facebook fbml apps, so that when I try to run the application through facebook I get this error:

FBML Error (line 3): illegal tag "body" under "fb:canvas"Sorry, the application you were using is experiencing a problem. Please try again later.

When viewing the source I can see that the problem is the injected html and body tags.  Am I doing something wrong?  How do I get the sdk to print the javascript without printing these extra tags?

Thanks a lot!

答:
First off, the Facebook C# SDK does not support FBML applications. Facebook is deprecating FBML. I would strongly suggest building an iFrame app if possible. That being said, the Facebook C# SDK has nothing to do with the html markup. Simply remove the html markup from your master page.

You should be able to get the Facebook C# SDK working with FBML, but again we do not support it and I would not recommend spending time developing a new app on a technology that is being deprecated.


问:
Stop time from saying 07 minutes and just 7 in Pyttsx3
```<code>import pyttsx3
import time

time = time.strftime("%M minutes past %I")

engine = pyttsx3.init()
engine.setProperty('rate',200)
engine.say("Hi Tom");
engine.say("The time is" + time);
engine.runAndWait();
</code>```

When running this it will say "Hi Tom, the time is 07 minutes past 10" for example and will say a 0 in front of the minutes if its between 0-9 but 10-59 its says it normally. Is there a way to remove the 0 from being said?

答:
Could this be useful</p>

```<code>t = time.localtime()
   ...
engine.say('The time is %d minutes past %s' % (t.tm_min,t.tm_hour))
</code>```

Body:
import pyttsx3
import time

time = time.strftime("%M minutes past %I")

engine = pyttsx3.init()
engine.setProperty('rate',200)
engine.say("Hi Tom");
engine.say("The time is" + time);
engine.runAndWait();

When running this it will say "Hi Tom, the time is 07 minutes past 10" for example and will say a 0 in front of the minutes if its between 0-9 but 10-59 its says it normally. Is there a way to remove the 0 from being said?

Body:
Could this be useful

t = time.localtime()
   ...
engine.say('The time is %d minutes past %s' % (t.tm_min,t.tm_hour))


问:
How do I identify a string using a wildcard using R?
I'd like to count the duration of some words containing the number "0" after a string, as shown in the picture (I inserted a red dot under the words with the character I'd like to work with).
Is there anything like a wildcard so that I can work only with the words containing this string?

[Picture]

答:
If the filename should not be part of the match, one can utilize the filename column to avoid regex from matching:

```<code>library(dplyr)
library(purrr)

df %>%
  mutate(no_filename = map2_chr(filename, text, ~gsub(.x, '', .y))) %>%
  filter(grepl("^0", no_filename)) %>%
  select(-no_filename)
</code>```

Result:

```<code>  filename      text     value
1       S2  S20XXXXX 0.2065314
2       S3  S30XXXXX 0.8146400
3       S4  S40XXXXX 0.8123895
4       S6  S60XXXXX 0.1111354
5       S7  S70XXXXX 0.1028646
6       S9  S90XXXXX 0.1306957
7       S9  S90XXXXX 0.3203732
8      S10 S100XXXXX 0.1876911
</code>```

Note:

Notice that S100XXXXX is matched, but not S101XXXXX

Data:

```<code>library(dplyr)
df = data.frame(filename = rep(paste0('S', 1:10), each = 5))
set.seed(123)
df = df %>%
  mutate(text = paste0(filename, sample(c(0:5), 50, replace = TRUE),
                     paste(rep('X', 5), collapse = "")),
         value = runif(50))
</code>```

Body:
If the filename should not be part of the match, one can utilize the filename column to avoid regex from matching:

library(dplyr)
library(purrr)

df %>%
  mutate(no_filename = map2_chr(filename, text, ~gsub(.x, '', .y))) %>%
  filter(grepl("^0", no_filename)) %>%
  select(-no_filename)

Result:

  filename      text     value
1       S2  S20XXXXX 0.2065314
2       S3  S30XXXXX 0.8146400
3       S4  S40XXXXX 0.8123895
4       S6  S60XXXXX 0.1111354
5       S7  S70XXXXX 0.1028646
6       S9  S90XXXXX 0.1306957
7       S9  S90XXXXX 0.3203732
8      S10 S100XXXXX 0.1876911

Note:

Notice that S100XXXXX is matched, but not S101XXXXX

Data:

library(dplyr)
df = data.frame(filename = rep(paste0('S', 1:10), each = 5))
set.seed(123)
df = df %>%
  mutate(text = paste0(filename, sample(c(0:5), 50, replace = TRUE),
                     paste(rep('X', 5), collapse = "")),
         value = runif(50))


问:
How to send email direct to gmail inbox not spam using codeigniter
I want to send email using codeigniter to gmail inbox not span. i have written following code but email sent to spam not inbox.

My code:

```<code><?php
$this->load->library('email');

                        //SMTP & mail configuration
                $email = $this->input->post('email');
                        $config = array(
                            'protocol'  => 'tls',
                           // 'protocol'  => 'smtp',
                            'smtp_host' => 'ssl://smtp.googlemail.com',
                            'smtp_port' => 465,
                            'smtp_user' => 'mitesh.ebiztrait@gmail.com',
                            'smtp_pass' => '*****',
                            'mailtype'  => 'html',
                            'charset'   => 'utf-8',
                            'mailpath' => '/usr/sbin/sendmail',
                             'wordwrap' => TRUE,
                        );
                        $this->email->initialize($config);
                        $this->email->set_mailtype("html");
                        $this->email->set_newline("\r\n");

                        //Email content
                $data = 'http://52.14.24.245/upload/images/purchasedticket/'.$qrcode_image;

                $htmlContent .=  '<!DOCTYPE html>
                <html>
                <head>
                    <meta charset="utf-8">
                    <meta http-equiv="X-UA-Compatible" content="IE=edge">
                    <title> </title>
                    <link rel="stylesheet" href="">
                </head>
                <body>
                    <p>Hi ,</p><br>
                    <strong>Payment for party ticket is successfull! </strong>

                    <p>Following is the QR Code, kindly present this QR code while you attend the party. </p>
                    <br>
                    URL : '.$data.'
                    <br>
                    <img src="'.$data.'"  / ><br />
                    <br>

                    Thanksbr, <br><br>
                    TheMove Team
                </body>
                </html>';
                        // $htmlContent = 'TheMove: party ticket purchase success!!';
                        // $htmlContent .= '<p>This email has sent via SMTP server from CodeIgniter application.</p>';

                        $this->email->to($email);
                        $this->email->from('ashvin.ebiztrait@gmail.com','Party App');
                        $this->email->subject('TheMove: party ticket purchase success!!');
                        $this->email->message($htmlContent);

                        //Send email
                        $data = $this->email->send();
?>
</code>```

How can i send email direct to gmail inbox not spam?

答:
Make sure that email content is less "spam like". Reduce HTML and images, make sure that you have enough copy and run it thru some online validator.

Looks like you are using a lot of exclamation marks in subject, from field is typical spam message and so on. It's not the issue with CI but with email copy

Body:
I want to send email using codeigniter to gmail inbox not span. i have written following code but email sent to spam not inbox.

My code:

<?php
$this->load->library('email');

                        //SMTP & mail configuration
                $email = $this->input->post('email');
                        $config = array(
                            'protocol'  => 'tls',
                           // 'protocol'  => 'smtp',
                            'smtp_host' => 'ssl://smtp.googlemail.com',
                            'smtp_port' => 465,
                            'smtp_user' => 'mitesh.ebiztrait@gmail.com',
                            'smtp_pass' => '*****',
                            'mailtype'  => 'html',
                            'charset'   => 'utf-8',
                            'mailpath' => '/usr/sbin/sendmail',
                             'wordwrap' => TRUE,
                        );
                        $this->email->initialize($config);
                        $this->email->set_mailtype("html");
                        $this->email->set_newline("\r\n");

                        //Email content
                $data = 'http://52.14.24.245/upload/images/purchasedticket/'.$qrcode_image;

                $htmlContent .=  '<!DOCTYPE html>

                    <meta charset="utf-8">
                    <meta http-equiv="X-UA-Compatible" content="IE=edge">
                    <title> </title>
                    <link rel="stylesheet" href="">

Hi ,

                    Payment for party ticket is successfull!

Following is the QR Code, kindly present this QR code while you attend the party.

                    URL : '.$data.'

                    Thanksbr,

                    TheMove Team

                ';
                        // $htmlContent = 'TheMove: party ticket purchase success!!';
                        // $htmlContent .= '
This email has sent via SMTP server from CodeIgniter application.
';

                        $this->email->to($email);
                        $this->email->from('ashvin.ebiztrait@gmail.com','Party App');
                        $this->email->subject('TheMove: party ticket purchase success!!');
                        $this->email->message($htmlContent);

                        //Send email
                        $data = $this->email->send();
?>

How can i send email direct to gmail inbox not spam?


问:
Anonymous inner classes in C#
I'm in the process of writing a C# Wicket implementation in order to deepen my understanding of C# and Wicket.  One of the issues we're running into is that Wicket makes heavy use of anonymous inner classes, and C# has no anonymous inner classes.

So, for example, in Wicket, you define a Link like this:

```<code>Link link = new Link("id") {
    @Override
    void onClick() {
        setResponsePage(...);
    }
};
</code>```

Since Link is an abstract class, it forces the implementor to implement an onClick method.

However, in C#, since there are no anonymous inner classes, there is no way to do this.  As an alternative, you could use events like this:

```<code>var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);
</code>```

Of course, there are a couple of drawbacks with this.  First of all, there can be multiple Click handlers, which might not be cool.  It also does not force the implementor to add a Click handler.

Another option might be to just have a closure property like this:

```<code>var link = new Link("id");
link.Click = () => setResponsePage(...);
</code>```

This solves the problem of having many handlers, but still doesn't force the implementor to add the handler.

So, my question is, how do you emulate something like this in idiomatic C#?

答:
You can make the delegate be part of the constructor of the Link class.  This way the user will have to add it.

```<code>public class Link
{
    public Link(string id, Action handleStuff)
    {
        ...
    }

}
</code>```

Then you create an instance this way:

```<code>var link = new Link("id", () => do stuff);
</code>```

Title: Anonymous inner classes in C#

Body:
I'm in the process of writing a C# Wicket implementation in order to deepen my understanding of C# and Wicket.  One of the issues we're running into is that Wicket makes heavy use of anonymous inner classes, and C# has no anonymous inner classes.

So, for example, in Wicket, you define a Link like this:

Link link = new Link("id") {
    @Override
    void onClick() {
        setResponsePage(...);
    }
};

Since Link is an abstract class, it forces the implementor to implement an onClick method.

However, in C#, since there are no anonymous inner classes, there is no way to do this.  As an alternative, you could use events like this:

var link = new Link("id");
link.Click += (sender, eventArgs) => setResponsePage(...);

Of course, there are a couple of drawbacks with this.  First of all, there can be multiple Click handlers, which might not be cool.  It also does not force the implementor to add a Click handler.

Another option might be to just have a closure property like this:

var link = new Link("id");
link.Click = () => setResponsePage(...);

This solves the problem of having many handlers, but still doesn't force the implementor to add the handler.

So, my question is, how do you emulate something like this in idiomatic C#?

Body:
You can make the delegate be part of the constructor of the Link class.  This way the user will have to add it.

public class Link
{
    public Link(string id, Action handleStuff)
    {
        ...
    }

}

Then you create an instance this way:

var link = new Link("id", () => do stuff);


问:
How do I parse a string with 'h', 'm', 's' suffixes to a TimeSpan?

I need to parse the string "26h44m3s" to  a TimeSpan in C#. I cannot find anything implemented in .NET that can handle it. So how do I accomplish it, and in clean way? And are there any existing nugets for this?

I am receiving the string from the "duration" property on Twitch API endpoint GetVideos.

答:
You can do this by using regex parsing without any external dependencies:

```<code>public static TimeSpan ParseTwitchTime(string input)
{
    var m = Regex.Match(input, @"^((?<hours>\d+)h)?((?<minutes>\d+)m)?((?<seconds>\d+)s)?$", RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.RightToLeft);

    int hs = m.Groups["hours"].Success ? int.Parse(m.Groups["hours"].Value) : 0;
    int ms = m.Groups["minutes"].Success ? int.Parse(m.Groups["minutes"].Value) : 0;
    int ss = m.Groups["seconds"].Success ? int.Parse(m.Groups["seconds"].Value) : 0;

    return TimeSpan.FromSeconds(hs*60*60 + ms*60 + ss);
}
</code>```

Usage:

```<code>        var d = ParseTwitchTime("100h");
        d = ParseTwitchTime("23m1000s");
        d = ParseTwitchTime("12345h678s");
</code>```

PS: RightToLeft option used just for regex performance and not affecting output result (it backtracks a lot if done without it).

Body:
You can do this by using regex parsing without any external dependencies:

public static TimeSpan ParseTwitchTime(string input)
{
    var m = Regex.Match(input, @"^((?<hours>\d+)h)?((?<minutes>\d+)m)?((?<seconds>\d+)s)?$", RegexOptions.ExplicitCapture | RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.RightToLeft);

    int hs = m.Groups["hours"].Success ? int.Parse(m.Groups["hours"].Value) : 0;
    int ms = m.Groups["minutes"].Success ? int.Parse(m.Groups["minutes"].Value) : 0;
    int ss = m.Groups["seconds"].Success ? int.Parse(m.Groups["seconds"].Value) : 0;

    return TimeSpan.FromSeconds(hs*60*60 + ms*60 + ss);
}

Usage:

        var d = ParseTwitchTime("100h");
        d = ParseTwitchTime("23m1000s");
        d = ParseTwitchTime("12345h678s");

PS: RightToLeft option used just for regex performance and not affecting output result (it backtracks a lot if done without it).


问:
Visual Studio - javascript file generation almost freeze PC - how to disable
right now I'm writing a code in Visual Studio 2017 (Community).

The code is a mix of Asp.Net, C# and Javascript (with some plugins, like jQuery, knockout, etc..)

I'm facing a very frustrating thing in visual studio that is EVERY time I modify and save a single javascript file, Visual Studio starts a generation of ALL javascript files that slows down A LOT the computer (SSD, intel i5, 8gb RAM) until it finishes, sometimes I need to wait it finish to be able to continue writing my code.

I don't know why VS do this, but I want to know if it's possible to disable it and prevent VS to generate/compile those files every time a save just one file.

Here goes an image that show what VS do:

Somebody knows what is that and what can be done to disable it?

答:
I was having a similar issue, and disabling the language service seemed to help me.

Tools > Options > Text Editor > JavaScript/TypeScript > Language Service

Disable Language Service


问:
two-way binding - nested object - angular - Cannot read property of undefined
I want to use [(ngModel)] for a nested object, but is giving me an error

Cannot read property 'mxn' of undefined

these are the data structure of my models:

company.model.ts

```<code>import Currency from './currency.model';

class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;

constructor() {
    this.name = '';
    this.date = new Date();
    this.maxLimit = 0;
    this.source = [''];
    this.deliveryMethod = [''];
    this.currency.mxn = 0;
    this.currency.php = 0;
    }
}

export default Company;
</code>```

currency.model.ts

```<code>class Currency {
mxn: number;
php: number;

constructor() {
    this.mxn = 0;
    this.php = 0;
}
}

export default Currency;
</code>```

and this is part of company.ts

```<code>public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];
</code>```

and HTML

in HTML page I'm able to show the mxn value by just using :

```<code><tr class="companies" *ngFor="let company of companiesList">
{{company.currency.mxn}}
</code>```

but when I want to use it with ngModel two-way binding for updating the value and sending it to the database it doesn't work.

[(ngModel)] = "newCompany.currency.mxn"
it produces the mentioned error above.
if I use
[(ngModel)] = "newCompany.currency" it doesn't give me an error but the code it's useless since i can't assign any value to mxn.

I have to say that [(ngModel)] = "newCompany.name" it works fine with this and I can update the name.

the backend works fine as I tried it with Postman. the problem is angular side.

so the question is if my data structure is correct how can I use two-way binding for the nested object?

答:
A slight change in your Company model should be enough:

class Company {
  _id: string;
  name: string;
  maxLimit: number;
  source: [string];
  deliveryMethod: [string];
  currency: Currency = new Currency(); // provide an instance, otherwise this field will be undefined
  date: Date;

  constructor() {
      this.name = '';
      this.date = new Date();
      this.maxLimit = 0;
      this.source = [''];
      this.deliveryMethod = [''];
      this.currency.mxn = 0;
      this.currency.php = 0;
      }
  }

export default Company;```

Body:
I want to use [(ngModel)] for a nested object, but is giving me an error

Cannot read property 'mxn' of undefined

these are the data structure of my models:

company.model.ts

import Currency from './currency.model';

class Company {
_id: string;
name: string;
maxLimit: number;
source: [string];
deliveryMethod: [string];
currency: Currency;
date: Date;

constructor() {
    this.name = '';
    this.date = new Date();
    this.maxLimit = 0;
    this.source = [''];
    this.deliveryMethod = [''];
    this.currency.mxn = 0;
    this.currency.php = 0;
    }
}

export default Company;

currency.model.ts

class Currency {
mxn: number;
php: number;

constructor() {
    this.mxn = 0;
    this.php = 0;
}
}

export default Currency;

and this is part of company.ts

public newCompany: Company = new Company();
companiesList: Company[];
editcompanies: Company[] = [];

and HTML

in HTML page I'm able to show the mxn value by just using :

{{company.currency.mxn}}

but when I want to use it with ngModel two-way binding for updating the value and sending it to the database it doesn't work.

[(ngModel)] = "newCompany.currency.mxn"
it produces the mentioned error above.
if I use
[(ngModel)] = "newCompany.currency" it doesn't give me an error but the code it's useless since i can't assign any value to mxn.

I have to say that [(ngModel)] = "newCompany.name" it works fine with this and I can update the name.

the backend works fine as I tried it with Postman. the problem is angular side.

so the question is if my data structure is correct how can I use two-way binding for the nested object?


问:
Use animate() with series of levelplots in R raster
I have a time series of 25 yearly land cover rasters. As this is categorical data, I use levelplot(inputRaster) (part of the rasterVis library) to plot a single raster. However, I would like to sequentially plot the yearly rasters, as the animate function of the raster library does. When I use

rasStack <- stack(listOfRasters)
animate(rasStack)

The result does not have a categorical legend.
So in short: how can I combine the functionalities of levelplot and animate?

答:
Function animate only accepts raster objects as input. You can try saveGIF to animate levelplots:

```<code>library(raster)
library(rasterVis)
library(animation)
library(classInt)

r <- raster(ncol=40, nrow=20)
r[] <- rnorm(n=ncell(r))
s <- stack(x=c(r, r*r, r*r*r, r*r*r*r))

classes <- classIntervals(values(r), n=5, style="fisher", precision = 3)
brks <- classes$brks
brks <- round(brks, 2)

saveGIF({
  for(i in c(1:nlayers(s))){
    l <- levelplot(s[[i]], colorkey=list(at=brks, labels=c(as.character(brks))), margin=FALSE)
    plot(l)
  }
}, interval=0.2, movie.name="animation.gif")
</code>```

Body:
Function animate only accepts raster objects as input. You can try saveGIF to animate levelplots:

library(raster)
library(rasterVis)
library(animation)
library(classInt)

r <- raster(ncol=40, nrow=20)
r[] <- rnorm(n=ncell(r))
s <- stack(x=c(r, r*r, r*r*r, r*r*r*r))

classes <- classIntervals(values(r), n=5, style="fisher", precision = 3)
brks <- classes$brks
brks <- round(brks, 2)

saveGIF({
  for(i in c(1:nlayers(s))){
    l <- levelplot(s[[i]], colorkey=list(at=brks, labels=c(as.character(brks))), margin=FALSE)
    plot(l)
  }
}, interval=0.2, movie.name="animation.gif")