Send to serial x0A

Question: I managed my COM device (Serial connect) under the Linux console.
For example, if I had run this command:
echo -ne '\x55\x90\x17\x01\x00' > /dev/ttyACM0
my device receive command and execute, but if i Run this command:
echo -ne '\x55\x90\x0A\x01\x00' > /dev/ttyACM0

device do not execute this command.
I know, the problem with x0A, because of this code associated with the command.
My question, how to send xOA string to the device.
Comment: May I suggest you edit your question a little to make it easier to read, say, by using the code formatting?
Answer: This article is a related Q&A of a similar phenomenon when communicating with perl.
RS232 issue with 0x0A and 0x0D while sending a message
It seems to be ok if you disable the function to convert the serial port character code by the stty command etc.
Unix man pages: stty (1)
Comment: yes, I use stty -F /dev/ttyACM0 115200 raw -echo, manual is too complicated, what exactly parameter I must add to stty?
Comment: Firstly, if there is a setting on the device side try it the same way (raw), then, try disabling the four items in that article.  -icrnl, -ocrnl, -onlcr, -opost.
Comment: stty -F /dev/ttyACM0 115200 raw -echo -icrnl -ocrnl -onlcr -opost, do not help.the device doesn't have any problem, when I send this command under Windows with RealTerm 0xA, device accepted command like intended, 0xA is registry address in the device.
Comment: Another thing to think about is try `echo -e` instead of `echo -ne`.
Comment: My question is still open, how to send 0xA to a device like a data? currently, stty interpreted and sending like a "new line" command.
Comment: Guys, I am new at this forum, maybe this is the wrong place for this question?
Comment: There may not be new advice for people watching the tag "serial-port". How about re-asking with a tag such as a large range of linux/unix, or the distribution you are using(such as ubuntu), or the hardware you are using(such as raspberry-pi)?
Answer: Some tty devices keep LF to CRLF conversion output on. You can disable it using:
stty -onlcr -F /dev/ttyACM0
or, for strict POSIX stay
stty -onlcr < -F /dev/ttyACM0
and then try
echo -ne '\x55\x90\x0A\x01\x00' > /dev/ttyACM0

Send to serial x0A


For a perfect group $G$, does taking universal perfect central extensions stabilize?

Question: Let $G$ be a perfect group (finite, if necessary). Let
$$1\rightarrow K\rightarrow E\rightarrow G\rightarrow 1$$
be a universal perfect central extension of $G$, so that $K$ is isomorphic to the Schur multiplier of $G$, and $E$ is the Schur cover of $G$, and is itself a perfect group.
Is $E$ "universal" in the sense that $E$ is its own Schur cover?
Answer: Yes, because for a perfect group $F$ one has Grün's lemma $$Z(F) = Z_{2}(F).$$
So if one considers the universal perfect central extension of $E$
$$1\rightarrow L\rightarrow F\overset{\pi}{\rightarrow}E\rightarrow 1$$
then
$$
\pi^{-1}(K) \le Z_{2}(F)
$$
(I am assuming for simplicity that $K \to E$ is inclusion)
so that $\pi^{-1}(K)$ must be central in $F$, so
$$
1\rightarrow \pi^{-1}(K)\rightarrow F\overset{\pi}{\rightarrow}G\rightarrow 1
$$
is central, etc.
Comment: @JEFFYELTON, thanks for the correction, I hadn't noticed that $\pi$ was on the wrong arrow!
Comment: Here you're assuming that $G$ is center-free?
Comment: @JEFFYELTON, sorry, one more correction. Hopefully is ok now. Thanks!
Comment: Okay, so just to be pedantic, you're proving that the universal perfect central extension of a perfect group itself has no perfect central extensions.
Comment: @JEFFYELTON, yes, I believe that's it.


Some results in a view appear twice or more

Question: On a multilingual site I have a view of all nodes with the following configuration:

View type: Page
Format: Table
Fields: Content (title)
Filter criteria: Published nodes
Sort criteria: Publishing date (descending)
Paging: Show all content
Pager link: No
Advanced settings: No
Rendering language: Default language of the website

My problem
My problem is that some results in the view (some links to nodes) appear twice or more, with some results appearing even five or six times.
The website is otherwise working fine with no errors.

What I have tried to solve this problem
1. Adding a view language criteria
If I try to add a filter criteria based on language, I get four options:

Original language (content)
Translation language (content)
Original language (content revision)
Translation language (content revision)

Thus:

I have tried to add the filter criteria Original language (content) were I chose the default (Hebrew) language of the site.
I have tried to add the filter criteria Translation language (content) were I chose "Which is not one of (everything)" so there won't be any translation.

None of these approaches helped.
2. Detecting possible SQL table joins
I don't recall ever joining any table with any table but anyway in my website under /admin/structure/views/settings I chose to show a SQL query above previews of a views.
I got the following output above the preview of the discussed view when no language filter criterias existed:
SELECT "taxonomy_index"."created" AS "taxonomy_index_created", "node_field_data"."nid" AS "nid"
FROM
{node_field_data} "node_field_data"
LEFT JOIN {taxonomy_index} "taxonomy_index" ON node_field_data.nid = taxonomy_index.nid
WHERE "node_field_data"."status" = '1'
ORDER BY "taxonomy_index_created" DESC

My question
How to solve my problem?
Comment: Is "some links to nodes" an entity reference? If so this has been asked many times on this site, and it is because of how joins work in SQL. Search "views reference duplicate". If not, we need more information.
Comment: I have added data about possible SQL table joins.
Answer: For a multilingual site you need to add a filter for the language. There are different strategies, filter the Translation language (content) by the current language (= Content language selected for page), or filter the Default translation (content) (a flag indicating whether this is the default translation) (= True) and then translate when rendering the view row (in the middle section of the View). The second method is for displaying all nodes one time even if not translated into the current language.
Since you've answered my question in a now deleted comment that your site is multilingual you need this filter to get only one hit per node for nodes with multiple translations (I don't know if you have any). As commented by @cilefen, the other source for duplicate entries are JOINs to other entity tables, for example taxonomy. Enable the display of SQL queries at /admin/structure/views/settings and check for JOINs.
Comment: **Comments have been [moved to chat](https://chat.stackexchange.com/rooms/150424/discussion-on-answer-by-4uk4-some-results-in-a-view-appear-twice-or-more); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed.
Answer: I wrote in the question:

Sort criteria: Publishing date (descending)

But I was wrong and it was actually:

Sort criteria: Taxonomy term publishing date (descending)

So, the problem was caused due to me mistakenly choosing the sort criteria "Publishing date" (Taxonomy term") instead just "Publishing date".
Choosing a sort criteria based on a date in which the content was related to a term caused the number of duplications in the view was corresponding to the number of taxonomy terms in the each node.
Replacing Sort criteria: Taxonomy term publishing date (descending) with Sort criteria: Publishing date (descending) solved my problem.


Why do musicians play too loud on social gatherings?

Question: For example on a wedding, restaurant,etc. so that guests can't talk to each other because it's too loud. Even when people ask them to turn the volume a bit down, they turn it down for a couple of songs, then they will turn it up again.
Comment: For me, the problem with the question is only that the OP has lumped weddings & restaurants into the same pigeon hole. They are not vaguely similar.
Comment: @user87626 - I have, many times in different bands I've played in. Too many times. A better question may be how do you get them to play quieter for longer.
Comment: I'd always question why anyone would book a band when what they actually want is a record/mp3 player with a volume control. If you want muzak, book muzak.
Comment: This is too close to the truth for many musos. Try to keep it open.
Comment: Also this might lead into a question about how playing nightly gigs affects the hearing of professional musicians.   This is not a snide remark, but you can only play in such a loud environment for so long before suffering some hearing loss, which means you need it louder, which means you damage your hearing more....
Comment: The 'close' brigade needs to look at the number of views this question has already. It shows what interest there is.
Comment: @Tetsujin popularity does not imply appropriateness...
Comment: Most likely answer is someone else came by after a couple songs and asked them to turn it back up. Audiences like it loud, but there's usually a few people who don't like it so loud. But we're in the minority
Comment: Last restaurant I worked in was with  a band which played for dining, then later morphed into 'let's break as many plates as we can, and dance on them' - yes,  a Greek restaurant. Learned about all sorts of strange time signatures then. Hardly any washing up at the end of the night, though!
Comment: @Tim Thanks, but I was referring more to the restaurants and weddings I've been to. I've never been to a real live band performance before, so I can't really comment on that.
Comment: @ToddWilcox - and why is it that those who don't want it loud often decide to sit close to the band and continue their conversations shouting..?
Comment: @Tim You'll have to find them and ask. I hate it loud. I've never brought larger than a 50 Watt 1x12 amp on stage for myself. I wear earplugs for shows that aren't classical or musical theatre, although I did put in earplugs for an MT show one time because some of those have gotten very loud.
Comment: @Tetsujin - Yeah, my experience is that restaurants (at least family and fast food ones) use radios more often than other types of prerecorded material...and way more often than live bands.
Comment: Voted to reopen. It might be borderline, but 1k views, 13 upvotes & 6 answers inside a day has got to be a sign people want to see it.
Comment: @AakashM - and each member has a vote.
Comment: Vote to re-open. This is just one aspect of musical practice. One that obviously needs addressing and has struck a chord, so to speak.
Comment: I have to admit, I initially voted to close it too - can't change your mind unless there's an edit.
Answer: Restaurants are where most folk go to eat, and chat. Weddings are where a lot of folk are given an opportunity to catch up with old friends and acquaintances. Both situations really don't need any more than background music, to cover any awkward silences. So any band playing under those circumstances needs to be aware that it's  there as the secondary part of the proceedings, not the primary.
Been in that situation hundreds of times, and understood that the band's place then was to provide background music. Not difficult - play more gentle, slower, peaceful stuff, at a lower volume, until those proceedings have finished, at which point the band can open up, and be the centre of attraction for the rest of the evening, or whenever.
It's not difficult, provided placing of the p.a.speakers is carefully considered. Playing at lower levels with those behind or level with the band never caused any feedback problems, and they could be moved forward if needed later. Good drummers can and do play quietly - or should be sacked !
The question says 'why?'. It's the same at rehearsals a lot of the time - I've walked out of auditions because the rest of the band wouldn't turn down to a sensible level. Partially it's the 'more of me' syndrome, where everyone wants to hear themselves more than the others, and the vicious spiral is made. Partially it's the 'I can only sound good when I'm loud' syndrome - guitarists and drummers in particular. Some of which can be alleviated by use of monitors, which can aggravate the situation by increasing the sound pressure on stage. Got round that on occasions by only using the monitors when the band was background music providers! Partially it's a purely selfish power game where 'I can play louder than you' come into play, literally.
Bottom line - hire a band of maturely thinking musos, who can get as much enjoyment from playing quietly as they can from belting it out, (someone will be listening, and appreciate it) or just go back to boring old wallpaper music.
Comment: @Clockwork - apparently at my school (after I had left) humming was used to similar effect. Never found out exactly what the reasons were.
Comment: Reminds me of a situation at school when the entire class would start out whispering very loudly, and progressively talk stronger than the next guy until it's as loud as a marketplace.
Answer: Blame the booker, not the band.
A restaurant is a different kettle of raspberries - there what you want is a solo electronic keyboard player or a guitarist with a volume control, not a band with a drummer, trumpeter or saxophonist & an absolute minimum volume they can feasibly play at.
It's really, really uncomfortable trying to play below minimum volume in a venue that would rather you weren't there at all.
So, if anyone books a 5-piece live band for that, they need their heads testing.
If you want to be a rock venue, stop trying to be a restaurant.
There is no 'long plot' to a restaurant. Every customer is there for an hour or two & no two sets of diners are in the same frame of mind at the same time. Each set of diners wants their own individual experience & usually doesn't want to be subsumed in an overall melée they did not ask for. [Of course, they ought to have checked the restaurant was of a similar mindset to them before booking, so some of the onus is back on the diners. You don't go to Hooters or TGI Friday for a romantic dinner for a middle-aged couple, live band or no live band, in the same way you wouldn't go to McDonald's either. Pick your venue, people.]
A wedding, on the other hand, has the same group of people all day, then they double the numbers at night as the party proper starts. It clearly has a set plot, known in general to all the attendees. It's not a dinner out, it's not a brief social gathering, it's a day-long celebration. It's not a sprint, it's a marathon. It has a long-plot, something for everyone, hopefully.
Let me take mine as an example - after all, it's the one I remember best & also had the biggest hand in organising.
For the 'service' a classical pianist, opera singer & a string quartet. Everybody had to damnwell shut up & listen, then applaud afterwards. Done. Thank you.
For the 'breakfast', nothing - speeches & stuff, you don't want music over that.
As everyone settled into their 5th glass of champagne and got on with the serious business of getting drunk & catching up with old friends & relations, a couple of pianists, one classical the other jazz, swapping duties every so often while the other got caught up with the drinking, making some very good muzak in the background, which few noticed at all. Those who did were impressed.
Later, as we get into 'evening' then all the big, sprawling 12-seater tables are cleared, replaced with fewer smaller tables - making some gather in different groups, others head for the quieter main lounge bar & leaving a very large open space in the middle. The last until now hidden segment of the room is opened up too, to reveal a stage, set & ready to go.
Cue the first 'band'; which is me, my wife & a guitarist friend. Couple of songs that everybody crowds in to listen to - well, that's kind of what they came for.
We then swap up to her full-time ten piece function band & the gig proper starts.
Dancing & much revelry ensues. The old folks go reclaim their places in the other bar, where they can talk to their hearts' content.
Three hours later, we swap to a DJ & some old faves for our age group.
Once we hit the hotel's curfew time, we drag back the 2 pianos & let the pianists again take over [with much improv, duels & impromptu karaoke] until the last guest falls over around 4am.
Good time had by all.
Loud enough for those who wanted it, quiet enough for those who didn't.
Answer: IMO this is actually an important question to think about. The underlying conflict is this:

The musicians see it as their job to make the audience feel good by listening to good music (regardless of what kind of gig this is). They can't do that if the audience doesn't really hear the music. In particular, if the ambient sound level of the audience talking is higher than the music level, then even those in the audience who really want to focus on the music won't be able to. And the musicians can't possibly give a good performance if they constantly need to think "how do I deal with this hostile mob" instead of sinking into an actual deep and meaningful act of art.
Some/many/most of the audience (don't over-generalize!) see it as their "job" to talk with old friends, make new acquaintances, etc.. They're not really there for the music at all, they more accept it as a nuisance that needs to be accepted "because convention dictates there has to be live music".

Well, force those two groups in an enclosed space and nobody's going to have a good time. Ok, you perhaps think the solution is: "the musicians are payed for a specific job which is to suck it up and just produce some sweet tones in the background, and make the whole event look more stylish than if there's canned music". In other words, you're reducing the musicians to a better wallpaper. You have to see that this is not a role that self-respecting musicians will ever be happy with. Sure, if the pay is right then many will do it – but seriously, what's the point?
There is a reason why there is music at social gatherings: many people like music a lot – and music is at its most powerful when it's really live, when it really reacts with the audience. But that doesn't work if none of the audience is even able to react to the music, because it's drowned by all the talking.
One solution is, indeed, to make the music so loud that the audience has no chance to drown it out. At least for some styles of music it's technologically easy, and it guarantees that people who want to listen and/or dance can do it. If you don't like it – well, consider that you can talk to your friends any time, really. But the people who like to dance with their friends to live music can't do that any time. Sure they can go to a concert where everyone has payed to listen, but that always has a different atmosphere.
I would however agree that brute force loudness is never a very good solution, even if there is more dancing than eating. It certainly isn't any good in a restaurant setting.
The real solution is that everybody respects everybody else and find a compromise. But the musicians are in a difficult position here: turn the volume down and they disrespect those audience members who want good music. Turn the volume up and they disrespect those who want to be able to talk.
The audience meanwhile has it easier: they can move around. If you want to talk, move somewhere where it's not that loud, and in particular where the noise that you make by talking won't reach the stage. This way, the musicians don't need to turn up the volume. Of course in a seated dinner, this requires planning ahead, which often doesn't work.
So if you find yourself in a situation where you feel you have no option but scream-talk over the music... well, take a pause and look around what the others in the audience want. Are many of them looking to the stage? Then maybe you should as well, and wait until the band is finished for more talkey interactions. Are many of them dancing and only occasionally talking in their neighbour's ear? Then maybe you should as well.
Or are many of them just looking unhappy and screaming in their neighbours' faces all the time? Then I suggest you reach out to those and say, let's move to the other room to talk a bit.
On the other side, I would say that the musicians (and sound engineer, if any) also should always consider what sound level really is appropriate, and not just be loud because they can. If the audience has no option to move, and really mostly wants to talk, then they will inevitably just talk louder and louder, and then turning up the music volume is just an arms race. Ironically, in my experience being quieter is often the most effective way of getting the audience to listen. In particular, playing entirely without amplification can do a lot to gain the audience's respect, and makes it much more likely that loud talking will be effectively hushed down by those who want to listen, whereas those who want to talk can simply whisper in the back or adjacent room. But that does require that everybody in the audience cooparates: just one noisy desk that doesn't even notice there is live music would ruin an unplugged performance. Also, many music styles just don't work without amplification.
Generally, and probably most effectively, there are a couple of things that party organisers should think about, which can help a lot:

Try to not trap two "hostile armies" in an enclosed space. In particular not a space whose acoustics carries all the sound everywhere. Select a venue where there's either a "music room" and a "talking room", or where the sound from the stage-end won't reach the rear-end too much and vice versa. Don't select an concert hall that's designed for quietly listening to delicate music, and definitely not an echoey sports hall with no acoustic treatment at all.
Make a proper programme, where it's clear when the audience is meant to eat and/or talk, when they're meant to listen to music, and when they're meant to dance. Try your best to ensure the audience respects this, and to ensure the musicians can focus on when they really have the audience's ears.
Comment: I'm not a musician, so this is just my opinion, but maybe, just maybe, _most_ people, in fact, do not go to _weddings_ or _restaurants_ because they've booked a good band they want to hear.  I think this take on the situation is awfully (and unrealistically) biased towards the band in the band vs. wedding guest or band vs. dinner-at-restaurant conflict.  Tim's answer is correct: the band is there for _background music_ and if the band doesn't like that they shouldn't take the gig, rather than turn up their volume.
Comment: @davidbak - honestly, this is the fault of the booker not the band. It's quite likely the band won't know really what they've been booked for until they get there. If they're a 5-piece rock band & they discover they're in an otherwise sedate fairly standard restaurant, there's not a lot they can do about it if they want the money. Anything with a drummer has an absolute minimum volume they can play at. Weddings you expect to get loud as the night goes on. All weddings do that. It's the norm. It's generally catering to the friends of the couple - mid-20's at a guess, not the 60+ relatives.
Comment: I was part of an open mic night a few months ago,and a party of people was sitting about as close to the stage as was possible. Other places available.It was obvious they hadn't come for the music,as their conversations were conducted in a very loud manner.So much so that at one point the guy performing put down his guitar,went over,and in no uncertain terms,with many expletives explained why they weren't doing 'the right thing'.Not sure it was the correct thing to do,but a lot of us musos felt someone had to do it.It spoiled the night somewhat, but what else was left?And - whose fault was it?
Comment: Bar gigs are about selling beer (or hard seltzer or whatever people drink these days) and that's it. It's sad but true. But also bar gigs pay, so… IMHO the best a band can get out of a bar gig is picks and sticks money plus the chance to test material and see if they can actually get the people who are not there for the music to listen to the music.
Comment: @Tetsujin - interesting, an aspect of how this stuff actually works that I didn't know.
Answer: You don't need musicians to have this effect: within a social gathering of certain size, conversations create a background noise and people raise voices to get over that background noise in their conversation group.  Everyone does it, so that raises the background noise.
This kind of escalation also happens within a band itself but musicians tend to arrive at some kind of balance during practice.  The background din of people trying to talk over the band disrupts that balance, so band members raise their volume to hear themselves over the others.
The solution for that in large concerts is monitoring: there are speakers directed at the musicians (or earphones) that give them a satisfactory feedback of what they are playing.  Very large acts may provide a personal mix for each player via their own sound technician; more common is one technician for both a monitor and an audience mix.
Weddings/restaurants tend to be venues where musicians (when amplified) just work with stage amps rather than a monitoring/PA setup.  That's more susceptible to loudness wars.
However, in my experience it is even tricky to get a DJ to keep the music at background levels in social gatherings, presumably because they take pride in their work and want it to be heard.
Answer: I can't see the obvious answer spelled out yet:
Musicians enjoy playing together; they generally enjoy hearing themselves and their bandmates make music, and so there is a natural tendency to play loud enough that they can hear themselves well.
And a related reason: some musicians can play effectively only when they can hear themselves and/or each other well. (Obviously, this depends on the instruments, and probably the style of music. But I've had a couple of occasions when I really couldn't hear what I was playing, and it was really hard work and not at all enjoyable.)
Now, a good band (professional or not) ought to a) care more about the needs of the event than about their own enjoyment, and b) be able to adjust their volume level to suit (subject of course to the minimum possible volume level that most mechanical instruments have). But not all bands care enough and/or are skilled enough to do so.
Also, there may not be complete agreement between whoever hired the band (and/or is paying them), and everyone else present (whether listening and enjoying, ignoring, or enduring patiently). If some have asked for it to be quite loud, and then others ask for it to be turned down, they can't please everyone.
Similarly, those desires may not be communicated well. If one person asks for it to be turned down, but it looks like many other people were enjoying it a little louder, then there's a judgement call to be made.
Either way, I guess it's natural for musicians to err on the louder side, because that's what they themselves want.
Comment: I remember early on when I was supposed to be playing the bass line on the piano. Afterwards I was sort of complaining that I wasn't even sure if I could be heard at all since the amplified guitars were so much louder, but the instructor in the audience said she could hear me just fine and I was adding something to the piece.
Answer: They can't hear themselves.
Many rock and pop musicians who are always loud (esp. drums) have damaged hearing from playing loud. They can't hear themselves play, so they play louder. Then the guitars etc have to turn it up because they can't hear themselves...
This is true in all genres where I have played. In Blasmusik brass bands the trumpeters are always too loud, and everyone else has to blow harder to be heard. You need a really authoritative conductor to keep the lid on 40 determined polka hounds. Also they are used to playing outside or in beer tents, where you do need to be louder than inside a building.
In jazz bands and big bands it is common to have monitors so the band can hear each other. In some venues the acoustics are so bad you can't even hear the drums. We saxes in the front row have no problem hearing the trombones, who are trying to fry our brains from behind. But we need to hear the lead sax or we are lost. Thus we tend to use those deflector things, in case you wonder what that's about.
So basically it's

lack of discipline; The band leader has to keep it down.
combined with bad acoustics (oh, the awful village halls and churches we've played in)
not enough kit. You need a monitor for bass and keyboard.
Comment: Anyone who books a brass band for a restaurant gets what they deserve ;))
Comment: Had to upvote, too many truths for previous downvote.
Comment: The brass band regularly plays for weddings of band members. Obviously they won't fit in a little place, but village halls are very popular.


How to deal with one hot encoded variables in a clustering problem?

Question: I'm using a dataset with customer card transactions to solve a clustering problem.
On a first approach, I'm trying K-means using R packages NbClust and cluster
My dataframe is normalized and it contains the following (sample):
as_tibble(full_dataset_log.stand)
# A tibble: 33,215 x 9
   monetary frequency recency_days GENDER_F0 GENDER_F1 GENDER_FNA
      <dbl>     <dbl>        <dbl>     <dbl>     <dbl>      <dbl>
 1   0.292    -1.10         1.02       1.28     -1.28     -0.0325
 2  -2.15     -1.10         0.301      1.28     -1.28     -0.0325
 3  -0.905     1.15        -0.614     -0.782     0.784    -0.0325
 4   0.968     1.77        -0.844     -0.782     0.784    -0.0325
 5   1.90      2.06        -2.15      -0.782     0.784    -0.0325
 6   1.90      2.06        -2.15      -0.782     0.784    -0.0325
 7  -1.10     -0.231       -0.423     -0.782     0.784    -0.0325
 8   1.55      1.77        -0.543     -0.782     0.784    -0.0325
 9   0.0536    0.196        0.0471    -0.782     0.784    -0.0325
10   0.523     0.0808       0.558     -0.782     0.784    -0.0325
# ... with 33,205 more rows, and 3 more variables:
#   GENDER_M0 <dbl>, GENDER_M1 <dbl>, GENDER_MNA <dbl>
>

This is the code I'm trying with 6 clusters:
k.means.fit_log <- kmeans(full_dataset_log.stand, 6)

My issue is how to deal with the GENDER variables which have been hot-encoded:
GENDER_F0
GENDER_F1
GENDER_FNA
GENDER_M0
GENDER_M1
GENDER_MNA

They just don't seem to make sense to have as separate variables and I was wondering how I can solve this problem.
Originally, the variables were:
GENDER_M: can be 0, 1 or NA
GENDER_F: can be 0, 1 or NA

Now, on this other question I wrote that hot encoding these variables didn't work out very well. I tried:
GENDER_M0: 1 for all the records that contain 0 in column GENDER_M - 0 otherwise
GENDER_M1: 1 for all the records that contain 1 in column GENDER_M - 0 otherwise
GENDER_MNA: idem
GENDER_F0: idem
GENDER_F1: idem
GENDER_FNA: idem

So, in total, I have 5 possible combinations:
NA/NA
0/0
0/1
1/0
1/1

1 means that there's a presence of the respective gender in the buying patters of the customer. For example, if a customer buys razors repeatedly, he will get a 1 in column GENDER_M.
Thanks for any help, I'm quite new to R and data science!
Answer: Obviously his encoding is very badly performed.
A better encoding would use just 2 or 3 variables: M, F, maybe "other". NA can be simply encoded by setting neither of them, and I doubt you'll have many records with both or neither.
But in the end, your problem is much more fundamental. It's not about getting k-means to run - but about asking the right question. The question shouldn't be "how does k-means cluster the data if I make all these encoding and preprocessing choices" I assume. K-means is a least squares minimization technique. It attempts to find a good solution for "what is the least-squares reduction of this data to k vectors". But what good is a least square on your one-hot variables? Probably not worth running this.
In the end, you'll only find that your data is best represented by three clusters: males, females, and NA.
Comment: @Anony_Mousse, thanks for your help. Actually, it's not just male, female or NA, please see my edited question above.
Comment: Clearly encoding 5 disjoint cases using 6 variables is redundant, isn't it? Plus, you ignore your domain knowledge about the problem to solve...
Answer: There are a couple of options for this case;

Look at the data dictionary (assuming you have it) and decode the meaning of the encodings.
If you do not have the data dictionary AND If you did not collect the data AND that the data was provided as it is in its current format, THEN decide whether you want this feature or not.
2.1. Assuming you want to keep this feature and you don't have the data dictionary, THEN I think best guess is to figure out if the feature values make any sense to you (based on common values etc).
If you collected the data then I think you should know what the feature encoding values are.
You did not collect the data, AND you do not have the data dictionary AND the feature values make no sense to you THEN discard the feature BECAUSE Computer is a dumb machine. If you can't interpret the feature value, don't expect any algorithm to do it for you either.


How do i classify a signal by using LDA

Question: I am using LDA algorithm to classify a signal, how can i do that with multiple classes ? I have read some references but don't get the result.
I I've looked example code at link
but it doesn't have explicit classifier part for me!
Answer: You can use OpenCV to keep doing this.

How do i classify a signal by using LDA


How can i import plain password that are not encrypted during a user migration?

Question: I am able to migrate all the datas of users account including the password but it doesn't work due to encryption and hash in drupal 8.
My password are not MD5. They are not encrypted, in csv file they are like normal plain text.
I've seen here :
https://www.drupal.org/docs/8/api/migrate-api/migrate-destination-entityuser

If the incoming passwords are not plain or are not MD5 hashed you'll
  have to deal with this in your migration

My password are plain so i guess it should work.
Here is what i've tried but the password are imported but not encrypted :
destination:
  plugin: 'entity:user'
  plaintext_passwords: true

In the documentation, it is explained how to import MD5 password but not plain password.
What should i use for the configuration ?

EDIT :
I've tried this :
pass:
    -
      plugin: callback
      callable: 'Drupal\Core\Password\PhpassHashedPassword::hash'
      source: passwebservice

And
pass:
    -
      plugin: callback
      callable:
        - 'Drupal\Core\Password\PhpassHashedPassword'
        - hash
      source: passwebservice

Error :

Error: Using $this when not in object context in
  Drupal\Core\Password\PhpassHashedPassword::hash()  [error] (line 215
  of
  Core/Password/PhpassHashedPassword.php)
  0 [internal function]: Drupal\Core\Password\PhpassHashedPassword::hash('9BQmM1')
  1 core/modules/migrate/src/Plugin/migrate/process/Callback.php(54):
  call_user_func('Drupal\Core\Pas...', '9BQmM1')

When i check hash()
public function hash($password) {
    return $this->crypt('sha512', $password, $this->generateSalt());
  }

I can't invoke method this way ($this does not exist in class context) so how can I do ? Is it possible in configuration file ?
Comment: `\Drupal::service('password')->hash($password)`
Comment: @IvanJaros I need a little bit more explanation. I guess it is a 2 step process : i import plain text password in database (i can do this) and then i hash the password with your code ?
Comment: The function you are calling is not a static function.  The docs say only static function.  There is also a known bug for plain passwords.  https://www.drupal.org/node/2816921
Answer: You can use Ivan Jaros' code in two ways:
As you said, preprocess your passwords to convert them to hashes.  This can be done via a Drush script that can be run from the command line.  Drush scripts are just snippets of PhP code that run in the Drupal context.  Run by  the command:
drush @site-alias scr [path to php snippet]
The alternative is to override you CVS Source class and use the preparerow method to hash the password.
  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $password = $row->getSourceProperty('password');
    $hash = \Drupal::service('password')->hash($password);
    $row->setSourceProperty('password', $hash);
  }

As pointed out in the comments, you can also use a process plug-in to do this.  The callback plugin only uses static classes and AFIAK the hash method requires access to the context information that is not available via static methods.
Here's some quick untested code to create your own process plug-in to hash a plain text password.
<?php

namespace Drupal\my_mode\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Converts a plain password to an hash.
 *
 * Example:
 *
 * @code
 * process:
 *   password:
 *     plugin: my_module_hash_password
 *     source: field_password
 * @endcode
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "my_module_hash_password"
 * )
 */
class HashPassword extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $hash = \Drupal::service('password')->hash($value);
    return $hash;
  }

}

Comment: Thanx for this explanation. I will try. Do you know if it is possible to do it with `Process plugin: callback` like this : https://www.drupal.org/docs/8/api/migrate-api/migrate-process/process-plugin-callback This way, the hash could be done with the migrate configuration file
Comment: Since it's a simple value transformation, that should work.  FWIW - I have mostly done custom source plugins that override prepareRow and some other methods because of the need for more detailed processing.  E.g. validating terms and other info from the source and skipping rows (return False).  Doing it this ways a bit more complicated to set up but more flexible.
Comment: I've updated my question. If you can have a look and tell me what you think ? I would like to know if it's possible to use  configuration file because i've spent a few hours on migrate module and i want to pursue it to the end
Answer: I have written custom migration to migrate users from CSV file. I have successfully migrated the user but when i tried to login its give me login error so I have checked my migration code found md5_passwords: true in it. md5_passwords convert any string to hashed string with md5() encryption. so i have written my custom plugin and added to my migration code without md5_passwords: true.
Here is the step by step solution:

Create custom module and define your plugins file in it:
custom_module->src->Plugins->plugins_name->process->plugin_file.php

in my case:
custom_module->src->Plugins->migrate->process->HashPasswords.php

Write this example code in your plugin_file.php
<?php

namespace Drupal\custom_module\Plugin\migrate\process;
use Drupal\Core\Password\PhpassHashedPassword;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
* Converts a plain password to an hash.
*
* Example:
*
* @code
* process:
*   password:
*     plugin: hashpasswords
*     source: password
* @endcode
*
* @see \Drupal\migrate\Plugin\MigrateProcessInterface
*
* @MigrateProcessPlugin(
*   id = "hashpasswords"
* )
*/
class HashPasswords extends ProcessPluginBase {

/**
* {@inheritdoc}
*/
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
   $passwordHasher = new PhpassHashedPassword(1);
   $hashedPassword = $passwordHasher->hash($value);
   return $hashedPassword;
  }
} ?>`

Now write your migration code and add this custom plugin.
id: ROF_user
label: 'Migrate ROF User from CSV'
source:
  plugin: csv
  path: modules/custom/custom_module/csv/user.csv
  header_row_count: 1
  keys:
    - ID
process:
  uid: ID
  name: name
  field_first_name: firstname
  field_last_name: lastname
  mail: email
  pass:
    plugin: hashpasswords
    source: password
  roles:
    plugin: explode
    delimiter: ','
    source: roles
  status: status
destination:
  plugin: 'entity:user'
migration_dependencies:
  required: {  }
  optional: {  }


Can I Force Implicit TLS Connection For Port 587 On Postfix?

Question: I have read many articles saying port 587 by default is explicit TLS. This means it's STARTTLS. It asks the server on an unsecured connection if TLS is supported and if it is, it continues with an encrypted connection. Implicit TLS (port 465) however is secure from the beginning of the connection to the end, it is never unsecure.
Just for educational purposes, say I wanted to make port 587 implicit TLS. Would I only need to change this in the main.cf file
smtpd_tls_security_level = may
To this:
smtpd_tls_security_level = encrypt
I understand I can use port 465 for the desired result. I just wanted to make sure if implicit TLS is ALSO supported for port 587 as many articles claim so.
I understand if this is possible for 587, it would definite the purpose. The reason why port 587 is the preferred port between the two is simply because some email clients dont support encryption
Answer: Certainly it is possible to put any service to listen on any port, such as SSH on port 443 (HTTPS) which is a common trick for bypassing port based firewalls. You could change this in master.cf for the smtpd instance listening on port 587. However, you should not change it in main.cf as it will affect the instance accepting incoming mail on port 25, too. The SMTP protocol (RFC 5321) must begin with plain text and, thus, always uses STARTTLS.
Howbeit, it does not make much sense to create a configuration that does not follow the IANA's Service Name and Transport Protocol Port Number Registry, the related Internet Standard RFC 6409 & Proposed Standard RFC 8314, 3.3. In practice, the mail user agents (MUA) i.e. the client software expect the standard ports, so they either pick the default port based on the settings or default settings based on the port. Some might not even allow such configuration altogether. You would have to configure both the server-side and the client-side to support this obscure setup. That means more confusion to your users & and requires extra documentation that could become misleading – you have already found that kind of articles. Do not create more confusion but stick to the standards.
Answer: No you can't change what a port is designated for. In the case of postfix, other mailservers expect a certain "payload" when communicating over that port.
When you communicate implicit tls and another mail server handling mail for another domain where you send mail to expects explicit tls, there is a mismatch and the connection will probably be rejected by the other party.
The reason why it needs to ask over a insecure connection if tls is supported, in the case a mailserver where you send mail to, doesn't support tls, i cant answer when everything is tls,and your mailserver doesn't have a answer.
And let's imagine that mailserver is from your biggest clients, you do want to send mail to, so it answers i can't do tls, and your mailserver falls back to non tls, and the mailservers are still able to handle your mail. In the case it isn't able to handle the mail for you or your company you might lose millions of dollars.
When doing tls, in the most cases there is a fallback from secure to non secure
I tried to make it practical for you with an example for better understanding.
Comment: The submission 587 and submissions 465 are not used by other mail servers. MTA to MTA always uses port 25.
Comment: Thank you Ace. That was helpful. So would you recommend port 587 for email clients?
Comment: Enail clients? I just explained you the mail server to server communication. The option you stated is also not for a client communication smtpd_tls_security_level = encrypt
Comment: A lot of mailservers nowadays uses ports 587 for submission, also because some ISP are blocking port 25.
Comment: For *submission* but never for SMTP. Those are two different protocols for different use cases.


MySQL query conjunction acting abnormally

Question: I'm having a problem with a query.  I query from one table using the following process (using php PDO and MySQL):
Build the query string $sql:
SELECT *
FROM  `user`
WHERE (`username`=:username OR  `email`=:username)
      AND  `password`=:password AND  `valid`='1';

And using this array $params:
Params
(
    [:password] => 18155dbf12503d726883784d1d9755f8d3382ba7
    [:username] => firstname.lastname@example.com
)

Call this function:
$results_array = $database->QueryForObject($sql, $params);

public function QueryForObject($query, $binds)
{
     $stmt = $this->db->prepare($query);

     foreach($binds as $bindKey => &$key)
     {
        $stmt->bindParam($bindKey, $key, PDO::PARAM_STR);
     }

     return $this->RunObjectQuery($stmt, NULL , "stdClass");
}

My problem is that the username can be incomplete or even missing, and all it uses to find the user is the password... I'm pretty sure it shouldn't do that, but I can't figure out why.
As a side note, here is the description of my table:
Field            , Type                                           , Null  ,Key  ,Default , Extra
id               , int(10) unsigned                               , NO    ,PRI  ,NULL     auto_increment
username         , varchar(30)                                    , NO    ,UNI  ,NULL
email            , varchar(50)                                    , NO    ,     ,NULL
password         , varchar(100)                                   , NO    ,     ,NULL
first_name       , varchar(30)                                    , NO    ,     ,NULL
last_name        , varchar(30)                                    , NO    ,     ,NULL
rights           , enum('normal','medium','high','admin','super') , NO    ,     ,NULL
last_loggedin    , timestamp                                      , YES   ,     ,NULL
status           , enum('current','expired','temporary')          , NO    ,     ,NULL
valid            , tinyint(1)                                     , NO    ,     ,NULL
other_comments   , varchar(500)                                   , YES   ,     ,NULL
gender           , enum('male','female')                          , YES   ,     ,NULL
company_position , varchar(50)                                   ,  YES  ,     , NULL

Any suggestions are welcomed!!
Comment: Do you have rows with a blank email address?
Comment: Your not passing an email address so any empty email address records will be returned
Comment: The "username" can be either an actual username or an email, so the redundant :username, was on purpose.  It represents whatever the user uses to fill in the username input field.
Answer: This isn't a definitive answer, but I believe I recall a bug with PDO and named bind parameters, with the same named bind parameter appearing more than once. (When we looked into it, it looked as the named arguments were being translated into positional arguments, and the bind_param was only setting one of the arguments.
As a workaround, we ensured that the named parameter appeared only once in the statement.
In your case, you might try (as a test) modifying the SQL so that it has only two named bind parameters, e.g.
SELECT *
  FROM  `user`
 WHERE :username IN (`username`,`email`)
   AND  `password`=:password AND `valid`='1';

Another alternative is to create a third named argument, and provide a separate bind value for the third parameter.
This isn't a definitive answer, just a suggestion of an approach that may allow you to  debug this issue.
(In our case, we went with the workaround, each named argument in the SQL statement was unique, and we provided a separate bind for each parameter.)
Comment: Hmm, both were good ideas! They don't seem to address the issue yet, but I'll keep experimenting. Thanks for your suggestions!  **EDIT** Nevermind!! I left a redundant `print_r(); exit;` statment in while I was adding your suggested changes. I took it out and your suggestions worked!


How to handle Meteor Data that requires state from child component?

Question: Switching some code over in Meteor 1.3 to ES6+ React syntax. Component requires getting Meteor data, so I'm using a createComponent to replace getMeteorData(). The problem is, the old getMeteorData used state from the component, which isn't being accessed by the createContainer component.
Old code:
Component = React.createClass({
   mixins: [ReactMeteorData],
   getMeteorData() {
    var mo = this.state.currentMonth;
    var start = newDate(moment(mo).startOf('month'));
    return {
     events:     collections.events.find({
        $or:       qwry,
        startDate: { $gte: start },
        endDate:   { $lte: end }
      }).fetch(),
    }
  },
  render() {
   ...
  }
});

New Code Thus Far
class Component = React.Component {
 constructor(props) {
  super(props);
 }
 render() {
  ...
 }
}

export default createContainer(({params}) => {
var mo = this.state.currentMonth;
        var start = newDate(moment(mo).startOf('month'));
        return {
         events:     collections.events.find({
            $or:       qwry,
            startDate: { $gte: start },
            endDate:   { $lte: end }
          }).fetch(),
        }
}, Component);

Getting the error "cannot get currentMonth of undefined," since it's trying to access state. Any suggestions?
Comment: Try not to send it from child to parent, it should be the other way around, parent holds the state of the children and passes it down as props... react docs on multiple components :

In React, data flows from owner to owned component through props: https://facebook.github.io/react/docs/multiple-components.html
Comment: yeah, I realize that, but I'm trying to figure out the best way to convert over to the new format based on the way it was being handled before. just trying to figure out if I need to completely rework the way we're getting the "mo" variable in the current code or if there's some sort of workaround for components that previously used the component's state in getMeteorData.
Comment: why can't you just put the getMeteorData function inside of the react.Component? thats fine to do
Comment: check out this blog posthttp://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes
I hope this is what you're talking about...I'm still not 100% sure
Comment: thanks for the resources! I think the issue is kind of specific to using React and Meteor in conjunction with each other. you can't really use the mixins with the React.Component element, which means that getMeteorData() doesn't work the way it should. might just be something we need to puzzle through a bit more on our own, since we haven't been able to come up with or find a decent solution so far.
Comment: Ok I see now, there seems to be a lot of info out there, I found this one pretty quickly: https://medium.com/@SamCorcos/meteor-react-design-pattern-mixins-v-composable-components-990a5411e1b7#.2h8kti4ho
Comment: yeah, that still doesn't really answer my question. thanks though!
Answer: You can split the old component into two partial components: one that holds the state and handles events, and a pure one that merely displays results. Make sure to pass event handlers as callbacks to the child component. Also note how the parent component uses the return value of the createContainer() function.
// Parent component, setState should go here
export default class StateHolder extends React.Component {
  constructor(params) {
    super(params);
    this.state = {myKey: 1};
  }

  incrementKey() {
    this.setState({myKey: this.state.myKey + 1});
  }

  render() {
    return <Container myKey={this.state.myKey} onClick={this.incrementKey.bind(this)} />;
  }
}

// Child component, renders only
class PureComponent extends React.Component {
  render() {
    return

      {this.props.myValue}
      <button onClick={this.props.onClick}>click me</button>

;
  }
}

// Decorated child container.
// Make sure to use this one in parent component's render() function!
let Container = createContainer((props) => {
  let doc = MyCollection.findOne({someKey: props.myKey});
  return {
    myValue: doc ? doc.someValue : null
  }
}, PureComponent);

Comment: @aedm BIG THANK YOU !


Como faço para pegar o valor de uma checkbox selecionada na mainActivity3 e 4 e mostrar esse item selecionado em um textView na main Activity1?

Question: Estou fazendo um trabalho de faculdade onde tenho q desenvolver um aplicativo para pedidos em um bar, ja criei 5 activity aonde a primeira e uma tela inicial e as outras telas de pedidos com checkbox, como faço para pegar os itens selecionados nas checkbox de todas main activity e mostra-los na mainactivity1? E tambem como faço para determinar um "preço" para cada checkbox onde na ultima activity eu possa mostrar o valor total de todas checkbox selecionadas?
Answer: Para pegar o valor do checkbox, você verifica se este está marcado e atribui um valor de referência, ex: [x] Cerveja:
<code>   String valores;
   if(cerveja.isChecked()){
      valores += "1";
   }
</code>
Pq aí se tiver outro check vc vai adicionando os valores, mas aí você fala: Como esse 1 pode identificar que cerveja estava marcado, como tem mais checkbox a string pode ficar : valores = "12354"; então como cada valor representa um item, você faz:
<code>  //Isso aqui na outra activity
  if(valores.contais("1")){
     //cerveja tava marcado
  }
</code>
Mas caso queira pegar o text do checkbox vc faz:
<code> String valor = checkbox.getText().toString();
</code>
Para passar valores entre activitys vc usa isso:
<code> Intent it = new Intent(context, proximaAcitivy.class);
          //Cada chave deve ser unica
          it.putExtra("chave", valor);
          startActivity(it);
</code>
Na outra activity para recuperar vc faz:
<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

 Intent intent = getIntent();
 String text = intent.getStringExtra("chave");

 }
</code>
Sobre os preços, a cada verificação de qual checkbox está marcado, vc salva os valores e passa para outra activity e o soma com o próximo valor, faz o msm na próxima até chegar na última


Does a primitive array length reflect the allocated size or the number of assigned elements?

Question: I declared an array as shown below:
int[] arr = new int[10];

Then I assigned following values to the array:
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;

Then I declared and initialized an integer variable:
int arrayLength = arr.length;

Will arrayLength contain 10, the allocated size of the array or 4, the count of elements that have been explicitly assigned?
Comment: This question has 1 million views due to the extremely generic title that hasn't reflected the content of the question well until 2022, but I don't understand why OP didn't simply [run the code](https://web.archive.org/web/20170723230450/http://importblogkit.com/2017/02/will-this-work/) to see what the output was, unless I'm misunderstanding the question.
Answer: It contains the allocated size, 10. The unassigned indexes will contain the default value which is 0 for int.
Comment: Yes, arrays are static memory allocation.
Comment: Can you show the javadoc? I don't know where this "length" property is.
Comment: @PhilipRego It's in the language specification https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.3
Answer: First of all, length is a property, so it would be arr.length instead of arr.length().
And it will return 10, the declared size. The elements that you do not declare explicitely are initialized with 0.
Comment: Cannot invoke length() on the array type long[]Java(67108980)
Comment: @AlessandroOrnano yep, that's exactly what the answer said would happen.
Answer: To find length of an array A you should use the length property. It is as A.length, do not use A.length() its mainly used for size of string related objects.

The length property will always show the total allocated space to the array during initialization.
If you ever have any of these kind of problems the simple way is to run it. Happy Programming!
Answer: Arrays are static memory allocation, so if you initialize an array of integers:
int[] intArray = new int[15];

The length will be always 15, no matter how many indexes are filled.
And another thing, when you intialize an array of integers, all the indexes will be filled with "0".
Answer: In this case, arr.length will return 10, the size of array you allocated. Logical size doesn't really apply here, as this is a fixed length array.
When you initialize the array:
int[] arr = new int[10];

Java will create an array with 10 elements and initialize all of these to 0. See the Java language spec for details of initial values for this and other primitive types.
Answer: In Java, your "actual" and "logical" size are the same. The run-time fills all array slots with default values upon allocation. So, your a contains 10.
Answer: int[] arr = new int[10];

arr is an int type array which has size 10. It is an array of 10 elements.
If we don't initialize an array by default array elements contains default value. In case of int array default value is 0.
length is a property which is applicable for an array.
here arr.length will give 10.
Answer: int array[] = new int[3];
array.length;

Here we have created an array with a memory space of 3.
This is how it looks actually:
0th  1st 2nd ...........>  Index
2     4   5  ...........> Number

As you can see, the size of this array is 3 but the index of array is only up to 2 since any array starts with 0th index.
The second statement's output shall be 3 since the length of the array is 3. Please don't get confused between the index value and the length of the array.
Answer: It will contain the actual size of the array as that is what you initialized the array to be when you declared it. Java has no concept of the "logical" size of an array, as far as it is concerned the default value of 0 is just as logical as the values you have manually set.
Answer:   int arr[]={4,7,2,21321,657,12321};
  int length =arr.length;
  System.out.println(length); // will return 6

  int arr2[] = new int[10];
   arr2[3] = 4;
  int length2 =arr2.length;
  System.out.println(length2); // // will return 10. all other digits will be 0 initialize because staic memory initialization

Answer: It contains the allocated size, 10. The remaining indexes will contain the default value which is 0.
Answer: If you want the logical size of the array, you can traverse all the values in the array and check them against zero. Increment the value if it is not zero and that would be the logical size. Because array size is fixed, you do not have any inbuilt method, may be you should have a look at collections.
Comment: This is just an "I assume 0 is not a valid value" size and if that is helpful is kind of doubtful.
Comment: I just came up with an idea to obtain the length of the array (0's are invalid). As i said you can use collections for more precise data manipulation.
Answer: It should be:
int a = arr.length;

Parenthesis should be avoided.
Comment: Welcome to stack overflow! Since this a question that's well over a year old, and already has six other answers, I would expect a longe answer than this. Moreover, you're not answering the point of the question - merely fixing a typo that has already been targeted in an answer (which answers the question) _and_ a question comment.
Answer: Java arrays are actually fixed in size, and the other answers explain how .length isn't really doing what you'd expect. I'd just like to add that given your question what you might want to be using is an ArrayList, that is an array that can grow and shrink:
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
Here the .size() method will show you the number of elements in your list, and you can grow this as you add things.
Answer: Arrays are allocated memory at compile time in java, so they are static, the elements not explicitly set or modified are set with the default values. You could use some code like this, though it is not recommended as it does not count default values, even if you explicitly initialize them that way, it is also likely to cause bugs down the line. As others said, when looking for the actual size, ".length" must be used instead of ".length()".
public int logicalArrayLength(type[] passedArray) {
    int count = 0;
    for (int i = 0; i < passedArray.length; i++) {
        if (passedArray[i] != defaultValue) {
            count++;
        }
    }
    return count;
}

Answer: if you mean by "logical size", the index of array, then simply
    int arrayLength = arr.length-1;
since the the array index starts with "0", so the logical or "array index" will always be less than the actual size by "one".
Comment: I don't think this is what OP is asking about. OP wants to know whether the `.length` property  refers to the total length or the number of initialized elements, not the last element index as in this interpretation.
Answer: Just to add,
In Java all the arrays are indexed and declared by int only. That is the size of an array must be specified by an int value and not long or short. All the arrays index beginning from 0 to ends at 2147483646. You can store elements up to 2147483647. If you try to store long (big) elements in the array, you will get performance problems. If you overcome performance problems you should go to the java collections framework.
Comment: What does this have to do with the question?


Compilar app para ios feitos no react em ambiente windows

Question: Estou estudando react native e preciso compilar um app para android e ios.
Gostaria de saber se posso desenvolver tudo no ambiente windows e depois só copiar os arquivos pra uma maquina virtual rodando OS X para compilar e publicar o app
Comment: Yep, aqui tem um tutorial mais explicado de como fazer [Xcode On Windows](https://blog.udemy.com/xcode-on-windows/)
Comment: @CaiqueCampos apesar de ser eficiente pra produção, é ilegal, e caso gerado com hackintosh e enviado para a loja, logo é detectado e a conta é banida
Answer: Pode fazer isso sem problemas, mas sugiro que voce teste tudo em um iphone ou no simulador do mac antes, pois sempre tem uns detalhezinhos que não funcionanam ou funcionam um pouquinho diferente no ios.
Nao sei se voce usa iphone ou android mas uma coisa que vejo muito e uma pessoa desenvolver e testar somente no android e acabar esquecendo de alguns detalhes de usabilidade/interface um pouco mais caracteristicos do ios.
Por exemplo ja vi gente fazendo funcionalidades que acabavam ficando dependentes do botao voltar do android, por exemplo para fechar uma modal, o que deixa um usuario do ios "preso" na modal.


How to add predefined text to contact form?

Question: I would like to add a couple paragraphs of predefined text (not an input field) to my contact page.  What are my options to do this in Drupal 8?  Until this point I've been using JS to get the job done.
Answer: You can create a module, hook on hook_form_alter and add a #prefix to the first input field.
More simple: Create a block with your paragraphs and switch it on for region "(main) content" on the contact page (no programming needed).
Comment: That worked nicely.  IMO, there should be more clear way to customize contact forms, but this is a fine answer to my question.  Thanks for the help.
Comment: Has anyone used a direct `$form['#prefix']` in a D8 form? Cause for me it is rendering twice. Once before the form starts and one right after the form starts. Weird...
Comment: $form['#prefix'] = 'bla' works perfectly for me.


How to run async tasks in several threads in Rust

Question: I want to run some async tasks in several threads. I tried to use tokio's Runtime and new_multi_thread, but I've got a panic
thread 'main' panicked at 'Cannot drop a runtime in a context where blocking is not allowed. This happens when a runtime is dropped from within an asynchronous context.'

Here's the code.
async fn routine(millis: u64) {
    tokio::time::sleep(std::time::Duration::from_millis(millis)).await;
}

#[tokio::main]
async fn main() {
    let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();

    let handles: Vec<tokio::task::JoinHandle<_>> = (1..10_u64).map(|i| {
        rt.spawn(routine(i))
    }).collect();

    for handle in handles {
        handle.await.unwrap();
    }
}

Could you please tell me what is wrong with the code?
Answer: You don't need to initialize a runtime as that's what the annotation #[tokio::main] does (it's a macro).
This...
#[tokio::main]
async fn main() {
    println!("hello");
}

...de-sugars to:
fn main() {
    tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            println!("hello");
        })
}

Note that #[tokio::main] is equivalent to #[tokio::main(flavor = "multi_thread")] (defaults to multi-threaded runtime), as opposed to the single-threaded runtime #[tokio::main(flavor = "current_thread")]. In your case  you can use this form #[tokio::main(worker_threads = 2)].
Comment: To have the multi-thread scheduler be used by default, the `rt-multi-thread` feature flag must be set
(https://docs.rs/tokio/latest/tokio/runtime/index.html#multi-thread-scheduler)
Answer: #[tokio::main] creates a Runtime and runs async fn main() on it. Your main then creates another Runtime. Normally, when we create our own runtime, we wouldn't use the #[tokio::main] macro, we'd just write a normal main.
We can use block_on to wait for the tasks to complete, then we can drop the Runtime. With a normal main, we're not dropping the Runtime in an asynchronous context, so the program no longer panics.
async fn routine(millis: u64) {
    println!("in routine({millis})");
    tokio::time::sleep(std::time::Duration::from_millis(millis)).await;
}

fn main() {
    let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().unwrap();

    let handles: Vec<tokio::task::JoinHandle<_>> = (1..10_u64).map(|i| {
        rt.spawn(routine(i))
    }).collect();

    rt.block_on(async {
        for handle in handles {
            handle.await.unwrap();
        }
    });
}

Comment: Is building `tokio::runtime::Builder` same as `#[tokio::main(flavor="multi_thread", max_workers=100)] ` the same thing?
Comment: @collinsmarra You can use [`cargo expand`](https://github.com/dtolnay/cargo-expand) to see what macros like `#[tokio::main]` expand to. The [Rust Playground](https://play.rust-lang.org/) also has this feature under **Tools** > **Expand macros**, however the playground doesn't have all crates available (but it *does* have `tokio`).


IE 6 PNG problem

Question: Having trouble getting the top left background suitable in IE 6, this is the JS im using, it works for everything else on the page but not this :(
http://www.naomisalsi.com
DD_belatedPNG.fix('#navigation, .logo, #contenttop, #content, #contentbottom, #flowerbottom, body');

Answer: IE6 breaks for transparent PNG. Maybe try this one ...
Comment: I think looking at the function's name, and the working bottom right image, a fix is already being used.
Answer: Can you try giving the body an id

and use that ID in the list:
DD_belatedPNG.fix('#navigation, .logo, #contenttop, #content, #contentbottom, #flowerbottom, #page_body');

IE 6 PNG problem


Issue on mouse hover in button

Question: I'm using Twitter Bootstrap and I'm having some weird using when hovering over a btn-primary button.
This is my code :

        Home

...

...

                   Log In

And this is what happens :
before

on hover

Any ideas why this could be happening?
Comment: @mgraph Do you mean to totally eliminate the `btn` class??? - I'm not sure if really get your point (what I'm using is a vanilla Twitter Bootstrap... with one-or-two tweaks... that's all)
Comment: Possible duplicate of [Twitter bootstrap, buttons hover style?](http://stackoverflow.com/questions/12501224/twitter-bootstrap-buttons-hover-style)
Answer: 2 solutions,

Easy : Remove the a href from the li. Pro: fast, no maintenance. Con : can't do this if you need a dropdown, can break design.
Preferrable : add missing css classes to support btn within li.

.navbar .nav > li > a.btn {
display: inline-block; padding: 4px 10px 4px; margin: 5px 5px 6px; line-height: 18px;
}

.navbar .nav > li > a.btn-primary,
.navbar .nav > li > a.btn-primary:hover {
   text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);
  color: #ffffff;
}

.navbar .nav > li > a.btn-primary:active {
   color: rgba(255, 255, 255, 0.75);
}

 .navbar .nav > li > a..btn-primary {
  background-color: #0074cc;
  background-image: -moz-linear-gradient(top, #0088cc, #0055cc);
  background-image: -ms-linear-gradient(top, #0088cc, #0055cc);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0055cc));
  background-image: -webkit-linear-gradient(top, #0088cc, #0055cc);
  background-image: -o-linear-gradient(top, #0088cc, #0055cc);
  background-image: linear-gradient(top, #0088cc, #0055cc);
  background-repeat: repeat-x;
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc',endColorstr='#0055cc', GradientType=0);
  border-color: #0055cc #0055cc #003580;
  border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
  filter: progid:dximagetransform.microsoft.gradient(enabled=false);
}
.navbar .nav > li > a.btn-primary:hover,
.navbar .nav > li > a.btn-primary:active,
.navbar .nav > li > a.btn-primary.disabled,
.navbar .nav > li > a.btn-primary[disabled] {
  background-color: #0055cc;
}
.navbar .nav > li > a.btn-primary:active,
.navbar .nav > li > a.btn-primary.active {
  background-color: #004099 \9;
}

Issue on mouse hover in button


sql query that select data that have only one value

Question: I am trying with this query to get only the rtp.releaseid that have a unique territory=200
select rtp.ReleaseId, rtp.TerritoryId  from ReleaseTerritoryPrice rtp where
rtp.TerritoryId=200

but I guess something is missing , can you please help.
Thanks.
Comment: why do you think something is missing! This is absolutely ok.
Comment: Try: rtp.TerritoryId= '200'
Comment: Do you mean you want those `ReleaseId` that have a `TerritoryId = 200` and no other `TerritoryId <> 200`?
Comment: yes exactly I want ReleaseId that have a TerritoryId = 200 and no other TerritoryId <>
Answer: You can use the following with NOT EXISTS in a WHERE clause:
select rtp1.releaseId, rtp1.territoryId
from ReleaseTerritoryPrice rtp1
where rtp1.territoryId = 200
  and not exists (select releaseId
                  from ReleaseTerritoryPrice t2
                  where t2.territoryId <> 200
                    and rtp1.releaseId = t2.releaseId);

See SQL Fiddle with Demo
Or you can use NOT IN in a WHERE clause:
select rtp1.releaseId, rtp1.territoryId
from ReleaseTerritoryPrice rtp1
where rtp1.territoryId = 200
  and rtp1.releaseId not in (select releaseId
                              from ReleaseTerritoryPrice t2
                              where t2.territoryId <> 200);

See SQL Fiddle with Demo
Comment: I am trying to use the same logic in your query in order to have data that exist in territory 62 but not in territory 200 i did this but it doesn't work :      select distinct r.UPC,rtp1.releaseId, rtp1.territoryId
from ReleaseTerritoryPrice rtp1
inner join Release r on r.Id=rtp1.ReleaseId
where rtp1.territoryId = 62
  and not exists (select releaseId
                  from ReleaseTerritoryPrice t2
                  where t2.territoryId =200
                    and rtp1.releaseId = t2.releaseId);
Comment: @saadamiens try using the second one if I got the logic correct the following should work, see this demo -- http://sqlfiddle.com/#!3/d42e2/4  or even this demo -- http://sqlfiddle.com/#!3/d42e2/6
Answer: A couple of ways
SELECT ReleaseId
FROM   ReleaseTerritoryPrice
WHERE  TerritoryId = 200
EXCEPT
SELECT ReleaseId
FROM   ReleaseTerritoryPrice
WHERE  TerritoryId IS NULL OR TerritoryId <> 200

Or
SELECT ReleaseId
FROM   ReleaseTerritoryPrice
GROUP BY ReleaseId
HAVING COUNT(DISTINCT TerritoryId) =1 AND MAX(TerritoryId )=200

Comment: I would like to use your first method with an inner join like this
Comment: inner join release r on r.id = release id , where can i put this line before or after the except ?
Answer: Maybe you mean this
SELECT MAIN.* FROM ReleaseTerritoryPrice MAIN
WHERE MAIN.ReleaseId in (
    SELECT rtp.ReleaseId
    FROM   ReleaseTerritoryPrice rtp
    WHERE rtp.TerritoryId =200
    GROUP BY rtp.ReleaseId
    HAVING COUNT(rtp.TerritoryId) =1 )

Answer: Use the DISTINCT keyword.
select DISTINCT rtp.ReleaseId,
     rtp.TerritoryId
from ReleaseTerritoryPrice rtp
where rtp.TerritoryId=200


How can I increase my vocal endurance and sing longer without getting hoarse and losing my voice?

Question: I sing either solo or as lead singer in my band, on shows lasting from 3 to 4 hours.  I do take a break occasionally and sip water between every other song.  I also avoid alcohol before and during my performance.
But by the third set, my voice begins to lose its quality and I have an increasingly difficult time cleanly hitting the higher notes.  The problem is worse if I sing many songs at the upper end of my range or sing with too much passion and power.  And the next day, I am hoarse all day long.
What happens to your voice as you continue singing - that results in the loss of ability to sing the upper end of your range and makes you hoarse?  Is it the vocal chords or something happening in your throat?
I don't know if your vocal chords themselves can become inflamed or tight or if it's more an issue with your throat (and other parts of your anatomy that are involved in singing) becoming inflamed or tensing up.
Specifically, I am looking for advice on what I can do to relieve, reduce or minimize these symptoms.  Drinking water helps a little if my throat is dry, but that is not the main issue.  It's the tightness in the throat and hoarseness that I want to minimize.
I know there are sprays you can buy that are supposed to help, but do any of these really work?  Will honey do any good?  Should I take an anti-inflammatory analgesic such as ibuprofen?  Are there natural remedies like grape juice that might help?
Also, what can be done to speed recovery between gigs besides getting plenty of sleep and keeping well hydrated?  I have to sing again tomorrow after singing last night - and my voice is still hoarse from last night.
I know some of you will want to tell me to not sing so much, but I have committed to these performances and don't want to have to cancel a scheduled show just because I was overzealous and agreed to too many. And yes I do know folks who have totally ruined their voice by over doing it.
Any advice from experienced singers on effective strategies to enhance my vocal endurance and minimize the tightening of the voice and getting hoarse, as well as next day recovery -  would be much appreciated.
Comment: I suggest you think less of remedies, more of singing in a way that doesn't strain your voice.
Comment: I suspect there is a long list of valid ideas. Some I can think of: * adjust the balance of what comes in your monitor so that you hear your own voice stronger. (less perceived need to strain.) 2: * Adjust the keys for some of the songs that you find more difficult (Of course that can be a difficult option for some styles and pieces for other band members.)
Comment: This isn't directly addressing your question so I'll leave it as a comment, but can you delegate more singing duties to other members of the band?
Comment: @Mr.Boy actually that is a great idea and I am trying to do that more!  Thanks for the comment.
Comment: My father doesn't sing (except for fun), but he speaks professionally. At peak, he did two or more seven or eight hour days, and developed voice problems. He went to a vocal doctor (who usually works with opera singers), and the one thing the doctor advised that hasn't already been mentioned is to avoid eating before bedtime, or anything else that can cause acid reflux.
Answer: Here are a few thoughts:

If you don't already, you definitely need to develop a vocal warm-up / cool-down routine.  You wouldn't run for four hours without stretching, would you? Why then would you sing?  I don't have time / space here to suggest specific exercises, but I'll say you should definitely start researching. A good exercise works from the back of the throat to the front. (Hint: search for Opera singer's blogs / advice about warm ups).  Doing excercises will improve your stamina, reduce the amount of damage, and will diminish recovery time between performances.
You need to drink water all the time.  Sipping / drinking helps a little during a performance, but you need to be drinking water all the time to be properly hydrated.  Without water, your vocal folds are basically just two pieces of dried play-doh rubbing eachother.
You need to sing less.  You don't have to cancel any gigs, but just don't make your sets so long!  2-2.5hrs is a considerable length for a concert; 4hrs is a marathon.  Being hoarse is your body's way of telling you you're hurting your voice - whether or not you want to accept the fact.
Just like when you work your muscles, they get tired and inflamed.  So too do your vocal folds when they are worked extensively.  The hoarse sound you hear is the result of inflamed vocal folds inefficiently resonating with air.  This creates a distortion in the sound, which we perceive as "hoarse".
You see this all the time with inexperienced brass players.  They sit down, immediately start wailing out high notes to impress everyone, but an hour later, their chops are shot and they're faking it.  A smart brass player sits down, plays quiet, long, low sounds and gradually works up through the range; high notes then take care of themselves.  The same applies to the voice as well.
Answer: Besides sleep and hydration, which are key, you should warm up and cool down. Also, like any endurance activity, you have to train up to it at a measured pace and there will always be a limit to how long you can go. If you are hoarse all the next day you are probably hurting your voice, and that damage can be permanent or semi-permanent. If you get nodules on your vocal cords they can take years to go away on their own, if ever, and the only other option is surgery to remove them.
Your voice will change as you age even if you rarely use it and baby it. 3 - 4 hours is a long time to be singing in a loud band. Put your highest notes earlier in the show, but not right at the beginning, since your first couple songs will be part of your warm up no matter how much warm up you do before the first song.
This kind of thing has caused cancellation of dates for major tours by famous artists. There's no magic bullet and in the end most humans just might not be able to sing for four hours straight two out of three nights. With that kind of schedule you should find a professional voice teacher to help make sure you do not have bad habits that will injure your voice.
Your vocal cords get tired and sore and worn out just like any of your other muscles, they just don't have the same nerves so it's not as easy to feel it, but as you well know you can definitely hear it. You're basically running a marathon with your vocal cords and most people require months to years of training to run a marathon with their legs without hurting themselves, and then they have breaks in between marathons.
Answer: 3 to 4 hours is too long to sustain on a regular basis. I work around 180 shows each year and duration of show is 90 min.  Vocal tiredness is inevitable as the varied environment of each gig offers its own individual problems for the voice.
Over straining the voice is difficult to avoid when working outdoors to a large crowd for example unless you have excellent stage monitors or a good earpiece. Learning to open your mouth in the correct manner to allow the different vowels to flow with ease will help with the stamina of the voice. But this will take practice and good training.
The other muscles in the throat will try to compensate for bad technique which is why you may feel tightness in this area the next day. Overall in my experience (and I am not an expert.) when you are young you will recover from bad technique  more quickly but as you age or have been gigging a lot for years you must step back and reconsider the best way to maintain the stamina in your voice, it will be more difficult to do this after years of incorrect use but you will thank yourself for it in the long term. Good hydration, good warm up, begin your show with a few songs which are easy for you and try to recognise any song which you over compensate with to reach the notes and try sitting down with it and learn a better more relaxed technique to do a good job of it. If this isn't possible for you then the song may just be out of your vocal range and it might be a good idea to drop the key or the song.
Comment: Excellent advice Dave.  Thanks for weighing in on an old question with new information.  I completely agree with everything you said.  Also I am learning that it is important to have bandmates who can also sing lead on some songs so we can share the load.
Answer: Rockin Cowboy- I could've written your initial question. In fact I have over about 40 years of doing the lead singer thing (mid 50s now, still doing it). I've asked so many teachers this same question.... Pay attention to the answers above that tell you that 'as you get older, it will get harder to recover'. This has been my experience as well. I'm in a number of different bands, lead singer of most of them. For me, things have gotten tougher than when I was a kid. Your cords loose elasticity and get thicker, so it will take a LOT of work to keep them in shape.
Water's key. So is technique. Learn to round or narrow your vowels. Learn to use your head voice more. Learn to breathe right (I still struggle on this). Get out of your throat.
Use in ear monitors (IEMs). I've used in IEMs since the late 90s and I'll NEVER go back to wedges. The IEMs have definitely prolonged my life as a singer.
The best piece of advice is to get a teacher that does this. Teachers that don't sing as part of their living... I dunno how much faith I have in them. I've had many teachers over the years and the best ones (for me) were the ones that actually sang for part of their living. BEWARE of self-professed "maestros" that are on youtube. Anybody can post a youtube video.
Work on trying to make what you do easier. If it hurts, if it's straining, if it's tight - then it's wrong. Work on your volume so that you get out of the 'shouty' registration. You shouldn't have to YELL to hit the notes. I still stuggle with this.
Downtime is crucial too. After your shows, when you have another coming up, get good sleep but also keep quiet as long as you can before you have to warm up for the next show. ALWAYS warm up. Doesn't have to be a long time. Just make sure that you have a voice. As you go through your show, your voice will usually warm up to the point where your show will be okay. However, after your show, that swelling will kind of compound, so now you'll have 2 nights of wear and tear.
Learn to say NO to too many gigs too.
Comment: This all seems like great advice. I'd love to hear more about how in-ear monitors "have definitely prolonged my life as a singer." Maybe you could add a bit about this to your answer? Great first answer, and welcome to SE Music!
Comment: Thanks for sharing your experience and ideas Barry.  That was all great advice.  Plus one.  I think one of my biggest problems is singing too loud.  People who hear me sing for the first time often say "you have a powerful voice" but I believe it's just the opposite - only I'm singing as loud as my soft voice can sing.  It never occured to me that in ear monitors might help save my voice.  But thinking about it my guess would be that with ears I might not  feel like I need to sing so loud.  I can let the mic and PA gear do their job to allow my vocals to be heard by the audience.
Answer: I do similar length gigs sometimes. I sing in a rock band and we like to party 'til late so sometimes this involves a 4 or 5 hour gig. Not all that often but sometimes.
I have found this works..
Enhance Vocal Endurance:

I'm no vocal trainer but I have learnt some thigns from this site. Eg I used to try to sing high notes with chest voice, pushing harder with the lungs to get higher. This works but it's MUCH easier endurance-wise if I use head voice and even falsetto sometimes (for me this isn't a great sound), and hold back on the pushing/belting. Maybe see a a vocal instructor to see how you can go about this. Basically, use the resources your voice has to good effect.
Start with songs which take little vocal effort. This works as a warm-up and you don't end up firing all your guns at the start. For me this means singing songs of a lower register, leaving the belters until I've warmed up.
DRINK WATER !!! Others have said it here - you can sweat a LOT when singing and dehydration is an energy killer. It makes your muscles cramp (including your vocal muscles) and tires you out generally. It might account for that tightness in your throat. So keep drinking. A sip isn't enough !
Take a break - even a song's worth of time can help. Maybe introduce some instrumentals or have someone else sing a few tunes, especially after something you find tricky.

Minimise tightening of voice:

Salt. If you're an energetic singer you might be sweating out salt a lot. I've found alka-seltzer (actually a hangover cure) helps or if not then eating something salty like crisps / potato chips. Be careful about crisps though because they can stick in your throat a bit so swill it down with some more water.
Coca cola. Sorry to name a brand but this one is best for me. It seems to help with rehydration and general energy levels. Probably the sugar. I remeber a specific occasion where I was flagging and asked one of the party people to fetch me a pint of coke. She did, bless her, and after a few slurps I felt immediately better. It;s not good for you long term but as a straight hit it works fine for me.
Vitamin C. Here (UK) you can get 1000mg vitamin C tablets which fizz into a pint of water nicely. Take one of those about an hour before the gig and generally the gig feels more effortless.

These are things that work for me - we're not all the same so maybe some will/won't work for you but perhaps they're worth a try.
Regards recovery:
Rest your voice. Obvious really. It's a muscle like anything else so don't go straining it too much if possible, and let it rest during the day aferwards. Avoid singing or even speaking if you can.
Finally if you really are having trouble, take a look at your schedule. If you're doing 4 hour gigs on a regular basis, maybe you're just overdoing it, as others have said. I know you don't want to hear that, but regular 4 hour gigs are already quite impressive, so allow yourself to be human.


Implementação de uma search box

Question: Boa noite,
Relativamente à pouco tempo aprendi HTML5 e CSS3 e de momento estou a aprender JavaScript. Estou a criar uma página web mas estou com dificuldades na parte da criação da search box. Eu já a tenho criada (usei a tag input com name="search") mas não sei como fazê-la procurar pelo conteúdo da página. Se pudessem ajudar agradecia muito.
Obrigado
Comment: Você logo vai descobrir que isso é mais difícil do que parece... O seu `name="search"` não significa nada em especial para o navegador ou para o servidor que receberá a requisição, e nada que diga para eles realizarem alguma espécie de busca.
Comment: Aproveite e dê uma lida em [https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/Input#Atributos](https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/Input#Atributos), já que estamos falando em atributos de ``
Comment: Podes dar um exemplo do que queres que aconteça quando inseres texto que encontra algo? queres marcar o texto?, queres perguntar no servidor por texto? queres mostrar ao utilizador palavras encontradas junto ao input?
Answer: Acredito que todos os internautas saibam como fazer uma busca na página pois quase todos os navegadores de internet possuem uma ferramenta de busca que permite pesquisar palavras ou frases correspondentes nas páginas acessadas. Basta teclar Ctrl+f (windows) ou Command+F (Mac) que uma caixa de pesquisa surgirá.
Mas também é possível com poucas linhas de códigos implementar essa caixa de busca na página.
CSS
 .found {background-color:#f99;}
 #searchbox {width:350px; position:absolute;
 _top:expression(document.body.scrollTop+document.body.clientHeight-this.clientHeight-10);
 left:0; top:0;}
 body > #searchbox {position:Fixed;}
 #searchbox fieldset {border:0;text-align:center;margin:3px;}
 #searchbox input {margin:1px;padding:2px;}
 #search {width:140px;}

JavaScript
inPageSearch = function() {document.getElementsByClassName = function(cl) {var retnode, myclass, elem,classes; retnode = []; myclass = new RegExp('\\b'+cl+'\\b'); elem = this.getElementsByTagName('*'); for (var i = 0, ii = elem.length ; i < ii ; i++) {classes = elem[i].className; if (myclass.test(classes)) retnode.push(elem[i]);} return retnode;}; elemTop = function(elem) {return elem.top || elem.pixelTop || elem.offsetTop || 0;}; search = function(str) {nodewalk = function(node, str) {var re, m, s, r, frag, sp; for (var i = 0; i < node.length; i++) {if (node[i].hasChildNodes() && 'SCRIPT' !== node[i].nodeName) nodewalk(node[i].childNodes,str); re = new RegExp(str,'ig'); if (3 === node[i].nodeType) {m = node[i].nodeValue.match(re); s = node[i].nodeValue.split(re); frag = document.createDocumentFragment(); if (m !== null) {frag.appendChild(document.createTextNode(s[0])); for (var j = 0, jj = m.length; j < jj; j++) {sp = document.createElement('span'); sp.appendChild(document.createTextNode(m[j])); sp.className = 'found'; frag.appendChild(sp);frag.appendChild(document.createTextNode(s[j+1]));} node[i].parentNode.replaceChild(frag,node[i]);i+=jj*2;}}}}; nodewalk(document.getElementsByTagName('body')[0].childNodes, str);}; clearfound = function(node) {var txt = node.previousSibling.nodeValue + node.firstChild.nodeValue + node.nextSibling.nodeValue; node.parentNode.removeChild(node.nextSibling); node.parentNode.removeChild(node.previousSibling); node.parentNode.replaceChild(document.createTextNode(txt), node);}; var d, F, fld, inp, b1, b2, b3; d =document.createElement("div"); d.id = 'searchbox';  F = document.createElement("form"); fld = document.createElement("fieldset"); inp = document.createElement("input"); inp.type = 'text'; inp.id = 'search'; fld.appendChild(inp); b1 = document.createElement("input"); b1.type = 'button'; b1.id = 'search1'; b1.value = 'Search'; b1.title = 'Buscar todos'; fld.appendChild(b1); F.appendChild(fld); d.appendChild(F); document.getElementsByTagName('body')[0].appendChild(d); document.getElementById('search1').onclick = function() {var nodes = document.getElementsByClassName('found'); for (var i = nodes.length - 1; i >= 0; i--) clearfound(nodes[i]); search(document.getElementById('search').value); window.scrollTo(0, elemTop(document.getElementsByClassName('found')[0])); return false;}; document.getElementById('search2').onclick = function() {var nodes = document.getElementsByClassName('found'); clearfound(nodes[0]); window.scrollTo(0, elemTop(document.getElementsByClassName('found')[0])); return false;};
document.getElementById('searchx').onclick = function() {var nodes = document.getElementsByClassName('found'); for (var i = nodes.length - 1; i >= 0; i--) clearfound(nodes[i]); document.getElementById('searchbox').style.display = 'none'; setTimeout(function() {document.getElementsByTagName('body')[0].removeChild(document.getElementById('searchbox'));},5);};};

inPageSearch();

Se você quiser que a caixa de pesquisa apareça quando a página for carregada use

Se preferir abrir a caixa de pesquisa através de link use

Search

Atalhos de teclado do Chrome
Mozilla support - Como buscar por textos e links no conteúdo de uma página
[Microsoft Edge] - Teclas de atalho

Implementação de uma search box


Add outer border to the wpf grid

Question: I ve got simple grid in my wpf app, I would like it to hace outer border border.
How can I achieve this ?
thanks for any hints
Comment: Please show some effort, at least in googling the question.
Answer: Simply put your Grid in a Border element:
<Border BorderBrush="SlateBlue" BorderThickness="5,10,15,20"
        Background="AliceBlue" Padding="5" CornerRadius="15">
  <Grid>

  </Grid>
</Border>

The Grid control cannot draw a border of its own.
Comment: @gruber How about just giving it a try?
Comment: would it work if window is full screen and grid set to 640 480 ?
Answer: Why not put a Border around the Grid:
<Border BorderBrush="Black" BorderThickness="5">
  <Grid>

  </Grid>
</Border>

Add outer border to the wpf grid


Prevent last updated property from changing when updating node in code?

Question: I have this code that updates a node in a queue worker:
      $changed = $entity->getChangedTime();
      // Don't update the changed time by
      $entity->setChangedTime($changed);
      $entity->set('my_field', "my_data");
      $entity->setNewRevision(FALSE);
      $entity->save();

Here is a screenshot of xdebug showing changed and after_save value with the relevant code:

But no matter what I do, the changed property keeps getting updated to the time of the update.
I tested the functionality in a different contenxt like:
  $node = Node::load($nid);
  $changed_time = new DrupalDateTime('2022-01-01 12:00:00');
  $timestamp = $changed_time->getTimestamp();
  $node->setChangedTime($timestamp);
  $node->save();

and this seem to work.
Why does my code in the queue worker fail to do the same thing? is it because it's updating a field value?
Comment: Did you verify you are actually getting value in `$changed = $entity->getChangedTime();` ?
Comment: @miststudent2011 yeah. I added a screenshot and of the values and relevant code. Maybe something else is acting on it when fields are being updated.
Comment: The changed time will always updted when saving a node. If you need a different timestamp, you will need to create another timestamp on the entity to track whatever it is you're trying to track.
Comment: @Jaypan do you know where is that happening? it feels like `$node->setChangedTime($timestamp);` should do it. but you may be right, if it's changed then it's always updating it.
Comment: I figured this out. The issue is that when I try to keep changed time to the original changed, Drupal overrides it. If I add a second, it works.
Answer: There's a module that could help with your request. It's a bit hackish but it works.