问:
How to implement SwipeRefreshLayout on a CardView inside a Fragment?
RecentNewsFragment.java

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final String TAG = "MainPageActivity";

    final RecyclerView rvNewsArticle;

    final SwipeRefreshLayout swipeRefreshLayout;

    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_recent_news, container, false);

    rvNewsArticle = (RecyclerView) view.findViewById(R.id.rvNewsArticle);
    rvNewsArticle.setHasFixedSize(true);
    LinearLayoutManager manager = new LinearLayoutManager(getActivity());
    rvNewsArticle.setLayoutManager(manager);

    swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);
    swipeRefreshLayout.setColorSchemeResources(R.color.primaryColor, R.color.primaryTextColor, R.color.secondaryColor);

    String url = "http://192.168.0.29/theflare/app/news.php";
    StringRequest stringRequest = new StringRequest(Request.Method.GET,
        url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response);

                ArrayList<News> newsList = new JsonConverter<News>()
                        .toArrayList(response, News.class);

                final NewsArticleAdapter adapter = new NewsArticleAdapter(getActivity(), newsList);

                rvNewsArticle.setAdapter(adapter);

                swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                rvNewsArticle.setAdapter(adapter);
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }, 2500);
                    }
                });

            }
        }
    );

    MySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);

    return view;
}
</code>```

As you can see, this is the code that I have built for my CardView. Unfortunately, my SwipeRefreshLayout does not work. (It works, but animation only, and does not refresh the view.) Have I put the setOnRefreshListener on the wrong place or am I just missing something here? Thanks for any help.

答:
You have your callback methods in the wrong place. You should create a new request in the onRefresh() method, not the other way around.

```<code>private static final String NEWS_URL = "http://192.168.0.29/theflare/app/news.php";

private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;

@Override
public view onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // ...

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            loadNews();
        }
    });

    return view;
}

private void loadNews() {
    StringRequest request = new StringRequest(Request.Method.GET, URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                ArrayList<News> newsList = new JsonConverter<News>().toArrayList(response, News.class);
                NewsArticleAdapter adapter = new NewsArticleAdapter(getActivity(), newsList);
                mRecyclerView.setAdapter(adapter);

                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
</code>```

Body:
RecentNewsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final String TAG = "MainPageActivity";

    final RecyclerView rvNewsArticle;

    final SwipeRefreshLayout swipeRefreshLayout;

    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_recent_news, container, false);

    rvNewsArticle = (RecyclerView) view.findViewById(R.id.rvNewsArticle);
    rvNewsArticle.setHasFixedSize(true);
    LinearLayoutManager manager = new LinearLayoutManager(getActivity());
    rvNewsArticle.setLayoutManager(manager);

    swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);
    swipeRefreshLayout.setColorSchemeResources(R.color.primaryColor, R.color.primaryTextColor, R.color.secondaryColor);

    String url = "http://192.168.0.29/theflare/app/news.php";
    StringRequest stringRequest = new StringRequest(Request.Method.GET,
        url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, response);

                ArrayList<News> newsList = new JsonConverter<News>()
                        .toArrayList(response, News.class);

                final NewsArticleAdapter adapter = new NewsArticleAdapter(getActivity(), newsList);

                rvNewsArticle.setAdapter(adapter);

                swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                rvNewsArticle.setAdapter(adapter);
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        }, 2500);
                    }
                });

            }
        }
    );

    MySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);

    return view;
}

As you can see, this is the code that I have built for my CardView. Unfortunately, my SwipeRefreshLayout does not work. (It works, but animation only, and does not refresh the view.) Have I put the setOnRefreshListener on the wrong place or am I just missing something here? Thanks for any help.

Body:
You have your callback methods in the wrong place. You should create a new request in the onRefresh() method, not the other way around.

private static final String NEWS_URL = "http://192.168.0.29/theflare/app/news.php";

private SwipeRefreshLayout mSwipeRefreshLayout;
private RecyclerView mRecyclerView;

@Override
public view onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    // ...

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            loadNews();
        }
    });

    return view;
}

private void loadNews() {
    StringRequest request = new StringRequest(Request.Method.GET, URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                ArrayList<News> newsList = new JsonConverter<News>().toArrayList(response, News.class);
                NewsArticleAdapter adapter = new NewsArticleAdapter(getActivity(), newsList);
                mRecyclerView.setAdapter(adapter);

                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}


来源: stackexchange

问:
Why does isinstance() return False in this case?
I would like to write a decorator that allows memoiziation of a constructor. When I construct a class, I want the object returned from cache when possible.

The following code has been adapted from here.

```<code>from functools import wraps

def cachedClass(klass):
    cache = {}

    @wraps(klass, updated=())
    class wrapper:
        def __new__(cls, *args, **kwargs):
            key = (cls,) + args + tuple(kwargs.items())
            try:
                inst = cache.get(key, None)
            except TypeError:
                # Can't cache this set of arguments
                inst = key = None
            if inst is None:
                inst = klass.__new__(klass, *args, **kwargs)
                inst.__init__(*args, **kwargs)
                if key is not None:
                    cache[key] = inst
            return inst

    return wrapper
</code>```

A small test suite revals the following:

```<code>>>> @cachedClass
... class Foo:
...     pass
>>> f1 = Foo()
>>> f2 = Foo()
>>> f1 is f2
True
>>> Foo
<class 'cache.Foo'>
>>> type(f1)
<class 'cache.Foo'>
>>> isinstance(f1, Foo)
False
</code>```

I expected that the last expression would return True. What am I missing?

答:
```<code>@cachedClass
class Foo:
    pass
</code>```

is semantically equivalent to

```<code>class Foo:
    pass

Foo = cachedClass(Foo)
</code>```

The Foo name is assigned the return value of cachedClass, which is the
 wrapper class.

wrapper is in turn decorated by functool.wraps that copies Foo's __name__ attribute along with some other dunder attributes, so the wrapper class looks like Foo.

If you remove the @wraps line and print

```<code>print(type(f1), Foo, type(f1) is Foo, sep=', ')
</code>```

you'll see that the f1 is an instance of the original Foo class, but the Foo name now refers to the wrapper class, and they are different objects:

```<code><class '__main__.Foo'>, <class '__main__.cachedClass.<locals>.wrapper'>, False
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to write a decorator that allows memoiziation of a constructor. When I construct a class, I want the object returned from cache when possible.

The following code has been adapted from here.

from functools import wraps

def cachedClass(klass):
    cache = {}

    @wraps(klass, updated=())
    class wrapper:
        def __new__(cls, *args, **kwargs):
            key = (cls,) + args + tuple(kwargs.items())
            try:
                inst = cache.get(key, None)
            except TypeError:
                # Can't cache this set of arguments
                inst = key = None
            if inst is None:
                inst = klass.__new__(klass, *args, **kwargs)
                inst.__init__(*args, **kwargs)
                if key is not None:
                    cache[key] = inst
            return inst

    return wrapper

A small test suite revals the following:

>>> @cachedClass
... class Foo:
...     pass
>>> f1 = Foo()
>>> f2 = Foo()
>>> f1 is f2
True
>>> Foo
<class 'cache.Foo'>
>>> type(f1)
<class 'cache.Foo'>
>>> isinstance(f1, Foo)
False

I expected that the last expression would return True. What am I missing?

Body:
@cachedClass
class Foo:
    pass

is semantically equivalent to

class Foo:
    pass

Foo = cachedClass(Foo)

The Foo name is assigned the return value of cachedClass, which is the
 wrapper class.

wrapper is in turn decorated by functool.wraps that copies Foo's __name__ attribute along with some other dunder attributes, so the wrapper class looks like Foo.

If you remove the @wraps line and print

print(type(f1), Foo, type(f1) is Foo, sep=', ')

you'll see that the f1 is an instance of the original Foo class, but the Foo name now refers to the wrapper class, and they are different objects:

<class '__main__.Foo'>, <class '__main__.cachedClass.<locals>.wrapper'>, False


问:
Contents of .feature file isn't recognized in intelliJ
I wrote feature files in a project in IntelliJ according to the cucumber syntax. This files worked in another computer. I added the cucumber-java jar files and also installed the Gherkin and cucumber plugins, but still feature files aren't recognized as they should be.
What could be the problem?</p>

答:
After installing plugin if you till face problem as i did, my feature files are not getting recognized because of groovy

therefore I manually set

File>>Settings>>Editor>>File Types
click "cucumber Scenario" and Click + to add .Feature in Recognize Patterns.


问:
Go gin framework CORS
I'm using Go gin framework gin

```<code>func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Content-Type", "application/json")
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Max")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(200)
        } else {
            c.Next()
        }
    }
}
</code>```

I've got Status Code:200 OK, but nothing happens after OPTIONS request.
It looks like I miss something, but I can't understand where am I wrong.

Can anybody help me?

答:
We created a minimal middleware.

```<code>import (
    "github.com/gin-gonic/gin"
    "net/http"
)

type optionsMiddleware struct {

}

func CreateOptionsMiddleware() *optionsMiddleware{
    return &optionsMiddleware{}
}

func (middleware *optionsMiddleware)Response(context *gin.Context){
    if context.Request.Method == "OPTIONS" {
        context.AbortWithStatus(http.StatusNoContent)
    }
}
</code>```

and register it with gin middleware :

```<code>app  := gin.New()
app.Use(middleware.CreateOptionsMiddleware().Response).
    Use(next-middleware)......
</code>```

Title: Go gin framework CORS

Body:
I'm using Go gin framework gin

func CORSMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Content-Type", "application/json")
        c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Max")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(200)
        } else {
            c.Next()
        }
    }
}

I've got Status Code:200 OK, but nothing happens after OPTIONS request.
It looks like I miss something, but I can't understand where am I wrong.

Can anybody help me?

Body:
We created a minimal middleware.

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

type optionsMiddleware struct {

}

func CreateOptionsMiddleware() *optionsMiddleware{
    return &optionsMiddleware{}
}

func (middleware *optionsMiddleware)Response(context *gin.Context){
    if context.Request.Method == "OPTIONS" {
        context.AbortWithStatus(http.StatusNoContent)
    }
}

and register it with gin middleware :

app  := gin.New()
app.Use(middleware.CreateOptionsMiddleware().Response).
    Use(next-middleware)......


问:
Cloud Firestore: Missing or insufficient permissions
I am getting (on Android):

com.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions

using these security rules:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}
</code>```

My app seems to be properly authenticated using FirebaseAuth, as the mFirebaseAuth.getCurrentUser().getUid() returns the proper user ID.

Is there something I am doing wrong?

答: It seem it's a Firestore problem (in beta today), not in the client side.

Body:
I am getting (on Android):

com.google.firebase.firestore.FirebaseFirestoreException:
  PERMISSION_DENIED: Missing or insufficient permissions

using these security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth != null;
    }
  }
}

My app seems to be properly authenticated using FirebaseAuth, as the mFirebaseAuth.getCurrentUser().getUid() returns the proper user ID.

Is there something I am doing wrong?


问:
R stats - memory issues when allocating a big matrix / Linux
I have read several threads about memory issues in R and I can't seem to find a solution to my problem.

I am running a sort of LASSO regression on several subsets of a big dataset. For some subsets it works well, and for some bigger subsets it does not work, with errors of type "cannot allocate vector of size 1.6Gb". The error occurs at this line of the code:

```<code>example <- cv.glmnet(x=bigmatrix, y=price, nfolds=3)
</code>```

It also depends on the number of variables that were included in "bigmatrix".

I tried on R and R64 for both Mac and R for PC but recently went onto a faster virtual machine on Linux thinking I would avoid any memory issues. It was better but still had some limits, even though memory.limit indicates "Inf".

Is there anyway to make this work or do I have to cut a few variables in the matrix or take a smaller subset of data ?

I have read that R is looking for some contiguous bits of memory and that maybe I should pre-allocate the matrix ? Any idea ?

答:
Try bigmemory package. It is very easy to use. The idea is that data are stored in file on HDD and you create an object in R as reference to this file. I have tested this one and it works very well.

There are some alternative as well, like "ff". See CRAN Task View: High-Performance and Parallel Computing with R for more information.

Body:
I have read several threads about memory issues in R and I can't seem to find a solution to my problem.

I am running a sort of LASSO regression on several subsets of a big dataset. For some subsets it works well, and for some bigger subsets it does not work, with errors of type "cannot allocate vector of size 1.6Gb". The error occurs at this line of the code:

example <- cv.glmnet(x=bigmatrix, y=price, nfolds=3)

It also depends on the number of variables that were included in "bigmatrix".

I tried on R and R64 for both Mac and R for PC but recently went onto a faster virtual machine on Linux thinking I would avoid any memory issues. It was better but still had some limits, even though memory.limit indicates "Inf".

Is there anyway to make this work or do I have to cut a few variables in the matrix or take a smaller subset of data ?

I have read that R is looking for some contiguous bits of memory and that maybe I should pre-allocate the matrix ? Any idea ?

ContentLicense: CC BY-SA 2.5


问:
My OpenAL C++ audio streaming buffer gliching
I have for the first time coding sound generating with OpenAL in C++.
What I want to do is to generate endless sinus wave into a double buffering way.
And the problem is that the sound is glittering/lags. I Think it is between the buffering and I don't know why it is like that.

My code:

```<code>void _OpenALEngine::play()
{
    if(!m_running && !m_threadRunning)
    {
        ALfloat sourcePos[] = {0,0,0};
        ALfloat sourceVel[] = {0,0,0};
        ALfloat sourceOri[] = {0,0,0,0,0,0};
        alGenSources(1, &FSourceID);
        alSourcefv (FSourceID, AL_POSITION, sourcePos);
        alSourcefv (FSourceID, AL_VELOCITY, sourceVel);
        alSourcefv (FSourceID, AL_DIRECTION, sourceOri);
        GetALError();

        ALuint FBufferID[2];
        alGenBuffers( 2, &FBufferID[0] );
        GetALError();

        // Gain
        ALfloat listenerPos[] = {0,0,0};
        ALfloat listenerVel[] = {0,0,0};
        ALfloat listenerOri[] = {0,0,0,0,0,0};
        alListenerf( AL_GAIN, 1.0 );
        alListenerfv(AL_POSITION, listenerPos);
        alListenerfv(AL_VELOCITY, listenerVel);
        alListenerfv(AL_ORIENTATION, listenerOri);
        GetALError();

        alSourceQueueBuffers( FSourceID, 2, &FBufferID[0] );
        GetALError();

        alSourcePlay(FSourceID);
        GetALError();

        m_running = true;
        m_threadRunning = true;
        Threading::Thread thread(Threading::ThreadStart(this, &_OpenALEngine::threadPlaying));
        thread.Start();
    }
}

Void _OpenALEngine::threadPlaying()
{

    while(m_running)
    {
        // Check how much data is processed in OpenAL's internal queue.
        ALint Processed;
        alGetSourcei( FSourceID, AL_BUFFERS_PROCESSED, &Processed );
        GetALError();

        // Add more buffers while we need them.
        while ( Processed-- )
        {
            alSourceUnqueueBuffers( FSourceID, 1, &BufID );

            runBuffer(); // <--- Generate the sinus wave and submit the Array to the submitBuffer method.

            alSourceQueueBuffers( FSourceID, 1, &BufID );

            ALint val;
            alGetSourcei(FSourceID, AL_SOURCE_STATE, &val);
            if(val != AL_PLAYING)
            {
                alSourcePlay(FSourceID);
            }
        }

        // Don't kill the CPU.
        Thread::Sleep(1);
    }

    m_threadRunning = false;

    return Void();
}

void _OpenALEngine::submitBuffer(byte* buffer, int length)
{
    // Submit more data to OpenAL
    alBufferData( BufID, AL_FORMAT_MONO8, buffer, length * sizeof(byte), 44100 );
}
</code>```

I generate the sinus wave in the runBuffer() method. And the sinus  generator is correct because when I increase the buffer array from 4096 to 40960 the glittering/lags sound with bigger interval. Thank you very much if some one know the problem and will share it :)

答:
Similar Problems are all over the internet and I'm not 100% sure this is the solution to this on. But it probably is, and if not it might at least help others. Most other threads are on different forums and I'm not registering everywhere just to share my knowledge...

The code below is what I came up after 2 days of experimenting. Most solutions I found did not work for me...
(it's not exactly my code, I stripped it of some parts special to my case, so I'm sorry if there are typos or similar that prevent it from being copied verbatim)

My experiments were on an iPhone. Some of the the things I found out, might be iOS-specific.

The problem is that there is no guaranty at what point a processed buffer is marked as such and is available for unqueueing. Trying to build a version that sleeps until a buffer becomes available again I saw that this might be much(I use very small buffers) later than expected. So I realised that the common idea to wait until a buffer is available(which works for most frameworks, but not openAL) is wrong. Instead you should wait until the time you should enqueue another buffer.
With that you have to give up the idea of double-buffering. When the time comes you should check if a buffer exists and unqueue it. But if none is available you need to create a 3rd...

Waiting for when a buffer should be enqueue can be done by calculating times relative to the system-clock, which worked fairly well for me but I decided to go for a version where I rely on a time source that is definitivly in sync with openAL. Best I came up with was wait depending on what s left in the queue. Here, iOS seems not fully in accordance to openAL-spec because AL_SAMPLE_OFFSET should be exact to one sample but I never saw anything but multiples of 2048. That's about 45 microseconds @44100, this is where the 50000 in the code comes from(little more than the smalest unit iOS handles)
Depending on the block-size this can easily be bigger. But with that code I had 3 times that alSourcePlay() was needed again in the last ~hour(compared to up to 10 per minute with other implementations that claimed to be the solution)

```<code>uint64 enqueued(0);  // keep track of samples in queue
while (bKeepRunning)
{
   // check if enough in buffer and wait
   ALint off;
   alGetSourcei(m_Source,  AL_SAMPLE_OFFSET, &off);
   uint32 left((enqueued-off)*1000000/SAMPLE_RATE);
   if (left > 50000) // at least 50000 mic-secs in buffer
     usleep(left - 50000);

   // check for available buffer
   ALuint buffer;

   ALint processed;
   alGetSourcei(m_Source, AL_BUFFERS_PROCESSED, &processed);
   switch (processed)
   {
   case 0:  // no buffer to unqueue->create new
     alGenBuffers(1, &buffer);
     break;
   case 1:  // on buffer to unqueue->use that
     alSourceUnqueueBuffers(m_Source, 1, &buffer);
     enqueued -= BLOCK_SIZE_SAMPLES;
     break;
   default:  // multiple buffers to unqueue->take one,delete on
     {       // could also delete more if processed>2
             // but doesn't happen often
             // therefore simple implementation(will del. in next loop)
       ALuint bufs[2];
       alSourceUnqueueBuffers(m_Source, 2, bufs);

       alDeleteBuffers(1, bufs);
       buffer = bufs[1];
       enqueued -= 2*BLOCK_SIZE_SAMPLES;
     }
     break;
   }

   // fill block
   alBufferData(buffer, AL_FORMAT_STEREO16, pData,
                BLOCK_SIZE_SAMPLES*4, SAMPLE_RATE);
   alSourceQueueBuffers(m_Source, 1, &buffer);

   //check state
   ALint state;
   alGetSourcei(m_Source, AL_SOURCE_STATE, &state);
   if (state != AL_PLAYING)
   {
     enqueued = BLOCK_SIZE_SAMPLES;
     alSourcePlay(m_Source);
   }
   else
     enqueued += BLOCK_SIZE_SAMPLES;
}
</code>```

Body:
I have for the first time coding sound generating with OpenAL in C++.
What I want to do is to generate endless sinus wave into a double buffering way.
And the problem is that the sound is glittering/lags. I Think it is between the buffering and I don't know why it is like that.

My code:

void _OpenALEngine::play()
{
    if(!m_running && !m_threadRunning)
    {
        ALfloat sourcePos[] = {0,0,0};
        ALfloat sourceVel[] = {0,0,0};
        ALfloat sourceOri[] = {0,0,0,0,0,0};
        alGenSources(1, &FSourceID);
        alSourcefv (FSourceID, AL_POSITION, sourcePos);
        alSourcefv (FSourceID, AL_VELOCITY, sourceVel);
        alSourcefv (FSourceID, AL_DIRECTION, sourceOri);
        GetALError();

        ALuint FBufferID[2];
        alGenBuffers( 2, &FBufferID[0] );
        GetALError();

        // Gain
        ALfloat listenerPos[] = {0,0,0};
        ALfloat listenerVel[] = {0,0,0};
        ALfloat listenerOri[] = {0,0,0,0,0,0};
        alListenerf( AL_GAIN, 1.0 );
        alListenerfv(AL_POSITION, listenerPos);
        alListenerfv(AL_VELOCITY, listenerVel);
        alListenerfv(AL_ORIENTATION, listenerOri);
        GetALError();

        alSourceQueueBuffers( FSourceID, 2, &FBufferID[0] );
        GetALError();

        alSourcePlay(FSourceID);
        GetALError();

        m_running = true;
        m_threadRunning = true;
        Threading::Thread thread(Threading::ThreadStart(this, &_OpenALEngine::threadPlaying));
        thread.Start();
    }
}

Void _OpenALEngine::threadPlaying()
{

    while(m_running)
    {
        // Check how much data is processed in OpenAL's internal queue.
        ALint Processed;
        alGetSourcei( FSourceID, AL_BUFFERS_PROCESSED, &Processed );
        GetALError();

        // Add more buffers while we need them.
        while ( Processed-- )
        {
            alSourceUnqueueBuffers( FSourceID, 1, &BufID );

            runBuffer(); // <--- Generate the sinus wave and submit the Array to the submitBuffer method.

            alSourceQueueBuffers( FSourceID, 1, &BufID );

            ALint val;
            alGetSourcei(FSourceID, AL_SOURCE_STATE, &val);
            if(val != AL_PLAYING)
            {
                alSourcePlay(FSourceID);
            }
        }

        // Don't kill the CPU.
        Thread::Sleep(1);
    }

    m_threadRunning = false;

    return Void();
}

void _OpenALEngine::submitBuffer(byte* buffer, int length)
{
    // Submit more data to OpenAL
    alBufferData( BufID, AL_FORMAT_MONO8, buffer, length * sizeof(byte), 44100 );
}

I generate the sinus wave in the runBuffer() method. And the sinus  generator is correct because when I increase the buffer array from 4096 to 40960 the glittering/lags sound with bigger interval. Thank you very much if some one know the problem and will share it :)

Body:
Similar Problems are all over the internet and I'm not 100% sure this is the solution to this on. But it probably is, and if not it might at least help others. Most other threads are on different forums and I'm not registering everywhere just to share my knowledge...

The code below is what I came up after 2 days of experimenting. Most solutions I found did not work for me...
(it's not exactly my code, I stripped it of some parts special to my case, so I'm sorry if there are typos or similar that prevent it from being copied verbatim)

My experiments were on an iPhone. Some of the the things I found out, might be iOS-specific.

The problem is that there is no guaranty at what point a processed buffer is marked as such and is available for unqueueing. Trying to build a version that sleeps until a buffer becomes available again I saw that this might be much(I use very small buffers) later than expected. So I realised that the common idea to wait until a buffer is available(which works for most frameworks, but not openAL) is wrong. Instead you should wait until the time you should enqueue another buffer.
With that you have to give up the idea of double-buffering. When the time comes you should check if a buffer exists and unqueue it. But if none is available you need to create a 3rd...

Waiting for when a buffer should be enqueue can be done by calculating times relative to the system-clock, which worked fairly well for me but I decided to go for a version where I rely on a time source that is definitivly in sync with openAL. Best I came up with was wait depending on what s left in the queue. Here, iOS seems not fully in accordance to openAL-spec because AL_SAMPLE_OFFSET should be exact to one sample but I never saw anything but multiples of 2048. That's about 45 microseconds @44100, this is where the 50000 in the code comes from(little more than the smalest unit iOS handles)
Depending on the block-size this can easily be bigger. But with that code I had 3 times that alSourcePlay() was needed again in the last ~hour(compared to up to 10 per minute with other implementations that claimed to be the solution)

uint64 enqueued(0);  // keep track of samples in queue
while (bKeepRunning)
{
   // check if enough in buffer and wait
   ALint off;
   alGetSourcei(m_Source,  AL_SAMPLE_OFFSET, &off);
   uint32 left((enqueued-off)*1000000/SAMPLE_RATE);
   if (left > 50000) // at least 50000 mic-secs in buffer
     usleep(left - 50000);

   // check for available buffer
   ALuint buffer;

   ALint processed;
   alGetSourcei(m_Source, AL_BUFFERS_PROCESSED, &processed);
   switch (processed)
   {
   case 0:  // no buffer to unqueue->create new
     alGenBuffers(1, &buffer);
     break;
   case 1:  // on buffer to unqueue->use that
     alSourceUnqueueBuffers(m_Source, 1, &buffer);
     enqueued -= BLOCK_SIZE_SAMPLES;
     break;
   default:  // multiple buffers to unqueue->take one,delete on
     {       // could also delete more if processed>2
             // but doesn't happen often
             // therefore simple implementation(will del. in next loop)
       ALuint bufs[2];
       alSourceUnqueueBuffers(m_Source, 2, bufs);

       alDeleteBuffers(1, bufs);
       buffer = bufs[1];
       enqueued -= 2*BLOCK_SIZE_SAMPLES;
     }
     break;
   }

   // fill block
   alBufferData(buffer, AL_FORMAT_STEREO16, pData,
                BLOCK_SIZE_SAMPLES*4, SAMPLE_RATE);
   alSourceQueueBuffers(m_Source, 1, &buffer);

   //check state
   ALint state;
   alGetSourcei(m_Source, AL_SOURCE_STATE, &state);
   if (state != AL_PLAYING)
   {
     enqueued = BLOCK_SIZE_SAMPLES;
     alSourcePlay(m_Source);
   }
   else
     enqueued += BLOCK_SIZE_SAMPLES;
}


问:
How to include one header for every page in different folders
How can I use one header.php file for every html page in different folders?

For example:

My header.php file is in homepage/includes folder.

And i include like this include "includes/header.php";

up to now, everything is okay.

And i have a diffent folder on my homepage called "users"

And i wanna include my header.php file, which is on homepage/includes folder, on homepage/users/index.php file.

And i include like this "include "../includes/header.php", but I have errors.

Cause on my header.php file I call my css files like <link href="assets/css/demo.css"/>

So I need to copy my header.php file to users folder.

And I need to change href="assets/...." like href="../assets/...."

Isn't there any way to solve it?? Thank you.

答:
First of the wall, you can create config.php file with global variables to all of your php files which needs that variables. Put it in the main folder of your project and include it in any file you need.

Then, you can define $path = '/absolute/path/to/your/project'; variable in your config.php and use it when you need. Then, if you ever will need to change this path value, you only should change value of that variable.

At the other hand, it is an magic constant __DIR__ (http://php.net/manual/en/language.constants.predefined.php), which return absolute path to file with it (if you use this constant in includes/header.php it will return /path/to/homepage/includes/, but if you use it in users/index.php it will return /path/to/homepage/users/).

In this case it should work, when you type include __DIR__.'../includes/header.php';, but I recommend to solve your problem in the first way, because if structure of your project will be changed, you must change any file with those lines in it.


问:
Office js Add-in compatibility
I have recently developed an Add-in for my company using the Word API. It works perfectly on my machine using Word 2016.

My question is, will this Add-in work for older Word versions (2003 or newer )?

If not is there a work around this, or how to rewrite one that works for all version starting from 2003?

答:
Office.js was launched with Office 2013 for Windows. It is not supported on any versions prior to Office 2013 for Windows (or Office 2016 for Mac).

WordApi is a more recent addition. This API is only supported by Word 2016 for Windows/Mac, Word for iPad and Word Online.

You can find the supported hosts and platforms at Office Add-in Availability.

With regards to your question on a workaround, there isn't any workarounds for leveraging Office.js with legacy/unsupported versions of Office.

Title: Office js Add-in compatibility


问:
Plotting categorical variable against numeric variable in matplotlib
My DataFrame's structure

```<code>trx.columns
Index(['dest', 'orig', 'timestamp', 'transcode', 'amount'], dtype='object')
</code>```

I'm trying to plot transcode (transaction code) against amount to see the how much money is spent per transaction. I made sure to convert transcode to a categorical type as seen below.

```<code>trx['transcode']
...
Name: transcode, Length: 21893, dtype: category
Categories (3, int64): [1, 17, 99]
</code>```

The result I get from doing plt.scatter(trx['transcode'], trx['amount']) is

Scatter plot

While the above plot is not entirely wrong, I would like the X axis to contain just the three possible values of transcode [1, 17, 99] instead of the entire [1, 100] range.

Thanks!

答:
In matplotlib 2.1 you can plot categorical variables by using strings. I.e. if you provide the column for the x values as string, it will recognize them as categories.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                   "y" : np.random.rand(100)*100})

plt.scatter(df["x"].astype(str), df["y"])
plt.margins(x=0.5)
plt.show()
</code>```

In order to optain the same in matplotlib <=2.0 one would plot against some index instead.

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                   "y" : np.random.rand(100)*100})

u, inv = np.unique(df["x"], return_inverse=True)
plt.scatter(inv, df["y"])
plt.xticks(range(len(u)),u)
plt.margins(x=0.5)
plt.show()
</code>```

The same plot can be obtained using seaborn's stripplot:

```<code>sns.stripplot(x="x", y="y", data=df)
</code>```

And a potentially nicer representation can be done via seaborn's swarmplot:

```<code>sns.swarmplot(x="x", y="y", data=df)
</code>```

Body:
My DataFrame's structure

trx.columns
Index(['dest', 'orig', 'timestamp', 'transcode', 'amount'], dtype='object')

I'm trying to plot transcode (transaction code) against amount to see the how much money is spent per transaction. I made sure to convert transcode to a categorical type as seen below.

trx['transcode']
...
Name: transcode, Length: 21893, dtype: category
Categories (3, int64): [1, 17, 99]

The result I get from doing plt.scatter(trx['transcode'], trx['amount']) is

Scatter plot

While the above plot is not entirely wrong, I would like the X axis to contain just the three possible values of transcode [1, 17, 99] instead of the entire [1, 100] range.

Thanks!

Body:
In matplotlib 2.1 you can plot categorical variables by using strings. I.e. if you provide the column for the x values as string, it will recognize them as categories.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                   "y" : np.random.rand(100)*100})

plt.scatter(df["x"].astype(str), df["y"])
plt.margins(x=0.5)
plt.show()

In order to optain the same in matplotlib <=2.0 one would plot against some index instead.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({"x" : np.random.choice([1,17,99], size=100),
                   "y" : np.random.rand(100)*100})

u, inv = np.unique(df["x"], return_inverse=True)
plt.scatter(inv, df["y"])
plt.xticks(range(len(u)),u)
plt.margins(x=0.5)
plt.show()

The same plot can be obtained using seaborn's stripplot:

sns.stripplot(x="x", y="y", data=df)

And a potentially nicer representation can be done via seaborn's swarmplot:

sns.swarmplot(x="x", y="y", data=df)


问:
How to use an overridden constant in an inheritanced class
given this code:

```<code>class A
  CONST = 'A'

  def initialize
    puts CONST
  end
end

class B < A
  CONST = 'B'
end

A.new # => 'A'
B.new # => 'A'
</code>```

I'd like B to use the CONST = 'B' definition, but I don't know how. Any ideas?

Greetings

Tom

答:
Sorry I couldn't get the code formatting to work in a 'comment' only in an 'answer' but this is in response to akostadinov's question to Hendrik "how is this different from his [Konstantin's] answer?"

I'd guess Hendrik was trying to access the constant from methods in his inheriting class & that depends on if it's an instance or static method.  It seems to behave as you'd expect in an instance method.  But maybe or maybe not how you'd expect for a static method.  Even if that's not what Hendrik meant, this may be worth noting:

If you have the exact class definitions as Konstantin, but you add a method to class A like this:

```<code>def self.print_const
  puts CONST
end
</code>```

Then you get A both times:

```<code>A.print_const # prints A
B.print_const # prints A
</code>```

However if you define the method in A by referencing the class:

```<code>def self.print_const
  puts self::CONST
end
</code>```

Then you get:

```<code>A.print_const # prints A
B.print_const # prints B
</code>```

Body:
given this code:

class A
  CONST = 'A'

  def initialize
    puts CONST
  end
end

class B  'A'
B.new # => 'A'

I'd like B to use the CONST = 'B' definition, but I don't know how. Any ideas?

Greetings

Tom

Body:
Sorry I couldn't get the code formatting to work in a 'comment' only in an 'answer' but this is in response to akostadinov's question to Hendrik "how is this different from his [Konstantin's] answer?"

I'd guess Hendrik was trying to access the constant from methods in his inheriting class & that depends on if it's an instance or static method.  It seems to behave as you'd expect in an instance method.  But maybe or maybe not how you'd expect for a static method.  Even if that's not what Hendrik meant, this may be worth noting:

If you have the exact class definitions as Konstantin, but you add a method to class A like this:

def self.print_const
  puts CONST
end

Then you get A both times:

A.print_const # prints A
B.print_const # prints A

However if you define the method in A by referencing the class:

def self.print_const
  puts self::CONST
end

Then you get:

A.print_const # prints A
B.print_const # prints B


问:
Akka-HTTP compilation error using custom requireParam() directive
I developed custom generic directive, which will provide param of given type, if it exists, or else reject with my custom exception.

```<code>import akka.http.scaladsl.common.NameReceptacle
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.ParameterDirectives.ParamDefAux
import akka.http.scaladsl.server.{Directive1, Route}

class MyCustomException(msg: String) extends Exception(msg)

def requireParam[T](name: NameReceptacle[T])
                   (implicit pdef: ParamDefAux[NameReceptacle[T], Directive1[T]]): Directive1[T] =
  parameter(name).recover { _ =>
    throw new MyCustomException(s"${name.name} is missed!")
  }
</code>```

It works ok, if I want to create route, using two parameters, for example:

```<code>val negSumParams: Route =
  (requireParam("param1".as[Int]) & requireParam("param2".as[Int])) {
    (param1, param2) =>
      complete((-param1-param2).toString)
  }
</code>```

But if I try to use exactly one parameter, this doesn't compile:

```<code>val negParamCompilationFail: Route =
  requireParam("param".as[Int]) {
    param => // scalac complains about missing type param here
      complete((-param).toString)
  }
</code>```

If I use it with pass directive, it works:

```<code>val negParamWithPass: Route =
  (pass & requireParam("param".as[Int])) { // this pass usage looks hacky
    param =>
      complete((-param).toString)
  }
</code>```

If I write requireParam() return type explicitly, it works too:

```<code>val negParamWithExplicitType: Route =
  (requireParam("param".as[Int]): Directive1[Int]) { // DRY violation
    param =>
      complete((-param).toString)
  }
</code>```

Why do I need these tricks? Why can't it work just with requireParam("param".as[Int])?

Scala version 2.12.1, Akka-HTTP 10.0.10.

答:
This error happens due to the Directive companion object apply method. IT allows to create a Route from a function with parameter (T => Route) => Route:

```<code>object Directive {

  /**
   * Constructs a directive from a function literal.
   */
  def apply[T: Tuple](f: (T ⇒ Route) ⇒ Route): Directive[T] =
    new Directive[T] { def tapply(inner: T ⇒ Route) = f(inner) }

}
</code>```

But the T parameter must be a tuple. In your case, the compiler can not build the Route. Your requireParam("param".as[Int]) returns a Directive1[Int] so the apply method doesn´t work because Int is not a Tuple.

To make this work you shoul use tapply method directly:

```<code>(requireParam("param1".as[Int])).tapply((param1) =>
    complete((-param1._1).toString))
</code>```

and

```<code>  val negSumParams2: Route =
    (requireParam("param1".as[Int]) & requireParam("param2".as[Int])).tapply {
      case (param1, param2) =>
        complete((-param1-param2).toString)
    }
</code>```

So it seems that every Directive tries to convert its param to TupleX. For example:

path("order" / IntNumber) returns a Directive[Tuple1[Int]] instead of Directive1[Int]. In your case requireParam("param1".as[Int]) returns Directive1[Int]

Maybe there is a better solution and to avoid tapply

Body:
I developed custom generic directive, which will provide param of given type, if it exists, or else reject with my custom exception.

import akka.http.scaladsl.common.NameReceptacle
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.ParameterDirectives.ParamDefAux
import akka.http.scaladsl.server.{Directive1, Route}

class MyCustomException(msg: String) extends Exception(msg)

def requireParam[T](name: NameReceptacle[T])
                   (implicit pdef: ParamDefAux[NameReceptacle[T], Directive1[T]]): Directive1[T] =
  parameter(name).recover { _ =>
    throw new MyCustomException(s"${name.name} is missed!")
  }

It works ok, if I want to create route, using two parameters, for example:

val negSumParams: Route =
  (requireParam("param1".as[Int]) & requireParam("param2".as[Int])) {
    (param1, param2) =>
      complete((-param1-param2).toString)
  }

But if I try to use exactly one parameter, this doesn't compile:

val negParamCompilationFail: Route =
  requireParam("param".as[Int]) {
    param => // scalac complains about missing type param here
      complete((-param).toString)
  }

If I use it with pass directive, it works:

val negParamWithPass: Route =
  (pass & requireParam("param".as[Int])) { // this pass usage looks hacky
    param =>
      complete((-param).toString)
  }

If I write requireParam() return type explicitly, it works too:

val negParamWithExplicitType: Route =
  (requireParam("param".as[Int]): Directive1[Int]) { // DRY violation
    param =>
      complete((-param).toString)
  }

Why do I need these tricks? Why can't it work just with requireParam("param".as[Int])?

Scala version 2.12.1, Akka-HTTP 10.0.10.

Body:
This error happens due to the Directive companion object apply method. IT allows to create a Route from a function with parameter (T => Route) => Route:

object Directive {

  /**
   * Constructs a directive from a function literal.
   */
  def apply[T: Tuple](f: (T ⇒ Route) ⇒ Route): Directive[T] =
    new Directive[T] { def tapply(inner: T ⇒ Route) = f(inner) }

}

But the T parameter must be a tuple. In your case, the compiler can not build the Route. Your requireParam("param".as[Int]) returns a Directive1[Int] so the apply method doesn´t work because Int is not a Tuple.

To make this work you shoul use tapply method directly:

(requireParam("param1".as[Int])).tapply((param1) =>
    complete((-param1._1).toString))

and

  val negSumParams2: Route =
    (requireParam("param1".as[Int]) & requireParam("param2".as[Int])).tapply {
      case (param1, param2) =>
        complete((-param1-param2).toString)
    }

So it seems that every Directive tries to convert its param to TupleX. For example:

path("order" / IntNumber) returns a Directive[Tuple1[Int]] instead of Directive1[Int]. In your case requireParam("param1".as[Int]) returns Directive1[Int]

Maybe there is a better solution and to avoid tapply


问:
Grails/Spring REQUIRES_NEW rolling back outer transaction
REQUIRES_NEW is rolling back all transactions:

I have a method marked @Transactional(propagation = REQUIRES_NEW)
within a bean that also has methods marked @Transactional(propagation = REQUIRED). These methods never call each other. They are called from another bean individually. However when my method that has been marked with REQUIRES_NEW fails, it rolls back the whole transaction, including the methods that are marked REQUIRED (which is problematic).

My understanding is that if factored this way Spring AOP will have a chance to intercept the REQUIRES_NEW method and start a new logical transaction.

The general idea looks like this:

```<code>@Transactional
class TransactionalBean{

     @Transactional(propagation = REQUIRED)
     public void methodA(){ //do transactional work }

     @Transactional(propagation = REQUIRES_NEW)
     public void methodB(){ //do transactional work }
}
</code>```

And then the calling bean looks like so:

```<code>@Transactional
class CallingBean{
   @Autowired
   TransactionalBean

   public void doWork(){
      TransactionalBean.methodA();
      TransactionalBean.methodB();
   }
}
</code>```

So if method A and B succeed, everything is fine. However when method B fails work done in method A gets rolled back. My understanding is that when methodB() is invoked that it 'should' get intercepted by AOP and start a new transaction and suspend the other transaction, but it's not working. How do I fix this? I'm using Grails 2.5, Hibernate, JPA

答:
The problem is with the way the CallingBean was marked as @Transactional. What is happening is that the CallingBean is creating a transaction, let's say t1. The CallingBean is invoking the two transactional methods methodA and methodB. Since methodA requires a transaction, it will make use of the existing transaction t1. However, methodB will create a new transaction as the annotation requires a new one, let's say t2. The transactional boundary of methodA does not end when the control exits methodA, but is kept alive until methodB is completed since the transaction started at the calling bean. Now that the transaction t2 is failing in methodB, the exception would bubble up to the calling bean and the transaction t1 would fail.

In order to resolve this, you can do one of the following based on your needs.

Turn off the @Transactional annotation in the CallingBean class.

```<code>//@Transactional
class CallingBean{
...
}
</code>```

Update the annotation to use noRollbackFor option

```<code>@Transactional(noRollbackFor={WhateverException.class})
class CallingBean{
...
}
</code>```

Body:
REQUIRES_NEW is rolling back all transactions:

I have a method marked @Transactional(propagation = REQUIRES_NEW)
within a bean that also has methods marked @Transactional(propagation = REQUIRED). These methods never call each other. They are called from another bean individually. However when my method that has been marked with REQUIRES_NEW fails, it rolls back the whole transaction, including the methods that are marked REQUIRED (which is problematic).

My understanding is that if factored this way Spring AOP will have a chance to intercept the REQUIRES_NEW method and start a new logical transaction.

The general idea looks like this:

@Transactional
class TransactionalBean{

     @Transactional(propagation = REQUIRED)
     public void methodA(){ //do transactional work }

     @Transactional(propagation = REQUIRES_NEW)
     public void methodB(){ //do transactional work }
}

And then the calling bean looks like so:

@Transactional
class CallingBean{
   @Autowired
   TransactionalBean

   public void doWork(){
      TransactionalBean.methodA();
      TransactionalBean.methodB();
   }
}

So if method A and B succeed, everything is fine. However when method B fails work done in method A gets rolled back. My understanding is that when methodB() is invoked that it 'should' get intercepted by AOP and start a new transaction and suspend the other transaction, but it's not working. How do I fix this? I'm using Grails 2.5, Hibernate, JPA

Body:
The problem is with the way the CallingBean was marked as @Transactional. What is happening is that the CallingBean is creating a transaction, let's say t1. The CallingBean is invoking the two transactional methods methodA and methodB. Since methodA requires a transaction, it will make use of the existing transaction t1. However, methodB will create a new transaction as the annotation requires a new one, let's say t2. The transactional boundary of methodA does not end when the control exits methodA, but is kept alive until methodB is completed since the transaction started at the calling bean. Now that the transaction t2 is failing in methodB, the exception would bubble up to the calling bean and the transaction t1 would fail.

In order to resolve this, you can do one of the following based on your needs.

Turn off the @Transactional annotation in the CallingBean class.

//@Transactional
class CallingBean{
...
}

Update the annotation to use noRollbackFor option

@Transactional(noRollbackFor={WhateverException.class})
class CallingBean{
...
}


问:
VS Code: Search multiple directories
When searching, VS Code has the ability to list files to include to scope the search.  This is used by default when using the "find in folder" feature.  For example, searching src results in ./src as the files to include.

Is there a syntax I can use to list multiple directories here?  For example, I want to search ./src and ./lib in one search.

答: Did you try a comma like ./dir1, ./dir2? For me it seems to work

Title: VS Code: Search multiple directories


问:
Why is `multiprocessing.Queue.get` so slow?
I need help in understanding multiprocessing.Queue. The problem I'm facing is that getting results from queue.get(...) are hilariously behind compared to calls to queue.put(...) and the queue's buffer (the deque).

This leaking abstraction led me to investigate the internals of the queue. Its straightforward source code just points me to the deque implementation, and that also seems simple enough that I cannot use it to explain the behavior I'm seeing. Also I read that Queue uses pipes, but I can't seem to find that in the source code.

I've boiled it down to a minimal example reproducing the problem, and I specify a possible output below that.

```<code>import threading
import multiprocessing
import queue

q = None
def enqueue(item):
    global q
    if q is None:
        q = multiprocessing.Queue()
        process = threading.Thread(target=worker, args=(q,))  # or multiprocessing.Process Doesn't matter
        process.start()
    q.put(item)
    print(f'len putted item: {len(item)}. qsize: {q.qsize()}. buffer len: {len(q._buffer)}')

def worker(local_queue):
    while True:
        try:
            while True:  # get all items
                item = local_queue.get(block=False)
                print(f'len got item: {len(item)}. qsize: {q.qsize()}. buffer len: {len(q._buffer)}')
        except queue.Empty:
            print('empty')

if __name__ == '__main__':
    for i in range(1, 100000, 1000):
        enqueue(list(range(i)))
</code>```

Output:

```<code>empty
empty
empty
len putted item: 1. qsize: 1. buffer len: 1
len putted item: 1001. qsize: 2. buffer len: 2
len putted item: 2001. qsize: 3. buffer len: 1
len putted item: 3001. qsize: 4. buffer len: 2
len putted item: 4001. qsize: 5. buffer len: 3
len putted item: 5001. qsize: 6. buffer len: 4
len putted item: 6001. qsize: 7. buffer len: 5
len putted item: 7001. qsize: 8. buffer len: 6
len putted item: 8001. qsize: 9. buffer len: 7
len putted item: 9001. qsize: 10. buffer len: 8
len putted item: 10001. qsize: 11. buffer len: 9
len putted item: 11001. qsize: 12. buffer len: 10
len putted item: 12001. qsize: 13. buffer len: 11
len putted item: 13001. qsize: 14. buffer len: 12
len putted item: 14001. qsize: 15. buffer len: 13
len putted item: 15001. qsize: 16. buffer len: 14
len got item: 1. qsize: 15. buffer len: 14
len putted item: 16001. qsize: 16. buffer len: 15
len putted item: 17001. qsize: 17. buffer len: 16
len putted item: 18001. qsize: 18. buffer len: 17
len putted item: 19001. qsize: 19. buffer len: 18
len putted item: 20001. qsize: 20. buffer len: 19
len putted item: 21001. qsize: 21. buffer len: 20
len putted item: 22001. qsize: 22. buffer len: 21
len putted item: 23001. qsize: 23. buffer len: 22
len putted item: 24001. qsize: 24. buffer len: 23
len putted item: 25001. qsize: 25. buffer len: 24
len putted item: 26001. qsize: 26. buffer len: 25
len putted item: 27001. qsize: 27. buffer len: 26
len putted item: 28001. qsize: 28. buffer len: 27
len got item: 1001. qsize: 27. buffer len: 27
empty
len putted item: 29001. qsize: 28. buffer len: 28
empty
empty
empty
len got item: 2001. qsize: 27. buffer len: 27
empty
len putted item: 30001. qsize: 28. buffer len: 28
</code>```

I want you to notice the following about the result: After inserting element 28001, the worker finds that there are no elements left in the queue, whereas there are dozens more. Because of synchronization, I'm okay with only getting all but a few of them. But it only manages to find two!

And this pattern continues.

This seems to do with the size of the objects I put on the queue. For small objects, say i as opposed to list(range(i)), this problem does not appear. But the sizes of the objects that were talking about are still kilobytes, not nearly large enough to dignify such significant delays (in my real-world non-minimal example this took minutes easily)

My question specifically is: How can I share (not so) large amounts of data between processes in Python?
Additionally, I'd like to know where in the internal implementation of Queue does this sluggishness comes from

答:
I met this problem too. I was sending large numpy arrays (~300MB), and it was so slow at mp.queue.get().

After some look into the python2.7 source code of mp.Queue, I found the slowest part (on unix-like systems) is _conn_recvall() in socket_connection.c, but I was not looking deeper.

To workaround the problem I build an experimental package FMQ.

This project is inspired by the use of multiprocessing.Queue (mp.Queue). mp.Queue is slow for large data item because of the speed limitation of pipe (on Unix-like systems).

With mp.Queue handling the inter-process transfer, FMQ implements a stealer thread, which steals an item from mp.Queue once any item is available, and puts it into a Queue.Queue. Then, the consumer process can fetch the data from the Queue.Queue immediately.

The speed-up is based on the assumption that both producer and consumer processes are compute-intensive (thus multiprocessing is neccessary) and the data is large (eg. >50 227x227 images). Otherwise mp.Queue with multiprocessing or Queue.Queue with threading is good enough.

fmq.Queue is used easily like a mp.Queue.

Note that there are still some Known Issues, as this project is at its early stage.

Body:
I need help in understanding multiprocessing.Queue. The problem I'm facing is that getting results from queue.get(...) are hilariously behind compared to calls to queue.put(...) and the queue's buffer (the deque).

This leaking abstraction led me to investigate the internals of the queue. Its straightforward source code just points me to the deque implementation, and that also seems simple enough that I cannot use it to explain the behavior I'm seeing. Also I read that Queue uses pipes, but I can't seem to find that in the source code.

I've boiled it down to a minimal example reproducing the problem, and I specify a possible output below that.

import threading
import multiprocessing
import queue

q = None
def enqueue(item):
    global q
    if q is None:
        q = multiprocessing.Queue()
        process = threading.Thread(target=worker, args=(q,))  # or multiprocessing.Process Doesn't matter
        process.start()
    q.put(item)
    print(f'len putted item: {len(item)}. qsize: {q.qsize()}. buffer len: {len(q._buffer)}')

def worker(local_queue):
    while True:
        try:
            while True:  # get all items
                item = local_queue.get(block=False)
                print(f'len got item: {len(item)}. qsize: {q.qsize()}. buffer len: {len(q._buffer)}')
        except queue.Empty:
            print('empty')

if __name__ == '__main__':
    for i in range(1, 100000, 1000):
        enqueue(list(range(i)))

Output:

empty
empty
empty
len putted item: 1. qsize: 1. buffer len: 1
len putted item: 1001. qsize: 2. buffer len: 2
len putted item: 2001. qsize: 3. buffer len: 1
len putted item: 3001. qsize: 4. buffer len: 2
len putted item: 4001. qsize: 5. buffer len: 3
len putted item: 5001. qsize: 6. buffer len: 4
len putted item: 6001. qsize: 7. buffer len: 5
len putted item: 7001. qsize: 8. buffer len: 6
len putted item: 8001. qsize: 9. buffer len: 7
len putted item: 9001. qsize: 10. buffer len: 8
len putted item: 10001. qsize: 11. buffer len: 9
len putted item: 11001. qsize: 12. buffer len: 10
len putted item: 12001. qsize: 13. buffer len: 11
len putted item: 13001. qsize: 14. buffer len: 12
len putted item: 14001. qsize: 15. buffer len: 13
len putted item: 15001. qsize: 16. buffer len: 14
len got item: 1. qsize: 15. buffer len: 14
len putted item: 16001. qsize: 16. buffer len: 15
len putted item: 17001. qsize: 17. buffer len: 16
len putted item: 18001. qsize: 18. buffer len: 17
len putted item: 19001. qsize: 19. buffer len: 18
len putted item: 20001. qsize: 20. buffer len: 19
len putted item: 21001. qsize: 21. buffer len: 20
len putted item: 22001. qsize: 22. buffer len: 21
len putted item: 23001. qsize: 23. buffer len: 22
len putted item: 24001. qsize: 24. buffer len: 23
len putted item: 25001. qsize: 25. buffer len: 24
len putted item: 26001. qsize: 26. buffer len: 25
len putted item: 27001. qsize: 27. buffer len: 26
len putted item: 28001. qsize: 28. buffer len: 27
len got item: 1001. qsize: 27. buffer len: 27
empty
len putted item: 29001. qsize: 28. buffer len: 28
empty
empty
empty
len got item: 2001. qsize: 27. buffer len: 27
empty
len putted item: 30001. qsize: 28. buffer len: 28

I want you to notice the following about the result: After inserting element 28001, the worker finds that there are no elements left in the queue, whereas there are dozens more. Because of synchronization, I'm okay with only getting all but a few of them. But it only manages to find two!

And this pattern continues.

This seems to do with the size of the objects I put on the queue. For small objects, say i as opposed to list(range(i)), this problem does not appear. But the sizes of the objects that were talking about are still kilobytes, not nearly large enough to dignify such significant delays (in my real-world non-minimal example this took minutes easily)

My question specifically is: How can I share (not so) large amounts of data between processes in Python?
Additionally, I'd like to know where in the internal implementation of Queue does this sluggishness comes from

Body:
I met this problem too. I was sending large numpy arrays (~300MB), and it was so slow at mp.queue.get().

After some look into the python2.7 source code of mp.Queue, I found the slowest part (on unix-like systems) is _conn_recvall() in socket_connection.c, but I was not looking deeper.

To workaround the problem I build an experimental package FMQ.

This project is inspired by the use of multiprocessing.Queue (mp.Queue). mp.Queue is slow for large data item because of the speed limitation of pipe (on Unix-like systems).

With mp.Queue handling the inter-process transfer, FMQ implements a stealer thread, which steals an item from mp.Queue once any item is available, and puts it into a Queue.Queue. Then, the consumer process can fetch the data from the Queue.Queue immediately.

The speed-up is based on the assumption that both producer and consumer processes are compute-intensive (thus multiprocessing is neccessary) and the data is large (eg. >50 227x227 images). Otherwise mp.Queue with multiprocessing or Queue.Queue with threading is good enough.

fmq.Queue is used easily like a mp.Queue.

Note that there are still some <a href="http://This%20project%20is%20inspired%20by%20the%20use%20of%20multiprocessing.Queue%20(mp.Queue).%20mp.Queue%20is%20slow%20for%20large%20data%20item%20because%20of%20the%20speed%20limitation%20of%20pipe%20(on%20Unix-like%20systems).%20%20With%20mp.Queue%20handling%20the%20inter-process%20transfer,%20FMQ%20implements%20a%20stealer%20thread,%20which%20steals%20an%20item%20from%20mp.Queue%20once%20any%20item%20is%20available,%20and%20puts%20it%20into%20a%20Queue.Queue.%20Then,%20the%20consumer%20process%20can%20fetch%20the%20data%20from%20the%20Queue.Queue%20immediately.%20%20The%20speed-up%20is%20based%20on%20the%20assumption%20that%20both%20producer%20and%20consumer%20processes%20are%20compute-intensive%20(thus%20multiprocessing%20is%20neccessary)%20and%20the%20data%20is%20large%20(eg.%20%3E50%20227x227%20images).%20Otherwise%20mp.Queue%20with%20multiprocessing%20or%20Queue.Queue%20with%20threading%20is%20good%20enough." rel="noreferrer">Known Issues, as this project is at its early stage.


问:
SQL Server Full Text Search using CONTAINS, FORMSOF, NEAR for multiple search words
I am new to SQL Server Full Text Searching, and am trying to figure out the best way to search on multiple words using the inflectional engine so the search uses the various forms of all of the words.

From what I read, FREETEXT uses an implicit OR when used with multiple words. I want an AND so that the search results contain all of the words, so because of this I am choosing to use CONTAINS.

I am trying to do something like the query below, which uses FORMSOF with the proximity keyword NEAR for multiple words. Note that this is not valid syntax and returns an error:

```<code>select top 5 *
from content
WHERE CONTAINS((Title,Subtitle,Body), 'FORMSOF(INFLECTIONAL, model NEAR airplane)')
</code>```

However, the query below works, but I don't know if it gives the intended results. Is there a difference between "AND" and "NEAR" with SQL Full Text Search?

```<code>select top 5 *
from content
WHERE CONTAINS((Title,Subtitle,Body), 'FORMSOF(INFLECTIONAL, model) AND FORMSOF(INFLECTIONAL, airplane)')
</code>```

I guess what I am asking is, is there a way to use CONTAINS, FORMSOF, and NEAR with multiple search words? Or should I just use the second query above that uses "AND"?

答:
From the docs:

```<code><proximity_term> ::=
     { <simple_term> | <prefix_term> }
     { { NEAR | ~ }
     { <simple_term> | <prefix_term> }
     } [ ...n ]
</code>```

This means you can use NEAR predicate for (possible prefixed) words, phrases and their combinations.

Since your search terms are inflected using quite simple rules, you can just use prefixes:

```<code>SELECT  *
FROM    content
WHERE   CONTAINS((Title,Subtitle,Body), 'model* NEAR airplane*')
</code>```

or use AND and do fine filtering on the client side

```<code>SELECT  *
FROM    ft
WHERE   CONTAINS((Title,Subtitle,Body), 'FORMSOF(INFLECTIONAL, "model") AND FORMSOF(INFLECTIONAL, "airplane")')
</code>```

Body:
I am new to SQL Server Full Text Searching, and am trying to figure out the best way to search on multiple words using the inflectional engine so the search uses the various forms of all of the words.

From what I read, FREETEXT uses an implicit OR when used with multiple words. I want an AND so that the search results contain all of the words, so because of this I am choosing to use CONTAINS.

I am trying to do something like the query below, which uses FORMSOF with the proximity keyword NEAR for multiple words. Note that this is not valid syntax and returns an error:

select top 5 *
from content
WHERE CONTAINS((Title,Subtitle,Body), 'FORMSOF(INFLECTIONAL, model NEAR airplane)')

However, the query below works, but I don't know if it gives the intended results. Is there a difference between "AND" and "NEAR" with SQL Full Text Search?

select top 5 *
from content
WHERE CONTAINS((Title,Subtitle,Body), 'FORMSOF(INFLECTIONAL, model) AND FORMSOF(INFLECTIONAL, airplane)')

I guess what I am asking is, is there a way to use CONTAINS, FORMSOF, and NEAR with multiple search words? Or should I just use the second query above that uses "AND"?

Body:
From the docs:

<proximity_term> ::=
     { <simple_term> | <prefix_term> }
     { { NEAR | ~ }
     { <simple_term> | <prefix_term> }
     } [ ...n ]

This means you can use NEAR predicate for (possible prefixed) words, phrases and their combinations.

Since your search terms are inflected using quite simple rules, you can just use prefixes:

SELECT  *
FROM    content
WHERE   CONTAINS((Title,Subtitle,Body), 'model* NEAR airplane*')

or use AND and do fine filtering on the client side

SELECT  *
FROM    ft
WHERE   CONTAINS((Title,Subtitle,Body), 'FORMSOF(INFLECTIONAL, "model") AND FORMSOF(INFLECTIONAL, "airplane")')


问:
NSURLConnection finished with error - code -1100
What is NSURLConnection finished with error - code -1100 ? I am getting this error while uploading image from camera in iOS build. I am working in ionic 1. How this issue can be fixed?</p>

答:
1100 - NSURLErrorFileDoesNotExist

Your code tries to retrieve something at wrong url.
Server says the file doesn't exist.


问:
Can I make a type for the positive float in Erlang?
My question is about Erlang Type Language.
Can I make a type for the positive float in Erlang?
Thanks in advance.</p>

答:
At this time you can't, you can't even define a type for a single floating point number (i.e. -type one() :: 1.0.).

On the other hand, though probably really complex to implement, this seems like a good idea.

You may consider creating a new EEP at https://github.com/erlang/eep

Or opening an issue at http://bugs.erlang.org/

Or even better, if you're up for the challenge, sending a PR to https://github.com/erlang/otp.

If you do any of the above, don't forget to allow for the same degree of liberty to number() types ;)


问:
How to change the proguard mapping file name in gradle for Android project
I have android project based on gradle and I want to change mapping.txt file name after it's generated for my build. How can it be done?

upd

How it can be done in build.gradle? Since I have access there to my flavors and other stiff, I would like to create mapping file name based on flavor/build variant version.

答:
For Android Studio Gradle Plugin Version 4.1.0 and newer (since about May 2020)

This version fixes the following warning:

WARNING: API 'variant.getMappingFile()' is obsolete and has been replaced with 'variant.getMappingFileProvider()'.

```<code>applicationVariants.all { variant ->
    variant.assembleProvider.get().doLast {
        def mappingFileProvider = variant.getMappingFileProvider().get()
        if (mappingFileProvider != null) {
            try {
                def mappingFiles = mappingFileProvider.getFiles()

                for (mappingFile in mappingFiles) {
                    if (mappingFile != null && mappingFile.exists()) {
                        def newMappingFileName = "$archivesBaseName-$variant.baseName-$mappingFile.name"
                        project.logger.lifecycle("Renaming '${mappingFile.name}' to '${newMappingFileName}'")
                        def newMappingFile = new File(mappingFile.parent, newMappingFileName)

                        newMappingFile.delete()
                        mappingFile.renameTo(newMappingFile)
                    }
                }
            } catch (Exception ignored) {
                project.logger.lifecycle("No mapping files found to rename")
            }
        }
    }
}
</code>```

For Android Studio Gradle Plugin Version 3.3.0 (January 2019) through about May 2020
This overcomes previous issues where Android 3.0/Android Gradle Plugin 3.0 deprecated BuildType.isMinifyEnabled() and the gradle plugin deprecated variant.getAssemble().

```<code>applicationVariants.all { variant ->
    variant.assembleProvider.get().doLast {
        if (variant.mappingFile != null && variant.mappingFile.exists()) {
            def mappingFilename = "$archivesBaseName-$variant.baseName-mapping.txt"
            (new File(variant.mappingFile.parent, mappingFilename)).delete()
            variant.mappingFile.renameTo(variant.mappingFile.parent +
                    "/" + mappingFilename)
        }
    }
}
</code>```

Body:
For Android Studio Gradle Plugin Version 4.1.0 and newer (since about May 2020)

This version fixes the following warning:

WARNING: API 'variant.getMappingFile()' is obsolete and has been replaced with 'variant.getMappingFileProvider()'.

applicationVariants.all { variant ->
    variant.assembleProvider.get().doLast {
        def mappingFileProvider = variant.getMappingFileProvider().get()
        if (mappingFileProvider != null) {
            try {
                def mappingFiles = mappingFileProvider.getFiles()

                for (mappingFile in mappingFiles) {
                    if (mappingFile != null && mappingFile.exists()) {
                        def newMappingFileName = "$archivesBaseName-$variant.baseName-$mappingFile.name"
                        project.logger.lifecycle("Renaming '${mappingFile.name}' to '${newMappingFileName}'")
                        def newMappingFile = new File(mappingFile.parent, newMappingFileName)

                        newMappingFile.delete()
                        mappingFile.renameTo(newMappingFile)
                    }
                }
            } catch (Exception ignored) {
                project.logger.lifecycle("No mapping files found to rename")
            }
        }
    }
}

For Android Studio Gradle Plugin Version 3.3.0 (January 2019) through about May 2020
This overcomes previous issues where Android 3.0/Android Gradle Plugin 3.0 deprecated BuildType.isMinifyEnabled() and the gradle plugin deprecated variant.getAssemble().

applicationVariants.all { variant ->
    variant.assembleProvider.get().doLast {
        if (variant.mappingFile != null && variant.mappingFile.exists()) {
            def mappingFilename = "$archivesBaseName-$variant.baseName-mapping.txt"
            (new File(variant.mappingFile.parent, mappingFilename)).delete()
            variant.mappingFile.renameTo(variant.mappingFile.parent +
                    "/" + mappingFilename)
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
No local JVM's were detected, not even the jvm running this instance of java mission control
I'm new at Java, and I've just recently installed it and set the environmental variables.

But when I try to compile something, it says:

```<code>javac: file not found: BoleanTest.java
Usage: javac <options> <source files>
use -help for a list of possible options
</code>```

And when I open JVM it says:

No local JVM's were detected, not even the jvm running this instance of java mission control.

Help please, thank you.

(A photo of the error as shown on the screen)

答:
Make sure that you are in the same location as your .java file in your terminal. It seems that you are in the wrong directory.

Or

you can execute javac command from a different location as your java file like this: javac C:\Program Files\SomeDirectory\Test.java

Body:
I'm new at Java, and I've just recently installed it and set the environmental variables.

But when I try to compile something, it says:

javac: file not found: BoleanTest.java
Usage: javac <options> <source files>
use -help for a list of possible options

And when I open JVM it says:

No local JVM's were detected, not even the jvm running this instance of java mission control.

Help please, thank you.

(A photo of the error as shown on the screen)


问:
Bulk updating normalized Redux state
Let's say I have normalized state like this (using normalizr)

```<code>entities: {
  todos: {
    'aaa': {
      id: 'aaa',
      text: 'Todo A',
      completed: false
    },
    'bbb': {
      id: 'bbb',
      text: 'Todo B',
      completed: false
    },
    'ccc': {
      id: 'ccc',
      text: 'Todo C',
      completed: false
    }
  }
}
</code>```

Then I have an action that fetches array of IDs from the server, that are completed. For that action type, I have reducer like this:

```<code>const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: action.payload.completedIds.map((id) => {
          return {
            [id]: {
              ...state.todos[id],
              completed: true
            }
          }
        })
      };
    default:
      return state;
  }
};
</code>```

If I recieved an array with ['aaa', 'ccc'] (could be thousands of items in real world app), I want to set "completed" to TRUE on those respective todos in a single action, is it possible?

My current implementation of reducer doesn't work since it returns an array of objects, while original normalized state is object with IDs as key.

Thanks.

答:
I think this is the solution for your problem:

```<code>const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: Object.keys(action.payload.completedIds).reduce((previous, current) => {
            previous[current] = {
              ...state.todos[current],
              completed: true
            }
            return previous;
          }, {})
        })
      };
    default:
      return state;
  }
};
</code>```

I used this solution because returns a new object and leaves the original object as it is

Title: Bulk updating normalized Redux state

Body:
Let's say I have normalized state like this (using normalizr)

entities: {
  todos: {
    'aaa': {
      id: 'aaa',
      text: 'Todo A',
      completed: false
    },
    'bbb': {
      id: 'bbb',
      text: 'Todo B',
      completed: false
    },
    'ccc': {
      id: 'ccc',
      text: 'Todo C',
      completed: false
    }
  }
}

Then I have an action that fetches array of IDs from the server, that are completed. For that action type, I have reducer like this:

const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: action.payload.completedIds.map((id) => {
          return {
            [id]: {
              ...state.todos[id],
              completed: true
            }
          }
        })
      };
    default:
      return state;
  }
};

If I recieved an array with ['aaa', 'ccc'] (could be thousands of items in real world app), I want to set "completed" to TRUE on those respective todos in a single action, is it possible?

My current implementation of reducer doesn't work since it returns an array of objects, while original normalized state is object with IDs as key.

Thanks.

Body:
I think this is the solution for your problem:

const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: Object.keys(action.payload.completedIds).reduce((previous, current) => {
            previous[current] = {
              ...state.todos[current],
              completed: true
            }
            return previous;
          }, {})
        })
      };
    default:
      return state;
  }
};

I used this solution because returns a new object and leaves the original object as it is


问:
How to get Png files of Font awesome icons?
I make unity game and I need icons.

I think that font awesome icons are the best.

How to get .png files of these icons?

I can't put css in unity game.

I tried to download other icons, but these images are bad.

答:
For all PHP developers !

This one helps me a lot :
https://github.com/exiang/php-font-awesome-to-png

Especially for font-awesome , developer can modify icons.data.php and can add his custom code into icons.data.php file and generate the image !

This script can also work with other Fonts , we just need to find out cheat-sheet and load it on icons.data.php file , this script will automatically generate the icons.


问:
Math needed for Sql Server
I've been working in Sql server jobs since 2 years now. Although I like it, sometimes I get the feeling that at certain times, I stall too much on some tasks, and I seem to be discouraged easily from things that involve relatively simple logic. It's like, at some point I must repeat a logical condition inside my head more than 2 or 3 times in order to understand it completely.

I have the feeling that this might be of my lack of math knowledge. Can anyone please let me know what area of mathematics I can study, that would improve my Sql server coding skills?

Thank you.

答:
The field of maths most likely to be useful to you is Boolean logic

Set Theory is good for second place however it will often go into more detail that you are likely to need/use in understanding most sql queries.

A quick cheat that you may find useful is if you feed a boolean expression into wolfram alpha it will spit out a truth table for you which some find a much easier way of visualising the expression.
http://www.wolframalpha.com/input/?i=a+or+not+b

OwnerDisplayName: anon

LastEditorDisplayName: anon

Title: Math needed for Sql Server


问:
Amazon Web Services: CloudFront Report, other than 'Popular Objects'
Is there a possibility in the AWS Interface to see a report overview on all (or any) hosted files?

Actually the same that is shown in CloudFront > CloudFront Popular Objects Report, but for all the 'not so popular' files. Or just one specific file.

expected values

答:
CloudFront only knows about files that are requested. Files that are not requested will remain unknown to CloudFront.

CloudFront creates log files. You could then index your S3 bucket to create a comparison of files that are not accessed or accessed infrequently.

Amazon Athena is a nice product for processing log files stored in S3 and supports SQL for queries.


问:
How to permanently erase a file from CVS history
I have been looking for a "proper" way to completely erase a file from CVS history, but can't find it. I don't care if it still appears in the logs, or if particular checkouts with earlier revisions related to that file show up errors. All that matters is that all other files remain intact and future CVS operations are still fine.

I'm aware of the cvs remove command, but as documented, it still allows the file to be restored. I have access to the CVS server, could I just go into the Attic directory and remove the files from there, or would it cause problems?

There are two reasons I want to do this. One is that I want to get rid of a file with sensitive information, before it gets uploaded to GitHub, where a synchronized repository will be kept.

The other is that git cvsimport is failing with a "NOTICE: used alternate strip path" error for a file that is in the Attic, and I'm thinking that the easiest way to fix it, is to simply remove all the files in that directory.

答:
It is completely safe to remove the file from Attic. This will not affect any of your other files, or tags or branches. It will mean that no versions of that file will be available anywyare so i.e. a previous version of the software needs that file to compile, then that previous version will not compile properly.

I would suspect your git cvsimport issue is something different, but I don't know. I would not particularly removing all files in Attic. Although if you want to do this on a copy, just to be able to run git cvsimport, then there's no harm trying that.


问:
Shorthand Regex expression to match an alphanumeric pattern instead of [A-Za-z0-9]
I am trying to validate a string of the pattern IN-XXXXXXXX-X, where X is an alphumeric value. For It I need to write the regex expression

The regex I write is

```<code>/^IN-\w{8}-\w/g
</code>```

But it validates alphanumeric as well as underscores in place of X.The other way would be

```<code> /^IN-[A-Za-z0-9]{8}-[A-Za-z0-9]/g
</code>```

However this seems way to long. Is there a shorthand to write [A-Za-z0-9] in order to validate alphanumeric values.

答:
How about using [^\W_] to match alphanumeric characters?

\W - non-word characters. Basically, we match anything except non-word characters and underscores, which is the set of alphanumeric characters.

The regex would shorten to

```<code>^IN-[^\W_]{8}-[^\W_]
</code>```

Try it here: https://regex101.com/r/l3rqsq/1

Body:
I am trying to validate a string of the pattern IN-XXXXXXXX-X, where X is an alphumeric value. For It I need to write the regex expression

The regex I write is

/^IN-\w{8}-\w/g

But it validates alphanumeric as well as underscores in place of X.The other way would be

 /^IN-[A-Za-z0-9]{8}-[A-Za-z0-9]/g

However this seems way to long. Is there a shorthand to write [A-Za-z0-9] in order to validate alphanumeric values.

Body:
How about using [^\W_] to match alphanumeric characters?

\W - non-word characters. Basically, we match anything except non-word characters and underscores, which is the set of alphanumeric characters.

The regex would shorten to

^IN-[^\W_]{8}-[^\W_]

Try it here: https://regex101.com/r/l3rqsq/1


问:
Passing JSON data to .getJSON in jQuery?
I am trying to pass a JSON object to .getJSON but I keep getting a bad request error. This is what I am trying:

```<code>var data = {
    "SomeID": "18",
    "Utc": null,
    "Flags": "324"
};

$.getJSON("https://somewhere.com/AllGet?callback=?", JSON.stringify(data), function (result) {
    alert(result);
});
</code>```

Currently to get it working, I have to do this, but I do not like how I have to manually construct the query string:

```<code>$.getJSON("https://somewhere.com/AllGet?SomeID=18&Utc=&Flags=324&callback=?", null, function (result) {
        alert(result);
    });
</code>```

Anyone know how to make requests easier with JSON objects being passed in? I would appreciate any help or advise.

答:
I tried encoding the json and it worked.

Not sure how efficient or practical it is, sharing it just as a work around for above question.

```<code> $.getJSON("https://somewhere.com/AllGet?data="+encodeURI(JSON.stringify(data)), function (result) {
        alert(result);
 });
</code>```

Body:
I am trying to pass a JSON object to .getJSON but I keep getting a bad request error. This is what I am trying:

var data = {
    "SomeID": "18",
    "Utc": null,
    "Flags": "324"
};

$.getJSON("https://somewhere.com/AllGet?callback=?", JSON.stringify(data), function (result) {
    alert(result);
});

Currently to get it working, I have to do this, but I do not like how I have to manually construct the query string:

$.getJSON("https://somewhere.com/AllGet?SomeID=18&Utc=&Flags=324&callback=?", null, function (result) {
        alert(result);
    });

Anyone know how to make requests easier with JSON objects being passed in? I would appreciate any help or advise.

Body:
I tried encoding the json and it worked.

Not sure how efficient or practical it is, sharing it just as a work around for above question.

 $.getJSON("https://somewhere.com/AllGet?data="+encodeURI(JSON.stringify(data)), function (result) {
        alert(result);
 });


问:
Difference in raster values between R and QGIS
I want to ask what probably is a basic question about the way in which R and QGIS import raster files.

I have a single band-raster. When I import it into R, using the "raster" function of the raster package, I get this range of pixel values:

```<code>class       : RasterLayer
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /data/MTDA/CGS_S2_RADIOMETRY/2017/10/15/S2B_20171015T104525Z_31UFS_TOC_V100/S2B_20171015T104525Z_31UFS_TOC-B02_10M_V100.tif
names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -32768, 32767  (min, max)
</code>```

When I stack this layer in a raster brick, I get these min-max values:

```<code>class       : RasterLayer
band        : 2  (of  11  bands)
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /tmp/Rtmp882dZS/raster/r_tmp_2017-11-10_172819_11532_86514.grd

names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -1129, 9994  (min, max)
</code>```

However, if I load the same raster in QGIS, the min value is 228 and the max value is 907 (I calculated these values with the options "Extent: Full" and "Accuracy: Actual (slower)".

So, where do these differences come from? I do not understand exactly what R and QGIS are doing...

答:
For the first object, the min and max values are not known as the file does not provide them (or not correctly). With RasterLayer r you can do

```<code> r <- setMinMax(r)
</code>```

To see what they are. If they do not become the same as for the second layer you show, then you probably mixed something up. After clarifying these things, it might be useful to compare with QGIS. For that, you would probably need to provide an example file.

Body:
I want to ask what probably is a basic question about the way in which R and QGIS import raster files.

I have a single band-raster. When I import it into R, using the "raster" function of the raster package, I get this range of pixel values:

class       : RasterLayer
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /data/MTDA/CGS_S2_RADIOMETRY/2017/10/15/S2B_20171015T104525Z_31UFS_TOC_V100/S2B_20171015T104525Z_31UFS_TOC-B02_10M_V100.tif
names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -32768, 32767  (min, max)

When I stack this layer in a raster brick, I get these min-max values:

class       : RasterLayer
band        : 2  (of  11  bands)
dimensions  : 10980, 10980, 120560400  (nrow, ncol, ncell)
resolution  : 10, 10  (x, y)
extent      : 6e+05, 709800, 5590200, 5700000  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=31 +datum=WGS84 +units=m +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : /tmp/Rtmp882dZS/raster/r_tmp_2017-11-10_172819_11532_86514.grd

names       : S2B_20171015T104525Z_31UFS_TOC.B02_10M_V100
values      : -1129, 9994  (min, max)

However, if I load the same raster in QGIS, the min value is 228 and the max value is 907 (I calculated these values with the options "Extent: Full" and "Accuracy: Actual (slower)".

So, where do these differences come from? I do not understand exactly what R and QGIS are doing...

Body:
For the first object, the min and max values are not known as the file does not provide them (or not correctly). With RasterLayer r you can do

 r <- setMinMax(r)

To see what they are. If they do not become the same as for the second layer you show, then you probably mixed something up. After clarifying these things, it might be useful to compare with QGIS. For that, you would probably need to provide an example file.