text:
Q: How to properly use cpow in a C function I'm trying to use cpow with r and I get a syntax error telling me to put a semi colon after r.
After reading the docs I'm still confused on what I'm doing wrong?
#include <math.h>
#include <complex.h>

float area(double r)
{
    r = (1 - r / 1.83) * 1.25;
    double complex z = cpow(r, .2); // i get an error here on the letter r saying missing colon (;)
    return r;

}

    int main()
    {
        float a,r;

        double radius, sum = 0;
        char continu[20];

        // the body of the loop is executed at least once
        do
        {
            float a,r;

            printf("Enter a number: ");
            printf("enter radius of the circle: ");
            scanf("%lf",&r);
            a=profile(r);
            printf("CCOC: %f\n",a);

        }
        while(continu = 'y');

        return 0;
    }

A: The variable name r in double complex r collides with the argument name r in double r. Give one of them another name.

A: On topo of conflicting r variable name and returnign wrong type the header for cpow is like this:
double complex cpow( double complex x, double complex y );

What you are calling it with is:
double complex z = cpow(double r,double .2);

Complex numbers have 2 components real and imaginary. As your operands are real domain you need to cast them to complex domain by copying them to real part and set imaginary part to zero.
I never used complex.h usually use my own code for stuff like this so I do not know how exactly cast this. According to this I would expect this would work:
double area(double r)
    {
    double complex cr,ce,cz;
    r = (1.0-(r/1.83))*1.25;
    cr=r+0.0*I;
    ce=0.2+0.0*I;
    cz=cpow(cr,cc);
    return  creal(cz);
    }

However as its most likely implemented like a macro its possible you need to write double complex before each operand of cpow ... Also the I I saw to be use as i too in the same linked doc... its really confusing which one or if booth or if they are required or not.
However using cpow from complex.h will not resolve your problem as it most certainly does not compute the correct k for cln and uses most likely just k=0 which will lead to non real results !!! If you use the last version of mine mypow in the linked answer you do not need complex.h nor anything else but math.h ...
Also only now its clear you are computing area. So why is r even negative? If you have some parts to add and some to substract from the total area then its OK however if not then maybe you just have wrong equation and after its correction you could use real domain pow ... such case is called XY problem ... you want to solve problem X by solving problem Y as you think it would lead you closer to solution however if X and Y are not related you just wasting time.


text:
Q: Google Maps Places API, need to get same markers as on Google emded Good day !
I'm developing custom service, that will grab params form Google Maps url, like https://www.google.nl/maps/search/fietsenmaker/@52.1285737,5.0837216,13z/data=!3m1!4b1?hl=en. From this example it's possible to take search param, longitude, latitude and zoom level. All this params will pass to Google Places API and markers will be drawn on Google map. The main problem, i can't get this markers look same as on embed Google Maps. Here is attachment:

In simple words:
Need to dynamically embed map with listing of places, that was originally in search param and place map center according lat/long with original markers as on embed map.
Any ideas ?
Thanks !

A: Google Embed API will allow you to embed maps with starting params, like map center, object name. You can find it here https://developers.google.com/maps/documentation/embed/guide
Good luck everybody !

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to read all of STDOUT produced by system() call into a socket written in C? The following is a code snippet from the server socket that reads a linux command sent by the client, executes it and sends the output back to the client :
    while(1){
          char command[200];
          message_read = read(sock, command, sizeof(command));

        if(message_read > 0){
            command[message_read] = '\0';
            dup2(sock, STDOUT_FILENO);
            dup2(sock, STDERR_FILENO);
            system(command);
        }
    }

The following is a code snippet of the client that sends a command to the server and receives back the output:
          char output[10240];

          send(sock, command, strlen(command), MSG_NOSIGNAL);
          if((message_read = read(sock, output, sizeof(output)))>0){
          output[message_read] = '\0';
          //print the output somewhere
          }

While the commands like "ls -al", "pwd", or "whoami" give the output in one go, the client fails to read whole of the output produced by commands like "ping", "ps" or "du". However when I call the above snippet multiple times, it gets me the rest of the output produced by the above commands(in chunks.)
I tried to modify the client function as follows:
       send(sock, command, strlen(command), MSG_NOSIGNAL);
       do{
          if((message_read = read(sock, output, sizeof(output))) > 0){
          output[message_read] = '\0';
          //print the output somewhere
          }
        }while(message_read);

The above solution hanged the client program. However, after I killed the server, the outputs did show up in the client's window!
Also, this time the output was all scattered and poorly indented.
Q1. What's happening?
Q2. How to solve it?

A: The way your code is sending and reading strings is not sufficient.
TCP is a byte stream.  There is no 1-to-1 relationship between sends and reads.  As such, the sender MUST either:

*

*send the string length before sending the string's data.

*send a unique terminator after the string data.

And the receiver MUST either:

*

*read the length then read the specified amount of data.

*read until the terminator is reached.

Also, send()/write() and recv()/read() can return fewer bytes than requested, so they need to be called in loops (or, in the case of recv(), you can use the MSG_WAITALL flag).
Try something more like this instead:
// common functions ...

bool sendRaw(int sock, void *data, size_t len)
{
    char *ptr = (char*) data;
    while (len > 0) {
        int sent = send(sock, ptr, len, MSG_NOSIGNAL);
        if (sent < 0) return false;
        ptr += sent;
        len -= sent;
    }
    return true;
}

int recvRaw(int sock, void *data, size_t len)
{
    char *ptr = (char*) data;
    while (len > 0) {
        int recvd = recv(sock, ptr, len, MSG_NOSIGNAL);
        if (recvd <= 0) return recvd;
        ptr += recvd;
        len -= recvd;
    }
    return 1;
}

bool sendUInt32(int sock, uint32_t value)
{
    value = htonl(value);
    return sendRaw(sock, &value, sizeof(value));
}

uint32_t recvUInt32(int sock)
{
    uint32_t value;
    if (recvRaw(sock, &value, sizeof(value)) <= 0) return -1;
    return ntohl(value);
}

bool sendString(int sock, const char *str)
{
    uint32_t len = strlen(str);
    if (!sendUInt32(sock, len)) return false;
    return sendRaw(sock, str, len);

    /* alternatively:
    return sendRaw(sock, str, strlen(len) + 1);
    */
}

/*
bool grow(char **str, size_t *cap, size_t stepBy)
{
    size_t newcap = cap + stepBy;
    char *newstr = (char*) realloc(*str, newcap);
    if (!newstr) return false;
    *str = newstr;
    *cap = newcap;
    return true;
}
*/

char* recvString(int sock)
{
    uint32_t len = recvUInt32(sock);
    if (len == -1) return NULL;

    char *str = (char*) malloc(len+1);
    if (!str) return NULL;

    if (recvRaw(sock, str, len) <= 0){
        free(str);
        return NULL;
    }

    str[len] = '\0';
    return str;

    /* alternatively:

    char ch, *str = NULL;
    size_t len = 0, cap = 0;

    do{
        if (recvRaw(sock, &ch, 1) <= 0){
            free(str);
            return NULL;
        }

        if (ch == '\0') break;

        if (len == cap){
            if (!grow(&str, &cap, 256)){
                free(str);
                return NULL;
            }
        }

        str[len++] = ch;
    }
    while (1);

    if (len == cap){
        if (!grow(&str, &cap, 1)){
            free(str);
            return NULL;
        }
    }

    str[len] = '\0';
    return str;
    */
}

// server ...

char *command;

while ((command = recvString(sock)) != NULL){
    // ...
    system(command);
    free(command);

    // read from command's stdout until finished ...

    if (!sendString(sock, output, outputLength)) break;
}

// client ...

if (sendString(sock, command)){
    char *output = recvString(sock);
    if (output){
        //print the output somewhere
        free(output);
    }
}

Alternatively, if you don't know the length of the command's response ahead of time, and/or don't want to buffer it all in a single memory buffer, then you can read it in chunks, sending each chunk as you go, eg:
// common functions, see above ...

typedef struct _chunk
{
    uint8_t size;
    char data[256];
} chunk;

bool sendChunk(int sock, const chunk *chk)
{
    uint8_t size = chk ? chk->size : 0;
    if (!sendRaw(sock, &size, 1)) return false;
    if (chk) return sendRaw(sock, chk->data, size);
    return true;
}

bool recvChunk(int sock, chunk *chk)
{
    if (recvRaw(sock, &(chk->size), 1) <= 0) return false;
    if (chk->size) return recvRaw(sock, chk->data, chk->size);
    return true;
}

// server ...

bool sendOutput(int sock)
{
    chunk chk;
    int size;

    do{
        // read from command's stdout ...
        size = read(..., chk.data, sizeof(chk.data));
        if (size <= 0) break;

        chk.size = (uint8_t) size;
        if (!sendChunk(sock, &chk)) return false;
    }
    while(1);

    // tell client the data is finished ...
    return sendChunk(sock, NULL);
}

char *command;

while ((command = recvString(sock)) != NULL){
    // ...
    system(command);
    free(command);
    if (!sendOutput(sock)) break;
}

// client ...

if (sendString(sock, command)){
    chunk chk;
    do{
        if (!recvChunk(sock, &chk)) break;
        if (chk.size == 0) break;
        //print the chk.data somewhere
    }
    while (1);
}


text:
Q: How to receive data from Ember send How do I send data from Ember to an Express server?
According to the official docs, we can do a save action in a router like this:
export default Ember.Route.extend({
  model(params) {
    var photo = this.get('store').createRecord('photo', {
      title: 'ni hao xin ji lu',
      owner: 'ViII',
      city: 'Dalian',
      image: 'fafa.jpg',
      star: 3,
      description: '.....'
    });

    photo.save();

On the server side, for example using Express, like this:
router.post('/photos', function(req, res, next) {
  console.log(req.body)//How To Do Here
});

Indeed, the server will trigger the post event, but when I search the req console out, there is nothing about the photo data from the Ember request.
Did I forgot something? How do I pass data to the server with Ember such that the server can receive it?
I'm using the latest Ember version.

A: By default Ember will send the data to the server as JSON. You need to tell Express to parse that. I believe Ember's JSONAPIAdapter sends a content-type header of application/vnd.api+json, which needs a bit of extra configuration for the bodyParser:
var bodyParser = require('body-parser');
app.use(bodyParser.json({type: 'application/vnd.api+json'}));


text:
Q: utf-8 to string gets extra added characters IN ANDROID
When I am getting an utf-8 result from a server and I take the output of the server to a string what happens is I get extra escape characters added to the string.
In code what happens is
String unicodeMessage =  "\u09aa\u09cd\u09b0\u099c\"; //this is how I want it

String unicodeMessage = "\\u09aa\\u09cd\\u09b0\\u099c\\"; // this is what happens

I tried doing the bytes method mentioned in the previous posts yet it doesn't work
byte[] bytes = unicodeMessage.getBytes("UTF-8");
answer = new String(bytes, "UTF-8");

I'm getting the same output as the input string.
Is there a way I can remove the escape characters added?
 String bengali = "\\u09aa\\u09cd\\u09b0\\u099c\\u099c"; //this is the input

//\u09aa\u09cd\u09b0\u099c\u099c is the output i get when i print bengali and use replace("\\\\","\\");

 //প্রজজ is the expected output when input = "\u09aa\u09cd\u09b0\u099c\u099c"

 // u09aau09cdu09b0u099cu099c output when i use replace("\\","")

A: What you have in a single unicode string like \u09aa is the hex value of the character (09aa = 2474 in decimal) escaped with \u. So you need to parse these values and convert them to a real unicode character. Below is a function to do so:
public static String getRealUnicodeString(String unicodeInput) {
    Pattern pattern = Pattern.compile("\\\\u([0-9a-fA-F]+)");
    Matcher m = pattern.matcher(unicodeInput);
    while (m.find()) {
        String unicodeChar = m.group(1);
        unicodeInput = unicodeInput.replaceAll("\\\\u" + unicodeChar, String.valueOf((char) Integer.parseInt(unicodeChar, 16)));
    }
    return unicodeInput;
}

And then use it:
System.out.println(getRealUnicodeString("\\u09aa\\u09cd\\u09b0\\u099c\\u099c \n StackoveFlow"));


text:
Q: I get "An error occurred while Windows was synchronizing with [name of time server]." when trying to automatically synchronise PC time Prompted by the answers to this question I decided to give the Windows built in time synchronisation another go.
However, no matter what time server I use I get this error:
"An error occurred while Windows was synchronizing with [name of time server]."
The help suggests the following as reasons for failure:

*

*You are not connected to the Internet. Establish an Internet connection before you attempt to synchronize your clock.

*Your personal or network firewall prevents clock synchronization. Most corporate and organizational firewalls will block time synchronization, as do some personal firewalls. Home users should read the firewall documentation for information about unblocking network time protocol (NTP). You should be able to synchronize your clock if you switch to Windows Firewall.

*The Internet time server is too busy or is temporarily unavailable. If this is the case, try synchronizing your clock later, or update it manually by double-clicking the clock on the taskbar. You can also try using a different time server.

*The time shown on your computer is too different from the current time on the Internet time server. Internet time servers might not synchronize your clock if your computer's time is off by more than 15 hours. To synchronize the time properly, ensure that the date and time settings are set close to your current time in the Date and Time Properties in Control Panel.

Now the first reason is clearly wrong - I am connected to the internet.
I can see the 2nd being the most likely cause. I have Sygate Personal Firewall running, but it normally asks if something it trying to connect for the first time. Does anyone know I can unblock the NTP protocol - or at least check if it is blocked?.
I don't think it's #3 or #4 as I've tried a number of different servers including the one currently used by Atomic Clock Sync. Though if someone knows the address of a UK time server I can double check this.

A: Try to run the following commands in CMD (as administrator):
net stop w32time
w32tm /unregister
w32tm /register
net start w32time
w32tm /config /manualpeerlist:pool.ntp.org /syncfromflags:manual /update

It should update the clock and print out this:

C:\Documents and Settings\user>net stop w32time
The Windows Time service is stopping. The Windows Time service was stopped successfully.
C:\Documents and Settings\user>w32tm /unregister
W32Time successfully registered.
C:\Documents and Settings\user>w32tm /register
W32Time successfully registered.
C:\Documents and Settings\user>net start w32time
The Windows Time service is starting. The Windows Time service was started
  successfully.
C:\Documents and Settings\user>w32tm /config /manualpeerlist:pool.ntp.org /update
The command completed successfully.

A: Sometimes the problem is simply the windows time service. It seems to get confused every now and then and need to be restarted.  This is especially true of older Windows releases and remains true for Windows 7.
Go to the "Administrative Tools" open the "Services" console (as administrator) and find the Windows Time service.  Right click on it and choose Restart.

A: You can add a new rule to SPF following the steps delineated here. The application is w32Time located under System32 is memory serves right.
However if SPF doesn't complain, the problem is certainly elsewhere. I see to remember having had problems with time sync before. I really can't remember what the reason was in end. But two things seem to nag me:

*

*The service was stopped or in Manual or something, and needed to be in Automatic(?).

*My router was blocking it

Errors coming from the time servers alone seem unlikely. As you say you have tried others. But in any case KB262680 contains huge lists of time servers you can use.
Meanhile KB314054 reveals manual configuration instructions of the service in the registry along with a detailed explanation of all keys further down the page. Could be a case of a bad registry configuration.
All the best.

A: Resetting time services worked for me (Windows 8.1):

Restart the Windows Time service.

*

*Press "Windows Logo" + "R" and type "services.msc" in the run command window.

*In the "Service" window scroll down to "Windows Time".

*Double click on it and click on "Start", if it is stopped.

*If it is already running, then stop it and then restart it again.

*Change the "Startup Type" to "Automatic".

*Click "Apply" and "OK".

*Restart the computer and check if you are able to synchronize the time with the "time.windows.com".

A: Also, if your computer is quite old and you did a restore/recover, be sure that the time, day, month and YEAR are as close as possible before synch.

*

*AND, try a different Server such as a .gov or .mil
     (tick.usno.navy.mil works as of 2016-02-15)

*As Well As

*

*Youtube Link

*HowTo Geek

A: In the "Internet Time" tab, click "Change settings".

*

*Search for an NTP server that's close to your location, here's a great search engine that gives you a good NTP server closest to your location (watch out the bold link, select & copy it to clipboard), but there are also continent, country and regional links, so get as close as you can.

*In the "Server" text box, enter the link of the NTP server you selected

*Click "Update now"

*That should work

A: I had the same problem, tried every step listed here and on Microsoft's support, i.e. from disabling firewall to enabling "Windows Time" service, and everything else but nothing worked.
Then I connected my laptop to other network, and it worked.
In my case, the problem is with the Wi-Fi/router. Though, I didn't face any issue with time synchronization with Ubuntu.

A: I solved this problem by rebooting my router. My router was apparently in a weird state as I was having problems with other URLs as well.


text:
Q: Invalid token '=' in class member declaration in C# I have this code:
public class Probna1 : INotifyPropertyChanged
{
    Person person = new Person();
    person.FirstName = "Joseph";
    person.LastName = "Samuel";
    FirstNameTextBox.DataContext = person;
}

The signs = have this error mesage: Invalid token '=' in class member declaration.
I have Class Person with public fields FirstName and LastName with {get; set;}

A: You can't set your properties directly in the class, you have to put your declarations in a method.
Try to do it in the constructor like this:
public class Probna1 : INotifyPropertyChanged
{
    Person person;

    public Probna1()
    {
        person = new Person();
        person.FirstName = "Joseph";
        person.LastName = "Samuel";
        FirstNameTextBox.DataContext = person;
    }
}

A: Milos, I get the impression that you are new not only to C#, but also to object-oriented programming. FirstNameTextBox belongs to your Windows Form, so you would have to reference that form from your class. However, that's not usually a good idea. What are you trying to accomplish?
I would recommend a good introductory book on C#, so you can understand the basics. I like the "Step by Step" book series, available on Amazon or Barnes and Noble. Happy programming!


text:
Q: endianness when using part of int array I'm trying to pullout values from a uint8_t array.
But I'm having troubles understanding how these are represented in the memory.
#include <cstdio>
#include <cstring>
#include <stdint.h>
int main(){
  uint8_t tmp1[2];
  uint16_t tmp2 = 511;//0x01 + 0xFF = 0x01FF
  tmp1[0] = 255;//0xFF
  tmp1[1] = 1;//0x01
  fprintf(stderr,"memcmp = %d\n",memcmp(tmp1,&tmp2,2));

  fprintf(stderr,"first elem in uint8 array  = %u\n",(uint8_t) *(tmp1+0));
  fprintf(stderr,"first elem in uint8 array  = %u\n",(uint8_t) *(tmp1+1));

  fprintf(stderr,"2xuint8_t as uint16_t  = %u\n",(uint16_t) *tmp1);
  return 0;
}

So i have an 2 element long array of datatype uint8_t. And I have a single variable uint16_t.
So when I take the value 511 on my little endian machine, I would assume this is layed out in memory as
0000 0001 1111 1111

But when I use memcompare it looks like it is actually being represented as
1111 1111 0000 0001

So little endianness is only used "within" each byte?
And since the single bit that is set in the tmp1[1] counts as 256, even though it is further "right" in my stream. The values for each byte (not bit), is therefore bigendian? I'm abit confused about this.
Also if I want to coerce an fprint, to printout, my 2xuint8_t as a single uint16_t, how do I do this. The code below doesn't work, it only printouts the first byte.
fprintf(stderr,"2x uint8_t as uint16_t  = %u\n",(uint16_t) *tmp1);

Thanks in advance

A: Your assumption of what you expect is backwards.  Your observation is consistent with little-endian representation.  To answer your last question, it would look like this:
fprintf(stderr,"2x uint8_t as uint16_t  = %u\n",*(uint16_t*)tmp1);

A: First, if you want be 100% sure that your variables are stored in right order in memory, you should put them in a struct.
Then note that memcmp() treats input you give it as a sequence of bytes, since it has no assumptions regarding the nature of the data you give it. Think, for example, of the following code:
#include <stdio.h>
#include <stdint.h>

int main(int argc, char** argv) {
    int32_t a, b;
    a = 1;
    b = -1;
    printf( "%i\n", memcmp( &a, &b, sizeof( int32_t ) ) );
}

It outputs -254 on my little-endian machine regardless of fact that a > b. This is because it has no ideas about what the memory actually is, so it compares them like an array of uint8_t.
If you actually want to visualize how the data is represented on your machine, you may first use fwrite to write a struct into the file and then open it with your favorite hex editor (in my experience, wxHexEditor is great in telling you how the data looks if it is X-bit Y-endian ingeter). Here's the source:
#include <stdio.h>
#include <stdint.h>

typedef struct {
    uint8_t tmp1[2];
    uint16_t tmp2;
} mytmp;

int main(int argc, char** argv) {
    mytmp tmp;
    tmp.tmp1[0] = 255;
    tmp.tmp1[1] = 1;
    tmp.tmp2 = 511;

    FILE* file = fopen( "struct-dump", "w" );
    fwrite( &tmp, sizeof( mytmp ), 1, file );
    fclose( file );
}

As for treating an array of uint8_t as uint16_t, you would probably want to declare a union or use pointer coercion.

A: Don't think of endianness as "within bytes". Think of it as "byte ordering". (That is, the actual bit ordering never matters because humans typically read values in big-endian.) If it helps to imagine that the bits are reversed on a little-endian machine, you can imagine it that way. (in that case, your example would have looked like 1111 1111 1000 0000, but as I said, humans don't typically read numbers such that the most significant values are to the right...but you might want to imagine that's how the computer sees things, if it helps you understand little-endian.)
On a little endian machine, 0xAABBCCDD would be seen as 0xDD 0xCC 0xBB 0xAA in memory, just as you are seeing. On a big-endian machine (such as a PPC box) you'd see the same ordering in-memory as you see when you write out the 32-bit word.


text:
Q: Build fails sample Qt5 Unresolved symbol QtConcurrent QunhandledExecption trying this sample code qt-concurrent, I am getting LNK2001 unresolved symbol QFutureInterfaceBase on link for x64 arch using MSVC 2019

LNK2001   symbole externe non résolu "__declspec(dllimport) public: void
__cdecl QFutureInterfaceBase::reportException(class QException const &)"
(_imp?reportException@QFutureInterfaceBase@@QEAAXAEBVQException@@@Z)
LNK2001   symbole externe non résolu "__declspec(dllimport) public:
virtual __cdecl QUnhandledException::~QUnhandledException(void)"
(_imp??1QUnhandledException@@UEAA@XZ)

#include <iostream>
#include <QtCore/QtCore>
#include <QtCore/QFuture>
#include <QtCore/QUnhandledException>

#include <QtConcurrent/QtConcurrent>
#include <QtConcurrent/QtConcurrentRun>
#include <QtConcurrent/QtConcurrentMap>

int main()
{
    // from https://doc.qt.io/qt-5/qtconcurrentrun.html#using-member-functions
    QByteArray bytearray = "Hello World!";
    QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ',');
    QList<QByteArray> result = future.result();
}

Here are my linked libs from directory C:\Qt\5.15.2\lib

Qt5Concurrent.lib Qt5Core.lib Qt5Network.lib Qt5Sql.lib Qt5Widgets.lib
Qt5Xml.lib

Note : When I checked Qt5Concurrent.dll it is well amd64 dll and so lib too.


text:
Q: what is the right whl file for pyqt4 for heroku deployment .whl file for pyqt4 mentioned in the requirements.txt fails to install
I am new to both Flask and Heroku.
I tried making a flask app ,it uses pyqt4 for webview.
I want the app to be deployed in heroku.
pyqt4 is removed from pip as pip now has pyqt5,for some reasons i could not get the code running with pyqt5,so I included the url of the pyqt4 .whl in the requirements.txt. Running the command  git push heroku master gives the message:
remote:        PyQt4-4.11.4-cp37-cp37m-win32.whl is not a supported wheel on this platform.
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:

The flask app runs locally with the installed pyqt4 without any errors,so i think there is no problem with the file
folder structure:
directory structure
requirements.txt:-
aniso8601==7.0.0
appdirs==1.4.3
autopep8==1.4.3
beautifulsoup4==4.7.1
bs4==0.0.1
certifi==2018.11.29
chardet==3.0.4
Click==7.0
cssselect==1.0.3
docutils==0.14
fake-useragent==0.1.11
Flask==1.0.3
Flask-RESTful==0.3.7
future==0.17.1
gunicorn==19.9.0
idna==2.8
itsdangerous==1.1.0
jedi==0.13.2
Jinja2==2.10.1
lxml==4.3.4
MarkupSafe==1.1.1
mccabe==0.6.1
parse==1.12.0
parso==0.3.4
pluggy==0.8.1
pycodestyle==2.5.0
pydocstyle==3.0.0
pyee==6.0.0
pyflakes==2.1.0
Pygments==2.3.1
pypiwin32==223
pyppeteer==0.0.25
PyQt5-sip==4.19.17
pyquery==1.4.0
python-jsonrpc-server==0.1.2
python-language-server==0.23.2
pytz==2019.1
pywin32==224
requests==2.21.0
requests-html==0.10.0
rope==0.12.0
sip==4.19.8
six==1.12.0
snowballstemmer==1.2.1
soupsieve==1.9.1
tqdm==4.32.1
urllib3==1.24.1
w3lib==1.20.0
websockets==7.0
Werkzeug==0.15.4
yapf==0.26.0
https://download.lfd.uci.edu/pythonlibs/t4jqbe6o/PyQt4-4.11.4-cp37-cp37m-win32.whl

Am i doing anything wrong,if yes then what is the right way to include .whl files in requirements.txt?Thanks in advance

A: This is the problem: PyQt4-4.11.4-cp37-cp37m-win32.whl is not a supported wheel on this platform. This wheel can only be used on 32bit windows systems. If you are running on a different system, you'd have to use a different wheel.


text:
Q: First child selection on DIV is not working Please find the below JSfiddle link. I am trying to hide the first DIV child (with aaaaaa value) inside the div with the attribute aria-labelledby value.
But i think i made some mistake in the CSS syntax.
Please suggest.
http://jsfiddle.net/5g7ot5qf/
div[aria-labelledby="ui-dialog-title-timeout-dialog"]:first-child {
    display:none;
}

HTML Code:-

I am a strong man. I am a strong man.

I am a strong man. I am a strong man.

  hello

aaaaaa

X2

X3

div:first-child as the selector
the >div is added

A: If you want the div with aaaaa content gone use
div[aria-labelledby="ui-dialog-title-timeout-dialog"] > div:first-child {
    display:none;
}

If you want all div's gone, but hello there use
div[aria-labelledby="ui-dialog-title-timeout-dialog"] > div {
    display:none;
}

If you want to target divs, use
div[aria-labelledby="ui-dialog-title-timeout-dialog"] > div:nth-child(n) {
    display:none;
}

Where n is the div you want to hide (n=1,2,3,...)
EDIT: A fiddle: http://jsfiddle.net/wh3d3dtj/

A: It will be better to use http://caniuse.com/#search=first-of-type
div[aria-labelledby="ui-dialog-title-timeout-dialog"] > div:first-of-type

Because if you put the text "hello" in some tag

hello

then :first-child will not work
http://jsfiddle.net/kxhk83um/


text:
Q: Spark streaming: task "predict" not serializable I am  trying to make a spark streaming program using a model to predict, but I get an error doing this: Task not serializable.
Code:
val model = sc.objectFile[DecisionTreeModel]("DecisionTreeModel").first()
val parsedData = reducedData.map { line =>
  val arr = Array(line._2._1,line._2._2,line._2._3,line._2._4,line._2._5,line._2._6,line._2._7,line._2._8,line._2._9,line._2._10,line._2._11)
  val vector = LabeledPoint(line._2._4, Vectors.dense(arr))
  model.predict(vector.features))
}

I paste the error:
scala> val parsedData = reducedData.map { line =>
     |     val arr = Array(line._2._1,line._2._2,line._2._3,line._2._4,line._2._5,line._2._6,line._2._7,line._2._8,line._2._9,line._2._10,line._2._11)
     |     val vector=LabeledPoint(line._2._4, Vectors.dense(arr))
     |     model.predict(vector.features)
     | }
org.apache.spark.SparkException: Task not serializable
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:304)
    at org.apache.spark.util.ClosureCleaner$.org$apache$spark$util$ClosureCleaner$$clean(ClosureCleaner.scala:294)
    at org.apache.spark.util.ClosureCleaner$.clean(ClosureCleaner.scala:122)
    at org.apache.spark.SparkContext.clean(SparkContext.scala:2030)
    at org.apache.spark.streaming.dstream.DStream$$anonfun$map$1.apply(DStream.scala:528)
    at org.apache.spark.streaming.dstream.DStream$$anonfun$map$1.apply(DStream.scala:528)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:147)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:108)
    at org.apache.spark.SparkContext.withScope(SparkContext.scala:709)
    at .......

How can I solve this issue?
Thanks!

A: Refer this link:
https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/troubleshooting/javaionotserializableexception.html
In your case, "model" is instantiated in driver and used in map which causes the object to be sent over network from driver to executors, so it should be serializable. If you cannot make model serializable, try avoiding having to serialize by instantiating model inside map.You may also need to control how often you create this object within executor - once per row(default), once per task(i.e., thread) or once per executor(i.e, jvm).
Finally, I don't think you can have a single global "model" object that you can cause mutations to from multiple executors - just in case that's what you are looking for(irrespective of whether you need to make it serializable or not).Comments welcome on this point.


text:
Q: Why RunListener class testRunStarted() method calling multiple times for a single test in JUnit? I have tried the example of JUnit listener given in the example in link
MyRunner.class
public class MyRunner extends BlockJUnit4ClassRunner {

public MyRunner(Class<?> klass) throws InitializationError {
    super(klass);
}

@Override public void run(RunNotifier notifier){
    notifier.addListener(new JUnitExecutionListener());
    notifier.fireTestRunStarted(getDescription());
    super.run(notifier);
}
}

JUnitExecutionListener.class
public class JUnitExecutionListener extends RunListener {

@Override
public void testRunStarted(Description description) throws Exception {
    System.out.println("Number of tests to execute: " + description.testCount());
}

@Override
public void testRunFinished(Result result) throws Exception {
    System.out.println("Number of tests executed: " + result.getRunCount());
}

@Override
public void testStarted(Description description) throws Exception {
    System.out.println("Starting: " + description.getMethodName());
}

@Override
public void testFinished(Description description) throws Exception {
    System.out.println("Finished: " + description.getMethodName());
}

@Override
public void testFailure(Failure failure) throws Exception {
    System.out.println("Failed: " + failure.getDescription().getMethodName());
}

@Override
public void testAssumptionFailure(Failure failure) {
    System.out.println("Failed: " + failure.getDescription().getMethodName());
}

@Override
public void testIgnored(Description description) throws Exception {
    System.out.println("Ignored: " + description.getMethodName());
}
}

I have 3 tests as below
Sample1Test.class
@RunWith(MyRunner.class)
public class Sample1Test {

@Test
public void step1() {
    System.out.println("Sample1Test step1");
}
}

Sample2Test.class
@RunWith(MyRunner.class)
public class Sample2Test {

@Test
public void step1() {
    System.out.println("Sample2Test step1");
}
}

Sample3Test.class
@RunWith(MyRunner.class)
public class Sample3Test {

@Test
public void step1() {
    System.out.println("Sample3Test step1");
}
}

On console I am getting log below,
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.demo.test.Sample1Test
Number of tests to execute: 1
Starting: step1
Sample1Test step1
Finished: step1
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.064 sec
Running com.demo.test.Sample2Test
Number of tests to execute: 1
Number of tests to execute: 1
Starting: step1
Starting: step1
Sample2Test step1
Finished: step1
Finished: step1
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.demo.test.Sample3Test
Number of tests to execute: 1
Number of tests to execute: 1
Number of tests to execute: 1
Starting: step1
Starting: step1
Starting: step1
Sample3Test step1
Finished: step1
Finished: step1
Finished: step1
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Number of tests executed: 3
Number of tests executed: 3
Number of tests executed: 3

Why JUnitExecutionListener methods are getting called twice for second test and thrice for the third abd so on ? Can we have a fix for this so that each method should call only once ?
Note : I am using junit-4.12

A: RunNotifier is shared among all the children: org.junit.runners.ParentRunner#runChildren. It basically means that every time method "run" is invoked for one of your runners, the listener is added to the already existing RunNotifier object that may contain your listener already.
There are two ways I see to address the issue:

*

*Make your listener singleton object or just store it in a static field and then before adding just check whether or not it is already in the list.

*Remove your listener after the invocation of method run. Like this:
super.run(notifier);
notifier.removeListener(listener);

Hope it was helpful.

A: I had the same issue and
I fixed it using a maven-surefire-plugin
you can register your custom JUnit listener by adding the below snippet in the maven-surefire plugin in pom.xml. No need to use a custom runner class and @RunWith annotation
<properties>
      <property>
          <name>listener</name>
          <value>path.to.listener.class</value>
      </property>
</properties>


text:
Q: preg_match returns nothing I'm trying to get the wheather data from http://www.weather-forecast.com/locations/Berlin/forecasts/latest
but preg_match just returns nothing

<?php

$contents=file_get_contents("http://www.weather-forecast.com/locations/Berlin/forecasts/latest");

preg_match('/3Day Weather Forecast Summary:<\/b><span class="phrase">(.*?)</s', $contents, $matches);

print_r($matches)

?>

A: Don't use a regex to parse html, user an html parser like DOMDocument,
$contents = file_get_contents("http://www.weather-forecast.com/locations/Berlin/forecasts/latest");
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($contents);
$x = new DOMXpath($dom);
foreach($x->query('//span[contains(@class,"phrase")]') as $phase)
{
    echo $phase->textContent;
}


text:
Q: average temperature in Arduino I have an Arduino thermometer by Sparkfun that measures temperature. It's very precise, but I need more of an average.
The code I'm using is straight from Sparkfun (https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-7-reading-a-temperature-sensor)
const int temperaturePin = 0;

void setup()
{
  Serial.begin(9600);
}

void loop()
{

  float voltage, degreesC, degreesF;

  voltage = getVoltage(temperaturePin);

  degreesC = (voltage - 0.5) * 100.0;

  degreesF = degreesC * (9.0/5.0) + 32.0;

  Serial.print("voltage: ");
  Serial.print(voltage);
  Serial.print("  deg C: ");
  Serial.print(degreesC);
  Serial.print("  deg F: ");
  Serial.println(degreesF);

  delay(1000);
}

float getVoltage(int pin)
{
  return (analogRead(pin) * 0.004882814);
}

I'm looking get a reading every minute on an AVERAGE of every 10 seconds, AND throw out outliers, rather than merely what is is every minute.
FOR EXAMPLE, if it reads 65, 64, 66, 67, 65, 44 over the course of a minute...it will average the first 5 and throw out 44, for an average of 65.4.

A: I suggest sorting the numbers and computing the average of a few numbers (about 10-25% of the number of samples may be a good start) near the median. This way you get rid of the outliers quite easy and obtain a relevant average.


text:
Q: Laravel undefined variable into blade after calling from JSON I've Signup form in my website. It was properly submitting before. Now I wanted to submit my form using ajax and wanted to return a variable from controller into JSON that I will use into blade file.
The form is submitting and values are showing into database but after redirection, it returns error.
Undefined variable: seller in report blade

I tried to decode my variable to make it work but still the same error.
How would I make it work?
Report-Blade
 @foreach(json_decode($seller, true) as $row)

  <a  href="{{route('Report', $row->id) }}" >
    {{ __('Show Report of ')}} {{$row->car_title}}
  </a>

 @endforeach

Controller
$seller = Sellers::take(1)->latest()->get();

return response(view('report',array('seller'=>$seller)),200, ['Content-Type' =>
'application/json']);

JavaScript
$("#submit-all").click(function(e){
    e.preventDefault();
     var _token = $('input[name="_token"]').val();

    $.ajax({
        type: "post",
        url: "{{ route('form_for_private_sellers') }}",
        data : $('#msform').serialize() + "&_token=" + _token,

        dataType: 'JSON',
        beforeSend: function(){
            // Show loading image
            $("#se-pre-con").show();
        },
        success: function(data) {
            window.location = "http://127.0.0.1:8000/report/";
        },
        complete:function(data){
            // Hide loading image
            $("#se-pre-con").hide();
        }
    });
});

A: you need two route for this
first for rendering blade
return view('report');

and the second for fetch seller
$seller = Sellers::latest()->take(1)->get();
return $seller

A: As understood from your comments,
window.location = "http://127.0.0.1:8000/report/";

will hit the route
Route::get('/report', function () {
  return view('report');
})->name('private_seller_report');

Report blade expects a variable named $seller, and it is not being sent from the route. You would need to change the route to something similar to this:
Route::get('/report', function () {
  $sellers = Seller::get(); //your logic
  return view('report', ['seller' => $sellers]);
})->name('private_seller_report');

Alternatively you can point the route to a method in a controller if you want to avoid bulking up your routes.


text:
Q: Google Maps API zoom on resize I have searched, researched and searched some more.
I am desperately trying to make it so my map changes its zoom automatically with different browser sizes as it keeps the markers on the map viewable. Right now the best thing that works for me is:
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);

And even that is flawed. When the map becomes smaller, say on a mobile device, the markers eventually leave visibility since the zoom does not change. I need the zoom to change. Seemingly, this is the solution(I've done a lot of research, mostly from Stack Overflow):
map.fitBounds(firstB,secondB);

firstB, and secondB are the latitude and longitude that my markers use for their position.
I've even tried:
bounds = new google.maps.LatLngBounds();
bounds.extend(marker);
bounds.extend(smarker);
map.fitBounds(bounds);

Currently this is what I have:

Nothing works.

A: Fix your bounds, make that global and call map.fitBounds in the resize handler code:
var bounds = new google.maps.LatLngBounds();

function initialize() {
  var firstB = new google.maps.LatLng(38.9395799,-104.7168500999999);
  var secondB = new google.maps.LatLng(38.9382571,-104.71727069999997);
  bounds.extend(firstB);
  bounds.extend(secondB);

Then:
google.maps.event.addDomListener(window, "resize", function() {
 google.maps.event.trigger(map, "resize");
 map.fitBounds(bounds);
});

working fiddle
code snippet:

var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();

function initialize() {
  var firstB = new google.maps.LatLng(38.9395799,-104.7168500999999);
  var secondB = new google.maps.LatLng(38.9382571,-104.71727069999997);
    bounds.extend(firstB);
    bounds.extend(secondB);
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(38.938987, -104.717286);
  var mapOptions = {
    zoom:18,
    center:latlng,
    disableDefaultUI:true
  }

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  map.fitBounds(bounds);

  var styles=[
  {
    featureType:"road",
    elementType:"labels",
    stylers:[
      {visibility:"off"}
    ]
  }
  ];
  map.setOptions({styles: styles});

var pinIcon = new google.maps.MarkerImage(
    'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(52, 52)
);

  var marker = new google.maps.Marker({
      position: firstB,
      map: map,
      title: 'AVS',
      icon:pinIcon,
  });

  var firstB_contentString = '

Medical Office Building

6007 E Woodmen Rd.

Colorado Springs, CO 80923

';

  var firstB_infowindow = new google.maps.InfoWindow({
    content: firstB_contentString
  });
  google.maps.event.addListener(marker, 'click', function() {
  firstB_infowindow.open(map,marker);
});

  var smarker = new google.maps.Marker({
      position: secondB,
      map: map,
      title: 'AVS',
      icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
  });
  var secondB_contentString = '

General Hospital

6001 E. Woodmen Rd.

Colorado Springs, CO 80923

';

  var secondB_infowindow = new google.maps.InfoWindow({
    content: secondB_contentString
  });
google.maps.event.addListener(smarker, 'click', function() {
  secondB_infowindow.open(map,smarker);
});

google.maps.event.addListener(map, 'mousedown', function() {
  firstB_infowindow.close(map,marker);
  secondB_infowindow.close(map,smarker);
});
google.maps.event.addListener(marker, 'mousedown', function() {
  firstB_infowindow.close();
  secondB_infowindow.close();
});
google.maps.event.addListener(smarker, 'mousedown', function() {
  firstB_infowindow.close();
  secondB_infowindow.close();
});

/*bounds = new google.maps.LatLngBounds();
bounds.extend(marker);
bounds.extend(smarker);
map.fitBounds(bounds);*/

}
google.maps.event.addDomListener(window, 'load', initialize);

google.maps.event.addDomListener(window, "resize", function() {
 google.maps.event.trigger(map, "resize");
 map.fitBounds(bounds);
});
html, body, #map-canvas {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
}


text:
Q: Can I return a value from a watcher? VUE I have a watcher, and I get an error when I try to return a value from a watcher.
Error is pretty vague: Coding style found in ...file...
Is it not possible to do this?
@Watch('elementIwantToWatch')
public getColumn() {
    //......
    return column;
}

A: It doesn't make sense to return value from watcher.
Watcher are special reactive hooks which we can utilise to take action on some side-effect, the returned value can't be utilise. Probably you are looking for computed property.
computed: {
  getColumn() {
   // return value here
  }

}

and in HTML, you can directly use:
<div> Column: { getColumn } </div>


text:
Q: Python 3.6 Как обратиться к разным файлам в цикле Здравствуйте,
стоит задача перемешать строки в текстовых файлах c одинаковым названием, лежащих в разных папках, например c:\Users\i\200818comments.txt где i=1...n
import random
for i in range(1, 10):
    filename = 'c:\\Users\\i\\200818comments.txt'
    f = open(filename)
    lines = f.readlines()
    f.close()
    random.shuffle(lines)
    f = open(filename,'w')
    f.writelines(lines)
    f.close()

К сожалению не работает такой подход: [Errno 2] No such file or directory
Прошу подсказать как решить вопрос

A: Конечно не работает. Вот в этой строке
filename = 'c:\\Users\\i\\200818comments.txt'
не достаточно просто написать i внутри строки, нужно объяснить питону, что он должен заменять её на значение соответствующей переменной. Используйте форматирование строк:
filename = 'c:\\Users\\{}\\200818comments.txt'.format(i)
И ещё совет: чтобы не писать двойные слэши (это может очень запутывать и приводить к ошибкам), используйте сырые строки:
filename = r'c:\Users\{}\200818comments.txt'.format(i)


text:
Q: How find this minimum of the value of $n$( 2013 china Mathematical olympiad simulation test )
Let $S=\{1,2,3,\cdots,n\}$. Find the minimum of positive integer $n$, such that for any partition of $S$ into $A$ and $B$,
  $$A\cap B =\emptyset,A\cup B=S$$
  then at least one of the subsets $A$ or $B$ must have two different elements $a,b$, such that
  $$a+b\mid ab$$

and  This problem is from this

I have consider sometimes,and this problem don't have solution,I hope someone can help,Thank you
my try:
let Gcd$(a,b)=d$,then
$$a=a_{1}d,b=b_{1},gcd(a_{1},a_{2})=1$$
since

$$(a+b)|ab$$
  then we have
  $$(a_{1}+b_{1})|(a_{1}b_{1}d)$$
  since
  $$(a_{1}+b_{1},a_{1})=(a_{1}+b_{1},b_{1})=(a_{1},b_{1})=1$$
  so
  $$(a+b)|ab\Longleftrightarrow (a_{1}+b_{1})|d$$

so let $d=k(a_{1}+b_{1})$.
so
$$a=ka_{1}(a_{1}+b_{1}),b=kb_{1}(a_{1}+b_{1})$$
Then I can't,Thank you for you can help.Thank you very much.
and I have found there is same problem; there is China National Olympiad 1996 problem 2: can see this: http://www.artofproblemsolving.com/Forum/viewtopic.php?p=1507766&sid=e25e6454134749f7426ce808796903b4#p1507766

A: Begin from your characterisation, $$a=ka_1(a_1+b_1), b=kb_1(a_1+b_1)$$
First observe that if $n$ satisfies the given property, so does  any $m \geq n$.
It turns out (after some trial and error) that $n=40$ is minimal. It then suffices to show that $n=40$ works, and $n=39$ does not.
We thus only concern ourselves with $a, b \leq 40$. We may WLOG assume $a<b$, so $a_1<b_1$. Note that we want $40 \geq b=kb_1(a_1+b_1) \geq (1)(b_1)(1+b_1)$ so $b_1 \leq 5$.
$a_1=1, b_1=2: (3, 6), (6, 12), (9, 18), (12, 24), (15, 30), (18, 36)$
$a_1=1, b_1=3: (4, 12), (8, 24), (12, 36)$
$a_1=2, b_1=3:(10, 15), (20, 30)$
$a_1=1, b_1=4: (5, 20), (10, 40)$
$a_1=3, b_1=4: (21, 28)$
$a_1=1, b_1=5: (6, 30)$
$a_1=2, b_1=5: (14, 35)$
$a_1=3, b_1=5: (24, 40)$
Consider $n \geq 40$, and assume on the contrary that there is a partition of $S$ into $A, B$ such that neither $A$ nor $B$ have two elements $a, b$ s.t. $a+b|ab$. Then WLOG assume $3 \in A$. Thus
$$3 \in A \Rightarrow 6 \in B \Rightarrow 12 \in A \Rightarrow 24 \in B \Rightarrow 40 \in A \Rightarrow 10 \in B \Rightarrow 15 \in A \Rightarrow 30 \in B \Rightarrow 6 \in A$$
We thus get a contradiction.
Therefore $n=40$ has the desired property.
Finally $n=39$ fails by the following partition:
$$A=\{4, 6, 9, 15, 20, 24, 28, 35, 36\}, B=S\setminus A=\{1, 2, \ldots , 39\} \setminus A$$
Thus $n=40$ is minimal.


text:
Q: FadeIn animation for div with display:none property I am having issues implementing a fadeIn function for one of my div tags that has a display:none property attached to it.
What would be the best way to go about having the div tag appear and then fade in? I am pretty adamant about keeping the display:none property.
This is what I have tried:

And then in my .script file:
document.getElementById('test_id').fadeIn(1000);

It simply does not play the animation. Any help/suggestions would be appreciated!

A: If you are trying to use the jQuery function, .fadeIn, you have to call refer to the DOM object like this:
$('#test_id').fadeIn(1000);

A: I think you meant to say:
$("#test_id").fadeIn(1000);

A: Try this solution if you want use javascript

aiuto

fade(document.getElementById('test_id'));

function fade(element) {
    var op = 0.1;  // initial opacity
    var timer = setInterval(function () {
        if (op >=1){
            clearInterval(timer);
            //element.style.display = 'none';
        }
        element.style.opacity = op;
        element.style.filter = 'alpha(opacity=' + op * 100 + ")";
        op += op * 0.1;
    }, 50);
}


text:
Q: How can I configure MyGeneration tool to run the code template for each table and create .cs file for each? How can I configure MyGeneration conde-generator tool to run the code template for each Db table and create a separate .cs for each?

A: Simply run the template and select all tables from the list (it is multi-Select).or you need to write a template for this.
for template writing , check the forum Here specially template forums (last three ones) .or try to make self learning by opening  an existing template such as : CSharp_SQL_dOOdads_BusinessEntity.vbgen you will find code such as :
Sub bindTables(sDatabase)
    Set db = MyMeta.Databases(sDatabase)
    lstTables.BindData(db.Tables)
End Sub

I dont know , if you can make a for loop on "db.Tables" and doing whatever for each table .
also check this question and this  and this and this template library


text:
Q: When to combine multi-related/join tables Considering database performance, please review this example..
If there are only 50,000 widgets in table one,two and three (total) and 50,000,000 widgets in table four.
Using the following relational/join table to handle the first three relationships:
    ID (int)
    IndexID (int)
    RelationType (int)
    RelationID (int)

Would it be ok just to use this relational table for table four as well (by changing the relationtype to Table4), but considering it has a signifigantly larger amount of data than the first three tables?  Or should table four have its own relational/join table:
   ID (int)
   IndexID (int)
   RelationID (int)

A: You can have the same relational table for table4 too and create a non clustered index on relationId.
Performance in inserting might be little slow but traversal and relating will be done fast.


text:
Q: NHibernate bi-directional association I am trying to model a parent/child association where a Parent class (Person) owns many instances of a child class (OwnedThing) - I want the OwnedThing instances to be saved automatically when the Person class is saved, and I want the association to be bi-directional.
public class Person
{
        public class MAP_Person : ClassMap<Person>
        {
                public MAP_Person()
                {
                        this.Table("People");
                        this.Id(x => x.ID).GeneratedBy.GuidComb().Access.BackingField();
                        this.Map(x => x.FirstName);
                        this.HasMany(x => x.OwnedThings).Cascade.AllDeleteOrphan().KeyColumn("OwnerID").Inverse();
                }
        }

        public virtual Guid ID { get; private set; }
        public virtual string FirstName { get; set; }
        public virtual IList<OwnedThing> OwnedThings { get; set; }

        public Person()
        {
                OwnedThings = new List<OwnedThing>();
        }
}

public class OwnedThing
{
        public class MAP_OwnedThing : ClassMap<OwnedThing>
        {
                public MAP_OwnedThing()
                {
                        this.Table("OwnedThings");
                        this.Id(x => x.ID).GeneratedBy.GuidComb().Access.BackingField();
                        this.Map(x => x.Name);
                        this.References(x => x.Owner).Column("OwnerID").Access.BackingField();
                }
        }

        public virtual Guid ID { get; private set; }
        public virtual Person Owner { get; private set; }
        public virtual string Name { get; set; }
}

If I set Person.OwnedThings to Inverse then the OwnedThing instances are not saved when I save the Person.  If I do not add Inverse then the save is successful but person.OwnedThings[0].Owner is always null after I retrieve it from the DB.
UPDATE
When saving the data NHibernate will set the single association end in the database because it is set via the many-end of the association, so when I retrieve the OwnedThing from the DB it does have the link back to the Person set.  My null reference was from Envers which doesn't seem to do the same thing.

A: OwnedThings[0].Owner is most likely null because you are not setting it when you do the add.  When using bidirectional relationships you have to do something like the below:
Person person = new Person();
OwnedThing pwnedThing = new OwnedThing();

pwnedThing.Owner = person;
person.OwnedThings.Add(pwnedThing);

If you do not explicity set the pwnedThing.Owner and you query that same object in the same ISession that you created it on it will be null.  Typically I have add or remove methods that do this "extra" work for me.  Take the below example:
public class Order : Entity
{
    private IList<OrderLine> orderLines;
    public virtual IEnumerable<OrderLine> OrderLines { get { return orderLines.Select(x => x); } }

    public virtual void AddLine(OrderLine orderLine)
    {
        orderLine.Order = this;
        this.orderLines.Add(orderLine);
    }

    public virtual void RemoveLine(OrderLine orderLine)
    {
        this.orderLines.Remove(orderLine);
    }
}

public class OrderMap : ClassMap<Order>
{
    public OrderMap()
    {
        DynamicUpdate();
        Table("ORDER_HEADER");
        Id(x => x.Id, "ORDER_ID");

        HasMany(x => x.OrderLines)
            .Access.CamelCaseField()
            .KeyColumn("ORDER_ID")
            .Inverse()
            .Cascade.AllDeleteOrphan();
    }
}

A: Am I understanding you correctly that your problem only occur on "history" entities read by nhibernate envers?
If so, it might be caused by this bug
https://nhibernate.jira.com/browse/NHE-64
The workaround for now is to use Merge instead of (SaveOr)Update.


text:
Q: Rails Array set to "0" after save I have built an array attribute into my model @users. I did this in the model user.rb serialize :year, Array.
I have a show page in my controller that first prints the @user and then changes the @user.year. It finishes by saving the @user.year.
The first time through when it prints @user.year it returns a [] to show that the array is empty. I print the array right before saving and it is populated with integers, but when I reload the next page the @user.year has switched from a [] to a 0. Any idea why this is?
:year is an assessable attribute in the @user model.
def show
@user = User.find(params[:id])
p "print @user"
p @user
...
@user.today_steps = day['summary']['steps']
@user.year.unshift(@user.today_steps)
...
p @user.year
  if @user.save(validate: false)
    p "Updated"
  else
    p "Failed to Update"
  end
end
end

The @today_steps does save and is shown in the next call, but year doesn't. Any idea why this is?

A: In order for serialize :year, Array to work, the year attribute needs to be a string.
Serialize stores the data in the database as yaml[1].
However, since your column type is integer, the yaml is being converted to an integer before being persisted to the database. Because of the way ruby converts strings to integers, 0 is the expected value given a yaml input.
y = [1,2,3].to_yaml # => "---\n- 1\n- 2\n- 3\n"
y.to_i              # => 0

[1]: unless the class you specify implements load and dump


text:
Q: Save pandas (string/object) column as VARCHAR in Oracle DB instead of CLOB (default behaviour) i am trying to transfer a dataframe to oracle database, but the transfer is taking too long, because the datatype of the variable is showing as clob in oracle. However i believe if i convert the datatype from clob to string of 9 digits with padded 0's , it will not take that much time. data is
product
000012320
000234234

is there a way to change the datatype of this variable to string of 9 digits. so that oracle does not think of it as CLOB object. i have tried the following.
df['product']=df['product'].astype(str)

or is there something else that might slow the transfer from python to oracle ?

A: Here is a demo:
import cx_Oracle
from sqlalchemy import types, create_engine
engine = create_engine('oracle://user:password@host_or_scan_address:1521:ORACLE_SID')
#engine = create_engine('oracle://user:password@host_or_scan_address:1521/ORACLE_SERVICE_NAME')

In [32]: df
Out[32]:
           c_str  c_int   c_float
0        aaaaaaa      4  0.046531
1            bbb      6  0.987804
2  ccccccccccccc      7  0.931600

In [33]: df.to_sql('test', engine, index_label='id', if_exists='replace')

In Oracle DB:
SQL> desc test
 Name                Null?    Type
 ------------------- -------- -------------
 ID                           NUMBER(19)
 C_STR                        CLOB
 C_INT                        NUMBER(38)
 C_FLOAT                      FLOAT(126)

now let's specify an SQLAlchemy dtype: 'VARCHAR(max_length_of_C_STR_column)':
In [41]: df.c_str.str.len().max()
Out[41]: 13

In [42]: df.to_sql('test', engine, index_label='id', if_exists='replace',
   ....:           dtype={'c_str': types.VARCHAR(df.c_str.str.len().max())})

In Oracle DB:
SQL> desc test
 Name            Null?    Type
 --------------- -------- -------------------
 ID                       NUMBER(19)
 C_STR                    VARCHAR2(13 CHAR)
 C_INT                    NUMBER(38)
 C_FLOAT                  FLOAT(126)

PS for padding your string with 0's please check @piRSquared's answer

A: use str.zfill
df['product'].astype(str).str.zfill(9)

0    000012320
1    000234234
Name: product, dtype: object


text:
Q: Is it safe to allocate logical CPUs to a VM after creation We're going to be serving our portal software on a virtual machine running Centos 5.2 on VMWare ESXi.
We're initially going to allocate two logical CPUs but there's a possibility that we might want to add an additional two some time in the future. We don't want to allocate all resources at this time because a few VMs are fighting for space on the server.
If we decided to move our VM off to a separate server later on and allocate additional logical CPUs bringing it to four, will this cause us any problems?

A: Yes you can do this. You can change the number of CPUs like you can change the amount of RAM the VM sees. You should shut down your VM, then change the number of CPUs, then power on the VM. Whether or not the guest OS handles the change smoothly is up to that OS, something as new as Centos 5.x should do just fine.
If you're using SMP VMs, you should read: http://communities.vmware.com/docs/DOC-4960 for more information. Generally a single VM shouldn't have as many virtual CPUs as your host has CPU cores.


text:
Q: Losing state value after function is finished I'm new to react concept, I don't understand why I lose the value of the state after the .then()
I lose the ISPList state value but I did set state :(
appreciate any help.
export default class Cartable extends
React.Component<IMainCartableProps, ICartableState> {
constructor(props: IMainCartableProps, state: ICartableState) {
    super(props)
    this.state = {
      status: "Ready",
      ISiteCollections: [],
      ISPLists:[],
      ISPTaskItems:[],
    }
   }

  public _getListOfLists(context: WebPartContext): Promise<ISPLists[]> {

    this.state.ISiteCollections.map(async (siteCollection:any)=>{

      let url = siteCollection.SPSiteUrl + `/forms/_api/web/lists?
    $filter=Hidden eq false and BaseTemplate eq 107`;
      //console.log(url)
       let config: SPHttpClientConfiguration = new
  SPHttpClientConfiguration({
        defaultODataVersion: ODataVersion.v3})

         new Promise<ISPLists[]>( async (resolve, reject)=>{
          this.props.context.spHttpClient.get(url, config, { headers: { Accept: "application/json;odata=minimalmetadata;charset=utf-8" }})
            .then((response: SPHttpClientResponse) => {
              //console.log(response.status)
              if(response.status==200){
                response.json().then((results: any) => {
                  //let resultsList = results.PrimaryQueryResult.RelevantResults.Table.Rows;
                  console.log(results)
                  results.value.map((result:any)=>{
                    TaskLists.push({
                      title: result.Title,
                      Id:result.Id
                    })

                  })

                  //console.log(TaskLists.length)
                  //this.setState({ ISPLists:TaskLists })
                  //console.log(this.state.ISPLists.length)
                  //resolve(TaskLists);
                  this.setState({ISPLists:TaskLists})

                    //this.setState({ ISPLists:TaskLists})
                    //console.log(this.state.ISPLists[1].title)
                    //this._getTaskItems()
                })

              }
             // return response.json();
             console.log(TaskLists.length)
            })

          })

    })
    console.log(TaskLists.length)
    console.log("Hereeeee")
    this.state.ISPLists.map(SPList=>{
      console.log(SPList.title)
    })

    return

  }

A: There are many things wrong with this code.

*

*You are using a map method,  returning nothing, and adding async operations

*this.setState replaces the existing state, it doesn't merge your new state with the existing state

Solution:

*

*If you just need to loop through ISiteCollections and send API requests
, then just simply use forEach or for loop to loop through the array

*To merge your new state with the existing state, use the es6 spread operator.this.setState({ispLists:[...this.state.ispLists , ...TaskLists ]})

A: Im not sure about your problem as Im not working with react for long time but as for debugging this:
1: Make a console.log for the ISPLists just after setState to make sure that the value has been set correctly.
2: Make sure you are looping through it after setState (as I didnt found any async/await in your code).
For cleaner way: make a separate function for setState ISPList value in order to have more flexibility on it and debugging easier. This really could help to debug it.


text:
Q: Combinatorics question with unequality and different subscript
a-) $x_1+x_2+...+x_7 \leq 30$ where $x_i's$ are even non-negative integers.
b-) $x_1+x_2+...+x_7 \leq 30$ where $x_i's$ are odd non-negative integers.
c-) $x_1+x_2+...+x_6 \leq 30$ where $x_i's$ are odd non-negative integers.

These questions is from my textbook. I know to solve similar questions such that $x_1+x_2+...+x_k \leq n$ where $x_i's$ are  non-negative integers. We add an extra term on the lefthandside and the rest found by combination with repetition such that $ \binom{n+(k+1)-1}{n}$.However , what happens when they are even or odd , is there any special technique ? Moreover , as you see the part a and b differ from only subscripts , i think that there must be a reason behind different subscript in same question.Is there any reason ? Thanks in advance..

A: Finding the number of solutions to $x_1+x_2+\dots+x_7\leq 30$ where each of the $x_i$'s are even non-negative integers...
Rather than writing them as $x_1,x_2,\dots$ since they are even we can write them as $2y_1,2y_2,\dots$
We have then $2y_1+2y_2+\dots+2y_7\leq 30$.  Divide both sides by $2$ and we are left with $y_1+y_2+\dots+y_7\leq 15$ where each of the $y_i$'s are non-negative integers with no restrictions on parity.
Similarly, for the later problems where you deal with odd numbers, you can rewrite as $2z_1+1, 2z_2+1,\dots$  You can then subtract the $1$'s from both sides and then use the same idea.  The punchline is to rewrite a problem you haven't seen before in such a way that it becomes a problem you have seen before.

A: For $(a)$, you should solve for $y_1+y_2+...+y_7 \leq 15, ~ $ where $x_i = 2y_i, y_ \geq 0$
For $(b)$, you should solve for $y_1+y_2+...+y_7 \leq 11$ where $x_i = 2y_i + 1, y_i \geq 0$
For $(c)$, you should solve for $y_1+y_2+...+y_6 \leq 12$ where $x_i = 2y_i + 1, y_i \geq 0$
The difference between $(b)$ and $(c)$ is that in $(b)$, there are $7$ odd numbers and $7$ odd numbers cannot sum to an even number so equality $( = 30)$ is not possible and you would have sum $\leq 29$. But in $(c)$, you have $6$ odd numbers so equality can be reached.


text:
Q: Why am I getting an error in Java AS400 error while extracting files? At my job we use this batch file to extract text files from our AS400 and save them on our hard drive. here is a sample of the bat file:
    echo on

    REM ****************
    SET mydate=%date:~4,2%-%date:~7,2%-%date:~12,2%
    SET myuser=%username%
    echo %myuser%
    REM ****************

    C:

    cd C:\Users\%myuser%\IBM\ClientSolutions\Start_Programs\Windows_i386-32\

    echo on
    echo Starting AS400 Transfer For Marketing Files as %myuser%
    echo.

    acslaunch_win-32.exe /plugin=download \\Path\DGCC008P.dtfx >>
    \\Path\TransferLogs\clm_Monthly_%mydate%_Log.txt

This was working last month for a user and it still works on my system but it stopped working for this user.  I do not have much java or AS400 experience and tried doing a search online.  Here is the error.
Any help would be appreciated.

A: What you see indicate a situation where some Java classes cannot be found where they are being looked for (the Java class path which is notoriously brittle)
The top part of the screen shot indicate that the "jt400.jar" (which might have another name depending on how you got it) is not on the classpath anymore (as it has worked before).


text:
Q: Multiple Attachments Edit in rails 4 I am working on Multiple Attachments to be stored in database and edit. But I'm able to store multiple files to db. Not able to Edit.
        Other_assets_controller.rb

def create
    @other_asset = OtherAsset.new(other_asset_params)
    @other_asset.asset.company_id = current_company.id
    @other_asset.asset.identifier_id = current_user.id
    @other_asset.asset.asset_state_id = 1
    if @other_asset.save
       params[:attachments]['attachment_file'].each do |a|
       @attachment =@other_asset.attachments.create(:attachment_file => a)
       end
   redirect_to other_assets_path
   else
    render 'new'
    end
end

def update
   @other_asset = OtherAsset.find(params[:id])
   @attachments = @other_asset.attachments.find(params[:id])
   if @other_asset.update_attributes(other_asset_params)
      params[:attachments]['attachment_file'].each do |a|
      @attachment =@other_asset.attachments.create(:attachment_file => a)
      end
     redirect_to other_assets_path
   else
     render 'new'
   end
 end

def edit
     @other_asset = OtherAsset.find(params[:id])
end

other_assets/edit.html.erb

              <%= form_for(@other_asset) do |f| %>
                <%= render 'form', :f => f, :other_asset => @other_asset %>

                      <%#= f.submit "Initiate Asset", :class => "orange_btn" %>
                      <%= f.submit "Update Other Asset", :class => "grey_btn" %>
                      Back

              <% end %>

Help me in these I'm using Rails 4 and carrierwave gem


text:
Q: Automatically detect changes in GCS for BigQuery Now I have a BigQuery table whose data source is from some bucket at GCS(Google Cloud Storage).
The GCS is dynamic constantly with new files added in. So do we have any available mechanisms for BigQuery to automatically detect the changes in GCS and sync with the latest data?
Thanks!

A: There is a very cool beta feature you can use to do that. Check out BigQuery Cloud Storage Transfer. You can schedule transfers run backfill, and much more.
Read "limitations" to see if it can work for you.


text:
Q: Sencha Touch - Scroll Delay on First Touch I have been searching around and it looks like this question has been asked quite a few times in various places with no answers or responses. That means that I can't be the only one experiencing this.
There is always a delay in the scrolling when you try to scroll a list or panel for the first time. After the first time you scroll a list or panel, there is no longer any delay. Is there a way I can simulate this "first touch" in an effort to remove the delay when attempting to scroll a list or panel for the first time?
I've been looking through the ScrollView and Scroller code and have not been able to find a point where anything heavy or expensive is happening on a first touch.
Any help or direction on how to remedy this would be greatly appreciated.
Thanks!

A: You can open the Chrome/Safari developer tools and start profiling("Profiles" tab) to see if there is any JavaScript code that is performing badly and causing the hang.
If it's not code that hangs, it might be a web browser issue (e.g. image cache allocation), for example due to the first time that things dynamically change in your web app.
It's also important to try and compare platforms and see if they have the same issue.
It's also often helpful if you specify the Sencha version (I assume 1.x?) and the platform(s) you've had the issue with. iOS/Android/PC can often react quite differently.


text:
Q: Rename file with a value stored in Variable in Python I have a file and want to rename the file with and get the name from
cellObj.value
    os.rename(r'C:\Users\Com\Downloads\Software 02E - Installed software on a specific computer.xlsx',r'C:\Users\Com\Downloads\OUTPUT.xlsx')

Need change Output by value in Cellobj   (Example value: BPTPC0132)

A: Reading a cell value from a excel file is no problem - from your question I cant get which cell you want to read your filename from so I assume the first cell in your first sheet for now:
import xlrd

xl_workbook = xlrd.open_workbook("insertyourfilepathhere")
sheet_names = xl_workbook.sheet_names()
xl_sheet = xl_workbook.sheet_by_index(0)
cell = xl_sheet.cell(0,0)
output = cell.value

You can then use the output variable for saving your file.

A: This format worked for me
workbook.save(cellObj.value+".xlsx")


text:
Q: Combine two plots in ggplot? I need to create a ggplot that is a column plot overlayed with a line plot.  The line plot shows mean values, while the column plot shows how the mean values relate to benchmark values.  I've managed to create two separate plots in ggplot, but I'm having trouble combining them.
My line plot looks like this:

And is created using this code:
benchMarkLine <- ggplot(UEQScores, aes(x=Scale, y=Score, group=1)) +
  geom_line(size = 1.4, colour = "black") +
  geom_point(size = 2.4, colour = "black") +
  scale_y_continuous(name = "Score", breaks = seq(0, 2.5, 0.25), limits = c(0, 2.5)) +
  scale_x_discrete(name = "Scale") +
  ggtitle("Mean Scores") +
  theme_bw() + # Set black and white theme +
  theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
        panel.grid.major = element_blank(), # Turn off major gridlines
        panel.grid.minor = element_blank(), # Turn off minor gridlines
        axis.title.x = element_text(size=10),
        axis.text.x = element_text(angle=30, vjust=0.6),
        axis.title.y = element_text(size=10))
benchMarkLine

My Column plot looks like this:

And was created with the following code:
benchmarkColPlot <- ggplot(benchmark_long, aes(x=factor(Scale, scaleLevels), y=value, fill=factor(cat, bmLevels))) +
  geom_col(position="fill") +
  scale_fill_manual(values = bmColours) +
  scale_y_continuous(name = "Score", breaks = seq(-1.0, 1.0, 0.25), limits = c(-1, 1)) +
  scale_x_discrete(name = "Scale") +
  ggtitle("Benchmark Scores") +
  theme_bw() + # Set black and white theme +
  theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
        panel.grid.major = element_blank(), # Turn off major gridlines
        panel.grid.minor = element_blank(), # Turn off minor gridlines
        axis.title.x = element_text(size=10),
        axis.text.x = element_text(angle=30, vjust=0.6),
        axis.title.y = element_text(size=10),
        legend.title = element_blank())
benchmarkColPlot

How can I combine these two?  I tried inserting geom_line(UEQScores, aes(x=Scale, y=Score, group=1)) + above  geom_col(position="fill") + in the column plot code, but I just get the following error:
Error: `mapping` must be created by `aes()`

How do I combine these two plots?

OK, I've given up on this - I just created the chart in Excel as it seems to be a bit easier for what I'm doing here.


text:
Q: Finding exact isomorphism between finite fields given as quotient rings I have two quotient rings over $\Bbb F := GF(3)$:
$$\Bbb F[x] / (x^3 -x - 1) \qquad \text{and} \qquad \Bbb F[x] / (x^3 -x + 1) .$$
These things I know: Both quotient rings are irreducible, that means they are the same size, so there should exist isomorphism.
I think these two quotient rings should be a field because they have maximum ideals.
I am trying to find function phi to create isomorphism between these quotient rings but not using brute force method. I have tried several ways but they are not "easy" enough. I know that identity element must be mapped to identity element but it didn't help me to find that exact isomorphic function.
Can somebody push me the correct way or give me tip how and where should I look to easily find isomorphism between these quotient rings without necessity to "heavy" computing.

A: Hint $$(-x)^3 - (-x) - 1 = -(x^3 - x + 1) .$$


text:
Q: Migrate OS and files from one VM to another (Oracle VirtualBox) I recently created a VM for work, Windows 10, 6GB RAM, 50GB harddrive. In this VM there are configurations for forward proxies in IIS and some other complex configurations I really do not want to have to go through again, the problem is though that the 50GB harddrive just wasn't big enough, now the VM crashes due to the lack of memory.
Is there a way I can copy everything from my current VM to a new one (already created with a 90GB HDD)? I really don't want to have to configure a new instance of Windows so I can work off it.
Even if someone could post a link pointing me in the right direction, that would be really helpful.

A: The Virtual Box machine lives in a folder on your host machine. Identify that folder.  It has the machine file and associated files in that folder.
Copy the entire folder to your other computer and now you can run Virtual Box on the other computer and open the machine file.
I do this whenever I get a new computer - that is, copy the machine folders to the new computer (VMware in my own case).
Make sure you provide enough space on the new machine for the Windows 10 machine. I allow a minimum of 100GB.
This should all work fine.
Here is a Virtual Box support article.
Move VBOX machine

If you intend to use the VM under Virtualbox, just copy the guest's
files and folders to the new computer and register the VM's .vbox file
with Virtualbox.


text:
Q: Using the BitBucket API, list which branches have all content in master and which dont I have a bitbucket server which has 100's of branches. I would like to separate the branches which contain code already on the master branch, and those that dont.
The only way I've thought to get the info would be to get a list of branches:
https://<bitbucket host>/rest/api/1.0/projects/<project>/repos/<MyRepo>/branches

and get the head of each branch
and see whether the commit exists in the list of commits from master:
https://<bitbucket host>/rest/api/1.0/projects/<project>/repos/<MyRepo>/commits?branch=master&limit=1000'
This is extremely slow. Can anybody think of a better way of doing this? Basically I'm hoping to identify all branches which have been added into master and so can be deleted somewhat safely.
Im thinking that I want the equivalent of:
for each branch:
  git rev-list --left-right --count origin/master...origin/FOO

Thanks in advance

A: What you can do first is get the list of all branches available in that particular repository using API call and make it into a python list. Since you have 100's of branches and also there is paging, try to loop the curl by iterating the page value until the obtained response is empty.
curl --url "https://api.bitbucket.org/2.0/repositories/workspace/repository_name/refs/branches?pagelen=100&page={Iterate}" --user username:password --request GET --header "Accept: application/json"

Later there is an API available to check if all the commits in the source branch is available in destination branch.
curl --url "https://api.bitbucket.org/2.0/repositories/workspace/repository_name/commits/source_branch?exclude=destination_branch" --user username:password --request GET --header "Accept: application/json"

So, you could have your source as master and iterate all other branches as destination and get the response. Based on the response if its empty or not, you can categorize the branches that has all the contents in master and that don't have the content.


text:
Q: Need to speedup PERL script(Takes 1 sec for every Row to input) This Perl script below that takes 1 sec per row to insert, which makes it quite inefficient when there are a lot of rows to be inserted. If the input file has over 1,000,000 rows, this script will take approx. 12 days to insert.
Sample Data(Rows)
/mnt/SYN/TEST-Dropbox/Documents/TempBM/10-07-19.docx
/mnt/SYN/CLIENT-DROPBOX-GSUITE/Dropbox-TEST/My Mac (TEST-iMac-Pro.local)/Documents/TempBM/10-07-19.docx

/mnt/SYN/TEST-Dropbox/Documents/TO BE TRANSCRIBED LATER/LASTNAME, FIRSTNAME, Tape 2 (Inaudible)/LASTNAME, FIRSTNAME, TAPE 2 SIDE B (Inaudible).mp3
/mnt/SYN/CLIENT-SYNOLOGY/A. TO BE TRANSCRIBED/*TO BE TRANSCRIBED LATER/LASTNAME, FIRSTNAME, Tape 2 (Inaudible)/LASTNAME, FIRSTNAME, TAPE 2 SIDE B (Inaudible).mp3
/mnt/SYN/CLIENT-SYNOLOGY/DropboxBackup/*TO BE TRANSCRIBED LATER/LASTNAME, FIRSTNAME, Tape 2 (Inaudible)/LASTNAME, FIRSTNAME, TAPE 2 SIDE B (Inaudible).mp3
/mnt/SYN/CLIENT-DROPBOX-GSUITE/Dropbox-TEST/My Mac (TEST-iMac-Pro.local)/Documents/TO BE TRANSCRIBED LATER/LASTNAME, FIRSTNAME, Tape 2 (Inaudible)/LASTNAME, FIRSTNAME, TAPE 2 SIDE B (Inaudible).mp3

Script
use strict;
use warnings;
use DateTime;
use DBI;

my $inputfile = shift || "-1";
my $startline = shift || "-1";
my $endline = shift || "-1";

if (($inputfile eq "-1") || ($startline eq "-1") || ($endline eq "-1") ){
        print "USAGE: $0 <name_of_file.txt> START_LINE_NUMBER END_LINE_NUMBER\n";
}

my $group_id = 1;
my $linecounter = 0;
my $dsn = "DBI:MariaDB:Potato1";
my $username = "root";
my $password = "";

my %attr = ( PrintError=>1, RaiseError=>1);
my $dbh = DBI->connect($dsn, $username, $password, \%attr);
print "Connected to MYSQL database";

my $sql = "INSERT INTO GMCfiles_tbl(file_id, file_add_date, group_id, filename, status, status_author, status_date) VALUES (?, ?, ?, ?, ?, ?, ?)";
my $stmt = $dbh->prepare($sql);
open(INFILE, "< $inputfile") or die "Could NOT open $inputfile";

while(<INFILE>) {
    my $data = $_;
    $linecounter++;
        if (length($data) < 5) {
            $group_id++;
            sleep 2;
        } else {
            my $file_add_date = DateTime->now;
            my $filename = $data;
            my $status = "New";
            my $status_author="";
            my $status_date = DateTime->now;

            if ( ($linecounter >= $startline) && ($linecounter <= $endline) ) {
                if ($stmt->execute($linecounter, $file_add_date, $group_id, $filename, $status, $status_author, $status_date)){
                    print "Row inserted successfully LINE $linecounter -- GROUP $group_id\n";
                }
                if ( ($linecounter > 0) && (($linecounter % 10) == 0) ) {
                    print "We're processing LINE $linecounter\n";
                }
            }
        }
}

close(INFILE);
$stmt->finish();
$dbh->disconnect;

As this script will run for days. Can someone point out a way to increase efficiency?

A: This problem appears to have a trivial solution. You have this in your code:
if (length($data) < 5) {
    $group_id++;
    sleep 2;

The function sleep will sleep (wait, pause) the number of seconds given as argument. In your case, 2 seconds. This applies to all lines shorter than 5 characters, given the if-clause.
Remove the sleep and see if that solves your problem.


text:
Q: question on Proj If $X$ is a projective variety with homogeneous coordinate ring $S(X)$, is it true that $$\text{Proj}(S(X)) \cong X$$
I think I'm missing some key point in the understanding here.

A: This is perfectly correct, except that $X$ only has a homogeneous coordinate ring after you fix an embedding $X\subseteq\Bbb P^n$. For different embeddings, the homogeneous coordinate rings can be nonisomorphic. One common example for this is the Veronese embedding: Take a degree $d$ hypersurface $X\subseteq\Bbb P^n$. Its image under the $d$-th Veronese $\nu_d:\Bbb P^n\to \Bbb P^m$ is a hyperplane.


text:
Q: Changing the background color of a div by referencing an external CSS file and property using JavaScript I would like to reference a CSS file and take property from that file and using in a div element.
var divVar = document.getElementById("change");
var externalCSSSource = document.getComputedStyle("https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.4/ace/theme/monokai");
var externalCSSProperty = externalCSSSource.getPropertyValue('.ace-monokai');

divVar.style.backgroundColor = externalCSSProperty;

This code doesn't work. I might not be referencing the property correctly.


text:
Q: CSS List Drop Down Menu I am creating a simple drop down menu using css.

Projects

Project 1

Project 2

What I can't figure out is, how can I get the anchor text "Projects" to change it's background correctly to indicate you're browsing under that list.
If I apply a background effect to li#base,
li#base:hover {
    background: #4b4b4b;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    -khtml-border-radius: 4px;
}

I get this undesired background if I am hovering over "Project 1" or "Project 2":
undesired
The image below is how I am wanting it to look, but this is with the hover pseudoclass applied to the anchor instead of li#base (which will only stay highlighted when I am over the link and not the whole list):
desired
I tried to present this in the simplest way I could think of...

A: You're setting the radius of all 4 corners. You want a rounded corner on just top right and top left.
-webkit-border-top-left-radius: 4px;
-webkit-border-top-right-radius: 4px;
-moz-border-radius-topleft: 4px;
-moz-border-radius-topright: 4px;
border-top-left-radius: 4px;
border-top-right-radius: 4px;


text:
Q: express route wildcard both sides I want each route containing the phrase Privacy to be rendered the same.
So I used http://forbeslindesay.github.io/express-route-tester to make sure:
/(.*)Privacy(.*)
Should work.
However - the following code still gets me 404 on valid examples:
/Privacy
/aaaPrivacy
/aaaPrivacyaa
var express = require('express');
var router = express.Router();

router.get('/(.*)Privacy(.*)', function(req, res) {
    res.render('privacy', {'isPrivacy': true});
});

module.exports = router;


text:
Q: DLL shared memory problems with different session, service and user session first, Thank you read this :)
I use DLL shared Memory and using interlocked~ functions. (Win 7)
DLL loaded by service exe and user app exe.
you know, service session is 0, user session is 1 so different.
if DLL's shared memory value changed by user app exe, not reflected service's DLL shared memory value.
is there a way to sync service and user app's DLL shared memory?

A: Shared sections don't work across session boundaries any more. Microsoft considered this a security problem and deliberately broke the feature, quite some time ago if memory serves. I believe each session now sees its own private copy of the section.
However memory mapped files (MMFs) work fine, and I use this in place of shared sections now. The only downer is that globally-available MMFs have to be created with high privilege, so I use a service to create the MMF.

A: Try using global shared memory.  Microsoft's documentation says:

Prefixing the file mapping object names with "Global\" allows
  processes to communicate with each other even if they are in different
  terminal server sessions.

A: Don't forget that the credentials also plays a role when sharing memory accross sessions.

This requires that the first process must have the SeCreateGlobalPrivilege privilege


text:
Q: Setting Java 1.6 as the default on Mac OS X 10.5.8 How can I set Java 1.6 to be the default for my MacBook Pro Intel Core 2 Duo with OS X 10.5.8? I have installed the latest software update, and dragged the Java SE 6 64-bit choice to the top in the "Java Preferences" application (and even rebooted), but still, on the command line, java -version responds with:
java version "1.5.0_24"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_24-b02-357-9M3165)
Java HotSpot(TM) Client VM (build 1.5.0_24-149, mixed mode, sharing)

Any ideas?

A: There are symbolic link in /System/Library/Frameworks/JavaVM.framework
They point to a specific version in the Versions sub folder.
I have had these links breaking on occasion.
AFAICT there is a Current link which points to the Current JRE and a CurrentJDK.
Verify if all the links are pointing somewhere logical. Aparently the Java configlet does something but the chains of links gets broken somewhere else.
Sorry I wish I could be of more help, but it is all rather mysterious to me. I have always been able to  fix it, but it was not pretty.

A: For temporal changes:
export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Home/


text:
Q: creating Keyspace I am trying to access cassandra from erlang, as a test I am trying to create a new keyspace. I do it as follows:
1> rr(cassandra_thrift).
[authenticationException,authenticationRequest,
 authorizationException,cfDef,column,columnDef,
 columnOrSuperColumn,columnParent,columnPath,counterColumn,
 counterSuperColumn,cqlMetadata,cqlResult,cqlRow,deletion,
 endpointDetails,indexClause,indexExpression,
 invalidRequestException,keyCount,keyRange,keySlice,ksDef,
 mutation,notFoundException,schemaDisagreementException,
 slicePredicate,sliceRange,superColumn|...]

2> {ok,C1}=thrift_client_util:new("127.0.0.1",9160,thrift_cassandra,[]).
{ok,{tclient,thrift_cassandra,
        {protocol,thrift_binary_protocol,
            {binary_protocol,
                {transport,thrift_buffered_transport,
                    {buffered_transport,
                        {transport,thrift_socket_transport,
                            {data,#Port<0.593>,infinity}},
                        []}},
                true,true}},
        0}}

3> Reply1=thrift_client:call(C1,set_keyspace,["Test_KS"]).
** exception exit: undef
     in function  thrift_cassandra:function_info/2
        called as thrift_cassandra:function_info(set_keyspace,params_type)
     in call from thrift_client:send_function_call/3 (thrift_client.erl, line 70)
     in call from thrift_client:call/3 (thrift_client.erl, line 40)

Am I doing something wrong, or does my erlang not have access to the cassandra functions? How can I fix it?

A: I would use https://github.com/ostinelli/erlcassa over raw Thrift from Erlang.


text:
Q: An almost straight curve with infinite curvature? I played around with computing the curvature of some curves, and found this weird example that is driving me nuts.
Consider the following (Bézier) curve (on a plane, the first point is $[-1,0]$):
$$bez(t) = [-1, 0] (1 - t)^3 + 3 [-1, 0] (1 - t)^2 t + 3 [1, 1] (1 - t) t^2 + [1, 0] t^3$$
If I plot this, the curve looks virtually straight near $t=0$, hence I would expect a low curvature. But if I actually plot the curvature (which I've computed in at least four different ways just to be absolutely certain), it's enormous when getting to the tip.
Now, in part, this does not surprise me. I explicitly constructed the curve to have a cusp at $t=0$. So for $t=0$ I would expect the curvature to be infinite. As it's all (mostly) continuous, I guess I should not be surprised that near $t=0$ the curvature is already going up. And of course, as $t$ is nearing zero, the derivative of arclength w.r.t. $t$ is also dropping to zero, so when graphing curvature as a function of $t$, the singularity gets blown up.
Still, the curve looks awfully straight when actually plotting it, and I do not think any sane person who is just shown the curve (for $t\in[0,\varepsilon]$, with $\varepsilon$ very small) would guess that it had huge curvature. I also tried making the endpoint match $[1,1]$ (so you get a straight line segment for $t\in[0,1]$), and this does in fact have zero curvature (even the endpoints have zero curvature in the limit as $t$ approaches them). So why does my (and probably others') intuition not match the objective result here?
For reference, one of the ways I computed the curvature is as follows (where $[bez'(t), bez''(t)]$ is a $2\times2$ matrix):
$$curvature(t)=\det([bez'(t), bez''(t)])/\|bez'(t)\|^3$$

A: A sane person who is just shown a smooth curve of length $O(\varepsilon)$ will have a very hard time telling it apart from a straight line! The more you zoom in, the harder it is to see the curvature.
Not only does your curve have a cusp at $t=0$, its slope is not constant as it approaches the cusp. Try plotting the slope, $m(t) = y'(t)/x'(t) = (2-3t)/(4-4t)$, against the $x$-coordinate, $x(t)$, over a region close to $t=0$.


text:
Q: How to center flip book before and after flip Im trying to autocenter this flip book on the page so it stays centred when flipped or not. Ive used the flip.js documentation of autoCenter, as well as $("#flipbook").turn("center"); but nothing works. Does anyone know if this can be done? A working example is in the fiddle below:-
http://jsfiddle.net/kmturley/GGea5/1/

                            /*
             * Turn.js responsive book
             */

            /*globals window, document, $*/

            (function () {
                'use strict';

                var module = {
                    ratio: 1.38,
                    init: function (id) {
                        var me = this;

                        // if older browser then don't run javascript
                        if (document.addEventListener) {
                            this.el = document.getElementById(id);
                            this.resize();
                            this.plugins();

                            // on window resize, update the plugin size
                            window.addEventListener('resize', function (e) {
                                var size = me.resize();
                                $(me.el).turn('size', size.width, size.height);
                            });
                        }
                    },
                    resize: function () {
                        // reset the width and height to the css defaults
                        this.el.style.width = '';
                        this.el.style.height = '';

                        var width = this.el.clientWidth,
                            height = Math.round(width / this.ratio),
                            padded = Math.round(document.body.clientHeight * 0.9);

                        // if the height is too big for the window, constrain it
                        if (height > padded) {
                            height = padded;
                            width = Math.round(height * this.ratio);
                        }

                        // set the width and height matching the aspect ratio
                        this.el.style.width = width + 'px';
                        this.el.style.height = height + 'px';

                        return {
                            width: width,
                            height: height
                        };
                    },
                    plugins: function () {
                        // run the plugin
                        $(this.el).turn({
                            gradients: true,
                            acceleration: true
                        });
                        // hide the body overflow
                        document.body.className = 'hide-overflow';
                    }
                };

                module.init('book');
            }());

A: Got it working. I missed putting this autocenter at the bottom of the code:-
            plugins: function () {
                // run the plugin
                $(this.el).turn({
                    gradients: true,
                    acceleration: true,
                    autoCenter: true
                });
                // hide the body overflow
                document.body.className = 'hide-overflow';
            }


text:
Q: Downloads Gallery plugin? I am designing a blog for a software vendor.
They have a number of downloads available, both their own, and also from their clients.
Downloads are usually tools that can be bolted onto the main software products.
They want to have a slick interface to be able to search and download these items.
I am looking for Wordpress plugins that might fit the description?
What we are after, could be something like this, or like this.
i.e. A thumbnail, name of tool, and maybe a user rating (not essential).  Hovering over the tool would provide more info.
Flexible on how it looks and feels, even something similar to Wordpress Plugins directory might work.
Any clear plugin winners out there?
:EDIT:
Sounds like I should be looking at Custom Post Types.
From what I have read so far, looks good, but still looks like I will need to write a fair bit of code to get what I want.
- Would love to be proved wrong --> perhaps there is a custom post template for what I am after?
(I will research further)

A: to do something like this is relatively large as a project so I couldn't really post you the code to do what you exactly want, but you could commission this as a project for someone to help you with just that aspect of the project.
But here are the steps involved to do something like this:
Step 1; Register custom post type
function create_post_type() {
    register_post_type( 'products',
        array(
            'labels' => array(
                'name' => __( 'products' ),
                'singular_name' => __( 'products' )
            ),
        'public' => true,
        'menu_position' => 6,
        'rewrite' => array('slug' => 'products'),
        'supports' => array('title','thumbnail','editor','custom-fields')
        )
    );
}
add_action('init', 'create_post_type');

Codex Link: http://codex.wordpress.org/Function_Reference/register_post_type
Step 2; Display Custom Post type
the below code basically prints your custom post into a page, and has the html markup ready for styling and functioning for jQuery.

<?php
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $post_per_page = 9; // -1 shows all posts & show 3 per line so 9 in total before showing the other pages
    $do_not_show_stickies = 1; // 0 to show stickies
    $args=array(
    'post_type' => 'products',
    'paged' => $paged,
    'posts_per_page' => $post_per_page,
    'order' => 'ASC',
    );
    $temp = $wp_query;  // assign orginal query to temp variable for later use
    $wp_query = null;
    $wp_query = new WP_Query($args);
    if( have_posts() ) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

    <?php $download_link = get_post_meta($post->ID, 'download-link', $single = true); // custom field on post to allow entry of a http link for the download?>

        <?php the_post_thumbnail(array(200,300), array('title'  => trim(strip_tags( $attachment->post_title)), ));?>
        <?php the_title();?>

        <?php the_post_thumbnail(array(200,300), array('title'  => trim(strip_tags( $attachment->post_title)), ));?>
        <a href="<?php echo $download_link ?>"><?php the_title();?>
        <?php the_content();?>

    <?php endwhile; ?>
<?php endif; $wp_query = $temp;  //reset back to original query ?>
<?php wp_reset_query();?>

To show the next and previous pages in a numbered format you can use a plugin such as WP-Pagination to get numbered pages like [1] [2] [3]
Step 3; the jQuery
This is what would take the most time to implement but what you can do is look for a tooltip style plugin or write your own, but if you are writting one yourself all you have to do is is use the div in the above code  and add a .hide() to that;
then when the mouse hovers over a class="trigger" it will .show() that div, the div will hold the information for your mouse over for page sliding effects well that itself is a larger task.
But i hope the above helps you get started on your project.
Here are some jQuery Plugins that will help you along the way;
http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
http://jquery.bassistance.de/tooltip/demo/


text:
Q: WIQL - Get possible values for BoardColumn field I'm trying to read out all column names in an VSO board and can't figure out how to do this.
I'm using the c# wrapper VisualStudioOnline.Api.Rest and the code:
var fieldInfo = _clientWit.GetField("System.BoardColumn").Result;
This only gives me the following info: Name, ReadOnly, ReferenceName, Type and Url.
I'd like to get the names of all columns.