问:
Convolutional auto-encoder error - 'RuntimeError: Input type (torch.cuda.ByteTensor) and weight type (torch.FloatTensor) should be the same'
For below model I received error 'Expected stride to be a single value integer or list'. I used suggested answer from https://discuss.pytorch.org/t/expected-stride-to-be-a-single-integer-value-or-a-list/17612/2
 and added

```<code>img.unsqueeze_(0)
</code>```

I now receive error :

```<code>RuntimeError: Input type (torch.cuda.ByteTensor) and weight type (torch.FloatTensor) should be the same
</code>```

For below code I three sample images and attempt to learn a representation of them using an auto-encoder :

```<code>%reset -f

import torch.utils.data as data_utils
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import pyplot as plt
from sklearn import metrics
import datetime
from sklearn.preprocessing import MultiLabelBinarizer
import seaborn as sns
sns.set_style("darkgrid")
from ast import literal_eval
import numpy as np
from sklearn.preprocessing import scale
import seaborn as sns
sns.set_style("darkgrid")
import torch
import torch
import torchvision
import torch.nn as nn
from torch.autograd import Variable
from os import listdir
import cv2
import torch.nn.functional as F
import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

number_channels = 3

%matplotlib inline

x = np.arange(10)
m = 1
b = 2
y = x * x
plt.plot(x, y)
plt.axis('off')
plt.savefig('1-increasing.jpg')

x = np.arange(10)
m = 0.01
b = 2
y = x * x * x
plt.plot(x, y)
plt.axis('off')
plt.savefig('2-increasing.jpg')

x = np.arange(10)
m = 0
b = 2
y = (m*x)+b
plt.plot(x, y)
plt.axis('off')
plt.savefig('constant.jpg')

batch_size_value = 2

train_image = []

train_image.append(cv2.imread('1-increasing.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))
train_image.append(cv2.imread('2-increasing.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))
train_image.append(cv2.imread('decreasing.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))
train_image.append(cv2.imread('constant.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))

data_loader = data_utils.DataLoader(train_image, batch_size=batch_size_value, shuffle=False,drop_last=True)

import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import os

if not os.path.exists('./dc_img'):
    os.mkdir('./dc_img')

def to_img(x):
    x = 0.5 * (x + 1)
    x = x.clamp(0, 1)
    x = x.view(x.size(0), 1, 28, 28)
    return x

num_epochs = 100
# batch_size = 128
batch_size = 2

learning_rate = 1e-3
dataloader = data_loader

class autoencoder(nn.Module):
    def __init__(self):
        super(autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Conv2d(3, 16, 3, stride=3, padding=1),  # b, 16, 10, 10
            nn.ReLU(True),
            nn.MaxPool2d(2, stride=2),  # b, 16, 5, 5
            nn.Conv2d(16, 8, 3, stride=2, padding=1),  # b, 8, 3, 3
            nn.ReLU(True),
            nn.MaxPool3d(3, stride=1)  # b, 8, 2, 2
        )
        self.decoder = nn.Sequential(
            nn.ConvTranspose3d(8, 16, 3, stride=2),  # b, 16, 5, 5
            nn.ReLU(True),
            nn.ConvTranspose3d(16, 8, 5, stride=3, padding=1),  # b, 8, 15, 15
            nn.ReLU(True),
            nn.ConvTranspose3d(8, 1, 2, stride=2, padding=1),  # b, 1, 28, 28
            nn.Tanh()
        )

    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

model = autoencoder()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
                             weight_decay=1e-5)

for epoch in range(num_epochs):
    for data in dataloader:
        img, _ = data
        img.unsqueeze_(0)
#         img.unsqueeze_(0)
#         print(img)
#         img.unsqueeze_(0)
        img = Variable(img).cuda()
        # ===================forward=====================
        output = model(img)
        loss = criterion(output, img)
        # ===================backward====================
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    # ===================log=================to_img=======
    print('epoch [{}/{}], loss:{:.4f}'
          .format(epoch+1, num_epochs, loss.data[0]))
    if epoch % 10 == 0:
        pic = to_img(output.cpu().data)
        save_image(pic, './dc_img/image_{}.png'.format(epoch))

torch.save(model.state_dict(), './conv_autoencoder.pth')
</code>```

But as stated earlier this results in error :

```<code>299     def forward(self, input):
300         return F.conv2d(input, self.weight, self.bias, self.stride,
</code>```

--> 301                         self.padding, self.dilation, self.groups)
      302
      303

RuntimeError: Input type (torch.cuda.ByteTensor) and weight type
  (torch.FloatTensor) should be the same

The issue appears to be related to img.unsqueeze_(0) ?

How to train the auto-encoder on these images ?

答: If you wish to use cuda for training your model. make sure both your model and inputs to your model are shifted to GPU. Shifting only model or only inputs will cause such erros.</p>

Body:
For below model I received error 'Expected stride to be a single value integer or list'. I used suggested answer from https://discuss.pytorch.org/t/expected-stride-to-be-a-single-integer-value-or-a-list/17612/2
 and added

img.unsqueeze_(0)

I now receive error :

RuntimeError: Input type (torch.cuda.ByteTensor) and weight type (torch.FloatTensor) should be the same

For below code I three sample images and attempt to learn a representation of them using an auto-encoder :

%reset -f

import torch.utils.data as data_utils
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import pyplot as plt
from sklearn import metrics
import datetime
from sklearn.preprocessing import MultiLabelBinarizer
import seaborn as sns
sns.set_style("darkgrid")
from ast import literal_eval
import numpy as np
from sklearn.preprocessing import scale
import seaborn as sns
sns.set_style("darkgrid")
import torch
import torch
import torchvision
import torch.nn as nn
from torch.autograd import Variable
from os import listdir
import cv2
import torch.nn.functional as F
import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt

number_channels = 3

%matplotlib inline

x = np.arange(10)
m = 1
b = 2
y = x * x
plt.plot(x, y)
plt.axis('off')
plt.savefig('1-increasing.jpg')

x = np.arange(10)
m = 0.01
b = 2
y = x * x * x
plt.plot(x, y)
plt.axis('off')
plt.savefig('2-increasing.jpg')

x = np.arange(10)
m = 0
b = 2
y = (m*x)+b
plt.plot(x, y)
plt.axis('off')
plt.savefig('constant.jpg')

batch_size_value = 2

train_image = []

train_image.append(cv2.imread('1-increasing.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))
train_image.append(cv2.imread('2-increasing.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))
train_image.append(cv2.imread('decreasing.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))
train_image.append(cv2.imread('constant.jpg', cv2.IMREAD_UNCHANGED).reshape(3, 288, 432))

data_loader = data_utils.DataLoader(train_image, batch_size=batch_size_value, shuffle=False,drop_last=True)

import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.utils import save_image
from torchvision.datasets import MNIST
import os

if not os.path.exists('./dc_img'):
    os.mkdir('./dc_img')

def to_img(x):
    x = 0.5 * (x + 1)
    x = x.clamp(0, 1)
    x = x.view(x.size(0), 1, 28, 28)
    return x

num_epochs = 100
# batch_size = 128
batch_size = 2

learning_rate = 1e-3
dataloader = data_loader

class autoencoder(nn.Module):
    def __init__(self):
        super(autoencoder, self).__init__()
        self.encoder = nn.Sequential(
            nn.Conv2d(3, 16, 3, stride=3, padding=1),  # b, 16, 10, 10
            nn.ReLU(True),
            nn.MaxPool2d(2, stride=2),  # b, 16, 5, 5
            nn.Conv2d(16, 8, 3, stride=2, padding=1),  # b, 8, 3, 3
            nn.ReLU(True),
            nn.MaxPool3d(3, stride=1)  # b, 8, 2, 2
        )
        self.decoder = nn.Sequential(
            nn.ConvTranspose3d(8, 16, 3, stride=2),  # b, 16, 5, 5
            nn.ReLU(True),
            nn.ConvTranspose3d(16, 8, 5, stride=3, padding=1),  # b, 8, 15, 15
            nn.ReLU(True),
            nn.ConvTranspose3d(8, 1, 2, stride=2, padding=1),  # b, 1, 28, 28
            nn.Tanh()
        )

    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

model = autoencoder()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
                             weight_decay=1e-5)

for epoch in range(num_epochs):
    for data in dataloader:
        img, _ = data
        img.unsqueeze_(0)
#         img.unsqueeze_(0)
#         print(img)
#         img.unsqueeze_(0)
        img = Variable(img).cuda()
        # ===================forward=====================
        output = model(img)
        loss = criterion(output, img)
        # ===================backward====================
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    # ===================log=================to_img=======
    print('epoch [{}/{}], loss:{:.4f}'
          .format(epoch+1, num_epochs, loss.data[0]))
    if epoch % 10 == 0:
        pic = to_img(output.cpu().data)
        save_image(pic, './dc_img/image_{}.png'.format(epoch))

torch.save(model.state_dict(), './conv_autoencoder.pth')

But as stated earlier this results in error :

299     def forward(self, input):
300         return F.conv2d(input, self.weight, self.bias, self.stride,

--> 301                         self.padding, self.dilation, self.groups)
      302
      303

RuntimeError: Input type (torch.cuda.ByteTensor) and weight type
  (torch.FloatTensor) should be the same

The issue appears to be related to img.unsqueeze_(0) ?

How to train the auto-encoder on these images ?


来源: stackexchange

问:
Angular Dynamic Html Template component with event emitter
I am trying to extend the functionality of this component by adding a generic event emitter

```<code>import {
  Component,
  Directive,
  NgModule,
  Input,
  ViewContainerRef,
  Compiler,
  ComponentFactory,
  ModuleWithComponentFactories,
  ComponentRef,
  ReflectiveInjector
} from '@angular/core';

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
  const cmpClass = class DynamicComponent { };
  const decoratedCmp = Component(metadata)(cmpClass);

  @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
  class DynamicHtmlModule { }

  return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
    .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
      return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
    });
}

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
  @Input() html: string;
  cmpRef: ComponentRef<any>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

  ngOnChanges() {
    const html = this.html;
    if (!html) return;

    if (this.cmpRef) {
      this.cmpRef.destroy();
    }

    const compMetadata = new Component({
      selector: 'dynamic-html',
      template: this.html,
    });

    createComponentFactory(this.compiler, compMetadata)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
      });
  }

  ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
  }
}
</code>```

Crediting original author
https://gist.github.com/benjamincharity/8116414c7f38cffe3cef0e44fe44295d

example of the desired event

```<code>@Output() genericEventEmitter = new EventEmitter<string>();

emitEvent(data:string){
this.genericEventEmitter.emit(data)
}
</code>```

I've tried adding this to the htmlOutlet class and also the DynamicComponent  I'm getting the error message

```<code>ERROR TypeError: _co.emitEvent is not a function
    at Object.eval [as handleEvent] (DynamicComponent.html:6)
</code>```

This is telling me that the function is not being properly added to the class when it's being created within the componentFactory

Any Angular Gurus, able to shed some insight on how I can get this to work?

答:
Managed to daisy chain a Subject in the dynamic component to an event emitter in the html outlet which can be captured by the parent of the html outlet</p>

```<code>import {
  Component,
  Directive,
  NgModule,
  Input,
  ViewContainerRef,
  Compiler,
  ComponentFactory,
  ModuleWithComponentFactories,
  ComponentRef,
  ReflectiveInjector,
  EventEmitter,
  Output,

} from '@angular/core';
import { Observable, Subject } from 'rxjs'

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { PartialObject } from 'lodash';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
  const cmpClass = class DynamicComponent {
    outputter: Subject<Object> = new Subject();
    genEmit(data) {
      this.outputter.next(data)
    }

  };
  const decoratedCmp = Component(metadata)(cmpClass);

  @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
  class DynamicHtmlModule {

  }

  return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
    .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
      return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
    });
}

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
  @Input() html: string;
  cmpRef: ComponentRef<any>;
  @Output() genericEmitter = new EventEmitter();

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {

  }
  ngOnChanges() {
    const html = this.html;
    if (!html) return;

    if (this.cmpRef) {
      this.cmpRef.destroy();
    }

    const compMetadata = new Component({
      selector: 'dynamic-html',
      template: this.html,
    });

    createComponentFactory(this.compiler, compMetadata)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
        this.cmpRef.instance.outputter.subscribe(v => {
          this.genericEmitter.emit(v)

        })

      });

  }

  ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to extend the functionality of this component by adding a generic event emitter

import {
  Component,
  Directive,
  NgModule,
  Input,
  ViewContainerRef,
  Compiler,
  ComponentFactory,
  ModuleWithComponentFactories,
  ComponentRef,
  ReflectiveInjector
} from '@angular/core';

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
  const cmpClass = class DynamicComponent { };
  const decoratedCmp = Component(metadata)(cmpClass);

  @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
  class DynamicHtmlModule { }

  return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
    .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
      return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
    });
}

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
  @Input() html: string;
  cmpRef: ComponentRef<any>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

  ngOnChanges() {
    const html = this.html;
    if (!html) return;

    if (this.cmpRef) {
      this.cmpRef.destroy();
    }

    const compMetadata = new Component({
      selector: 'dynamic-html',
      template: this.html,
    });

    createComponentFactory(this.compiler, compMetadata)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
      });
  }

  ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
  }
}

Crediting original author
https://gist.github.com/benjamincharity/8116414c7f38cffe3cef0e44fe44295d

example of the desired event

@Output() genericEventEmitter = new EventEmitter<string>();

emitEvent(data:string){
this.genericEventEmitter.emit(data)
}

I've tried adding this to the htmlOutlet class and also the DynamicComponent  I'm getting the error message

ERROR TypeError: _co.emitEvent is not a function
    at Object.eval [as handleEvent] (DynamicComponent.html:6)

This is telling me that the function is not being properly added to the class when it's being created within the componentFactory

Any Angular Gurus, able to shed some insight on how I can get this to work?

Body:
Managed to daisy chain a Subject in the dynamic component to an event emitter in the html outlet which can be captured by the parent of the html outlet

import {
  Component,
  Directive,
  NgModule,
  Input,
  ViewContainerRef,
  Compiler,
  ComponentFactory,
  ModuleWithComponentFactories,
  ComponentRef,
  ReflectiveInjector,
  EventEmitter,
  Output,

} from '@angular/core';
import { Observable, Subject } from 'rxjs'

import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { PartialObject } from 'lodash';

export function createComponentFactory(compiler: Compiler, metadata: Component): Promise<ComponentFactory<any>> {
  const cmpClass = class DynamicComponent {
    outputter: Subject<Object> = new Subject();
    genEmit(data) {
      this.outputter.next(data)
    }

  };
  const decoratedCmp = Component(metadata)(cmpClass);

  @NgModule({ imports: [CommonModule, RouterModule], declarations: [decoratedCmp] })
  class DynamicHtmlModule {

  }

  return compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule)
    .then((moduleWithComponentFactory: ModuleWithComponentFactories<any>) => {
      return moduleWithComponentFactory.componentFactories.find(x => x.componentType === decoratedCmp);
    });
}

@Directive({ selector: 'html-outlet' })
export class HtmlOutlet {
  @Input() html: string;
  cmpRef: ComponentRef<any>;
  @Output() genericEmitter = new EventEmitter();

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {

  }
  ngOnChanges() {
    const html = this.html;
    if (!html) return;

    if (this.cmpRef) {
      this.cmpRef.destroy();
    }

    const compMetadata = new Component({
      selector: 'dynamic-html',
      template: this.html,
    });

    createComponentFactory(this.compiler, compMetadata)
      .then(factory => {
        const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
        this.cmpRef = this.vcRef.createComponent(factory, 0, injector, []);
        this.cmpRef.instance.outputter.subscribe(v => {
          this.genericEmitter.emit(v)

        })

      });

  }

  ngOnDestroy() {
    if (this.cmpRef) {
      this.cmpRef.destroy();
    }
  }
}


问:
How to Implement Custom Table View Section Headers and Footers with Storyboard
Without using a storyboard we could simply drag a UIView onto the canvas, lay it out and then set it in the tableView:viewForHeaderInSection or tableView:viewForFooterInSection delegate methods.

How do we accomplish this with a StoryBoard where we cannot drag a UIView onto the canvas

答:
Similar to laszlo answer but you can reuse the same prototype cell for both the table cells and the section header cell. Add the first two functions below to your UIViewController subClass</p>

```<code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell") as! DataCell
    cell.data1Label.text = "DATA KEY"
    cell.data2Label.text = "DATA VALUE"
    return cell
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 75
}

// Example of regular data cell dataDelegate to round out the example
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as! PlayerCell

    cell.data1Label.text = "\(dataList[indexPath.row].key)"
    cell.data2Label.text = "\(dataList[indexPath.row].value)"
    return cell
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Similar to laszlo answer but you can reuse the same prototype cell for both the table cells and the section header cell. Add the first two functions below to your UIViewController subClass

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell") as! DataCell
    cell.data1Label.text = "DATA KEY"
    cell.data2Label.text = "DATA VALUE"
    return cell
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 75
}

// Example of regular data cell dataDelegate to round out the example
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as! PlayerCell

    cell.data1Label.text = "\(dataList[indexPath.row].key)"
    cell.data2Label.text = "\(dataList[indexPath.row].value)"
    return cell
}


问:
expand for MongoDB Scala driver?
Casbah has an expand function that lets you retrieve nested keys.
Does the newer MongoDB Scala Driver have this functionality?</p>

答:
In Scala MongoDB driver you can use Macros to generate codecs from your case classes. Even you can create your codecs for you co-products (sealed trait). According to the doc: "Simple case classes and nested case classes are supported.". So take a look to the examples here

ReactiveMongo uses macros too, but there are another alternatives using Shapeless like: https://github.com/julienrf/reactivemongo-derived-codecs

Title: expand for MongoDB Scala driver?


问:
split xml value with xpath and check string position
I have the following xml file:

```<code> <courses>
   <course>
    <name>Course 1</name>
    <code>00162</code>
    <questions>2,2,1,1,2,1,1,1</questions>
   </course>
   </courses>
</code>```

I need to query the file (I'm using xpath) to split the 'questions' element, check the position in which each number appears and check if it is number 1 or 2.

Basically I need to this in xpath:

```<code>Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer

        For i = 0 To UBound(ints)
            If ints(i) = "2" Then
             'do something
            Else
            'do something else
            End If
        Next
</code>```

Update from comments

Hi, thank you. I was going to edit the
  question as it was incorrect. I want
  to get, for example, all course names
  and codes whose 'questions' element
  (after split) has "2" in the second
  position, as in 1,2,2,1,1,1,2,1
  Thanks!

答:
Well there's tokenize(string, pattern) in XPath, so you could write

```<code>/courses/course/questions[(tokenize(text(), "[0-9]+")) ]
                     put something clever here -------^
</code>```

But I don't get, what you mean by "do something" and "do something else". XPath is for selecting nodes / retrieving information. You need XSLT or XQuery to "do something" else.

Body:
I have the following xml file:

 <courses>
   <course>
    <name>Course 1</name>
    00162
    <questions>2,2,1,1,2,1,1,1</questions>
   </course>
   </courses>

I need to query the file (I'm using xpath) to split the 'questions' element, check the position in which each number appears and check if it is number 1 or 2.

Basically I need to this in xpath:

Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer

        For i = 0 To UBound(ints)
            If ints(i) = "2" Then
             'do something
            Else
            'do something else
            End If
        Next

Update from comments

Hi, thank you. I was going to edit the
  question as it was incorrect. I want
  to get, for example, all course names
  and codes whose 'questions' element
  (after split) has "2" in the second
  position, as in 1,2,2,1,1,1,2,1
  Thanks!

Body:
Well there's tokenize(string, pattern) in XPath, so you could write

/courses/course/questions[(tokenize(text(), "[0-9]+")) ]
                     put something clever here -------^

But I don't get, what you mean by "do something" and "do something else". XPath is for selecting nodes / retrieving information. You need XSLT or XQuery to "do something" else.


问:
How do I checkout a branch added after a Github clone?
I have cloned a Github repository with the "--recursive" qualifier.  I then checked out the latest branch in that repository.

Later, the author of the repository added a new branch.  When I attempted to checkout that new branch with git checkout branch-name, git reported that the branch-name was unknown.

Is there a way to get the new branch-name without again cloning the repository?

答: To get all the data (and also newly added branches) from remote repository which you don't have yet use the command git fetch.


问:
How to Reduce Google App Script Service Calls
This script here renames the sheetnames with the value in A1. I manage a school database with over 150 sheets. The script is throwing a maximum time execution timeout error. I have read on the forums here that you can reduce service calls. This here Google app script timeout ~ 5 minutes? looks like a solution but I can't in the life of me wrap my head around what's going on.

I should probably mention that I am a complete noob and your help will be of immense help.

```<code>function onEdit() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();

// Array holding the names of the sheets to exclude from the execution
var exclude ="Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s=10;s<allsheets.length;s++) {
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
}

} // end of loop

} // end of function
</code>```

Kindly help me reduce the number of service calls the script is making or a faster way to avoid the timeout error.

//Updated Script

//Sample code below generating error missing ) after condition

```<code>function testArray() {
    var arr = ["Sh1","Sh2","Sh3","Sh4","Sh5","Sh6","Sh7","Sh8","Sh9","Sh10"];  //etc etc
    var res = [];

    arr.forEach(function (element,index) {
        if(index>9) {
            var sheet = allsheets[s];
            var oldName = sheet.getName();
            var newName = sheet.getRange(1,1).getValue();

            if (newName.toString().length>0 && newName !== oldName) {
                sheet.setName(newName); // Stop iteration execution if the condition is meet.
                if(exclude.indexOf(sheet.getName())==-1}) continue; //iterable code goes here;
            }
        // }
     });
}
</code>```

答:
First of all, get rid of unnecessary calls - did you consider the splice() part of my answer to your previous question?

```<code>allsheets.splice(0,10); //0-based start and end indexes;
</code>```

If excluded sheet names can be encountered anywhere, keep your exclude Array and if statement (btw, there seems to be a typo in your sample - the Array declaration misses an opening bracket).

Regardless of how you exclude your first 10 sheets, the call to stop iteration becomes overkill as you invoke getName() method allsheets.length times (thus, 150 unnecessary method calls) - reference the newName variable instead.

You can further reduce calls by checking for the condition before calling the setName() method (assuming you do not want to do anything is new name is in exclude Array).

Then, use the for loop to do the same manipulations (note that in case the Array is filtered using splice(), index s should be 0):

```<code>for(var s=10; s<allsheets.length; s++) {
  var sheet = allsheets[s];
  var oldName = sheet.getName();
  var newName = sheet.getRange(1,1).getValue();

  //this reduces setName() calls if you don't need to set reserved names;
  if(exclude.indexOf(newName)!==-1) { continue; }

  if (newName.toString().length>0 && newName !== oldName) {
    sheet.setName(newName);
  }
}
</code>```

Alternatively, you can use a forEach to make manipulations you want. This is how the whole function will look like using splice() and forEach():

```<code>function testArray() {

  var ss = SpreadsheetApp.getActive();
  var arr = ss.getSheets();

  arr.splice(0,10); //removes first 10 Sheets from Array;

  var exclude = []; //fill with unchangeable names;

  arr.forEach(function (sheet,index) { //iterates over Array of Sheets;

      var oldName = sheet.getName();
      var newName = sheet.getRange(1,1).getValue();

      if(newName.toString().length>0 && newName!==oldName) {

        //Move to next iteration if new name should be excluded;
        if(exclude.indexOf(newName)===-1) {
          sheet.setName(newName); //set name otherwise;
        }

      }

  }); // end of loop

} // end of function
</code>```

Body:
This script here renames the sheetnames with the value in A1. I manage a school database with over 150 sheets. The script is throwing a maximum time execution timeout error. I have read on the forums here that you can reduce service calls. This here Google app script timeout ~ 5 minutes? looks like a solution but I can't in the life of me wrap my head around what's going on.

I should probably mention that I am a complete noob and your help will be of immense help.

function onEdit() {
var ss = SpreadsheetApp.getActive();
var allsheets = ss.getSheets();

// Array holding the names of the sheets to exclude from the execution
var exclude ="Sheet1","Sheet2","Sheet3","Article","Frontpage","Logos","Sheet4","Sheet5","Sheet6","Sheet10"];

for(var s=10;s<allsheets.length;s++) {
var sheet = allsheets[s];
var oldName = sheet.getName();
var newName = sheet.getRange(1,1).getValue();
if (newName.toString().length>0 && newName !== oldName) {
sheet.setName(newName);

// Stop iteration execution if the condition is meet.
if(exclude.indexOf(sheet.getName())==-1) continue;
}

} // end of loop

} // end of function

Kindly help me reduce the number of service calls the script is making or a faster way to avoid the timeout error.

//Updated Script

//Sample code below generating error missing ) after condition

function testArray() {
    var arr = ["Sh1","Sh2","Sh3","Sh4","Sh5","Sh6","Sh7","Sh8","Sh9","Sh10"];  //etc etc
    var res = [];

    arr.forEach(function (element,index) {
        if(index>9) {
            var sheet = allsheets[s];
            var oldName = sheet.getName();
            var newName = sheet.getRange(1,1).getValue();

            if (newName.toString().length>0 && newName !== oldName) {
                sheet.setName(newName); // Stop iteration execution if the condition is meet.
                if(exclude.indexOf(sheet.getName())==-1}) continue; //iterable code goes here;
            }
        // }
     });
}

Body:
First of all, get rid of unnecessary calls - did you consider the splice() part of my answer to your previous question?

allsheets.splice(0,10); //0-based start and end indexes;

If excluded sheet names can be encountered anywhere, keep your exclude Array and if statement (btw, there seems to be a typo in your sample - the Array declaration misses an opening bracket).

Regardless of how you exclude your first 10 sheets, the call to stop iteration becomes overkill as you invoke getName() method allsheets.length times (thus, 150 unnecessary method calls) - reference the newName variable instead.

You can further reduce calls by checking for the condition before calling the setName() method (assuming you do not want to do anything is new name is in exclude Array).

Then, use the for loop to do the same manipulations (note that in case the Array is filtered using splice(), index s should be 0):

for(var s=10; s<allsheets.length; s++) {
  var sheet = allsheets[s];
  var oldName = sheet.getName();
  var newName = sheet.getRange(1,1).getValue();

  //this reduces setName() calls if you don't need to set reserved names;
  if(exclude.indexOf(newName)!==-1) { continue; }

  if (newName.toString().length>0 && newName !== oldName) {
    sheet.setName(newName);
  }
}

Alternatively, you can use a forEach to make manipulations you want. This is how the whole function will look like using splice() and forEach():

function testArray() {

  var ss = SpreadsheetApp.getActive();
  var arr = ss.getSheets();

  arr.splice(0,10); //removes first 10 Sheets from Array;

  var exclude = []; //fill with unchangeable names;

  arr.forEach(function (sheet,index) { //iterates over Array of Sheets;

      var oldName = sheet.getName();
      var newName = sheet.getRange(1,1).getValue();

      if(newName.toString().length>0 && newName!==oldName) {

        //Move to next iteration if new name should be excluded;
        if(exclude.indexOf(newName)===-1) {
          sheet.setName(newName); //set name otherwise;
        }

      }

  }); // end of loop

} // end of function


问:
override handler level through logger.log
Is there a way to Override the Handler's level through logger Object.

Eg:

```<code>FileHandler logFile = new FileHandler("DefaultLogger.log");
logger.setLevel(Level.FINE);
</code>```

should set the fileHandler's level to fine as well.

答:
You can use the Logger::getHandlers method to acquire all of the install handlers for the given logger.  For example:

```<code>private static void setHandlersLevel(Logger logger, Level lvl) {
    for (Handler h : logger.getHandlers()) {
       h.setLevel(lvl);
    }
}
</code>```

Otherwise if you want to find all handler on all loggers you can use the following:

```<code>private static void setAllHandlersLevel(Level lvl) {
    LogManager lm = LogManager.getLogManager();
    synchronized (lm) {
        Enumeration<String> e = lm.getLoggerNames();
        while (e.hasMoreElements()) {
            Logger l = lm.getLogger(e.nextElement());
            if (l != null) {
                for (Handler h : l.getHandlers()) {
                    h.setLevel(lvl);
                }
            }
        }
    }
}
</code>```

Body:
Is there a way to Override the Handler's level through logger Object.

Eg:

FileHandler logFile = new FileHandler("DefaultLogger.log");
logger.setLevel(Level.FINE);

should set the fileHandler's level to fine as well.

Body:
You can use the Logger::getHandlers method to acquire all of the install handlers for the given logger.  For example:

private static void setHandlersLevel(Logger logger, Level lvl) {
    for (Handler h : logger.getHandlers()) {
       h.setLevel(lvl);
    }
}

Otherwise if you want to find all handler on all loggers you can use the following:

private static void setAllHandlersLevel(Level lvl) {
    LogManager lm = LogManager.getLogManager();
    synchronized (lm) {
        Enumeration<String> e = lm.getLoggerNames();
        while (e.hasMoreElements()) {
            Logger l = lm.getLogger(e.nextElement());
            if (l != null) {
                for (Handler h : l.getHandlers()) {
                    h.setLevel(lvl);
                }
            }
        }
    }
}


问:
Passport JWT works with empty payload
I have initialized strategy for JWT:

```<code>const jwtStrategyOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('x-access-token'),
  secretOrKey: 'publicKey',
}

passport.use(
  new JwtStrategy(
    jwtStrategyOptions,
    (payload, done) => {
      MySQL.Users.readOne(['id'], { id: payload.userId })
      .fork(
        error => {console.log(error)
          done(error)},
        user => {
          console.log(user)
          done(null, user)}
      )
    }
  )
)
</code>```

And middleware:

```<code>const isAuthenticated: RequestHandler = (req, res, next) => {
  passport.authenticate(
    'jwt',
    { session: false, failWithError: true },
    (error, user) => {
      //error is null when I pass empty payload
      if (error) {
        return next(error)
      }
      req.user = user

      return next()
    }
  )(req, res, next)
}
</code>```

But when I pass empty or invalid token Passport just pass this

```<code>(payload, done) => {
  MySQL.Users.readOne(['id'], { id: payload.userId })
  .fork(
    error => {console.log(error)
      done(error)},
    user => {
      console.log(user)
      done(null, user)}
  )
}
</code>```

step and code execute next() function.
Can I somehow detect that payload is invalid or empty?

答:
I'm not quite sure about the MySQL call return type, but if nothing matches the id, does it raise an error?

```<code>(payload, done) => {
  MySQL.Users.readOne(['id'], { id: payload.userId })
  .fork(
    error => {console.log(error)
      done(error)},
    user => {
      console.log(user)
      done(null, user)}
  )
}
</code>```

If it doesn't raise an error but return null or empty value, you need to check it in the 'success' callback function, because in this case it will call done(null, user) with an empty value.

Based on your comment, this might help, some code that I was using to check for a token expiration error :

```<code>    passport.authenticate('jwt',
        {session: false},
        //we need this callback to return information on why it's failing
        //err is not populated, but 'info' is...
        (err, user, info) => {
            if (err) {
                return next(err);
            }

            //if we couldn't authenticate the user, check why
            //401 is used when no token or random information is provided
            //403 is used when a well-formed token is provided, but it has expired thus not valid anymore
            if (!user) {
                if (info.name === 'TokenExpiredError') {
                    return res.status(403).send(info.name);
                }
                else {
                    return res.status(401).send(info.message);
                }
            }

            req.user = user;

            return next();
</code>```

Title: Passport JWT works with empty payload

Body:
I have initialized strategy for JWT:

const jwtStrategyOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('x-access-token'),
  secretOrKey: 'publicKey',
}

passport.use(
  new JwtStrategy(
    jwtStrategyOptions,
    (payload, done) => {
      MySQL.Users.readOne(['id'], { id: payload.userId })
      .fork(
        error => {console.log(error)
          done(error)},
        user => {
          console.log(user)
          done(null, user)}
      )
    }
  )
)

And middleware:

const isAuthenticated: RequestHandler = (req, res, next) => {
  passport.authenticate(
    'jwt',
    { session: false, failWithError: true },
    (error, user) => {
      //error is null when I pass empty payload
      if (error) {
        return next(error)
      }
      req.user = user

      return next()
    }
  )(req, res, next)
}

But when I pass empty or invalid token Passport just pass this

(payload, done) => {
  MySQL.Users.readOne(['id'], { id: payload.userId })
  .fork(
    error => {console.log(error)
      done(error)},
    user => {
      console.log(user)
      done(null, user)}
  )
}

step and code execute next() function.
Can I somehow detect that payload is invalid or empty?

Body:
I'm not quite sure about the MySQL call return type, but if nothing matches the id, does it raise an error?

(payload, done) => {
  MySQL.Users.readOne(['id'], { id: payload.userId })
  .fork(
    error => {console.log(error)
      done(error)},
    user => {
      console.log(user)
      done(null, user)}
  )
}

If it doesn't raise an error but return null or empty value, you need to check it in the 'success' callback function, because in this case it will call done(null, user) with an empty value.

Based on your comment, this might help, some code that I was using to check for a token expiration error :

    passport.authenticate('jwt',
        {session: false},
        //we need this callback to return information on why it's failing
        //err is not populated, but 'info' is...
        (err, user, info) => {
            if (err) {
                return next(err);
            }

            //if we couldn't authenticate the user, check why
            //401 is used when no token or random information is provided
            //403 is used when a well-formed token is provided, but it has expired thus not valid anymore
            if (!user) {
                if (info.name === 'TokenExpiredError') {
                    return res.status(403).send(info.name);
                }
                else {
                    return res.status(401).send(info.message);
                }
            }

            req.user = user;

            return next();


问:
JOIN TWO SQL Queries in MS SQL
I am looking for some help combining two queries:

The first:

```<code>SELECT TITLE,
       count(TITLE) as DUPLICATES
FROM CONTENT
WHERE CONTENTTYPE = 'ATTACHMENT' GROUP BY TITLE having count(TITLE) > 1
</code>```

The second is just

```<code>SELECT CONTENTID,
       TITLE
FROM CONTENT
</code>```

I wanted to see CONTENTID as part of the first query, but I was not sure how to do that.  The two queries are against the same table, CONTENT.

答:
I suspect that you want to see all records belonging to a TITLE group whose attachment records number in excess of one.  We can try using COUNT here:

```<code>WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY TITLE) cnt
    FROM CONTENT
    WHERE CONTENTTYPE = 'ATTACHMENT'
)

SELECT CONTENTID, TITLE
FROM cte
WHERE cnt > 1;
</code>```

This approach uses COUNT as an analytic function to identify the TITLE records matching your requeiments.

Title: JOIN TWO SQL Queries in MS SQL

Body:
I am looking for some help combining two queries:

The first:

SELECT TITLE,
       count(TITLE) as DUPLICATES
FROM CONTENT
WHERE CONTENTTYPE = 'ATTACHMENT' GROUP BY TITLE having count(TITLE) > 1

The second is just

SELECT CONTENTID,
       TITLE
FROM CONTENT

I wanted to see CONTENTID as part of the first query, but I was not sure how to do that.  The two queries are against the same table, CONTENT.

Body:
I suspect that you want to see all records belonging to a TITLE group whose attachment records number in excess of one.  We can try using COUNT here:

WITH cte AS (
    SELECT *, COUNT(*) OVER (PARTITION BY TITLE) cnt
    FROM CONTENT
    WHERE CONTENTTYPE = 'ATTACHMENT'
)

SELECT CONTENTID, TITLE
FROM cte
WHERE cnt > 1;

This approach uses COUNT as an analytic function to identify the TITLE records matching your requeiments.


问:
webdriverIO - Unhandled promise rejection: NoSuchSessionError: invalid session id
I'm learning UI testing with Jasmine & WebdriverIO. I use it with NodeJS.
I have the next test code:

const projectsPage = require('../../lib/pages/projects.page');
const by = require('selenium-webdriver').By;

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q')).sendKeys('test');
  })
});```
</div>
</div>
</p>

<p>When I run it, I receive the error:</p>

```Unhandled promise rejection: NoSuchSessionError: invalid session id
      (Driver info: chromedriver=2.46.628411 (3324f4c8be9ff2f70a05a30ebc72ffb013e1a71e),platform=Mac OS X 10.14.5 x86_64)
```

<p>But the code below performs successfully:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q'))
  })
});</code>```

Where I was wrong?

答:
Since findElement and sendKeys also return promises, you'll have to await the methods as well:

```<code>await driver.findElement(by.name('q')).then(element => element.sendKeys('test'));
</code>```

Body:
I'm learning UI testing with Jasmine & WebdriverIO. I use it with NodeJS.
I have the next test code:

const projectsPage = require('../../lib/pages/projects.page');
const by = require('selenium-webdriver').By;

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q')).sendKeys('test');
  })
});

When I run it, I receive the error:

Unhandled promise rejection: NoSuchSessionError: invalid session id
      (Driver info: chromedriver=2.46.628411 (3324f4c8be9ff2f70a05a30ebc72ffb013e1a71e),platform=Mac OS X 10.14.5 x86_64)

But the code below performs successfully:

describe('Projects page', () => {
  it('Search google', async() => {
    await projectsPage.navigateTo();
    driver.getTitle().then(function(title) {
      expect(title).toBe('Google');
    });
    driver.findElement(by.name('q'))
  })
});

Where I was wrong?

Body:
Since findElement and sendKeys also return promises, you'll have to await the methods as well:

await driver.findElement(by.name('q')).then(element => element.sendKeys('test'));


问:
Is there a way to get html footer on bottom of any page?
I'm building my own website for a project. I have an event page where I show all upcoming events. Every time you add an event, the page will get bigger. ATM, the footer is in the middle of the page because there are not enough events.

The problem is, I want the footer to be on the bottom of the screen, unless the page is bigger than the screen. If the page is bigger than the screen, the footer should be on the bottom of the page.

I tried to use height: 100% or height: 100vh but they put the height on "fit to screen", so if there are for example 20 events (bigger than the screen), the footer will be stuck on the bottom of the screen and the events will go through the footer.

The page now looks like this:

and the table is build up like this:

      Date/Time
      Event

            #_EVENTDATES
            #_EVENTTIMES

            #_EVENTLINK
            {has_location}
#_LOCATIONNAME, #_LOCATIONTOWN #_LOCATIONSTATE{/has_location}

```

答:
There are a few different ways to do what you want, depending on exactly what you want. Some sites like to have a footer that's at the bottom of what's visible (although less do that these days), while others (most) have it rooted to the bottom of the entire page so you have to scroll to it, while also ensuring it doesn't sit halfway up the visible window when the page is too small.

You probably want the latter.

There's a decent guide for it here: https://www.freecodecamp.org/news/how-to-keep-your-footer-where-it-belongs-59c6aa05c59c/

There are also several others across the web, including this one from W3C:

https://www.w3schools.com/howto/howto_css_fixed_footer.asp

If you really want consistency, you can try throwing a little php magic in there as well. Nothing impresses in a web-dev project like a little php!

Hope I've helped.


问:
Finding out when MapLoader finished (eager) loading in Hazelcast
I use the MapLoader for initial loading data from the data store to Hazelcast (InitialLoadMode = EAGER). I need to load this data from a materialized view that is created for the sake of this loading at the beginning of this loading process and after the loading is done, I need to remove this materialized view.

Is there any way to tell Hazelcast to fire my code creating this view before it starts loading the data using MapLoader?

Is there any way to be notified by Hazelcast after the initial load is finished? I looked through listeners but I only saw those regarding the single value.

The only way I came up with is to create the materialized view in MapLoader.loadAllKeys() (it guarantees it will be executed only once and that it will be executed befor anyone can get something from the map, and so before anyone can invoke the loading process inadvertently) and then somewhere else invoke getMap("") (I use EAGER) and when it finishes, delete the entity.

Is there a better way of doing this?

答:
If you need full control of your initialization process then probably you need to fill your map manually without MapLoader:</p>

```<code>public class MapWrapper {

    private Lock lock = hazelcastInstance.getLock("map-lock");
    private IAtomicLong mapIsLoaded = ...;
    ICountDownLatch latch = hazelcastInstance.getCountDownLatch("map-loaded");

    public MapWrapper() {
        latch.trySetCount(1);
    }

    public void initialize() {
        lock.lock();
        // Loading:
        try {
            // Skip loading if map already loaded (ensure only once for cluster)
            if(mapIsLoaded.get() == 1) {
                return;
            }
            mapIsLoaded.set(0);
            // Here code to load your map, clean database:
            initializeDatabase();
            loadMap();
            cleanDatabase();
        } finally {
            latch.countdown();
            mapIsLoaded.set(1);
            lock.unlock();
        }
    }

    public Map getMap() {
        // Blocking until loading is completed:
        latch.await();
        return hazelcastInstance.getMap(...);
    }
}
</code>```

Body:
If you need full control of your initialization process then probably you need to fill your map manually without MapLoader:

public class MapWrapper {

    private Lock lock = hazelcastInstance.getLock("map-lock");
    private IAtomicLong mapIsLoaded = ...;
    ICountDownLatch latch = hazelcastInstance.getCountDownLatch("map-loaded");

    public MapWrapper() {
        latch.trySetCount(1);
    }

    public void initialize() {
        lock.lock();
        // Loading:
        try {
            // Skip loading if map already loaded (ensure only once for cluster)
            if(mapIsLoaded.get() == 1) {
                return;
            }
            mapIsLoaded.set(0);
            // Here code to load your map, clean database:
            initializeDatabase();
            loadMap();
            cleanDatabase();
        } finally {
            latch.countdown();
            mapIsLoaded.set(1);
            lock.unlock();
        }
    }

    public Map getMap() {
        // Blocking until loading is completed:
        latch.await();
        return hazelcastInstance.getMap(...);
    }
}


问:
Can I conditionally activate the Git prompt depending on the repository I'm in?
I'm using the built-in git prompt shell script to improve my Bash prompt.

```<code>. ~/git-completion.bash
. ~/git-prompt.sh

export GIT_PS1_SHOWDIRTYSTATE=1
export GIT_PS1_SHOWUNTRACKEDFILES=1
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS=1
</code>```

I have this one enormous enterprise application repository (100s of thousands of files, a very deep directory tree, the .git directory is almost 2 GB). The prompt is taking a very long time to complete.

Is there some way to tell git-prompt.sh to ignore this workspace? Either by flags or in my .bashrc?

答:
The built-in git prompt shell script has per-repository options you can set to speed up the prompt.

Set bash.showDirtyState to false to disable checking for changes:

```<code>$ git config --local --add bash.showDirtyState false
</code>```

Set bash.showUntrackedFiles to false to stop checking for untracked files:

```<code>$ git config --local --add bash.showUntrackedFiles false
</code>```

Set bash.showUpstream to the empty string to stop comparing HEAD with its upstream:

```<code>$ git config --local --add bash.showUpstream ''
</code>```

Body:
I'm using the built-in git prompt shell script to improve my Bash prompt.

. ~/git-completion.bash
. ~/git-prompt.sh

export GIT_PS1_SHOWDIRTYSTATE=1
export GIT_PS1_SHOWUNTRACKEDFILES=1
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS=1

I have this one enormous enterprise application repository (100s of thousands of files, a very deep directory tree, the .git directory is almost 2 GB). The prompt is taking a very long time to complete.

Is there some way to tell git-prompt.sh to ignore this workspace? Either by flags or in my .bashrc?

Body:
The built-in git prompt shell script has per-repository options you can set to speed up the prompt.

Set bash.showDirtyState to false to disable checking for changes:

$ git config --local --add bash.showDirtyState false

Set bash.showUntrackedFiles to false to stop checking for untracked files:

$ git config --local --add bash.showUntrackedFiles false

Set bash.showUpstream to the empty string to stop comparing HEAD with its upstream:

$ git config --local --add bash.showUpstream ''


答:
You can use PHP to get your footer on any page, look at this : https://www.w3schools.com/php/php_includes.asp
Or you can use a framework like angular</p>

Title: Is there a way to get html footer on bottom of any page?

Body:
I'm building my own website for a project. I have an event page where I show all upcoming events. Every time you add an event, the page will get bigger. ATM, the footer is in the middle of the page because there are not enough events.

The problem is, I want the footer to be on the bottom of the screen, unless the page is bigger than the screen. If the page is bigger than the screen, the footer should be on the bottom of the page.

I tried to use height: 100% or height: 100vh but they put the height on "fit to screen", so if there are for example 20 events (bigger than the screen), the footer will be stuck on the bottom of the screen and the events will go through the footer.

The page now looks like this:

and the table is build up like this:

      Date/Time
      Event

            #_EVENTDATES
            #_EVENTTIMES

            #_EVENTLINK
            {has_location}
#_LOCATIONNAME, #_LOCATIONTOWN #_LOCATIONSTATE{/has_location}


问:
How to evaluate a spreadsheet formula within a custom function?
In a spreadsheet I can enter =SIN(45)+123 in a cell, and it will be evaluated.

How can I evaluate spreadsheet functions within a custom function, something like an "eval"
function that would work like this :

function myFunc() {
  return Sheet.eval("=SIN(45)+123")
}
```

is it possible ?

Note that I don't care about the SIN function in particular, what I want is to have access to the complete arsenal of spreadsheet functions (PMT, QUERY, NPER, etc..)

答:
I know this is an old question, but it might help someone.
just assign the formula to a range, then grab the value.</p>

```<code>//asign a formula to the range
var range = sheet.getRange("A1").setFormula("=SUM(D1:D100)");
//get the result
var result  = range.getValue();
//clean up
range.setFormula("");
</code>```

Body:
In a spreadsheet I can enter =SIN(45)+123 in a cell, and it will be evaluated.

How can I evaluate spreadsheet functions within a custom function, something like an "eval"
function that would work like this :

function myFunc() {
  return Sheet.eval("=SIN(45)+123")
}

is it possible ?

Note that I don't care about the SIN function in particular, what I want is to have access to the complete arsenal of spreadsheet functions (PMT, QUERY, NPER, etc..)

Body:
I know this is an old question, but it might help someone.
just assign the formula to a range, then grab the value.

//asign a formula to the range
var range = sheet.getRange("A1").setFormula("=SUM(D1:D100)");
//get the result
var result  = range.getValue();
//clean up
range.setFormula("");


问:
Tabs on the side of Visual Studio
I'm starting WPF. I need a tab on the sides of the screen; I do not know how to open that tab.

I do know how to open solution explorer but not other things like properties, notifications and toolbox.

答: Please see the below screenshot, just click the ones you want then pin them as needed

Title: Tabs on the side of Visual Studio


问:
Wanted: ASP.NET control to view/print PDF, TIFF, possibly more?
I'm looking for an asp.NET control that will allow for viewing and printing of a pdf and TIFF within a web form.  I'm willing to use more than 1 control if needed (1 control for pdf, 1 for Tiff, show and hide based on file extension), but I have not been able to find a good Tiff viewer.

Files are stored on our LAN in a shared folder, and this application is an intranet site.

Open source / free licensing preferred, but I'm willing to look at paid options as well.

答:
You can get a free licence of ABCPDF (provided you link back to their site) which will do the conversion from TIFF to PDF for you as per @Chris Lively 's suggestion.

It'll also do conversion from PDF to TIFF if you decide to do things backwards.

It makes sense to present the content in a common format.  If you wanted to you can embed the PDF in the browser to create the 'seamless' experience you're looking for using something like PDFObject.

As @BenCr says though, PDF is a really common format and the tools already exist to open and work with them, so introducing new ways to perform existing tasks could actually end up complicating matters unnecessarily.


问:
ReactJS tag rasa nlu entities text highlighting
I'm developing a simple react app to show rasa HTTP api results data, and I want to tag the entities in a sentence. My code works good for 1 word entity but breaks with 2 words (only the first word is highlighted)

This is what I'm doing

```<code>  const [colors, setColors] = useState([
    "salmon",
    "primary",
    "purple",
    "orange"
  ]);

  const tagSentence = () => {
    let sentence = props.data.text;
    const entities = props.data.entities;

    entities.map((e, eIndex) => {
      sentence = sentence.replace(e.value, `<${eIndex}>${e.value}`);
    });
    return sentence.split(" ");
  };

          <Typography variant="h5" component="h2">
            {props.data.entities.map(t => {
              if (t.value.includes("<")) {
                return (
                  <Chip
                    key={t.value}
                    label={t.slice(3, t.length)}
                    color="primary"
                    style={{ backgroundColor: colors[t.slice(1, 2)] }}
                  />
                );
              } else {
                return ` ${t} `;
              }
            })}
          </Typography>
</code>```

Entities object has the index of start and end of the words , but I cant figure out how to use it.

Example sentence :

Peter is my best friend

```<code>{
"text" : "peter is my best friend"
"entities" : [{"entity": "PERSON", "value": "peter", "start": 1, "end": 5...}]
}
</code>```

EDIT:

Ended with this, now looking how to make whole word includes in JS

```<code>          <Typography variant="h5" component="h2">
            {props.data.text.split(" ").map((s, sIndex) => {
              return props.data.entities.map((e, eIndex) => {
                if (e.value.includes(s)) {
                  return (
                    <Chip
                      key={s}
                      label={s}
                      style={{ backgroundColor: colors[sIndex] }}
                      color="primary"
                    />
                  );
                } else {
                  return ` ${s} `;
                }
              });
            })}
          </Typography>
</code>```

答:
I finally used https://github.com/iansinnott/react-string-replace to easily replace  strings with components, worked like a charm.</p>

```<code>  const tagSentence = () => {
    let sentence = props.data.text;
    props.data.entities.forEach((e, eIndex) => {
      sentence = reactStringReplace(sentence, e.value, (match, i) => (
        <Chip
          key={i}
          label={match}
          style={{ backgroundColor: colors[eIndex] }}
          color="primary"
        />
      ));
    });
    return sentence;
  };
</code>```

Body:
I'm developing a simple react app to show rasa HTTP api results data, and I want to tag the entities in a sentence. My code works good for 1 word entity but breaks with 2 words (only the first word is highlighted)

This is what I'm doing

  const [colors, setColors] = useState([
    "salmon",
    "primary",
    "purple",
    "orange"
  ]);

  const tagSentence = () => {
    let sentence = props.data.text;
    const entities = props.data.entities;

    entities.map((e, eIndex) => {
      sentence = sentence.replace(e.value, `<${eIndex}>${e.value}`);
    });
    return sentence.split(" ");
  };

          <Typography variant="h5" component="h2">
            {props.data.entities.map(t => {
              if (t.value.includes("<")) {
                return (
                  <Chip
                    key={t.value}
                    label={t.slice(3, t.length)}
                    color="primary"
                    style={{ backgroundColor: colors[t.slice(1, 2)] }}
                  />
                );
              } else {
                return ` ${t} `;
              }
            })}
          </Typography>

Entities object has the index of start and end of the words , but I cant figure out how to use it.

Example sentence :

Peter is my best friend

{
"text" : "peter is my best friend"
"entities" : [{"entity": "PERSON", "value": "peter", "start": 1, "end": 5...}]
}

EDIT:

Ended with this, now looking how to make whole word includes in JS

          <Typography variant="h5" component="h2">
            {props.data.text.split(" ").map((s, sIndex) => {
              return props.data.entities.map((e, eIndex) => {
                if (e.value.includes(s)) {
                  return (
                    <Chip
                      key={s}
                      label={s}
                      style={{ backgroundColor: colors[sIndex] }}
                      color="primary"
                    />
                  );
                } else {
                  return ` ${s} `;
                }
              });
            })}
          </Typography>

Body:
I finally used https://github.com/iansinnott/react-string-replace to easily replace  strings with components, worked like a charm.

  const tagSentence = () => {
    let sentence = props.data.text;
    props.data.entities.forEach((e, eIndex) => {
      sentence = reactStringReplace(sentence, e.value, (match, i) => (
        <Chip
          key={i}
          label={match}
          style={{ backgroundColor: colors[eIndex] }}
          color="primary"
        />
      ));
    });
    return sentence;
  };


问:
How disable row selection when using Ctrl + Shift+ Up or Down key in xamdatagrid?
I have a grid in which if I press Ctrl+Shift+Down or up, the xamdatagrid selects the row until the column in next/previous row. How do I disable the selection of row when these keys are down?</p>

答:
You could handle the PreviewKeyDown event:

```<code>xamDataGrid1.PreviewKeyDown += (s, e) =>
{
    if ((e.Key == Key.Down || e.Key == Key.Up)
        && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
    {
        e.Handled = true;
        MessageBox.Show("CTRL + SHIFT + Up/Down detected!");
    }
};
</code>```

Body:
You could handle the PreviewKeyDown event:

xamDataGrid1.PreviewKeyDown += (s, e) =>
{
    if ((e.Key == Key.Down || e.Key == Key.Up)
        && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
    {
        e.Handled = true;
        MessageBox.Show("CTRL + SHIFT + Up/Down detected!");
    }
};


问:
Optimized projection of a matrix orthogonaly to a vector with Numpy
I need to make all other columns of a matrix A orthogonal to one of its column j.

I use the following algorithm :

```<code># Orthogonalize with selected column
for i in remaining_cols:
    A[:,i] = A[:,i] - A[:,j] * np.dot(A[:,i], A[:,j]) / np.sum(A[:,j]**2)
</code>```

The idea comes from the QR decomposition with the Gram-Schmidt process.

But this code is not optimized and unstable because of the Gram-Schmidt process.

Does Numpy provide any method to compute the orthogonal projection of those vectors ?

With Householder Matrix

I heard that the Householder Reflectors are used in numpy.linalg.qr. This would allow me to compute an orthogonal matrix Q so that

```<code>Q * A[:,j] = [0 ... 0 1 0 ... 0]
                      |
                 j_th coordinate
</code>```

I would only have to ignore the line j and multiply back with Q.T.

Is there a method to obtain the Householder Matrix with Numpy ? I mean without coding the algorithm by hand.

Body:
I need to make all other columns of a matrix A orthogonal to one of its column j.

I use the following algorithm :

# Orthogonalize with selected column
for i in remaining_cols:
    A[:,i] = A[:,i] - A[:,j] * np.dot(A[:,i], A[:,j]) / np.sum(A[:,j]**2)

The idea comes from the QR decomposition with the Gram-Schmidt process.

But this code is not optimized and unstable because of the Gram-Schmidt process.

Does Numpy provide any method to compute the orthogonal projection of those vectors ?

With Householder Matrix

I heard that the Householder Reflectors are used in numpy.linalg.qr. This would allow me to compute an orthogonal matrix Q so that

Q * A[:,j] = [0 ... 0 1 0 ... 0]
                      |
                 j_th coordinate

I would only have to ignore the line j and multiply back with Q.T.

Is there a method to obtain the Householder Matrix with Numpy ? I mean without coding the algorithm by hand.

Body:
IIUC, here could be a vectorized way:

np.random.seed(10)
B = np.random.rand(3,3)

col = 0
remaining_cols = [1,2]

#your method
A = B.copy()
for i in remaining_cols:
    A[:,i] = A[:,i] - A[:,col] * np.dot(A[:,i], A[:,col]) / np.sum(A[:,col]**2)
print (A)
[[ 0.77132064 -0.32778252  0.18786796]
 [ 0.74880388  0.16014712 -0.2079702 ]
 [ 0.19806286  0.67103261  0.05464156]]

# vectorize method
A = B.copy()
A[:,remaining_cols] -= (A[:,col][:,None] * np.sum(A[:,remaining_cols]* A[:,col][:,None], axis=0)
                                              / np.sum(A[:,col]**2))

print (A) #same result
[[ 0.77132064 -0.32778252  0.18786796]
 [ 0.74880388  0.16014712 -0.2079702 ]
 [ 0.19806286  0.67103261  0.05464156]]


问:
change most significant bit of an 8 bit binary to 0 and get the decimal value of first seven bits only
I have a binary number and i want to get the decimal value of only the seven bits and not include the 8th bit. How do i go about this in java.

eg. 130 as binary => 10000010, I only need 00000010 =>2 ,ie, change only the most significant bit to 0.

Please help.

答:
Use a bit-mask:</p>

```<code>int y = x & 0x7F;
</code>```

Body:
Use a bit-mask:

int y = x & 0x7F;


问:
How to convert between vector_float2 and CGPoint*?
What's the easiest/fastest way to convert between vector_float2 and CGPoint* in Objective-C?

Does Apple provide any built-in functionality for this kind of type conversion? I noticed in 2-3 places in sample apps they just call CGPointMake() etc. to make the conversion

Is it possible to simply cast a CGPoint* to vector_float2 and vice versa? Is it safe to do so?

Update: obviously the solution is:

```<code>vector_float2 v = (vector_float2){(float)point.x, (float)point.y};
CGPoint p = CGPointMake(v.x, v.y);
</code>```

But this is cumbersome if you need to do so frequently, and more so if there's a C array of either vector_float2* or CGPoint*. So I'm looking for already-existing solutions or very simple alternatives that I may be overlooking.

答:
Example:</p>

```<code>CGPoint p                   = CGPointMake(1.0f, 1.0f);
vector_float2 v             = simd_make_float2(p.x, p.y);
CGPoint x                   = CGPointMake(v[0], v[1]);
</code>```

Body:
What's the easiest/fastest way to convert between vector_float2 and CGPoint* in Objective-C?

Does Apple provide any built-in functionality for this kind of type conversion? I noticed in 2-3 places in sample apps they just call CGPointMake() etc. to make the conversion

Is it possible to simply cast a CGPoint* to vector_float2 and vice versa? Is it safe to do so?

Update: obviously the solution is:

vector_float2 v = (vector_float2){(float)point.x, (float)point.y};
CGPoint p = CGPointMake(v.x, v.y);

But this is cumbersome if you need to do so frequently, and more so if there's a C array of either vector_float2* or CGPoint*. So I'm looking for already-existing solutions or very simple alternatives that I may be overlooking.

Body:
Example:

CGPoint p                   = CGPointMake(1.0f, 1.0f);
vector_float2 v             = simd_make_float2(p.x, p.y);
CGPoint x                   = CGPointMake(v[0], v[1]);


问:
How can I use "weak" correctly?? or C function overriding
I want to use __attribute__((weak)) correctly, for function overriding.

My code does not work as I expected.  What's wrong with it?

common.h

```<code>#include <stdio.h>

int __attribute__((weak)) doJob1(void);
int __attribute__((weak)) doJob2(int, int);

typedef int (*Job1)(void);
typedef int (*Job2)(int, int);
</code>```

common.c

```<code>#include <stdio.h>
#include "common.h"

__attribute__((weak)) int doJob1(void)
{
        printf("doJob1 common WEAK\n");
        return 0;
}

__attribute__((weak)) int doJob2(int a, int b)
{
        printf("doJob2 common WEAK\n");
        return 0;
}
</code>```

driverA.c

```<code>#include <stdio.h>
#include "common.h"

int doJob1(void)
{
        printf("doJob1 driverA Strong\n");
}

void main()
{
        Job1 j1 = doJob1;
        Job2 j2 = doJob2;

        j1();
        j2(0, 0);
}
</code>```

When I run the program, I see:

```<code>sh> ./a.out
doJob1 common WEAK
doJob2 common WEAK
</code>```

I expected this result, instead:

```<code>sh> ./a.out
doJob1 driverA Strong
doJob2 common WEAK
</code>```

How can I obtain the expected result?

Overall, there are many functions of the form "Job1", "Job2"..."JobXX".
driverA wants to use its own functions for few jobs and common functions for for some jobs, and some functions will be NULL:

```<code>ex>
Job1 - driverA_Job1
Job2 - common Job2
Job3 - NULL
..
</code>```

A different driver, say driverB, may make different choices:

```<code>Job1 - common job1
job2 - B's own job2
job5 - NULL
</code>```

How can I override functions correctly?

答:
This is happening because the __attribute__((weak)) declaration in the common.h header file applies to BOTH definitions; the one in common.c (which you intend to be weak) and also the definition in driverA.c (which you intend to be strong).

To get the behavior you want, apply the __attribute__((weak)) only in common.c, and not in the header file.

Body:
I want to use __attribute__((weak)) correctly, for function overriding.

My code does not work as I expected.  What's wrong with it?

common.h

#include <stdio.h>

int __attribute__((weak)) doJob1(void);
int __attribute__((weak)) doJob2(int, int);

typedef int (*Job1)(void);
typedef int (*Job2)(int, int);

common.c

#include <stdio.h>
#include "common.h"

__attribute__((weak)) int doJob1(void)
{
        printf("doJob1 common WEAK\n");
        return 0;
}

__attribute__((weak)) int doJob2(int a, int b)
{
        printf("doJob2 common WEAK\n");
        return 0;
}

driverA.c

#include <stdio.h>
#include "common.h"

int doJob1(void)
{
        printf("doJob1 driverA Strong\n");
}

void main()
{
        Job1 j1 = doJob1;
        Job2 j2 = doJob2;

        j1();
        j2(0, 0);
}

When I run the program, I see:

sh> ./a.out
doJob1 common WEAK
doJob2 common WEAK

I expected this result, instead:

sh> ./a.out
doJob1 driverA Strong
doJob2 common WEAK

How can I obtain the expected result?

Overall, there are many functions of the form "Job1", "Job2"..."JobXX".
driverA wants to use its own functions for few jobs and common functions for for some jobs, and some functions will be NULL:

ex>
Job1 - driverA_Job1
Job2 - common Job2
Job3 - NULL
..

A different driver, say driverB, may make different choices:

Job1 - common job1
job2 - B's own job2
job5 - NULL

How can I override functions correctly?


答:
If you want to see the rows associated with duplicate attachment titles, you can use window functions:</p>

```<code>SELECT c.*  -- or whatever columns you want
FROM (SELECT c.*, COUNT(*) OVER (PARTITION BY TITLE) as cnt
      FROM CONTENT c
      WHERE CONTENTTYPE = 'ATTACHMENT'
     ) c
WHERE cnt >= 2;
</code>```

Title: JOIN TWO SQL Queries in MS SQL

Body:
I am looking for some help combining two queries:

The first:

SELECT TITLE,
       count(TITLE) as DUPLICATES
FROM CONTENT
WHERE CONTENTTYPE = 'ATTACHMENT' GROUP BY TITLE having count(TITLE) > 1

The second is just

SELECT CONTENTID,
       TITLE
FROM CONTENT

I wanted to see CONTENTID as part of the first query, but I was not sure how to do that.  The two queries are against the same table, CONTENT.

Body:
If you want to see the rows associated with duplicate attachment titles, you can use window functions:

SELECT c.*  -- or whatever columns you want
FROM (SELECT c.*, COUNT(*) OVER (PARTITION BY TITLE) as cnt
      FROM CONTENT c
      WHERE CONTENTTYPE = 'ATTACHMENT'
     ) c
WHERE cnt >= 2;


问:
Query to find accounts with specified months
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH
</code>```

I am still getting account ids which where in JULY

答:
```<code>SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE MONTH(DATA_MONTH)  BETWEEN 5  AND  6
GROUP BY Year(DATA_MONTH),month(DATA_MONTH)
</code>```

Body:
I Want to extract those account ids which are present in may and JUNE but not in JULY . I have data for 6 months

i have tried using CONDITION(AND/ NOT)

SELECT ACCOUNT_ID, DATA_MONTH
FROM DATA1
WHERE DATA_MONTH ='01-MAY-18' AND DATA_MONTH <> '01-JULY-18
GROUP BY DATA_MONTH

I am still getting account ids which where in JULY


问:
What does datatype "S7" mean
Use the following command, the s.dtype will be 'S7', what does 'S7' means?

I have Googled, but only a Japanese website with failed link

I have read the Document in numpy, no luck

```<code>>>> strings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])
>>> s = strings[[0,1]]
>>> s.dtype
dtype('S7')
</code>```

Thanks for your help

答:
The dtype object describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes different aspects of the data such as:

Type of data

Size of the data

Byte order of the data etc.

Here, 'S7' means that the object is of type string and it's size(no. of bytes) is 7. You can confirm this by calling the 'itemsize' attribute for s.

```<code>>>>s.itemsize
7
</code>```

Title: What does datatype "S7" mean

Body:
Use the following command, the s.dtype will be 'S7', what does 'S7' means?

I have Googled, but only a Japanese website with failed link

I have read the Document in numpy, no luck

>>> strings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat'])
>>> s = strings[[0,1]]
>>> s.dtype
dtype('S7')

Thanks for your help

Body:
The dtype object describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes different aspects of the data such as:

Type of data

Size of the data

Byte order of the data etc.

Here, 'S7' means that the object is of type string and it's size(no. of bytes) is 7. You can confirm this by calling the 'itemsize' attribute for s.

>>>s.itemsize
7


答:
```<code>SELECT min(CONTENTID) as CONTENTID, TITLE, count(TITLE) as DUPLICATES
FROM CONTENT
WHERE CONTENTTYPE = 'ATTACHMENT'
GROUP BY TITLE
HAVING count(TITLE) > 1
</code>```

Title: JOIN TWO SQL Queries in MS SQL


问:
why scrollview with views is not able to scroll to till last?
I am adding UIScrollView in storyboard with all sides(trailing,leading,top,bottom) constraints. I have added a contentView inside a UIScrollView added constraints all sides(trailing,leading,top,bottom) and Equal width and Heights to SuperView(not scrollView) and changed height constraint priority to 250.

I have kept 3 views insdie content view for all views I have mentioned height and 3 sides(except bottom) but for last view I have kept all four sides and height.

But why i am not able to scroll till last view bottom.

]2

答:
You give the contentView equal height constraint to main view ( Remove it )

While you should hook subviews of it so the scrollView will scroll according to the current content


问:
"No such module" when using @testable in Xcode Unit tests
I recently updated to Xcode 7 beta 5. I tried adding a unit test to an earlier project, but I am getting the error message "No such module [myModuleName]" on the @testable import myModuleName line.

I tried

cleaning the project with Option Clean Build Folder

checking that "Enable Testability" (debug) was set to Yes in the Build Options

deleting the tests target and then re-adding the iOS Unit testing bundle

None of this worked for this project (but I have gotten testing to work in another project). Has anyone else had this problem and solved it?

答:
After spending couple of days on this issues finally I make it to work with my project. Problem was in Bridging Header - path in Tests target can't be empty if you are using Bridging Header in your main target

Hope it will save some time for someone.


问:
Eager load a relationship with subquery join
i have to join a table that has relations with another table and return the result to my view in readable data and display the correct data for each user. This is my code in the controller.

This works but the data from the relations are missing, what am i doing wrong?

```<code>    $GetUsers = User::groupBy('id');

    $all = OngoingTasks::with(['tasksdata', 'taskstatus'])->joinSub($GetUsers, 'users', function ($join) {
        $join->on('ongoing_tasks.user_id', '=', 'users.id');
    })->get();
</code>```

OngoingTasks has a One to Many relation with taskstatus and a One to One relation with taskdata.

User has a One to many with OngoingTasks.

答:
If an OngoingTask belongs to one user then in the OngoingTask model add this:

```<code>public function user()
{
    return $this->belongsTo(User::class);
}
</code>```

And you can change the query to this:

```<code>OngoingTasks::with(['tasksdata', 'taskstatus', 'user'])->get();
</code>```

If you want to get OngoingTasks based on the user ids even though the approach above would do the same, but just in case you filter for couple of users, do this instead:

```<code>$userIds = User::pluck('id');

$all = OngoingTasks::with(['tasksdata', 'taskstatus', 'user'])->whereIn('user_id', $userIds)->get();
</code>```

Body:
i have to join a table that has relations with another table and return the result to my view in readable data and display the correct data for each user. This is my code in the controller.

This works but the data from the relations are missing, what am i doing wrong?

    $GetUsers = User::groupBy('id');

    $all = OngoingTasks::with(['tasksdata', 'taskstatus'])->joinSub($GetUsers, 'users', function ($join) {
        $join->on('ongoing_tasks.user_id', '=', 'users.id');
    })->get();

OngoingTasks has a One to Many relation with taskstatus and a One to One relation with taskdata.

User has a One to many with OngoingTasks.

Body:
If an OngoingTask belongs to one user then in the OngoingTask model add this:

public function user()
{
    return $this->belongsTo(User::class);
}

And you can change the query to this:

OngoingTasks::with(['tasksdata', 'taskstatus', 'user'])->get();

If you want to get OngoingTasks based on the user ids even though the approach above would do the same, but just in case you filter for couple of users, do this instead:

$userIds = User::pluck('id');

$all = OngoingTasks::with(['tasksdata', 'taskstatus', 'user'])->whereIn('user_id', $userIds)->get();


问:
Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)?
I have a class in system-C with some data members as such:

```<code>long double x[8];
</code>```

I'm initializing it in the construction like this:

```<code>for (i = 0; i < 8; ++i) {
    x[i] = 0;
}
</code>```

But the first time I use it in my code I have garbage there.

Because of the way the system is built I can't connect a debugger easily.  Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?

Edit:
@Prakash:
Actually, this is a typo in the question, but not in my code...  Thanks!

答:
Sure, it will be garbage!

The code should have been as

```<code>for (i = 0; i < 8; ++i) {
    x[i] = 0;
}
</code>```

EDIT: Oops, Sorry for underestimating ;)

OwnerDisplayName: Nathan Fellman

ContentLicense: CC BY-SA 2.5

Body:
I have a class in system-C with some data members as such:

long double x[8];

I'm initializing it in the construction like this:

for (i = 0; i < 8; ++i) {
    x[i] = 0;
}

But the first time I use it in my code I have garbage there.

Because of the way the system is built I can't connect a debugger easily.  Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?

Edit:
@Prakash:
Actually, this is a typo in the question, but not in my code...  Thanks!

LastEditorDisplayName: Nathan Fellman

Body:
Sure, it will be garbage!

The code should have been as

for (i = 0; i < 8; ++i) {
    x[i] = 0;
}

EDIT: Oops, Sorry for underestimating ;)

OwnerDisplayName: Prakash

LastEditorDisplayName: Prakash


问:
C# Manage windows events
I would like to delete an event from the Windows event log using C#.

Can anyone point me in the right direction of how to achieve this?

答:
Easy :).

But the removing is look like removing item from array, you need to make a copy of all array, except of item that you need to remove.

There is example, how to "remove each of item from log where item have non even index".

```<code>using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;

class EventLogEntryCollection_Item
{
    /// <summary>
    /// Prints all.
    /// </summary>
    /// <param name="myEventLogEntryCollection">My event log entry collection.</param>
    private static void PrintAll(EventLogEntryCollection myEventLogEntryCollection)
    {
        for (int i = 0; i < myEventLogEntryCollection.Count; i++)
        {
            Console.WriteLine("The Message of the EventLog is :"
               + myEventLogEntryCollection[i].Message);
        }
    }

    /// <summary>
    /// Creates the new log message.
    /// </summary>
    /// <param name="LogName">Name of the log.</param>
    /// <param name="message">The message.</param>
    private static void CreateNewLogMessage(string LogName, string message)
    {
        EventLog myEventLog = new EventLog();
        myEventLog.Source = LogName;
        myEventLog.WriteEntry(message);
        myEventLog.Close();
    }

    /// <summary>
    /// Mains this instance.
    /// </summary>
    public static void Main()
    {
        try
        {

            // Check if the source exists.
            if (!EventLog.SourceExists("MySource"))
            {
                // Create the source.
                // An event log source should not be created and immediately used.
                // There is a latency time to enable the source, it should be created
                // prior to executing the application that uses the source.
                EventLog.CreateEventSource("MySource", "MySource");
                Console.WriteLine("Creating EventSource");
                Console.WriteLine("Exiting, execute the application a second time to use the source.");
                Thread.Sleep(2000);
                // The source is created.  sleep to allow it to be registered.
            }

            string myLogName = EventLog.LogNameFromSourceName("MySource", ".");

            // Create a new EventLog object.
            EventLog myEventLog1 = new EventLog();
            myEventLog1.Log = myLogName;

            //Create test messages.
            myEventLog1.Clear();
            for (int i = 0; i < 20; i++)
            {
                CreateNewLogMessage("MySource", "The entry number is " + i);
            }

            // Obtain the Log Entries of "MyNewLog".
            EventLogEntryCollection myEventLogEntryCollection =
               myEventLog1.Entries;
            //myEventLog1.Close();
            Console.WriteLine("The number of entries in 'MyNewLog' = "
               + myEventLogEntryCollection.Count);

            // Copy the EventLog entries to Array of type EventLogEntry.
            EventLogEntry[] myEventLogEntryArray =
               new EventLogEntry[myEventLogEntryCollection.Count];
            myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0);

            Console.WriteLine("before deleting");
            // Display the 'Message' property of EventLogEntry.
            PrintAll(myEventLogEntryCollection);

            myEventLog1.Clear();

            Console.WriteLine("process deleting");
            foreach (EventLogEntry myEventLogEntry in myEventLogEntryArray)
            {
                //Console.WriteLine("The LocalTime the Event is generated is "
                // + myEventLogEntry.TimeGenerated + " ; " + myEventLogEntry.Message);
                if (myEventLogEntry.Index % 2 == 0)
                {
                    CreateNewLogMessage("MySource", myEventLogEntry.Message);
                }
            }

            Console.WriteLine("after deleting");
            PrintAll(myEventLogEntryCollection);

            myEventLog1.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception:{0}", e.Message);
        }
        Console.ReadKey();
    }
}
</code>```

OwnerDisplayName: Jade M

Title: C# Manage windows events

Body:
Easy :).

But the removing is look like removing item from array, you need to make a copy of all array, except of item that you need to remove.

There is example, how to "remove each of item from log where item have non even index".

using System;
using System.Collections;
using System.Diagnostics;
using System.Threading;

class EventLogEntryCollection_Item
{
    /// <summary>
    /// Prints all.
    /// </summary>
    /// <param name="myEventLogEntryCollection">My event log entry collection.</param>
    private static void PrintAll(EventLogEntryCollection myEventLogEntryCollection)
    {
        for (int i = 0; i < myEventLogEntryCollection.Count; i++)
        {
            Console.WriteLine("The Message of the EventLog is :"
               + myEventLogEntryCollection[i].Message);
        }
    }

    /// <summary>
    /// Creates the new log message.
    /// </summary>
    /// <param name="LogName">Name of the log.</param>
    /// <param name="message">The message.</param>
    private static void CreateNewLogMessage(string LogName, string message)
    {
        EventLog myEventLog = new EventLog();
        myEventLog.Source = LogName;
        myEventLog.WriteEntry(message);
        myEventLog.Close();
    }

    /// <summary>
    /// Mains this instance.
    /// </summary>
    public static void Main()
    {
        try
        {

            // Check if the source exists.
            if (!EventLog.SourceExists("MySource"))
            {
                // Create the source.
                // An event log source should not be created and immediately used.
                // There is a latency time to enable the source, it should be created
                // prior to executing the application that uses the source.
                EventLog.CreateEventSource("MySource", "MySource");
                Console.WriteLine("Creating EventSource");
                Console.WriteLine("Exiting, execute the application a second time to use the source.");
                Thread.Sleep(2000);
                // The source is created.  sleep to allow it to be registered.
            }

            string myLogName = EventLog.LogNameFromSourceName("MySource", ".");

            // Create a new EventLog object.
            EventLog myEventLog1 = new EventLog();
            myEventLog1.Log = myLogName;

            //Create test messages.
            myEventLog1.Clear();
            for (int i = 0; i < 20; i++)
            {
                CreateNewLogMessage("MySource", "The entry number is " + i);
            }

            // Obtain the Log Entries of "MyNewLog".
            EventLogEntryCollection myEventLogEntryCollection =
               myEventLog1.Entries;
            //myEventLog1.Close();
            Console.WriteLine("The number of entries in 'MyNewLog' = "
               + myEventLogEntryCollection.Count);

            // Copy the EventLog entries to Array of type EventLogEntry.
            EventLogEntry[] myEventLogEntryArray =
               new EventLogEntry[myEventLogEntryCollection.Count];
            myEventLogEntryCollection.CopyTo(myEventLogEntryArray, 0);

            Console.WriteLine("before deleting");
            // Display the 'Message' property of EventLogEntry.
            PrintAll(myEventLogEntryCollection);

            myEventLog1.Clear();

            Console.WriteLine("process deleting");
            foreach (EventLogEntry myEventLogEntry in myEventLogEntryArray)
            {
                //Console.WriteLine("The LocalTime the Event is generated is "
                // + myEventLogEntry.TimeGenerated + " ; " + myEventLogEntry.Message);
                if (myEventLogEntry.Index % 2 == 0)
                {
                    CreateNewLogMessage("MySource", myEventLogEntry.Message);
                }
            }

            Console.WriteLine("after deleting");
            PrintAll(myEventLogEntryCollection);

            myEventLog1.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception:{0}", e.Message);
        }
        Console.ReadKey();
    }
}

OwnerDisplayName: Avram


问:
How to redirect only homepage /index.php to / and not apply for orther page in Nginx?
I have a home page: homepage/index.php and admin page: homepage/admin/index.php. And I want to redirect only homepage from .index.php to non .index.php. I am tried with code:

It's redirect all to root domain.com. How can apply for homepage only? Thanks

This is for new Linux server, running MySQL 5, PHP 5, Nginx and Apache 2.

```<code>      rewrite ^(.*/)index\.(php?)$ $1 permanent;
    }
</code>```

I want to redirect only homepage.

答:
I tried your option but failed. I try the orther way: </p>

```<code>rewrite ^/index\.php?$ scheme://$host/ redirect;
</code>```

Body:
I have a home page: homepage/index.php and admin page: homepage/admin/index.php. And I want to redirect only homepage from .index.php to non .index.php. I am tried with code:

It's redirect all to root domain.com. How can apply for homepage only? Thanks

This is for new Linux server, running MySQL 5, PHP 5, Nginx and Apache 2.

      rewrite ^(.*/)index\.(php?)$ $1 permanent;
    }

I want to redirect only homepage.

Body:
I tried your option but failed. I try the orther way:

rewrite ^/index\.php?$ scheme://$host/ redirect;


问:
Why we need to use <uses-feature> attribute?
My question is related to camera. When an application needs to use the system camera, we create an intent with ACTION_IMAGE_CAPTURE action and add a permission like this in the manifest file.

```<code><uses-permission android:name="android.permission.CAMERA"/>
</code>```

But besides that, there is one such

```<code><uses-feature android:name="android.hardware.camera"/>
</code>```

What is it for? I read that if this line is written, then if the phone does not have a camera the application will not install. Is it true? And besides this, why do we need this?

And for what the line <uses-feature/> is generally responsible in manifest file?

答:
As a developer - lets ask this Question to ourself with respect to your app.

What will user do with my app whose phone does not have Camera?

If the answer to Above is "Not much" - then what is the point allowing user to install your app on phone if user can't do much with it? It is waste of time & Internet bandwidth for the user.

Also if user is really frustrated by eventually learning that this app is not much of use,  they may RATE your app poorly on Play Store.

Hence its there is <uses-feature/> option to protect both developers & users from above scenario.

Body:
My question is related to camera. When an application needs to use the system camera, we create an intent with ACTION_IMAGE_CAPTURE action and add a permission like this in the manifest file.

<uses-permission android:name="android.permission.CAMERA"/>

But besides that, there is one such

<uses-feature android:name="android.hardware.camera"/>

What is it for? I read that if this line is written, then if the phone does not have a camera the application will not install. Is it true? And besides this, why do we need this?

And for what the line <uses-feature/> is generally responsible in manifest file?


问:
Is the pumping lemma proof wrong from book <Introduction to the Theory of Computation>?
The proof for 'pumping lemma' from book <Introduction to the Theory of Computation> :

Pumping lemma: If A is a regular language, then there is a number p
(the pumping length) where if s is any string in A of length at least
p, then s may be divided into three pieces, s = xyz, satisfying the
following conditions:

for each i ≥ 0, xyiz ∈ A,

|y| > 0, and

|xy| ≤ p

Let M = (Q, Σ, δ, q1, F) be a DFA that recognizes A. We assign the
pumping length p to be the number of states of M. We show that any
string s in A of length at least p may be broken into the three pieces
xyz, satisfying our three conditions. What if no strings in A are of
length at least p? Then our task is even easier because the theorem
becomes vacuously true: Obviously the three conditions hold for all
strings of length at least p if there aren’t any such strings.

Question: the bold quote part, which I think is wrong. Because if no strings in A are of length at least p, then it is clearly not a regular language.

答:
There are two points to clarify here:

The pumping lemma states, "if a language is regular, then all strings of length at least p in that language have some properties." If your language doesn't have any strings of length at least p, the statement is vacuously true in the sense that there are no counterexamples. "If x, then y" is mathematically true if x is false. "If the moon is made of cheese, then I am the king of France" is a mathematically true statement. This is perhaps a little different from the way we typically use conditionals where we assume the hypothesis is typically (conditionally, hypothetically) true. But this is its formal meaning.

Any language whose strings have length not at least p has strings whose lengths are strictly less than p. Because the length of a string must be a nonnegative integer, this means there are finitely many lengths. Because each string length corresponds to finitely many possible strings over the language's alphabet, and a sum of finitely many finite terms must be finite, any such language must be finite. We know that finite languages must be regular, no matter what the pumping lemma says; in any event, the pumping lemma for regular languages doesn't concern itself with this case so whether what is says is true or false here is really irrelevant. It would be less confusing to simply say nothing for languages with shorter strings than to try to note that its claims are consistent for those cases as well.


问:
Use a ranged object for a loop
I'm searching for a certain header and saving it as a ranged object (FindEQ4). Now I want to use this header as a starting point for a dynamic ranged object. My question is, how can I get the information that Header 1 is in C5 and use it like Set TestR = .Range("C" & 5 + x)?

```<code> Sub FindCopyPasteV3()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ4 As Range
        Dim TestR As Range
        Dim x As Long

        Set FindEQ4 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        'I'm looking for something like TestR = .Range("FindEQ4" + x)
        'which works like Set TestR = .Range("C" & 5 + x)

    End With

End Sub
</code>```

答:
Using the .Columnor .Rowproperties for a Rangeobject:

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

    Dim FindEQ4  As Range
    Dim StartRow As Long
    Dim StartColumn As Long
    Dim TestR As Range

    With ThisWorkbook.Sheets("Sheet1")
        Set FindEQ4 = .Range("A1")
        StartRow = FindEQ4.Row + 1
        StartColumn = FindEQ4.Column
        Set TestR = .Cells(StartRow, StartColumn) 'A2
    End With

End Sub
</code>```

Title: Use a ranged object for a loop

Body:
I'm searching for a certain header and saving it as a ranged object (FindEQ4). Now I want to use this header as a starting point for a dynamic ranged object. My question is, how can I get the information that Header 1 is in C5 and use it like Set TestR = .Range("C" & 5 + x)?

 Sub FindCopyPasteV3()

    With Worksheets("Sheet1").Range("A:FF")

        Dim FindEQ4 As Range
        Dim TestR As Range
        Dim x As Long

        Set FindEQ4 = .Find(What:="Header 1", LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)

        'I'm looking for something like TestR = .Range("FindEQ4" + x)
        'which works like Set TestR = .Range("C" & 5 + x)

    End With

End Sub

Body:
Using the .Columnor .Rowproperties for a Rangeobject:

Option Explicit
Sub test()

    Dim FindEQ4  As Range
    Dim StartRow As Long
    Dim StartColumn As Long
    Dim TestR As Range

    With ThisWorkbook.Sheets("Sheet1")
        Set FindEQ4 = .Range("A1")
        StartRow = FindEQ4.Row + 1
        StartColumn = FindEQ4.Column
        Set TestR = .Cells(StartRow, StartColumn) 'A2
    End With

End Sub