问:
guru meditation error when reading data from ESPAsyncWebServer request parameters
I am working on ESP32, New to this device.

I am currently facing the following error.
when I try to read the data from  request->value().c_str() the serial monitor shows me guru meditation error error
SS of error:

My code:

```<code>server.on("/register", HTTP_POST, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", Register(request->getParam("plain",true)).c_str());
});
</code>```

The function:

```<code>string Register(AsyncWebParameter *request){

  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 250;;
  StaticJsonDocument<bufferSize>  data;
  deserializeJson(data, request->value().c_str()); // facing issue here when request->value().c_str() is called
  const char* name = data["username"];

  return String("Execution complete");
  }
</code>```

I have return simple javascript function to call the API:

function Register() {
const tosend={
      "username":"Mohit",
      "password":"Mohit10#",
      "lastname":"mhatre",
      "firstname":"Mohit"
  };
  const url="http://192.168.2.120/register";

  fetch(url, {
    method: 'post',
    headers: {
      // if you want to set
    },
    body: tosend
  })
    .then(
      function(response) {
        response.json().then(function(data) {
          console.log(data);
        });
      }
    )
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    });
}```

Can someone please help me resolve the issue i am new to this and stuck here from yesterday

答:
I resolved this issue.
As described by Botje in the comment above.
The problem was that Register(request->getParam("plain",true)).c_str() was returning empty results so when i tried to access them the esp it caused issue.

Following are the code changes I made:

Server code:

```<code>  server.on("/register", HTTP_POST, [](AsyncWebServerRequest *request){request->send(200, "text/plain", "");}, NULL, Register);
</code>```

the function

```<code>void Register(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
{
  chipid=ESP.getEfuseMac();

  StaticJsonDocument<200> doc;
  deserializeJson(doc, data);

  doc["device_id"] = (uint16_t)(chipid>>32)+(uint32_t)chipid;

  char jsonBuffer[512];
  serializeJson(doc, jsonBuffer);
  // used the json as required.
}
</code>```

Body:
I am working on ESP32, New to this device.

I am currently facing the following error.
when I try to read the data from  request->value().c_str() the serial monitor shows me guru meditation error error
SS of error:

My code:

server.on("/register", HTTP_POST, [](AsyncWebServerRequest *request) {
    request->send(200, "text/plain", Register(request->getParam("plain",true)).c_str());
});

The function:

string Register(AsyncWebParameter *request){

  const size_t bufferSize = JSON_OBJECT_SIZE(1) + 250;;
  StaticJsonDocument<bufferSize>  data;
  deserializeJson(data, request->value().c_str()); // facing issue here when request->value().c_str() is called
  const char* name = data["username"];

  return String("Execution complete");
  }

I have return simple javascript function to call the API:

function Register() {
const tosend={
      "username":"Mohit",
      "password":"Mohit10#",
      "lastname":"mhatre",
      "firstname":"Mohit"
  };
  const url="http://192.168.2.120/register";

  fetch(url, {
    method: 'post',
    headers: {
      // if you want to set
    },
    body: tosend
  })
    .then(
      function(response) {
        response.json().then(function(data) {
          console.log(data);
        });
      }
    )
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    });
}

Can someone please help me resolve the issue i am new to this and stuck here from yesterday

Body:
I resolved this issue.
As described by Botje in the comment above.
The problem was that Register(request->getParam("plain",true)).c_str() was returning empty results so when i tried to access them the esp it caused issue.

Following are the code changes I made:

Server code:

  server.on("/register", HTTP_POST, [](AsyncWebServerRequest *request){request->send(200, "text/plain", "");}, NULL, Register);

the function

void Register(AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total)
{
  chipid=ESP.getEfuseMac();

  StaticJsonDocument<200> doc;
  deserializeJson(doc, data);

  doc["device_id"] = (uint16_t)(chipid>>32)+(uint32_t)chipid;

  char jsonBuffer[512];
  serializeJson(doc, jsonBuffer);
  // used the json as required.
}


来源: stackexchange

问:
Rails 6.0.1 - Trix Editor Parameters not transmitted from form
The added or changed data from a Trix editor field is not submitted/ transmitted.

```<code><%= form_with(model: @comment, local: true) do |form| %>
  <div class="form-group">
  <h4>Titel</h4>
  <%= form.text_field :header, class: "form-control border-top-0 border border-right-0 border-left-0 rounded-0 p-0" %>

  <br/>
  <h4>Inhalt</h4>
  <%= form.trix_editor :comment %>

  <%= form.text_field :tonie_id, value: tonie_id, hidden: true %>
  <%= form.text_field :user_id, value: current_user.id, hidden: true %>
  <%= form.check_box :private %> privater Kommentar

  <br/>

  <%= form.submit "speichern ",class: 'btn btn-success' %>
</div>
<% end %>
</code>```

looking into my logs I get the following:

```<code>Parameters: {"authenticity_token"=>"xxxx", "tcomment"=>{"header"=>"title", "comment"=>"", "tonie_id"=>"49", "user_id"=>"1", "private"=>"0"}, "commit"=>"speichern "}
</code>```

Any idea, what could be wrong?

答:
This may happen if there are multiple forms of the same model type on your page. I also encountered the same problem. I think it may be caused by duplicate ID.

When multiple rich text editors of the same model type appear on the same page, only the first one can be used normally. After other windows input content, they will be filled into the hidden tags of the first window, so when submitting , The data is null

Sorry i don't know how to express my thoughts in english, hope you understand my speech

ContentLicense: CC BY-SA 4.0

Body:
The added or changed data from a Trix editor field is not submitted/ transmitted.

<%= form_with(model: @comment, local: true) do |form| %>

Titel

  <%= form.text_field :header, class: "form-control border-top-0 border border-right-0 border-left-0 rounded-0 p-0" %>

Inhalt

  <%= form.trix_editor :comment %>

  <%= form.text_field :tonie_id, value: tonie_id, hidden: true %>
  <%= form.text_field :user_id, value: current_user.id, hidden: true %>
  <%= form.check_box :private %> privater Kommentar

  <%= form.submit "speichern ",class: 'btn btn-success' %>

<% end %>

looking into my logs I get the following:

Parameters: {"authenticity_token"=>"xxxx", "tcomment"=>{"header"=>"title", "comment"=>"", "tonie_id"=>"49", "user_id"=>"1", "private"=>"0"}, "commit"=>"speichern "}

Any idea, what could be wrong?


问:
Editing then combining large number of CSV in Mac terminal
I have a folder of ~8400 CSV files that are large:

2 columns

~17k lines

I tired just merging it all in Terminal with cat, and got a 3.2 GB CSV file that Excel just laughed at when I tried to import. So I need to get these smaller before I merge them so I can start messing with the data in Excel. Fortunately, I need only a small subset of the data.

Basically, it is an hourly time-series going back to Jan 2018 (first column is date/time), but I only need the end-of-day number for the last 90 days

Extract the last ~2160 lines of each CSV (90*24)

I also need a delimiter to show me where each table begins once merged, so after extracting the last ~2160 lines, I want to insert in a line at the beginning of each with the filename without extension.

Delete all but the last record of each day.

By my math, this leaves me with under 800k lines, which Excel should be able to open.

I was thinking sed could do all this, then cat to merge the new edited files, but it’s way beyond my abilities. Any help much appreciated. Thanks.

答:
Here's an extremely simplified version that you can extrapolate from.

I have five files in my directory:

```<code>$ ls folder-with-files/
a   b   c   d   e
</code>```

Each file has five rows.

```<code>$ cat folder-with-files/a
1
2
3
4
5

$ cat folder-with-files/b
10
11
12
13
14
15
</code>```

etc.

Now let's say I want the last two lines of each file. The key there is the tail command. Before that I'll echo out the file name according to your spec.

```<code>$ for f in folder-with-files/*; do echo "FILE: " $f; tail -2 $f; done > big.csv
</code>```

Result:

```<code>$ cat big.csv
FILE:  folder-with-files/a
4
5
FILE:  folder-with-files/b
14
15
FILE:  folder-with-files/c
24
25
FILE:  folder-with-files/d
34
35
FILE:  folder-with-files/e
44
45
</code>```

Body:
Here's an extremely simplified version that you can extrapolate from.

I have five files in my directory:

$ ls folder-with-files/
a   b   c   d   e

Each file has five rows.

$ cat folder-with-files/a
1
2
3
4
5

$ cat folder-with-files/b
10
11
12
13
14
15

etc.

Now let's say I want the last two lines of each file. The key there is the tail command. Before that I'll echo out the file name according to your spec.

$ for f in folder-with-files/*; do echo "FILE: " $f; tail -2 $f; done > big.csv

Result:

$ cat big.csv
FILE:  folder-with-files/a
4
5
FILE:  folder-with-files/b
14
15
FILE:  folder-with-files/c
24
25
FILE:  folder-with-files/d
34
35
FILE:  folder-with-files/e
44
45


问:
Memory barriers on entry and exit of Java synchronized block
I came across answers, here on SO, about Java flushing the work copy of variables within a synchronized block during exit. Similarly it syncs all the variable from main memory once during the entry into the synchronized section.

However, I have some fundamental questions around this:

What if I access mostly non-volatile instance variables inside my synchronized section? Will the JVM automatically cache those variables into the CPU registers at the time of entering into the block and then carry all the necessary computations before finally flushing them back?

I have a synchronized block as below:
The underscored variables _ e.g. _callStartsInLastSecondTracker are all instance variables which I heavily access in this critical section.

```<code>public CallCompletion startCall()
{
  long currentTime;
  Pending pending;
  synchronized (_lock)
  {
    currentTime = _clock.currentTimeMillis();
    _tracker.getStatsWithCurrentTime(currentTime);
    _callStartCountTotal++;
    _tracker._callStartCount++;
    if (_callStartsInLastSecondTracker != null)
      _callStartsInLastSecondTracker.addCall();
    _concurrency++;
    if (_concurrency > _tracker._concurrentMax)
    {
      _tracker._concurrentMax = _concurrency;
    }
    _lastStartTime = currentTime;
    _sumOfOutstandingStartTimes += currentTime;
    pending = checkForPending();
  }
  if (pending != null)
  {
    pending.deliver();
  }
  return new CallCompletionImpl(currentTime);
}
</code>```

Does this mean that all these operations e.g. +=, ++, > etc. requires the JVM to interact with main memory repeatedly? If so, can I use local variables to cache them (preferably stack allocation for primitives) and perform operations and in the end assign them back to the instance variables? Will that help to optimise performance of this block?

I have such blocks in other places as well. On running a JProfiler, it has been observed that most of the time threads are in WAITING state and throughput is also very low. Hence the optimisation necessity.

Appreciate any help here.

答:
(I don't know Java that well, just the underlying locking and memory-ordering concepts that Java is exposing.  Some of this is based on assumptions about how Java works, so corrections welcome.)

I'd assume that the JVM can and will optimize them into registers if you access them repeatedly inside the same synchronized block.

i.e. the opening { and closing } are memory barriers (acquiring and releasing the lock), but within that block the normal rules apply.

The normal rules for non-volatile vars are like in C++: the JIT-compiler can keep private copies / temporaries and do full optimization.  The closing } makes any assignments visible before marking the lock as released, so any other thread that runs the same synchronized block will see those changes.

But if you read/write those variables outside a synchronized(_lock) block while this synchronized block is executing, there's no ordering guarantee and only whatever atomicity guarantee Java has.  Only volatile would force a JVM to re-read a variable on every access.

most of the time threads are in WAITING state and throughput is also very low. Hence the optimisation necessity.

The things you're worried about wouldn't really explain this.  Inefficient code-gen inside the critical section would make it take somewhat longer, and that could lead to extra contention.

But there wouldn't be a big enough effect to make most threads be blocked waiting for locks (or I/O?) most of the time, compared to having most threads actively running most of the time.

@Kayaman's comment is most likely correct: this is a design issue, doing too much work inside one big mutex.  I don't see loops inside your critical section, but presumably some of those methods you call contain loops or are otherwise expensive, and no other thread can enter this synchronized(_lock) block while one thread is in it.

The theoretical worst case slowdown for store/reload from memory (like compiling C in anti-optimized debug mode) vs. keeping a variable in a register would be for something like while (--shared_var >= 0) {}, giving maybe a 6x slowdown on current x86 hardware.  (1 cycle latency for dec eax vs. that plus 5 cycle store-forwarding latency for a memory-destination dec).  But that's only if you're looping on a shared var, or otherwise creating a dependency chain through repeated modification of it.

Note that a store buffer with store-forwarding still keeps it local to the CPU core without even having to commit to L1d cache.

In the much more likely case of code that just reads a var multiple times, anti-optimized code that really loads every time can have all those loads hit in L1d cache very efficiently.  On x86 you'd probably barely notice the difference, with modern CPUs having 2/clock load throughput, and efficient handling of ALU instructions with memory source operands, like cmp eax, [rdi] being basically as efficient as cmp eax, edx.

(CPUs have coherent caches so there's no need for flushing or going all the way to DRAM to ensure you "see" data from other cores; a JVM or C compiler only has to make sure the load or store actually happens in asm, not optimized into a register.  Registers are thread-private.)

But as I said, there's no reason to expect that your JVM is doing this anti-optimization inside synchronized blocks.  But even if it were, it might make a 25% slowdown.

Body:
I came across answers, here on SO, about Java flushing the work copy of variables within a synchronized block during exit. Similarly it syncs all the variable from main memory once during the entry into the synchronized section.

However, I have some fundamental questions around this:

What if I access mostly non-volatile instance variables inside my synchronized section? Will the JVM automatically cache those variables into the CPU registers at the time of entering into the block and then carry all the necessary computations before finally flushing them back?

I have a synchronized block as below:
The underscored variables _ e.g. _callStartsInLastSecondTracker are all instance variables which I heavily access in this critical section.

public CallCompletion startCall()
{
  long currentTime;
  Pending pending;
  synchronized (_lock)
  {
    currentTime = _clock.currentTimeMillis();
    _tracker.getStatsWithCurrentTime(currentTime);
    _callStartCountTotal++;
    _tracker._callStartCount++;
    if (_callStartsInLastSecondTracker != null)
      _callStartsInLastSecondTracker.addCall();
    _concurrency++;
    if (_concurrency > _tracker._concurrentMax)
    {
      _tracker._concurrentMax = _concurrency;
    }
    _lastStartTime = currentTime;
    _sumOfOutstandingStartTimes += currentTime;
    pending = checkForPending();
  }
  if (pending != null)
  {
    pending.deliver();
  }
  return new CallCompletionImpl(currentTime);
}

Does this mean that all these operations e.g. +=, ++, > etc. requires the JVM to interact with main memory repeatedly? If so, can I use local variables to cache them (preferably stack allocation for primitives) and perform operations and in the end assign them back to the instance variables? Will that help to optimise performance of this block?

I have such blocks in other places as well. On running a JProfiler, it has been observed that most of the time threads are in WAITING state and throughput is also very low. Hence the optimisation necessity.

Appreciate any help here.


问:
How to write QuerySet syntax let field contains items in a list?
I know in Django I can use __icontains to query database use LIKE.

```<code>name = "joe"

Q(name__icontains=name)
</code>```

but if I have a list:

```<code>name_list = ["joe", "klare"]
</code>```

How can I write the QuerySet syntax let the name contains "joe" or "klare"?

答:
By creating multiple conditions:</p>

```<code>filters = Q()
for name in name_list:
    filters |= Q(name__icontains=name)

queryset.filter(filters)
</code>```

Body:
I know in Django I can use __icontains to query database use LIKE.

name = "joe"

Q(name__icontains=name)

but if I have a list:

name_list = ["joe", "klare"]

How can I write the QuerySet syntax let the name contains "joe" or "klare"?

Body:
By creating multiple conditions:

filters = Q()
for name in name_list:
    filters |= Q(name__icontains=name)

queryset.filter(filters)


问:
Adaptive icons not working in Oreo - why?
I'm trying to add a custom icon from an SVG file to my Android app by right-clicking on the res folder -> new -> Image asset. I have selected the default options, using my SVG but I can't see the icon when I'm running the app.
I have tried to do a clean project before installing it and also an invalidate cache and restart and the result is the same.

I've also realized that mipmap-anydpi-v26/ic_launcher.xml shows the default icon I'm seeing when my app is installed. This file contains:

```<code><?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@drawable/ic_launcher_background"/>
    <foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>
</code>```

when clicking on the @drawable/ic_launcher_foreground I get to locations to open: drawable and drawable-24. The first one shows my recently updated icon, but drawable-24 shows the default Android icon I see when installing my app.

Is there anything I'm missing here? Anything else I have to do?

Thanks!

答: Well, in the end, I just created the icons from a PNG instead an SVG and it works great.</p>

Body:
I'm trying to add a custom icon from an SVG file to my Android app by right-clicking on the res folder -> new -> Image asset. I have selected the default options, using my SVG but I can't see the icon when I'm running the app.
I have tried to do a clean project before installing it and also an invalidate cache and restart and the result is the same.

I've also realized that mipmap-anydpi-v26/ic_launcher.xml shows the default icon I'm seeing when my app is installed. This file contains:

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
    <background android:drawable="@drawable/ic_launcher_background"/>
    <foreground android:drawable="@drawable/ic_launcher_foreground"/>
</adaptive-icon>

when clicking on the @drawable/ic_launcher_foreground I get to locations to open: drawable and drawable-24. The first one shows my recently updated icon, but drawable-24 shows the default Android icon I see when installing my app.

Is there anything I'm missing here? Anything else I have to do?

Thanks!


问:
Curly brace is missing in a json, while saving the json in azurestorage blob using rest api
I have tried to save a json which has the following json with a special character 'ø'.

The json is {"username":"Jøhn"}.

I have used this api to save the json in azure blob ==>  https://${storageAccountName}.blob.core.windows.net/${containerName}/${name}${sasToken}

The json saved in the blob container is {"username":"Jøhn"  (LAST CURLY BRACE IS MISSING).

The headers used in rest api is :  'x-ms-blob-type': 'BlockBlob',
          'x-ms-date': date,
          'x-ms-version': '2016-05-31',
          'Content-Type': 'text/plain',
          'Content-Length': value.length

The code is :

```<code>const date = (new Date()).toUTCString();

const sasToken = await Storage.GenerateSasTokenIfExpired();

const endpoint = `https://${storageAccountName}.blob.core.windows.net/${containerName}/${name}${sasToken}`;

return backOff(() => new Promise((resolve, reject) => {
  request.put({
    'body': value,
    'headers': {
      'x-ms-blob-type': 'BlockBlob',
      'x-ms-date': date,
      'x-ms-version': '2016-05-31',
      'Content-Type': 'text/plain',
      'Content-Length': value.length
    },
    'url': endpoint
  }, function (err, result) {
    if (err) {
      return reject(err);
    }
    if (result.statusCode !== 201) {
      return reject(result.body);
    }
    return resolve(result);
  });
}), AzureBackOff.retryPolicy);
</code>```

答:
Your suspicion is correct. Basically the issue is coming because of value.length of a string containing special character (ø).

When I ran the following code:

```<code>const value = '{"username":"Jøhn"}';
console.log(value);
console.log('value.length', value.length);//Prints 19
const buffer = Buffer.from(value);
console.log('buffer length', buffer.length);//Prints 20
</code>```

Because the content-length is being passed as 19, one less character is sent and that's why you're seeing this issue.

Please change the following line of code:

```<code>'Content-Length': value.length
</code>```

to

```<code>'Content-Length': Buffer.from(value).length
</code>```

and that should fix the problem.

Body:
I have tried to save a json which has the following json with a special character 'ø'.

The json is {"username":"Jøhn"}.

I have used this api to save the json in azure blob ==>  https://${storageAccountName}.blob.core.windows.net/${containerName}/${name}${sasToken}

The json saved in the blob container is {"username":"Jøhn"  (LAST CURLY BRACE IS MISSING).

The headers used in rest api is :  'x-ms-blob-type': 'BlockBlob',
          'x-ms-date': date,
          'x-ms-version': '2016-05-31',
          'Content-Type': 'text/plain',
          'Content-Length': value.length

The code is :

const date = (new Date()).toUTCString();

const sasToken = await Storage.GenerateSasTokenIfExpired();

const endpoint = `https://${storageAccountName}.blob.core.windows.net/${containerName}/${name}${sasToken}`;

return backOff(() => new Promise((resolve, reject) => {
  request.put({
    'body': value,
    'headers': {
      'x-ms-blob-type': 'BlockBlob',
      'x-ms-date': date,
      'x-ms-version': '2016-05-31',
      'Content-Type': 'text/plain',
      'Content-Length': value.length
    },
    'url': endpoint
  }, function (err, result) {
    if (err) {
      return reject(err);
    }
    if (result.statusCode !== 201) {
      return reject(result.body);
    }
    return resolve(result);
  });
}), AzureBackOff.retryPolicy);

Body:
Your suspicion is correct. Basically the issue is coming because of value.length of a string containing special character (ø).

When I ran the following code:

const value = '{"username":"Jøhn"}';
console.log(value);
console.log('value.length', value.length);//Prints 19
const buffer = Buffer.from(value);
console.log('buffer length', buffer.length);//Prints 20

Because the content-length is being passed as 19, one less character is sent and that's why you're seeing this issue.

Please change the following line of code:

'Content-Length': value.length

to

'Content-Length': Buffer.from(value).length

and that should fix the problem.


问:
Unable to add user to group with ldap api when there is a slash on group DN Name
Although this code functions well with groups and users that do not have a slash in their Distringuished name, it appears that i have a problem when a slash exists in the DN name of the group.

```<code>        String groupDNName =
            "CN=test/group,OU=TestOU,OU=Test,DC=TestDC,DC=test,DC=test";
        Set<String> usersToAddDN = new HashSet();

        usersToAddDN.add("CN=testUser,OU=TestOU,OU=TestO,DC=TestDC,DC=test,DC=test");

        //Add Users
        if (usersToAddDN != null && !usersToAddDN.isEmpty()) {

            for (String userDistinguishedName :
                 usersToAddDN) { //Add to  group

                    ModificationItem[] mods = new ModificationItem[1];
                    mods[0] =
                            new ModificationItem(DirContext.ADD_ATTRIBUTE,
                                                 new BasicAttribute("member",
                                                                    userDistinguishedName));

                    ctx.modifyAttributes(groupDNName,
                                         mods); //Add user to group
                                         }}
</code>```

I get the following error:

javax.naming.NamingException: [LDAP: error code 1 - 000020D6:
  SvcErr: DSID-031007DB, problem 5012 (DIR_ERROR), data 0 ]; remaining
  name 'CN=test/group,OU=TestOU,OU=Test,DC=TestDC,DC=test,DC=test'

Does anyone have any clues on this?

答:
I managed to find a work out for this. It seems that there was indeed a problem with the slash.

Instead of inserting a String for the group DN name in the modifyAttributes , I inserted a Name object.

It worked after that:

```<code> Name name = new CompositeName().add(groupDNName);

                ctx.modifyAttributes(name,
                                     mods); //Add user to group
</code>```

Body:
Although this code functions well with groups and users that do not have a slash in their Distringuished name, it appears that i have a problem when a slash exists in the DN name of the group.

        String groupDNName =
            "CN=test/group,OU=TestOU,OU=Test,DC=TestDC,DC=test,DC=test";
        Set<String> usersToAddDN = new HashSet();

        usersToAddDN.add("CN=testUser,OU=TestOU,OU=TestO,DC=TestDC,DC=test,DC=test");

        //Add Users
        if (usersToAddDN != null && !usersToAddDN.isEmpty()) {

            for (String userDistinguishedName :
                 usersToAddDN) { //Add to  group

                    ModificationItem[] mods = new ModificationItem[1];
                    mods[0] =
                            new ModificationItem(DirContext.ADD_ATTRIBUTE,
                                                 new BasicAttribute("member",
                                                                    userDistinguishedName));

                    ctx.modifyAttributes(groupDNName,
                                         mods); //Add user to group
                                         }}

I get the following error:

javax.naming.NamingException: [LDAP: error code 1 - 000020D6:
  SvcErr: DSID-031007DB, problem 5012 (DIR_ERROR), data 0 ]; remaining
  name 'CN=test/group,OU=TestOU,OU=Test,DC=TestDC,DC=test,DC=test'

Does anyone have any clues on this?

Body:
I managed to find a work out for this. It seems that there was indeed a problem with the slash.

Instead of inserting a String for the group DN name in the modifyAttributes , I inserted a Name object.

It worked after that:

 Name name = new CompositeName().add(groupDNName);

                ctx.modifyAttributes(name,
                                     mods); //Add user to group


问:
Create file event to the SAS batch
I need to create new file event to the SAS batch, which will check if nightly batch has finished working and after it my SAS job will run.
To do that i am checking table:

```<code>select * from table where date=sysdate
</code>```

And if it has record that means that nightly batch is finished running.

Has anybody any idea how to create file event with this condition?

答:
Maybe you are meaning selective structure:</p>

```<code>proc sql noprint;
    select * from table where date=sysdate;
quit;

%if &sysnobs %then %do;
    my sas job...
%end;
</code>```

Title: Create file event to the SAS batch

Body:
I need to create new file event to the SAS batch, which will check if nightly batch has finished working and after it my SAS job will run.
To do that i am checking table:

select * from table where date=sysdate

And if it has record that means that nightly batch is finished running.

Has anybody any idea how to create file event with this condition?

Body:
Maybe you are meaning selective structure:

proc sql noprint;
    select * from table where date=sysdate;
quit;

%if &sysnobs %then %do;
    my sas job...
%end;


问:
Access a subclass from an interface
I have an arraylist of an interface named Component. There is another class named Frame that extends component as follows: Component (interface) > AbstractComponent (abstract class) > AbstractContainer (abstract class) > OrganizedContainer (class) > Frame (class)

Everything in the component arraylist goes to a renderer to be rendered. I want to be able to access the methods of the Frame object from the AbstractContainer class. Is this possible without declaring the method in the Component interface?

答: The only way to do that is check if the component is of type Frame with component instanceof Frame and then cast the component to Frame.

Title: Access a subclass from an interface


问:
Applescript Tell Application launched by specific user
I am running two Skype on the same computer: one is launched normally and the other one is launched in Terminal under a different user account B.

Then, I want to use Applescript to Tell application "Skype" (which is launched by account B) to do something. How should I specific the instance of Skype that is launched by account B in Applescript?

Many thanks!

miu

答:
I don't think you can. However I have thought of a work-around. Here's the idea. You can target an application several ways, one of them by its bundle identifier. For example to target TextEdit you could do this...

```<code>tell application id "com.apple.TextEdit" to activate
</code>```

With that in mind, your 2 running versions of skype would need to have different bundle ids so you can target them separately. That's not the case right now but you can make that happen. Just duplicate the skype application (make a copy). Then open the package contents of the copy, open the "info.plist" file in there, find the bundle identifier key, and change it to something else. Now you have 2 versions of skype with different bundle ids which means you can target them separately.

I checked this using TextEdit. I made a duplicate copy and set its bundle id to "com.apple.myTextEdit". I opened both applications and could target them separately. So user B could use "com.apple.myTextEdit" and the normal user would use "com.apple.TextEdit"... or vice versa.

It's not an ideal solution but it would work.

ContentLicense: CC BY-SA 3.0

Body:
I don't think you can. However I have thought of a work-around. Here's the idea. You can target an application several ways, one of them by its bundle identifier. For example to target TextEdit you could do this...

tell application id "com.apple.TextEdit" to activate

With that in mind, your 2 running versions of skype would need to have different bundle ids so you can target them separately. That's not the case right now but you can make that happen. Just duplicate the skype application (make a copy). Then open the package contents of the copy, open the "info.plist" file in there, find the bundle identifier key, and change it to something else. Now you have 2 versions of skype with different bundle ids which means you can target them separately.

I checked this using TextEdit. I made a duplicate copy and set its bundle id to "com.apple.myTextEdit". I opened both applications and could target them separately. So user B could use "com.apple.myTextEdit" and the normal user would use "com.apple.TextEdit"... or vice versa.

It's not an ideal solution but it would work.


问:
How to read & write Local MySQL Server 8 from Google Colab with Pyspark?
I have been trying but failing to write/read tables from MySQL Server 8.0.19 on localhost on Windows 10 with pyspark from Google colab. There's also a lot of similar questions and with some suggested answers but none of the solutions seem to work here. Here is my code:

```<code>    <...installations  ...>

        from pyspark.sql import SparkSession

        spark = SparkSession\
        .builder\
        .appName("Word Count")\
        .config("spark.driver.extraClassPath", "/content/spark-2.4.5-bin-hadoop2.7/jars/mysql-connector-java-8.0.19.jar")\
        .getOrCreate()
</code>```

An here is the connection string:

```<code>MyjdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://127.0.0.1:3306/mydb?user=testuser&password=pwtest")\
                    .option("dbtable", "collisions")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load()
</code>```

I have as well used the .option("driver","com.mysql.jdbc.Driver") but still keep getting this error:

```<code>Py4JJavaError: An error occurred while calling o154.load.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

...
...
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)
</code>```

From this, I guess that MySQL Sever is not reachable.
I have Telnetted to port 3306 & it confirmed that MySQL Server is accepting connections from client machine. I have read that running: netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306 will permitting firewall rule for MySQL Server incase it was being blocked, yet no change.

Can somebody help outpy?

答:
You are trying to connect mysql database installed on your local machine i.e. windows 10 from google colab as localhost instance.

This is not possible because google colab spins up instance of their own to execute your code, if you want to access your local mysql you need to host it on a server so that it is reachable over the internet.

Otherwise, you can install mysql on colab then use that to run your code for testing.

```<code>!apt-get -y install mysql-server
</code>```

then configure it on instance to use

Body:
I have been trying but failing to write/read tables from MySQL Server 8.0.19 on localhost on Windows 10 with pyspark from Google colab. There's also a lot of similar questions and with some suggested answers but none of the solutions seem to work here. Here is my code:

    <...installations  ...>

        from pyspark.sql import SparkSession

        spark = SparkSession\
        .builder\
        .appName("Word Count")\
        .config("spark.driver.extraClassPath", "/content/spark-2.4.5-bin-hadoop2.7/jars/mysql-connector-java-8.0.19.jar")\
        .getOrCreate()

An here is the connection string:

MyjdbcDF = spark.read.format("jdbc")\
                    .option("url", "jdbc:mysql://127.0.0.1:3306/mydb?user=testuser&password=pwtest")\
                    .option("dbtable", "collisions")\
                    .option("driver","com.mysql.cj.jdbc.Driver")\
                    .load()

I have as well used the .option("driver","com.mysql.jdbc.Driver") but still keep getting this error:

Py4JJavaError: An error occurred while calling o154.load.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

...
...
...
Caused by: java.net.ConnectException: Connection refused (Connection refused)

From this, I guess that MySQL Sever is not reachable.
I have Telnetted to port 3306 & it confirmed that MySQL Server is accepting connections from client machine. I have read that running: netsh advfirewall firewall add rule name="MySQL Server" action=allow protocol=TCP dir=in localport=3306 will permitting firewall rule for MySQL Server incase it was being blocked, yet no change.

Can somebody help outpy?

Body:
You are trying to connect mysql database installed on your local machine i.e. windows 10 from google colab as localhost instance.

This is not possible because google colab spins up instance of their own to execute your code, if you want to access your local mysql you need to host it on a server so that it is reachable over the internet.

Otherwise, you can install mysql on colab then use that to run your code for testing.

!apt-get -y install mysql-server

then configure it on instance to use


问:
Getting strange characters when pasting into my iterm2 terminal
I'm using iterm2 v 3.0.15 on Mac Sierra.  I'm having trouble cutting and pasting from other places (e.g. text on a web page) into my terminal.  For instance, I highlight some text from a web page, press Command + C, go to the terminal, and then press Command + V, I get

```<code>localhost:myproject nataliab$ 00~on the next01~
</code>```

Notice the "00~" and "01~" in front of and behind my text.  I do not see these characters when I cut and paste into a text editor or other places.  How do I eliminate these special characters from appearing when I cut and paste into my iterm2 terminal?

答: I had to do shell-->Hard Reset to make it work immediately

Body:
I'm using iterm2 v 3.0.15 on Mac Sierra.  I'm having trouble cutting and pasting from other places (e.g. text on a web page) into my terminal.  For instance, I highlight some text from a web page, press Command + C, go to the terminal, and then press Command + V, I get

localhost:myproject nataliab$ 00~on the next01~

Notice the "00~" and "01~" in front of and behind my text.  I do not see these characters when I cut and paste into a text editor or other places.  How do I eliminate these special characters from appearing when I cut and paste into my iterm2 terminal?


问:
Acrobat Dynamic Date Stamp with Dialogue Box Results not Displaying
I am completely a novice at this, and borrowed part of a script from a sample online.

I am working a stamp with a dialogue box prompting for the date, and defaulting to the current date if no response. I have gotten it to display the dialogue box and the default date. But, the results don't end up on the stamp. Could someone please assist on resolving the issues?

```<code>if(event.source.forReal && (event.source.stampName == "#2Nw2jMn7S5l9QIPW-WGOHB"))
{
   var rgEmpty = /^\s*$/;
   var cDate = null;
   var cDfltDate = null;
   if((event.value != null)  && !rgEmpty.test(event.value) && util.scand("mmm dd yyyy",event.value))
      cDfltDate = event.value;
   else
      cDfltDate = util.printd("mmm dd yyyy",new Date());
   while((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
   {
       cDate = app.response({cQuestion:"Please Enter the Date",
                             cTitle:"Stamp Date Entry",
                             cDefault:cDfltDate ,
                             cLabel:"Date:"
                           });
       if((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
       {
          app.alert("Please enter date as \"mmm dd yyyy\"\n\nEx: Apr 15 2020",1);
          if(cDate != null)
            cDfltDate = cDate;
       }
   }
}
</code>```

Also, I would like to distribute the final stamp to my coworkers as a template rather than them creating the script. Can I share the stamp pdf, and have them create one off my template without them having to modify the script?

Thank you!

答:
First take a look at the following; https://acrobatusers.com/tutorials/dynamic_stamp_secrets

1) You should have a separate pdf file, that is the stamp file. This file can then be distributed to your coworkers if they copy the stamp file in the correct location, to find out the correct location run following code;

```<code>app.getPath ("app", "stamps");
app.getPath ("user", "stamps");
</code>```

2) This stamp file should contain "fields", these fields can be filled in by a script that is attached to the stamp file, so you only need to distribute the stamp file that includes the script.

3) In your script you don't have a statement event.value = ...; if this is linked to a field it will fill in the field with the inputted date or current date.

Hope this is a help.

Body:
I am completely a novice at this, and borrowed part of a script from a sample online.

I am working a stamp with a dialogue box prompting for the date, and defaulting to the current date if no response. I have gotten it to display the dialogue box and the default date. But, the results don't end up on the stamp. Could someone please assist on resolving the issues?

if(event.source.forReal && (event.source.stampName == "#2Nw2jMn7S5l9QIPW-WGOHB"))
{
   var rgEmpty = /^\s*$/;
   var cDate = null;
   var cDfltDate = null;
   if((event.value != null)  && !rgEmpty.test(event.value) && util.scand("mmm dd yyyy",event.value))
      cDfltDate = event.value;
   else
      cDfltDate = util.printd("mmm dd yyyy",new Date());
   while((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
   {
       cDate = app.response({cQuestion:"Please Enter the Date",
                             cTitle:"Stamp Date Entry",
                             cDefault:cDfltDate ,
                             cLabel:"Date:"
                           });
       if((cDate==null) || rgEmpty.test(cDate) || (null == util.scand("mmm dd yyyy",cDate)))
       {
          app.alert("Please enter date as \"mmm dd yyyy\"\n\nEx: Apr 15 2020",1);
          if(cDate != null)
            cDfltDate = cDate;
       }
   }
}

Also, I would like to distribute the final stamp to my coworkers as a template rather than them creating the script. Can I share the stamp pdf, and have them create one off my template without them having to modify the script?

Thank you!

Body:
First take a look at the following; https://acrobatusers.com/tutorials/dynamic_stamp_secrets

1) You should have a separate pdf file, that is the stamp file. This file can then be distributed to your coworkers if they copy the stamp file in the correct location, to find out the correct location run following code;

app.getPath ("app", "stamps");
app.getPath ("user", "stamps");

2) This stamp file should contain "fields", these fields can be filled in by a script that is attached to the stamp file, so you only need to distribute the stamp file that includes the script.

3) In your script you don't have a statement event.value = ...; if this is linked to a field it will fill in the field with the inputted date or current date.

Hope this is a help.


问:
Not getting any audio output during Text to speech with Pyttsx3 module on Pycharm
My python version is 3.7  and Pyaudio version is 2.7
Program is totally running during engine init, but I can't use sipas5 for windows so I have used dummy

```<code>import pyttsx3
    engine = pyttsx3.init("dummy")
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[0].id)

    def speak(text):
        print('Rex:' + text)
        engine.say(text)
        engine.runAndWait()

    print("On")
    speak("This program is running perfectly")
    print("End")
</code>```

Output

```<code>On
Rex:This program is running perfectly
End

Process finished with exit code 0
</code>```

答:
Dummy isnt a voice engine. Its tk simply test. There are 3 types for pyttsx3. Sapi5, nsss, and espeak. This is what you put inside of that init (). This is the link for the official python package with information.

https://pypi.org/project/pyttsx3/

Body:
My python version is 3.7  and Pyaudio version is 2.7
Program is totally running during engine init, but I can't use sipas5 for windows so I have used dummy

import pyttsx3
    engine = pyttsx3.init("dummy")
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[0].id)

    def speak(text):
        print('Rex:' + text)
        engine.say(text)
        engine.runAndWait()

    print("On")
    speak("This program is running perfectly")
    print("End")

Output

On
Rex:This program is running perfectly
End

Process finished with exit code 0


问:
How do web servers stay alive?
I am wondering how web servers i.e. Nginx, Flask, Django stay alive and wait for requests. And how I can write my own program which stays alive and waits for a request before launching an action.</p>

答:
The short answer for the overwhelming number of cases involving nginx is systemd service. When you install nginx it sets itself up as a systemd service which is configured to start nginx on boot and keep it running.

You can adapt systemd to load and keep your own services (like Flask, etc.) alive and waiting for requests as well. Here is an article that explains the basics.

An alternative to systemd (which is built into most of the Linux systems you would be using on a server) is supervisord. Like systemd, supervisord can be configured to monitor, start, and keep your service running in the background, waiting for a request.

Title: How do web servers stay alive?


问:
Get text from ".txt" file and save it in String variable dart
I have a ".txt" file called "bio.txt" inside the Document folder of my application.
I want to read its content and store it inside a String variable.
My problem is that the "reading action" is a "Future" function and I have some troubles to save its value in a "String".

I read the file with :

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> _localFile(String name) async {
  final path = await _localPath;
  return File('$path/$name');
}

Future<String> _read(String filename) async {
  try {
    final file = await _localFile(filename);

    // Read the file.
    return await file.readAsString();
  } catch (e) {
    // If encountering an error, return 0.
    return "Can't read";
  }
}
```

<p>And I would like to save it with :</p>

<pre class="lang-dart prettyprint-override"><code>String _bio = _read("bio.txt").then((value) => String);
</code>```

Do you know why this solution isn't working?
Any suggestion?

答:
This is my solution : </p>

```<code>String _myRead( String filename){
 var _bio;

 _read("bio.txt").then((String) {
   _bio = String;
 });
 return _bio;
}
String _bio=_myRead("bio.txt");
</code>```

Body:
I have a ".txt" file called "bio.txt" inside the Document folder of my application.
I want to read its content and store it inside a String variable.
My problem is that the "reading action" is a "Future" function and I have some troubles to save its value in a "String".

I read the file with :

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<File> _localFile(String name) async {
  final path = await _localPath;
  return File('$path/$name');
}

Future<String> _read(String filename) async {
  try {
    final file = await _localFile(filename);

    // Read the file.
    return await file.readAsString();
  } catch (e) {
    // If encountering an error, return 0.
    return "Can't read";
  }
}

And I would like to save it with :

String _bio = _read("bio.txt").then((value) => String);

Do you know why this solution isn't working?
Any suggestion?

Body:
This is my solution :

String _myRead( String filename){
 var _bio;

 _read("bio.txt").then((String) {
   _bio = String;
 });
 return _bio;
}
String _bio=_myRead("bio.txt");


问:
Generate multiple columns based on conditions from other columns
I've searched quite a bit for a solution, but almost all questions are related to the creation of a single column.
So, here is my problem.

Given an example DataFrame:

```<code>df = pd.DataFrame({
    "blue": [5, 5, 4],
    "red": [1, 7, 5],
    "yellow": [3, 9, 0],
    "orange": [9, 7, 3],
    "config": ["north", "south", "north"]
})
</code>```

```<code>   blue config  orange  red  yellow
0     5  north       9    1       3
1     5  south       7    7       9
2     4  north       3    5       0
</code>```

What I would like to achieve is to create additional columns based on multiple conditions (a mapping to be specific). Here is an example of what I have tried:

```<code>def gen_col(row):

    if row["config"] == "north":
        new_blue = row["blue"]
        new_red = row["red"]
        new_yellow = row["yellow"]
        new_orange = row["orange"]
        return new_blue, new_red, new_yellow, new_orange
    elif row["config"] == "south":
        new_blue = row["orange"]
        new_red = row["yellow"]
        new_yellow = row["red"]
        new_orange = row["blue"]
        return new_blue, new_red, new_yellow, new_orange

df["new_blue", "new_red", "new_yellow", "new_orange"] = df.apply(gen_col, axis=1)
</code>```

However, this returns the following:

```<code>   blue config  orange  red  yellow (new_blue, new_red, new_yellow, new_orange)
0     5  north       9    1       3             (5, 1, 3, 9)
1     5  south       7    7       9             (7, 9, 7, 5)
2     4  north       3    5       0             (4, 5, 0, 3)
</code>```

Any ideas on how to create separate new columns?

答:
Use result_type='expand' parameter in DataFrame.apply and also add nested lists for assigned columns:

```<code>df[["new_blue", "new_red", "new_yellow", "new_orange"]] = df.apply(gen_col, axis=1, result_type='expand')
print (df)
   blue  red  yellow  orange config  new_blue  new_red  new_yellow  new_orange
0     5    1       3       9  north         5        1           3           9
1     5    7       9       7  south         7        9           7           5
2     4    5       0       3  north         4        5           0           3
</code>```

Body:
I've searched quite a bit for a solution, but almost all questions are related to the creation of a single column.
So, here is my problem.

Given an example DataFrame:

df = pd.DataFrame({
    "blue": [5, 5, 4],
    "red": [1, 7, 5],
    "yellow": [3, 9, 0],
    "orange": [9, 7, 3],
    "config": ["north", "south", "north"]
})

   blue config  orange  red  yellow
0     5  north       9    1       3
1     5  south       7    7       9
2     4  north       3    5       0

What I would like to achieve is to create additional columns based on multiple conditions (a mapping to be specific). Here is an example of what I have tried:

def gen_col(row):

    if row["config"] == "north":
        new_blue = row["blue"]
        new_red = row["red"]
        new_yellow = row["yellow"]
        new_orange = row["orange"]
        return new_blue, new_red, new_yellow, new_orange
    elif row["config"] == "south":
        new_blue = row["orange"]
        new_red = row["yellow"]
        new_yellow = row["red"]
        new_orange = row["blue"]
        return new_blue, new_red, new_yellow, new_orange

df["new_blue", "new_red", "new_yellow", "new_orange"] = df.apply(gen_col, axis=1)

However, this returns the following:

   blue config  orange  red  yellow (new_blue, new_red, new_yellow, new_orange)
0     5  north       9    1       3             (5, 1, 3, 9)
1     5  south       7    7       9             (7, 9, 7, 5)
2     4  north       3    5       0             (4, 5, 0, 3)

Any ideas on how to create separate new columns?

Body:
Use result_type='expand' parameter in DataFrame.apply and also add nested lists for assigned columns:

df[["new_blue", "new_red", "new_yellow", "new_orange"]] = df.apply(gen_col, axis=1, result_type='expand')
print (df)
   blue  red  yellow  orange config  new_blue  new_red  new_yellow  new_orange
0     5    1       3       9  north         5        1           3           9
1     5    7       9       7  south         7        9           7           5
2     4    5       0       3  north         4        5           0           3


问:
Google API: How do I discover the client secret for an existing API Key?
A while back I created an API Key in Google API's.

I'm navigating around the API Key UI. I can see the API Key. But I can't see any way of revealing the client secret.

Is there a way to recover the secret?
Or do I have to regenerate the key and secret, thus breaking any existing application currently using it?

答: Go to google developer console  find the credential you are after.  Then click the pencil icon on that row.  It will open a new window where you can see your client secret.


问:
AEM 6.1 and 6.5 switching on local machine
~We have some projects still running in AEM 6.1 SP2 (the move to newest version of AEM is in progress) and new projects in AEM 6.5.
AEM 6.1 runs in java 8 and AEM 6.5 runs in java 11.
For us developers this switching between jdk versions is difficult in our local environment, quite often we get our AEM instances corrupted or maven project imports are no longer working properly in IDE.
Anyone else had this situation? What are the best practices for such a situation?</p>

答:
If you are running your AEM instances via shell scripts E.g. ./crx-quickstart/bin/start you can always specify the JAVA_HOME variable to be used in this particular file.

E.g.

```<code>export JAVA_HOME="path to your JVM"

export PATH=$JAVA_HOME/bin:$PATH
</code>```

Body:
If you are running your AEM instances via shell scripts E.g. ./crx-quickstart/bin/start you can always specify the JAVA_HOME variable to be used in this particular file.

E.g.

export JAVA_HOME="path to your JVM"

export PATH=$JAVA_HOME/bin:$PATH


问:
Add or Remove class in jQuery
This looks awkward but when I'm trying to add any class or remove any class using jQuery it's not working, Instead of adding or removing class I tried with the alert window, in that case, it's working fine. Can anyone tell me why I'm not able to add or remove any class?

```<code>$('#sign').click(function(){
    alert("I'm working");
    $('#signup').ready(function(){
        $(this).addClass('hidden');
    });
});
</code>```

This is the code I've tried and #sign is the id in Sidebar or navbar whatever. When I click on that link then it goes to the section with id #signup. In this section I want that class to add or remove.

答:
See: https://api.jquery.com/ready/

$('#signup').ready(...) does not seem applicable. The page is already loaded, so you do not need to wait for DOM ready. Just remove that wrapper and manipulate the class directly:

```<code>$('#sign').click(function(){
    alert("I'm working");
    $('#signup').addClass('hidden');
});
</code>```

I am assuming you are trying to handle clicking on and changing the classes on DIFFERENT elements (despite the similar names).

Title: Add or Remove class in jQuery

Body:
This looks awkward but when I'm trying to add any class or remove any class using jQuery it's not working, Instead of adding or removing class I tried with the alert window, in that case, it's working fine. Can anyone tell me why I'm not able to add or remove any class?

$('#sign').click(function(){
    alert("I'm working");
    $('#signup').ready(function(){
        $(this).addClass('hidden');
    });
});

This is the code I've tried and #sign is the id in Sidebar or navbar whatever. When I click on that link then it goes to the section with id #signup. In this section I want that class to add or remove.

Body:
See: https://api.jquery.com/ready/

$('#signup').ready(...) does not seem applicable. The page is already loaded, so you do not need to wait for DOM ready. Just remove that wrapper and manipulate the class directly:

$('#sign').click(function(){
    alert("I'm working");
    $('#signup').addClass('hidden');
});

I am assuming you are trying to handle clicking on and changing the classes on DIFFERENT elements (despite the similar names).


问:
How to count using input strings?
Hi I am trying to count max value in given problem using an input string.
Problem decscription:
Given two months x and y, where y > x, find the hashtag name that has increased the number of tweets the most from month x to month y. We have already written code in your code template that reads the x and y values from the keyboard.  Ignore the tweets in the months between x and y, so just compare the number of tweets at month x and at month y. Report the hashtag name, the number of tweets in months x and y. Ignore any hashtag names that had no tweets in either month x or y. You can assume that the combination of hashtag and month is unique.  Print the result to the terminal output using println. For the above small example data set the output should be the following:

```<code>Input       x = 200910, y = 200912

Output  hashtagName: mycoolwife, countX: 1, countY: 500
Data Fomrat:

Token type  Month   count   Hash Tag Name

hashtag 200910  2   Babylove

hashtag 200911  2   babylove

hashtag 200912  90  babylove
</code>```

My attempt:

```<code>// Load the input data and split each line into an array of strings
val twitterLines = sc.textFile("hdfs:///user/ashhall1616/bdc_data/twitter-small.tsv")
val twitterdata = twitterLines.map(_.split("\t"))

// Each month is a string formatted as YYYYMM
val x = scala.io.StdIn.readLine("x month: ")
val y = scala.io.StdIn.readLine("y month: ")

val matchmonth= twitterdata.map(r => (r(0)== x ,r(0)==y, r(2), r(3))).sortBy(_._3, false)
if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
   {
       val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
       val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
           println("[" + ht1 + "," + ht2 + "]")
   }
</code>```

errors getting:

```<code> val matchmonth= twitterdata.map(r => (r(0)== x ,r(0)==y, r(2), r(3))).sortBy(_._3, false)
matchmonth: org.apache.spark.rdd.RDD[(Boolean, Boolean, String, String)] = MapPartitionsRDD[20] at sortBy at <console>:32
scala> if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
<console>:1: error: identifier expected but '(' found.
if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
              ^
<console>:1: error: identifier expected but '(' found.
if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
                                         ^
scala>    {
     |        val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
     |        val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
     |            println("[" + ht1 + "," + ht2 + "]")
     |    }
<console>:36: error: (Boolean, Boolean, String, String) does not take parameters
              val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
                                              ^
<console>:36: error: (Boolean, Boolean, String, String) does not take parameters
              val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
                                                    ^
<console>:37: error: (Boolean, Boolean, String, String) does not take parameters
              val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
                                              ^
<console>:37: error: (Boolean, Boolean, String, String) does not take parameters
              val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
</code>```

can someone have a look what is wrong here?

答:
I suggest you read a few articles on Spark SQL and the DataFrame API.

matchmonth is a DataFrame (if it helps you can think of this as an SQL table). Using it in an if statement makes no sense. It is also very useful to name the columns. e.g.

```<code>val twitterdata = twitterLines.map(_.split("\t")).toDF("tokenType", "month", "count", "hash")
</code>```

By applying map to your DataFrame twitterdata you have transformed it from shape  (String, String, String, String, String) to shape (Boolean, Boolean, String, String) - is that what you want?

if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1))) is not valid syntax.

To get started you want to select the rows that match your month range. This will return another DataFrame. From there I will leave it to you to read up on spark sql. groupBy and sum will probably help you

```<code>import spark.implicits._
import org.apache.spark.sql.functions.lit

val filteredDf = twitterdata.where($"month" >= lit(x) && $"month" <= lit(y))
</code>```

Title: How to count using input strings?

Body:
Hi I am trying to count max value in given problem using an input string.
Problem decscription:
Given two months x and y, where y > x, find the hashtag name that has increased the number of tweets the most from month x to month y. We have already written code in your code template that reads the x and y values from the keyboard.  Ignore the tweets in the months between x and y, so just compare the number of tweets at month x and at month y. Report the hashtag name, the number of tweets in months x and y. Ignore any hashtag names that had no tweets in either month x or y. You can assume that the combination of hashtag and month is unique.  Print the result to the terminal output using println. For the above small example data set the output should be the following:

Input       x = 200910, y = 200912

Output  hashtagName: mycoolwife, countX: 1, countY: 500
Data Fomrat:

Token type  Month   count   Hash Tag Name

hashtag 200910  2   Babylove

hashtag 200911  2   babylove

hashtag 200912  90  babylove

My attempt:

// Load the input data and split each line into an array of strings
val twitterLines = sc.textFile("hdfs:///user/ashhall1616/bdc_data/twitter-small.tsv")
val twitterdata = twitterLines.map(_.split("\t"))

// Each month is a string formatted as YYYYMM
val x = scala.io.StdIn.readLine("x month: ")
val y = scala.io.StdIn.readLine("y month: ")

val matchmonth= twitterdata.map(r => (r(0)== x ,r(0)==y, r(2), r(3))).sortBy(_._3, false)
if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
   {
       val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
       val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
           println("[" + ht1 + "," + ht2 + "]")
   }

errors getting:

 val matchmonth= twitterdata.map(r => (r(0)== x ,r(0)==y, r(2), r(3))).sortBy(_._3, false)
matchmonth: org.apache.spark.rdd.RDD[(Boolean, Boolean, String, String)] = MapPartitionsRDD[20] at sortBy at <console>:32
scala> if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
<console>:1: error: identifier expected but '(' found.
if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
              ^
<console>:1: error: identifier expected but '(' found.
if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1)))
                                         ^
scala>    {
     |        val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
     |        val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
     |            println("[" + ht1 + "," + ht2 + "]")
     |    }
<console>:36: error: (Boolean, Boolean, String, String) does not take parameters
              val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
                                              ^
<console>:36: error: (Boolean, Boolean, String, String) does not take parameters
              val ht1 = matchmonth.map(r => (r(2), r(3))).take(1)
                                                    ^
<console>:37: error: (Boolean, Boolean, String, String) does not take parameters
              val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)
                                              ^
<console>:37: error: (Boolean, Boolean, String, String) does not take parameters
              val ht2 = matchmonth.map(r => (r(2), r(3))).take(1,2)

can someone have a look what is wrong here?

Body:
I suggest you read a few articles on Spark SQL and the DataFrame API.

matchmonth is a DataFrame (if it helps you can think of this as an SQL table). Using it in an if statement makes no sense. It is also very useful to name the columns. e.g.

val twitterdata = twitterLines.map(_.split("\t")).toDF("tokenType", "month", "count", "hash")

By applying map to your DataFrame twitterdata you have transformed it from shape  (String, String, String, String, String) to shape (Boolean, Boolean, String, String) - is that what you want?

if(matchmonth.(r => (r(0))) < matchmonth.(r => (r(1))) is not valid syntax.

To get started you want to select the rows that match your month range. This will return another DataFrame. From there I will leave it to you to read up on spark sql. groupBy and sum will probably help you

import spark.implicits._
import org.apache.spark.sql.functions.lit

val filteredDf = twitterdata.where($"month" >= lit(x) && $"month" <= lit(y))


问:
laravel event not send to pusher
i have pusher app, then i try to send message to pusher by laravel event, this is my event :

```<code>namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewOrder
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $email;
    public $message;

    public function __construct($email)
    {
        $this->email = $email;
        $this->message = "New order from {$email}, please check.";
        //
    }

    public function broadcastOn()
    {
        return ['new-order'];
    }

}
</code>```

and i try to test it with route test,

```<code>Route::get('test', function () {
    event(new App\Events\NewOrder('John'));
    return "Event has been sent!";
});
</code>```

my pusher configuration have been configured like my pusher's account configuration, but after access /test , the pusher debug console doesn't show anything.

this is my broadcasting.php

```<code>    'default' => env('BROADCAST_DRIVER', 'pusher'),

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                // 'cluster' => 'ap1',
                'encrypted' => true,
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];
</code>```

i don't know to see pusher's log from laravel app, anyone can help me?
i'm using laravel 5.5

答:
Hi I had this problem too and fix it by clearing the cache! Here is the code!

```<code>php artisan config:cache
php artisan config:clear
php artisan route:cache
php artisan route:clear
php artisan optimize --force
</code>```

Hopefully it can be helpful to you!

Title: laravel event not send to pusher

Body:
i have pusher app, then i try to send message to pusher by laravel event, this is my event :

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class NewOrder
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    public $email;
    public $message;

    public function __construct($email)
    {
        $this->email = $email;
        $this->message = "New order from {$email}, please check.";
        //
    }

    public function broadcastOn()
    {
        return ['new-order'];
    }

}

and i try to test it with route test,

Route::get('test', function () {
    event(new App\Events\NewOrder('John'));
    return "Event has been sent!";
});

my pusher configuration have been configured like my pusher's account configuration, but after access /test , the pusher debug console doesn't show anything.

this is my broadcasting.php

    'default' => env('BROADCAST_DRIVER', 'pusher'),

    'connections' => [

        'pusher' => [
            'driver' => 'pusher',
            'key' => env('PUSHER_APP_KEY'),
            'secret' => env('PUSHER_APP_SECRET'),
            'app_id' => env('PUSHER_APP_ID'),
            'options' => [
                'cluster' => env('PUSHER_APP_CLUSTER'),
                // 'cluster' => 'ap1',
                'encrypted' => true,
            ],
        ],

        'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
        ],

        'log' => [
            'driver' => 'log',
        ],

        'null' => [
            'driver' => 'null',
        ],

    ],

];

i don't know to see pusher's log from laravel app, anyone can help me?
i'm using laravel 5.5

Body:
Hi I had this problem too and fix it by clearing the cache! Here is the code!

php artisan config:cache
php artisan config:clear
php artisan route:cache
php artisan route:clear
php artisan optimize --force

Hopefully it can be helpful to you!


问:
SSL with default KafkaConsumer
Does a default KafkaConsumer instance use/support SSL for consuming? I would assume not but I could not yet find a documentation which default properties will be used.

答:
Yes, a KafkaConsumer supports SSL. However, by default, all security setting are set to "null".

You will find all configuration in the Consumer Configs section of the Kafka documentation.

To be more precise, the default setting of a Kafka Consumer for security.protocol is PLAINTEXT. Only if you set this on purpose to SSL it will enable SSL communication.

Title: SSL with default KafkaConsumer


问:
Need Help Checking if a file exists?
I have a way to Save files using a button that grabs the text in textboxes and saves them with a number specified in one of those text boxes. example: "enter employee id:"  (I would enter) "12345" and click the button, and it would save the file as 12345 with some info in it from other text boxes.

Now I also have implemented a way to check if that file exists in two separate folders so that is doesn't create a file with multiple of the same name.

Now I am trying to check if the file exists (in both directories) again when someone clicks a button to login on a separate page but I run into a problem where it always tells me the file doesn't exist. I'm new to programming so I'm a little lost. Here is my code:

Login Page:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class Employee_Login_Page : Form
    {
        public Employee_Login_Page()
        {
            InitializeComponent();
        }
        string ManagerPath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
        string EmployeePath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Staff\Staff_Ids.txt"; //Path to Employees Logins

        string FileName; //Declares FileName
        bool FileExists;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
                (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
            else if (e.KeyChar == (char)13)                                         //Checks if The "Enter" Key is pressed
            {
                Login_Btn_Click(this, new EventArgs());                             //If so activate the Login Button
            }
        }

        private void Employee_Login_Page_Load(object sender, EventArgs e)
        {

        }

        private void Login_Btn_Click(object sender, EventArgs e)
        {

            FileName = Employee_Id_TextBox.Text=".txt"; //sets the string FileName to Employee Id Entered
            string pathManagerString = System.IO.Path.Combine(ManagerPath, FileName); //Combine Manager Path With New Id and sets to pathManagerString
            string pathEmployeeString = System.IO.Path.Combine(EmployeePath, FileName); //Combine Manager Path With New Id and sets to pathEmployeeString

            if (FileExists = File.Exists(pathEmployeeString)) //Check If Employee ID File Exists in Employee folder
            {
                MessageBox.Show("Employee ID Entered as Employee");
                EmployeeHome_Page myForm = new EmployeeHome_Page();
                this.Hide();
                myForm.ShowDialog();
            }
            else if(FileExists = File.Exists(pathManagerString))
            {
                MessageBox.Show("Employee ID Entered as Manager");
                EmployeeHome_Page myForm = new EmployeeHome_Page();
                this.Hide();
                myForm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Employee ID Not Found");
            }
            //need to check logins and wether they are manager or just standard users/and if so activate manager button
        }
    }
}
</code>```

Second Form:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class AddEmployee_Page : Form
    {
        public AddEmployee_Page()
        {
            InitializeComponent();
        }
        string ManagerPath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers";
        string EmployeePath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Staff";
        private void AddEmployee_Page_Load(object sender, EventArgs e)
        {

        }
        string FileName; //Declares FileName
        bool FileExists;

        private void CancelAddEmployee_Btn_Click(object sender, EventArgs e)
        {
            EmployeeHome_Page myForm = new EmployeeHome_Page ();
            this.Hide();
            myForm.ShowDialog();
        }

        private void AddEmployee_Btn_Click(object sender, EventArgs e)
        {
            FileName = EmployeeID_AddEmployee_TextBox.Text; //sets the string FileName to Employee Id Entered
            string pathManagerString = System.IO.Path.Combine(ManagerPath, FileName); //Combine Manager Path With New Id and sets to pathManagerString
            string pathEmployeeString = System.IO.Path.Combine(EmployeePath, FileName); //Combine Manager Path With New Id and sets to pathEmployeeString

            if (FirstName_AddEmployee_TextBox.Text == "" || LastName_AddEmployee_TextBox.Text == "" || EmployeeID_AddEmployee_TextBox.Text == "")  //checks if any feild are empty if so show prompt
            {
                MessageBox.Show("Missing Information!");
            }
            else if (EmployeeID_AddEmployee_TextBox.TextLength < 5)      //checks if employee id is less then 5 digits long, if so display message
            {
                MessageBox.Show("ID Needs To Be Five Numbers Long");
            }
            else if (IsManager_CheckBox.Checked)  //checks if manager
            {
                if (FileExists = File.Exists(pathManagerString)) //Check If Employee ID File Exists in manager folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else if (FileExists = File.Exists(pathEmployeeString)) //Check If Employee ID File Exists in employee folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else
                {
                    using (System.IO.StreamWriter file =
                        new System.IO.StreamWriter(pathManagerString, true))
                    {
                        file.WriteLine("Manager First Name: " + FirstName_AddEmployee_TextBox.Text); //Writes First Name
                        file.WriteLine("Manager Last Name: " + LastName_AddEmployee_TextBox.Text);//Writes Last Name
                    }
                }
            }
            else
            {
                if (FileExists = File.Exists(pathEmployeeString)) //Check If Employee ID File Exists in emoployee folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else if(FileExists = File.Exists(pathManagerString)) //Check If Employee ID File Exists in manager folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else
                {
                    using (System.IO.StreamWriter file =
                        new System.IO.StreamWriter(pathEmployeeString, true))
                    {
                        file.WriteLine("Employee First Name: " + FirstName_AddEmployee_TextBox.Text); //Writes First Name
                        file.WriteLine("Employee Last Name: " + LastName_AddEmployee_TextBox.Text);//Writes Last Name
                    }
                }
            }
        }

        private void FirstName_AddEmployee_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void EmployeeID_AddEmployee_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
    (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
        }

        private void IsManager_CheckBox_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}
</code>```

答:
Change this line of code of Login_Btn_Click method:

Old

```<code>FileName = Employee_Id_TextBox.Text=".txt";
</code>```

Replacement

```<code> FileName = Employee_Id_TextBox.Text+".txt";
</code>```

And update location of both folder:

```<code>string ManagerPath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers";
string EmployeePath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Staff";
</code>```

Title: Need Help Checking if a file exists?

Body:
I have a way to Save files using a button that grabs the text in textboxes and saves them with a number specified in one of those text boxes. example: "enter employee id:"  (I would enter) "12345" and click the button, and it would save the file as 12345 with some info in it from other text boxes.

Now I also have implemented a way to check if that file exists in two separate folders so that is doesn't create a file with multiple of the same name.

Now I am trying to check if the file exists (in both directories) again when someone clicks a button to login on a separate page but I run into a problem where it always tells me the file doesn't exist. I'm new to programming so I'm a little lost. Here is my code:

Login Page:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class Employee_Login_Page : Form
    {
        public Employee_Login_Page()
        {
            InitializeComponent();
        }
        string ManagerPath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers\Manager_Ids.txt"; //Path To Manager Logins
        string EmployeePath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Staff\Staff_Ids.txt"; //Path to Employees Logins

        string FileName; //Declares FileName
        bool FileExists;

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Employee_Id_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
                (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
            else if (e.KeyChar == (char)13)                                         //Checks if The "Enter" Key is pressed
            {
                Login_Btn_Click(this, new EventArgs());                             //If so activate the Login Button
            }
        }

        private void Employee_Login_Page_Load(object sender, EventArgs e)
        {

        }

        private void Login_Btn_Click(object sender, EventArgs e)
        {

            FileName = Employee_Id_TextBox.Text=".txt"; //sets the string FileName to Employee Id Entered
            string pathManagerString = System.IO.Path.Combine(ManagerPath, FileName); //Combine Manager Path With New Id and sets to pathManagerString
            string pathEmployeeString = System.IO.Path.Combine(EmployeePath, FileName); //Combine Manager Path With New Id and sets to pathEmployeeString

            if (FileExists = File.Exists(pathEmployeeString)) //Check If Employee ID File Exists in Employee folder
            {
                MessageBox.Show("Employee ID Entered as Employee");
                EmployeeHome_Page myForm = new EmployeeHome_Page();
                this.Hide();
                myForm.ShowDialog();
            }
            else if(FileExists = File.Exists(pathManagerString))
            {
                MessageBox.Show("Employee ID Entered as Manager");
                EmployeeHome_Page myForm = new EmployeeHome_Page();
                this.Hide();
                myForm.ShowDialog();
            }
            else
            {
                MessageBox.Show("Employee ID Not Found");
            }
            //need to check logins and wether they are manager or just standard users/and if so activate manager button
        }
    }
}

Second Form:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Rent_a_Car
{
    public partial class AddEmployee_Page : Form
    {
        public AddEmployee_Page()
        {
            InitializeComponent();
        }
        string ManagerPath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers";
        string EmployeePath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Staff";
        private void AddEmployee_Page_Load(object sender, EventArgs e)
        {

        }
        string FileName; //Declares FileName
        bool FileExists;

        private void CancelAddEmployee_Btn_Click(object sender, EventArgs e)
        {
            EmployeeHome_Page myForm = new EmployeeHome_Page ();
            this.Hide();
            myForm.ShowDialog();
        }

        private void AddEmployee_Btn_Click(object sender, EventArgs e)
        {
            FileName = EmployeeID_AddEmployee_TextBox.Text; //sets the string FileName to Employee Id Entered
            string pathManagerString = System.IO.Path.Combine(ManagerPath, FileName); //Combine Manager Path With New Id and sets to pathManagerString
            string pathEmployeeString = System.IO.Path.Combine(EmployeePath, FileName); //Combine Manager Path With New Id and sets to pathEmployeeString

            if (FirstName_AddEmployee_TextBox.Text == "" || LastName_AddEmployee_TextBox.Text == "" || EmployeeID_AddEmployee_TextBox.Text == "")  //checks if any feild are empty if so show prompt
            {
                MessageBox.Show("Missing Information!");
            }
            else if (EmployeeID_AddEmployee_TextBox.TextLength < 5)      //checks if employee id is less then 5 digits long, if so display message
            {
                MessageBox.Show("ID Needs To Be Five Numbers Long");
            }
            else if (IsManager_CheckBox.Checked)  //checks if manager
            {
                if (FileExists = File.Exists(pathManagerString)) //Check If Employee ID File Exists in manager folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else if (FileExists = File.Exists(pathEmployeeString)) //Check If Employee ID File Exists in employee folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else
                {
                    using (System.IO.StreamWriter file =
                        new System.IO.StreamWriter(pathManagerString, true))
                    {
                        file.WriteLine("Manager First Name: " + FirstName_AddEmployee_TextBox.Text); //Writes First Name
                        file.WriteLine("Manager Last Name: " + LastName_AddEmployee_TextBox.Text);//Writes Last Name
                    }
                }
            }
            else
            {
                if (FileExists = File.Exists(pathEmployeeString)) //Check If Employee ID File Exists in emoployee folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else if(FileExists = File.Exists(pathManagerString)) //Check If Employee ID File Exists in manager folder
                {
                    MessageBox.Show("Employee ID Exists Please Choose Another Id #");
                }
                else
                {
                    using (System.IO.StreamWriter file =
                        new System.IO.StreamWriter(pathEmployeeString, true))
                    {
                        file.WriteLine("Employee First Name: " + FirstName_AddEmployee_TextBox.Text); //Writes First Name
                        file.WriteLine("Employee Last Name: " + LastName_AddEmployee_TextBox.Text);//Writes Last Name
                    }
                }
            }
        }

        private void FirstName_AddEmployee_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {

        }

        private void EmployeeID_AddEmployee_TextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&           //Checks Characters entered are Numbers Only and allows them
    (e.KeyChar != '0'))
            {
                e.Handled = true;
            }
        }

        private void IsManager_CheckBox_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}

Body:
Change this line of code of Login_Btn_Click method:

Old

FileName = Employee_Id_TextBox.Text=".txt";

Replacement

 FileName = Employee_Id_TextBox.Text+".txt";

And update location of both folder:

string ManagerPath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Managers";
string EmployeePath = @"C:\Users\mogee\Visual Studios Project Custom Files\Rent A Car Employee Id's\Staff";


问:
Zepto.js doesn't return false?
I'm trying to bind an event handler to a click function using zepto.js.  Normally in JQuery I can just say return false and the actual click will never go through.  Does Zepto not support this?  And if so, how to get around this?</p>

答: To duplicate the behaviour of returning false in a jQuery event handler you need to call event.preventDefault() and event.stopPropagation().

Title: Zepto.js doesn't return false?


问:
BigQuery Standard Get first not null value when grouping
I have a table like this:

```<code>CUSTOMERS_ID  DATE_SALES  DIMENSION
MARIO1        20200201    NULL
MARIO1        20200113    Spain
MARIO2        20200131    NULL
MARIO3        20200101    France
MARIO3        20191231    Spain
</code>```

and I need to order by CUSTOMERS_ID and DATE_SALES DESC fields. Then I want to group by CUSTOMERS_ID field and get first not null value of DIMENSION field.
The output table would be:

```<code>CUSTOMERS_ID  DIMENSION
MARIO1        Spain
MARIO2        NULL
MARIO3        France
</code>```

Any ideas? I have tried COALESCE functions, FIRST_VALUE, and I have not the results I had expected.

Thanks in advance!

答:
We can just use a ROW_NUMBER trick here:

```<code>WITH cte AS (
SELECT CUSTOMERS_ID,
       ROW_NUMBER() OVER (PARTITION BY CUSTOMERS_ID
                          ORDER BY -1.0*UNIX_SECONDS(DATE_SALES) DESC) rn
    FROM yourTable
)

SELECT CUSTOMERS_ID, DIMENSION
FROM cte
WHERE rn = 1
ORDER BY CUSTOMERS_ID;
</code>```

The logic is to order row number descending by the negative number of seconds since the epoch.  This places more recent sales first, and also places NULL at the very end, so a NULL value would only receive row number 1 in the event that no non NULL dimension data be available.

Body:
I have a table like this:

CUSTOMERS_ID  DATE_SALES  DIMENSION
MARIO1        20200201    NULL
MARIO1        20200113    Spain
MARIO2        20200131    NULL
MARIO3        20200101    France
MARIO3        20191231    Spain

and I need to order by CUSTOMERS_ID and DATE_SALES DESC fields. Then I want to group by CUSTOMERS_ID field and get first not null value of DIMENSION field.
The output table would be:

CUSTOMERS_ID  DIMENSION
MARIO1        Spain
MARIO2        NULL
MARIO3        France

Any ideas? I have tried COALESCE functions, FIRST_VALUE, and I have not the results I had expected.

Thanks in advance!

Body:
We can just use a ROW_NUMBER trick here:

WITH cte AS (
SELECT CUSTOMERS_ID,
       ROW_NUMBER() OVER (PARTITION BY CUSTOMERS_ID
                          ORDER BY -1.0*UNIX_SECONDS(DATE_SALES) DESC) rn
    FROM yourTable
)

SELECT CUSTOMERS_ID, DIMENSION
FROM cte
WHERE rn = 1
ORDER BY CUSTOMERS_ID;

The logic is to order row number descending by the negative number of seconds since the epoch.  This places more recent sales first, and also places NULL at the very end, so a NULL value would only receive row number 1 in the event that no non NULL dimension data be available.