text:
Q: Is there any LAME C++ wrapper\simplifier (working on Linux Mac and Win from pure code)? I want to create simple pcm to mp3 C++ project. I want it to use LAME. I love LAME but it's really big. so I need some kind of OpenSource working from pure code with pure lame code workflow simplifier. So to say I give it File with PCM and DEST file. Call something like:
LameSimple.ToMP3(file with PCM, File with MP3 , 44100, 16, MP3, VBR);
ore such thing in 4 - 5 lines (examples of course should exist) and I have vhat I needed It should be light, simple, powerfool, opensource, crossplatform.
Is there any thing like this?

A: inspired by Mike Seymour's answer I created a pure C++ wrapper which allows to encode / decode WAV and MP3 files in just 2 lines of code
convimp3::Codec::encode( "test.wav", "test.mp3" );
convimp3::Codec::decode( "test.mp3", "test_decoded.wav" );

no need to bother about sample rate, byte rate and number of channels - this info is obtained from WAV or MP3 file during encoding / decoding.
The library doesn't use old C i/o functions, but C++ streams only. I find it more elegant.
For convinience I created a very thin C++ wrapper over LAME and called it lameplus and a small library for extraction of sampling information from WAV files.
All files can be found here:
encoding/decoding: https://github.com/trodevel/convimp3
lameplus: https://github.com/trodevel/lameplus
wav handling: also on github, repository is wave

A: Lame really isn't difficult to use, although there are a lot of optional configuration functions if you need them. It takes slightly more than 4-5 lines to encode a file, but not much more. Here is a working example I knocked together (just the basic functionality, no error checking):
#include <stdio.h>
#include <lame/lame.h>

int main(void)
{
    int read, write;

    FILE *pcm = fopen("file.pcm", "rb");
    FILE *mp3 = fopen("file.mp3", "wb");

    const int PCM_SIZE = 8192;
    const int MP3_SIZE = 8192;

    short int pcm_buffer[PCM_SIZE*2];
    unsigned char mp3_buffer[MP3_SIZE];

    lame_t lame = lame_init();
    lame_set_in_samplerate(lame, 44100);
    lame_set_VBR(lame, vbr_default);
    lame_init_params(lame);

    do {
        read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
        if (read == 0)
            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
        else
            write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
        fwrite(mp3_buffer, write, 1, mp3);
    } while (read != 0);

    lame_close(lame);
    fclose(mp3);
    fclose(pcm);

    return 0;
}

A: I have successfully used libmp3lame in the way mike seymour proposed.
I am now trying to use the same approach using posix threads to speed up encoding.
I am greating one lame_t pointer, and have several threads doing bits of the conversion,
taking care that each thread has a unique bit of the pcm track that it transcodes.
I use one global lame_t structure that is used for the encoding in each thread.
My code works for 1 thread (no parallel execution), it also works if I delay the thread creation in parallel mode (such that there is no parallel execution, but the data structures are arrays).
When I run my code in parallel mode, I get a lot of errors such as
Internal buffer inconsistency. flushbits <> ResvSizebit reservoir error:
l3_side->main_data_begin: 5440
Resvoir size:             4088
resv drain (post)         1
resv drain (pre)          184
header and sideinfo:      288
data bits:                1085
total bits:               1374 (remainder: 6)
bitsperframe:             3336
This is a fatal error.  It has several possible causes:90%  LAME compiled with buggy version of gcc using advanced optimizations 9%  Your system is overclocked 1%  bug in LAME encoding libraryfinished encoding
Internal buffer inconsistency. flushbits <> ResvSizefinished encoding

For referernce, I attach the code that I am using, that compiles just fine.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <iostream>
#include <string>
#include <lame/lame.h>
#include <pthread.h>
#include <thread>
#include <chrono>

using namespace std;

typedef struct Data{
    lame_t lame;
    FILE * wav_file;
    short int * pcm_buffer;
    unsigned char * mp3_buffer;
    unsigned long mp3_buffer_size;
    unsigned long first_sample;
    unsigned long n_samples;
    unsigned long items_read;
    unsigned long mp3_bytes_to_write;
    pthread_mutex_t *mutexForReading;
} Data;

void *encode_chunk(void *arg)
{
    Data * data = (Data *) arg;

    unsigned long offset = 40 + 2 * 2 * data->first_sample;
    pthread_mutex_lock(data->mutexForReading);
    fseek(data->wav_file, offset, SEEK_SET);

    data->items_read = fread(data->pcm_buffer, 2*sizeof(short int) , data->n_samples, data->wav_file);

    cout << "first sample " << data->first_sample << " n_samples "<<  data->n_samples << " items read " << data->items_read << " data address " << data << " mp3 a " << static_cast<void *> (data->mp3_buffer) << endl;
    pthread_mutex_unlock(data->mutexForReading);

    if (data->items_read != 0)
    {
        data->mp3_bytes_to_write = lame_encode_buffer_interleaved(data->lame,
                                                                  data->pcm_buffer,
                                                                  data->items_read,
                                                                  data->mp3_buffer,
                                                                  data->mp3_buffer_size);
    }
    cout << "finished encoding " << endl;
    return NULL;
}

int main(int argc, char * argv[])
{
    int read,write;

    FILE *wav = fopen("test.wav", "rb");
    FILE *mp3 = fopen("file.mp3", "wb");

    fseek(wav,0,SEEK_END);

    unsigned long file_size_wav = ftell(wav);
    unsigned long bytes_PCM = file_size_wav - 40;
    unsigned long n_total_samples = bytes_PCM / 4;

    const unsigned long MAX_SAMPLE_NUMBER = pow(2,10);
    const unsigned short NTHREADS = 2;
    const unsigned long MAX_MP3_SIZE = int(MAX_SAMPLE_NUMBER * 1.25 + 7200) + 1;

    short int pcm_buffer[NTHREADS][MAX_SAMPLE_NUMBER * 2]; // 2 channels
    unsigned char mp3_buffer[NTHREADS][MAX_MP3_SIZE]; // according to libmp3lame api

    lame_t lame = lame_init();
    lame_set_in_samplerate(lame, 44100);
    lame_set_VBR(lame, vbr_default);

    // lame_set_brate(lame, 128); // only for CBR mode
    // lame_set_quality(lame, 2);
    // lame_set_mode(lame, JOINT_STEREO); // 1 joint stereo , 3 mono

    lame_init_params(lame);

    Data data_ptr[NTHREADS];

    unsigned short n_main_loops = n_total_samples / MAX_SAMPLE_NUMBER / NTHREADS + 1;

    cout << "total samples " << n_total_samples << endl;
    cout << "Number of iterations in main loop : " << n_main_loops << endl;

    unsigned long samples_remaining = n_total_samples;
    unsigned long current_sample = 0;

    pthread_t threadID[NTHREADS];
    pthread_mutex_t mutexForReading = PTHREAD_MUTEX_INITIALIZER;

    for (unsigned long i = 0 ; i < n_main_loops; i ++)
    {
        for (unsigned short j = 0; j < NTHREADS; j++ )
        {
            Data data;
            data.lame = lame;
            data.wav_file = wav;
            data.pcm_buffer = pcm_buffer[j];
            data.mp3_buffer = mp3_buffer[j];
            data.first_sample = current_sample;
            data.n_samples = min(MAX_SAMPLE_NUMBER, n_total_samples - current_sample);
            data.mutexForReading = &mutexForReading;

            current_sample += data.n_samples;
            samples_remaining -= data.n_samples;

            data_ptr[j] = data;

            if (data_ptr[j].n_samples > 0)

            {
                cout << "creating " << i << " " << j << " " << data_ptr[j].first_sample << " " << data_ptr[j].n_samples << endl;
                pthread_create( &threadID[j],
                           NULL,
                           encode_chunk,
                           (void *) (&data_ptr[j]));
            }

        }
        for (unsigned short j = 0; j < NTHREADS; j++)
        {
            if (data_ptr[j].n_samples > 0)
            {
                pthread_join( threadID[j], NULL);
            }
        }

        for (unsigned short j = 0; j< NTHREADS; j++)
            if (data_ptr[j].n_samples > 0)
            {

                fwrite(data_ptr[j].mp3_buffer, data_ptr[j].mp3_bytes_to_write, 1, mp3);
            }
            else
            {
                data_ptr[j].mp3_bytes_to_write = lame_encode_flush(lame, data_ptr[j].mp3_buffer, data_ptr[j].mp3_buffer_size);

            }

    }

    lame_close(lame);
    fclose(mp3);
    fclose(wav);

}

Maybe someone knows if lame can not be used in this way in parallel code. I did not find any hints if this is possible or not.
The problem seems to be that the global lame_t structure is accessed by several threads at the same time. I thought that this would only be reading, so no problem, but I seem to be mistaken.
I also thought that a workaround might be to create a lame_t object for each thread.
I tried that, using the threads to encode mutually exclusive bits of the original wav file.
The code compiles and runs without problems, but the resulting file contains no sound.
If anyone is interested, I can add the code. It is just a minor modification of the above code with lame_t being an array of size NTHREADS.

A: I got this to work by changing 41000 to around 8000:
lame_set_in_samplerate(lame, 44100);

to
lame_set_in_samplerate(lame, 8000);

And compiled prog.c with:
gcc prog.c -lmp3lame -o prog

The file.pcm does not sound good as file.mp3. I got a perfect conversion when I used this bash command:
lame -V 5 file.wav file.mp3


text:
Q: Crashlytics (tvOS) - Symbols Still Obfuscated After Uploading DSYMs My tvOS app uses Crashlytics for stack trace reporting. As it is a bitcode built app, I used the steps here to upload the missing dSYMs from iTunes Connect. However, while the Fabric dashboard has crossed off the missing dSYM entry, all of the stack trace data for our app is still reported as __hidden.... Not sure where we're going wrong.
For my build settings, I have:
Deployment Postprocessing -> Yes (for Release configuration)
Strip Linked/Installed Product -> Yes (for all configurations)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unbound as a caching intermediate server is slow, and doing more than what I need What I need
A forwarding DNS server as an intermediry to another DNS server that serves expired records and renews its cache later.
Problem
I tried to use unbound as the only software that I've found to have this serve-expired feature.
However the problem with my unbound setup is that it sends multiple queries and does weird stuff to make itself slower (~few hundred ms) than a simple dig or nslookup (~100ms) to the upstream server (let's suppose it's address is 22.22.22.22). Is there anything that I can do to make unbound to act even simpler than this?:
/etc/unbound/unbound.conf:
include-toplevel: "/etc/unbound/unbound.conf.d/*.conf"

server:
  chroot: ""
  logfile: /var/log/unbound.log
  verbosity: 2
  log-queries: yes
  port: 53
  cache-min-ttl: 600
  rrset-cache-size: 400m
  msg-cache-size: 200m
  prefetch: yes
  serve-expired: yes
  serve-expired-ttl: 172800 # :)
  do-not-query-localhost: no
  tcp-upstream: no
  outgoing-num-tcp: 4000
  incoming-num-tcp: 4000
  access-control: ... # a few access-control lines
  so-reuseport: yes
  tcp-idle-timeout: 10000
  edns-tcp-keepalive: yes

remote-control:
  control-enable: yes

forward-zone:
  name: "ir"
  forward-addr: 46.224.1.42
  forward-addr: 8.8.4.4

forward-zone:
  name: "."
  forward-addr: 22.22.22.22 # Upstream server

A: For my purpose (caching and serving expired/stale records) and my limited knowledge CoreDNS seems to work better. It's Coredns file can be something like this:
. {
  bind lo
  forward . 22.22.22.22
  log
  cache {
    success 20000 3600 600
    denial 10000 1800 600
    prefetch 5000
    serve_stale 172800s immediate
  }
}

Where 22.22.22.22 is address of upstream sever and serve_stale 172800s immediate which imitates serve-expired feature of unbound should mean when responses are expired they are considered fresh up to 172800 seconds and immediately send the expired response to the client before checking to see if the entry is available from the source. (https://coredns.io/plugins/cache/)


text:
Q: Unexpected result with "group by"-query I am doing pagination stuff. I have sales transaction, each of which has a unique transaction id.
$sql = "SELECT COUNT(*) from sale_history group by transaction_id";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$rows = $row[0];
print $rows;
exit;

Data in my table is like:
sale id    item         customer     transaction_id
 1          abc           aaa           1234
 2          def           aaa           1234
 3          abc           bbb           9876
 4          def           bbb           9876

Now this count should give me row count 2, but it is giving me 1.

A: In order to output Number of Rows, you should use
mysql_num_rows

$sql = "SELECT COUNT(*) from sale_history group by transaction_id";
$query = mysql_query($sql);
$num_rows = mysql_num_rows($query);

A: You are looking for mysql_num_rows()
***mysql_* is a depreacted library on php though. Use PDO or mysqli_* instead.


text:
Q: Incompatibility between import and minted? minted doesn't seem to work with import using \subimport*. Is there a way to fix that because I'm becoming addicted to the package import?
Main file
\documentclass[12pt,a4paper]{article}

\usepackage{minted}
\usepackage{import}

\begin{document}

\begin{minted}{python}
for i in range(4):
    print(i**2)
\end{minted}

\input{content/intro}

\subimport*{content/}{intro}   % <-- PB here.

\end{document}

File content/intro.tex
\begin{minted}{python}
for i in range(4):
    print(i**2)
\end{minted}


text:
Q: Can't access deep children in mount mode with jest in my test Version
"jest-cli": "^22.4.2",
"babel-jest": "^22.4.1",
"react": "^16.3.2",
Summary
I have a component: <ComponentListRenderer />.
This component have a children component:
 with button role and which having an onClick function.
When onCick function is triggered it affect another children component of <ComponentListRenderer />, this component is <Collapse /> and after onClick function is triggered it isOpen props will pass from false to true.
This function is called at line 61 of ComponentsListRenderer file
The encountered issue is that i can't test this function in my test file of <ComponentListRenderer />
current bug behavior
I can't access to
 with it onClick function neither to <Collapse /> component (neither any other child of <ComponentsListRenderer />).
What actually happens
The log only show my <ComponentsListRendererUnstyled /> so I can't test my function and check if it properly pass the <Collapse /> props isOpen from false to true. I test my component using mount mode (cause shallow mode will not return a deep rendering)
For now i wrote my test (unworking test) like this.
Below is the current log in my terminal after run jest cmd:
console.log src/rsg-components/ComponentsList/tests/ComponentsListRenderer.test.js:57
<BootstrapProvider theme={{...}} injectGlobal={false} utils={{...}}>
  <ThemeProvider theme={{...}}>
    <UtilityProvider utils={{...}} theme={{...}}>

    </UtilityProvider>
  </ThemeProvider>
</BootstrapProvider>

What is the expected correct behavior?
To test my component onClick behaviour i need to be able to access to child component of <ComponentsListRenderer />. For me the console.log() in my test should return something like below:
<BootstrapProvider theme={{...}} injectGlobal={false} utils={{...}}>
  <ThemeProvider theme={{...}}>
    <UtilityProvider utils={{...}} theme={{...}}>

    </UtilityProvider>
  </ThemeProvider>
</BootstrapProvider>

Is someone know how to solve this issue ?

A: SOLVED:
My bad, I didn't use a correct props items.
Using the props below make my child component appear when log:

      items: [
        {
          name: 'First component',
          href: '/#first-component',
          filepath: 'first-component.md',
          heading: false,
          level: 0,
          content: false,
          collapse: true,
          slug: 'introduction',
          components: [],
          sections: [],
        },
      ],


text:
Q: Sum of Squares and Harmonic Functions Let $a_0, a_1, \dots a_k$ be non-negative reals. Any homogeneous polynomial $p$ of degree $2k$ in $\mathbb{R}^{d}$ can be decomposed as
$$
p(x)=\sum_{i=0}^{k}c_i|x|^{2(k-i)}p_{2i}(x)
$$
for some $c_i$, where each $p_{2i}$ is a spherical harmonic of degree $2i$. My question is:
$$
\begin{equation}
\boxed{\text{Is there any sum of squares } p(x) \text{ such that } p_{2i}(e_1)=a_i \text{ for } i=0,\dots, k?}
\end{equation}
$$
Here $e_1=(1,0,\dots,0)\in \mathbb{R}^d$. If so, how can I found one of those?
Thanks!


text:
Q: javascript get index of a value in the dropdownlist I am passing a value to the dropdownlist, how to get the index of the value of the dropdownlist and set it using javascript?
 document.getElementById("ddlColors").selectedIndex = ?

Thank you

A: A loop is the only way, really:
var options = document.getElementById('ddlColors').options;

for(var i = 0; i < options.length; i++) {
    if(options[i].value === someValue) {
        options[i].selected = true;
        break;
    }
}

Here's a demo.

A: I think I misunderstood your question cause if I didn't the answer is too pretty forward: use the value
http://jsbin.com/urezor/2/edit


text:
Q: Элементы коллекции Set в порядке добавления Здравствуйте. Есть Set, но элементы его расположены не в порядке добавления. Почему и как с этим бороться? Как сделать чтобы элементы сета располагались в порядке добавления? Спасибо.

A: Разобрался. Нужно использовать LinkedHashSet


text:
Q: Two loader gifs handling two events in the same PHP page I'm trying to get a 'Loader' gif showed up in the same PHP page in two different instances.

*

*One the page load

*Other on form submission.

My script looks like this.

Corresponding
 /  looks like this:

Loading...

Unfortunately the e.preventDefault(); does not seems to work in this instance where I see the page load 'Loader' also display on form submission.
Is there a workaround?
EDIT
With the comments I did edit the snippet like this however the issue remains unsolved.

A: If you are writing anything after return, it means that is not calling at all. In your case you are using e.preventDefault() after return so it is not calling.


text: Q: How to direct sound to one headphone ubuntu vlc? My right earpiece is gone. So , I would like to send the sound only to left headphone . Is it possible ??the thing is , some sound is low in one earpiece and high in other , like the base is very low in left but louder in right. But Now I have to make all equal.


text:
Q: How does a circular object reference work in JavaScript? This question arose from an exercise that prompted me to create a circular object such that, in pseudo-code,
circular.value === "Hello World"
circular === circular.self
circular.self === circular.self.self

...and so on.
I noticed that if I construct an object literal like this,
var circular= {
  value: 'Hello World',
  self: circular
}

then circular.self is undefined. However, if I construct an empty object and then assign the values to the properties like this,
var circular = {};
circular.value = 'Hello World',
circular.self = circular;

then circular.self (or circular.self.self.self.self.self) is { value: 'Hello World', self: [Circular] }. The same is true no matter what I name the property that is self in these examples.
So my specific question is what causes circular.self to be undefined in the former example while it behaves as I expected in the latter?

A: var circular is (because it uses the var keyword) hoisted and declares a variable in the current scope as the scope is created (i.e. when the function or global scope is entered). It starts out with a value of undefined
{ ... } creates a new object and evaluates as a reference to it.
circular = { ... } takes that reference and assigns it to circular.
The assignment doesn't take place until after the object literal syntax has been evaluated.
If you try to read the value of circular inside the object literal syntax, it will be undefined because you are doing so before the assignment happens.

In the second example, the object exists and the reference has been assigned to circular before you try to read the value of circular. The object can then be modified to add a new property whose value is that reference.


text:
Q: file in the controller says undefined I am having trouble while uploading a file. I have created one service:
angular
.module('app')
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
    var fd = new FormData();
    fd.append('file', file);
    $http.post(uploadUrl, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
}}]);

then i have a directive:
.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};}]);

And in the controller:
$scope.uploadFile = function(){
    var file = $scope.myFile;
    console.log('file is ' );
    console.dir(file);
    var uploadUrl = "/fileUpload";
    fileUpload.uploadFileToUrl(file, uploadUrl);
};

HTML:
Browse <input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>

As you can see i am using console.log in the controller and what i am having is

file is undefined

Thanks in advance!

A: change
    .directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
scope: {
        percent: "=fileModel"

    },
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;
scope.$watch('percent', function(value) {
console.log(value)
});

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};}]);

check the console value inside the percentage watch once you upload file


text:
Q: Loop inverse of pointer, last character? I have a problem when it comes to showing a result of a pointer.
I'm trying to show the word and for each time eliminating the last character, that is, what I'm trying to do is the opposite of this
#include <stdio.h>

int main() {
    char str[128] = "Some Text";
    char *p;
    int i =0;

    for (p = str; *p ; p++) {
        printf(" value => %s \n ",p);
    }

    return 0;
}

outPut
 value => Some Text
  value => ome Text
  value => me Text
  value => e Text
  value =>  Text
  value => Text
  value => ext
  value => xt
  value => t

I'm trying this, but I do not get it
value => Some Text
value => Some Tex
value => Some Te
value => Some T
value => Some
value => Som
value => So
value => S

A: First thing you need to do is remove the space character after the newline character in the format string.
    printf(" value => %s \n",p);

The next thing you need to do is keep moving the terminating null character. For that, you need to store a pointer that points to the terminating null character.
Here's an updated version of your program:
#include <stdio.h>
#include <string.h>

int main() {
    char str[128] = "Some Text";
    char *p = str;
    char *end = str + strlen(str);

    // The *(--end) = '\0' is the crucial part.
    // It decrements end so it points to the previous character
    // and changes its value to the null character.
    for ( ; end > p; *(--end) = '\0')
    {
       printf(" value => %s \n",p);
    }

    return 0;
}

Can you put any example with the typical "for" with index?

Sure.
Here's one that a little bit more simplified than the first one.
for ( ; end > p; --end)
{
   *end = '\0';
   printf(" value => %s \n",p);
}

Here's one that uses a "typical" for loop.
for ( int i = 0; i < len; ++i)
{
   p[len-i] = '\0';
   printf(" value => %s \n",p);
}

A: The question's code changes the string's beginning by adjusting where the string starts (p++ in the for loop). To change the ending of the string we instead adjust where the string ends by overwriting the last character with a NUL (0) byte. We achieve this by moving an index (i) from the end of the string (strlen(str)) towards the beginning.
#include <stdio.h>

int main() {
    char str[128] = "Some Text";
    char *p;
    int i;

    for (i = strlen(str); i>0; i--) {
        str[i] = 0;
        printf(" value => %s \n ",str);
    }

    return 0;
}

A: An alternate solution, using a bit of a different technique:
#include <stdio.h>

int main() {
    char str[128] = "Some Text";
    int i = strlen(str) + 1 ;

    while( i --> 1 ) {
        printf("value => %.*s \n", i, str );
    }

    return 0;
}


text:
Q: ConcurrentModificationException Room Android I am using Room in my app and while inserting data into my db a ConcurrentModificationException is thrown at times. Why is it so?
I use a pagination api and after each api call I insert dataList into my db using
new Thread(new Runnable() {
            @Override
            public void run() {
                    appDatabase.dataDao().insertMultipleData(dataList);
            }
        }).start();

where
appDatabase = Room.databaseBuilder(context, AppDatabase.class, AppDatabase.DATABASE_NAME)
                .fallbackToDestructiveMigration()
                .build();

Insert operation
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertMultipleData(List<Data> dataList);

A: This is a typical scenario if you are trying to insert data in a paginated list. Since you have not pasted error logs, i assume that the error is caused on the dataList object. In that case the error message woule look like below.
 java.util.ConcurrentModificationException
        at java.util.ArrayList$Itr.next(ArrayList.java:860)
        at androidx.room.EntityInsertionAdapter.insertAndReturnIdsArray(EntityInsertionAdapter.java:131)
        at com.myApp.data.database.entities.FeedDataDao_Impl.insertAll(FeedDataDao_Impl.java:220)

If this is the case, the error is caused by paralell modification of same variable by different threads. In this case i assume that you are inserting the data to database and at the same doing new service call(pagination) to fetch data updating the same data object. Or this can be thrown even if you remove the contents from original array source while it is being inserted. The solution is pretty simple. You can copy the variable dataList to a new variable and use the new local variable as parameter to your insert call.
Eg:  (Kotlin)
val localCopy = dataList
CoroutineScope(Dispatchers.IO).launch {

        AppDatabase.getDatabase(context).feedDataDao().insertAll(localCopy).size

 }.invokeOnCompletion {
        Log.d("Inserted all items")
 }

Eg:  (Java)
List<MyDataType> localCopy = dataList
AppDatabase.getDatabase(context).feedDataDao().insertAll(localCopy).size


text:
Q: Cross browser Issue with horizontal image scrolling Here is my Fiddle.
I am facing issues in scrolling.
I open the page in Chrome the scroll works perfectly fine,it stops when the content is finished.But in firefox it keeps on scrolling even if the content is finished as i have defined the fixed width to div.
My problem is i don't know how many images will be there, as it will come from database so i can't use fixed width for scrolling.
How can i get this fixed.
I use mouse drag for scrolling.
Here is my CSS code
#timeline {
    height: 375px;
    margin-top: 10px;
    padding: 20px;
    overflow: auto;
}

.tl-events {
    width: 11800px;
    list-style: none;
    padding: 0;
    margin: 0;
}

.tl-events li {
    float: left;
    width: 300px;
    margin-right: 10px;
}

.tl-events ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

This is my html

Welcome to the interactive timeline of Google history!

Travel through time by dragging the timeline or the slider below. Click on any event to see more information.

Welcome to the interactive timeline of Google history!

Travel through time by dragging the timeline or the slider below. Click on any event to see more information.

Welcome to the interactive timeline of Google history!

Travel through time by dragging the timeline or the slider below. Click on any event to see more information.

Welcome to the interactive timeline of Google history!

Travel through time by dragging the timeline or the slider below. Click on any event to see more information.

Welcome to the interactive timeline of Google history!

Travel through time by dragging the timeline or the slider below. Click on any event to see more information.

Welcome to the interactive timeline of Google history!

Travel through time by dragging the timeline or the slider below. Click on any event to see more information.

And here is my JS
$(document).ready(function () {
        $('#timeline').mousedown(function (event) {
            $(this)
                .data('down', true)
                .data('x', event.clientX)
                .data('scrollLeft', this.scrollLeft);

            return false;
        }).mouseup(function (event) {
            $(this).data('down', false);
        }).mousemove(function (event) {
            if ($(this).data('down') == true) {
                this.scrollLeft = $(this).data('scrollLeft') + $(this).data('x') - event.clientX;
            }
        }).mousewheel(function (event, delta) {
            this.scrollLeft -= (delta * 30);
        }).css({
            'overflow' : 'hidden',
            'cursor' : '-moz-grab'
        });
    });

    $(window).mouseout(function (event) {
        if ($('#timeline').data('down')) {
            try {
                if (event.originalTarget.nodeName == 'BODY' || event.originalTarget.nodeName == 'HTML') {
                    $('#timeline').data('down', false);
                }
            } catch (e) {}
        }
    });

What am i doing wrong here?

A: Add display: inline-flex; width:auto; to .tl-events and then check.

A: It seems you have to get the width of the element that wrap the li options to set the width of .tl-events. You must no use a static width like .tl-events { width: 11800px;. How could you resolve.
var welcome = $('.welcome'), cont=0;

$(welcome).each(function(index) {
    cont++;
});

var welcome_w = $('.welcome').width * cont;
$('#timeline').css('width', welcome_w);

You need the element 'welcome' to get it's width and multiply it by the number of welcome elements. Try this inside your $(document).ready function. And IMPORTANT delete your width from css of your .tl-events class.


text:
Q: Rad Editor style Issue Hi i am new to Rad Editor,
i have set background for Rad Editor it looks like

but when i use same code in my another machine

both of the system configuration are same
browser also same
I think it may thier is setting in the Rad Editor
i dont why it changes please give me some solution to solve this
Thanks in Advance

A: The problem is not reproducible in the live demos of RadEditor under IE11, Chrome and Firefox: http://demos.telerik.com/aspnet-ajax/editor/examples/builtincontentfilters/defaultcs.aspx
Check whether you have not disabled any of the built-in content filters of the control.


text:
Q: I'm trying to perform certain pattern matching using python's re module Text = " If I can stop one heart from breaking,

I shall not live in vain;

If I can ease one life the aching,

Or cool one pain,

Or help one fainting robin

Unto his nest again,

I shall not live in vain."

Problem:
If the pattern has characters ai or hi, replace the next three characters with *\*.
I have tried using re.search() and re.sub() numerous times but I'm not able to figure out the logic to replace the next three characrers.
Expected Output:
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the achi*\*
Or cool one pain,
Or help one fai*\*ng robin
Unto hi*\*est again,
I shall not live in vain.
My code:
match_res = re.search(r"ai|hi",poem).group()

I'm not able extract "hi"
I'm also not able to get the desired output

A: The re module will work for this, if you use a positive lookbehind:
your_text = "If I can ease one life the aching,"
re.sub("(?<=[ah]i).{3}", "***", your_text)

Output
'If I can ease one life the achi***'

Explanation
(?<=[ah]i) is a positive lookbehind, which will match only when the preceding two characters match the pattern [ah]i
.{3} matches any three characters (except newlines)


text:
Q: What is the difference between Optical flow estimation and Disparity estimation? I am trying to understand some computer vision topics. One main difference I observed between these two is that In optical flow, the 2nd image is often at time (t+1) whereas in disparity estimation, its often the same time-step unless one is having a static view and using single non-stereo camera.
Is there any other difference and their respective implications ?

A: As you pointed out, Optical flow represents the displacement of pixels between an image at time t and at time t+1 whereas disparity estimation is the displacement of a pixel between one camera and another.
Strictly speaking these two tasks could be considered identical.
However, in practice, disparity is computed using a "right" and a "left" camera which are horizontally aligned. Therefore, the disparity is only horizontal (and in a single direction due to the laws of optics) and can be represented by a heatmap.
On the contrary, Optical flow is a 2D vector field in which vectors can take any value.
In machine learning, this distinction mainly changes the dimension of the output (1D for disparity and 2D for Optical flow) to predict as well as its scale (positive for disparity vs all real numbers for Optical flow).
I hope my answer was clear :)


text:
Q: Python: how to drop rows in Pandas if two columns don't appear in another pandas column? I have two dataframes df and df1. df contains name and attributes of people.
df  Name       Age
0   Jack       33
1   Anna       25
2   Emilie     49
3   Frank      19
4   John       42

while df1 contains the info of the number of contacts between two people. In df1 we can have some people that don't appear in df.
df1    Name1    Name2   c
0      Frank    Paul    2
1      Julia    Anna    5
2      Frank    John    1
3      Emilie   Jack    3
4      Tom      Steven  2
5      Tom      Jack    5

I want to drop all the rows from df1 in Name1 or Name2 don't appear in df.
df1    Name1    Name2   c
0      Frank    John    1
1      Emilie   Jack    3

A: Use isin -
df1[df1[['Name1', 'Name2']].isin(df.Name).all(1)]

#    Name1 Name2  c
#2   Frank  John  1
#3  Emilie  Jack  3

Or:
df1[df1.Name1.isin(df.Name) & df1.Name2.isin(df.Name)]

#    Name1 Name2  c
#2   Frank  John  1
#3  Emilie  Jack  3

A: Can also use np.isin
df1[np.isin(df1.Name1, df.Name) &
    np.isin(df1.Name2, df.Name)]


text:
Q: Black screen when trying to play movie from camera roll I have looked at a dozen different posts here and on the web. Still can't figure out. I can play a movie locally that I have attached to supporting files but when I try to play movie picked from camera roll I get a black screen. So I believe the problem is in getting the url from the uipicker and playing it.
I think my problem lies here in first two lines of playMovie-

NSURL *videoURL = [NSURL URLWithString:@"public.movie"];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: videoURL];

This is not giving me the proper url to  play movie from picker. I have also tried putting 'url' instead of @"public.movie"
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize player;

-(IBAction) selectMovie
{

    UIImagePickerController *picker =
    [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType =
    UIImagePickerControllerSourceTypePhotoLibrary;

    picker.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil];

    [self presentModalViewController:picker animated:YES];
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    //NSString *mediaType = [info valueForKey:UIImagePickerControllerMediaType];
    //[mediaType isEqualToString:@"public.movie"];
    //{
        NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];//used to be*videoURL
    MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];

    [picker dismissModalViewControllerAnimated:YES];
    //[picker release];

}

-(IBAction)playMovie
{

    NSURL *videoURL = [NSURL URLWithString:@"public.movie"];
    MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: videoURL];
    [moviePlayer prepareToPlay];
    moviePlayer.view.frame = CGRectMake(100, 100, 200, 200);
[self.view addSubview:moviePlayer.view];
    moviePlayer.shouldAutoplay = NO;
    moviePlayer.view.backgroundColor = [UIColor grayColor];

[moviePlayer play];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:moviePlayer];
    //[player release];

}

-(void) moviePlayBackDidFinish:(NSNotification*)notification
{
    MPMoviePlayerController *moviePlayer = [notification object];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:moviePlayer];
    [self dismissModalViewControllerAnimated:YES];
    //[player autorelease];
    //[player release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [moviePlayer release];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

@end

A: the problem is here
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];

try this:
videoURL = (NSURL*)[info objectForKey:@"UIImagePickerControllerMediaURL"];

and when you play video instead this
NSURL *videoURL = [NSURL URLWithString:@"public.movie"];
MPMoviePlayerController *moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL: videoURL];

moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
and movieplayer should be a property.
hope it helps.


text:
Q: Error when using my ccspriteframes class i wanted to have already loaded frames for my bullet sprites so I made a class that will hold all of the sprite frames. When I use this class it crashes. I could really use the help, thank you a lot.
.h
@interface loadedFrames : NSObject
{
    CCSpriteFrame *bullet0;
}
@property (nonatomic, retain) CCSpriteFrame *bullet0;
@end
@interface HelloWorldLayer : CCLayer <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>
{
    loadedFrames *frames;
}
@property (nonatomic, retain) loadedFrames *frames;

.m
@implementation loadedFrames : NSObject
@synthesize bullet0;
@end

- (void) loadSprites
{
      [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:
      [NSString stringWithFormat:@"clonespritesheet%d.plist", loadlevel]];

      self.frames.bullet0 = [[CCSpriteFrameCache sharedSpriteFrameCache]
               spriteFrameByName:@"bullet0.png"];
}

- (void) addBullet:(int)bulletType
{
      mainbullet = [bullet spriteWithSpriteFrame:frames.bullet0];
}

crashlog
2013-04-01 01:45:42.596 test[15111:907] *** Assertion failure in -[bullet initWithSpriteFrame:], /Users/Fei/Desktop/test/libs/cocos2d/CCSprite.m:212
(lldb)


text:
Q: save some data in mysql on my server by curl I want to save some data in mysql on my server by curl, my code is something like this
my curl
  function  verify_data_on_server
   ($user_id,$user_name,$user_code,$user_type,$user_url,$ user_email)

 {

 $ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://myurl.com/apis/verified_user.php");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query(array('user_id' => $user_id,'user_name' => $user_name,'user_code' => $user_code,'user_type' => $user_type,'user_url' => $user_url,'user_email' => $user_email)));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
  if ($server_output == "status") { echo "done"; } else { echo "fail!";}
 }  ?>

but data not save . please guide me where im wrong ?
I want to save some data in mysql on my server by curl, I tried a lot but didn't get any success

A: what do you mean?
you can't save data by cURl, you can send requests by cURL.
but I suppose that you want to send a request to your server by cURL and store some data within cURL request.
so you need a function or code or stuff for getting some data from requests and storing data in the database.
you can get all data within requests by $_REQUEST
example
$user_id=$_REQUEST['user_id'];
$user_name=$_REQUEST['user_name'];

and stuff ...
then you can store these data in your database.


text:
Q: C# How to make a standalone version of windows app with SQL Server database? So I got this windows app in C# which displays FAQ. All the data are stored in SQL Server. I used an ADO.NET Entity Data Model to build connection between my app and the database. Now the app is finished and I don't know how to make it standalone.
I need the app to run even if the PC where I'll copy the app doesn't have SQL Server. I tried to copy the .mdf file to bin/debug folder and make some changes to app.config but it doesn't work or maybe I just don't know the proper way to change app.config connection string because it is auto generated by the ADO.NET Entity Data Model. I'm an intern and this is my requirement to pass. please help
Here's the current app.config connection config:
<connectionStrings>
    <add name="dbFAQEntities"
         connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-CK86A2B;initial catalog=dbFAQ;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
         providerName="System.Data.EntityClient" />
    <add name="dbFAQEntities1"
         connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=DESKTOP-CK86A2B;initial catalog=dbFAQ;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
         providerName="System.Data.EntityClient" />
</connectionStrings>

A: If I understand your question correctly you want to make the app run on PCs which does NOT have Sql Server installed.
A simple answer: You cannot
It is just like asking to make .mp3 files stand alone without a player.


text:
Q: Not sure why I am recieving an Auth0 invalid grant Error when exchanging my authentication code for an access token I am building a server application using NestJs, I am 'faking' the client side user authentification by running 2 apps in my nest application, one for auth0 to attach login and logout routes to, and one for the actual server application.
When I try to use the access code returned from the user authentification (this is taken from the network park of dev tools, where I am getting a 301 response with a code and state) and have it request an access token from my API im getting this error
{"error":"invalid_grant","error_description":"Invalid authorization code"}%
I have been stuck on this for about half a day and cant seem to figure out whats going wrong.
this is the request im using to get the access token:
`curl --request POST \
\--url 'https://\<domain_name\>.eu.auth0.com/oauth/token' \
\--header 'content-type: application/x-www-form-urlencoded' \
\--data grant_type=authorization_code \
\--data 'client_id= {My client ID}' \
\--data 'client_secret={My client secret}' \
\--data 'code={code returned from authenticating user}' \\
\--data 'redirect_uri=http://localhost:8080/callback'

{"error":"invalid_grant","error_description":"Invalid authorization code"}%`
I have checked and my client ID and secret is the same in my auth0 config for my client auth set up, so is my callback URL, im really lost here!
(im using an express app and converter in my main.js for the client side)
expressApp.use(
    auth({
    secret: process.env.SECRET_SESSION,
    clientSecret: process.env.AUTH0_APP_CLIENT_SECRET,
    authRequired: false,
    auth0Logout: true,
    baseURL: 'http://localhost:8080',
    clientID: process.env.AUTH0_APP_CLIENTID,
    issuerBaseURL: process.env.AUTH0_ISSUER_URL,
    authorizationParams: {
    response_type: 'code',
    audience: process.env.AUTH0_AUDIANCE,
    },
   }),
);

If anyone has any advice it would be extremely appriciated <3


text:
Q: question involving $\ell^p$ spaces I would like to prove the following:

I am not asking for a solution! I would simply like a bit of guidance, I can't seem to get started on this problem. Would the proof involve using weak convergence? Perhaps there is a useful theorem for this I can't recall off the top of my head. Any help is greatly appreciated.

A: (b) $\Rightarrow$ (a): you can use Young's inequality to obtain
$$
f_n(x_n) \le \|f_n\|_{X^*}\|x_n\|_X \le  \frac1q\|f_n\|_{X^*}^q + \frac1p \|x\|_X^p.
$$
(a) $\Rightarrow$ (b): Construct a sequence $x_n$ to be suitable multiples of elements $z_n\in X$ that satisfy $f_n(z_n)=\|f_n\|_{X^*}$, $\|z_n\|_X=1$.
Set $x_n=t_nz_n$, $t_n\in \mathbb R$, choose $t_n$ such that $\sum_{n=1}^\infty f_n(x_n)<\infty$, by using the convergence of $\sum_{n=1}^\infty \|f_n\|^q$. Then prove convergence of $\sum_{n=1}^\infty \|x_n\|_X^p$ using that $\frac1p+\frac1q=1$.
No weak convergence, just playing with series and inequalities in $l^p$-norms.
Hope this helps.


text:
Q: Backup solo directorios Actualmente en nuestra empresa tenemos un servidor linux en el cual se crean diariamente diferentes carpetas y necesitamos que guarde solo la estructura de las carpetas sin la información.

A: Con un programa (opción cómoda)
Instalas tree (apt-get install tree en caso de que sea un sistema que maneja dpkg).
Ejecutas tree -da /home/hamza/directorio-master > tuarchivo.txt, cambiando /home/hamza/directorio-master por tu directorio (el que quieres analizar y ver que sub-directorios tiene), también cambias tuarchivo.txt por el archivo en el que quieras guardar el resultado.
Opciones:
-d = solo lista los directorios
-a = lista los directorios (u archivos) ocultos
Resultado:

Sin un programa (opción eficiente)
Ejecutas find /home/hamza/directorio-master type -d > tuarchivo.txt, cambiando /home/hamza/directorio-master por tu directorio (el que quieres analizar y ver que sub-directorios tiene), también cambias tuarchivo.txt por el archivo en el que quieras guardar el resultado.
Opciones:
-d = solo busca los directorios
Resultado:


text:
Q: GridView Custom Paging - First, Last, Next, Previous,Numeric I am using a sql store procedure for custom paging.
Now i want to make a custom pager for gridview.
I have searched on google and find various articles about it.
But i am not getting which i want.
please help me for it if you have any idea about it.
Thanks,
Rajbir

A: I think you looking for something like this
<ItemTemplate>
    <asp:LinkButton ID="lnkPage" runat="server" Text = '<%#Eval("Text") %>' CommandArgument = '<%# Eval("Value") %>' Enabled = '<%# Eval("Enabled") %>' OnClick = "Page_Changed"></asp:LinkButton>
</ItemTemplate>

You will find more form Custom Paging in ASP.Net GridView using SQL Server Stored Procedure

A: there is nothing to do with Stored Procedure to use Paging in Gridview. Only you need to do is to bind your GridView on OnPageIndexChanging event.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
  GridView1.PageIndex = e.NewPageIndex;
}

Please visit this link for example: ASP.NET GridView with Custom Paging UI


text:
Q: List becomes empty After query.closeall methodin jdo public static List<FieldOption>
getFieldOptionListOfField(PersistenceManager pm, long fieldId) throws NoSuchFieldOptionException {
    Query query = pm.newQuery(FieldOption.class);

    try {
        query.setFilter("this.fieldId == fieldId");
        query.declareParameters("long fieldId");
        query.setOrdering("orderId ascending");
        List<FieldOption> fieldOptions = (List<FieldOption>) query.execute(fieldId);
        logger.debug("fieldOptions = " + fieldOptions);
        return fieldOptions();
    } finally {
        query.closeAll();
    }
}

After execution of excute method 'fieldOptions' is having certain values. But after closeAll() the list becomes empty. Can you please suggest why it happens?

A: The "List" returned after you end a transaction and close a PM is not a real List, but instead a lazy load list, that cannot lazy load once it has no connection to the datastore. Easiest option is put (copy) the query results into your own List before closing the txn/PM.


text:
Q: Dynamic class declare and instantiate? Is it possible in java to declare and instantiate a class at runtime?
I am attempting following code:
    public static void t4() {
    Object o = new Object() {
        private String uid = "1";
        private String name = "2";

        public String getName() {
            return name;
        }

        public String getUid() {
            return uid;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setUid(String uid) {
            this.uid = uid;
        }

        @Override
        public String toString() {
            return uid + " " + name;
        }
    };

But, I would want this to happen using reflection, cause i will be injecting attributes into pojo from xml source.
Any more thoughts?

A: It is possible upto some degree to dynamically compile a class using the JDK6.0's Java Compiler API from a String object(holding the code).
http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm refer here.
The code also shows you how to dynamically instantiate that "newly compiled" class from a class file(using Class.forName()) method.

A: Well there are answers all over the internet for this...
here you go with one
What is the difference between "Class.forName()" and "Class.forName().newInstance()"?
The answer of above post demonstrates how to create a new instance on run time.


text:
Q: blocked by software restriction policies? Alguem ja se deparou com esta mensagem ao abrir o Visual Sdudio??

\packages\EntityFramework.5.0.0\tools\init.ps1
  cannot be loaded because its operation is blocked by software restriction policies, such as those created by using Group Policy.
  At line:1 char:45
  + $__pc_args=@(); $input|%{$__pc_args+=$_}; & 'D:\Fontes\Projetos Particulares\Vis ...
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : SecurityError: (:) [], PSSecurityException
      + FullyQualifiedErrorId : UnauthorizedAccess

Poderia me ajudar a solucionar isso?

A: No Package Manager Console, digite o seguinte:
PM> Set-ExecutionPolicy Unrestricted

Não há problemas em reduzir a política de restrição de scripts em uma máquina de desenvolvimento.
Se não funcionar de primeira, experimente executar o Visual Studio como administrador e tente novamente.
Além disso, se não for uma restrição de projeto, é até melhor atualizar o Entity Framework. A versão 6 não tem essa restrição.

A: No meu caso este problema ocorreu porque havia um certificado da Microsoft com problema. Para resolver vá em Internet Options => Content => Certificates  na aba Untrusted Publishers e remova Microsoft Corporation.
https://github.com/NuGet/Home/issues/7158


text:
Q: Initialize a stand-alone service class The context here is that i have a task to write unit test for that service.
Supposedly, i have a win32 service class.
Like this class TestService(win32serviceutil.ServiceFramework).
Is there any way to create an instance of this class without using servicemanager ?
Thank you


text:
Q: Remove codesign from iOS framework I have build an iOS framework and it is working fine with adhoc and development profiles but appStore submission is getting failed due to codesign errors. Is there any command like:

lipo -remove codesign

to remove codesign from my Framework? Thanks in advance.

A: If anyone still face this issue then following was my solution:

*

*Build 1st framework for device and 2nd framework for simulator

*Strip off the simulator slices of 2nd framework by using lipo -info to see the simulator architecture, then remove them using commands
lipo -remove x86_64 MyFrameWork -o MyFrameWork
lipo -remove i386 MyFrameWork -o MyFrameWork

*Remove the codesign of 1st framework by following step 2

*Use lipo to create universal iOS framework from previous both framework. this universal framework can be used in the project which will be codesign under that project and no issue in submitting to the AppStore.


text:
Q: A postapocalyptic comic in the US published in the 80's? I can't remember the name of a Comic book series that I read in the middle to late 80's.
The books were about two young men/boys after an apocalyptic event in the US where society was broken down and it was a kind of "Wild west". A little more structure in society than what we see in the "Book of Eli" but a lot of lawlessness.
One of the boys is the son of a farmer and his parents are killed and he is on his own.
In the first book, he meets up with a ruthless selfish streetsmart boy his own age, and they stick together.
In every one of the books they end up fighting some evil, while never setting out to be heroes. Totally western style, but a little darker. I remember 5 or 6 books ... It was not a long series.
The drawing style is not DC or Marvel, but more like the detailed dirty scenes of something like Blueberry. I don't know if it is from a European or a US company.
I have been googling for a couple weeks now, and at my local library unable to find them. Can anyone remember the name from my description?

A: What you write reminds me of the Jeremiah comic books. It has been about 25 years ago, that I have read one of them, so my memory might play tricks on me.
Wikipedia page

Racial wars have torn the U.S. apart, resulting in a post-apocalyptic world. Many small pockets of civilization still exist; from isolated super high-tech fortresses, hidden research labs, or racial groups in walled-in cities — all fighting each other among the more regular population which in many ways resembles the "old west".
Jeremiah and his friend Kurdy travel the country, taking odd jobs and getting mixed up in various affairs. Jeremiah, being the more noble of the two, often sticks his neck out to help others, while Kurdy is a more wily, opportunistic scoundrel.
Despite its setting, Jeremiah's underlying motif is of hope and the survival of mankind. The storylines carry little from album to album, meaning they can be read individually.

Author's page (in french)


text:
Q: How do i remove the dots in a php directory I have a code that shows dots in the directory. I'm trying to get rid of them but google doesn't help, those dots mean back and localhost and the dots need to be removed how do i do this?
<?php
 $map = opendir('file');
 while ($bestand = readdir($map))
 {
   echo "$bestand
";
 }
 closedir($map);
?>

those dots

A: add
if ($bestand == '.' || $bestand == '..')
    continue;

before the line contains echo
This code will skip iteration whenever $bestand is the dots.

A: add
if(is_dir($bestand)){ continue; }

in the loop.
This will skip all directories and only add files.

A: Referring to the manual at php.net and adding to HungHsuan Wei's answer.
<?php

if ($map = opendir('file')) {

    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($map))) {
        if($bestand == '.' || $bestand == '..')
        continue;
    }
    closedir($handle);
}


text:
Q: What is an elegant way to convert the result of [x for x in y] from list to a regular variable? What is an elegant way to convert the result of [x for x in y] from list to a regular variable?
result= [x for x in range(10) if x==7]

The result of the above will be [7].
I am now using result=result[0] but ...it does not look right :-)
thanks

A: You can use next that retrieves the next object from the iterator. The parameter that goes within next is a generator. This allows saves you from fully constructing the list and then filtering for 7. Instead it only iterates until it hits 7, and wont evaluate until the next next(..) is called on the generator object.
>>> next(x for x in range(10) if x==7)
7

A: You have a list comprehension on the right hand side. It evaluates to a list.
You want to pick up the first element (which is perhaps the only element for the kind of problems you are trying to solve) from it, so index the 0-th element in the list returned by the list comprehension, just like you would do it for a regular list.
result = [x for x in range(10) if x == 7][0]

You can also use a generator expression instead of a list expression and then call the next() function to retrieve the first item from the iterator returned by the generator expression.
result = next(x for x in range(10) if x == 7)


text:
Q: Different definitions of the $E^{\infty}$ page of a spectral sequence. In Lecture Notes in Algebraic Topology by Davis and Kirk it seems that given a (convergent, bigraded) spectral sequence $(E^r, d^r)$ one defines the $E^{\infty}$-page as $$E^r_{p, q} = \operatorname{colim}_{r \to \infty}E^r_{p, q}.$$
However it seems that the convention (at least by books such as Weibel's: An Introduction to Homological Algebra and Rotman's An Introduction to Homological Algebra) is that for any (bigraded) spectral sequence $(E^r, d^r)$, one defines $E^{\infty}_{p, q}$ in the following way. Suppose that $d^r$ has bidegree $(a, b)$, then we define $B^r_{p, q} = \operatorname{im} d^r_{p-a, q-b} : E^r_{p-a, q-b} \to E^r_{p, q}$ and $Z^r_{p, q} = \operatorname{ker} d^r_{p, q} : E^r_{p, q} \to E^r_{p+a, q+b}$ so that $$E^{r+1}_{p, q} = Z^r_{p, q} / B^r_{p, q}.$$
Then one defines $$E^{\infty}_{p, q} = \frac{\bigcap_r Z^r_{p, q}}{\bigcup_r B^r_{p, q}}.$$
Now at some point in Lecture Notes in Algebraic Topology by Davis and Kirk it seems that implicitly it is the case that $$E^{\infty}_{p, q} = \bigcap_{r}E^r_{p, q}$$ as in one of the proofs it is stated that $E^{\infty}_{n, 0} = \bigcap_r E^r_{n, 0}$, which leads me to guess that the above holds.
More confusingly still, it seems that in an earlier version of Lecture Notes in Algebraic Topology by Davis and Kirk, the $E^{\infty}$-page was defined as $$E^{\infty}_{p, q} = \lim_{r \to \infty} E^r_{p, q}$$ as indicated by this question here on Math.StackExchange: definition of convergence of a spectral sequence

So it seems that there are possibly four ways of defining the $E^{\infty}$ page of spectral sequence, in what ways are these equivalent? Do they agree for convergent spectral sequences?
Also I don't see how the authors could swap out taking a colimit for a direct limit as categorically speaking those should be dual notions.
Also I'd like to mention that I am inferring a lot from the text, I'm sure that it is due to a misinterpretation on my part, (and not the authors) that I've claimed something incorrect to hold.


text:
Q: Nonblocking sockets even if not explicitly setting them as nonblocking I have a TCP application written in C++, where a client and a server exchange data. I've istantiated a socket, believing that it would have been blocking by default; on the contrary, after server waits for a client, I have that client calls the recv function without waiting for data. This is the code in which I inizialize the socket fr the client.
int TCPreceiver::initialize(char* address, int port)
{
    sock = socket (AF_INET, SOCK_STREAM, 0);
    cout << "Socket: " << sock << endl;
    sockaddr_in target;
    target.sin_family = AF_INET;
    target.sin_port = htons (port);
    target.sin_addr.s_addr = inet_addr(address);

    int fails=0;
    while (connect(sock, (sockaddr*) &target, sizeof(target)) == -1)
    {
        fails++;
        if (fails==10)
        {
            close(sock);
            cout << "Error with connection to the server, try again"<< endl;
            exit(-1);
        }
    }

    cout << "Client connected (control channel)" << endl;

    unsigned char text[10]; //Request message
    //fill text[]
    if(send(sock, (char*)text, 10, 0)==-1)
    {
            printf("send() failed with error code : %d" , -1);
            exit(EXIT_FAILURE);
    }

    return 0;
}

I've tried adding this code:
int opts;
opts = fcntl(sock,F_GETFL);
if (opts < 0) {
    perror("fcntl(F_GETFL)");
    exit(0);
}
opts = (opts & (~O_NONBLOCK));
if (fcntl(sock,F_SETFL,opts) < 0) {
    perror("fcntl(F_SETFL)");
    exit(0);
}

but it still doesn't work, and if I call the recv(), the application doesn't block (and recv() always returns 0). Here is the function where I call the recv():
void TCPreceiver::receive(char* text, int& dim)
{
    int ret;

    ret = recv(sock, text, dim, 0);
    dim=ret;
    if(ret == -1){
        printf("recv() failed with error (%d)\n", ret);
        //system("PAUSE");
        exit(1);
    }
}

Where am I wrong?

A: recv() returning zero indicates either (1) you passed a zero length, which is just a programming error which I won't discuss further here, or (2) end of stream. The peer has close the connection. This isn't a non-blocking situation, this is the end of the connection. You must close the socket and stop using it. It will never return anything. It zero ever again.
See the man pages.


text:
Q: How to dynamically allocate memory without affecting other data allocated dynamically? Im implementing a card game using C, here's my code:
deck.h:
#ifndef DECK_H
    #define DECK_H
    #define S_NUM 4
    #define V_NUM 12
    #define S_MAXLEN 9
    #define V_MAXLEN 6
    #define OFLEN 5

    typedef char deck_t
        [S_NUM * V_NUM]
            [S_MAXLEN + V_MAXLEN + OFLEN];

    typedef struct {
        deck_t *hand;
        deck_t *remaining_cards;
    } dealed_deck_t;

    deck_t *new_deck(void);
    void print_deck(const deck_t *);
    dealed_deck_t deal(const deck_t *, int);
    void free_deck(const deck_t *);

    static void deckcpy(const deck_t *const, deck_t *, int);

#endif

deck.c:
#include "deck.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

deck_t *new_deck() {
    int i, j, k;
    deck_t *cards = calloc(1, sizeof(deck_t));
    char suits[S_NUM][S_MAXLEN] = {
        "Spades", "Diamonds",
        "Hearts", "Clubs"
    };
    char values[V_NUM][V_MAXLEN] = {
        "Ace", "Two", "Three",
        "Four", "Five", "Six",
        "Seven", "Eight", "Nine",
        "Jack", "Queen", "King"
    };
    for (i = 0; i < S_NUM * V_NUM; ++i) {
        memset(*cards[i], 0, strlen(*cards[i]));
    }
    for (i = 0, j = 0; i < S_NUM; ++i) {
        for (k = 0; k < V_NUM; ++k, ++j) {
            strcat(*cards[j], values[k]);
            strcat(*cards[j], " of ");
            strcat(*cards[j], suits[i]);
        }
    }
    return cards;
}

void print_deck(const deck_t *deck) {
    for (int i = 0; i < S_NUM * V_NUM && strlen(*deck[i]); ++i) {
        printf("%s\n", *deck[i]);
    }
}

dealed_deck_t deal(const deck_t *deck, int handsize) {
    int i, j;
    dealed_deck_t dealed_deck;
    dealed_deck.hand = calloc(1, sizeof(deck_t));
    dealed_deck.remaining_cards = calloc(1, sizeof(deck_t));

    // print_deck(deck);

    return dealed_deck;
}

void free_deck(const deck_t *deck) {
    free((void *)deck);
}

static void deckcpy(const deck_t *const deck, deck_t *dest, int handsize) {
    for (int i = 0; i < handsize; ++i) {
        char temp[strlen(*deck[i])];
        for (int j = 0; j < strlen(*deck[i]); ++j) {
            temp[j] = (*deck[i])[j];
            temp[j] = '\0';
        }
        for (int j = 0; j < strlen(temp); ++j) {
            (*dest[i])[j] = temp[j];
            (*dest[i])[j] = '\0';
        }
    }
}

main.c:
#include "deck.h"

int main() {
    deck_t *cards = new_deck();
    deck_t *hand = deal(cards, 6).hand;
    // print_deck(cards);
    free_deck(cards);
    return 0;
}

the problem is deck.c in the deal function.
when I allocate memory for dealed_deck.hand and dealed_deck.remaining_cards the data pointed to by the parameter deck is affected and changed, so when I comment the two lines:
dealed_deck.hand = calloc(1, sizeof(deck_t)); and dealed_deck.remaining_cards = calloc(1, sizeof(deck_t));, the data is the same, when I uncomment the data change a bit.
I'm using calloc here because when I used malloc the data pointed to by dealed_deck.hand and dealed_deck.remaining_cards was the same as the data pointed to by deck,  but when I used calloc they were empty as I want.
I need a way to allocate memory without messing the memory and data I allocated before, how to do that?
I'm compiling using a MacOS and gcc.
thanks.

A: The line memset(*cards[i], 0, strlen(*cards[i])); is wrong. First, cards was allocated with calloc, so it is filled with zero bytes, which act as empty strings. So, if *cards[i] pointed to something in cards, strlen returns zero, and memset sets zero bytes to zero.
Unfortunately, *cards[i] is valid only when i is zero. Since cards is a pointer to a deck_t, cards[0] is the first deck_t, which is an array of array of char. As an array, it is automatically converted to a pointer to its first, element, an array of char. Then *cards[0] is that array of char. As an array, it is automatically converted to a pointer to its first element, which is passed to strlen. However, when i is one (or greater), cards[i] would be the second (or greater) deck_t. But space for only one deck_t was allocated. So *cards[i] is invalid; it attempts to access space that was not allocated.
Since this line is not needed (due to calloc), remove it and the loop it is in.
In strcat(*cards[j], the same problem exists—*cards[j] is valid only when j is zero. A correct expression is (*cards)[j].
In (*cards)[j], cards is a pointer to a deck_t, so (*cards) is a deck_t, which is an array of array of char. Then (*cards)[j] is element j of that array, so it is an array of char.
Similarly, in print_deck, change *deck[i] to (*deck)[i].
(The code can be changed so that deck[i] can be used instead of (*deck)[i] by changing the type of deck to char (*MyType)[S_MAXLEN + V_MAXLEN + OFLEN]. However, you may wish to make the above changes first and understand them before changing types.)


text:
Q: Or statement & conditions dictating execution of one of two or three for loops Here is my data within Cells E1:G14
Issue Name                      Ticker
F/c 90day euro$ futr  dec15  Edz5 xcme
F/c h-shares idx fut  jul15     Hcn5 xhkf
F/c mini msci emg mkt sep15     Mesu5ifus
F/c s&p/tsx 60 ix fut sep15     Ptu5 xmod
F/c russell 2000 mini sep15     Rtau5ifus
F/c swiss mkt ix futr sep15     Smu5 xeur
F/c us 10yr note(cbt) sep15     Tyu5 xcbt
F/c euro buxl 30y bnd sep15     Ubu5 xeur
F/c euro stoxx 50     sep15     Vgu5 xeur
F/c us ultra bond(cbt sep15     Wnu5 xcbt
F/c gasoline rbob fut sep15     Xbu5 xnym
F/c aust 10yr bond fut sep 15   Xmu5 xsfe
F/c ftse 100 idx fut  sep15     Z u5 ifll

And my code as of right now:
Sub copy_paste()

Worksheets(1).Activate
Dim ch As Long
Dim c As Variant
Dim d As Variant
Dim v As Range
Dim w As Range
Dim brow As Long
Dim crow As Long
Dim cc As Variant

Set w = Sheets(1).Range("E:E")
brow = w(w.Cells.Count).End(xlUp).Row
Set w = Range(w(2), w(brow))

Set v = Sheets(1).Range("G:G")
brow = v(v.Cells.Count).End(xlUp).Row
Set v = Range(v(2), v(brow))

    For Each d In w
        d = d.Text
        If InStr(1, d, "mini") Then
                For Each c In v
                bbv1 = " QR "
                bbv2 = " HCPI "
                c = Mid(c, 1, 5) & " <INDEX>" & bbv2 '& c.Offset(0, 3)
                Debug.Print (c)
            Next c
        End If
Next d
End Sub

My out put from this half of my code is as follows:
Edz5  <INDEX> HCPI
Hcn5  <INDEX> HCPI
Mesu5 <INDEX> HCPI
Ptu5  <INDEX> HCPI
Rtau5 <INDEX> HCPI
Smu5  <INDEX> HCPI
Tyu5  <INDEX> HCPI
Ubu5  <INDEX> HCPI
Vgu5  <INDEX> HCPI
Wnu5  <INDEX> HCPI
Xbu5  <INDEX> HCPI
Xmu5  <INDEX> HCPI
Z u5  <INDEX> HCPI
Edz5  <INDEX> HCPI
Hcn5  <INDEX> HCPI
Mesu5 <INDEX> HCPI
Ptu5  <INDEX> HCPI
Rtau5 <INDEX> HCPI
Smu5  <INDEX> HCPI
Tyu5  <INDEX> HCPI
Ubu5  <INDEX> HCPI
Vgu5  <INDEX> HCPI
Wnu5  <INDEX> HCPI
Xbu5  <INDEX> HCPI
Xmu5  <INDEX> HCPI
Z u5  <INDEX> HCPI

The procedure cycles through each Issue name, two of which meet the mini criteria and thus are printed to the immediate console in the desired format. Now I would like to execute another for loop identical to the one above except handling a different criteria: ix instead of mini and if any Issue name meets neither of these criteria I would like an Elseif statement to handle the remaining issue names.
If InStr(1, d, "ix") Then
    For Each c In v
        bbv1 = " QR "
        bbv2 = " HCPI "
        c = Mid(c, 1, 4) & " <INDEX>" & bbv2 & c.Offset(0, 3)
        Debug.Print (c)
        Next c
     End If

Elseif
            For Each c In v
            'ch = DDEInitiate("winblp", "bbk")
                bbv1 = " QR "
                bbv2 = " HCPI "
                c = Mid(c, 1, 5) & " <INDEX>" & bbv2 '& c.Offset(0, 3)
                Debug.Print (c)
            Next c
        End If
`The syntax may be wrong on the Elseif

Ergo any commodity future which does not represent and index should be printed as Xbu5 <CMDTY> HCPI how ever I have not been able to figure out how to switch for loops on these conditions. How could I incorporate an OR condition within the If InStr() method and eliminate one of the first two for loops?
The final desired results should be: (Please note the mini Indices have a c = Mid(c, 1, 5) condition)
Edz5 <CMDTY> HCPI
Hcn5 <INDEX> HCPI
Mesu5 <INDEX> HCPI
Ptu5 <INDEX> HCPI
Rtau5 <INDEX> HCPI
Smu5 <INDEX> HCPI
Tyu5 <CMDTY> HCPI
Ubu5 <CMDTY> HCPI
Vgu5 <CMDTY> HCPI
Wnu5 <CMDTY> HCPI
Xbu5 <CMDTY> HCPI
Xmu5 <CMDTY> HCPI
Z u5 <CMDTY> HCPI

A: Not sure I follow exactly, but I think you can resolve this by putting your Instr test inside the loop and doing conditional assignment to c, rather than trying to "switch" loops or otherwise build three different loops.
For Each d In w
    d = d.Text

    For Each c In v
        bbv1 = " QR "
        bbv2 = " HCPI "
        If InStr(1, d, "mini") Then
            c = Mid(c, 1, 5) & " <INDEX>" & bbv2 '& c.Offset(0, 3)
        ElseIf Instr(1, d, "ix") Then
            c = Mid(c, 1, 4) & " <INDEX>" & bbv2 & c.Offset(0, 3)
        Else
            c = Mid(c, 1, 5) & " <INDEX>" & bbv2
        End If
        Debug.Print (c)
    Next c

Next d


text:
Q: Android httpURLConnection already running I've got an app where in I was calling an httpURLConnection with the requestproperty connection "stay-alive".
Because I didn't call the HttpURLConnection.disconnect() when my app was crashing, he didn't make it to the disconnect call because I didn't put it in the finally method.
Problem
When I rerun my app, I see that my url.openConnection() already see the old HttpUrlConnection and take that back out of the pool. Problem now is that I can't simply kill the already existed connection.
After some research on the web I found an old bug report (https://code.google.com/p/android/issues/detail?id=2939)
I already tried different approaches, but after the url.openConnection() calling httpURLConnection.disconnect() didn't do anthing. Reinstall app, reboot pc and tablet also weren't effective.
Known exceptions

*

*java.lang.IllegalStateException: Already connected

Question
So my question is: How can I kill the existed HttpURLConnection?
Here a brief example of the wrong used code:
try{
        File file = new File("resources/test.png");
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlRequest);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();

        //Get Cookie from session
        String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
        String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();

        //allow inputs & outputs
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        //Enable GET method
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("User-Agent", "MyAgent");
        connection.setRequestProperty("Cookie", key+"="+value);

        //Call with stream fields
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;

        //Call with stream
        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
        /*outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""+ Configuration.userTempImage.getPath()+ "\""+lineEnd);
        outputStream.writeBytes(lineEnd);*/

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        //Read file
        bytesRead = fileInputStream.read(buffer, 0 , bufferSize);

        while(bytesRead > 0){
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        /*outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);*/

        // Responses from the server (code and message)
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();

        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
        String jsonText = readAll(rd);

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();

        System.out.print(serverResponseCode + " - " + serverResponseMessage+" -> ");
    } catch (Exception ex){
        System.out.print(ex.getMessage());
    }

And this is my updated code
private static String getImagePath(String urlRequest){
    System.setProperty("http.keepAlive", "false");

    // ?
    FileOutputStream fos = null;
    // The connection to the server
    HttpURLConnection connection = null;
    // The data steam for sending the file to the server
    DataOutputStream outputStream = null;
    // A file stream to read the local file.
    FileInputStream fileInputStream = null;
    // ?
    ByteArrayOutputStream stream = null;
    // Cropped image file
    File croppedImage = null;

    try{
        try{
            stream = new ByteArrayOutputStream();
            Configuration.userTempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            // Close the output-stream
            if(stream != null) { stream.close(); }

            croppedImage = new File(Environment.getExternalStorageDirectory(), "test.jpg");

            if(croppedImage.exists()){
                croppedImage.delete();
            }

            fos = new FileOutputStream(croppedImage);
            fos.write(byteArray);
        } catch (java.io.IOException e) {
            Log.e("PictureDemo", "Exception in photoCallback", e);
        } finally {
            if(fos != null) { fos.close(); }
        }

        //Get Cookie from session
        String key = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getName();
        String value = MyHttpClient.sharedInstance().getCookieStore().getCookies().get(0).getValue();

        URL url = new URL(urlRequest);
        connection = (HttpURLConnection)url.openConnection();

        //Allow inputs & outputs
        connection.setDoInput(true); // <-- Exception is thrown here
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        // Set connection properties
        connection.setRequestProperty("Cookie", key+"="+value);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("User-Agent", "MyAgent");

        // Set connection headers
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(10000);
        connection.setReadTimeout(10000);

        //Call with stream fields
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;

        // Create an input stream to the cropped image file
        fileInputStream = new FileInputStream(croppedImage);
        // Create an output stream to send the file to the server
        outputStream = new DataOutputStream(connection.getOutputStream());

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        //Read file
        bytesRead = fileInputStream.read(buffer, 0 , bufferSize);

        while(bytesRead > 0){
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // Be sure to send everything
        outputStream.flush();

        // Responses from the server (code and message)
        int serverResponseCode = connection.getResponseCode();
        String serverResponseMessage = connection.getResponseMessage();

        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
        String jsonText = RequestHelper.readAll(rd);

        return jsonText;
    }catch(Exception ex){
        ex.printStackTrace();
    } finally {
        try{
            if(fileInputStream != null) { fileInputStream.close(); }
            if(outputStream != null) { outputStream.close(); }
        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            if(connection != null) { connection.disconnect(); }
        }
    }

    return null;
}


text:
Q: Passing SQL data in codeigniter to highcharts with JSON I am having trouble passing SQL data from my controller to my view. I have verified the information shows up from my model. I don't know JSON very well but I'm trying to learn. My goal is to populate a chart with two fields that are just numbers into this highcharts javascript. Please help, thank you!
Controller
function dashboard() {

    // Tickets in Queue
    $query = $this->mhedash_model->maint_pending_tickets();
    $result3 = $query->result_array();

    $this->table->set_heading('Work Number', 'Vehicle Number','Submit Date','Submit Time');
    $data['table']['Vehicle in Queue']  = $this->table->generate_table($result3);

    // Active Tickets
    $query = $this->mhedash_model->select_active();
    $result = $query->result_array();

    $this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
    $data['table']['Vehicles Actively Being Worked On']  = $this->table->generate_table($result);

    // Tickets Waiting On Parts
    $query = $this->mhedash_model->select_pending_parts();
    $result2 = $query->result_array();

    $this->table->set_heading('Service Number','Start Date','Mechanic','Vehicle Number','Description','Type');
    $data['table']['Waiting For Parts']  = $this->table->generate_table($result2);

    //Graph - Availble Highreaches
    $query = $this->mhedash_model->graph_available_hr();
    $result4 = $query->result_array();
    $data['row']['']  = $this->table->generate_table($result4);

    $query = $this->mhedash_model->graph_available_dt();
    $result5 = $query->result_array();
    $data['row']['']  = $this->table->generate_table($result5);

    $series_data[] = array('name' => 'available', 'data' => (int)$result4);
    $series_data[] = array('name' => 'not_available', 'data' => (int)$result5);
    $this->view_data['series_data'] = json_encode($series_data, JSON_NUMERIC_CHECK);

    // Load view
    $data['page_title'] = 'MHE Dashboard';
    $data['main_content'] = 'mhe/mhe_dashboard_view';
    $data['array'] = $result;
    $data['array2'] = $result2;
    $data['array3'] = $result3;

    print json_encode($series_data);
    //echo json_encode($series_data, JSON_NUMERIC_CHECK);

    return $this->load->view('includes/template',$data);

}

View that has the highcharts javascript
var chart;
$(function () {

  $('#container').highcharts({
    chart: {
        type: 'column'
    },
    xAxis: {
        categories: ['one', 'two']
    },
    plotOptions: {
        series: {
            allowPointSelect: true
        }
    },
    series: [{
        data: [<?php echo join($series_data, ',') ?>]
    }]
});

// the button action
$('#button').click(function () {
    var chart = $('#container').highcharts(),
        selectedPoints = chart.getSelectedPoints();

    if (chart.lbl) {
        chart.lbl.destroy();
    }
    chart.lbl = chart.renderer.label('You selected ' + selectedPoints.length + ' points', 100, 60)
        .attr({
            padding: 10,
            r: 5,
            fill: Highcharts.getOptions().colors[1],
            zIndex: 5
        })
        .css({
            color: 'white'
        })
        .add();
});
});
        </script>

Also, this is what prints when I print son_encode for my $series_data
[{"name":"available","data":1},{"name":"not_available","data":1}]


text:
Q: What does handle_data() return? I tried to get a list of only meaningful context from a webpage (there are only two lines of webpage content in my test code) using handle_data() from html.parser, but got multiple lists which are not in a list. I don't understand what does handle_data() returns. Anybody can help me with it? How can I store them in only one list?
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_data(self, data):
        a = []
        for i in data.split():
            a.append(i)
        print(a)
        return a

parser = MyHTMLParser()
parser.feed('<title>Test</title>
Parse me!
')

Result:
    ['Test']
    ['Parse', 'me!']

A: the handle_data method from HTMLparser is called every time the parser found a text/content inside html tag.
In your case, handle_data will be called two times. In the first call, the variable data is equal to 'Test', and the second call will be 'Parse me!'.
If you want to store all of the text/content inside one list, then just create a variable inside your class.
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):
    a = []

    def handle_data(self, data):
        self.a.append(data)

parser = MyHTMLParser()
parser.feed('<title>Test</title>
Parse me!
')

print(parser.a) # ['Test', 'Parse me!']

A: As I know http.parser is low level module which can help to parse HTML but it returns nothing. You have to decide what to do with data. You can print it or put in some variable or create tree, etc. But this need to write all code which will return anything.
For example I create class variable result to keep all strings which I get in handle_data and later I can get all text from this variable.
from html.parser import HTMLParser

class MyHTMLParser(HTMLParser):

    result = []

    def handle_data(self, data):
        self.result.append(data)

parser = MyHTMLParser()
parser.feed('<title>Test</title>
Parse me!
')
print(parser.result)


text:
Q: How to put Expandable list view inside scroll view in flutter? Hello there i am making a flutter application in which inside ScrollView in need to put Expandable list view.First of all here is my build method.
  return Scaffold(
    appBar: AppBar(
      backgroundColor: app_color,
      iconTheme: IconThemeData(
        color: Colors.white, //change your color here
      )),
    //debugShowCheckedModeBanner: false,
    //key: scaffoldKey,
    backgroundColor: app_color,
  body: SingleChildScrollView(
    child: Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children:<Widget>[
          Text("Header"),
          new ListView.builder(
            itemCount: datas.length,
            shrinkWrap: true,
            itemBuilder: (context, i) {
              return new ExpansionTile(
                title: new Text(datas[i].title, style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold,                                 fontStyle: FontStyle.italic),),
                children: <Widget>[
                  new Column(
                    children: _buildExpandableContent(datas[i]),
                  ),
                ],
              );
            },
          ),
          Text("Footer"),
        ],
      ),
    )
  )

);
  }

Now the problem is that without SingleScrollChidView this works fine But after using SingleScrollChidView it does not shows anything and gives error RenderBox was not laid out.What is wrong here ? How can i use Expandable list view inside Singlechildscroll view in flutter.

A: I was able to achieve Expanded ListView within ScrollView with text by
- Use of Wrap inside SingleChildScrollView, provided you make all ListView using shrinkWrap: true
SingleChildScrollView(
      child: Wrap(
        direction: Axis.horizontal,
        children: <Widget>[
          _textBody, // text body, with 1000+ words
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Column(
              children: <Widget>[
                ListViewOne(_genericListDataOne()),
              ],
            ),
          ),
          Column(
            children: <Widget>[
              ListViewTwo(_genericListDataTwo())
            ],
          )
        ],
  ),
    ),

part of the Code for ListViewOne
 ListViewOne(
  shrinkWrap: true,
  padding: new EdgeInsets.symmetric(vertical: 8.0),
  children: // build list here,
);

A: Give your ListView a fixed height using SizedBox or similar
SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Text("Header"),// tested with 20 of these for scrolling
            SizedBox(
              height: MediaQuery.of(context).size.height / 2,
              child: new ListView.builder(
                itemCount: 20,
                shrinkWrap: true,
                itemBuilder: (context, i) {
                  return new ExpansionTile(/* whatever */ );
                },
              ),
            ),
            Text("Footer"),// tested with 20 of these for scrolling
          ],
        ),
      )

A: Use SizedBox.expand for this problem,
SizedBox.expand(
child : ListView.builder(
            itemCount: datas.length,
            shrinkWrap: true,
            itemBuilder: (context, i) {
              return new ExpansionTile(
                title: new Text(datas[i].title, style: new TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold,                                 fontStyle: FontStyle.italic),),
                children: <Widget>[
                  new Column(
                    children: _buildExpandableContent(datas[i]),
                  ),
                ],
              );
            },
          ),
);

A: Edited answer
Try this, you should get the desired output you are looking for.
You can find the output here.
Column(
  children: <Widget>[
     Text(),
     ListView(
       shrinkWrap: true,
       physics: ScrollPhysics(),
       children:[]),
     Text()
   ]
 )

adding below shown code in ListView will allow smooth scrolling of widget
 shrinkWrap: true,
 physics: ScrollPhysics(),


text:
Q: Nginx setting server gives installation page I'm trying to set up Nginx for the first time and in following a tutorial I have come to the point that I'm getting the Welcome page to Nginx. I removed the last two includes in the /etc/nginx/nginx.conf file and added the following code. However, no matter how many times I attempt to move things around I get only the welcome page and not the page in my htdocs directory.
I'm sure that I'm missing something simple, but any pointers would be appreciated.
server {
                listen          80;
                server_name     domain.com;
                root            /var/www/domain.com/htdocs;
                location ~ \.php$ {
                        try_files $uri =404;
                        fastcgi_pass unix:/var/run/php5-fpm.sock;
                        index index.html index.php;
                }
        }

A: From your comments it sounds like you are running two copies of nginx. Here's how you can troubleshoot:
service nginx stop
ps auxwww|grep nginx  # is it still running?

Once you have successfully stopped nginx, try checking locally using curl instead of using Chrome or Safari. This will bypass any caches/proxies and give you a better low level insight into what's going on. Let's say the public IP of your server is 1.2.3.4. Then on the same server running nginx you'd do something like this and check the output:
curl -XGET http://1.2.3.4:80
curl -XGET http://1.2.3.4:80/test.html

Now you have some data and you can do some deductions.
Case A
You still get the nginx welcome page even that you stopped the service and killed any lingering processes by hand. You're likely working on the wrong server or the IP isn't routing the way you expect. Maybe it's connected to a CDN like CloudFlare which shows the last retrieved page even when the server is down.
Try accessing the page through localhost to confirm:
curl -XGET http://127.0.0.1:80

Case B
You had to kill nginx by hand, but once you did the server did stop responding. In this case something is wrong with your service definition of nginx or something is starting it in a different way (supervisord, manual rc.local thing). The wrong settings files might be used as well.
Figure out what's starting nginx and get rid of it, then use your package manager to reinstall nginx with normal startup scripts.
Case C
Stopping the service did work, curl did not get a response after you did. In this case your testing with Chrome/Safari was likely affected by some caching or local proxy.
Start the service again and now use curl to test with until you get the configuration file right.


text:
Q: Accessing localhost not possible on MacOS my situation is that the website I'm building has a landing page the main App page and the API section. They are respectively reachable with [domain_name], app.[domain_name] and api.[domain_name]. When calling those I don't have any problems reaching them in any browser. When I host them however in my local environment then api.localhost does only work when I call it with Postman.
When I try to ping the api.localhost it only says:
ping: cannot resolve api.localhost: Unknown host

On other systems, this will get a response.
In terms of Django Cors stuff, it all seems to be managed correctly as it is working on other systems. But I can add any code if asked for such, just don't want to add everything that I can think of from the Django project.
And information about my System MacOS 10.15.3, Django 2.1.5
I have no idea what to try or what to change so any help would be beneficial.


text:
Q: The image is null, cannot read properties const url = "http://api.tvmaze.com/search/shows?q=girls";

export default function MoviesList() {
    const [movie, setMovie] = useState([]);

    useEffect( () => {
        loadData();
        }, []);
        const loadData = async () => {
            await fetch(url)
            .then(response => response.json())
            .then(data => setMovie(data))
            .catch(error => console.log(error));
        }

    function movieCard (movie) {
        return (
            <Card className="movie-card" key={movie.show.id}>
                <Card.Body>
                    <Card.Title>{movie.show.name}</Card.Title>
                    <Card.Text>{movie.show.url}
                    <Card.Img src={movie.show.image.medium} />
                    </Card.Text>
                </Card.Body>
            </Card>
        );
    }
    return (
        <>

Movie List

        {movie.map(movieCard)}
        </>
    )
}

So what I'm trying to do is I try to access the image URL from the API and use it on my card component. But as soon as I access it, the web goes blank and this is what shows up at console.

Any idea how to fix this? Thanks a lot in advance!

A: When it comes to fetching with APIs you need to be ready for larger data structures, since I can only see 1 item in the output above I'll try and show why things are not working.
In your setMovie, you set movie to the entirety of the data.
If we instead go ahead and set movie by using
setMovie(data[0])
we instead save that first item.
There might be some future adjustments, but now movie will have access to both url, name and medium in your movieCard function.
Ask yourself if it really is data[0] that you need, or if your initial fetch(url) needs to be altered to get 1 specific item.

Based on your comment below, you want to show movieCards for each item. How I would do that would rewrite abit and make a return that calls movieCard for each movie and then returns that.
const [movie, setMovie] = useState([]);
I would change to
const [movies, setMovies] = useState([]); to show that we might be working with several movies depending on what we fetch.
We also go back to your original way of setting the state:
setMovie(data) as we now know that you have all items in there.
What we can do next is rewrite your return like this:
 return (
        <>

Movie List

        {movies.map((movie) => (
           movieCard(movie);
        )}
        </>
    )

What will happen now is that instead of returning 1 item calling movieCard function, the state containing all the data will iterate and create a movieCard for each movie item it contains.

A: The render function runs before data arrive, add a condition that if the array is empty, don't make the card
function movieCard (movie) {
    if(movie !== ''){
        return (
            <Card className="movie-card" key={movie.show.id}>
                <Card.Body>
                    <Card.Title>{movie.show.name}</Card.Title>
                    <Card.Text>{movie.show.url}
                    <Card.Img src={movie.show.image.medium} />
                    </Card.Text>
                </Card.Body>
            </Card>
        );
    }
}

Also, change data to data[0] as data is in 1st element of the array
useEffect( () => {
        loadData();
        }, []);
        const loadData = async () => {
            await fetch(url)
            .then(response => response.json())
            .then(data => setMovie(data[0]))
            .catch(error => console.log(error));
        }


text:
Q: Sharedpreferences retrieve String I save some EditText data into shared preferences and then on another activity I show it in TextView (it works - easy) - but when I want to use saved variable in a method it does not work - do you have any idea how to retrieve e.g. IP from shared pref?
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
String AJPI  = Text1.getText().toString();
editor.putString(IPv4, AJPI);
editor.commit();

A: Did you add this line?
editor = sharedpreferences.edit();

A: Save:
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(IPv4, "myString").apply();

Retrieve:
String s =
PreferenceManager.getDefaultSharedPreferences(context)
.getString("myString", "defaultStringIfNothingFound");

A: Save to SharePreference
 SharedPreferences pref = getSharedPreferences("Preference", MODE_PRIVATE);
 SharedPreferences.Editor editor = pref.edit();
 editor.putString("Value", your_value);
 editor.commit();

Read from SharePreference
 SharedPreferences pref = getSharedPreferences("Preference", MODE_PRIVATE);
 String phone_number = pref .getString("Value", "");