问:
Spring caching ehcache issue
I have problem to set up properly caching for ehcache, Spring boot 1.5.2

```<code>@EnableCaching
@EnableScheduling
@SpringBootApplication
public class CacheTestConfig extends SpringBootServletInitializer {

@Bean
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
    EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
    factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
    factory.setShared(true);
    return factory;
}
}
</code>```

ehcache.xml

```<code><ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">

<diskStore path="java.io.tmpdir" />

<cache name="pujcka"
    maxEntriesLocalHeap="100"
    maxEntriesLocalDisk="1000"
    eternal="false"
    diskSpoolBufferSizeMB="300"
    timeToLiveSeconds="600"
    memoryStoreEvictionPolicy="LFU"
    transactionalMode="off">
    <persistence strategy="localTempSwap" />
</cache>

</ehcache>
</code>```

PujckaCachingRepository .java

```<code>public interface PujckaCachingRepository extends CrudRepository<Pujcka, Integer> {
    static final String CACHE_MAME = "pujcka";

    @Override
    @Cacheable(cacheNames = CACHE_MAME, key = "#id", condition = "#id != null") // each calling select into DB - not cached
    //@Cacheable(cacheNames = CACHE_MAME, key = "#id", condition = "#id == null") //IllegalArgumentException Popis: Null key returned for cache operation
//@Cacheable(cacheNames = CACHE_MAME)
Pujcka findOne(Integer id);

@Override
@Cacheable(cacheNames = CACHE_MAME)
Iterable<Pujcka> findAll();

@Override
    //@CachePut(cacheNames = CACHE_MAME, key = "#pujcka.id") //URL: http://localhost:8081/pujcka/nova Vyjimka: SpelEvaluationException Popis: EL1007E: Property or field 'id' cannot be found on null
@CachePut(cacheNames = CACHE_MAME)
<S extends Pujcka> S save(S pujcka);

@CacheEvict(cacheNames = CACHE_MAME)
default void refreshAll() {
    //This method will remove all 'products' from cache, say as a result of flush API.
}
</code>```

}

Pujcka.java

```<code>@Entity
@ToString
@Getter @Setter
public class Pujcka implements Serializable{

private static final long serialVersionUID = -1385887062145410511L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
</code>```

PujckaController.java

```<code>@Controller
@RequestMapping("pujcka")
public class PujckaController extends RootController {

@Autowired
private PujckaCachingRepository pujckaCachingRepository;

@RequestMapping(value = "nova", method = RequestMethod.POST)
public String ulozPujcku(@Valid Pujcka pujcka, BindingResult bindingResult, Model model) {
    pujckaCachingRepository.save(pujcka);
    pujckaCachingRepository.refreshAll();
    return "redirect:/pujcka/seznam";
}

@RequestMapping(value = "seznam", method = RequestMethod.GET)
public String seznam(Model model) {
    model.addAttribute("pujckaList", pujckaCachingRepository.findAll());
    return getRequestPath();
}

@RequestMapping(value = "edit/id/{id}", method = RequestMethod.GET)
public String edit(@PathVariable Integer id, Model model) {
    Pujcka pujcka = pujckaCachingRepository.findOne(id);
    model.addAttribute("pujcka", pujcka);
    return "pujcka/nova";
}
</code>```

When I refreshing http://localhost:8081/pujcka/seznam at first call are featched data from DB and in second call are used this data from cache. This is working fine.

When I refreshing http://localhost:8081/pujcka/edit/id/1, each time is called DB and cache is not working. ---WHY????--- What am I doing wrong?

When I edit data and save it, select all is fired and list is updated, next refresh is populated from cache - that's working fine

With this settings is used cache, but in a cache are old values

```<code>   //@Cacheable(cacheNames = CACHE_MAME)
   Pujcka findOne(Integer id);
</code>```

Thanks for help

UPDATE 1 - this helps, thanks jmw5598

```<code>@Cacheable(cacheNames = CACHE_MAME, key = "#p0")
Pujcka findOne(Integer id);

@CachePut(cacheNames = CACHE_MAME, key="#result.id")
<S extends Pujcka> S save(S pujcka);

@CacheEvict(cacheNames = CACHE_MAME)
default void refreshAll() {
}

@Cacheable(cacheNames = CACHE_MAME)
Iterable<Pujcka> findAll();
</code>```

in controller

```<code>pujckaCachingRepository.save(pujcka);
pujckaCachingRepository.refreshAll();
</code>```

I removed refreshAll() method and tried to edit some rows. For calling findOne(id) is cache working, but for findAll() is not updated, so I return refreshAll() method back.

Is this correct or is there any way how to update cache in findAll() after editing item and calling save(pujcka) ?

答:
Since you're using Spring Data JPA, I don't believe you can reference the parameters directly by their names.  You can use SpEL metadata to reference the parameters though.

```<code>@Override
@Cacheable(cacheNames = CACHE_MAME, key = "#p0", condition = "#p0 != null")
Pujcka findOne(Integer id);
</code>```

also for the @CachePut you can use the result metadata item to reference the result objects id (or whatever field you want to use as the key).

```<code>@Override
@CachePut(cacheNames = CACHE_MAME, key="#result.id")
<S extends Pujcka> S save(S pujcka);
</code>```

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-spel-context

Title: Spring caching ehcache issue

Body:
I have problem to set up properly caching for ehcache, Spring boot 1.5.2

@EnableCaching
@EnableScheduling
@SpringBootApplication
public class CacheTestConfig extends SpringBootServletInitializer {

@Bean
public CacheManager cacheManager() {
    return new EhCacheCacheManager(ehCacheCacheManager().getObject());
}

@Bean
public EhCacheManagerFactoryBean ehCacheCacheManager() {
    EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
    factory.setConfigLocation(new ClassPathResource("ehcache.xml"));
    factory.setShared(true);
    return factory;
}
}

ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">

<diskStore path="java.io.tmpdir" />

<cache name="pujcka"
    maxEntriesLocalHeap="100"
    maxEntriesLocalDisk="1000"
    eternal="false"
    diskSpoolBufferSizeMB="300"
    timeToLiveSeconds="600"
    memoryStoreEvictionPolicy="LFU"
    transactionalMode="off">
    <persistence strategy="localTempSwap" />
</cache>

</ehcache>

PujckaCachingRepository .java

public interface PujckaCachingRepository extends CrudRepository<Pujcka, Integer> {
    static final String CACHE_MAME = "pujcka";

    @Override
    @Cacheable(cacheNames = CACHE_MAME, key = "#id", condition = "#id != null") // each calling select into DB - not cached
    //@Cacheable(cacheNames = CACHE_MAME, key = "#id", condition = "#id == null") //IllegalArgumentException Popis: Null key returned for cache operation
//@Cacheable(cacheNames = CACHE_MAME)
Pujcka findOne(Integer id);

@Override
@Cacheable(cacheNames = CACHE_MAME)
Iterable<Pujcka> findAll();

@Override
    //@CachePut(cacheNames = CACHE_MAME, key = "#pujcka.id") //URL: http://localhost:8081/pujcka/nova Vyjimka: SpelEvaluationException Popis: EL1007E: Property or field 'id' cannot be found on null
@CachePut(cacheNames = CACHE_MAME)
<S extends Pujcka> S save(S pujcka);

@CacheEvict(cacheNames = CACHE_MAME)
default void refreshAll() {
    //This method will remove all 'products' from cache, say as a result of flush API.
}

}

Pujcka.java

@Entity
@ToString
@Getter @Setter
public class Pujcka implements Serializable{

private static final long serialVersionUID = -1385887062145410511L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;

PujckaController.java

@Controller
@RequestMapping("pujcka")
public class PujckaController extends RootController {

@Autowired
private PujckaCachingRepository pujckaCachingRepository;

@RequestMapping(value = "nova", method = RequestMethod.POST)
public String ulozPujcku(@Valid Pujcka pujcka, BindingResult bindingResult, Model model) {
    pujckaCachingRepository.save(pujcka);
    pujckaCachingRepository.refreshAll();
    return "redirect:/pujcka/seznam";
}

@RequestMapping(value = "seznam", method = RequestMethod.GET)
public String seznam(Model model) {
    model.addAttribute("pujckaList", pujckaCachingRepository.findAll());
    return getRequestPath();
}

@RequestMapping(value = "edit/id/{id}", method = RequestMethod.GET)
public String edit(@PathVariable Integer id, Model model) {
    Pujcka pujcka = pujckaCachingRepository.findOne(id);
    model.addAttribute("pujcka", pujcka);
    return "pujcka/nova";
}

When I refreshing http://localhost:8081/pujcka/seznam at first call are featched data from DB and in second call are used this data from cache. This is working fine.

When I refreshing http://localhost:8081/pujcka/edit/id/1, each time is called DB and cache is not working. ---WHY????--- What am I doing wrong?

When I edit data and save it, select all is fired and list is updated, next refresh is populated from cache - that's working fine

With this settings is used cache, but in a cache are old values

   //@Cacheable(cacheNames = CACHE_MAME)
   Pujcka findOne(Integer id);

Thanks for help

UPDATE 1 - this helps, thanks jmw5598

@Cacheable(cacheNames = CACHE_MAME, key = "#p0")
Pujcka findOne(Integer id);

@CachePut(cacheNames = CACHE_MAME, key="#result.id")
<S extends Pujcka> S save(S pujcka);

@CacheEvict(cacheNames = CACHE_MAME)
default void refreshAll() {
}

@Cacheable(cacheNames = CACHE_MAME)
Iterable<Pujcka> findAll();

in controller

pujckaCachingRepository.save(pujcka);
pujckaCachingRepository.refreshAll();

I removed refreshAll() method and tried to edit some rows. For calling findOne(id) is cache working, but for findAll() is not updated, so I return refreshAll() method back.

Is this correct or is there any way how to update cache in findAll() after editing item and calling save(pujcka) ?

Body:
Since you're using Spring Data JPA, I don't believe you can reference the parameters directly by their names.  You can use SpEL metadata to reference the parameters though.

@Override
@Cacheable(cacheNames = CACHE_MAME, key = "#p0", condition = "#p0 != null")
Pujcka findOne(Integer id);

also for the @CachePut you can use the result metadata item to reference the result objects id (or whatever field you want to use as the key).

@Override
@CachePut(cacheNames = CACHE_MAME, key="#result.id")
<S extends Pujcka> S save(S pujcka);

https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-spel-context


来源: stackexchange

问:
Zend_auth multiple instances
As ZF creates single instance of zend_auth.

But i need separate for admin and front panel of my site

So i have made a copy on zend/Auth.php and saved as zend/Autuadmin.php in library  and created sessin as zend_Authadmin and its now working fine at all places.

Is it correct way to do?
or can it crate problem in future ?

答:
Using Zend_Auth with Zend_Acl should you to create two roles with different access for each role. I control acl's using an ini file but it is quite easy to configure either way.

Zend_Acl

very quick example...

```<code>$acl->addRole(new Zend_Acl_Role('admin'), 'staff');
$acl->addResource(new Zend_Acl_Resource('news'));
$acl->allow('admin', array('news', 'latest'));
</code>```

Then to check you can use $acl->isAllowed()

ContentLicense: CC BY-SA 2.5

Title: Zend_auth multiple instances

Body:
Using Zend_Auth with Zend_Acl should you to create two roles with different access for each role. I control acl's using an ini file but it is quite easy to configure either way.

Zend_Acl

very quick example...

$acl->addRole(new Zend_Acl_Role('admin'), 'staff');
$acl->addResource(new Zend_Acl_Resource('news'));
$acl->allow('admin', array('news', 'latest'));

Then to check you can use $acl->isAllowed()


问:
Why can't I change the value of a variable captured by copy in a lambda function?
I'm reading the C++ Programming Language by B. Stroustrup in its section 11.4.3.4 "mutable Lambdas", which says the following:

Usually, we don’t want to modify the state of the function object (the
  closure), so by default we can’t. That is, the operator()() for the
  generated function object (§11.4.1) is a const member function. In the
  unlikely event that we want to modify the state (as opposed to
  modifying the state of some variable captured by reference; §11.4.3),
  we can declare the lambda mutable.

I don't understand why the default for the operator()() is const when the variable is captured by value. What's the rational for this? What could go wrong when I change the value of a variable, which is copied into the function object?

答:
It is easier to reason about const data.

By defaulting const, brief lamndas are easier to reason about.  If you want mutability you can ask for it.

Many function objects in std are copied around; const objects that are copied have simpler state to track.

ContentLicense: CC BY-SA 3.0


问:
CMake link static library error, while with NDK works fine
I'm trying to build my native library with CMake in latest Android Studio. I prepared gradle scripts for this, no any problems, but I found a small problem - I can not compile my library for x86 arch.

Some time before...
My library uses OpenSSL AES/DES encryption/decryption. I compiled OpenSSL 1.0.2k as is (static library), linked it to my shared library and all was fine except x86 arch - there was an error shared library text segment is not shareable while dlopen on then device. Then I recompiled OpenSSL with -fPIC flag, linked it again and error went away. I was building with NDK 13b.

Now...
I am trying to migrate from NDK to CMake because it is has more features for me and Android Studio can normally autocomplete and lint C/C++ code only with CMake. I wrote CMakeList.txt and it works, but problem with shared library text segment is not shareable appeared again, but on linkage step of CMake build process. Error:

```<code>D:/User/AppData/Local/Android/sdk/ndk-bundle/toolchains/x86-4.9/prebuilt/windows-x86_64/lib/gcc/i686-linux-android/4.9.x/../../../../i686-linux-android/bin\ld: warning: shared library text segment is not shareable
  D:/User/AppData/Local/Android/sdk/ndk-bundle/toolchains/x86-4.9/prebuilt/windows-x86_64/lib/gcc/i686-linux-android/4.9.x/../../../../i686-linux-android/bin\ld: error: treating warnings as errors
</code>```

I disabled treating this warning as error and shared library text segment is not shareable appeared while dlopen on the device again.

What is the problem? Why NDK builds without any problems and CMake does not?

P.S. I tried different CMAKE flags (such as CMAKE_POSITION_INDEPENDENT_CODE) and nothing works. This problem occurrs only for x86 arch.

CMakeLists.txt (Build failed for x86, all others - no problems):

```<code>cmake_minimum_required(VERSION 3.4.1)

include_directories(include/)
find_library(log-lib log)
add_library(libcrypto STATIC IMPORTED)
add_library(libssl STATIC IMPORTED)
add_library(testlib SHARED test.c)

set_target_properties(libcrypto
                      PROPERTIES
                      IMPORTED_LOCATION
                      ${CMAKE_SOURCE_DIR}/static/${ANDROID_ABI}/libcrypto.a)
set_target_properties(libssl
                      PROPERTIES
                      IMPORTED_LOCATION
                      ${CMAKE_SOURCE_DIR}/static/${ANDROID_ABI}/libssl.a)

target_link_libraries(testlib libcrypto libssl ${log-lib})

set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fPIC")
set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} -fPIC")
</code>```

Android.mk (NDK14b, All archs - no problems):

```<code>LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := $(LOCAL_PATH)/static/$(TARGET_ARCH_ABI)/libcrypto.a
LOCAL_MODULE := crypto
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := $(LOCAL_PATH)/static/$(TARGET_ARCH_ABI)/libssl.a
LOCAL_MODULE := ssl
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LCOAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := test.c
LOCAL_MODULE := testlib
LOCAL_STATIC_LIBRARIES := crypto ssl

include $(BUILD_SHARED_LIBRARY)
</code>```

Thanks in advance for any help!

答:
```<code>set(CMAKE_SHARED_LINKER_FLAGS "-Wall -v -Wl, --no-warn-shared-textrel")
</code>```

this exact toolcain is treating warnings as errors, so just add this to suppress the warning. --no-warn-shared-textrel is the key

Body:
I'm trying to build my native library with CMake in latest Android Studio. I prepared gradle scripts for this, no any problems, but I found a small problem - I can not compile my library for x86 arch.

Some time before...
My library uses OpenSSL AES/DES encryption/decryption. I compiled OpenSSL 1.0.2k as is (static library), linked it to my shared library and all was fine except x86 arch - there was an error shared library text segment is not shareable while dlopen on then device. Then I recompiled OpenSSL with -fPIC flag, linked it again and error went away. I was building with NDK 13b.

Now...
I am trying to migrate from NDK to CMake because it is has more features for me and Android Studio can normally autocomplete and lint C/C++ code only with CMake. I wrote CMakeList.txt and it works, but problem with shared library text segment is not shareable appeared again, but on linkage step of CMake build process. Error:

D:/User/AppData/Local/Android/sdk/ndk-bundle/toolchains/x86-4.9/prebuilt/windows-x86_64/lib/gcc/i686-linux-android/4.9.x/../../../../i686-linux-android/bin\ld: warning: shared library text segment is not shareable
  D:/User/AppData/Local/Android/sdk/ndk-bundle/toolchains/x86-4.9/prebuilt/windows-x86_64/lib/gcc/i686-linux-android/4.9.x/../../../../i686-linux-android/bin\ld: error: treating warnings as errors

I disabled treating this warning as error and shared library text segment is not shareable appeared while dlopen on the device again.

What is the problem? Why NDK builds without any problems and CMake does not?

P.S. I tried different CMAKE flags (such as CMAKE_POSITION_INDEPENDENT_CODE) and nothing works. This problem occurrs only for x86 arch.

CMakeLists.txt (Build failed for x86, all others - no problems):

cmake_minimum_required(VERSION 3.4.1)

include_directories(include/)
find_library(log-lib log)
add_library(libcrypto STATIC IMPORTED)
add_library(libssl STATIC IMPORTED)
add_library(testlib SHARED test.c)

set_target_properties(libcrypto
                      PROPERTIES
                      IMPORTED_LOCATION
                      ${CMAKE_SOURCE_DIR}/static/${ANDROID_ABI}/libcrypto.a)
set_target_properties(libssl
                      PROPERTIES
                      IMPORTED_LOCATION
                      ${CMAKE_SOURCE_DIR}/static/${ANDROID_ABI}/libssl.a)

target_link_libraries(testlib libcrypto libssl ${log-lib})

set (CMAKE_POSITION_INDEPENDENT_CODE TRUE)
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -fPIC")
set(CMAKE_STATIC_LINKER_FLAGS "${CMAKE_STATIC_LINKER_FLAGS} -fPIC")

Android.mk (NDK14b, All archs - no problems):

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := $(LOCAL_PATH)/static/$(TARGET_ARCH_ABI)/libcrypto.a
LOCAL_MODULE := crypto
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := $(LOCAL_PATH)/static/$(TARGET_ARCH_ABI)/libssl.a
LOCAL_MODULE := ssl
include $(PREBUILT_STATIC_LIBRARY)

include $(CLEAR_VARS)
LCOAL_C_INCLUDES := $(LOCAL_PATH)/include
LOCAL_SRC_FILES := test.c
LOCAL_MODULE := testlib
LOCAL_STATIC_LIBRARIES := crypto ssl

include $(BUILD_SHARED_LIBRARY)

Thanks in advance for any help!

Body:
set(CMAKE_SHARED_LINKER_FLAGS "-Wall -v -Wl, --no-warn-shared-textrel")

this exact toolcain is treating warnings as errors, so just add this to suppress the warning. --no-warn-shared-textrel is the key


问:
Rails: polymorphic associations, find commented on
I've implemented polymorphic comments on my Rails app using this tutorial.

So I have:

```<code>class Place < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end
</code>```

Now I want to index all comments and join them with the places they comment on, but I have no idea on how to achieve this.

In my comments_controller.rb I have:

```<code>class CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end
end
</code>```

And in my comments index.html.erb I can access:

```<code><%= comment.commentable_type %>
<%= comment.commentable_id %>
</code>```

But how do I access the actual attributes of what the comments are on, example: <%= comment.place.name %>?

I believe it is related to this answer but I don't know how: rails joins polymorphic association

答:
mccalljt answer's above is much better

Believe I've got it:

Added to comment.rb:

```<code>belongs_to :place, foreign_key: 'commentable_id'
</code>```

Added to comments_controller.rb:

```<code>@comments = Comment.where(commentable_type: "Place").joins(:place)
</code>```

Though this is not reusable when there are more associations, but I could change it to:

```<code>@place_comments = Comment.where(commentable_type: "Place").joins(:place)
@other_comments = Comment.where(commentable_type: "Other").joins(:other)
</code>```

Body:
I've implemented polymorphic comments on my Rails app using this tutorial.

So I have:

class Place < ApplicationRecord
  has_many :comments, as: :commentable
end

class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true
end

Now I want to index all comments and join them with the places they comment on, but I have no idea on how to achieve this.

In my comments_controller.rb I have:

class CommentsController < ApplicationController
  def index
    @comments = Comment.all
  end
end

And in my comments index.html.erb I can access:

<%= comment.commentable_type %>
<%= comment.commentable_id %>

But how do I access the actual attributes of what the comments are on, example: <%= comment.place.name %>?

I believe it is related to this answer but I don't know how: rails joins polymorphic association

Body:
mccalljt answer's above is much better

Believe I've got it:

Added to comment.rb:

belongs_to :place, foreign_key: 'commentable_id'

Added to comments_controller.rb:

@comments = Comment.where(commentable_type: "Place").joins(:place)

Though this is not reusable when there are more associations, but I could change it to:

@place_comments = Comment.where(commentable_type: "Place").joins(:place)
@other_comments = Comment.where(commentable_type: "Other").joins(:other)


问:
Java Concurrent Modification Error HashMap
Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?</p>

```<code>Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}
</code>```

答:
This

```<code>for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}
</code>```

will always throw a ConcurrentModificationException because you remove items while you iterate. What you need is an Iterator which has the remove operation:

```<code>for(Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<String, Integer> entry = it.next();
    if(entry.getValue() < 50) {
      it.remove();
    }
}
</code>```

There is also the ConcurrentHashMap which supports concurrent operations and only locks buckets if you need it.

Body:
Fun question here. Why does the first version of this throw a concurrent modification error, while the second does not. Should this happen?

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Map<String,Integer> map = new HashMap<>();
... // Populate the map
for(String key : new ArrayList<String>(map.keySet())){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

Body:
This

for(String key : map.keySet()){
    if(map.get(key) < 50){
        map.remove(key);
    }
}

will always throw a ConcurrentModificationException because you remove items while you iterate. What you need is an Iterator which has the remove operation:

for(Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<String, Integer> entry = it.next();
    if(entry.getValue() < 50) {
      it.remove();
    }
}

There is also the ConcurrentHashMap which supports concurrent operations and only locks buckets if you need it.


问:
Applying a Popover Message Box OnClick
I'm new to this. I found an example of popover message box in the link below. I tried to implement it and it doesn't seem to work am i missing something?

Or is their an easier way to implement a popover message box (onclick) that looks like the on in the image.

Link: http://getbootstrap.com/javascript/#js-individual-compiled

Image:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="left" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on left
</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="top" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on top
</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="bottom" data-content="Vivamus
sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on bottom
</button>

<button type="button" class="btn btn-default" data-container="body" data-toggle="popover" data-placement="right" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
  Popover on right
</button>```

答:
The popover functionality is optional in Bootstrap. You need to enable it by adding the following code:</p>

```<code><script>
$(function () {
  $('[data-toggle="popover"]').popover()
})
</script>
</code>```

Title: Applying a Popover Message Box OnClick

Body:
The popover functionality is optional in Bootstrap. You need to enable it by adding the following code:

<script>
$(function () {
  $('[data-toggle="popover"]').popover()
})
</script>


问:
What exactly does lowering the priority of a constraint do?
I am constructing a variable size table view within another view. The table view should not scroll so I am programmatically determining its content size and adjusting a height constraint so that the table view always fits its content.

The problem I run into is a warning about a broken constraint:

```<code>Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x170498b00 h=--& v=--& UIView:0x1024f2c90.height == 322   (active)>",
"<NSLayoutConstraint:0x17428d660 UITableView:0x103152400.height == 322   (active)>",
"<NSLayoutConstraint:0x174482da0 V:[UITableView:0x103152400]-(27)-|   (active, names: '|':UIView:0x1024f2c90 )>",
"<NSLayoutConstraint:0x17429da10 V:|-(16)-[UITableView:0x103152400]   (active, names: '|':UIView:0x1024f2c90 )>"
)
</code>```

To fix this, I tried 2 things:

Set translatesAutoresizingMaskIntoConstraints = false.  This causes everything to go haywire with the table view.

Lower the priority of the adjustable height constraint to 999.

Point 2 solves my problem and I'm able to adjust the height of the view using the lower priority constraint.  But, I don't understand why this works.

So, how does Auto Layout interpret the priority of a constraint?  I would've expected the NSAutoresizingMaskLayoutConstraint to take over the lower priority constraint and make it so I could not resize the view using the constraint.

答:
Since you are setting the height at run time I would select the height/vertical constraint in IB you don't need at run time and turn the 'Placeholder' for the constraint to 'Remove at build time', this should remove your warnings.

The priority setting determines when there are conflicting constraints which one will be used.

Body:
I am constructing a variable size table view within another view. The table view should not scroll so I am programmatically determining its content size and adjusting a height constraint so that the table view always fits its content.

The problem I run into is a warning about a broken constraint:

Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
    (1) look at each constraint and try to figure out which you don't expect;
    (2) find the code that added the unwanted constraint or constraints and fix it.
(Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x170498b00 h=--& v=--& UIView:0x1024f2c90.height == 322   (active)>",
"<NSLayoutConstraint:0x17428d660 UITableView:0x103152400.height == 322   (active)>",
"<NSLayoutConstraint:0x174482da0 V:[UITableView:0x103152400]-(27)-|   (active, names: '|':UIView:0x1024f2c90 )>",
"<NSLayoutConstraint:0x17429da10 V:|-(16)-[UITableView:0x103152400]   (active, names: '|':UIView:0x1024f2c90 )>"
)

To fix this, I tried 2 things:

Set translatesAutoresizingMaskIntoConstraints = false.  This causes everything to go haywire with the table view.

Lower the priority of the adjustable height constraint to 999.

Point 2 solves my problem and I'm able to adjust the height of the view using the lower priority constraint.  But, I don't understand why this works.

So, how does Auto Layout interpret the priority of a constraint?  I would've expected the NSAutoresizingMaskLayoutConstraint to take over the lower priority constraint and make it so I could not resize the view using the constraint.


问:
Get value option page ACF
I've created an ACF option page, all went good. I created some custom fields, once again all went good. I also saved data in the fields, all went good.

I looked in the database and it was saved under wp_options, so all went good.

Now I wan't to get the values in an php script on the backend.

Let's say my field name is field_name.

I used get_field('field_name', 'option');, it didn't give me anything.

I also tried get_fields(); - this gave me an array with the option fields like this:

```<code>array(3) {
  ["field_name"]=> array(0) { }
  ["field_name1"]=> bool(false)
  ["field_name2"]=> string(0) ""
}
</code>```

So, somehow the values are empty.

I checked the database again, but they're there.

```<code>$field = get_field_object('field_879e859f07841');
var_dump(get_post_meta ( $field['key'], 'field_name'));
</code>```

This gave the same empty array..

I can't figure this out.

Can someone help with figuring what's happening?

答:
Please check ACF Get values

To Display a field:

```<code><p><?php the_field('field_name', 'option'); ?></p>
</code>```

To retrieve a field as a variable:

```<code><?php

$variable = get_field('field_name', 'option');

// do something with $variable

?>
</code>```

Title: Get value option page ACF

Body:
I've created an ACF option page, all went good. I created some custom fields, once again all went good. I also saved data in the fields, all went good.

I looked in the database and it was saved under wp_options, so all went good.

Now I wan't to get the values in an php script on the backend.

Let's say my field name is field_name.

I used get_field('field_name', 'option');, it didn't give me anything.

I also tried get_fields(); - this gave me an array with the option fields like this:

array(3) {
  ["field_name"]=> array(0) { }
  ["field_name1"]=> bool(false)
  ["field_name2"]=> string(0) ""
}

So, somehow the values are empty.

I checked the database again, but they're there.

$field = get_field_object('field_879e859f07841');
var_dump(get_post_meta ( $field['key'], 'field_name'));

This gave the same empty array..

I can't figure this out.

Can someone help with figuring what's happening?

Body:
Please check ACF Get values

To Display a field:

<p><?php the_field('field_name', 'option'); ?></p>

To retrieve a field as a variable:

<?php

$variable = get_field('field_name', 'option');

// do something with $variable

?>


问:
Simple Gif like animation with Spritekit
I can't really find a simple solution for this, every example I see only shows very complex solutions, but all I want is 2-3 images that cycle so it appears as if it is animated. Same effect as an animated Gif.  For now I have this to create an image  </p>

```<code>MonsterNode = SKSpriteNode(imageNamed: "MonsterNode_GameScene")
</code>```

<p>but how would I set MonsterNode variable to an animation of this sort? I am really looking for the very least amount of code needed to achieve this. </p>

答:
I was getting the same issue of big red X.
So instead of defining the monsterNode in code. I created the monstor on sks screen by dragging first image of animation from atlas folder. Then assign it a name: monsterNode from properties section. Here's the code </p>

```<code>var runAnimation = [SKTexture]()

override func didMove(to view: SKView) {
    let runAtlas = SKTextureAtlas(named: "run")
    for index in 1...runAtlas.textureNames.count{
        let textureName = String.init(format: "run%1d", index)
        runAnimation.append(SKTexture(imageNamed: textureName))
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let monsterNode = self.childNode(withName: "monsterNode")
    if(monsterNode != nil){
        let animation = SKAction.animate(with: runAnimation, timePerFrame: 0.1)
        monsterNode?.run(SKAction.repeatForever(animation))
     }
}
</code>```

Body:
I can't really find a simple solution for this, every example I see only shows very complex solutions, but all I want is 2-3 images that cycle so it appears as if it is animated. Same effect as an animated Gif.  For now I have this to create an image

MonsterNode = SKSpriteNode(imageNamed: "MonsterNode_GameScene")

but how would I set MonsterNode variable to an animation of this sort? I am really looking for the very least amount of code needed to achieve this.

Body:
I was getting the same issue of big red X.
So instead of defining the monsterNode in code. I created the monstor on sks screen by dragging first image of animation from atlas folder. Then assign it a name: monsterNode from properties section. Here's the code

var runAnimation = [SKTexture]()

override func didMove(to view: SKView) {
    let runAtlas = SKTextureAtlas(named: "run")
    for index in 1...runAtlas.textureNames.count{
        let textureName = String.init(format: "run%1d", index)
        runAnimation.append(SKTexture(imageNamed: textureName))
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let monsterNode = self.childNode(withName: "monsterNode")
    if(monsterNode != nil){
        let animation = SKAction.animate(with: runAnimation, timePerFrame: 0.1)
        monsterNode?.run(SKAction.repeatForever(animation))
     }
}


问:
Making ONLY part of an axis show in an R plot
Background: As you can see in the image below, currently the y-axis extends from -2 to 2 (i.e, the y-axis contains both positive and negative values).

Question:

Keeping everything as shown in the image below, I was wondering is there might be a way to only show the positive part of the y-axis (from 0 on) and somehow HIDE the negative portion of the y-axis? (please see the R code further below)

Here is the R code:

```<code>if(!require(library(plotrix))){install.packages('plotrix') }
library(plotrix)          ## A package for drawing ellipses ##

plot(1, ty='n', ann = F, axes = F, xlim = c(-4, 6), ylim = c(-2.5, 2) ) ## platform for ellipses

axis(side = 2)   ## HERE is my question ## ???

draw.ellipse(x = rep(1, 11), y = rep(-1.2, 11),
     a = seq(1, 6, by = .4), b = seq(1/4.5, 6/4.5 , by = .4/4.5 ),
     lty = 2, border = 'gray60' )       ## Draw multiple Concentric ellipses ##

AA <- seq(-4, 6, len = 13)     ## A range of values on the x-xis just like "xlim" ##
BB <- dcauchy( AA, 1, .95)*5   ## The Height for the AA according to a distribution ##

segments(AA, rep(-1.2, length(AA) ), AA, BB, lty = 3, lwd = 2, col= 'green4' )

curve(dcauchy(x, 1, .95)*5, -4, 6, add = T, col ='magenta', lwd = 3)
</code>```

答:
See ?axis. You just need to specify the at argument.

axis(side = 2, at = 0:2)

Body:
Background: As you can see in the image below, currently the y-axis extends from -2 to 2 (i.e, the y-axis contains both positive and negative values).

Question:

Keeping everything as shown in the image below, I was wondering is there might be a way to only show the positive part of the y-axis (from 0 on) and somehow HIDE the negative portion of the y-axis? (please see the R code further below)

Here is the R code:

if(!require(library(plotrix))){install.packages('plotrix') }
library(plotrix)          ## A package for drawing ellipses ##

plot(1, ty='n', ann = F, axes = F, xlim = c(-4, 6), ylim = c(-2.5, 2) ) ## platform for ellipses

axis(side = 2)   ## HERE is my question ## ???

draw.ellipse(x = rep(1, 11), y = rep(-1.2, 11),
     a = seq(1, 6, by = .4), b = seq(1/4.5, 6/4.5 , by = .4/4.5 ),
     lty = 2, border = 'gray60' )       ## Draw multiple Concentric ellipses ##

AA <- seq(-4, 6, len = 13)     ## A range of values on the x-xis just like "xlim" ##
BB <- dcauchy( AA, 1, .95)*5   ## The Height for the AA according to a distribution ##

segments(AA, rep(-1.2, length(AA) ), AA, BB, lty = 3, lwd = 2, col= 'green4' )

curve(dcauchy(x, 1, .95)*5, -4, 6, add = T, col ='magenta', lwd = 3)


问:
Module 'GoogleMobileAds' not found in iOS
Came across a topic with similar problem, but was unable to solve it.

Integrated Admob ads in Unity app for ios and loaded the project in XCode. Added framework GoogleMobileAds simply dragging it into the project window. Unfortunately when you build the project the error is displayed.

I tryed replace GoogleMobileAds.h on #import <GoogleMobileAds/GoogleMobileAds.h> in GADUNativeCustomTemplateAd.h but it not help me.

Used Google Mobile Ads Unity Plugin v3.0.4
Xcode v. 7.3.1
Error: umbrella header googlemobileads h not found
1 img
2 img

答:
I finally found the solution in this video https://www.youtube.com/watch?v=rxO_rcMxGU4, here is a summary:

Download googlemobileadssdkios.zip from https://firebase.google.com/docs/admob/ios/download

Unzip file. Go to Project Navigator View. Move the unzip file inside the Framework folder.

Build the code, if it doesn't work then substitute the string that gives error with

(void)loadRequest:(GADRequest *)request withAdUnitID:(NSString *)adUnitID userID:(NSString *)userID {

[self.rewardBasedVideo loadRequest:request withAdUnitID:adUnitID];
}


问:
define a function alias in VBA, possible?
I am using VBA behind MS Access
Say I have global methods foo1 and foo2 that gets the same arguments but do different things.
I know that in C++ I can assign a function an alias. Something like:
instead of:

```<code>If (term) then
   foo1 arg1, arg2, arg3
else
   foo2 arg1, arg2, arg3
End If
</code>```

I want to write:

```<code>Var new_func = Iff (term, foo1,foo2)
new_func arg1, arg2, arg3
</code>```

Can I do this on vba?

答:
Would Run suit?

```<code>new_func = IIf(term, "foo1", "foo2")
''new_func arg1, arg2, arg3

res = Run(new_func, "a", "b", 1)
</code>```

More information: http://msdn.microsoft.com/en-us/library/aa199108(office.10).aspx

Body:
I am using VBA behind MS Access
Say I have global methods foo1 and foo2 that gets the same arguments but do different things.
I know that in C++ I can assign a function an alias. Something like:
instead of:

If (term) then
   foo1 arg1, arg2, arg3
else
   foo2 arg1, arg2, arg3
End If

I want to write:

Var new_func = Iff (term, foo1,foo2)
new_func arg1, arg2, arg3

Can I do this on vba?

Body:
Would Run suit?

new_func = IIf(term, "foo1", "foo2")
''new_func arg1, arg2, arg3

res = Run(new_func, "a", "b", 1)

More information: http://msdn.microsoft.com/en-us/library/aa199108(office.10).aspx


问:
How to perform DTW on an array of MFCC coefficients?
Currently I'm working on speech recognition project in MATLAB.
 I've taken two voice signals and have extracted the MFCC coefficients of the same.
As far as I know, I should now calculate the Euclidean distance between the two and then apply the DTW algorithm. That's why I calculated the distnace between the two and got an array of the distances.
So my question is how to implement DTW on resultant array?

Here's my MATLAB code:

clear all; close all; clc;

```<code>% Define variables
Tw = 25;                % analysis frame duration (ms)
Ts = 10;                % analysis frame shift (ms)
alpha = 0.97;           % preemphasis coefficient
M = 20;                 % number of filterbank channels
C = 12;                 % number of cepstral coefficients
L = 22;                 % cepstral sine lifter parameter
LF = 300;               % lower frequency limit (Hz)
HF = 3700;              % upper frequency limit (Hz)
wav_file = 'Play.wav';  % input audio filename
wav_file1 = 'Next.wav';

% Read speech samples, sampling rate and precision from file
[ speech, fs, nbits ] = wavread( wav_file );
[ speech1, fs, nbits ] = wavread( wav_file1 );

% Feature extraction (feature vectors as columns)
[ MFCCs, FBEs, frames ] = ...
                mfcc( speech, fs, Tw, Ts, alpha, @hamming, [LF HF], M, C+1, L );
[ MFCC1s, FBEs, frames ] = ...
                mfcc( speech1, fs, Tw, Ts, alpha, @hamming, [LF HF], M, C+1, L );

L = pdist2(MFCCs, MFCC1s, 'euclidean');
</code>```

答:
Disclaimer: I'm not a matlab user.

I think there may be a misconception in your statement "I should now calculate the Euclidean distance between the two and then apply the DTW algorithm".

The point of using DTW is that you have to compare two series (MFCCs series for wav 1 and for wav 2), and chances are that both wavs are of different duration, so you'll end up with two sets of MFCCs vectors of different size. DTW helps you compare the two MFCCs series regardless of their sizes (see https://en.wikipedia.org/wiki/Dynamic_time_warping).

So, for example, if you have extracted, let's say, 3 MFCC feature vectors for wav 1, and 5 MFCC feature vectors for wav 2, by applying DTW you can compare them, thus effectively obtaining the difference or distance between them. You don't have to calculate distance "before" DTW, you use DTW to calculate it (in fact, I don't know how would I calculate a distance between to series of different length otherwise).

Like I said at the beginning, I'm not a matlab user, but a quick google search for "matlab dtw" pointed me to this article: https://www.mathworks.com/help/signal/ref/dtw.html, in which they refer to dtw():

```<code>  dist = dtw(x,y) stretches two vectors, x and y, onto a common set of
  instants such that dist, the sum of the Euclidean distances between
  corresponding points, is smallest
</code>```

Body:
Currently I'm working on speech recognition project in MATLAB.
 I've taken two voice signals and have extracted the MFCC coefficients of the same.
As far as I know, I should now calculate the Euclidean distance between the two and then apply the DTW algorithm. That's why I calculated the distnace between the two and got an array of the distances.
So my question is how to implement DTW on resultant array?

Here's my MATLAB code:

clear all; close all; clc;

% Define variables
Tw = 25;                % analysis frame duration (ms)
Ts = 10;                % analysis frame shift (ms)
alpha = 0.97;           % preemphasis coefficient
M = 20;                 % number of filterbank channels
C = 12;                 % number of cepstral coefficients
L = 22;                 % cepstral sine lifter parameter
LF = 300;               % lower frequency limit (Hz)
HF = 3700;              % upper frequency limit (Hz)
wav_file = 'Play.wav';  % input audio filename
wav_file1 = 'Next.wav';

% Read speech samples, sampling rate and precision from file
[ speech, fs, nbits ] = wavread( wav_file );
[ speech1, fs, nbits ] = wavread( wav_file1 );

% Feature extraction (feature vectors as columns)
[ MFCCs, FBEs, frames ] = ...
                mfcc( speech, fs, Tw, Ts, alpha, @hamming, [LF HF], M, C+1, L );
[ MFCC1s, FBEs, frames ] = ...
                mfcc( speech1, fs, Tw, Ts, alpha, @hamming, [LF HF], M, C+1, L );

L = pdist2(MFCCs, MFCC1s, 'euclidean');

Body:
Disclaimer: I'm not a matlab user.

I think there may be a misconception in your statement "I should now calculate the Euclidean distance between the two and then apply the DTW algorithm".

The point of using DTW is that you have to compare two series (MFCCs series for wav 1 and for wav 2), and chances are that both wavs are of different duration, so you'll end up with two sets of MFCCs vectors of different size. DTW helps you compare the two MFCCs series regardless of their sizes (see https://en.wikipedia.org/wiki/Dynamic_time_warping).

So, for example, if you have extracted, let's say, 3 MFCC feature vectors for wav 1, and 5 MFCC feature vectors for wav 2, by applying DTW you can compare them, thus effectively obtaining the difference or distance between them. You don't have to calculate distance "before" DTW, you use DTW to calculate it (in fact, I don't know how would I calculate a distance between to series of different length otherwise).

Like I said at the beginning, I'm not a matlab user, but a quick google search for "matlab dtw" pointed me to this article: https://www.mathworks.com/help/signal/ref/dtw.html, in which they refer to dtw():

  dist = dtw(x,y) stretches two vectors, x and y, onto a common set of
  instants such that dist, the sum of the Euclidean distances between
  corresponding points, is smallest


问:
Java compiler level does not match the version of the installed Java project facet", but it does
I'm updating an ancient WebSphere 5 web appliction, porting it to run in Tomcat, replacing IBM RAD 7.0 with Eclipse Kepler, and using Maven for dependencies.

I am getting the "Faceted Project Problem (Java Version Mismatch)" error.  The specific text is "Java compiler level does not match the version of the installed Java project facet.".

Here's where I've checked for compiler version:

I right-click on the project and select Properties.  I click "Project Facets", and see my Java facet says 1.7.

I check the "Java Compiler" properties page (I'd like the "Enable project specific settings" box to remain unchecked, but it's checked and when I uncheck it, Maven->Refresh Project, and it's checked again.).  The compiler version is grayed out, but it is also 1.7.

Window/Preferences/Java/Compiler is also 1.7, and the "Use default compliance settings" box is checked.

Windows/Preferences/Java/Installed JREs has both jdk1.7.0_71 (checked), and jre7 available.

pom.xml also says 1.7:

```<code>    <project xmlns="http://maven.apache.org/POM/4.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        ...
        <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
        ...
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.opennms.core.snmp</groupId>
                <artifactId>org.opennms.core.snmp.joesnmp</artifactId>
                <version>0.2.6</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
</code>```

Where am I setting a Java compiler level that "does not match the version of the installed Java project facet"?

答: I had similar case.. changing "Project Faces" brought no results. In my case helped right click on project -> properties -> java compplier and then uncheck option "use compliance from execution environemnt..." and choose your java version (in my case 1.8)</p>

Body:
I'm updating an ancient WebSphere 5 web appliction, porting it to run in Tomcat, replacing IBM RAD 7.0 with Eclipse Kepler, and using Maven for dependencies.

I am getting the "Faceted Project Problem (Java Version Mismatch)" error.  The specific text is "Java compiler level does not match the version of the installed Java project facet.".

Here's where I've checked for compiler version:

I right-click on the project and select Properties.  I click "Project Facets", and see my Java facet says 1.7.

I check the "Java Compiler" properties page (I'd like the "Enable project specific settings" box to remain unchecked, but it's checked and when I uncheck it, Maven->Refresh Project, and it's checked again.).  The compiler version is grayed out, but it is also 1.7.

Window/Preferences/Java/Compiler is also 1.7, and the "Use default compliance settings" box is checked.

Windows/Preferences/Java/Installed JREs has both jdk1.7.0_71 (checked), and jre7 available.

pom.xml also says 1.7:

    <project xmlns="http://maven.apache.org/POM/4.0.0"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        ...
        <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
        ...
    </build>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.opennms.core.snmp</groupId>
                <artifactId>org.opennms.core.snmp.joesnmp</artifactId>
                <version>0.2.6</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Where am I setting a Java compiler level that "does not match the version of the installed Java project facet"?


问:
Programatically adding a Carousel as a SubView
I am trying to add Carousel on the View as follows. As I testing it, nothing happens, it does not even hit any of carousel delegate method.

ViewController.h

```<code>@property (nonatomic, strong) iCarousel *carousel;
</code>```

ViewController.m

```<code>carousel = [[iCarousel alloc] initWithFrame:CGRectMake(25, 50, self.view.frame.size.width-50, self.view.frame.size.height-75)];
[self.view addSubview:carousel];

carousel.delegate = self;
carousel.dataSource = self;

self.carousel.type = iCarouselTypeCoverFlow2;

self.items = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
    [carouselItems addObject:@(i)];
}
[carousel reloadData];
</code>```

答:
Replace your code with this</p>

```<code>self.carousel = [[iCarousel alloc] initWithFrame:CGRectMake(25, 50, self.view.frame.size.width-50, self.view.frame.size.height-75)];
self.carousel.delegate = self;
self.carousel.dataSource = self;
self.carousel.type = iCarouselTypeCoverFlow2;
[self.view addSubview:self.carousel];

self.items = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
    [carouselItems addObject:@(i)];
}
[self.carousel reloadData];
</code>```

Body:
I am trying to add Carousel on the View as follows. As I testing it, nothing happens, it does not even hit any of carousel delegate method.

ViewController.h

@property (nonatomic, strong) iCarousel *carousel;

ViewController.m

carousel = [[iCarousel alloc] initWithFrame:CGRectMake(25, 50, self.view.frame.size.width-50, self.view.frame.size.height-75)];
[self.view addSubview:carousel];

carousel.delegate = self;
carousel.dataSource = self;

self.carousel.type = iCarouselTypeCoverFlow2;

self.items = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
    [carouselItems addObject:@(i)];
}
[carousel reloadData];

Body:
Replace your code with this

self.carousel = [[iCarousel alloc] initWithFrame:CGRectMake(25, 50, self.view.frame.size.width-50, self.view.frame.size.height-75)];
self.carousel.delegate = self;
self.carousel.dataSource = self;
self.carousel.type = iCarouselTypeCoverFlow2;
[self.view addSubview:self.carousel];

self.items = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
    [carouselItems addObject:@(i)];
}
[self.carousel reloadData];


问:
CSS grid wrapping
Is it possible to make a CSS grid wrap without using media queries?

In my case, I have a non-deterministic number of items that I want placed in a grid and I want that grid to wrap. Using Flexbox, I'm unable to reliably space things nicely. I'd like to avoid a bunch of media queries too.

Here's some sample code:

.grid {
  display: grid;
  grid-gap: 10px;
  grid-auto-flow: column;
  grid-template-columns: 186px 186px 186px 186px;
}

.grid > * {
  background-color: green;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

And here's a GIF image:

As a side-note, if anyone can tell me how I could avoid specifying the width of all the items like I am with grid-template-columns that would be great. I'd prefer the children to specify their own width.

答:
You may be looking for auto-fill:

```<code>grid-template-columns: repeat(auto-fill, 186px);
</code>```

Demo: http://codepen.io/alanbuchanan/pen/wJRMox

To use up the available space more efficiently, you could use minmax, and pass in auto as the second argument:

```<code>grid-template-columns: repeat(auto-fill, minmax(186px, auto));
</code>```

Demo: http://codepen.io/alanbuchanan/pen/jBXWLR

If you don't want the empty columns, you could use auto-fit instead of auto-fill.

ContentLicense: CC BY-SA 4.0

Title: CSS grid wrapping

Body:
Is it possible to make a CSS grid wrap without using media queries?

In my case, I have a non-deterministic number of items that I want placed in a grid and I want that grid to wrap. Using Flexbox, I'm unable to reliably space things nicely. I'd like to avoid a bunch of media queries too.

Here's some sample code:

.grid {
  display: grid;
  grid-gap: 10px;
  grid-auto-flow: column;
  grid-template-columns: 186px 186px 186px 186px;
}

.grid > * {
  background-color: green;
  height: 200px;
}

1

2

3

4

And here's a GIF image:

As a side-note, if anyone can tell me how I could avoid specifying the width of all the items like I am with grid-template-columns that would be great. I'd prefer the children to specify their own width.

Body:
You may be looking for auto-fill:

grid-template-columns: repeat(auto-fill, 186px);

Demo: http://codepen.io/alanbuchanan/pen/wJRMox

To use up the available space more efficiently, you could use minmax, and pass in auto as the second argument:

grid-template-columns: repeat(auto-fill, minmax(186px, auto));

Demo: http://codepen.io/alanbuchanan/pen/jBXWLR

If you don't want the empty columns, you could use auto-fit instead of auto-fill.


问:
How can I make a random set generator with equal possibility to generate uniform sets and non-uniform sets?
So let's say I have a set of items:

```<code>['a', 'b', 'c', 'd', 'e']
</code>```

and I want to generate a random set (order does not matter) from those choices:

```<code>['a', 'e', 'd', 'c']
</code>```

which is child's play, but instead of it being unlikely to generate a uniform result:

```<code>['c', 'c', 'c', 'c']
</code>```

compared to something less uniform like:

```<code>['a', 'b', 'e', 'd']
</code>```

I want to make it equally likely that a uniform set can be generated as it is likely that a non-uniform set can be generated.

Edit:

The result I'm trying to express is not just ['c', 'c', 'c', 'c', 'c', 'c'] or ['d', 'd', 'd', 'd', 'd', 'd'] but also the areas in between those uniformities like ['c', 'c', 'c', 'c', 'c', 'a'] or ['d', 'd', 'd', 'd', 'd', 'b'] or ['c', 'c', 'c', 'c', 'b', 'a']. Making all of those uniform sets and the areas in-between equally likely as non-uniform results is what I find challenging to create. I'm at a loss for where to even begin creating a set generator that does that.

Further clarification:

So if I generate a set of 1000 items, I want it to be equally likely that the set is 90% uniform or 100% uniform or 80% uniform or 20% uniform.

How can/should this be done?

答:
From what you're saying, you want to ignore the order of the elements in your random set, so if your original set was ab then the possible outcomes (ignoring order) would be aa, ab, bb, and you'd like to see each of those appearing with equal probability (of 1/3), no?

A brute-force solution to this would be:

generate all outcomes (see Finding All Combinations of JavaScript array values),

sort each of the results so the elements appear alphabetically,

remove duplicates (see Remove duplicates from an array of objects in javascript)

select one of the remaining results at random

So for example, with abc:

```<code>all combinations =   [`aaa`, `aab`, `aac`
                      `aba`, `abb`, `abc`
                      `aca`, `acb`, `acc`
                      `baa`, `bab`, `bac`
                      `bba`, `bbb`, `bbc`
                      `bca`, `bcb`, `bcc`
                      `caa`, `cab`, `cac`
                      `cba`, `cbb`, `cbc`
                      `cca`, `ccb`, `ccc`]

sorted combinations = [`aaa`, `aab`, `aac`
                       `aab`, `abb`, `abc`
                       `aac`, `abc`, `acc`
                       `aab`, `abb`, `abc`
                       `abb`, `bbb`, `bbc`
                       `abc`, `bbc`, `bcc`
                       `aac`, `abc`, `acc`
                       `abc`, `bbc`, `bcc`
                       `acc`, `bcc`, `ccc`]

remove duplicates  = [`aaa`, `aab`, `aac`,
                      `abb`, `abc`, `acc`,
                      `bbb`, `bbc`, `bcc`,
                      `ccc`]

then choose from these with equal probability of 1/10
</code>```

EDIT The final output above gives a clue to a non-brute-force solution: for each item the letters that follow each letter are of equal or 'higher' value (alphabetically speaking). So 'b' will never be followed by 'a', and 'c' will never be followed by 'a' or 'b' and so on.

So we can recursively generate all the combinations like this (sorry it's in python, you'll have to translate to javascript):

```<code>r=['a','b','c','d']

def get_combos(bound, n):
  global r
  if n == 1:
    return r[bound:]
  result=[]
  for i in range(bound,len(r)):
    for combo in get_combos(i, n-1):
      result.append(r[i]+combo)
  return result

x = get_combos(0,len(r))
print(x) # ['aaaa', 'aaab', 'aaac', 'aaad', 'aabb', 'aabc', 'aabd', 'aacc', 'aacd', 'aadd', 'abbb', 'abbc', 'abbd', 'abcc', 'abcd', 'abdd', 'accc', 'accd', 'acdd', 'addd', 'bbbb', 'bbbc', 'bbbd', 'bbcc', 'bbcd', 'bbdd', 'bccc', 'bccd', 'bcdd', 'bddd', 'cccc', 'cccd', 'ccdd', 'cddd', 'dddd']

print(len(x)) # 35
</code>```

Body:
So let's say I have a set of items:

['a', 'b', 'c', 'd', 'e']

and I want to generate a random set (order does not matter) from those choices:

['a', 'e', 'd', 'c']

which is child's play, but instead of it being unlikely to generate a uniform result:

['c', 'c', 'c', 'c']

compared to something less uniform like:

['a', 'b', 'e', 'd']

I want to make it equally likely that a uniform set can be generated as it is likely that a non-uniform set can be generated.

Edit:

The result I'm trying to express is not just ['c', 'c', 'c', 'c', 'c', 'c'] or ['d', 'd', 'd', 'd', 'd', 'd'] but also the areas in between those uniformities like ['c', 'c', 'c', 'c', 'c', 'a'] or ['d', 'd', 'd', 'd', 'd', 'b'] or ['c', 'c', 'c', 'c', 'b', 'a']. Making all of those uniform sets and the areas in-between equally likely as non-uniform results is what I find challenging to create. I'm at a loss for where to even begin creating a set generator that does that.

Further clarification:

So if I generate a set of 1000 items, I want it to be equally likely that the set is 90% uniform or 100% uniform or 80% uniform or 20% uniform.

How can/should this be done?

Body:
From what you're saying, you want to ignore the order of the elements in your random set, so if your original set was ab then the possible outcomes (ignoring order) would be aa, ab, bb, and you'd like to see each of those appearing with equal probability (of 1/3), no?

A brute-force solution to this would be:

generate all outcomes (see Finding All Combinations of JavaScript array values),

sort each of the results so the elements appear alphabetically,

remove duplicates (see Remove duplicates from an array of objects in javascript)

select one of the remaining results at random

So for example, with abc:

all combinations =   [`aaa`, `aab`, `aac`
                      `aba`, `abb`, `abc`
                      `aca`, `acb`, `acc`
                      `baa`, `bab`, `bac`
                      `bba`, `bbb`, `bbc`
                      `bca`, `bcb`, `bcc`
                      `caa`, `cab`, `cac`
                      `cba`, `cbb`, `cbc`
                      `cca`, `ccb`, `ccc`]

sorted combinations = [`aaa`, `aab`, `aac`
                       `aab`, `abb`, `abc`
                       `aac`, `abc`, `acc`
                       `aab`, `abb`, `abc`
                       `abb`, `bbb`, `bbc`
                       `abc`, `bbc`, `bcc`
                       `aac`, `abc`, `acc`
                       `abc`, `bbc`, `bcc`
                       `acc`, `bcc`, `ccc`]

remove duplicates  = [`aaa`, `aab`, `aac`,
                      `abb`, `abc`, `acc`,
                      `bbb`, `bbc`, `bcc`,
                      `ccc`]

then choose from these with equal probability of 1/10

EDIT The final output above gives a clue to a non-brute-force solution: for each item the letters that follow each letter are of equal or 'higher' value (alphabetically speaking). So 'b' will never be followed by 'a', and 'c' will never be followed by 'a' or 'b' and so on.

So we can recursively generate all the combinations like this (sorry it's in python, you'll have to translate to javascript):

r=['a','b','c','d']

def get_combos(bound, n):
  global r
  if n == 1:
    return r[bound:]
  result=[]
  for i in range(bound,len(r)):
    for combo in get_combos(i, n-1):
      result.append(r[i]+combo)
  return result

x = get_combos(0,len(r))
print(x) # ['aaaa', 'aaab', 'aaac', 'aaad', 'aabb', 'aabc', 'aabd', 'aacc', 'aacd', 'aadd', 'abbb', 'abbc', 'abbd', 'abcc', 'abcd', 'abdd', 'accc', 'accd', 'acdd', 'addd', 'bbbb', 'bbbc', 'bbbd', 'bbcc', 'bbcd', 'bbdd', 'bccc', 'bccd', 'bcdd', 'bddd', 'cccc', 'cccd', 'ccdd', 'cddd', 'dddd']

print(len(x)) # 35


问:
Entity Framework with elastic pool. How to manage my SaaS client database?
I am currently looking to build an SaaS in ASP.Net hosted on Azure Cloud.
I am looking for advice on how to best build my database and the Entity Framework that goes with it. Once a customer registers on the web app, the app needs to create a seperate database for each customer on my Azure SQL server.

I have started looking into the option of elastic pooling, but it has left me quite confused. To tell you a bit about my database, it has one "meta"-database for all general settings. And then each customer has a database with his portfolio.

Example

database [Settings] with tables (Currency, Stocks, Bonds) [

[Customer1] SomeFinanceProduct [Currency as foreign, stock as foreign], SomeOtherFinanceProduct [Currency as foreign, bond as foreign]

[Customer2] SomeFinanceProduct [Currency as foreign, stock as foreign],
    SomeOtherFinanceProduct [Currency as foreign, bond as foreign]

[Customer3] etc.

I would appreciate some help from more experienced developpers. Many thanks, this is an important issue for me. I have also found this post from 2015 where they said that the solution would be soon released, but I have not found anything on the web.

答:
I can't speak to the Entity Framework part of your question too much, however, I can speak to the elastic pool side of things.

It's important to note that an Azure elastic pool is just a billing and resource allocation construct. As far as your application or its code is concerned, there is no difference if you use an elastic pool. You still have a database, it lives on a server, and that server (and indirectly, but more specifically in the case of Azure, that database) has resource constraints.

In Azure, you traditionally create a database and choose a service or pricing tier. You pay X dollars in exchange for Y resources (CPU, memory, storage size, connection counts, etc) for that database. You repeat this for every single database you create. Over time, databases grow in size or usage and they become more demanding, so you must change the service tiers of each database individually as this happens. As you have more and more databases, this becomes tedious and cost ineffective.

With elastic pools, you can take any number of individual databases and drop the individual service/pricing plans and instead buy a big bucket of resources [i.e. the elastic pool] and give those resources to all of the databases. The theory is that collectively you need fewer resources with this approach, and this allows you to save money. It also makes better use of the resources you are buying.

The reason you need fewer resources is because generally databases experience peak demand at different times. When you buy resources individually, you have to over buy on every single database to handle the peaks (which means you have a lot of wasted resources just sitting there unused). On an elastic pool, since all database are in the pool together you only buy enough extra resources which will cover however many peaks you typically would have going on concurrently at the same time; now you have fewer resources sitting idle wasting money.

As I mentioned, the other benefit of using elastic pools is that you can make better use of the resources you have. Consider a database which has very low demands placed upon it; you'd naturally purchase a small (and thus cheap) plan for it. Then consider a database which has high demands placed upon it; you'll likely buy a plan with much greater resources. Now, occasionally the low use database gets some big hits. With the small plan, the resources aren't enough and performance degrades terribly. Meanwhile the other database has tons of resources and much of it is being unused. Wouldn't it be nice if the small database which is experiencing the unusual peak could borrow some of those resources for a few minutes? That's exactly what elastic pools do! Elastic pools have lots of built in scalability wins for your applications!

The last important thing to note, is that elastic pools cost more per unit of resource, than regular databases. This means that there is a break even point and that its more expensive to use elastic pools until you have enough databases to make it worthwhile. For my needs I've found 10-15 databases to be a fairly good break even point. Once you have enough, create the pool. Then, as you add more databases to the pool later on, the "per database" costs start going down even more.

--

So to get back to your question, elastic pools will not specifically affect your ability to use Entity Framework for your project. Regardless of whether you choose to pool your databases or not, you'll have to get your code to talk to the appropriate customer specific database based on who is logged in.


问:
EmbeddedDocument field never optional in Django Mongoengine REST framework
I am using Django REST framework with Mongoengine. When I attempt serialize an optional field on an embedded document, the framework still requires the field and returns the error message that the field cannot be left blank. How do I make fields optional on an EmbeddedDocument? It works fine for standard Document model objects, just not for EmbeddedDocument objects.

My model:

```<code>class Event(EmbeddedDocument):
    id = ObjectIdField(required=True, default=ObjectId())
    status = StringField(required=True, max_length=50)
    note = StringField(required=False, max_length=2000)
    created = DateTimeField(required=True, default=timezone.now())
</code>```

My serializer:

```<code>class EventSerializer(EmbeddedDocumentSerializer):

    class Meta:
        model = Event
        depth = 2

    def validate(self, data):
        return data
</code>```

Note that the field "note" is set to required=False. When I serialize the document, however, I still get an error message that the field can't be left blank. Thank you!

答: I came across the same problem, I think you can mark the fields as blank=True and it should allow you to place nothing in those fields.

Body:
I am using Django REST framework with Mongoengine. When I attempt serialize an optional field on an embedded document, the framework still requires the field and returns the error message that the field cannot be left blank. How do I make fields optional on an EmbeddedDocument? It works fine for standard Document model objects, just not for EmbeddedDocument objects.

My model:

class Event(EmbeddedDocument):
    id = ObjectIdField(required=True, default=ObjectId())
    status = StringField(required=True, max_length=50)
    note = StringField(required=False, max_length=2000)
    created = DateTimeField(required=True, default=timezone.now())

My serializer:

class EventSerializer(EmbeddedDocumentSerializer):

    class Meta:
        model = Event
        depth = 2

    def validate(self, data):
        return data

Note that the field "note" is set to required=False. When I serialize the document, however, I still get an error message that the field can't be left blank. Thank you!


答:
Use either auto-fill or auto-fit as the first argument of the repeat() notation.

<auto-repeat> variant of the repeat() notation:

```<code>repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )
</code>```

auto-fill

When auto-fill is given as the repetition number, if the grid
container has a definite size or max size in the relevant axis, then
the number of repetitions is the largest possible positive integer
that does not cause the grid to overflow its grid container.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

The grid will repeat as many tracks as possible without overflowing its container.

In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.

The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.

auto-fit

The auto-fit keyword behaves the same as auto-fill, except
that after grid item placement any empty repeated tracks are collapsed.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0.

A collapsed track is treated as having a fixed track sizing function of 0px.

Unlike the auto-fill image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.

auto-fill vs auto-fit

The difference between the two is noticeable when the minmax() function is used.

Use minmax(186px, 1fr) to range the items from 186px to a fraction of the leftover space in the grid container.

When using auto-fill, the items will grow once there is no space to place empty tracks.

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

When using auto-fit, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px.

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

Playground:

CodePen

Inspecting auto-fill tracks

Inspecting auto-fit tracks

Title: CSS grid wrapping

Body:
Use either auto-fill or auto-fit as the first argument of the repeat() notation.

<auto-repeat> variant of the repeat() notation:

repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )

auto-fill

When auto-fill is given as the repetition number, if the grid
container has a definite size or max size in the relevant axis, then
the number of repetitions is the largest possible positive integer
that does not cause the grid to overflow its grid container.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

The grid will repeat as many tracks as possible without overflowing its container.

In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.

The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.

auto-fit

The auto-fit keyword behaves the same as auto-fill, except
that after grid item placement any empty repeated tracks are collapsed.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0.

A collapsed track is treated as having a fixed track sizing function of 0px.

Unlike the auto-fill image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.

auto-fill vs auto-fit

The difference between the two is noticeable when the minmax() function is used.

Use minmax(186px, 1fr) to range the items from 186px to a fraction of the leftover space in the grid container.

When using auto-fill, the items will grow once there is no space to place empty tracks.

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

When using auto-fit, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px.

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}

<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>

Playground:

CodePen

Inspecting auto-fill tracks

Inspecting auto-fit tracks


问:
Create NSArray with row content (MySQL)
I want to create a NSArray witch contains the content of a MySQL table row

I use a php script to get the data

```<code>$response = $bdd->query('SELECT * FROM iPhoneTests');

while ($datas = $response->fetch())
{
?>
    <array>
    <integer><?php echo $datas['Temperature']; ?></integer>
    </array>

<?php
}
</code>```

and to test Iuse this code in my app

```<code>    NSURL *getTemperature = [NSURL URLWithString:@"myURL..."];
    NSError* error;
    temperature = [NSArray arrayWithContentsOfURL:getTemperature ];
    NSLog(@"%@",temperature);
</code>```

When I test in my web broswer I get all my datas but in my app, with the NSlog I only get the first value.

I on this problem since a few time, but I can't succeed
If someone see my mistake please tell me

答:
We can communicate in many ways with server. And I would suggest that communication data should only be in String format, one way is using JSON, you can get JSON parser from here https://github.com/schwa/TouchJSON , this is explained as below:

Starting Communication

[[[NSURLConnection alloc] initWithRequest:[NSURLRequest requestWithURL:
[NSURL URLWithString:urlStr]] delegate:self startImmediately:YES] autorelease];
//urlStr is NSString ref

Start receiving data

(void)connection:(NSURLConnection *)connection didReceiveResponse:
(NSURLResponse *)response{
[receivedData setLength:0];
}
//receivedData is NSMutableData ref

Get data in chunks

(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}

After getting complete data

(void)connectionDidFinishLoading:(NSURLConnection *)connection{

// json data retrival complete    (received data is NSMutableData)
if(receivedData == nil || [receivedData length] == 0){
  //handle error in getting response, may be no network
    [self showAlertViewWithTitle:@"No network" andMessage:@"Could not open the
    page, because internet connection was not found." andTag:0];
    return;
}

NSString *responseBody = [[[NSString alloc] initWithData:receivedData
  encoding:NSUTF8StringEncoding] autorelease];
////NSLog(responseBody);
NSError *jsonParsingError = [[[NSError alloc] init] autorelease];
NSDictionary * jsonData = [NSDictionary dictionaryWithJSONData:
                             [responseBody dataUsingEncoding:NSUTF8StringEncoding]
                                 error:&jsonParsingError];

NSDictionary *serverError = [jsonData objectForKey:@"error"]==[NSNull null]?
                               nil:[jsonData objectForKey:@"error"];

if(serverError==nil || [serverError count]==0){
    // no error found else
    NSDictionary *response = [jsonData objectForKey:@"response"]==[NSNull null]?
                               nil:[jsonData objectForKey:@"response"];
    NSArray *array = [response objectForKey:@"array"]==[NSNull null]?nil:
                          [response objectForKey:@"array"];
// I have left the code incomplete, its just for understanding

Check for null values
Never forget to check null values from JSON data as follows:

NSString *dataValue =  [[[array objectAtIndex:i] objectForKey:@"key"]==[NSNull null]?
                         @"0":[[array objectAtIndex:i] objectForKey:@"key"] intValue];

Please let me know if you require further explanation..

Title: Create NSArray with row content (MySQL)

Body:
I want to create a NSArray witch contains the content of a MySQL table row

I use a php script to get the data

$response = $bdd->query('SELECT * FROM iPhoneTests');

while ($datas = $response->fetch())
{
?>
    <array>
    <integer><?php echo $datas['Temperature']; ?></integer>
    </array>

<?php
}

and to test Iuse this code in my app

    NSURL *getTemperature = [NSURL URLWithString:@"myURL..."];
    NSError* error;
    temperature = [NSArray arrayWithContentsOfURL:getTemperature ];
    NSLog(@"%@",temperature);

When I test in my web broswer I get all my datas but in my app, with the NSlog I only get the first value.

I on this problem since a few time, but I can't succeed
If someone see my mistake please tell me


问:
state management using ngrx/store and ngrx/effects in Angular 2
I am working on a sample Angular 2 application , and I am planning to use @ngrx/store and @ngrx/effects for state management.

This sample application has a root module and multiple feature modules.

Now my questions are.

Can I import StoreModule and EffectsModule in all my feature modules
OR
Should they be imported only once in root module ?

In order to import a single effects file in a module I had written below line of code in module file

```<code>EffectsModule.run(AuthorEffects)
</code>```

What if there are multiple effect files ?

答:
Most of the time it should be imported in the root module. It looks like the ngrx has a solution in the v3 beta version to provide dynamic reducer functionality:

https://github.com/ngrx/store/pull/269

As far as multiple effects, you will need to call EffectsModule.run() for each effect.

Body:
I am working on a sample Angular 2 application , and I am planning to use @ngrx/store and @ngrx/effects for state management.

This sample application has a root module and multiple feature modules.

Now my questions are.

Can I import StoreModule and EffectsModule in all my feature modules
OR
Should they be imported only once in root module ?

In order to import a single effects file in a module I had written below line of code in module file

EffectsModule.run(AuthorEffects)

What if there are multiple effect files ?


问:
htmlentities returning empty string
The following code outputs an empty string. The cause is the "ó" in $text, but why? What characters does utf-8 encode then?

The problem is solved when using iso-8859-1, but I need to use utf-8, so what am I doing wrong?

```<code><!doctype html>
<head>
  <meta charset="utf-8">
</head>

<body>
<?
$text = 'Hola ó Hola';
$text = htmlentities($text,ENT_QUOTES,'utf-8');
echo $text;
?>
</body>
</html>
</code>```

答:
Open your code editor (notepad++ for instance or other).

Click in New > Save As.. put the name of file (blank for a while) and in type select PHP Hypertext ...

Now copy all content of your original file and put in this new file.

Click in save and try.

Title: htmlentities returning empty string

Body:
The following code outputs an empty string. The cause is the "ó" in $text, but why? What characters does utf-8 encode then?

The problem is solved when using iso-8859-1, but I need to use utf-8, so what am I doing wrong?

<!doctype html>

  <meta charset="utf-8">

<?
$text = 'Hola ó Hola';
$text = htmlentities($text,ENT_QUOTES,'utf-8');
echo $text;
?>


答:
Here's a simple snippet that gets it done, using the strategy of first deciding whether to generate an extreme or non-extreme set.

const choices = ['a', 'b', 'c', 'd', 'e']

const repeatN = (times, x) => {
  const ret = [];
  while (times--) {
    ret.push(x);
  }
  return ret;
}

const chooseN = (n, choices) => {
  let list = choices.slice();
  let ret = [];
  while (n-- && list.length) {
    let i = Math.floor(Math.random() * list.length);
    ret.push(list[i]);
  }
  return ret;
};

const set = Math.random() > 0.5 ?
  chooseN(5, choices) :
  repeatN(5, chooseN(1, choices)[0]);

console.log(set);```

Title: How can I make a random set generator with equal possibility to generate uniform sets and non-uniform sets?


问:
In exported Jupyter Notebooks, how do I disable the ¶?
When I export a notebook to html, my headings have a ¶ (pilcrow) at the end; how do I turn that off?

Here is an example command I am using:

```<code>jupyter nbconvert --to html --template basic Untitled.ipynb
</code>```

where the notebook just contains a cell with a markdown heading and text:

```<code># Here I am

Rock you like a hurricane
</code>```

答:
I had this problem too. My work-around was to realise that the pilcrow has its own class in the html, which is different to the headings it follows, and add the following to the css to make the pilcrow have font size 0, which removes the pilcrow from the rendered page.

```<code>.anchor-link{
    font-size: 0;
}
</code>```

You could also make the text-color the same as the background, or a number of other things to make the Pilcrow effectively disappear.

Body:
When I export a notebook to html, my headings have a ¶ (pilcrow) at the end; how do I turn that off?

Here is an example command I am using:

jupyter nbconvert --to html --template basic Untitled.ipynb

where the notebook just contains a cell with a markdown heading and text:

# Here I am

Rock you like a hurricane

Body:
I had this problem too. My work-around was to realise that the pilcrow has its own class in the html, which is different to the headings it follows, and add the following to the css to make the pilcrow have font size 0, which removes the pilcrow from the rendered page.

.anchor-link{
    font-size: 0;
}

You could also make the text-color the same as the background, or a number of other things to make the Pilcrow effectively disappear.


问:
How to start Travis CI deploy only when tag name matches a regex
I want to kick off an npm deployment when a tag, that looks like a semantic version, is pushed, e.g. v1.2.3. I see that the tag name is in the TRAVIS_TAG environment variable and that I can specify an on: condition, which "can be any Bash condition". I have no idea what to write here and how to debug it.

- provider: npm
  on:
    tags: true
    all_branches: true
    condition: ???

Ideally, I would like to not bother with Bash at all - I would like the condition to execute a Node.js script and then decide whether to deploy or not depending on the node exit code. How can I do that?

答:
eshizari's answer didn't work for me. This is the approach that I'm using instead:  </p>

```<code>on:
  all_branches: true
  condition: $TRAVIS_TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+
</code>```

Body:
eshizari's answer didn't work for me. This is the approach that I'm using instead:

on:
  all_branches: true
  condition: $TRAVIS_TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+


问:
Check checkbox from antoher activity
I was wondering if anyone could tell me how I could check a checkBox in an  activity from another activity.

I'm making a homework app and I want to put a check next to the questions that have been completed.

So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.

答:
You should use intent and bundle logic for passing data between activities.(in most cases)

In the first activity, whenever you are creating the second activity, you pass your data.

```<code>Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("checked",checkBox.isChecked());
startActivity(intent);
</code>```

In the second activity you receive your data by using :

```<code>Intent receivedIntent = getIntent();
boolean finalChecked = receivedIntent.getExtras().getBoolean("checked");
//now you can apply your logic with finalChecked variable
</code>```

Title: Check checkbox from antoher activity

Body:
You should use intent and bundle logic for passing data between activities.(in most cases)

In the first activity, whenever you are creating the second activity, you pass your data.

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("checked",checkBox.isChecked());
startActivity(intent);

In the second activity you receive your data by using :

Intent receivedIntent = getIntent();
boolean finalChecked = receivedIntent.getExtras().getBoolean("checked");
//now you can apply your logic with finalChecked variable


问:
Chrome doesn't refresh static JS file when running local development with Google App Engine Flask dev_appserver.py
Chrome loads the javascript file, but when I update the file, the update doesn't appear in Chrome. I've tried this in Firefox and I can see that the javascript file has updated when I refresh the page, but not in Chrome.

I'm using Flask and the javascript files are in the static folder. My directory looks like:

```<code>app
-env
-lib
-static
--css
--img
--js <-- there is where my js file is
-templates
--partials
-app.yaml
-main.py
-requirements.txt
</code>```

My app.yaml file is:

```<code>runtime: python27
api_version: 1
threadsafe: yes
# Handlers define how to route requests to your application.
handlers:
# This handler tells app engine how to route requests to a WSGI application.
# The script value is in the format <path.to.module>.<wsgi_application>
# where <wsgi_application> is a WSGI application object.
- url: .*  # This regex directs all routes to main.app
  script: main.app
</code>```

答:
Ctrl + Shift + i    Network Tab > Disable cache.

Note: Dev tools has to be open for options to work.

Body:
Chrome loads the javascript file, but when I update the file, the update doesn't appear in Chrome. I've tried this in Firefox and I can see that the javascript file has updated when I refresh the page, but not in Chrome.

I'm using Flask and the javascript files are in the static folder. My directory looks like:

app
-env
-lib
-static
--css
--img
--js <-- there is where my js file is
-templates
--partials
-app.yaml
-main.py
-requirements.txt

My app.yaml file is:

runtime: python27
api_version: 1
threadsafe: yes
# Handlers define how to route requests to your application.
handlers:
# This handler tells app engine how to route requests to a WSGI application.
# The script value is in the format <path.to.module>.<wsgi_application>
# where <wsgi_application> is a WSGI application object.
- url: .*  # This regex directs all routes to main.app
  script: main.app


问:
Find the smallest area rectangle covering a query point
I'm working on a personal project to do with computational geometry. The question in the title is an abstraction of one of the small subproblems that I am trying, but struggling, to solve efficiently. Hopefully it's general enough to maybe be of use of more than just me!

The problem

Imagine we have a set S of rectangles in the plane, all of which have edges parallel to the coordinate axes (no rotations). For my problem we'll assume that rectangle intersections are very common. But they are also very nice: If two rectangles intersect, we can assume one of them always completely contains the other. So there's no "partial" overlaps.

I want to store these rectangles in a way that:

We can efficiently add new rectangles.

Given a query point (x,y) we can efficiently report back the
rectangle of smallest area that contains the point.

The illustration provides the motivation for the latter. We always want to find the most deeply nested rectangle that contains the query point, so that's always the one of smallest area.

My thoughts

So I know that both R-Trees and Quad-Trees are often used for spatial indexing problems, and indeed both can work well in some cases. The problem with R-Trees is that they can degrade to linear performance in the worst case.

I thought about building a set of balanced binary trees based on nestedness. The left subtree of node r contains all the rectangles that are inside rectangle r. The right subtree contains all the rectangles that r is inside of. The illustrated example would have three trees.

But what if none of the rectangles are nested? Then you need O(n) trees of 1 element and again we have something that performs just as poorly as a linear scan through the boxes.

How could I solve this in  a way that we have asymptotically sub linear time in the worst case? Even if that means sacrificing some performance in the best cases or storage requirements. (I assume for a problem like this, there may be a need to maintain two data structures and that's cool)

I am certain that the very specific way in which rectangles are allowed to intersect should help make this problem possible. In fact, it looks like a candidate for logarithmic performance to me but I'm just not getting anywhere.

Thanks in advance for any ideas you have!

答:
I'd suggest storing the rectangles per nesting level, and tackling the rectangle-finding per level. Once you've found which top-level rectangle the point is in, you can then look at the second-level rectangles that are inside that rectangle, find the rectangle the point is in using the same method, then look at the third-level, and so on.

To avoid a worst-case of O(n) to find the rectangle, you could use a sort of ternary spatial tree, where you repeatedly draw a vertical line across the space and divide the rectangles into three groups: those to the left (blue), those intersected by (red), and those to the right (green) of the line. For the group of intersected rectangles (or once a vertical line would intersect most or all of the rectangles), you switch to a horizontal line and divide the rectangles into groups above, intersected by, and below the line.

You would then repeatedly check whether the point is to the left/right or above/below the line, and go on to check the rectangles on the same side and those intersected by the line.

In the example, only four rectangles would actually need to be checked to find which rectangle contains the point.

If we use the following numbering for the rectangles in the example:

then the ternary spatial tree would be something like this: