问:
Attribute center print to console pygame
I am trying to print to the console in pygame, and here:

```<code>def drawPressKeyMsg(self):
    BASICFONT = pygame.font.Font("freesansbold.ttf", 18)
    pressKeySurf = BASICFONT.render("Press a key to play.", True, DARK_GREY)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (WINDOW_WIDTH - 200, WINDOW_HEIGHT - 30)
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
</code>```

I am able to use the .topleft but later in the code:

```<code>def showMenuScreen(self):
    menuFont = pygame.font.Font("freesansbold.ttf", 100)
    optionFont = pygame.font.Font("freesansbold.ttf", 50)
    menuSurf = menuFont.render("PONG GAME", True, WHITE, TURQUOISE)
    option1Surf = optionFont.render("Press 1 to play the game!", True, WHITE, TURQUOISE)
    option2Surf = optionFont.render("Press 2 to exit!", True, WHITE, TURQUOISE)
    menuRect = menuSurf.get_rect
    option1Rect = option1Surf.get_rect
    option2Rect = option2Surf.get_rect

    menuRect.center = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
    option1Rect.center = (WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2) - 25)
    option2Rect.center = (WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2) - 50)

    DISPLAYSURF.blit(menuSurf, menuRect)
    DISPLAYSURF.blit(option1Surf, option1Rect)
    DISPLAYSURF.blit(option2Surf, option2Rect)
</code>```

the .center displays the error "AttributeError: 'builtin_function_or_method' object has no attribute 'center'"

答: You forgot () in all get_rect() so it doesn't return Rect which have center but it returns reference to method get_rect and reference doesn't have center

Body:
I am trying to print to the console in pygame, and here:

def drawPressKeyMsg(self):
    BASICFONT = pygame.font.Font("freesansbold.ttf", 18)
    pressKeySurf = BASICFONT.render("Press a key to play.", True, DARK_GREY)
    pressKeyRect = pressKeySurf.get_rect()
    pressKeyRect.topleft = (WINDOW_WIDTH - 200, WINDOW_HEIGHT - 30)
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

I am able to use the .topleft but later in the code:

def showMenuScreen(self):
    menuFont = pygame.font.Font("freesansbold.ttf", 100)
    optionFont = pygame.font.Font("freesansbold.ttf", 50)
    menuSurf = menuFont.render("PONG GAME", True, WHITE, TURQUOISE)
    option1Surf = optionFont.render("Press 1 to play the game!", True, WHITE, TURQUOISE)
    option2Surf = optionFont.render("Press 2 to exit!", True, WHITE, TURQUOISE)
    menuRect = menuSurf.get_rect
    option1Rect = option1Surf.get_rect
    option2Rect = option2Surf.get_rect

    menuRect.center = (WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2)
    option1Rect.center = (WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2) - 25)
    option2Rect.center = (WINDOW_WIDTH / 2, (WINDOW_HEIGHT / 2) - 50)

    DISPLAYSURF.blit(menuSurf, menuRect)
    DISPLAYSURF.blit(option1Surf, option1Rect)
    DISPLAYSURF.blit(option2Surf, option2Rect)

the .center displays the error "AttributeError: 'builtin_function_or_method' object has no attribute 'center'"


来源: stackexchange

问:
Difference between Interface and Class in Java
As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.

```<code>package com.main.service;

public interface SomeService{
   public void someMethod();
}
</code>```

But why below code is allowed in Java?

```<code> com.main.service.SomeService.class;
</code>```

I am using this code to get beans from Spring application context like below:-

```<code> SomeService someservice = applicationContext
            .getBean(com.main.service.SomeService.class);
</code>```

答:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.

```<code>ClassLiteral:
TypeName {[ ]} . class
NumericType {[ ]} . class
boolean {[ ]} . class
void . class
</code>```

The type of C.class, where C is the name of a class, interface, or
  array type, is Class.

A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader  of the class of the current instance.

ContentLicense: CC BY-SA 3.0

Body:
As per multiple articles in Java Interface and Class are completely different. Let me write an Interface.

package com.main.service;

public interface SomeService{
   public void someMethod();
}

But why below code is allowed in Java?

 com.main.service.SomeService.class;

I am using this code to get beans from Spring application context like below:-

 SomeService someservice = applicationContext
            .getBean(com.main.service.SomeService.class);

Body:
A class literal is an expression consisting of the name of a class, interface, array, or primitive type, or the pseudo-type void, followed by a '.' and the token class.

ClassLiteral:
TypeName {[ ]} . class
NumericType {[ ]} . class
boolean {[ ]} . class
void . class

The type of C.class, where C is the name of a class, interface, or
  array type, is Class.

A class literal evaluates to the Class object for the named type (or for void) as defined by the defining class loader  of the class of the current instance.


问:
How are constant expressions dealt with in c++ enum?
What is the range of a c++ enum with a constant expression? This is my code

```<code>#include <iostream>

int main(){
    enum e3{min = -10, max = 100000};
    e3 x = e3(-1000);
    e3 y= e3(-100000912241);
    std::cout<<x<<" "<<y<<std::endl;
}
</code>```

It outputs -1000 -1216664433

How is this happening?
Also, The C++ programming language by Bjarne Stroustrup specifies that the result of conversion of integral type to enumeration is undefined unless the value is the within the range of the enumeration. What is this range and how to calculate it?

答:
The range of an enum is the range of the underlying type. The compiler has probably selected an int as the underlying type of your enum.

It's allowed to do that since an int (assuming it's 32 bit on your platform) can contain all the explicit values you've given it.

You'll probably find that the type of -100000912241 is a long or a long long on your platform (note there is no such thing as a negative literal in C++: -100000912241 is the unary negation of the literal 100000912241.). But -100000912241 can't fit into that int, so the behaviour of your code is undefined.

If you want to inspect the underlying type of an enum, then use std::underlying_type.

Reference: http://en.cppreference.com/w/cpp/types/underlying_type

Body:
What is the range of a c++ enum with a constant expression? This is my code

#include <iostream>

int main(){
    enum e3{min = -10, max = 100000};
    e3 x = e3(-1000);
    e3 y= e3(-100000912241);
    std::cout<<x<<" "<<y<<std::endl;
}

It outputs -1000 -1216664433

How is this happening?
Also, The C++ programming language by Bjarne Stroustrup specifies that the result of conversion of integral type to enumeration is undefined unless the value is the within the range of the enumeration. What is this range and how to calculate it?


问:
How detect my std::function is still available?
Im using std::function and std::bind for my async thread callback system.
but sometimes my system delete my object even some threads are not done.
here some example code

```<code>#include <iostream>
#include <functional>

using namespace std;

class Character {
public:
    Character() { a = 10; }

    void Print() { cout << a << endl; }

private:
    int a;

};

void main() {
    Character* pChar = new Character();

    std::function<void()> callback = std::bind(&Character::Print, pChar);
    callback(); // it's fine

    delete pChar;

    callback(); // fail

    if (callback)   // this if doesn't work
        callback();

    // i want to check callback is still available
}
</code>```

please help me to do this.

答: This is because you are deleting pChar* pointer which is used in your callback() method. Delete pChar after you are done with everything.

Body:
Im using std::function and std::bind for my async thread callback system.
but sometimes my system delete my object even some threads are not done.
here some example code

#include <iostream>
#include <functional>

using namespace std;

class Character {
public:
    Character() { a = 10; }

    void Print() { cout << a << endl; }

private:
    int a;

};

void main() {
    Character* pChar = new Character();

    std::function<void()> callback = std::bind(&Character::Print, pChar);
    callback(); // it's fine

    delete pChar;

    callback(); // fail

    if (callback)   // this if doesn't work
        callback();

    // i want to check callback is still available
}

please help me to do this.


问:
How to Autowired in ConversionService in springboot
Trying to access the ConversionControl in model in springboot, no luck.

```<code>@Component
public class CityHelperService  {

    @Autowired
    ConversionService conversionService;// = ConversionServiceFactory.registerConverters();

    public City toEntity(CityDTO dto){
        City entity = conversionService.convert(dto, City.class);
        return entity;
    }

    public CityDTO toDTO(City entity){
        CityDTO dto = conversionService.convert(entity, CityDTO.class);
        return dto;
    }
}
</code>```

It shows the following error:

```<code>Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.lumiin.mytalk.model.CityModel com.lumiin.mytalk.controllers.CityController.cityModel;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cityModel' defined in file : Unsatisfied dependency expressed through constructor argument with index 1 of type [com.lumiin.mytalk.dao.CityHelperService]: : Error creating bean with name 'cityHelperService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.core.convert.ConversionService com.lumiin.mytalk.dao.CityHelperService.conversionService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cityHelperService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.core.convert.ConversionService com.lumiin.mytalk.dao.CityHelperService.conversionService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code>```

答:
Not totally agreed with the accepted answers, because there would be a default ConverstionService named mvcConversionService so you would get duplicate bean exception. Instead addConverter to FormatterRegistry, here is the link for the part answer:

Java Config equivalent for conversionService / FormattingConversionServiceFactoryBean

Also you would need (in some cases) to define to at least an empty Component for ConversionService, something like below:

```<code>@Component @Primary
public class MyConversionService extends DefaultConversionService implements ConversionService {
    // an empty ConversionService to initiate call to register converters
}
</code>```

This is to force spring container to initiate a call to:

```<code>class WebMvcConfigurerAdapter {
    ...

    public void addFormatters(FormatterRegistry registry) {
         //registry.addConverter(...);
    }
}
</code>```

Body:
Trying to access the ConversionControl in model in springboot, no luck.

@Component
public class CityHelperService  {

    @Autowired
    ConversionService conversionService;// = ConversionServiceFactory.registerConverters();

    public City toEntity(CityDTO dto){
        City entity = conversionService.convert(dto, City.class);
        return entity;
    }

    public CityDTO toDTO(City entity){
        CityDTO dto = conversionService.convert(entity, CityDTO.class);
        return dto;
    }
}

It shows the following error:

Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.lumiin.mytalk.model.CityModel com.lumiin.mytalk.controllers.CityController.cityModel;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cityModel' defined in file : Unsatisfied dependency expressed through constructor argument with index 1 of type [com.lumiin.mytalk.dao.CityHelperService]: : Error creating bean with name 'cityHelperService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.core.convert.ConversionService com.lumiin.mytalk.dao.CityHelperService.conversionService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)};
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cityHelperService': Injection of autowired dependencies failed;
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.springframework.core.convert.ConversionService com.lumiin.mytalk.dao.CityHelperService.conversionService;
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.core.convert.ConversionService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Body:
Not totally agreed with the accepted answers, because there would be a default ConverstionService named mvcConversionService so you would get duplicate bean exception. Instead addConverter to FormatterRegistry, here is the link for the part answer:

Java Config equivalent for conversionService / FormattingConversionServiceFactoryBean

Also you would need (in some cases) to define to at least an empty Component for ConversionService, something like below:

@Component @Primary
public class MyConversionService extends DefaultConversionService implements ConversionService {
    // an empty ConversionService to initiate call to register converters
}

This is to force spring container to initiate a call to:

class WebMvcConfigurerAdapter {
    ...

    public void addFormatters(FormatterRegistry registry) {
         //registry.addConverter(...);
    }
}


问:
Is JHipster UAA enable to make user federation
I am studying JHipster architecture with some excitations. But now a question come up to me: is JHipster UAA server able to integrate to my already created LDAP directory server doing federation (Let's say Active Directory)?

Best Regards,

-Rod

答: Did you look at the documentation about LDAP here ?</p>


问:
Calculating population density in Mapbox.js
I've been trying to color in a layer based on population density and I'm running into some problems. I have two properties in the layer, Area ('ALAND') and population ('B01001_001') that I'd like to use to calculate population density and then use that to fill in. Here's my attempt:

```<code>map.setPaintProperty('fullcitylayer', 'fill-color', ['interpolate', interpolation: ['linear'], input:['/', ['get', 'B19001_017'], ['/',['get', 'ALAND'],1000000]], stop_input1: 10, stop_output1: '#00adef', stop_input2: 100, stop_output2: '#212529', stop_input3: 1000, stop_output3: '#ea950b', stop_input4: 5000, stop_output4: '#e94e34'] )
</code>```

For some reason I keep getting a syntax error when I attempt to run this. Any idea why?

答:
Copied over from the github issue I answered your question:

You still have to write valid JavaScript in order to make expressions work

Your issue is with lines like ['interpolation', interpolation: ['linear'], ...]. You can't "label" the array items like this, their purpose is already determined by the position in the array/expression. Expressions always take the form of [<operator>, <arg1>, <arg2>, <argN>, ...]. So your expression should look something like this:

```<code>[
  'interpolate',
  ['linear'],
  ['/', ['get', 'B19001_017'], ['/', ['get', 'ALAND'], 1000000]],
  10,
  '#00adef',
  100,
  '#212529',
  1000,
  '#ea950b',
  5000,
  '#e94e34'
];
</code>```

Body:
I've been trying to color in a layer based on population density and I'm running into some problems. I have two properties in the layer, Area ('ALAND') and population ('B01001_001') that I'd like to use to calculate population density and then use that to fill in. Here's my attempt:

map.setPaintProperty('fullcitylayer', 'fill-color', ['interpolate', interpolation: ['linear'], input:['/', ['get', 'B19001_017'], ['/',['get', 'ALAND'],1000000]], stop_input1: 10, stop_output1: '#00adef', stop_input2: 100, stop_output2: '#212529', stop_input3: 1000, stop_output3: '#ea950b', stop_input4: 5000, stop_output4: '#e94e34'] )

For some reason I keep getting a syntax error when I attempt to run this. Any idea why?

Body:
Copied over from the github issue I answered your question:

You still have to write valid JavaScript in order to make expressions work

Your issue is with lines like ['interpolation', interpolation: ['linear'], ...]. You can't "label" the array items like this, their purpose is already determined by the position in the array/expression. Expressions always take the form of [<operator>, <arg1>, <arg2>, <argN>, ...]. So your expression should look something like this:

[
  'interpolate',
  ['linear'],
  ['/', ['get', 'B19001_017'], ['/', ['get', 'ALAND'], 1000000]],
  10,
  '#00adef',
  100,
  '#212529',
  1000,
  '#ea950b',
  5000,
  '#e94e34'
];


问:
Reduce size of Rating Bar in Android Studio
Below is my rating bar which I need to reduce its size. Please help me!</p>

```<code><RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar"
    android:numStars="3"
    android:stepSize="0.1"
    android:isIndicator="true"
    android:layout_below="@+id/textView15"
    android:layout_alignLeft="@+id/textView15"
    android:layout_alignStart="@+id/textView15"
    android:layout_alignBottom="@+id/imageView"
    android:layout_alignRight="@+id/textView15"
    android:layout_alignEnd="@+id/textView15" />
</code>```

答:
Scale it down and add a negative bottom margin as the rating bar will stil take up its full size space.</p>

```<code>                            <RatingBar
                                android:id="@+id/ratingBar"
                                android:layout_width="wrap_content"
                                android:layout_height="50dp"
                                android:layout_marginBottom="-26dp"
                                android:numStars="5"
                                android:stepSize="0.1"
                                android:theme="@style/RatingBar"
                                android:rating="3.5"
                                android:scaleX=".5"
                                android:scaleY=".5"
                                android:transformPivotX="0dp"
                                android:transformPivotY="0dp"
                                android:isIndicator="true" />
</code>```

Body:
Below is my rating bar which I need to reduce its size. Please help me!

<RatingBar
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/ratingBar"
    android:numStars="3"
    android:stepSize="0.1"
    android:isIndicator="true"
    android:layout_below="@+id/textView15"
    android:layout_alignLeft="@+id/textView15"
    android:layout_alignStart="@+id/textView15"
    android:layout_alignBottom="@+id/imageView"
    android:layout_alignRight="@+id/textView15"
    android:layout_alignEnd="@+id/textView15" />

Body:
Scale it down and add a negative bottom margin as the rating bar will stil take up its full size space.

                            <RatingBar
                                android:id="@+id/ratingBar"
                                android:layout_width="wrap_content"
                                android:layout_height="50dp"
                                android:layout_marginBottom="-26dp"
                                android:numStars="5"
                                android:stepSize="0.1"
                                android:theme="@style/RatingBar"
                                android:rating="3.5"
                                android:scaleX=".5"
                                android:scaleY=".5"
                                android:transformPivotX="0dp"
                                android:transformPivotY="0dp"
                                android:isIndicator="true" />


问:
tensorflow set pre-weights gives dimension error
I'm a tensorflow newbie. I want to build a vgg-16 network then use that to modify the network.

So far I'm stucked at layer 1 here is what I have:

```<code>def conv_layer(bottom, name, kernel):
    with tf.variable_scope(name):

        #net weight dictionary from caffe's version of caffe
        conv = tf.nn.conv2d(net.weights[name+'/w'], kernel, [1, 1, 1, 1], padding='SAME')

        conv_biases = tf.constant(net.weights[name+'/b'], name="biases")
        bias = tf.nn.bias_add(conv, conv_biases)

        relu = tf.nn.relu(bias)
        return relu

kernel1_1= tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32, stddev=1e-1), name='weights')
conv_layer(tf.cast(image_batch, tf.float32), "conv1_1", kernel1_1)
</code>```

The error I get is:

```<code> Dimensions must be equal, but are 64 and 3 for 'conv1_1_15/Conv2D' (op: 'Conv2D') with input shapes: [3,3,3,64], [3,3,3,64]
</code>```

This makes no sense to me

答:
I am not sure what net.weights contains, but assuming that has weights for your kernel it seems to me that you should be assigning those to the kernel variable.

```<code>conv = tf.nn.conv2d(net.weights[name+'/w'], kernel, [1, 1, 1, 1], padding='SAME')
</code>```

should be

```<code>conv = tf.nn.conv2d(bottom, kernel, [1, 1, 1, 1], padding='SAME')
</code>```

and once your network definition is done, you assign the weights to kernels and biases.

Body:
I'm a tensorflow newbie. I want to build a vgg-16 network then use that to modify the network.

So far I'm stucked at layer 1 here is what I have:

def conv_layer(bottom, name, kernel):
    with tf.variable_scope(name):

        #net weight dictionary from caffe's version of caffe
        conv = tf.nn.conv2d(net.weights[name+'/w'], kernel, [1, 1, 1, 1], padding='SAME')

        conv_biases = tf.constant(net.weights[name+'/b'], name="biases")
        bias = tf.nn.bias_add(conv, conv_biases)

        relu = tf.nn.relu(bias)
        return relu

kernel1_1= tf.Variable(tf.truncated_normal([3, 3, 3, 64], dtype=tf.float32, stddev=1e-1), name='weights')
conv_layer(tf.cast(image_batch, tf.float32), "conv1_1", kernel1_1)

The error I get is:

 Dimensions must be equal, but are 64 and 3 for 'conv1_1_15/Conv2D' (op: 'Conv2D') with input shapes: [3,3,3,64], [3,3,3,64]

This makes no sense to me

Body:
I am not sure what net.weights contains, but assuming that has weights for your kernel it seems to me that you should be assigning those to the kernel variable.

conv = tf.nn.conv2d(net.weights[name+'/w'], kernel, [1, 1, 1, 1], padding='SAME')

should be

conv = tf.nn.conv2d(bottom, kernel, [1, 1, 1, 1], padding='SAME')

and once your network definition is done, you assign the weights to kernels and biases.


问:
Jquery: What's faster? .text() or .attr('id')?
just wondering, which of these would be faster?

```<code>if ( $(this).text() == 'Test' )
{
    ...
}
</code>```

or

```<code>if ( $(this).attr('id') == 'Test' )
{
    ...
}
</code>```

or is there a faster way?

or are they both the same?

thanks

答: A simple test shows that they're almost equally fast. text() seems to be slightly faster.

ContentLicense: CC BY-SA 2.5

Body:
just wondering, which of these would be faster?

if ( $(this).text() == 'Test' )
{
    ...
}

or

if ( $(this).attr('id') == 'Test' )
{
    ...
}

or is there a faster way?

or are they both the same?

thanks


问:
Error in Running Docker image. Showing no module named cv2,request,boto3
```<code>#!/usr/bin/env python
from time import sleep
import datetime
import os
import shutil
import cv2
import io
import numpy as np
import glob
from threading import Thread
import urllib2
import requests
import json
import boto3
import datetime
</code>```

I am not able to run my script on docker as I am not able to run modules like cv2,numpy, requests and boto3. It works perfectly when I run it on terminal but when I run it as docker image it is showing error that no modules named ... How can i make it run on my docker?

Dockerfile:

```<code>FROM resin/raspberry-pi-python:latest
RUN mkdir /myscript
WORKDIR /myscript
COPY capturing.py .
CMD ["/myscript/capturing.py", "-flag"]
</code>```

答:
You can run your container:

```<code>docker run -it <image_name>
</code>```

and execute the following command in python console that will install specified packages in your container:

```<code>import os
os.system("pip install --upgrade pip")
os.system("pip install numpy requests boto3 opencv-python")
</code>```

You will see:

```<code>Collecting numpy
  Downloading numpy-1.13.3-cp36-cp36m-manylinux1_x86_64.whl (17.0MB)
    100% |████████████████████████████████| 17.0MB 124kB/s
Collecting requests
  Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
    100% |████████████████████████████████| 92kB 4.8MB/s
Collecting boto3
  Downloading boto3-1.4.7-py2.py3-none-any.whl (128kB)
    100% |████████████████████████████████| 133kB 3.4MB/s
Collecting opencv-python
  Downloading opencv_python-3.3.0.10-cp36-cp36m-manylinux1_x86_64.whl (15.4MB)
    100% |████████████████████████████████| 15.5MB 126kB/s
Collecting certifi>=2017.4.17 (from requests)
  Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB)
    100% |████████████████████████████████| 337kB 2.9MB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 4.4MB/s
Collecting idna<2.7,>=2.5 (from requests)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
    100% |████████████████████████████████| 61kB 6.0MB/s
Collecting urllib3<1.23,>=1.21.1 (from requests)
  Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
    100% |████████████████████████████████| 133kB 3.4MB/s
Collecting jmespath<1.0.0,>=0.7.1 (from boto3)
  Downloading jmespath-0.9.3-py2.py3-none-any.whl
Collecting s3transfer<0.2.0,>=0.1.10 (from boto3)
  Downloading s3transfer-0.1.11-py2.py3-none-any.whl (54kB)
    100% |████████████████████████████████| 61kB 6.4MB/s
Collecting botocore<1.8.0,>=1.7.0 (from boto3)
  Downloading botocore-1.7.46-py2.py3-none-any.whl (3.7MB)
    100% |████████████████████████████████| 3.7MB 535kB/s
Collecting python-dateutil<3.0.0,>=2.1 (from botocore<1.8.0,>=1.7.0->boto3)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
    100% |████████████████████████████████| 194kB 3.1MB/s
Collecting docutils>=0.10 (from botocore<1.8.0,>=1.7.0->boto3)
  Downloading docutils-0.14-py3-none-any.whl (543kB)
    100% |████████████████████████████████| 552kB 2.2MB/s
Collecting six>=1.5 (from python-dateutil<3.0.0,>=2.1->botocore<1.8.0,>=1.7.0->boto3)
  Downloading six-1.11.0-py2.py3-none-any.whl
Installing collected packages: numpy, certifi, chardet, idna, urllib3, requests, jmespath, six, python-dateutil, docutils, botocore, s3transfer, boto3, opencv-python
Successfully installed boto3-1.4.7 botocore-1.7.46 certifi-2017.11.5 chardet-3.0.4 docutils-0.14 idna-2.6 jmespath-0.9.3 numpy-1.13.3 opencv-python-3.3.0.10 python-dateutil-2.6.1 requests-2.18.4 s3transfer-0.1.11 six-1.11.0 urllib3-1.22
</code>```

So all is ok. I tested it in container built using FROM python:latest Dockerfile.

Body:
#!/usr/bin/env python
from time import sleep
import datetime
import os
import shutil
import cv2
import io
import numpy as np
import glob
from threading import Thread
import urllib2
import requests
import json
import boto3
import datetime

I am not able to run my script on docker as I am not able to run modules like cv2,numpy, requests and boto3. It works perfectly when I run it on terminal but when I run it as docker image it is showing error that no modules named ... How can i make it run on my docker?

Dockerfile:

FROM resin/raspberry-pi-python:latest
RUN mkdir /myscript
WORKDIR /myscript
COPY capturing.py .
CMD ["/myscript/capturing.py", "-flag"]

Body:
You can run your container:

docker run -it <image_name>

and execute the following command in python console that will install specified packages in your container:

import os
os.system("pip install --upgrade pip")
os.system("pip install numpy requests boto3 opencv-python")

You will see:

Collecting numpy
  Downloading numpy-1.13.3-cp36-cp36m-manylinux1_x86_64.whl (17.0MB)
    100% |████████████████████████████████| 17.0MB 124kB/s
Collecting requests
  Downloading requests-2.18.4-py2.py3-none-any.whl (88kB)
    100% |████████████████████████████████| 92kB 4.8MB/s
Collecting boto3
  Downloading boto3-1.4.7-py2.py3-none-any.whl (128kB)
    100% |████████████████████████████████| 133kB 3.4MB/s
Collecting opencv-python
  Downloading opencv_python-3.3.0.10-cp36-cp36m-manylinux1_x86_64.whl (15.4MB)
    100% |████████████████████████████████| 15.5MB 126kB/s
Collecting certifi>=2017.4.17 (from requests)
  Downloading certifi-2017.11.5-py2.py3-none-any.whl (330kB)
    100% |████████████████████████████████| 337kB 2.9MB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB)
    100% |████████████████████████████████| 143kB 4.4MB/s
Collecting idna<2.7,>=2.5 (from requests)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
    100% |████████████████████████████████| 61kB 6.0MB/s
Collecting urllib3<1.23,>=1.21.1 (from requests)
  Downloading urllib3-1.22-py2.py3-none-any.whl (132kB)
    100% |████████████████████████████████| 133kB 3.4MB/s
Collecting jmespath<1.0.0,>=0.7.1 (from boto3)
  Downloading jmespath-0.9.3-py2.py3-none-any.whl
Collecting s3transfer<0.2.0,>=0.1.10 (from boto3)
  Downloading s3transfer-0.1.11-py2.py3-none-any.whl (54kB)
    100% |████████████████████████████████| 61kB 6.4MB/s
Collecting botocore<1.8.0,>=1.7.0 (from boto3)
  Downloading botocore-1.7.46-py2.py3-none-any.whl (3.7MB)
    100% |████████████████████████████████| 3.7MB 535kB/s
Collecting python-dateutil<3.0.0,>=2.1 (from botocore<1.8.0,>=1.7.0->boto3)
  Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
    100% |████████████████████████████████| 194kB 3.1MB/s
Collecting docutils>=0.10 (from botocore<1.8.0,>=1.7.0->boto3)
  Downloading docutils-0.14-py3-none-any.whl (543kB)
    100% |████████████████████████████████| 552kB 2.2MB/s
Collecting six>=1.5 (from python-dateutil<3.0.0,>=2.1->botocore<1.8.0,>=1.7.0->boto3)
  Downloading six-1.11.0-py2.py3-none-any.whl
Installing collected packages: numpy, certifi, chardet, idna, urllib3, requests, jmespath, six, python-dateutil, docutils, botocore, s3transfer, boto3, opencv-python
Successfully installed boto3-1.4.7 botocore-1.7.46 certifi-2017.11.5 chardet-3.0.4 docutils-0.14 idna-2.6 jmespath-0.9.3 numpy-1.13.3 opencv-python-3.3.0.10 python-dateutil-2.6.1 requests-2.18.4 s3transfer-0.1.11 six-1.11.0 urllib3-1.22

So all is ok. I tested it in container built using FROM python:latest Dockerfile.

ContentLicense: CC BY-SA 4.0


问:
convert constexpr n-dimensional array of one type to constexpr n-dimensional array of a different type
Using C++11 or C++14:

I have a:

```<code>constexpr double [2][3][4] = some value;
</code>```

I want constexpr int [2][3][4] from this.

(Actually I will want constexpr my_type [2][3][4], but that should be trivially solvable once int works.)

The only solution I came up with was a container class with operator[] overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly std::array<std::array...>> without creating a new class?

I do not want the input to be std::array - that is a constraint of the system. The input must be C compatible. The converted array can be C++.

答:
Unfortunately, std::array::operator[] is not constexpr before C++17. Hence you probably need to come up with your own boilerplate.

Here is an example in C++17. If you export the "indices trick" into a separate function (instead of lambda) and implement your own version of std::array, then this approach should also work with C++14.

https://godbolt.org/g/FayqEn

```<code>#include <array>
#include <iostream>
#include <utility>

////////////////////////////////////////////////////////////////////////////////

template<size_t... is, class F>
constexpr decltype(auto) indexer(std::index_sequence<is...>, F f) {
  return f(std::integral_constant<std::size_t, is>{}...);
}

template<size_t N_, class F>
constexpr decltype(auto) indexer(F f) {
  constexpr size_t max_index_length = 4096;
  constexpr size_t N = std::min(N_, max_index_length);
  static_assert(N == N_, "");
  return indexer(std::make_index_sequence<N>{}, f);
}

////////////////////////////////////////////////////////////////////////////////

template<class T>
constexpr auto make_array(T val) {
  return val;
}

template<class NestedArrays, std::size_t N>
constexpr auto make_array(NestedArrays(&arr)[N]) {
  using NestedStdArrays = decltype(make_array(arr[0]));
  return indexer<N>([=] (auto... ns) {
    return std::array<NestedStdArrays, N>{
      make_array(arr[ns])...
    };
  });
}

////////////////////////////////////////////////////////////////////////////////

int main() {
  constexpr int input_from_c[1][3][2]{
    { {0, 10}, {20, 30}, {40, 50} }
  };

  constexpr auto nested_std_arrays = make_array(input_from_c);
  using NestedStdArrays = std::decay_t<decltype(nested_std_arrays)>;

  static_assert(
    std::is_same<
      NestedStdArrays,
      std::array<std::array<std::array<int, 2>, 3>, 1>
    >{}, ""
  );

  static_assert(0 == nested_std_arrays[0][0][0], "");
  static_assert(10 == nested_std_arrays[0][0][1], "");
  static_assert(20 == nested_std_arrays[0][1][0], "");
  static_assert(30 == nested_std_arrays[0][1][1], "");
  static_assert(40 == nested_std_arrays[0][2][0], "");
  static_assert(50 == nested_std_arrays[0][2][1], "");

  return 0;
}
</code>```

Body:
Using C++11 or C++14:

I have a:

constexpr double [2][3][4] = some value;

I want constexpr int [2][3][4] from this.

(Actually I will want constexpr my_type [2][3][4], but that should be trivially solvable once int works.)

The only solution I came up with was a container class with operator[] overloaded so it behaves like an array. Is there a way to keep standard array syntax? Or possibly std::array<std::array...>> without creating a new class?

I do not want the input to be std::array - that is a constraint of the system. The input must be C compatible. The converted array can be C++.

Body:
Unfortunately, std::array::operator[] is not constexpr before C++17. Hence you probably need to come up with your own boilerplate.

Here is an example in C++17. If you export the "indices trick" into a separate function (instead of lambda) and implement your own version of std::array, then this approach should also work with C++14.

https://godbolt.org/g/FayqEn

#include <array>
#include <iostream>
#include <utility>

////////////////////////////////////////////////////////////////////////////////

template<size_t... is, class F>
constexpr decltype(auto) indexer(std::index_sequence<is...>, F f) {
  return f(std::integral_constant<std::size_t, is>{}...);
}

template<size_t N_, class F>
constexpr decltype(auto) indexer(F f) {
  constexpr size_t max_index_length = 4096;
  constexpr size_t N = std::min(N_, max_index_length);
  static_assert(N == N_, "");
  return indexer(std::make_index_sequence<N>{}, f);
}

////////////////////////////////////////////////////////////////////////////////

template<class T>
constexpr auto make_array(T val) {
  return val;
}

template<class NestedArrays, std::size_t N>
constexpr auto make_array(NestedArrays(&arr)[N]) {
  using NestedStdArrays = decltype(make_array(arr[0]));
  return indexer<N>([=] (auto... ns) {
    return std::array<NestedStdArrays, N>{
      make_array(arr[ns])...
    };
  });
}

////////////////////////////////////////////////////////////////////////////////

int main() {
  constexpr int input_from_c[1][3][2]{
    { {0, 10}, {20, 30}, {40, 50} }
  };

  constexpr auto nested_std_arrays = make_array(input_from_c);
  using NestedStdArrays = std::decay_t<decltype(nested_std_arrays)>;

  static_assert(
    std::is_same<
      NestedStdArrays,
      std::array<std::array<std::array<int, 2>, 3>, 1>
    >{}, ""
  );

  static_assert(0 == nested_std_arrays[0][0][0], "");
  static_assert(10 == nested_std_arrays[0][0][1], "");
  static_assert(20 == nested_std_arrays[0][1][0], "");
  static_assert(30 == nested_std_arrays[0][1][1], "");
  static_assert(40 == nested_std_arrays[0][2][0], "");
  static_assert(50 == nested_std_arrays[0][2][1], "");

  return 0;
}


问:
Bash - Why $(sudo cat file) cannot find a file which exists?

Question

Why $(sudo cat) cannot find a file which exists?

This works:

```<code>for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        sudo cat /etc/origin/master/ca-bundle.crt
EOF
done
</code>```

-----BEGIN CERTIFICATE-----

  XYZ...

  -----END CERTIFICATE-----

This does not work but no idea why:

```<code>for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
        echo "${RESULT%x}"
EOF
done
</code>```

"cat: /etc/origin/master/ca-bundle.crt: No such file or directory"

Fix

Based on the answer, fixed as below and worked. Thanks a lot.

```<code>#!/bin/bash
set -u
for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash <<'EOF'
RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
echo "${RESULT%x}"
EOF
done
</code>```

答:
Your loop driver is still kind of horrible.  You could trivially avoid the useless use of cat but the whole thing looks like it's begging for a refactoring

```<code>#!/bin/bash
awk '$1 !~ /^master-/ && !a[$1] { print $1; ++a[$1] }' /etc/ansible/hosts |
xargs -r -n 1 ssh {} sudo cat /etc/origin/master/ca-bundle.crt
</code>```

This does away with adding and then removing a trailing x -- I suspect you ended up with that in the first place because you were capturing and then echoing output instead of just letting cat do what it does -- print to standard output.

Body:
Question

Why $(sudo cat) cannot find a file which exists?

This works:

for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        sudo cat /etc/origin/master/ca-bundle.crt
EOF
done

-----BEGIN CERTIFICATE-----

  XYZ...

  -----END CERTIFICATE-----

This does not work but no idea why:

for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash << EOF
        RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
        echo "${RESULT%x}"
EOF
done

"cat: /etc/origin/master/ca-bundle.crt: No such file or directory"

Fix

Based on the answer, fixed as below and worked. Thanks a lot.

#!/bin/bash
set -u
for host in $(cat /etc/ansible/hosts | cut -d ' ' -f 1 | grep -P '^master-' | sort | uniq)
do
    ssh ${host} /bin/bash <<'EOF'
RESULT="$(sudo cat /etc/origin/master/ca-bundle.crt; echo x)"
echo "${RESULT%x}"
EOF
done

Body:
Your loop driver is still kind of horrible.  You could trivially avoid the useless use of cat but the whole thing looks like it's begging for a refactoring

#!/bin/bash
awk '$1 !~ /^master-/ && !a[$1] { print $1; ++a[$1] }' /etc/ansible/hosts |
xargs -r -n 1 ssh {} sudo cat /etc/origin/master/ca-bundle.crt

This does away with adding and then removing a trailing x -- I suspect you ended up with that in the first place because you were capturing and then echoing output instead of just letting cat do what it does -- print to standard output.


问:
JDBC metadata doesn't recognize mysql data types
I'm trying to create a method to recognize MySQL datatypes to create queries, but it doesn't work for some reason.

Here is the code that fails:

```<code>int type = meta.returnDataType(data[i], table);

if(type == 4){
    preparedStatement.setString(i + 1, data[i]);
    System.out.println("String går");
}if(type == 12){
    preparedStatement.setInt(i + 1, Integer.parseInt(data[i]));
    System.out.println("int går");
}else if(type == 92){
    DateFormat formatter = new SimpleDateFormat("HH:mm");
    preparedStatement.setTime(i + 1, new java.sql.Time(formatter.parse(data[i]).getTime()));
}else if(type == 93){
    DateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm");
    preparedStatement.setTimestamp(i + 1, new java.sql.Timestamp(formatter.parse(data[i]).getTime()));
}
</code>```

and here's my returnDataType method:

```<code>try(Connection con = DBConnection.getMySQLDataSourceForUpdate().getConnection();
    Statement stmt = con.createStatement()){
    String query = "select * from " + table;

    ResultSet rs = stmt.executeQuery(query);
    ResultSetMetaData rsmd = rs.getMetaData();
    return rsmd.getColumnType(1);

}catch(IOException e){

}catch (SQLException e){

}
</code>```

Now the problem is that it doesn't recognize varchar, even though the number 12 is returned every time I try it with system out print. When I try to detect it with if statements or switch, the result is either that they only register integers or they treat everything as integers. I can't seem to see why this is the case.

My CSV file goes like this, the first is an int and the second is a String. At least that's what it should be and that's the way it is in the database.

```<code>1,Per Lauvås
2,Per Per
</code>```

答:
Your returnDataType method always returns the type of the first column of a table. You need to fix that. You should use the parameter metadata of the prepared statement, or maybe the column metadata from DatabaseMetaData. Or at least access the right column index.

You also have switched your if-branches. Type 4 is java.sql.Types.INTEGER, but you attempt to set it as a string, while type 12 is java.sql.Types.VARCHAR, but you try to set it as an integer (with a conversion that might fail).

Sidenote: You should not use integer values like 4, 12, 92 and 93, instead you should use the java.sql.Types constants INTEGER, VARCHAR, TIME and TIMESTAMP. It will make your code more readable and make it easier to detect mistakes like the above.

Body:
I'm trying to create a method to recognize MySQL datatypes to create queries, but it doesn't work for some reason.

Here is the code that fails:

int type = meta.returnDataType(data[i], table);

if(type == 4){
    preparedStatement.setString(i + 1, data[i]);
    System.out.println("String går");
}if(type == 12){
    preparedStatement.setInt(i + 1, Integer.parseInt(data[i]));
    System.out.println("int går");
}else if(type == 92){
    DateFormat formatter = new SimpleDateFormat("HH:mm");
    preparedStatement.setTime(i + 1, new java.sql.Time(formatter.parse(data[i]).getTime()));
}else if(type == 93){
    DateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm");
    preparedStatement.setTimestamp(i + 1, new java.sql.Timestamp(formatter.parse(data[i]).getTime()));
}

and here's my returnDataType method:

try(Connection con = DBConnection.getMySQLDataSourceForUpdate().getConnection();
    Statement stmt = con.createStatement()){
    String query = "select * from " + table;

    ResultSet rs = stmt.executeQuery(query);
    ResultSetMetaData rsmd = rs.getMetaData();
    return rsmd.getColumnType(1);

}catch(IOException e){

}catch (SQLException e){

}

Now the problem is that it doesn't recognize varchar, even though the number 12 is returned every time I try it with system out print. When I try to detect it with if statements or switch, the result is either that they only register integers or they treat everything as integers. I can't seem to see why this is the case.

My CSV file goes like this, the first is an int and the second is a String. At least that's what it should be and that's the way it is in the database.

1,Per Lauvås
2,Per Per


问:
Hide default column gridview VB
I have a simple question. How can I hide the column below in the red box in windowed application. I am using vb as the programming language

答:
There is a property in your DataGridView called RowHeadersVisible for that purpose.

```<code>DataGridView.RowHeadersVisible = False
</code>```

Title: Hide default column gridview VB

Body:
There is a property in your DataGridView called RowHeadersVisible for that purpose.

DataGridView.RowHeadersVisible = False


问:
Unable to use devise_token_auth with active_admin
I'm trying to used devise_token_auth with active_admin. When running rails g active_admin:install User I get the following error.

error

usr/local/lib/ruby/gems/2.4.0/gems/actionpack-5.1.4/lib/action_dispatch/routing/route_set.rb:578:in
  add_route': Invalid route name, already in use: 'new_user_session'
  You may have defined two routes with the same name using the:as`
  option, or you may be overriding a route already defined by a resource
  with the same naming.

routes.rb

```<code>Rails.application.routes.draw do
  devise_for :users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  mount_devise_token_auth_for 'User', at: 'auth'

  scope module: 'api' do
    namespace :v1 do
      resources :users, only: [:index, :show]
    end
  end

  get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')
end
</code>```

答:
can you try a different approach by defining two controllers: one for api and the other for active_admin?

```<code># app/controllers/api_controller.rb
# API routes extend from this controller
class ApiController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
end

# app/controllers/application_controller.rb
# leave this for ActiveAdmin, and any other non-api routes
class ApplicationController < ActionController::Base
end
</code>```

Now inherit all api controllers from ApiController and ActiveAdmin ones from ApplicationController.

There is a known issue between ActiveAdmin and DeviseTokenAuth

Body:
I'm trying to used devise_token_auth with active_admin. When running rails g active_admin:install User I get the following error.

error

usr/local/lib/ruby/gems/2.4.0/gems/actionpack-5.1.4/lib/action_dispatch/routing/route_set.rb:578:in
  add_route': Invalid route name, already in use: 'new_user_session'
  You may have defined two routes with the same name using the:as`
  option, or you may be overriding a route already defined by a resource
  with the same naming.

routes.rb

Rails.application.routes.draw do
  devise_for :users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  mount_devise_token_auth_for 'User', at: 'auth'

  scope module: 'api' do
    namespace :v1 do
      resources :users, only: [:index, :show]
    end
  end

  get '/docs' => redirect('/swagger/dist/index.html?url=/apidocs/api-docs.json')
end

Body:
can you try a different approach by defining two controllers: one for api and the other for active_admin?

# app/controllers/api_controller.rb
# API routes extend from this controller
class ApiController < ActionController::Base
  include DeviseTokenAuth::Concerns::SetUserByToken
end

# app/controllers/application_controller.rb
# leave this for ActiveAdmin, and any other non-api routes
class ApplicationController < ActionController::Base
end

Now inherit all api controllers from ApiController and ActiveAdmin ones from ApplicationController.

There is a known issue between ActiveAdmin and DeviseTokenAuth


问:
Is a returned value moved or not?
With this code:

```<code>struct Point {
    x: f64,
    y: f64,
}

struct Rectangle {
    p1: Point,
    p2: Point,
}

impl Rectangle {
    pub fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Rectangle {
        let r = Rectangle {
            p1: Point { x: x1, y: y1 },
            p2: Point { x: x2, y: y2 },
        };
        // some code where r is used
        r
    }
}

let rectangle = Rectangle::new(0.0, 0.0, 10.0, 10.0);
</code>```

From a memory point of view, is rectangle the same instance as r, or is it a copy of r?

Do I have to explicitly return by reference (something like &r)?

I have to create millions of rectangles, and I don't want there to be useless copies.

答:
From a memory point of view, is rectangle the same instance as r, or is it a copy of r?

Unspecified.

The Rust language specifies the semantics of the language, and while they do constrain the implementation somewhat, in this case they do not. How a return value is passed up the call stack is part of the ABI, and not only is the ABI unstable (in Rust), it's also platform specific.

Do I have to explicitly return by reference (something like &r)?

Returning by reference is not possible.

You could return a Box<Rectangle> but the cost of the memory allocation would dwarf the cost of copying a Rectangle in the first place, so it's hardly advisable.

You could force this using output parameters instead, but this has other issues:

if you have a &mut Rectangle parameter, you first need to have a valid instance, which has to be initialized; rather wasteful,

if you have a *mut Rectangle pointing to uninitialized memory, you need to use unsafe code, hardly satisfying.

However...

I have to create millions of rectangles, and I don't want there to be useless copies.

I think you are worrying for nothing.

The first rule of performance tuning is measure first; and I doubt that you'll be able to observe a performance issue in the creation of those millions of rectangles.

The compiler has multiple tricks up its sleeves, such as:

not even materializing the rectangle instance to start with, but pass its components via CPU registers instead,

inlining new at the call site, avoiding any copy whatsoever,

...

Thus, before worrying about the cost of copying 4 f64, I would implement the naive solution, compile in release mode, and observe what happens.

Title: Is a returned value moved or not?

Body:
With this code:

struct Point {
    x: f64,
    y: f64,
}

struct Rectangle {
    p1: Point,
    p2: Point,
}

impl Rectangle {
    pub fn new(x1: f64, y1: f64, x2: f64, y2: f64) -> Rectangle {
        let r = Rectangle {
            p1: Point { x: x1, y: y1 },
            p2: Point { x: x2, y: y2 },
        };
        // some code where r is used
        r
    }
}

let rectangle = Rectangle::new(0.0, 0.0, 10.0, 10.0);

From a memory point of view, is rectangle the same instance as r, or is it a copy of r?

Do I have to explicitly return by reference (something like &r)?

I have to create millions of rectangles, and I don't want there to be useless copies.


问:
How to give the slide up /slide down effect to bootstrap tab-pane
I have got the basic tab of bootstrap and i want when i change the tab menu the content (tab-pane) should animate like bootstrap collapse does( slide down/slide up)
Is it possible ?

```<code><ul class="nav" id="myTab" role="tablist">
  <li class="nav-item">
    <a class="nav-link active" data-toggle="tab" href="#home" role="tab" aria-controls="home">Home</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#profile" role="tab" aria-controls="profile">Profile</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#messages" role="tab" aria-controls="messages">Messages</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" data-toggle="tab" href="#settings" role="tab" aria-controls="settings">Settings</a>
  </li>
</ul>

<div class="tab-content">
  <div class="tab-pane active" id="home" role="tabpanel">This Is good</div>
  <div class="tab-pane" id="profile" role="tabpanel">This is better</div>
  <div class="tab-pane" id="messages" role="tabpanel">Thhis is excellent </div>
  <div class="tab-pane" id="settings" role="tabpanel">This is poor</div>
</div>
</code>```

I'm running out of idea so please help me i know it's a silly question.

Here is the EXAMPLE

答:
What about that :</p>

```<code>$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
  $($(e.target).attr('href')).hide()
})
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  $($(e.target).attr('href')).slideDown()
})
</code>```

Body:
I have got the basic tab of bootstrap and i want when i change the tab menu the content (tab-pane) should animate like bootstrap collapse does( slide down/slide up)
Is it possible ?

    Home

    Profile

    Messages

    Settings

This Is good

This is better

Thhis is excellent

This is poor

I'm running out of idea so please help me i know it's a silly question.

Here is the EXAMPLE

Body:
What about that :

$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
  $($(e.target).attr('href')).hide()
})
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
  $($(e.target).attr('href')).slideDown()
})


问:
How to change HyperlinkButton background and foreground color when PointerEntered in UWP
Here is my sample UWP code in C# and XAML
Where i created one hyperlink button in MainPage method and set the style attributes like foreground and background.

Now i want to change the background and foreground colors when PointerEntered event triggered like mouseover, in this case only font size is changing but not the colors

```<code>public MainPage(){
    this.InitializeComponent();

    var hLinkButton = new HyperlinkButton();

    hLinkButton.Name = "LearnMoreHyperLink";
    hLinkButton.Content = "Learn More...";

    hLinkButton.Background = new SolidColorBrush(Colors.Red);
    hLinkButton.Foreground = new SolidColorBrush(Colors.White);
    hLinkButton.FontWeight = FontWeights.SemiBold;
    hLinkButton.FontSize = 18.0;

    hLinkButton.PointerEntered += OnPointerEntered;
    LayoutGrid.Children.Add(hLinkButton);
}

private void OnPointerEntered(object sender, PointerRoutedEventArgs e){
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}

// Only fontsize effecting on mouseover, background and foreground is not working
</code>```

答:
You can override the style template for the HyperlinkButton to achieve this.

To do this you need to right click on your HyperLinkButton > Edit template > Edit a copy.
Then add the relevant code to the visual state. In your case the visual state is "PointerOver".

The following code will make the foreground of the HyperLinkButton to Red and the background to white.

```<code>  <VisualState x:Name="PointerOver">
      <Storyboard>
         <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                     Storyboard.TargetProperty="Foreground">
           <DiscreteObjectKeyFrame KeyTime="0" Value="#FFFF0000" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                     Storyboard.TargetProperty="Background">
        <DiscreteObjectKeyFrame KeyTime="0" Value="#FFFFFFFF" />
       </ObjectAnimationUsingKeyFrames>
      </Storyboard>
   </VisualState>
</code>```

EDIT

In c# code what you are doing is changing the Background and Foreground color of the HyperLinkButton which is overriding the color for the "Normal" visual state of the control.. While the pointer is above your control, the default control style predefined in the XAML(for "PointerOver" state) is showing the color that it is supposed to,so you can only see the change after the pointer is removed from your control..

Thus, overriding the xaml styling of the control is the correct and the best solution for PointerOver event in my opinion..

Please ask any further questions that you may have regarding this.. I will be happy to give a proper explanation if required.

Body:
Here is my sample UWP code in C# and XAML
Where i created one hyperlink button in MainPage method and set the style attributes like foreground and background.

Now i want to change the background and foreground colors when PointerEntered event triggered like mouseover, in this case only font size is changing but not the colors

public MainPage(){
    this.InitializeComponent();

    var hLinkButton = new HyperlinkButton();

    hLinkButton.Name = "LearnMoreHyperLink";
    hLinkButton.Content = "Learn More...";

    hLinkButton.Background = new SolidColorBrush(Colors.Red);
    hLinkButton.Foreground = new SolidColorBrush(Colors.White);
    hLinkButton.FontWeight = FontWeights.SemiBold;
    hLinkButton.FontSize = 18.0;

    hLinkButton.PointerEntered += OnPointerEntered;
    LayoutGrid.Children.Add(hLinkButton);
}

private void OnPointerEntered(object sender, PointerRoutedEventArgs e){
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}

// Only fontsize effecting on mouseover, background and foreground is not working

Body:
You can override the style template for the HyperlinkButton to achieve this.

To do this you need to right click on your HyperLinkButton > Edit template > Edit a copy.
Then add the relevant code to the visual state. In your case the visual state is "PointerOver".

The following code will make the foreground of the HyperLinkButton to Red and the background to white.

  <VisualState x:Name="PointerOver">
      <Storyboard>
         <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                     Storyboard.TargetProperty="Foreground">
           <DiscreteObjectKeyFrame KeyTime="0" Value="#FFFF0000" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                     Storyboard.TargetProperty="Background">
        <DiscreteObjectKeyFrame KeyTime="0" Value="#FFFFFFFF" />
       </ObjectAnimationUsingKeyFrames>
      </Storyboard>
   </VisualState>

EDIT

In c# code what you are doing is changing the Background and Foreground color of the HyperLinkButton which is overriding the color for the "Normal" visual state of the control.. While the pointer is above your control, the default control style predefined in the XAML(for "PointerOver" state) is showing the color that it is supposed to,so you can only see the change after the pointer is removed from your control..

Thus, overriding the xaml styling of the control is the correct and the best solution for PointerOver event in my opinion..

Please ask any further questions that you may have regarding this.. I will be happy to give a proper explanation if required.


问:
how to name CouchDB Key Value fields
I asked this question previously but did not seem to make myself clear.
When emitting values from a CouchDB View like:

```<code>{emit(doc.payload.creator, doc.payload.startTS);}
</code>```

Is it possible to somehow "name" or "label" the results?  I would like to return the Key as "Created by" and the Value as "Start Time".

答:
In the view function definition you can use this kind of operations in order to build the value as a JSON document with the required attributes

```<code>function (doc) {
  var value = {};
  value['Created By'] = doc.payload.creator;
  value['Start Time'] = doc.payload.startTS;
  emit(doc.payload.creator, value);
}
</code>```

If you would like to export the data in a different format you may use a list function over the view results.

http://docs.couchdb.org/en/2.1.1/ddocs/ddocs.html#list-functions

Title: how to name CouchDB Key Value fields

Body:
I asked this question previously but did not seem to make myself clear.
When emitting values from a CouchDB View like:

{emit(doc.payload.creator, doc.payload.startTS);}

Is it possible to somehow "name" or "label" the results?  I would like to return the Key as "Created by" and the Value as "Start Time".

Body:
In the view function definition you can use this kind of operations in order to build the value as a JSON document with the required attributes

function (doc) {
  var value = {};
  value['Created By'] = doc.payload.creator;
  value['Start Time'] = doc.payload.startTS;
  emit(doc.payload.creator, value);
}

If you would like to export the data in a different format you may use a list function over the view results.

http://docs.couchdb.org/en/2.1.1/ddocs/ddocs.html#list-functions


问:
convert mysql query to sql server query
I want to convert below mysql query to sql query.I want to use If condition in sql server</p>

```<code>SELECT
foodName,
IF( foodPrice>2000, 'Expensive', 'Cheap') as fpDesc,
discountPercent
FROM restaurant.foods;
</code>```

答:
if is MySQL proprietary, as you noticed. The standard way to do this is case

```<code>CASE WHEN foodPrice > 2000
     THEN 'Expensive'
     ELSE 'Cheap'
 END
</code>```

See also: http://modern-sql.com/feature/case

Title: convert mysql query to sql server query

Body:
I want to convert below mysql query to sql query.I want to use If condition in sql server

SELECT
foodName,
IF( foodPrice>2000, 'Expensive', 'Cheap') as fpDesc,
discountPercent
FROM restaurant.foods;

Body:
if is MySQL proprietary, as you noticed. The standard way to do this is case

CASE WHEN foodPrice > 2000
     THEN 'Expensive'
     ELSE 'Cheap'
 END

See also: http://modern-sql.com/feature/case


问:
Linq query to Join tables if value not in first table fetch from second
I have 2 lists with below structure.

```<code>public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D2" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D1"} }
};

var allTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D1" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D2"}, Codriver = new Driver { DriverId = "C2"} }
};
</code>```

I want to get all the Id's of driver and codriver from modifiedTeams but if driver/codriver is not there in modifiedTeams then fetch it from allTeams based on Team ids(T1,T2) Eg: Id of codriver from Team T2

Final Output:

```<code>{D2,C1,D1,C2}
</code>```

Can some one help me how I could achieve this via LINQ(Lambda expressions) in C#.

Simple C# code:-

```<code>List<string> allDriverCodriverIds = new List<string>();
foreach (var team in modifiedTeams)
{
    if (team.Driver != null && !string.IsNullOrEmpty(team.Driver.DriverId))
    {
        allDriverCodriverIds.Add(team.Driver.DriverId);
    }
    else {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Driver != null && !string.IsNullOrEmpty(existingTeam.Driver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Driver.DriverId);
        }
    }
    if (team.Codriver != null && !string.IsNullOrEmpty(team.Codriver.DriverId))
    {
        allDriverCodriverIds.Add(team.Codriver.DriverId);
    }
    else
    {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Codriver != null && !string.IsNullOrEmpty(existingTeam.Codriver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Codriver.DriverId);
        }
    }
}
</code>```

答:
So what you are looking to do is to left join the allTeams to the modified teams. Then if the left join find a matching value you take the id of that object, otherwise of allTeams:

```<code>var result = (from a in allTeams
             join m in modifiedTeams on a.Id equals m.Id into mj
             from m in mj.DefaultIfEmpty()
             select new Team
             {
                 Id = a.Id,
                 Driver = m?.Driver ?? a.Driver,
                 Codriver = m?.Codriver ?? a.Codriver
             }).ToList();
</code>```

For getting only the ids do:

```<code>var result = (from a in allTeams
              join m in modifiedTeams on a.Id equals m.Id into mj
              from m in mj.DefaultIfEmpty()
              select new [] { m?.Driver?.DriverId ?? a.Driver?.DriverId,
                              m?.Codriver?.DriverId ?? a.Codriver?.DriverId
              }).SelectMany(i => i).ToList();
</code>```

Body:
I have 2 lists with below structure.

public class Team
{
    public string Id { get; set; }
    public Driver Driver { get; set; }
    public Driver Codriver { get; set; }
}

public class Driver
{
    public string DriverId { get; set; }
}

var modifiedTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D2" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D1"} }
};

var allTeams = new List<Team>
{
    new Team {Id = "T1", Driver = new Driver { DriverId = "D1" }, Codriver = new Driver { DriverId = "C1"} },
    new Team {Id = "T2", Driver = new Driver { DriverId = "D2"}, Codriver = new Driver { DriverId = "C2"} }
};

I want to get all the Id's of driver and codriver from modifiedTeams but if driver/codriver is not there in modifiedTeams then fetch it from allTeams based on Team ids(T1,T2) Eg: Id of codriver from Team T2

Final Output:

{D2,C1,D1,C2}

Can some one help me how I could achieve this via LINQ(Lambda expressions) in C#.

Simple C# code:-

List<string> allDriverCodriverIds = new List<string>();
foreach (var team in modifiedTeams)
{
    if (team.Driver != null && !string.IsNullOrEmpty(team.Driver.DriverId))
    {
        allDriverCodriverIds.Add(team.Driver.DriverId);
    }
    else {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Driver != null && !string.IsNullOrEmpty(existingTeam.Driver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Driver.DriverId);
        }
    }
    if (team.Codriver != null && !string.IsNullOrEmpty(team.Codriver.DriverId))
    {
        allDriverCodriverIds.Add(team.Codriver.DriverId);
    }
    else
    {
        var existingTeam = allTeams.FirstOrDefault(e => e.Id.ToString() == team.Id);
        if (existingTeam != null && existingTeam.Codriver != null && !string.IsNullOrEmpty(existingTeam.Codriver.DriverId))
        {
            allDriverCodriverIds.Add(existingTeam.Codriver.DriverId);
        }
    }
}

Body:
So what you are looking to do is to left join the allTeams to the modified teams. Then if the left join find a matching value you take the id of that object, otherwise of allTeams:

var result = (from a in allTeams
             join m in modifiedTeams on a.Id equals m.Id into mj
             from m in mj.DefaultIfEmpty()
             select new Team
             {
                 Id = a.Id,
                 Driver = m?.Driver ?? a.Driver,
                 Codriver = m?.Codriver ?? a.Codriver
             }).ToList();

For getting only the ids do:

var result = (from a in allTeams
              join m in modifiedTeams on a.Id equals m.Id into mj
              from m in mj.DefaultIfEmpty()
              select new [] { m?.Driver?.DriverId ?? a.Driver?.DriverId,
                              m?.Codriver?.DriverId ?? a.Codriver?.DriverId
              }).SelectMany(i => i).ToList();


问:
Understanding solr field cache
While I was working on this solr LowerCaseFilterFactory not working, I got the following error:

```<code>...enable docvalues true n reindex or place useFieldCache=true...
</code>```

It was resolved by specifying useFieldCache=true in the query.

Is it the lucene FieldCache?

Can anybody help me know more about this?

答:
In Lucene-Solr 4.5 and later, docValues are mostly disk-based to avoid the requirement for large heap allocations in Solr. If you use the field cache in sort, stats, and other queries, make those fields docValues

Please check this

Title: Understanding solr field cache

Body:
While I was working on this solr LowerCaseFilterFactory not working, I got the following error:

...enable docvalues true n reindex or place useFieldCache=true...

It was resolved by specifying useFieldCache=true in the query.

Is it the lucene FieldCache?

Can anybody help me know more about this?


问:
SQLException: ResultSet closed
I'm trying to execute method which should create a new object with fields from database, and everytime i run this code im getting SQLException: ResultSet closed.

```<code> public DatabasedClient getDatabaseClient(int clientDatabaseid){
    if(DatabaseClientUtil.isInDatabase(clientDatabaseid)){
        return DatabaseClientUtil.getDBClient(clientDatabaseid);
    }else{
        try{
            System.out.println("Trying to find user in db");
            ResultSet rs = fbot.getStorage().query("select * from database_name where clientDBId = " + clientDatabaseid);
            System.out.println("deb " + rs.getString("nick"));
            while (rs.next()) {
                DatabasedClient databasedClient = new DatabasedClient(clientDatabaseid);
                databasedClient.setUid(rs.getString("uid"));
                databasedClient.setNick(rs.getString("nick"));
                databasedClient.setLastConnect(rs.getLong("lastConnected"));
                databasedClient.setLastDisconnect(rs.getLong("lastDisconnect"));
                databasedClient.setTimeSpent(rs.getLong("timeSpent"));
                databasedClient.setLongestConnection(rs.getLong("longestConnection"));
                return databasedClient;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return null;
}
</code>```

}

Im using hikari, here are methods from AbstractStorage class

```<code>@Override
public void execute(String query) throws SQLException {
    try (Connection connection = getConnection()){
        connection.prepareStatement(query).executeUpdate();
    }
}

@Override
public ResultSet query(String query) throws SQLException {
    try (Connection connection = getConnection()) {
        return  connection.prepareStatement(query).executeQuery();
    }
}
</code>```

Screenshot from error

I hope someone will help me with this.

答:
I think the exact error you are seeing is being caused by the following line of code:

```<code>System.out.println("deb " + rs.getString("nick"));
</code>```

You are trying to access the result set before you advance the cursor to the first record.  Also, your method getDatabaseClient  is returning a single object which conceptually maps to a single expected record from the query.  Hence, iterating once over the result set would seem to make sense.  Taking all this into consideration, we can try the following:

```<code>try {
    System.out.println("Trying to find user in db");
    ResultSet rs = fbot.getStorage().query("select * from database_name where clientDBId = " + clientDatabaseid);
    // do not access the result set here

    if (rs.next()) {
        DatabasedClient databasedClient = new DatabasedClient(clientDatabaseid);
        databasedClient.setUid(rs.getString("uid"));
        databasedClient.setNick(rs.getString("nick"));
        databasedClient.setLastConnect(rs.getLong("lastConnected"));
        databasedClient.setLastDisconnect(rs.getLong("lastDisconnect"));
        databasedClient.setTimeSpent(rs.getLong("timeSpent"));
        databasedClient.setLongestConnection(rs.getLong("longestConnection"));
        return databasedClient;
    }
} catch (SQLException e) {
     e.printStackTrace();
}
</code>```

Title: SQLException: ResultSet closed

Body:
I'm trying to execute method which should create a new object with fields from database, and everytime i run this code im getting SQLException: ResultSet closed.

 public DatabasedClient getDatabaseClient(int clientDatabaseid){
    if(DatabaseClientUtil.isInDatabase(clientDatabaseid)){
        return DatabaseClientUtil.getDBClient(clientDatabaseid);
    }else{
        try{
            System.out.println("Trying to find user in db");
            ResultSet rs = fbot.getStorage().query("select * from database_name where clientDBId = " + clientDatabaseid);
            System.out.println("deb " + rs.getString("nick"));
            while (rs.next()) {
                DatabasedClient databasedClient = new DatabasedClient(clientDatabaseid);
                databasedClient.setUid(rs.getString("uid"));
                databasedClient.setNick(rs.getString("nick"));
                databasedClient.setLastConnect(rs.getLong("lastConnected"));
                databasedClient.setLastDisconnect(rs.getLong("lastDisconnect"));
                databasedClient.setTimeSpent(rs.getLong("timeSpent"));
                databasedClient.setLongestConnection(rs.getLong("longestConnection"));
                return databasedClient;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return null;
}

}

Im using hikari, here are methods from AbstractStorage class

@Override
public void execute(String query) throws SQLException {
    try (Connection connection = getConnection()){
        connection.prepareStatement(query).executeUpdate();
    }
}

@Override
public ResultSet query(String query) throws SQLException {
    try (Connection connection = getConnection()) {
        return  connection.prepareStatement(query).executeQuery();
    }
}

Screenshot from error

I hope someone will help me with this.

Body:
I think the exact error you are seeing is being caused by the following line of code:

System.out.println("deb " + rs.getString("nick"));

You are trying to access the result set before you advance the cursor to the first record.  Also, your method getDatabaseClient  is returning a single object which conceptually maps to a single expected record from the query.  Hence, iterating once over the result set would seem to make sense.  Taking all this into consideration, we can try the following:

try {
    System.out.println("Trying to find user in db");
    ResultSet rs = fbot.getStorage().query("select * from database_name where clientDBId = " + clientDatabaseid);
    // do not access the result set here

    if (rs.next()) {
        DatabasedClient databasedClient = new DatabasedClient(clientDatabaseid);
        databasedClient.setUid(rs.getString("uid"));
        databasedClient.setNick(rs.getString("nick"));
        databasedClient.setLastConnect(rs.getLong("lastConnected"));
        databasedClient.setLastDisconnect(rs.getLong("lastDisconnect"));
        databasedClient.setTimeSpent(rs.getLong("timeSpent"));
        databasedClient.setLongestConnection(rs.getLong("longestConnection"));
        return databasedClient;
    }
} catch (SQLException e) {
     e.printStackTrace();
}


问:
Sharepoint discussion board, replicate the settings and rules to a webpart
I am currently developing a sharepoint webpart to display a private discussion board. The discussion can only be viewed by limitted users. The following allowed users as of now could be: Site Collection Owner, Discussion Board Members, Discussion Board Owner.

The way I setup the security of the webpart is by getting all the users and check if they belong to the said allowed persons in the discussion board.

My logic seems to be working right now but, the concern here of my client is:
What if in the future they will change the settings or security of the discussion board and I might no longer be around to fix the code of the webpart such that the settings and security of the webpart will sync to the discussion board?
My idea as of now is, instead of developing a code that will copy the settings and security of the discussion board and apply it to the webpart, I will point the settings and security of the webpart right directly to the discussion board. My question right now is, would this be possible?

Please see the attached pic to have a better view of what I wanted to happen.

答:
Hi I have fixed the problem!

this word does the thing "DoesUserHavePermissions"... here is my code snippet

```<code>try
{
    string strListUrl = "http://MySite.com/List/MyDiscussion/AllItems.aspx";
    SPUser objCurrentUser = SPContext.Current.Web.CurrentUser;
    SPSite objSite = new SPSite(SPContext.Current.Web.Url);
    SPWeb objWeb = objSite.OpenWeb();
    SPList objList = objWeb.Lists[strListUrl];

    if(!objList.DoesUserHavePermissions(objCurrentUser,SPBasePermissions.EditListItems)){
        throw new UnauthorizedAccessException("You are not authorized to view this discussion!");
    }
}
catch(UnauthorizedAccessException uae){
    /// some exception handling codes here
}
</code>```

@djeeg: thanks for the help! 1 vote for you! :)

Body:
Hi I have fixed the problem!

this word does the thing "DoesUserHavePermissions"... here is my code snippet

try
{
    string strListUrl = "http://MySite.com/List/MyDiscussion/AllItems.aspx";
    SPUser objCurrentUser = SPContext.Current.Web.CurrentUser;
    SPSite objSite = new SPSite(SPContext.Current.Web.Url);
    SPWeb objWeb = objSite.OpenWeb();
    SPList objList = objWeb.Lists[strListUrl];

    if(!objList.DoesUserHavePermissions(objCurrentUser,SPBasePermissions.EditListItems)){
        throw new UnauthorizedAccessException("You are not authorized to view this discussion!");
    }
}
catch(UnauthorizedAccessException uae){
    /// some exception handling codes here
}

@djeeg: thanks for the help! 1 vote for you! :)


问:
print"we don't found this letter" java with loop
this my program

```<code>import java.util.*;
public class LeTter { //open class name
    static Scanner keyboard = new Scanner(System.in); // Scanner
    public static void main(String[] args) { //open main class
        char letter; //decl
        int y, x, z; //decl
        boolean check = false;
        System.out.println("Enter 8 letters: "); // print sentince
        char[] des = new char[8]; //array
        for (y = 0; y < des.length; y++) { // for without semicolon :), open for loop
            des[y] = keyboard.next().charAt(0); //initialize
        } // close for loop
        System.out.println("Enter any letter to check about it: "); //will apper to the user
        letter = keyboard.next().charAt(0); //initi
        for (x = 0; x < des.length; x++) { //for loop opens
            if (des[x] == letter) { //open if loop
                System.out.println("we found it's " + des[x] + " and the index of it is " + x);
                System.out.println("so we will show you this letters " + x + " times");
                for (z = 0; z < x; z++)
                    System.out.println(des[x] + "  ");
                check = false;
            } //close if loop
            if (true)
                System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
        } // close for loop
    } //close main
} //close class
</code>```

put if the user didn't put the letter that not look like 8 letter was enter i want to print this statement "we don't found it"
how can I do it

example:
enter 8 letters
a s d f g h j k
enter any letter
t
we don't found it  << how can I do this??

another example:
enter 8 letters
a s d f g h j k
enter any letter
a
we found it  << i did this , i want the first one ""onlly""

答:
I've shortened your code, as you can just add the user's input into a char array, and remove the spaces.

I used break; to get out of the loop once the first char was found, you can remove this if you want to mind multiple instance of it.

```<code>static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Enter 8 letters: ");
        String letters = keyboard.nextLine().replaceAll(" ", "");
        char cArray[] = letters.toCharArray();
        System.out.println("Enter any letter to check about it: ");
        char letter = keyboard.next().charAt(0);
        boolean found = false;
        for (int i = 0; i < cArray.length; i++) {
            if (cArray[i] == letter) {
                System.out.println("We found " + letter + " at position " + i);
                found = true;
                break; //used as you specify only to find the first one
            }
        }
        if (!found) {
            System.out.println("Are you sure about the letter you entered? We didn't find it");
        }
    }
</code>```

Try it online!

Body:
this my program

import java.util.*;
public class LeTter { //open class name
    static Scanner keyboard = new Scanner(System.in); // Scanner
    public static void main(String[] args) { //open main class
        char letter; //decl
        int y, x, z; //decl
        boolean check = false;
        System.out.println("Enter 8 letters: "); // print sentince
        char[] des = new char[8]; //array
        for (y = 0; y < des.length; y++) { // for without semicolon :), open for loop
            des[y] = keyboard.next().charAt(0); //initialize
        } // close for loop
        System.out.println("Enter any letter to check about it: "); //will apper to the user
        letter = keyboard.next().charAt(0); //initi
        for (x = 0; x < des.length; x++) { //for loop opens
            if (des[x] == letter) { //open if loop
                System.out.println("we found it's " + des[x] + " and the index of it is " + x);
                System.out.println("so we will show you this letters " + x + " times");
                for (z = 0; z < x; z++)
                    System.out.println(des[x] + "  ");
                check = false;
            } //close if loop
            if (true)
                System.out.println("are you sure about the letter's you enterd it? we didnt found it ");
        } // close for loop
    } //close main
} //close class

put if the user didn't put the letter that not look like 8 letter was enter i want to print this statement "we don't found it"
how can I do it

example:
enter 8 letters
a s d f g h j k
enter any letter
t
we don't found it  << how can I do this??

another example:
enter 8 letters
a s d f g h j k
enter any letter
a
we found it  << i did this , i want the first one ""onlly""

Body:
I've shortened your code, as you can just add the user's input into a char array, and remove the spaces.

I used break; to get out of the loop once the first char was found, you can remove this if you want to mind multiple instance of it.

static Scanner keyboard = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("Enter 8 letters: ");
        String letters = keyboard.nextLine().replaceAll(" ", "");
        char cArray[] = letters.toCharArray();
        System.out.println("Enter any letter to check about it: ");
        char letter = keyboard.next().charAt(0);
        boolean found = false;
        for (int i = 0; i < cArray.length; i++) {
            if (cArray[i] == letter) {
                System.out.println("We found " + letter + " at position " + i);
                found = true;
                break; //used as you specify only to find the first one
            }
        }
        if (!found) {
            System.out.println("Are you sure about the letter you entered? We didn't find it");
        }
    }

Try it online!


问:
putting html file into iframe or div and click in it
i am creating a survey app where user can create surveys, those surveys are stored in separate html files (example: 123.html), in order to be able to edit this file like add or remove textbox or checkbox... i read the file with cordova and put the contents in an iframe,what i am trying now is when user clicks in this iframe user should be able to edit the clicked element. however sometimes the click works and sometimes not. i have tried many different codes but none seems to be fine, when it works then on reloading the page it doesnt work anymore
some sample code i already tried:

```<code>$(function(){
$('#ifr2').on('click',function(){
    $('#ifr2').contents().find("h2").click(function(){alert('title');});
var q=$('#ifr2').contents(); console.log(q);
$(q).find('html').on('click',function(e){console.log(e.target.id);});});
});
</code>```

and:

```<code>$(function(){ var r= $('#ifr2').contents().find("body");console.log(r);
      $(r).on('click',function(event){
           console.log(event.target.nodeName);
      });
    // alert(event.target.nodeName);});
</code>```

and:

```<code>$("#ifr2").contents().find("h2").on('click',function(){alert('h2');});
</code>```

and:

```<code>$('#ifr2').load(function(){
var iframeBody = $('body', $('#ifr2').contentWindow.document);
$(iframeBody).on('click', 'h2', function(event) {
   console.log(event.target.nodeName);
});});
</code>```

the first one and last one works only sometimes, so after reading alot of pages here and from google i decided it would be better to just put the content in a div instead of an iframe

```<code><div id="test" style="border:1px solid black; padding:10px 10px 10px 10px; " data-role="none"></div>
</code>```

putting the content into the div works but now there is an issue with the checkboxes and radiobuttons which come from the html file, they are not aligned, i tried to align them but also failed, take a look at the screens:

Iframe content looks good

div content doesnt look good

i also tried to align the labels for the chkboxes and radios like this:

```<code>function testf(){
    $('#test label').css({"float":"right"});

}
</code>```

after seeing that the div content is kind of messed up, i copied the div content into another page just for testing and there it is aligned properly

for me it is not important if its a div or an iframe, important is that i can easily click in it for editing and that it is aligned properly when it is loaded.

the file content is the following:

```<code><!DOCTYPE html>
<html>
<head>
<title>Umfrage</title>
</head>
<body>
<h2 style="text-align:center;">survey title</h2>
description <br>
<form>
<fieldset style="border:1px solid black"><legend><b>1</b></legend><p>question 1</p><textarea name="txtarea1"></textarea></fieldset><br>
<fieldset style="border:1px solid black"><legend><b>2</b></legend><p>radiobuttons </p>
<input id="radio1" name="radio1" type="radio"><label for="radio1">a</label><br>
<input id="radio2" name="radio1" type="radio"><label for="radio2">abcdefg</label><br>
<input id="radio3" name="radio1" type="radio"><label for="radio3">c</label><br></fieldset>
<fieldset style="border:1px solid black"><legend><b>3</b></legend><p>chkboxquestion</p>
<input id="chkbox1" name="chkbox1" type="checkbox"><label for="chkbox1">a</label><br>
<input id="chkbox2" name="chkbox1" type="checkbox"><label for="chkbox2">b</label><br>
<input id="chkbox3" name="chkbox1" type="checkbox"><label for="chkbox3">abcde</label><br></fieldset>
<hr id="hrid">
<input value="Abschicken" type="submit">
</form>
</body>
</html>
</code>```

edit

solved it by using the below code for changing the div css:

```<code> $('#test :radio, :checkbox, label').css({"float":"left","line-height": "1.6em","height":"1.6em","margin":"0px 2px","padding":"0px"});
   $('#test :radio, :checkbox').css({"clear":"left"});
</code>```

thanks to TheGr8_Nik from How to align checkboxes and their labels consistently cross-browsers

there is no need for an iframe now, div is better

答:
```<code>$('#test :radio, :checkbox, label').css({"float":"left","line-height": "1.6em","height":"1.6em","margin":"0px 2px","padding":"0px"});
   $('#test :radio, :checkbox').css({"clear":"left"});
</code>```

thanks to TheGr8_Nik

Body:
i am creating a survey app where user can create surveys, those surveys are stored in separate html files (example: 123.html), in order to be able to edit this file like add or remove textbox or checkbox... i read the file with cordova and put the contents in an iframe,what i am trying now is when user clicks in this iframe user should be able to edit the clicked element. however sometimes the click works and sometimes not. i have tried many different codes but none seems to be fine, when it works then on reloading the page it doesnt work anymore
some sample code i already tried:

$(function(){
$('#ifr2').on('click',function(){
    $('#ifr2').contents().find("h2").click(function(){alert('title');});
var q=$('#ifr2').contents(); console.log(q);
$(q).find('html').on('click',function(e){console.log(e.target.id);});});
});

and:

$(function(){ var r= $('#ifr2').contents().find("body");console.log(r);
      $(r).on('click',function(event){
           console.log(event.target.nodeName);
      });
    // alert(event.target.nodeName);});

and:

$("#ifr2").contents().find("h2").on('click',function(){alert('h2');});

and:

$('#ifr2').load(function(){
var iframeBody = $('body', $('#ifr2').contentWindow.document);
$(iframeBody).on('click', 'h2', function(event) {
   console.log(event.target.nodeName);
});});

the first one and last one works only sometimes, so after reading alot of pages here and from google i decided it would be better to just put the content in a div instead of an iframe

putting the content into the div works but now there is an issue with the checkboxes and radiobuttons which come from the html file, they are not aligned, i tried to align them but also failed, take a look at the screens:

Iframe content looks good

div content doesnt look good

i also tried to align the labels for the chkboxes and radios like this:

function testf(){
    $('#test label').css({"float":"right"});

}

after seeing that the div content is kind of messed up, i copied the div content into another page just for testing and there it is aligned properly

for me it is not important if its a div or an iframe, important is that i can easily click in it for editing and that it is aligned properly when it is loaded.

the file content is the following:

<!DOCTYPE html>

<title>Umfrage</title>

survey title

description

<form>
<fieldset style="border:1px solid black"><legend>1</legend>
question 1
<textarea name="txtarea1"></textarea></fieldset>

<fieldset style="border:1px solid black"><legend>2</legend>
radiobuttons

<input id="radio1" name="radio1" type="radio">a

<input id="radio2" name="radio1" type="radio">abcdefg

<input id="radio3" name="radio1" type="radio">c
</fieldset>
<fieldset style="border:1px solid black"><legend>3</legend>
chkboxquestion

<input id="chkbox1" name="chkbox1" type="checkbox">a

<input id="chkbox2" name="chkbox1" type="checkbox">b

<input id="chkbox3" name="chkbox1" type="checkbox">abcde
</fieldset>

<input value="Abschicken" type="submit">
</form>

edit

solved it by using the below code for changing the div css:

 $('#test :radio, :checkbox, label').css({"float":"left","line-height": "1.6em","height":"1.6em","margin":"0px 2px","padding":"0px"});
   $('#test :radio, :checkbox').css({"clear":"left"});

thanks to TheGr8_Nik from How to align checkboxes and their labels consistently cross-browsers

there is no need for an iframe now, div is better


问:
laravel validation doesnt work for .JPG
In Laravel5 I validate a picture with the following code:

```<code>public function rules() {
    return [
        'name' => 'required',
        'pic' => 'required|mimes:jpeg,png',
    ];
}
</code>```

It works for files with extensions filename.jpg and filename.jpeg but it doesn't for filename.JPG.

However, it doesn't return wrong file extension but a missing file. Can anyone help?

答:
Try this in your pic rules:

'pic' => 'required|mimes:jpeg,jpg,png',
```

Explanation

Had this problem and found that when you use mimes: rule, you have to specify the extensions you want as valid i. e. you have to add both jpeg and jpg extension variations.

Other solutions

Use mimetypes: rule with image/jpeg that covers 3 extension variations for the jpeg format: jpg jpeg jpe.

Use image rule which covers jpeg, png, bmp, gif, or svg including jpeg's extension variations

More on the mimes and mimetypes rules: https://laravel.com/docs/5.5/validation#rule-mimetypes

All MIME types:

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

Title: laravel validation doesnt work for .JPG

Body:
In Laravel5 I validate a picture with the following code:

public function rules() {
    return [
        'name' => 'required',
        'pic' => 'required|mimes:jpeg,png',
    ];
}

It works for files with extensions filename.jpg and filename.jpeg but it doesn't for filename.JPG.

However, it doesn't return wrong file extension but a missing file. Can anyone help?

Body:
Try this in your pic rules:

'pic' => 'required|mimes:jpeg,jpg,png',

Explanation

Had this problem and found that when you use mimes: rule, you have to specify the extensions you want as valid i. e. you have to add both jpeg and jpg extension variations.

Other solutions

Use mimetypes: rule with image/jpeg that covers 3 extension variations for the jpeg format: jpg jpeg jpe.

Use image rule which covers jpeg, png, bmp, gif, or svg including jpeg's extension variations

More on the mimes and mimetypes rules: https://laravel.com/docs/5.5/validation#rule-mimetypes

All MIME types:

A full listing of MIME types and their corresponding extensions may be found at the following location: https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types


问:
replace multiple consecutive hyphens with one
Is this possible in Javascript?

I have this from Java, but can not be used in Javascript.

```<code>s/-{2,}/-/g
</code>```

Is there another way that works?

Body:
Is this possible in Javascript?

I have this from Java, but can not be used in Javascript.

s/-{2,}/-/g

Is there another way that works?

Body: query.trim().replace(/\s\s+/g, '-').replace(/[\s.;,?%]/, '-')