问:
Can someone explain this definition of the 'dirent' struct in Solaris?
Recently I was looking at the 'dirent' structure (in dirent.h) and was a little puzzled by its definition.

NOTE: This header file is from a Solaris machine at my school.

```<code>
typedef struct dirent {
    ino_t       d_ino;
    off_t       d_off;
    unsigned short  d_reclen;
    char        d_name[1];
} dirent_t;
```

Particularly the d_name field. How would this work in the operating system? If you need to store a null terminated string what good is an array of a single char? I know that you can get the address of an array by its first element but I am still confused. Obviously something is happening, but I don't know what. On my Fedora Linux system at home this field is simply defined as:

```<code>char d_name[256];
</code>```

Now that makes a lot more sense for obvious reasons. Can someone explain why the Solaris header file defines the struct as it does?

答:
As others have pointed out, the last member of the struct doesn't have any set size. The array is however long the implementation decides it needs to be to accommodate the characters it wants to put in it. It does this by dynamically allocating the memory for the struct, such as with malloc.

It's convenient to declare the member as having size 1, though, because it's easy to determine how much memory is occupied by any dirent variable d:

```<code>sizeof(dirent) + strlen(d.d_name)
</code>```

Using size 1 also discourages the recipient of such struct values from trying to store their own names in it instead of allocating their own dirent values. Using the Linux definition, it's reasonable to assume that any dirent value you have will acept a 255-character string, but Solaris makes no guarantee that its dirent values will store any more characters than they need to.

I think it was C 99 that introduced a special case for the last member of a struct. The struct could be declared like this instead:

```<code>typedef struct dirent {
  ino_t d_ino;
  off_t d_off;
  unsigned short d_reclen;
  char d_name[];
} dirent_t;
</code>```

The array has no declared size. This is known as the flexible array member. It accomplishes the same thing as the Solaris version, except that there's no illusion that the struct by itself could hold any name. You know by looking at it that there's more to it.

Using the "flexible" declaration, the amount of memory occupied would be adjusted like so:

```<code>sizeof(dirent) + strlen(d.d_name) + 1
</code>```

That's because the flexible array member does not factor in to the size of the struct.

The reason you don't see flexible declarations like that more often, especially in OS library code, is likely for the sake of compatibility with older compilers that don't support that facility. It's also for compatibility with code written to target the current definition, which would break if the size of the struct changed like that.

OwnerDisplayName: TURBOxSPOOL

Body:
Recently I was looking at the 'dirent' structure (in dirent.h) and was a little puzzled by its definition.

NOTE: This header file is from a Solaris machine at my school.

typedef struct dirent {
    ino_t       d_ino;
    off_t       d_off;
    unsigned short  d_reclen;
    char        d_name[1];
} dirent_t;

Particularly the d_name field. How would this work in the operating system? If you need to store a null terminated string what good is an array of a single char? I know that you can get the address of an array by its first element but I am still confused. Obviously something is happening, but I don't know what. On my Fedora Linux system at home this field is simply defined as:

char d_name[256];

Now that makes a lot more sense for obvious reasons. Can someone explain why the Solaris header file defines the struct as it does?

Body:
As others have pointed out, the last member of the struct doesn't have any set size. The array is however long the implementation decides it needs to be to accommodate the characters it wants to put in it. It does this by dynamically allocating the memory for the struct, such as with malloc.

It's convenient to declare the member as having size 1, though, because it's easy to determine how much memory is occupied by any dirent variable d:

sizeof(dirent) + strlen(d.d_name)

Using size 1 also discourages the recipient of such struct values from trying to store their own names in it instead of allocating their own dirent values. Using the Linux definition, it's reasonable to assume that any dirent value you have will acept a 255-character string, but Solaris makes no guarantee that its dirent values will store any more characters than they need to.

I think it was C 99 that introduced a special case for the last member of a struct. The struct could be declared like this instead:

typedef struct dirent {
  ino_t d_ino;
  off_t d_off;
  unsigned short d_reclen;
  char d_name[];
} dirent_t;

The array has no declared size. This is known as the flexible array member. It accomplishes the same thing as the Solaris version, except that there's no illusion that the struct by itself could hold any name. You know by looking at it that there's more to it.

Using the "flexible" declaration, the amount of memory occupied would be adjusted like so:

sizeof(dirent) + strlen(d.d_name) + 1

That's because the flexible array member does not factor in to the size of the struct.

The reason you don't see flexible declarations like that more often, especially in OS library code, is likely for the sake of compatibility with older compilers that don't support that facility. It's also for compatibility with code written to target the current definition, which would break if the size of the struct changed like that.

OwnerDisplayName: Rob Kennedy


来源: stackexchange

问:
In the same search box search by multiple array object properties
```<code>searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }
</code>```

I am making the search term with name which is the property or key in records array. In the same search box I also want to search by age and course.
How can I achieve this.

```<code><input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">
</code>```

答:
You could try to combine the conditions with or, for example like this.</p>

```<code>search() {

      this.records = this.records.filter((res: any)=>{
        return (res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase() ||
            res.age.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase() ||
            res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }

I am making the search term with name which is the property or key in records array. In the same search box I also want to search by age and course.
How can I achieve this.

<input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">

Body:
You could try to combine the conditions with or, for example like this.

search() {

      this.records = this.records.filter((res: any)=>{
        return (res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase() ||
            res.age.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase() ||
            res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }


问:
how to use a non static variable of a class ( let A) in another class ( let B). Here , cannot create a instance of A in B
I want to use a variable of one class (let it be A) in another class (let it be B), but I cannot create an instance for the first class A in class B and should not use static keyword in class A</p>

答:
If the variable is not static, then it doesn't exist without an instance. You may be misunderstanding how OO variables are meant to work.

Think of a class called Person.

If you want a variable that is the same for everyone like "species" then you want a static variable.

```<code>static final String species = "Homo sapiens";
</code>```

Otherwise, if you want something that varies from person to person, then you need a person to exist to get the answer. Otherwise it's like asking "What colour are a person's eyes?" You need to know which person you're talking about to know the answer.

So, if you're trying to call a variable that is constant among all objects of your class then you can make it static. That's what static is there for.
Otherwise, you need to reference an instance.

Body:
If the variable is not static, then it doesn't exist without an instance. You may be misunderstanding how OO variables are meant to work.

Think of a class called Person.

If you want a variable that is the same for everyone like "species" then you want a static variable.

static final String species = "Homo sapiens";

Otherwise, if you want something that varies from person to person, then you need a person to exist to get the answer. Otherwise it's like asking "What colour are a person's eyes?" You need to know which person you're talking about to know the answer.

So, if you're trying to call a variable that is constant among all objects of your class then you can make it static. That's what static is there for.
Otherwise, you need to reference an instance.


问:
How to know about OutOfMemory or StackOverflow errors ahead of time
In Java, is there a way to know that a StackOverflow error or OutOfMemory exception may happen soon?

The OutOfMemory exception might be an easier one to catch, if one is capable of getting memory usage statistics programmatically, and if one knows ahead of time how much memory needs to be used before the OutOfMemory exception is thrown.  But are those values knowable?

For the StackOverflow error, is there a way to get recursion depth, and how does one know what value for recursion depth would cause the error to occur?

By knowing ahead of time whether these errors will happen, I feel I can recover the application more gracefully, instead of watching it crash.

答:
Implementation example using MemoryPoolMXBean

```<code>import static java.lang.management.ManagementFactory.getMemoryMXBean;
import static java.lang.management.ManagementFactory.getMemoryPoolMXBeans;
import static java.lang.management.MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED;
import static java.lang.management.MemoryType.HEAP;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MemoryWatcher {

    public interface Listener {
        void memoryUsageLow(long usedMemory, long maxMemory);
    }

    private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool();
    private static final Logger logger = LoggerFactory.getLogger(MemoryWatcher.class);

    private static MemoryPoolMXBean findTenuredGenPool() {
        for (MemoryPoolMXBean pool : getMemoryPoolMXBeans())
            if (pool.getType() == HEAP && pool.isUsageThresholdSupported())
                return pool;
        return null;
    }

    public static MemoryPoolMXBean getTenuredGenPool() {
        return tenuredGenPool;
    }

    private final Collection<Listener> listeners = new CopyOnWriteArrayList<>();

    public MemoryWatcher(double usageThresholdPercent) {
        if (tenuredGenPool == null) {
            logger.warn("Tenured pool is not used");
            return;
        }
        if (tenuredGenPool.getUsageThreshold() != 0)
            logger.warn("Overriding tenured usage threshold {} with {}", tenuredGenPool.getUsage().getMax() / (double) tenuredGenPool.getUsageThreshold(), usageThresholdPercent);
        tenuredGenPool.setUsageThreshold((long) (tenuredGenPool.getUsage().getMax() * usageThresholdPercent));

        NotificationEmitter emitter = (NotificationEmitter) getMemoryMXBean();
        emitter.addNotificationListener((Notification n, Object hb) -> {
            MemoryUsage usage = tenuredGenPool.getUsage();
            if (n.getType().equals(MEMORY_THRESHOLD_EXCEEDED) && usage.getMax() == usage.getCommitted())
                listeners.forEach(listener -> listener.memoryUsageLow(usage.getUsed(), usage.getMax()));
        }, null, null);
    }

    public boolean addListener(Listener listener) {
        return listeners.add(listener);
    }

    public boolean removeListener(Listener listener) {
        return listeners.remove(listener);
    }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Implementation example using MemoryPoolMXBean

import static java.lang.management.ManagementFactory.getMemoryMXBean;
import static java.lang.management.ManagementFactory.getMemoryPoolMXBeans;
import static java.lang.management.MemoryNotificationInfo.MEMORY_THRESHOLD_EXCEEDED;
import static java.lang.management.MemoryType.HEAP;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.management.Notification;
import javax.management.NotificationEmitter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MemoryWatcher {

    public interface Listener {
        void memoryUsageLow(long usedMemory, long maxMemory);
    }

    private static final MemoryPoolMXBean tenuredGenPool = findTenuredGenPool();
    private static final Logger logger = LoggerFactory.getLogger(MemoryWatcher.class);

    private static MemoryPoolMXBean findTenuredGenPool() {
        for (MemoryPoolMXBean pool : getMemoryPoolMXBeans())
            if (pool.getType() == HEAP && pool.isUsageThresholdSupported())
                return pool;
        return null;
    }

    public static MemoryPoolMXBean getTenuredGenPool() {
        return tenuredGenPool;
    }

    private final Collection<Listener> listeners = new CopyOnWriteArrayList<>();

    public MemoryWatcher(double usageThresholdPercent) {
        if (tenuredGenPool == null) {
            logger.warn("Tenured pool is not used");
            return;
        }
        if (tenuredGenPool.getUsageThreshold() != 0)
            logger.warn("Overriding tenured usage threshold {} with {}", tenuredGenPool.getUsage().getMax() / (double) tenuredGenPool.getUsageThreshold(), usageThresholdPercent);
        tenuredGenPool.setUsageThreshold((long) (tenuredGenPool.getUsage().getMax() * usageThresholdPercent));

        NotificationEmitter emitter = (NotificationEmitter) getMemoryMXBean();
        emitter.addNotificationListener((Notification n, Object hb) -> {
            MemoryUsage usage = tenuredGenPool.getUsage();
            if (n.getType().equals(MEMORY_THRESHOLD_EXCEEDED) && usage.getMax() == usage.getCommitted())
                listeners.forEach(listener -> listener.memoryUsageLow(usage.getUsed(), usage.getMax()));
        }, null, null);
    }

    public boolean addListener(Listener listener) {
        return listeners.add(listener);
    }

    public boolean removeListener(Listener listener) {
        return listeners.remove(listener);
    }
}


问:
How to check whether data or object already exist in PList, iPhone?
I can add and remove an object or data in PList successfully but I wanna know that the data or an object already exist in PList. my code is

```<code>NSUInteger countObjectsFromPList;
countObjectsFromPList = [[mdict allKeys] count];
NSLog(@"objects in PList %d", countObjectsFromPList);
for(int i=0; i <= countLawsFromPList; i++){
NSLog(@"\n\n\n%d\n\n\n", i);
//if([objectName isEqualToString:[[mdict allKeys] objectAtIndex:i]])
if(objectName ==[[mdict allKeys] objectAtIndex:i]){
NSLog(@"Already exists");
//NSLog("String is equal");
}
else {
NSLog(@"Added to Favorites");
}
}
</code>```

Please any one help me to over come this. thanks

答:
```<code>id object = [mdict objectForKey:key];
BOOL exists = (object != nil);
</code>```

Edit: apparently that wasn't clear enough.
Basically with objectForKey you're just telling the dictionary "could you please give me the object for my key key"? If the object is there for that key, the returning value will be non-nil. Otherwise it will be nil. That's why you check for object != nil in order to know if that object exists in the dictionary for your key. goes to take more coffee

ContentLicense: CC BY-SA 3.0

Body:
I can add and remove an object or data in PList successfully but I wanna know that the data or an object already exist in PList. my code is

NSUInteger countObjectsFromPList;
countObjectsFromPList = [[mdict allKeys] count];
NSLog(@"objects in PList %d", countObjectsFromPList);
for(int i=0; i <= countLawsFromPList; i++){
NSLog(@"\n\n\n%d\n\n\n", i);
//if([objectName isEqualToString:[[mdict allKeys] objectAtIndex:i]])
if(objectName ==[[mdict allKeys] objectAtIndex:i]){
NSLog(@"Already exists");
//NSLog("String is equal");
}
else {
NSLog(@"Added to Favorites");
}
}

Please any one help me to over come this. thanks

Body:
id object = [mdict objectForKey:key];
BOOL exists = (object != nil);

Edit: apparently that wasn't clear enough.
Basically with objectForKey you're just telling the dictionary "could you please give me the object for my key key"? If the object is there for that key, the returning value will be non-nil. Otherwise it will be nil. That's why you check for object != nil in order to know if that object exists in the dictionary for your key. goes to take more coffee


问:
C# set button.BackColor = System.Drawing.Color.Blue where the Button has the AccessibleDescription "1"
Basically, i have a Matrix of Buttons where i want to play Battleships. If you click on a Button, the 2 Buttons under the clicked Button should go blue. I set the AccessibleDescription from 1-100 for each button in the matrix from left to right. So i want to talk the the Button under the clicked Button/Search for a Button with a specific AccessibleDescription.</p>

答:
Group the buttons into panels and then call:

```<code>foreach (Control c in panel.Controls)
{
   if (c is Button) ((Button)c).BackColor = Color.Blue;
}
</code>```

This will return a collection of controls contained within the panel, so you can get them.

Body:
Group the buttons into panels and then call:

foreach (Control c in panel.Controls)
{
   if (c is Button) ((Button)c).BackColor = Color.Blue;
}

This will return a collection of controls contained within the panel, so you can get them.


问:
Swipe slide and move imageView position
in my code some time it increases a lot and some time let the image position increase and decrease.</p>

```<code>IBOutlet weak var bgImage: UIImageView!
IBOutlet weak var sliders: UISlider!
IBOutlet weak var imgViews: UIImageView!
var location = CGPoint(x: 0, y: 0)
var valueOFButterFly = 54.5
var lastValueOfSlider = Float()

@IBAction func sliderValue(_ sender: UISlider) {
    print(sender.value)

    if lastValueOfSlider >= sender.value {

        valueOFButterFly = valueOFButterFly - 1
         print("new value \(valueOFButterFly)")
        imgViews.center = CGPoint(x: valueOFButterFly, y: 81.5)

    }
    else if (lastValueOfSlider < sender.value) {

        valueOFButterFly = valueOFButterFly + 1
        print("new value \(valueOFButterFly)")
        imgViews.center = CGPoint(x: valueOFButterFly, y: 81.5)

    }
    else {
        print("else if")
    }
    self.lastValueOfSlider = sender.value
}
</code>```

答:
In case you want to match the imageView's centre with that of the slider value, you need to set the slider's currentValue as imageView's centre instead of incrementing or decrementing by 1.

Also, update the imageView.center in valueOFButterFly's didSet property observer instead of updating it multiple times throughout the code.

```<code>class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var slider: UISlider!

    var lastValueOfSlider = Float()

    var valueOFButterFly = 54.5 {
        didSet {
            imageView.center = CGPoint(x: self.valueOFButterFly, y: 81.5)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        slider.minimumValue = 0
        slider.maximumValue = Float(UIScreen.main.bounds.width)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        imageView.center = CGPoint(x: self.valueOFButterFly, y: 81.5)
    }

    @IBAction func sliderValue(_ sender: UISlider) {
        print(sender.value)
        valueOFButterFly = Double(sender.value)
        self.lastValueOfSlider = sender.value
    }
}
</code>```

In the above code, I've used

slider.minimumValue = 0

slider.maximumValue = Float(UIScreen.main.bounds.width)

You can configure the above properties as per your requirement.

Title: Swipe slide and move imageView position

Body:
in my code some time it increases a lot and some time let the image position increase and decrease.

IBOutlet weak var bgImage: UIImageView!
IBOutlet weak var sliders: UISlider!
IBOutlet weak var imgViews: UIImageView!
var location = CGPoint(x: 0, y: 0)
var valueOFButterFly = 54.5
var lastValueOfSlider = Float()

@IBAction func sliderValue(_ sender: UISlider) {
    print(sender.value)

    if lastValueOfSlider >= sender.value {

        valueOFButterFly = valueOFButterFly - 1
         print("new value \(valueOFButterFly)")
        imgViews.center = CGPoint(x: valueOFButterFly, y: 81.5)

    }
    else if (lastValueOfSlider < sender.value) {

        valueOFButterFly = valueOFButterFly + 1
        print("new value \(valueOFButterFly)")
        imgViews.center = CGPoint(x: valueOFButterFly, y: 81.5)

    }
    else {
        print("else if")
    }
    self.lastValueOfSlider = sender.value
}

Body:
In case you want to match the imageView's centre with that of the slider value, you need to set the slider's currentValue as imageView's centre instead of incrementing or decrementing by 1.

Also, update the imageView.center in valueOFButterFly's didSet property observer instead of updating it multiple times throughout the code.

class ViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var slider: UISlider!

    var lastValueOfSlider = Float()

    var valueOFButterFly = 54.5 {
        didSet {
            imageView.center = CGPoint(x: self.valueOFButterFly, y: 81.5)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        slider.minimumValue = 0
        slider.maximumValue = Float(UIScreen.main.bounds.width)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        imageView.center = CGPoint(x: self.valueOFButterFly, y: 81.5)
    }

    @IBAction func sliderValue(_ sender: UISlider) {
        print(sender.value)
        valueOFButterFly = Double(sender.value)
        self.lastValueOfSlider = sender.value
    }
}

In the above code, I've used

slider.minimumValue = 0

slider.maximumValue = Float(UIScreen.main.bounds.width)

You can configure the above properties as per your requirement.


问:
How to understand this rx-swift map function
I have some textfileds in my viewcontroller. And use rx-swift to observer the .editingDidBegin event.

I want to judge which textfield sends event.

```<code>let tags = txtFieldArray.map{($0.rx.controlEvent(.editingDidBegin), $0.tag)}
            .map{obs, tag in obs.map{tag}}
let value = Observable.merge(tags)
        value.bind {[weak self] (tags) in
            guard let strongSelf = self else { return }
            if let view = strongSelf.ipEnteryView.viewWithTag(tags) as? UITextField {
                strongSelf.viewMode.changeTextFiledBottomColor(view, true)
            }
            }.disposed(by: disposedBag)
</code>```

The txtFieldArray's first map return a array, element is tuples(as my understand),first is controlEvent, second is a int value. What i don't understand is the second map function. Obs is contrlEvent type. Why obs.map{tag} return a observable. And how to understand map{obs, tag in obs.map{tag}}?
Thank you very much!

答:
obs.map { tag } returns an Observable because the signature of the function is:

ObservableType.map<Result>(_ transform: @escaping (Self.Element) throws -> Result) -> RxSwift.Observable<Result>

Since map returns an Observable, ops.map { tag } returns an Observable.

.map{obs, tag in obs.map{tag}} takes an Array of (ControlEvent<()>, Int), goes through each element converts it into an Observable<Int>.

map is just a function that transforms the subtype of the functor it is called on. So the first map transforms an Array of X into Array of Y and the second map transforms an ObservableType of X into an Observable of Y.

Body:
I have some textfileds in my viewcontroller. And use rx-swift to observer the .editingDidBegin event.

I want to judge which textfield sends event.

let tags = txtFieldArray.map{($0.rx.controlEvent(.editingDidBegin), $0.tag)}
            .map{obs, tag in obs.map{tag}}
let value = Observable.merge(tags)
        value.bind {[weak self] (tags) in
            guard let strongSelf = self else { return }
            if let view = strongSelf.ipEnteryView.viewWithTag(tags) as? UITextField {
                strongSelf.viewMode.changeTextFiledBottomColor(view, true)
            }
            }.disposed(by: disposedBag)

The txtFieldArray's first map return a array, element is tuples(as my understand),first is controlEvent, second is a int value. What i don't understand is the second map function. Obs is contrlEvent type. Why obs.map{tag} return a observable. And how to understand map{obs, tag in obs.map{tag}}?
Thank you very much!


问:
Building of Docker image from Dockerfile making error "docker build" requires exactly 1 argument"
I am trying to build Docker image by using Jenkins pipeline script. When I am running the following code,

```<code>docker build -f Dockerfile -t spacestudykubernetes /var/lib/jenkins/workspace/cicd/pipeline
</code>```

I added this command in inside Jenkins pipeline job shell script. There "cd" command will not work. Change directory not working in shell script. Because of that without changing directly, I gave the command with full path. According to your command it will work (after putting change directory) . I am trying to execute from cicd folder, not from pipeline folder. Dockerfile is resides in pipeline folder.

My Jenkins pipeline script

```<code>pipeline
{
    agent any
    stages
        {
            stage ('imagebuild')
                {
                    steps
                        {

sh 'docker build -f Dockerfile -t spacestudykubernetes /var/lib/jenkins/workspace/cicd/pipeline'

                        }
                }
        }
}
</code>```

Error

I am getting the error like the following,

```<code>unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /var/lib/jenkins/workspace/cicd/Dockerfile: no such file or directory
</code>```

I am not running from direct folder where Dockerfile is resides. My Dockerfile is resides in pipeline folder. That is my code checked out from SVN. And I am trying to run this command from cicd folder. And I gave the full path with -f argument.

答:
You miss context directory at the end of command line. Usually it is simply .. This directory will serve as root for all paths in Dockerfile whenever you use ADD/COPY and also as a build context - meaning its content will be zipped and passed to docker daemon when build is executed.

```<code>cd /var/lib/jenkins/workspace/cicd/pipeline
docker build -f Dockerfile -t spacestudykubernetes .
</code>```

Body:
I am trying to build Docker image by using Jenkins pipeline script. When I am running the following code,

docker build -f Dockerfile -t spacestudykubernetes /var/lib/jenkins/workspace/cicd/pipeline

I added this command in inside Jenkins pipeline job shell script. There "cd" command will not work. Change directory not working in shell script. Because of that without changing directly, I gave the command with full path. According to your command it will work (after putting change directory) . I am trying to execute from cicd folder, not from pipeline folder. Dockerfile is resides in pipeline folder.

My Jenkins pipeline script

pipeline
{
    agent any
    stages
        {
            stage ('imagebuild')
                {
                    steps
                        {

sh 'docker build -f Dockerfile -t spacestudykubernetes /var/lib/jenkins/workspace/cicd/pipeline'

                        }
                }
        }
}

Error

I am getting the error like the following,

unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /var/lib/jenkins/workspace/cicd/Dockerfile: no such file or directory

I am not running from direct folder where Dockerfile is resides. My Dockerfile is resides in pipeline folder. That is my code checked out from SVN. And I am trying to run this command from cicd folder. And I gave the full path with -f argument.

Body:
You miss context directory at the end of command line. Usually it is simply .. This directory will serve as root for all paths in Dockerfile whenever you use ADD/COPY and also as a build context - meaning its content will be zipped and passed to docker daemon when build is executed.

cd /var/lib/jenkins/workspace/cicd/pipeline
docker build -f Dockerfile -t spacestudykubernetes .


问:
Redimensioning array of ranges into a single array containing only the values of each range element
I have multiple worksheets with ranges which I collect into an array of ranges, and I cant do Union since it does not work across worksheets.
Since I want to create a chart where the time-series or FullSeriesCollection are based on the elements of my combined ranges, I thought that redimensioning the array of ranges into a single array might serve as my solution.
Perhaps there is an easier solution that I am not seeing.

I tried to outline the general case below. The ranges are dynamic in my code, but here I just set them arbitrarily.

```<code>Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            ReDim Preserve arrDate(j)
            arrDate(j) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub
</code>```

When I use this code I get an array with 22 elements corresponding to the range of rng_3. What I want to end up with after the nested loop is an array that contains the elements from all ranges in 1 single array with 1 dimension.

The reason I want this in the end is I want to create chart using the array values.

答:
This should work for you:</p>

```<code>Option Explicit
Sub Collection()

    Dim arrDate As Variant
    Dim ws_1 As Worksheet, ws_2 As Worksheet
    Dim LastRow As Long, j As Long

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    Set ws_1 = ThisWorkbook.Sheets(1)
    Set ws_2 = ThisWorkbook.Sheets(2)

    With ThisWorkbook
        .Sheets.Add After:=.Sheets(.Sheets.Count)
    End With
    With ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
        .Range("A1").Resize(ws_1.Range("A2:A10").Rows) = ws_1.Range("A2:A10").Value
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
        .Range("A" & LastRow).Resize(ws_1.Range("A11:A22").Rows) = ws_1.Range("A11:A22").Value
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
        .Range("A" & LastRow).Resize(ws_2.Range("A2:A22").Rows) = ws_2.Range("A2:A22").Value
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        j = 1
        ReDim arrDate(1 To LastRow)
        For Each C In .Range("A1:A" & LastRow)
            arrDate(j) = C
        Next C
        .Delete
    End With

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With

End Sub
</code>```

Body:
I have multiple worksheets with ranges which I collect into an array of ranges, and I cant do Union since it does not work across worksheets.
Since I want to create a chart where the time-series or FullSeriesCollection are based on the elements of my combined ranges, I thought that redimensioning the array of ranges into a single array might serve as my solution.
Perhaps there is an easier solution that I am not seeing.

I tried to outline the general case below. The ranges are dynamic in my code, but here I just set them arbitrarily.

Sub Collection()

Dim arrDate() As Variant
Dim arrRngTotal As Variant
Dim rng_1 As Range, rng_2 As Range, rng_3 As Range
Dim ws_1 As Worksheet, ws_2 As Worksheet
Dim j As Integer, k As Integer

Set ws_1 = ThisWorkbook.Sheets(1)
Set ws_2 = ThisWorkbook.Sheets(2)
' Example of ranges, not static in the original code.
Set rng_1 = ws_1.Range("A2:A10")
Set rng_2 = ws_1.Range("A11:A22")
Set rng_3 = ws_2.Range("A2:A22")

arrRngTotal = Array(rng_1.Value, rng_2.Value, rng_3.Value)

For k = LBound(arrRngTotal, 1) To UBound(arrRngTotal, 1)
    For j = LBound(arrRngTotal(k), 1) To UBound(arrRngTotal(k), 1)
            ReDim Preserve arrDate(j)
            arrDate(j) = arrRngTotal(k)(j, 1)
    Next j
Next k

End Sub

When I use this code I get an array with 22 elements corresponding to the range of rng_3. What I want to end up with after the nested loop is an array that contains the elements from all ranges in 1 single array with 1 dimension.

The reason I want this in the end is I want to create chart using the array values.

Body:
This should work for you:

Option Explicit
Sub Collection()

    Dim arrDate As Variant
    Dim ws_1 As Worksheet, ws_2 As Worksheet
    Dim LastRow As Long, j As Long

    With Application
        .ScreenUpdating = False
        .DisplayAlerts = False
    End With

    Set ws_1 = ThisWorkbook.Sheets(1)
    Set ws_2 = ThisWorkbook.Sheets(2)

    With ThisWorkbook
        .Sheets.Add After:=.Sheets(.Sheets.Count)
    End With
    With ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
        .Range("A1").Resize(ws_1.Range("A2:A10").Rows) = ws_1.Range("A2:A10").Value
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
        .Range("A" & LastRow).Resize(ws_1.Range("A11:A22").Rows) = ws_1.Range("A11:A22").Value
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
        .Range("A" & LastRow).Resize(ws_2.Range("A2:A22").Rows) = ws_2.Range("A2:A22").Value
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
        j = 1
        ReDim arrDate(1 To LastRow)
        For Each C In .Range("A1:A" & LastRow)
            arrDate(j) = C
        Next C
        .Delete
    End With

    With Application
        .ScreenUpdating = True
        .DisplayAlerts = True
    End With

End Sub


问:
Hibernate @id composite
I am modeling a database.

There is TRIPLE which contains three CONCEPT. So the primary key of the class TRIPLE is three uri all together.  (One concept could be in different TRIPLE).

Also TRIPLE is related with another class, ANNOTATION, and here is the question, how can triple_id be identified?? But first of all, if building this Id composite is correct.
To model that:

Concept.java

```<code>@Entity
@Table(name = "concept")
public class Concept implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private String id;
    private List<TripleDBModel> triples;
@ManyToMany(
            cascade={CascadeType.ALL},
            fetch=FetchType.LAZY,
            mappedBy = "concepts"
    )
    public List<TripleDBModel> getTriples() {
        return triples;
    }

    public void setTriples(List<TripleDBModel> triples) {
        this.triples = triples;
    }
</code>```

ConceptPk.java

```<code>@Embeddable
public class ConceptPk implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private String uri;

    public ConceptPk(String uri, String label){
        this.uri = uri;
    }

    public ConceptPk(){
        super();
    }

    @Id
    @Column(name = "uri", length = 100, unique = true, nullable = false)
    public String getUri() {
        return uri;
    }
    public void setUri(String uri) {
        this.uri = uri;
    }
}
</code>```

Triple.java

```<code>@Entity
@IdClass(ConceptPk.class)
@Table(name = "triple")
public class TripleDBModel {

    protected List<Annotation> annotations;
    protected String conceptUriSubject;
    protected String conceptUriObject;
    protected String conceptUriPredicate;

    @ManyToMany(
            cascade={CascadeType.ALL},
            fetch=FetchType.LAZY
    )
    @JoinTable(name = "triple_has_concept",
            joinColumns=@JoinColumn(name="uri"),
            inverseJoinColumns=@JoinColumn(name="triple_id")) //What shoul I write here???
    public List<Annotation> getAnnotations() {
        return annotations;
    }
    public void setAnnotations(List<Annotation> annotations) {
        this.annotations = annotations;
    }
    @Id public String getConceptUriSubject() {
        return conceptUriSubject;
    }
    public void setConceptUriSubject(String conceptUriSubject) {
        this.conceptUriSubject = conceptUriSubject;
    }
    @Id public String getConceptUriObject() {
        return conceptUriObject;
    }
    public void setConceptUriObject(String conceptUriObject) {
        this.conceptUriObject = conceptUriObject;
    }
    @Id public String getConceptUriPredicate() {
        return conceptUriPredicate;
    }
    public void setConceptUriPredicate(String conceptUriPredicate) {
        this.conceptUriPredicate = conceptUriPredicate;
    }
}
</code>```

Thanks in advance!!

答:
You could use an Id class like this:

```<code>class TripleId implements Serializable {
  @Column(...)
  private String conceptUriSubject;

  @Column(...)
  private String conceptUriObject;
}
</code>```

And use it in Triple:

```<code>@Entity
@Table(name = "triple")
public class TripleDBModel {

  @EmbeddedId
  private TripleId id;
  ...
}
</code>```

Also note that you can provide multiple join columns:
inverseJoinColumns= {@JoinColumn(name="subjectUri"), @JoinColumn(name="objectUri"),  ... }

Title: Hibernate @id composite

Body:
I am modeling a database.

There is TRIPLE which contains three CONCEPT. So the primary key of the class TRIPLE is three uri all together.  (One concept could be in different TRIPLE).

Also TRIPLE is related with another class, ANNOTATION, and here is the question, how can triple_id be identified?? But first of all, if building this Id composite is correct.
To model that:

Concept.java

@Entity
@Table(name = "concept")
public class Concept implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private String id;
    private List<TripleDBModel> triples;
@ManyToMany(
            cascade={CascadeType.ALL},
            fetch=FetchType.LAZY,
            mappedBy = "concepts"
    )
    public List<TripleDBModel> getTriples() {
        return triples;
    }

    public void setTriples(List<TripleDBModel> triples) {
        this.triples = triples;
    }

ConceptPk.java

@Embeddable
public class ConceptPk implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private String uri;

    public ConceptPk(String uri, String label){
        this.uri = uri;
    }

    public ConceptPk(){
        super();
    }

    @Id
    @Column(name = "uri", length = 100, unique = true, nullable = false)
    public String getUri() {
        return uri;
    }
    public void setUri(String uri) {
        this.uri = uri;
    }
}

Triple.java

@Entity
@IdClass(ConceptPk.class)
@Table(name = "triple")
public class TripleDBModel {

    protected List<Annotation> annotations;
    protected String conceptUriSubject;
    protected String conceptUriObject;
    protected String conceptUriPredicate;

    @ManyToMany(
            cascade={CascadeType.ALL},
            fetch=FetchType.LAZY
    )
    @JoinTable(name = "triple_has_concept",
            joinColumns=@JoinColumn(name="uri"),
            inverseJoinColumns=@JoinColumn(name="triple_id")) //What shoul I write here???
    public List<Annotation> getAnnotations() {
        return annotations;
    }
    public void setAnnotations(List<Annotation> annotations) {
        this.annotations = annotations;
    }
    @Id public String getConceptUriSubject() {
        return conceptUriSubject;
    }
    public void setConceptUriSubject(String conceptUriSubject) {
        this.conceptUriSubject = conceptUriSubject;
    }
    @Id public String getConceptUriObject() {
        return conceptUriObject;
    }
    public void setConceptUriObject(String conceptUriObject) {
        this.conceptUriObject = conceptUriObject;
    }
    @Id public String getConceptUriPredicate() {
        return conceptUriPredicate;
    }
    public void setConceptUriPredicate(String conceptUriPredicate) {
        this.conceptUriPredicate = conceptUriPredicate;
    }
}

Thanks in advance!!

Body:
You could use an Id class like this:

class TripleId implements Serializable {
  @Column(...)
  private String conceptUriSubject;

  @Column(...)
  private String conceptUriObject;
}

And use it in Triple:

@Entity
@Table(name = "triple")
public class TripleDBModel {

  @EmbeddedId
  private TripleId id;
  ...
}

Also note that you can provide multiple join columns:
inverseJoinColumns= {@JoinColumn(name="subjectUri"), @JoinColumn(name="objectUri"),  ... }


问:
Bookmarking in pdf generated using velocity template
I have huge data, the data will be used to generate PDF using velocity template. I have index page generated using .vm file which is a table. I should provide bookmarking from index page to other pages which is intended to.

I tried using just href in HTML.

index.vm:

```<code><table>
<tr>
<td>
1
</td>
<td>
<a href="#go">chapter1</a>
<td>
</tr>
</table>
</code>```

assembly.vm:

```<code><table>
<tr>
<p1 id="go">assembly1</p>
</tr>
</table>
</code>```

It's expected to have link in index page and on click on it, go to that respective content page.

答:
I have faced the same problem to generate PDFs from templates but I was using JSP. It is the same logic for every template engine.

To achieve it make a request on your own server to fetch the generated content from template in HTML and convert it to PDF with flying-saucer.

So basically you'll have

A servlet returning your generated Velocity template according to parameters

(i.e. : http://127.0.0.1/getgeneratedpdf)

```<code>    dopost etc. ...
</code>```

Another servlet calling this first servlet with needed parameters to fetch generated content in HTML

```<code>   URLConnection connection = new URL(urlOfTheServletAbove).openConnection();
   connection.setDoOutput(true); // POST
   connection.setRequestProperty("Accept-Charset", "UTF-8");
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
   try (OutputStream output = connection.getOutputStream()) {
       // parameters is encoded query string
       output.write(parameters.getBytes(StandardCharsets.UTF_8));
   }
   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String inputLine;
   while ((inputLine = in.readLine()) != null) { sb.append(inputLine); }
   in.close();
</code>```

A PDF builder based on flying-saucer

```<code>import org.xhtmlrenderer.pdf.ITextRenderer;
// ...
private static final String TMP_DIR = System.getProperty("java.io.tmpdir");
// ...
File tempPdf = new File(TMP_DIR+tempPdfName);
if (!tempPdf.exists()) { tempPdf.createNewFile(); }
FileOutputStream fos = new FileOutputStream(tempPdf);
new ITextRenderer() {{
    setDocumentFromString(sb.toString());
    layout();
    createPDF(fos);
}};
fos.close();
// ...
</code>```

Then write PDF into response

```<code>void writePDFContentToResponse(File pdf, HttpServletResponse response) throws IOException {
    InputStream fis = new FileInputStream(pdf);
    String mimeType = getServlet().getServletContext().getMimeType(pdf.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) pdf.length());
    response.setHeader("Content-Disposition", "attachment; filename=yourPDFName.pdf"); // or +pdf.getName();
    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); }
    os.flush();
    os.close();
    fis.close();
    response.flushBuffer();
    Files.delete(pdf.toPath());
}
</code>```

Body:
I have huge data, the data will be used to generate PDF using velocity template. I have index page generated using .vm file which is a table. I should provide bookmarking from index page to other pages which is intended to.

I tried using just href in HTML.

index.vm:

1

chapter1

assembly.vm:

<p1 id="go">assembly1

It's expected to have link in index page and on click on it, go to that respective content page.

Body:
I have faced the same problem to generate PDFs from templates but I was using JSP. It is the same logic for every template engine.

To achieve it make a request on your own server to fetch the generated content from template in HTML and convert it to PDF with flying-saucer.

So basically you'll have

A servlet returning your generated Velocity template according to parameters

(i.e. : http://127.0.0.1/getgeneratedpdf)

    dopost etc. ...

Another servlet calling this first servlet with needed parameters to fetch generated content in HTML

   URLConnection connection = new URL(urlOfTheServletAbove).openConnection();
   connection.setDoOutput(true); // POST
   connection.setRequestProperty("Accept-Charset", "UTF-8");
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
   try (OutputStream output = connection.getOutputStream()) {
       // parameters is encoded query string
       output.write(parameters.getBytes(StandardCharsets.UTF_8));
   }
   BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
   StringBuilder sb = new StringBuilder();
   String inputLine;
   while ((inputLine = in.readLine()) != null) { sb.append(inputLine); }
   in.close();

A PDF builder based on flying-saucer

import org.xhtmlrenderer.pdf.ITextRenderer;
// ...
private static final String TMP_DIR = System.getProperty("java.io.tmpdir");
// ...
File tempPdf = new File(TMP_DIR+tempPdfName);
if (!tempPdf.exists()) { tempPdf.createNewFile(); }
FileOutputStream fos = new FileOutputStream(tempPdf);
new ITextRenderer() {{
    setDocumentFromString(sb.toString());
    layout();
    createPDF(fos);
}};
fos.close();
// ...

Then write PDF into response

void writePDFContentToResponse(File pdf, HttpServletResponse response) throws IOException {
    InputStream fis = new FileInputStream(pdf);
    String mimeType = getServlet().getServletContext().getMimeType(pdf.getAbsolutePath());
    response.setContentType(mimeType != null ? mimeType : "application/octet-stream");
    response.setContentLength((int) pdf.length());
    response.setHeader("Content-Disposition", "attachment; filename=yourPDFName.pdf"); // or +pdf.getName();
    ServletOutputStream os = response.getOutputStream();
    byte[] bufferData = new byte[1024];
    int read = 0;
    while((read = fis.read(bufferData)) != -1) { os.write(bufferData, 0, read); }
    os.flush();
    os.close();
    fis.close();
    response.flushBuffer();
    Files.delete(pdf.toPath());
}


问:
Accessing website on old server with cPanel
We have a new website and it'll be using new server. We'd like the domain to point to new server but also want to keep the old website running and access it for internal purpose.

I tried oldserveripaddress/~ftpusername but this did not work.

How do we go about this? Both old and new servers are cPanel.

Thanks.

答:
Assuming that the old web server is still answering to the domain name.

set up a entry in your host file (on your pc) to point your website at the old IP address
xxx.xxx.xxx.xxx www.yourwebsite.com

then you should be able to access the old site, just comment it out after when you want to access the new one.


问:
how to use item decoration in a recyclerview within a dialog with rounded corners and transparent background
I am using a dialog and in this dialog I am using a recyclerview and I am also setting a custom background drawable with rounded corners for that dialog.
the problem is whenever I try to set an item decoration for the recyclerview it shows some weird lines in bottom cut corners of dialog like here 1 and here 2
 I think that's because I set the dialog background to be transparent.
I want to know how to remove these lines

The item decoration

public ItemDecoration(Context context) {

        mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i <= childCount-2; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }
```

<p>the background for dialog </p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
    <corners android:radius="@dimen/viewsRadius"></corners>
</shape>
</code>```

Layout for dialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_corners_dialog_back"
    >

    <TextView
        android:id="@+id/dialogNameTxt"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:tag="bold"
        android:text=""
        android:textColor="@color/black"
        android:textSize="@dimen/textSize"
        android:textStyle="" />

    <TextView
        android:id="@+id/closeBtn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:tag="icon"
        android:gravity="center"
        android:background="@drawable/yellow_circle"
        android:textColor="@color/white"
        android:textSize="@dimen/textSize"
        android:text="@string/closeIcon" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/dialogList"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/closeBtn"
        android:tag="bold" />

    <Button
        android:id="@+id/addBtn"
        android:layout_width="match_parent"
        android:layout_height="@dimen/viewsHeight"
        android:text="@string/add"
        android:tag="bold"
        android:layout_margin="10dp"
        android:textColor="@color/white"
        android:textAllCaps="false"
        android:background="@drawable/rounded_yellow_button"
        android:layout_below="@id/dialogList"
        />

  <android.support.constraint.ConstraintLayout
      android:visibility="gone"
      android:id="@+id/commentView"
      android:layout_width="match_parent"
      android:layout_below="@id/dialogList"
     android:layout_margin="10dp"
      android:layout_height="wrap_content">

      <EditText
          android:id="@+id/messageEditTxt"
          android:layout_width="0dp"
          android:layout_height="@dimen/viewsHeight"
          android:background="@drawable/edit_text_back"
          android:ems="10"
          android:hint="@string/write_a_comment"
          android:inputType="textPersonName"
          android:paddingStart="10dp"
          android:paddingEnd="10dp"
          android:layout_marginEnd="10dp"
          android:tag="regularFont"
          android:textColor="@color/black"
          android:textCursorDrawable="@null"
          app:layout_constraintEnd_toStartOf="@+id/sendBtn"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintBottom_toBottomOf="parent" />

      <TextView
          android:id="@+id/sendBtn"
          android:layout_width="@dimen/circleButtonDimension"
          android:layout_height="@dimen/circleButtonDimension"
          android:background="@drawable/yellow_circle"
          android:gravity="center"
          android:padding="@dimen/iconTextPadding"
          android:tag="icon"
          android:text="@string/sendIcon"
          android:textColor="@color/white"
          android:textSize="@dimen/iconTextSize"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintEnd_toEndOf="parent"/>

  </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/dialogNameTxt"
        android:id="@+id/cancelDialogView"
        android:visibility="gone">

        <TextView
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="10dp"
            android:tag="regularFont"
            android:text="@string/confirm_cancel"
            android:textColor="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            app:layout_constraintBottom_toTopOf="@id/yesBtn"/>

        <Button
            android:id="@+id/yesBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/yes"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/guideline4"
            app:layout_constraintStart_toStartOf="parent" />

        <Button
            android:id="@+id/noBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/no"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/guideline4" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/errorIcon"
            android:textSize="60sp"
            android:textColor="@color/red"
            android:tag="icon"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

</RelativeLayout>
```

<p>and here I set the background transparent for dialog in order to show my background</p>

<pre class="lang-java prettyprint-override"><code>getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
</code>```

答:
Use this

Solution 1

```<code> recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                    DividerItemDecoration.VERTICAL));
</code>```

Solution 2

Declare a view like this in bottom of your item layout by setting layout gravity or below the text

```<code>    <View
         android:layout_width="match_parent"
         android:layout_height="1dp"
         android:background="@color/grey"></View>
</code>```

Body:
I am using a dialog and in this dialog I am using a recyclerview and I am also setting a custom background drawable with rounded corners for that dialog.
the problem is whenever I try to set an item decoration for the recyclerview it shows some weird lines in bottom cut corners of dialog like here 1 and here 2
 I think that's because I set the dialog background to be transparent.
I want to know how to remove these lines

The item decoration

public ItemDecoration(Context context) {

        mDivider = context.getResources().getDrawable(R.drawable.recycler_horizontal_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        int left = parent.getPaddingLeft();
        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();
        for (int i = 0; i <= childCount-2; i++) {
            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;
            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

the background for dialog

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/white"></solid>
    <corners android:radius="@dimen/viewsRadius"></corners>
</shape>

Layout for dialog

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/rounded_corners_dialog_back"
    >

    <TextView
        android:id="@+id/dialogNameTxt"
        android:layout_width="wrap_content"
        android:layout_height="30dp"
        android:layout_alignParentStart="true"
        android:layout_marginStart="10dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:tag="bold"
        android:text=""
        android:textColor="@color/black"
        android:textSize="@dimen/textSize"
        android:textStyle="" />

    <TextView
        android:id="@+id/closeBtn"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:tag="icon"
        android:gravity="center"
        android:background="@drawable/yellow_circle"
        android:textColor="@color/white"
        android:textSize="@dimen/textSize"
        android:text="@string/closeIcon" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/dialogList"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_below="@id/closeBtn"
        android:tag="bold" />

    <Button
        android:id="@+id/addBtn"
        android:layout_width="match_parent"
        android:layout_height="@dimen/viewsHeight"
        android:text="@string/add"
        android:tag="bold"
        android:layout_margin="10dp"
        android:textColor="@color/white"
        android:textAllCaps="false"
        android:background="@drawable/rounded_yellow_button"
        android:layout_below="@id/dialogList"
        />

  <android.support.constraint.ConstraintLayout
      android:visibility="gone"
      android:id="@+id/commentView"
      android:layout_width="match_parent"
      android:layout_below="@id/dialogList"
     android:layout_margin="10dp"
      android:layout_height="wrap_content">

      <EditText
          android:id="@+id/messageEditTxt"
          android:layout_width="0dp"
          android:layout_height="@dimen/viewsHeight"
          android:background="@drawable/edit_text_back"
          android:ems="10"
          android:hint="@string/write_a_comment"
          android:inputType="textPersonName"
          android:paddingStart="10dp"
          android:paddingEnd="10dp"
          android:layout_marginEnd="10dp"
          android:tag="regularFont"
          android:textColor="@color/black"
          android:textCursorDrawable="@null"
          app:layout_constraintEnd_toStartOf="@+id/sendBtn"
          app:layout_constraintStart_toStartOf="parent"
          app:layout_constraintBottom_toBottomOf="parent" />

      <TextView
          android:id="@+id/sendBtn"
          android:layout_width="@dimen/circleButtonDimension"
          android:layout_height="@dimen/circleButtonDimension"
          android:background="@drawable/yellow_circle"
          android:gravity="center"
          android:padding="@dimen/iconTextPadding"
          android:tag="icon"
          android:text="@string/sendIcon"
          android:textColor="@color/white"
          android:textSize="@dimen/iconTextSize"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintEnd_toEndOf="parent"/>

  </android.support.constraint.ConstraintLayout>

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/dialogNameTxt"
        android:id="@+id/cancelDialogView"
        android:visibility="gone">

        <TextView
            android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="20dp"
            android:layout_marginTop="10dp"
            android:tag="regularFont"
            android:text="@string/confirm_cancel"
            android:textColor="@color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView3"
            app:layout_constraintBottom_toTopOf="@id/yesBtn"/>

        <Button
            android:id="@+id/yesBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/yes"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/guideline4"
            app:layout_constraintStart_toStartOf="parent" />

        <Button
            android:id="@+id/noBtn"
            android:layout_width="0dp"
            android:layout_height="@dimen/viewsHeight"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            android:layout_marginBottom="10dp"
            android:background="@drawable/rounded_yellow_button"
            android:text="@string/no"
            android:textAllCaps="false"
            android:textColor="@color/white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/guideline4" />

        <android.support.constraint.Guideline
            android:id="@+id/guideline4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.5" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/errorIcon"
            android:textSize="60sp"
            android:textColor="@color/red"
            android:tag="icon"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </android.support.constraint.ConstraintLayout>

</RelativeLayout>

and here I set the background transparent for dialog in order to show my background

getWindow().requestFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

Body:
Use this

Solution 1

 recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
                    DividerItemDecoration.VERTICAL));

Solution 2

Declare a view like this in bottom of your item layout by setting layout gravity or below the text

    <View
         android:layout_width="match_parent"
         android:layout_height="1dp"
         android:background="@color/grey"></View>


问:
How to Create button dynamically mvc using list and sql database column
I have code That work in create button dynamically in mvc. The problem is i have column call estates when we enter new estates ,it should create new button dyamically in the view page...

Here I done some of function it will create button using list.now i want to using sql column. When we enter new data in the sql column(Esates) it should create new button dyamically with the name what we entered in the sql column.

```<code>  List<Estates> estates = new List<Estates>
  {
    new Estates { Estate_ID = 1 , EstateName = "Annfiled"},
    new Estates { Estate_ID = 2 , EstateName = "Battalgalla"},
    new Estates { Estate_ID = 3 , EstateName = "Fordyce"},
   };
</code>```

This view Code

```<code>@foreach (var item in Model)
{
    <button type="submit" id="Estate_id_Button" class="Estates_button">@item.EstateName
    </button>
}
</code>```

答: Use foreach loop to loop through your data and create buttons.</p>

Body:
I have code That work in create button dynamically in mvc. The problem is i have column call estates when we enter new estates ,it should create new button dyamically in the view page...

Here I done some of function it will create button using list.now i want to using sql column. When we enter new data in the sql column(Esates) it should create new button dyamically with the name what we entered in the sql column.

  List<Estates> estates = new List<Estates>
  {
    new Estates { Estate_ID = 1 , EstateName = "Annfiled"},
    new Estates { Estate_ID = 2 , EstateName = "Battalgalla"},
    new Estates { Estate_ID = 3 , EstateName = "Fordyce"},
   };

This view Code

@foreach (var item in Model)
{
    <button type="submit" id="Estate_id_Button" class="Estates_button">@item.EstateName
    </button>
}


问:
Troueble to sending email in laravel
I'm trying to send mail with SendGrid, picking up the email that the user wants to send and the message, but I'm having this error when i try to submit:

Failed to authenticate on SMTP server with username "João Gabriel" using 2 possible authenticators. Authenticator LOGIN returned Swift_TransportException: Expected response code 250 but got an empty response in ...

My Mailable:

```<code>public $remetente;
public $nome;
public $destinatario;
public $data;

public function __construct($remetente, $nome, $destinatario, $data)
{
    $this->remetente = $remetente;
    $this->nome = $nome;
    $this->destinatario = $destinatario;
    $this->data = $data;

}

public function build()
{
    //$address = 'janeexampexample@example.com';
    $subject = 'This is a demo!';
    $name = 'Jane Doe';
    return $this->view('emails.test')
                ->from($this->remetente, $this->nome)
                ->subject($subject)
                ->replyTo($this->destinatario, $name);
}
</code>```

}

My Controller:

```<code>public function enviarEmail(Request $request){
    $destinatario = $request->input('destinatario');
    $mensagem = $request->input('mensagem');
    $remetente = \Auth::user()->email;
    $nome = \Auth::user()->name;

    Mail::to($destinatario)->send(new TestEmail($remetente, $nome, $destinatario, $mensagem));
}
</code>```

Can someone help me?

答:
Your error message indicates that there is something wrong with the authentication on the SMTP server. There seems to be nothing wrong with your code.

Maybe inspect the error message better, there might be a specific log message somewhere down the stacktrace maybe?

Have you verified your credentials to be correct? Have you verified host and port? Check your .env file and the config/mail.php to see if your settings are correct.

Title: Troueble to sending email in laravel

Body:
I'm trying to send mail with SendGrid, picking up the email that the user wants to send and the message, but I'm having this error when i try to submit:

Failed to authenticate on SMTP server with username "João Gabriel" using 2 possible authenticators. Authenticator LOGIN returned Swift_TransportException: Expected response code 250 but got an empty response in ...

My Mailable:

public $remetente;
public $nome;
public $destinatario;
public $data;

public function __construct($remetente, $nome, $destinatario, $data)
{
    $this->remetente = $remetente;
    $this->nome = $nome;
    $this->destinatario = $destinatario;
    $this->data = $data;

}

public function build()
{
    //$address = 'janeexampexample@example.com';
    $subject = 'This is a demo!';
    $name = 'Jane Doe';
    return $this->view('emails.test')
                ->from($this->remetente, $this->nome)
                ->subject($subject)
                ->replyTo($this->destinatario, $name);
}

}

My Controller:

public function enviarEmail(Request $request){
    $destinatario = $request->input('destinatario');
    $mensagem = $request->input('mensagem');
    $remetente = \Auth::user()->email;
    $nome = \Auth::user()->name;

    Mail::to($destinatario)->send(new TestEmail($remetente, $nome, $destinatario, $mensagem));
}

Can someone help me?


问:
TypeScript: Conditional generic types as function return values not assignable
I have a problem with assignable values in one of my generic functions:

```<code>interface BuildArguments<T extends string> {
    type: T;
}

type PromiseResult<T> =
    T extends 'standalone' ? Promise<void> :
    T extends 'all' ? Promise<void> :
    Promise<void[]>;

const foo: PromiseResult<'standalone'> = Promise.resolve();
const bar: PromiseResult<'all'> = Promise.resolve();
const baz: PromiseResult<'foo'> = Promise.resolve([]);

bundle({ type: 'foo' });

function bundle<T extends string>(buildArguments: BuildArguments<T>): PromiseResult<T> {
    switch (buildArguments.type) {
        case 'standalone':
            return Promise.resolve(); // error here, not assignable to PromiseResult<T>
        case 'all':
            return Promise.resolve(); // error here, not assignable to PromiseResult<T>
        default:
            return Promise.all([ // error here, not assignable to PromiseResult<T>
                Promise.resolve(),
                Promise.resolve()
            ]);
    }
}
</code>```

The consts foo, bar and baz show that the conditional type works fine. the function call bundle({ type: 'foo' }) also correctly provides the type Promise<void[]> if you use the ts playground and hover over it. Why doesn't it work for the return values?
I also tried if this is caused by TypeScript not being able to infer T by adding a kind: T argument to the function, but no changes. Asserting Promise.resolve() to PromiseResult<T> works fine.

答:
Typescript will generally not let you do much with conditional types as long as they still have unresolved conditional types (as is T in case in PromiseResult<T>)

Moreover in this case you assume that narrowing buildArguments.type narrows T. It does not. Narrowing narrows a value, not a whole type parameter. This is can be no other way, consider this example:

```<code>function foo<T extends string | number>(a: T, b: T) {
    if(typeof a === "string") {
        // should b be string? No
    }
}

foo<string | number>(1, "");
</code>```

Just because we narrowed one value that is of a type T has no bearing on other such variables.

The simplest solution is to use a separate implementation signature that is more permissive, while keeping the public signature with conditional types that is better for the caller:

```<code>function bundle<T extends string>(buildArguments: BuildArguments<T>): PromiseResult<T>
function bundle(buildArguments: BuildArguments<string>): PromiseResult<'standalone' | 'all'> | PromiseResult<string> {
    switch (buildArguments.type) {
        case 'standalone':
            return Promise.resolve();
        case 'all':
            return Promise.resolve();
        default:
            return Promise.all([
                Promise.resolve(),
                Promise.resolve()
            ]);
    }
}
</code>```

Body:
I have a problem with assignable values in one of my generic functions:

interface BuildArguments<T extends string> {
    type: T;
}

type PromiseResult<T> =
    T extends 'standalone' ? Promise<void> :
    T extends 'all' ? Promise<void> :
    Promise<void[]>;

const foo: PromiseResult<'standalone'> = Promise.resolve();
const bar: PromiseResult<'all'> = Promise.resolve();
const baz: PromiseResult<'foo'> = Promise.resolve([]);

bundle({ type: 'foo' });

function bundle<T extends string>(buildArguments: BuildArguments<T>): PromiseResult<T> {
    switch (buildArguments.type) {
        case 'standalone':
            return Promise.resolve(); // error here, not assignable to PromiseResult<T>
        case 'all':
            return Promise.resolve(); // error here, not assignable to PromiseResult<T>
        default:
            return Promise.all([ // error here, not assignable to PromiseResult<T>
                Promise.resolve(),
                Promise.resolve()
            ]);
    }
}

The consts foo, bar and baz show that the conditional type works fine. the function call bundle({ type: 'foo' }) also correctly provides the type Promise<void[]> if you use the ts playground and hover over it. Why doesn't it work for the return values?
I also tried if this is caused by TypeScript not being able to infer T by adding a kind: T argument to the function, but no changes. Asserting Promise.resolve() to PromiseResult<T> works fine.

Body:
Typescript will generally not let you do much with conditional types as long as they still have unresolved conditional types (as is T in case in PromiseResult<T>)

Moreover in this case you assume that narrowing buildArguments.type narrows T. It does not. Narrowing narrows a value, not a whole type parameter. This is can be no other way, consider this example:

function foo<T extends string | number>(a: T, b: T) {
    if(typeof a === "string") {
        // should b be string? No
    }
}

foo<string | number>(1, "");

Just because we narrowed one value that is of a type T has no bearing on other such variables.

The simplest solution is to use a separate implementation signature that is more permissive, while keeping the public signature with conditional types that is better for the caller:

function bundle<T extends string>(buildArguments: BuildArguments<T>): PromiseResult<T>
function bundle(buildArguments: BuildArguments<string>): PromiseResult<'standalone' | 'all'> | PromiseResult<string> {
    switch (buildArguments.type) {
        case 'standalone':
            return Promise.resolve();
        case 'all':
            return Promise.resolve();
        default:
            return Promise.all([
                Promise.resolve(),
                Promise.resolve()
            ]);
    }
}


问:
How to implement multiple file upload in Django
How to implement multiple file upload in Django with two models?
I have 1 form but two models that make two forms

models.py

```<code>class Ads(models.Model):
    title = models.CharField(max_length=85, blank=False)

class Images(models.Model):
    ad = models.ForeignKey(Ads, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(blank=True, upload_to='')
    thumbnail = models.BooleanField(default=False)
</code>```

views.py

```<code>class CreateAd(CreateView):
    model = Ads
    form_class = CreateAdForm
    success_url = reverse_lazy('index')
</code>```

forms.py

```<code>class CreateAdForm(forms.ModelForm):
    class Meta:
        model = Ads
        fields = ('title',)

class ImageForm(forms.ModelForm):

    class Meta:
        model = Images
        fields = ('image', )
</code>```

答:
Basically you are looking for django formset

formset is a layer of abstraction to work with multiple forms on the same page.

Body:
How to implement multiple file upload in Django with two models?
I have 1 form but two models that make two forms

models.py

class Ads(models.Model):
    title = models.CharField(max_length=85, blank=False)

class Images(models.Model):
    ad = models.ForeignKey(Ads, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(blank=True, upload_to='')
    thumbnail = models.BooleanField(default=False)

views.py

class CreateAd(CreateView):
    model = Ads
    form_class = CreateAdForm
    success_url = reverse_lazy('index')

forms.py

class CreateAdForm(forms.ModelForm):
    class Meta:
        model = Ads
        fields = ('title',)

class ImageForm(forms.ModelForm):

    class Meta:
        model = Images
        fields = ('image', )


问:
Excel - Split cell with a delimiter and if delimiter not found get complete cell value to another cell
I have an excel file with data where I want a Split cell with a delimiter and if the delimiter is not found then copy that cell value to another cell

e.g.

ABC Ltd.

ABC Ltd. - Ind

PQR Ltd. - USA

LMN Corp.

Output - delimiter "-"

ColumnA       ColumnB

ABC Ltd.   ABC Ltd.

ABC Ltd.    Ind

PQR Ltd.     USA

LMN Corp.    LMN Corp.

However, I'm using below formula but not getting what I want.

=TRIM(LEFT(B2,FIND("-",B2)-1))

=TRIM(REPLACE(B2,1,FIND("-",B2),""))

答:
Alternative approach (doesn't necessarily mean better though ;) )

1

```<code>=TRIM(LEFT(B2&"-",FIND("-",B2&"-",1)-1))
</code>```

2

```<code>=TRIM(RIGHT(SUBSTITUTE(A2,"-",REPT(" ",99)),99))
</code>```

Body:
Alternative approach (doesn't necessarily mean better though ;) )

1

=TRIM(LEFT(B2&"-",FIND("-",B2&"-",1)-1))

2

=TRIM(RIGHT(SUBSTITUTE(A2,"-",REPT(" ",99)),99))


问:
How to return ISO date format in PHP for MongoDB?
I want to store the current date generated from PHP into MongoDB collection as an ISO date formate.

```<code>ISODate("2012-11-02T08:40:12.569Z")
</code>```

However I am not able to generate such Kind of date in php which will be stored in MongoDB as an ISODate format.

This is what I ve done.

```<code> $d = new MongoDate(time());
 echo $d;
</code>```

and it is outputting something like,

```<code>0.00000000 1353305590
</code>```

which is not the format I need. How to do this?

答:
```<code>convert ISO date time in UTC date time here :

$timestamp = $quicky_created_date->__toString(); //ISO DATE Return form mongo database
$utcdatetime = new MongoDB\BSON\UTCDateTime($timestamp);
$datetime = $utcdatetime->toDateTime();
$time=$datetime->format(DATE_RSS);
$dateInUTC=$time;
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("d M Y", $time);
echo $dateInLocal; die;
</code>```

Body:
I want to store the current date generated from PHP into MongoDB collection as an ISO date formate.

ISODate("2012-11-02T08:40:12.569Z")

However I am not able to generate such Kind of date in php which will be stored in MongoDB as an ISODate format.

This is what I ve done.

 $d = new MongoDate(time());
 echo $d;

and it is outputting something like,

0.00000000 1353305590

which is not the format I need. How to do this?


问:
Reading rich text from an Excel cell
I am attempting to read an excel spreadsheet in which some cells contain rich text.  I would like to convert this to a plain text format that encodes the formatting in some way.  For example, given the text:

"Here's some text with italics in the middle of it."

I would like to convert this to:

"Here's some text [i]with italics in the middle[/i] of it".

The problem is that I haven't found a way to extract rich text from an excel cell.  Interop.Office.Excel allows me to get a Range and examine its Style property, but that only tells me whether the cell itself is italicized; it doesn't give me information about any of the individual characters.  The best "solution" I've found involves copying the contents of the cell to the clipboard and calling Clipboard.GetData(System.Windows.DataFormats.Rtf), and it's too slow to be practical.

Is there a smart way to access the rich text contained in an excel cell that I'm missing?

答:
The way to access the format of individual characters in a string is to use the Range.Characters object

To demonstrate here is a simple UDF in VBA that does the Italic format you describe.  You can extend it to detect any other formats you need

```<code>Function DecodeText(r As Range) As Variant
    Dim strDecoded As String
    Dim bItalic As Boolean
    Dim i As Long, j As Long

    If TypeName(r.Value) = "String" Then

        bItalic = False
        strDecoded = r
        j = 1
        For i = 1 To Len(strDecoded)
            If Not bItalic And r.Characters(i, 1).Font.Italic Then
                strDecoded = Left(strDecoded, j - 1) & "[i]" & Mid(strDecoded, j)
                bItalic = True
                j = j + 3
            ElseIf bItalic And Not r.Characters(i, 1).Font.Italic Then
                strDecoded = Left(strDecoded, j - 1) & "[/i]" & Mid(strDecoded, j)
                bItalic = False
                j = j + 4
            End If
            j = j + 1
        Next
        If bItalic Then strDecoded = strDecoded & "[/i]"
        DecodeText = strDecoded
    Else
        DecodeText = r
    End If
End Function
</code>```

Title: Reading rich text from an Excel cell

Body:
The way to access the format of individual characters in a string is to use the Range.Characters object

To demonstrate here is a simple UDF in VBA that does the Italic format you describe.  You can extend it to detect any other formats you need

Function DecodeText(r As Range) As Variant
    Dim strDecoded As String
    Dim bItalic As Boolean
    Dim i As Long, j As Long

    If TypeName(r.Value) = "String" Then

        bItalic = False
        strDecoded = r
        j = 1
        For i = 1 To Len(strDecoded)
            If Not bItalic And r.Characters(i, 1).Font.Italic Then
                strDecoded = Left(strDecoded, j - 1) & "[i]" & Mid(strDecoded, j)
                bItalic = True
                j = j + 3
            ElseIf bItalic And Not r.Characters(i, 1).Font.Italic Then
                strDecoded = Left(strDecoded, j - 1) & "[/i]" & Mid(strDecoded, j)
                bItalic = False
                j = j + 4
            End If
            j = j + 1
        Next
        If bItalic Then strDecoded = strDecoded & "[/i]"
        DecodeText = strDecoded
    Else
        DecodeText = r
    End If
End Function


问:
In the same search box search by multiple array object properties
```<code>searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }
</code>```

I am making the search term with name which is the property or key in records array. In the same search box I also want to search by age and course.
How can I achieve this.

```<code><input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">
</code>```

答:
Try:

```<code>search() {
    this.records = this.records.filter((res: any)=>{
      return Object.keys(res).some(item => {
        return item.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())
      });
    });
  }
</code>```

This will search whatever property is in the object and check whether it's value matched the criteria. It will stop on the first match

Body:
searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }

I am making the search term with name which is the property or key in records array. In the same search box I also want to search by age and course.
How can I achieve this.

<input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">

Body:
Try:

search() {
    this.records = this.records.filter((res: any)=>{
      return Object.keys(res).some(item => {
        return item.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())
      });
    });
  }

This will search whatever property is in the object and check whether it's value matched the criteria. It will stop on the first match


问:
How to generate APN certificate so that it should handle to support both old as well as new application after ios app transfer
I have transferd my ios app from my account(AA) to client account(BB).for push notification in fire-base server we uploaded APN (private key) which is generated by AA. But now account is changed and also i am updating app with new account. So if i upload new APN generate from new account, older app will not support push notification. But however i read like " we can generate a APN which will support older and new app"

But how to achieve that..?

With old APN i tried to push notifn to new app which is signed/updated with new account i.e BB , notification is failing..

答:
[https://support.appmachine.com/hc/en-us/articles/360000012284-Transfer-your-app-to-another-iOS-Developer-Account][1]

I think its support you for move application one account to another