Out-of-practice pianist wants suggestions for getting back into it

Question: So long story short I was an active concert pianist who had to give it up due to repetitive strain injuries in the wrists/forearms. I took up a PhD in a fall-back field and I feel like my injuries are manageable as they now have minimal impact on my day-to-day life.
I'm looking for repertoire suggestions to ease back into regular playing. It's so easy to fall back onto extraordinarily "academic" repertoire or convince myself that playing through Chopin Op 10 isn't a bad idea, but I want to do this right and enjoy myself doing it while not overburdening my wrists and elbows.
So - does anyone have suggestions for enjoyable (but also non-trivial) repertoire?
Comment: I left some suggestions in [the chat room](https://chat.stackexchange.com/transcript/message/58894761#58894761).
Comment: @ToddWilcox that is in fact a good idea but living on a grad student stipend completely prohibits me from hiring a teacher
Comment: @JarradPerron you might consider barter.  I've had a couple of students over the years who swapped professional services for lessons.  It might be harder to find someone willing to accept whatever it is you have to offer instead of money, but it's probably worth trying.
Comment: Your practice regime should be influenced by what exactly your ambitions are in regards to your playing
Comment: Hire a teacher who is able and willing to work with you on your particular situation
Comment: I'm assuming the OP is American, but you can get quality music education for around 30 - 50 $ per hour lesson. This could be equal to eating take-out meals one time a week less
Comment: @JarradPerron I'm going to second the recommendation of professional help, but not so much for repertoire as for posture and technique. Especially with a prior injury, you should make sure you're not going to re-injure yourself. Maybe a physical therapist who specializes in music.
Comment: @Aaron your advice was by far the most helpful thank you muchly
Answer: Firstly I must endorse Todd Wilcox' idea that you should find a teacher.  That would be the your best move here.
But if that is really out of the question then surely the sort of thing that you are looking for are pieces by some of the great masters that are stylisticly difficult but technically easier.
For example Mozarts sonatas, much early Beethoven, much of J.S. Bach.  Not as technically demanding as late romantic or many modern pieces but extremely satisfying to play and requiring considerable effort to play in the correct style.
I could make a list but as someone with experience who has already got to a high level of playing I expect that you can identify the sort of pieces fairly I mean easily by yourself.
Godd luck.
Answer: There is no such thing as repetitive strain, only improper movement which makes all movement repetitive strain.  I suggest you contact Edna Golandsky in NYC and relearn how to move properly.
I was paralyzed with bilateral tendonitis pain for two years and sought relief from multiple doctors to no avail.  It was the teaching of Dorothy Taubman (deceased) which has had me pain free for the past 20 years.  The problem with re-learning how to move is that the improper movements are permanently hardwired into our brains (muscle memory) forever.  They can be overwritten but are always laying in wait to resurface and wreak havoc. If you have been taught to brow-beat technique into your fingers, which have no muscle, through strength and endurance, then learn to move properly according to the laws of physics, and then the improper movement resurfaces, you can injure yourself all over again and rather quickly because the improper "strength and endurance" quickly atrophies.  That is why missing a few days of practice can make us feel rusty.  The body is purging what it knows it doesn't need.  Old technique can resurface when we are nervous or cold.  I just played a recital which I could execute flawlessly and at great speed but I was nervous and could feel the old movements trying to creep back in and was giving me the "twisties."  I could sense the downward spiral but I was about 75% successful at maintaining proper movement by focusing on gravity, rotation and in/out movement. I give myself a C- and hopefully the next time I can raise that to a C+.


How can I separate the output of SQL tables using SQL UNION?

Question: I have several tables in one database, with each table containing the exact same column names. I'm using SQL UNION in order to pull every record from all of those tables, and output the records onto a web page. Each record is output between a div with an ID of 'contributors.'
What I am ultimately tying to do is set some sort of separation between each table that is being output, so that I don't have every record within a table seamlessly running into the next table.
I tried to echo a div before the 'contributors' div, but that did not work. Does anyone have any idea how I can output data from issue1, then create a heading to  below to separate issue1 from issue2?
<?php

$res=mysql_query('
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue1 UNION ALL
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue2 UNION ALL
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue3
');
if (!$res) { // add this check.
    die('Invalid query: ' . mysql_error());
}
while($row=mysql_fetch_array($res))
{
$cont_img_path = $img_path.end(explode('/', $row['Picture']));
if(file_exists($cont_img_path))
{
?>

<?php echo $row['First']; ?> <?php echo $row['Last']; ?>

<?php echo $row['Title']; ?>

<?php echo $row['Genre']; ?>

<a href="<?php echo $row['Picture']; ?>" id="3e-fancybox" name="<?php echo $row['First'] .' '. $row['Last']; ?>" StoryLink="<?php echo $row['StoryLink']; ?>" Ptitle="<?php echo $row['Title']; ?>" genre="<?php echo $row['Genre']; ?>" about="<?php echo str_replace('"', '"', ($row['About'])); ?>" WebLink="<?php echo $row['Link']; ?>"><img src="<?php echo $row['Picture']; ?>" alt="<?php echo $row['ALT']; ?>">

<?php } } ?>

Comment: So you are doing UNION with three different tables that have the same column names?
Comment: Yes, and everything is getting pulled onto the page, I just can't separate the tables.
Comment: Instead of doing UNION, could you JOIN the tables with themselves? Is there a way of joining them?
Comment: I tried that, but I kept getting duplicates, everything was very messy.
Comment: If you are getting duplicates, use distinct. If you explain the relationship between the tables, we can help you build the query. Maybe you are using the wrong join (inner, left or right join)
Comment: The tables are made up of simple information such as first name, last name, issue title, a url to a picture. Each table is storing names of contributors to issue1, the same thing for issue2 table. Every table uses the exact same column names. I am trying to group this data by issue/table
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/107911/discussion-between-marlon-and-erick).
Answer: Notwithstanding that if you want three separate results sets, it makes more sense to use AJAX and make three separate requests, here is a solution:
$res = mysql_query('
SELECT
      'Issue1' as context,
      First,
      Last,
      Title,
      StoryLink,
      Genre,
      About,
      Link,
      Picture,
      ALT
FROM
    issue1
UNION ALL
SELECT
      'Issue2' as context,
      First,
      Last,
      Title,
      StoryLink,
      Genre,
      About,
      Link,
      Picture,
      ALT
FROM
    issue2
UNION ALL
SELECT
      'Issue3' as context,
      First,
      Last,
      Title,
      StoryLink,
      Genre,
      About,
      Link,
      Picture,
      ALT
FROM
      issue3
)';

This solves the question, as asked, however I'm not convinced your database structure is correct to begin with.
Comment: @Marlon I use select `'something' as some_other_thing` in mysql all the time in production, so yes.
Comment: I haven't had a chance to try this out yet, but looking at the part 'as context,' will that work with MySQL?
Answer: I think the idea of a Union is to have it return one set of seamless results.
Aside from running three separate queries to get the results, you might could count the number of rows each query returns and add a
 tag or something in your while loop when a counter reaches the number of rows.
Answer: Add another column to your query eg:
SELECT Title, 'issue1' FROM issue1 UNION ALL
SELECT Title, 'issue2' FROM issue2

Then your code could be somthing like
print header for 'issue1'
for each 'issue1' in results
    display row
print header for 'issue2'
for each 'issue2' in results
    display row


Designing javascript function accepting string or function

Question: In Javascript in particular, it is common for APIs to expose functions that accept either strings or functions for a specific argument. Strings provide "already initialized" values, while functions produce values at run-time.
// Call foo with known value
api.foo('bar')
// or defer value determination to run-time
api.foo(function() { return 'bar'; }

This is more flexible are sometimes the arguments to pass to these API calls are not known until runtime, e.g.
api.foo(function() { return prompt('foo or bar ?'); });

This method would be somewhat reserved to public-facing functions (because they introduce more complex signatures and may have gotchas - best to keep their number low), but still, what is a good idiom for writing such functions ?
Something along the lines of
api = {
  // "public" function
  func: function(a) {
    if (typeof(a) == 'function')
      return this._func(a());
    else
      return this._func(a);
  },
  // Actual implementation
  _func: function(a) {
    [...]
  }
}

should work but there are certainly more efficient/elegant alternatives. Any ideas ?
UPDATE: Following comments by @camus (and an answer that has now disappeared but was relevant), here is an update clarifying my intentions and explaining how this relates to APIs
Consider that when writing the function we do not know which way it is going to be called, and we don't want to place restrictive assumptions on it. The function is designed to be versatile, so it can be called multiple times using different signatures. We could force the caller to use strings, but it can be convenient to let a function that returns a string do the job. This function could be passed additional parameters (like an index, ...) and this is of course very specific to the context of the API, but the general idea is rather "how to I process strings and functions-that-return-a-string arguments in an elegant manner?".
Comment: You're in good company with that solution: jQuery's `on` event binding is implemented like this: https://github.com/jquery/jquery/blob/c61150427fc8ccc8e884df8f221a6c9bb5477929/src/event.js#L684 Basically a nested `if/else` to sort out the calling mess.
Comment: what is the point executing the function right away ? a function passed as an argument should be used as a continuation or it makes no sense. why not just do fun(my_func()) in the code directly then ... in the first exemple it ( "defer value determination to run-time") it makes little sense too , because you'll have to use  closures to change the result of the passed function. The result of the passed function is predictable in most cases.
Comment: You should not start your variables with an underscore (_), because an underscore is usually refering to a private variable, which `_func`  is not.
Answer: Here's a simple way to implement it:
api = {
  // "public" function
  func: function(a) {
    if (typeof a == 'function') {
      a = a();
    }
    // rest of function
  }
}

Comment: It's `typeof a` (no parentheses)
Comment: @David: I've been using `typeof()` for a long time without [realizing](http://stackoverflow.com/questions/2797517/typeof-is-an-operator-and-a-function). Thanks.
Answer: I'd go with :
api = {
  func: function(a) {
    if(typeof a == 'function') a = a.call(this); // Transmit api as scope for a, may be useful for accessing api tools ...

    // Process a ...
  }
};

Comment: Passing arguments to the function is indeed a very useful thing to do. Some APIs will transmit their specific context using `this` as you suggest, but also an index (for data collections), or anything that is relevant in their scope.
Comment: Accepting this answer because @yent needs more rep than @Barmar :) Actually, because of the `this` argument - which is a nice forethought the question did not call for.
Answer: api = {
  func: function( a ) {
    typeof a == 'function' && a.call( this, arguments );
  }
};


Expander with GridSplitter

Question: I've a grid splitter before to the expander(which exists in the right side of a wpf window) and when i was running the app i need to use grid splitter to see more data from expander after its expanded, but the problem is when i was drag splitter i'm getting full view of my expander irrespective of original width but after click on expander to collapse it won't go to its original position by maintaining the splitter dragged width. So any one help me how can i send back expander to its original position.
Thanks,
@nagaraju.
Answer: Once you have used the splitter the grid column widths will no longer be 'auto'.
One solution is to respond to the collapsed event of the expander and reset the width of the first column to auto using column.Width=GridLength.Auto;
Comment: its working when i set column.width=GridLength.Auto; plz edit your answer with this line i'll accept it.
Answer: As you are resizing the contents of the Expander it may make more sense to place the GridSplitter inside the Expander, and on the outside you just have a normal Grid which makes the cell where the Expander is size to content.

Expander with GridSplitter


How to use Bloomberg JSON API as JSONP

Question: To create a chart, I found that Bloomberg is providing data in JSON format. Please have a look at this URL: http://www.bloomberg.com/markets/chart/data/1Y/IBM:US This sends data of the chart in JSON format. I want to get this data in an Ajax request, so that I can parse it and create a chart. But I can't use Ajax, as this is a cross domain affair. I need to use JSONP. I am not sure how Bloomberg API supports JSOP. If you know how can we use JSONP with the above url, please let me know. If there is any alternative, please let me know.
Answer: You can't. JSONP requires that the server be on board with the transaction so that it can properly handle the callback injection. If the server isn't providing it, there's no way to force it unilaterally.
What you might be able to do, subject to your hosting provider's policies, is have your server-side script load the Bloomberg data, then pass it on from there, either printed in the initial page or as a JSON/JSONP call to your own server (which is probably a better idea, as it leaves you more flexibility to update the data on the fly and also allows the page's markup to be cached).
Note that some hosting providers do not allow outgoing requests because they don't want their servers to be used as proxies (which is, after all, basically what I'm suggesting you do). You may have an option to whitelist Bloomberg, or you may just need to keep outgoing traffic to a minimum (i.e. cache the Bloomberg data on your server so that you're not refreshing it every time someone loads your page). Check your hosting terms.
Comment: This is what I was planning to do. I asked if someone is award of JSONP support by Bloomberg. Thank you for explaining the answer so well, that others will be benefitted.

How to use Bloomberg JSON API as JSONP


File Not Found in Delphi (FMX)

Question: I am trying to load a bunch of lines from a text file located in same directory as the .dproj and Delphi can't find the file I'm trying to read from.
the code is as follows:
    procedure TFoPrincipale.Button2Click(Sender: TObject);
var monFich : TextFile;
    Sligne : string;
begin
try
AssignFile(monFich, 'docText.txt');
Reset(monFich);
except
      showmessage('Le fichier est introuvable');
      exit;
end;

  while not Eof (monFich) do
  begin
    Readln(monFich, Sligne);
    Memo1.Lines.Add(Sligne);
  end;

CloseFile(monFich);

end;

Comment: You are not providing a path to the file and I see a Win32 subfolder there. Your executable is most probably in that subfolder and I suspect its working directory will be that one. Try it out first with specifying a complete path in the filename
Comment: Never use relative paths.
Comment: Have a look at the concept of "Working/Current directory" and also how to dynamically get the path you require
Comment: @AndreasRejbrand Unless you are writing a conosle app
Comment: yes it's working when I move it over to Win32\Debug
I'll try specifying the complete path to it and give you feedback.
Thanks mate
Comment: Both methods are working.
Answer: If you are using default project options then your application executable isn't compiled into the project directory but instead into the Win32\Debug or Win32\Release subfolder of your project folder.
So you should take into account the relative path to your file. In your case, the desired file is in second parent folder of the folder in which your executable resides.
I recommend you first get the path location of your executable file using ExtractFilePath(Application.ExeName).
Then you can make use of TDirectory.GetParent() in order to move up the directory chain until you reach the desired directory.
Comment: Thank you, this is a very very insightful comment.

File Not Found in Delphi (FMX)


How to calculate the averaged equations for the weakly nonlinear oscillator $\ddot x+x+\varepsilon (x\dot x^2)=0$?

Question: This is Strogatz exercise $7.6.5:$
For the system $\ddot x+x+\varepsilon h(x,\dot x)=0$, where $h(x,\dot x)=x\dot x^2$ with $0 < ε << 1$, calculate the averaged equations and if possible, solve the averaged equations explicitly for $x(t,ε)$, given the initial conditions $x(0)=a$, $\dot x(0)=0$.
Answer: $0)$
$$r=\sqrt{x^2+y^2},$$
$$\phi=\arctan\biggr(\frac{y}{x}\biggr)-t\ (\theta=t+\phi\rightarrow\phi=\theta-t).$$
$1)$
$$h(x,\dot x)=x\dot x^2=r\cos(t+\phi)r^2\sin^2(t+\phi)=r^3\cos(t+\phi)\sin^2(t+\phi).$$
$2)$
$$\dot{\bar r}=\Bigr<\varepsilon h\sin(t+\phi)\Bigr>_t,$$
$$\dot{\bar \phi}=\Bigr<\frac{\varepsilon h}{r}\cos(t+\phi)\Bigr>_t.$$
\begin{align}
\rightarrow \dot r & = \Bigr<\varepsilon r^3\cos(t+\phi)\sin^2(t+\phi)\Bigr[\sin(t+\phi)\Bigr]\Bigr>_t \\
& = \varepsilon r^3\Bigr<\cos(t+\phi)\sin^3(t+\phi)\Bigr>_t \\
& = \varepsilon r^3\frac{1}{2\pi}\displaystyle \int_{t-\pi}^{t+\pi}\cos(t+\phi)\sin^3(t+\phi)dt=0 \\
& \rightarrow \dot r=0\rightarrow \frac{dr}{dt}=0\rightarrow dr=0\rightarrow r=r_0.
\end{align}
\begin{align}
\rightarrow \dot \phi & = \Bigr<\frac{\varepsilon}{r} r^3\cos(t+\phi)\sin^2(t+\phi)\Bigr[\cos(t+\phi)\Bigr]\Bigr>_t \\
& = \varepsilon r^2\Bigr<\cos^2(t+\phi)\sin^2(t+\phi)\Bigr>_t \\
& = \varepsilon r^2\frac{1}{2\pi}\displaystyle \int_{t-\pi}^{t+\pi}\cos^2(t+\phi)\sin^2(t+\phi)dt \\
& = \varepsilon r^2\frac{1}{2\pi}\frac{\pi}{4}=\frac{\varepsilon r^2}{8} \\
& \rightarrow \dot \phi= \frac{\varepsilon r^2}{8}\rightarrow \frac{d\phi}{dt}=\frac{\varepsilon r^2}{8} \\
& \rightarrow d\phi=\frac{\varepsilon r^2}{8}dt \rightarrow \phi=\frac{\varepsilon r^2}{8}t+\phi_0.
\end{align}
The amplitude of the closed orbit can be anything and the closed orbit is approximately circular.
$3)$
$$x(0)=a,$$
$$\dot x(0)=0.$$
$$\rightarrow r_0=\sqrt{x^2+y^2}=\sqrt{0+a^2}=a\rightarrow r=a.$$
$$\rightarrow \phi_0=\arctan\Bigr(\frac{0}{a}\Bigr)-0=0\rightarrow \phi=\frac{\varepsilon r^2}{8}t.$$
$4)$
$$x(t)=r(t)\cos(t+\phi)\rightarrow x(t)=a\cos\Bigr(t+\frac{\varepsilon r^2}{8}t\Bigr).$$
Answer: This equation, that is the perturbation term, has a curious structure that allows to find a first integral via
\begin{align}
\ddot x + x(1+ε\dot x^2)&=0\\[1em]
\implies
\frac{2\dot x\ddot x}{1+ε\dot x^2}+2x\dot x=0\\[1em]
\implies
\frac1ε\ln|1+ε\dot x^2|+x^2 = C
\end{align}
For $(x(0),\dot x(0))=(a,0)$ this gives $C=a^2$. Thus it is a consequence that the solutions are periodic, follow the level curves of the first integral, the average radius change over a period is zero in all orders of perturbation.

To compute the period, first isolate the derivative
$$
\dot x=\pm\sqrt{\frac{\exp(ε(a^2-x^2)-1}{ε}}=\pm\sqrt{a^2-x^2}\sqrt{1+\fracε2(a^2-x^2)+\frac{ε^2}6(a^2-x^2)^2+...}
$$
A quarter period then computes as
\begin{align}
\frac{T}4&=\int_0^a\frac{\sqrtε\,dx}{\sqrt{\exp(ε(a^2-x^2)-1}}\\
&=\int_0^{\frac\pi2}\frac{ds}{\sqrt{1+\fracε2a^2\cos^2s+\frac{ε^2}6a^4\cos^4s+...}}\\
&=\frac\pi2-\fracε4a^2\int_0^{\frac\pi2}\cos^2s\,ds+ \frac{ε^2}{96}a^4\int_0^{\frac\pi2}\cos^4s\,ds + \frac{ε^3}{384}a^6\int_0^{\frac\pi2}\cos^6s\,ds - \frac{ε^3}{10240}a^8\int_0^{\frac\pi2}\cos^8s\,ds \mp\dots\\
&=\frac\pi2\left(1-\fracε8a^2+ \frac{ε^2}{256}a^4 + \frac{5ε^3}{6144}a^6 - \frac{7ε^4}{262144}a^8\mp\dots\right)
\end{align}
The perturbed frequency is then
$$
\frac{2\pi}{T}=\frac{\pi/2}{T/4}=1 + \frac{ε}8a^2 + \frac{3ε^2}{256}a^4 + \frac{ε^3}{6144}a^6 - \frac{79ε^4}{786432}a^8+\dots
$$

Series expansion using the CAS Magma (online calculator), with $z=εa^2$,
<code>PS<z>:=PowerSeriesRing(Rationals());
q:=PS!(((Exp(z)-1)/z)^(-1/2));"integrand:",q;
iq := PS![ Coefficient(q,k)*Binomial(2*k,k)/4^k : k in [0..19] ]; "period factor:",iq;
"frequency factor:",1/iq;
</code>


Blank spaces opening RSS XML file - How to solve?

Question: All of the sudden, we are experiencing problems with our RSS feed which comes with the Drupal core 7.x . It is no longer valid due to two spaces before the opening XML tag. The following error is what I get in the feed validator:

line 1, column 2: XML parsing error: <unknown>:1:2: XML or text declaration not at start of entity

So I am aware of other related posts on Stack Exchange and tried the things mentioned in:

Approach to removing extra space at beginning of RSS file?
xml sitemap module : XML declaration allowed only at the start of the document [closed]
RSS Feed does not validate using Views RSS module

These are the things we did do so far:

Checked all PHP-files on the website for containing blank spaces before the opening tags. There were a few, we fixed them all but no help.
Changed the default theme to another theme, making sure it is not theme related.
When I create a custom RSS feed with Views, the same two blank spaces show up before the XML opening tag.
I checked every page, block and view that has manually written PHP tags everywhere and deleted every space that could cause this.
All modules and Drupal core is updated to the most recent versions.
I checked on the Drupal forum for related issues in XML Sitemap, Metatag, RDF, Schema.org (modules we are using) with no success. I disabled every one of the above mentioned modules one by one, but with no success.
Eventually we exported the complete website, except the sites/default/files/ folder which contains no PHP files anyway, and imported it local. The blank spaces are gone in the local setup.

What makes it a bit difficult too, is that I have no idea when the RSS feed went broken. It can be between a week and a few months, making it difficult to filter out when I updated some contrib modules.
So we are quite desperate in finding this, especially since the problem doesn't exist in a local setup. We have a news website so having a working RSS feed is pretty important.
We must be overlooking something, but have no idea what it can be.
Answer: Some more troubleshooting ideas:

Do the spaces only appear on the RSS page, or also on other pages? That could tell you whether the problem is in a central place or a template/include-file that is only loaded for the RSS feed.
You can use var_dump(get_included_files()) (ideally in the template, just before the XML is generated) to see a list of all PHP files that have been included so far. This might help with investigating - look for closing PHP tags at the end of the files, print statements, etc.

Also, an idea for a dirty workaround (may cause other problems, but could be worth a try if it's urgent): ob_start() buffers all output, while ob_end_clean() deletes it. So if you put an ob_start() in the top of your index.php and an ob_end_clean() at the start of the RSS template, this might let you discard the spaces. (It shouldn't affect anything else, because the buffer is flushed automatically if it's still open when the script ends.)
Comment: Yeah, this is definitely a problem to watch out for. Drupal coding standards actually say to omit the closing PHP tag entirely: It's optional, and removing it reduces avoids the risk of whitespace issues.
Comment: I managed to solve the problem. The issue was a module which had two blank spaces AFTER the closing PHP-tags in its .module file. All the topics I've found on the internet only mentioned blank space before the opening PHP-tags, so if anyone else ever have this issue, also look in the closing tags.
Answer: To debug whitespaces in the page output, you can use XDebug PHP extension. Here are the suggested options in your XDebug PHP's ini file:
; Data
xdebug.default_enable = 1           ; bool: The stacktraces will be shown by default on an error event.
xdebug.collect_vars = 1             ; bool: Gather information about which variables are used in a certain scope.
xdebug.show_local_vars=1            ; int: Generate stack dumps in error situations.
xdebug.collect_assignments=1        ; bool: Controls whether Xdebug should add variable assignments to function traces.
xdebug.collect_params=4             ; int1-4: Collect the parameters passed to functions when a function call is recorded.
xdebug.collect_return=1             ; bool: Write the return value of function calls to the trace files.
xdebug.var_display_max_children=256 ; int: Amount of array children and object's properties are shown.
xdebug.var_display_max_data=1024    ; int: Max string length that is shown when variables are displayed.
xdebug.var_display_max_depth=5      ; int: How many nested levels of array/object elements are displayed.
xdebug.show_mem_delta=0             ; int: Show the difference in memory usage between function calls.
xdebug.show_exception_trace=0       ; bool: Show a stack trace whenever an exception is raised.
xdebug.max_nesting_level=256        ; int: Controls the protection mechanism for infinite recursion protection.

Then either use step-by-step debugging mode, or temporary activate xdebug.auto_trace=1 to generate trace files within your xdebug.trace_output_dir on every request.
Then request XML file and check the trace file. It'll take a while to track down the source of it by checking the returns of certain functions near end, but at least it's possible.

Alternatively disable as many modules as you can and you can find the problem by trial and error.

If you believe one of your .module's file could consist trailing spaces, the following ex command (part of Vim) will remove any of these:
ex +'bufdo!%s/\s\+$//e' -scxa **/*.*

Note: If your shell supports a new globbing option, use ** for recursive scan. Enable by: shopt -s globstar.

Another way is to run your files through the coding standards using Coder module. After installation, the following command will find the issue related hidden trailing spaces:
phpcs --standard=Drupal some_folder/

To fix the issue in-place, try this one:
phpcbf --standard=Drupal some_folder/

Note: Before run, make sure you've everything committed or made a backup, as above command will reformat all your files.
Answer: The issue was a module which had two blank spaces AFTER the closing PHP-tags in its .module file. All the topics I've found on the internet only mentioned blank space before the opening PHP-tags, so if anyone else ever have this issue, also look in the closing tags
Comment: `.module` files are not suppose to have closing tags.


Reading GPS data from android device with Python

Question: I am trying to read data from an Android device with Python using Pydroid3.
I first tried the following:
import android, time
droid = android.Android()
droid.startLocating(0, 0)
event = droid.eventWait(1000).result
if event['name'] == "location":
  print(event['data']['gps'])
droid.stopLocating()

But this fails with:
Error importing module "android": this module is a part of Kivy
You cannot use it from elsewhere

Would be cool, if I could use it...
I then tried to use plyer to test an alternative:
from plyer import gps

def print_locations(**kwargs):
    print('lat: {lat}, lon: {lon}'.format(**kwargs))

gps.configure(on_location=print_locations)
gps.start()
# later
gps.stop()

And that fails with:
ModuleNotFoundError: No module named 'plyer.platforms.linux.gps'

I couldn't really find any resources that had similar issues...
Help is highly appreciated as I am a bit stuck here...
Thanks!
Comment: how are you executing python script? and how are you connecting to android device?
Comment: I have Pydroid 3 (https://play.google.com/store/apps/details?id=ru.iiec.pydroid3&hl=de) as a Python IDE installed on my phone and execute the code locally on the phone.
Answer: It's an older question, but for anyone still seeking an answer, here's how to achieve this for Android versions >= 12:

Launch the terminal in the Pydroid3 app.
If plyer is already installed, uninstall it:

pip uninstall plyer

Install the plyer fork from HyTurtle:

pip install https://github.com/HyTurtle/plyer/archive/master.zip

That's it!


Why is the error message not being printed?

Question: Here is a minimal reproducible example of the problem:
#include <iostream>
#include <string>

struct MyEx : public std::exception
{
    std::string name;
    MyEx(std::string name);
    ~MyEx() throw();
    virtual const char* what() const throw();
};

MyEx::MyEx(std::string name):
    name{name}
{}

MyEx::~MyEx() throw() {}

const char* MyEx::what() const throw() {
    std::string msg = name + "...";
    return msg.c_str();
}

int foo() {
    throw MyEx("This is an exception");
}

int main() {
    try {
        int res = foo();
        std::cout << res << std::endl;
    } catch (MyEx& caught) {
        std::cout << caught.what() << std::endl;
    }
}

When I execute the executable compiled with g++, I should be getting: This is an exception..., but all I am getting is a newline.
Why would this be happening?
Comment: `return msg.c_str();` returns a dangling pointer - the object that owns the text is out of scope after the function returns
Comment: @UnholySheep Isn't a copy made using the string copy constructor? What would be an alternative to achieve what I am trying to do?
Comment: It's the copy that is going out of scope. `msg` only exists for the duration of `what()`, which ends after `return msg.c_str();` - You could try creating the proper error message in the constructor instead
Comment: @UnholySheep Is this correct: "Since `msg` is of type `const char *`, and we are returning a pointer to something that we have made on the stack of function `what()`, when we return and the stack pops, the pointer `msg` is invalid memory." That's why we can't access it in main? So if instead `msg` was a string (and say return type of `what()` was a string), then this would work flawlessly right? Since a copy of the object is created in the stack of main?
Comment: That should work, although generally speaking using a `std::string` inside an exception object is a bad idea, as allocations required by `std::string` could throw as well (which would destroy your error handling)
Answer: One way to avoid the "dangling pointer" mentioned by UnholySheep in the comments is to make msg a member variable (but you'll need to remove the const from what) ...
struct MyEx : public std::exception
{
    std::string name;
    std::string msg; // This will stay 'in scope` while object exists
    MyEx(std::string name);
    ~MyEx() throw();
    virtual const char* what() throw(); // Note removal of const
};
//...

const char* MyEx::what() throw() {
    msg = name + "...";
    return msg.c_str();
}


Clamd won't start after update

Question: Since updating clamd to 0.99.2-1.e15 on our RedHat 5 x86_64 system, it has failed to start successfully. The error we get is as follows:
LibClamAV Error: cli_pcre_compile: PCRE compilation failed at offset 52: unrecognized character after (?<
LibClamAV Error: cli_pcre_build: failed to build pcre regex
ERROR: Database initialization error: Malformed database [FAILED]

Freshclam works fine. I've even removed clamd, clamav-milter, and freshclam, then re-installed them (using "yum install clamd" and "yum install clamav-milter"), but even after running freshclam, I get the same error when trying to start clamd (using service clamd start).
I've been Googling this error and found a Mac OS X with a similar issue but the patch was not available
Please advise because I'm not sure how to correct this issue. It appears to be something with PCRE, but I'm not sure (we're running pcre.x86_64, version 6.6-9.el5).
Comment: clamav is an EPEL package. Have you [filed a bug report](https://bugzilla.redhat.com/enter_bug.cgi?product=Fedora%20EPEL&component=clamav)? Also keep in mind that RHEL 5 support ends March 31 (in 27 days).
Comment: I'm seeing this problem on a CentOS 5 server as of a few hours ago. ClamAV is installed via WHM 56.0 (build 43).
Answer: In summary:
This temporary workaround from the CentOS 5 CLI (Command Line Interface) got our mail happily flowing again via amavisd-new:
sudo sh -c "cat << EOF >> /var/lib/clamav/daily-23161.ign2
Doc.Macro.GenericHeuristic-5901772-0
Doc.Macro.GenericHeuristic-5931846-1
EOF
service clamd restart"

More details:
The (filename doesn't matter).ign2 whitelists the troublesome entries from the latest daily.cvd
Thanks @Jamen-McGranahan for the OP (Original Post) and @Michael-Hampton for mentioning bug report. Found these resources useful:
ClamAV Bugzilla: Bug 11800 - 23161 seems to break clamd
Stack Overflow: How do I use sudo to redirect output ...
Unix & Linux Stack Exchange: How to append multiple lines to a file with bash
amavis
Answer: The problem is the daily update.  I restored the daily.cld from a few days ago and it works fine.  I also disabled freshclam for now so it doesn't mess it up again.
Comment: Just ran freshclam and it appears that the updates are now fixed.
Comment: They reversed the PCRE 7+ requirement for the signatures. We can expect this problem to happen again once RHEL/CentOS/CloudLinux 5 reach EOL later this month.

Clamd won't start after update


Adding a class to img tags using JavaScript

Question: I am a learning javascript guy and I am trying to add the Image Hover Shadow Effect With CSS to my images and for that to work , I have to add an class to all my img tags , which is not possible manually so i am trying to write a javascript that does that and uses jquery , to do so .
it needs to add an class to img tag , such as this
From this

to

Can anyone help :)
Thanks
Answer: To add the class to all of the images on your page with jQuery:
$("img").addClass("imagedropshadow")

Without jQuery is is not very difficult either:
var images = document.getElementsByTagName("img");
var i;

for(i = 0; i < images.length; i++) {
    images[i].className += " imagedropshadow";
}

Comment: The activity of adding the class can be made simpler as follows

`images[i].classList.add('imagedropshadow');`
Answer: give an ID to your image, let's say it's imgId and then write this jquery (if you want to add class to any specific img tag.)
$(document).ready(function(){
      $('#imgId').addClass('imagedropshadow');
});

for all img tag simply use this;
$("img").addClass("imagedropshadow");

Answer: Are you sure you need the class. If you are planning to add a css class to all images and hook the shadow to it, you should be able to do it on the img tags directly.
img:hover{
 /*properties*/
}

Comment: THANKS THIS WORKS .. $("img").addClass("imagedropshadow");  this did not work though :( anyway THANKS !
Answer: You can use the addClass function with jQuery. See the API here for examples.
Comment:   so is this how i am supposed to do so ? it is not working
Comment: place your code inside `$(document).ready(function(){ $("img").addClass("imagedropshadow"); });`
Comment: Thanks img:hover{
 /*properties*/
} worked jsfiddle is a gr8 site for debugging THANKS :) @Vivek @James Allardice
Answer: You can try this:
$('img').addClass('imagedropshadow');

But I suggest you that you add an id or general class into the img tag for selecting.


Datetimepicker só funciona no Bootstrap 3

Question:

Quando clicar, basta abrir este pop-up. IMG1
Ao clicar no pop-up, ele desliza para cima e não mostra o calendário. IMG2 Quando altero o boostrap para a versão 3.x.x, ele funciona corretamente.
Mas todo o meu projeto está usando a versão 4.3.1.
Alguma sugestão?

$(function () {
  $('#datetimepicker5').datetimepicker({
    defaultDate: "04/09/2019",
    locale: 'pt-br'
  });
});

<link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="assets/css/jquery-ui.min.css">
  <link rel="stylesheet" type="text/css" href="assets/js/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.css">

                    <input type='text' class="form-control" />

Comment: Tenho uma sugestão! Use um plugin que foi feito para o BS4, e não um plugin do BS3 dentro do BS4 ;)
Comment: Opa, to revirando a internet e não encontro algo específico do datetimepicker para o BS4
Answer: Seu problema é que várias classe e data atributes do BS3 são diferentes do BS4, inclusive um tem o popper.js e o outro não. São várias diferenças entre as versões, não vou aborda-las aqui, mas o fato é que não é possível usar os plugins do BS3 no BS4.
Aqui tem um modelo feito para o BS4 que pode te ajudar.

<!DOCTYPE html>

<meta charset="utf-8" />
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.min.css" />

            <input type="text" class="form-control" id="datepicker" placeholder="DD/MM/AAAA" data-date-format="dd/mm/yyyy">

    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet" />

Comment: o mesmo serve para o datetimepicker?
Comment: @FelipeFernandes acredito que não... vc tem que consultar a documentação desse plugin para ver o que tem disponível lá... Esse ai da resposta é bem completo. Aqui tem a documentação completa dele https://bootstrap-datepicker.readthedocs.io/en/stable/
Comment: valeu pela dica!.


Not enough memory on raspberry pi to install opencv , Is there a special way to install raspbian OS on SD card to save lot free memory

Question: I have a raspberry pi B+. I installed raspbian OS on 16GB SD card and put it in to raspberry pi(work properly). Now I want to install opencv on it. But it shows only small available memory.(cannot install opencv on it, because of not enough free space).
how can I get more memory. Is there a special way to write raspbian image  in SD card(like partition the SD card and install raspbian). looking for your help. thanx.....
Comment: Sounds fishy... 16GB SD is gigantic. I don't even get my 8GB full. Are you sure you use your whole card? If you installed a 4GB raspian image, you use only 4GB... you have to use raspi-config to enlarge your filesystem to use the full 16GB.
Comment: I'm new to raspberry pi technology. could you please tell me how to do that. Tank you very much for your help Mr.Greenflow
Comment: Just enter **sudo raspi-config** in console. First point: Expand Filesystem. Use it.
Comment: It works ... thank you very much agin, Greenflow
Answer: https://www.raspberrypi.org/documentation/configuration/raspi-config.md
Fresh raspian images are 2GB. If you copy such an image to a SD card, everything beyond that is unused. Fortunately this can easily be fixed.
In a console enter:

sudo raspi-config

The menu, which appears has as first menu item:

1 Expand Filesystem              Ensures that all of the SD card
  storage is available to the OS
   1 Expand Filesystem              Ensures that all of the SD card storage is available to the OS

Use it and you are done.


Postfix using virtual.db file instead of mysql table

Question: I have specified virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf, but still I got errors like

warning: hash:/etc/postfix/virtual is unavailable. open database /etc/postfix/virtual.db: No such file or directory

If I create the virtual and virtual.db files, everything works fine, but I want my virtual user account to be stored in DB, not if a file.
Why does postfix use the virtual.db file instead of db table?
postconf -n:
alias_maps = hash:/etc/aliases
broken_sasl_auth_clients = yes
config_directory = /etc/postfix
dovecot_destination_recipient_limit = 1
inet_interfaces = all
inet_protocols = ipv4
milter_default_action = accept
milter_protocol = 2
mydestination = localhost
non_smtpd_milters = unix:/var/run/opendkim/opendkim.sock
smtp_tls_note_starttls_offer = yes
smtpd_milters = unix:/var/run/opendkim/opendkim.sock
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
smtpd_sasl_auth_enable = yes
smtpd_sasl_local_domain = example.tst
smtpd_sasl_path = private/auth
smtpd_sasl_security_options = noanonymous
smtpd_sasl_type = dovecot
smtpd_tls_auth_only = no
smtpd_tls_cert_file = /etc/dovecot/dovecot.pem
smtpd_tls_key_file = /etc/dovecot/private/dovecot.pem
smtpd_tls_loglevel = 1
smtpd_tls_received_header = yes
smtpd_tls_security_level = may
smtpd_tls_session_cache_timeout = 3600s
smtpd_use_tls = yes
virtual_alias_maps = mysql:/etc/postfix/mysql-virtual-alias-maps.cf
virtual_mailbox_domains = mysql:/etc/postfix/mysql-virtual-mailbox-domains.cf
virtual_mailbox_maps = mysql:/etc/postfix/mysql-virtual-mailbox-maps.cf
virtual_transport = dovecot

Actually I have /etc/postfix/virtual in master.cf:
submission inet n - - - - smtpd
  -o smtpd_tls_security_level=encrypt
  -o smtpd_sasl_auth_enable=yes
  -o smtpd_sasl_type=dovecot
  -o smtpd_sasl_path=private/auth
  -o smtpd_sasl_security_options=noanonymous
  -o smtpd_sasl_local_domain=$myhostname
  -o smtpd_client_restrictions=permit_sasl_authenticated,reject
  -o smtpd_sender_login_maps=hash:/etc/postfix/virtual
  -o smtpd_sender_restrictions=reject_sender_login_mismatch
  -o smtpd_recipient_restrictions=reject_non_fqdn_recipient,reject_unknown_recipient_domain,permit_sasl_authenticated,reject

Comment: You did `postfix reload`, right?
Comment: Do you get virtual.db anywhere when you run 'postconf'?
Comment: @dan, yes, of cource
Comment: @tim-stoop no, I don't
Comment: You sure `postconf | grep /etc/postfix/virtual` doesn't show the hashmap being referenced?
Comment: @dan, yes, I've checked it with grep several times trying to find anything unusual. postconf | grep /etc/postfix/virtual returns nothing
Answer: The problem was the line -o smtpd_sender_login_maps=hash:/etc/postfix/virtual in master.cf. I forgot to look there, because this exact configuration was running fine for months on another my server.
Comment: Would you like to accept this answer so this question wasn't left in unanswered state?
Answer: I've solved that by modifying the line in etc/postfix/main.cf  :
virtual_alias_maps = hash:/etc/postfix/virtual

to
virtual_alias_maps = hash:/etc/aliases

(or as an alternative, just create the etc/postfix/virtual file with content):
your_linux_username:  firstname.lastname@example.com

then restart postfix:  sudo systemctl restart postfix and then mails were sent.


Azure YAML pipeline: find variable in group dynamically

Question: I have a Powershell script that is executed in my YAML pipeline during the release stage.
I can reference group variables using <code>$(myVar)</code>.  However now I have a need to reference a variable dynamically given its name.
For instance, if I have the string 'myVar', I want to search the variable group for a variable named 'myVar' and get its value.
Is this possible to achieve ?
Answer: In the end I did it like this. First I installed the Devops module for powershell so I can get group variables through devops api :
<code> Add-AzureDevOpsAccount    -OrganisationName "myor"   -ProjectName "myproj"   -Token "mytoken"

Write-Host -ForegroundColor DarkGreen "Getting variables group based on name"
$group = Get-AzureDevOpsVariableGroup -SearchString "dev"
</code>
Then to get a variable based on its name :
<code>$tokenValue = $group.variables | Select-Object -ExpandProperty $someName | Select-Object -ExpandProperty Value
</code>


How solved the sintax to concat an element HTML?

Question: I have a code to render my value

{`${t('single:yes')}: ${value}`}

but i need to put a span between the value, for example:

{`${t('single:yes')}:<span> ${value}<span>`}

but dont work, what is the wrong?
Comment: Can you show us code from what you've already tried?
Comment: @Green-Avocado its my try {`${t('single:yes')}: ${value}`}
Answer: I think u want the code show like this?
before

{`${t('single:yes')}:<span> ${value}<span>`}

after

{t('single:yes')}: {value}


Custom Block Content with HTML and PHP

Question: I am having a lot of trouble understanding what is wrong with my code. I am trying to create a custom Facebook block, utilizing the Facebook Graph API. My module works to the extent that I see some posts show but the following is taking place:
1) The posts duplicate. This does not happen when recreating the feed outside of a drupal module.
2) Output of Block content is outside of any region and loads at the top of the page.
Here is the code I am using:
/**
 * Implementation of hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['facebook_block'] = array(
    'info' => t('Facebook Block'),
  );
  return $blocks;
}

/**
 * Implementation of hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();
  switch ($delta) {
    case 'facebook_block':
      $block['subject'] = '';
      $block['content'] = facebook_main_contents();
      break;
  }
  return $block;
}

function facebook_main_contents(){
require_once('resources/facebook-php-sdk-master/src/facebook.php');

// connect to app
$config = array();
$config['appId'] = 'MYAPPID';
$config['secret'] = 'MYSECRETID';
$config['fileUpload'] = false; // optional

// instantiate
$facebook = new Facebook($config);

// set page id
$pageid = "MYPAGEID";

// now we can access various parts of the graph, starting with the feed
$pagefeed = $facebook->api("/" . $pageid . "/feed");

echo "
";

// set counter to 0, because we only want to display 10 posts
$i = 0;
foreach($pagefeed['data'] as $post) {

    if ($post['type'] == 'link' || $post['type'] == 'photo') {

        // open up an fb-update div
        echo "
";

            // check if post type is a link
            if ($post['type'] == 'link') {
                echo "
" . $post['message'] . "
";
                echo "
";
                echo "

";
                echo "
" . $post['name'] . "
";
                echo "
";
                echo "
Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
            }

            // check if post type is a photo
            if ($post['type'] == 'photo') {
                echo "
Photo posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
                if (empty($post['story']) === false) {
                    echo "

Story
" . $post['story'] . "
";
                } elseif (empty($post['message']) === false) {
                    echo "

Message
" . $post['message'] . "
";
                }
                echo "
View photo →
";
            }

        echo "
"; // close fb-update div

        $i++; // add 1 to the counter if our condition for $post['type'] is met
    }

    //  break out of the loop if counter has reached 10
    if ($i == 5) {
        break;
    }
} // end the foreach statement

echo "
";
}

I have tried placing my content code in a separate php file and including it, but that just breaks everything.
Answer: The problem is the lack of a return value in facebook_main_contents(); As you can see in the api documentation $block['content'] should contain either a Drupal render array or fully rendered html. facebook_main_contents(); is not actually returning anything but instead echoing output to the page.
You need to collect your rendered html and return it, like so:
$content = "
";
// check if post type is a link
if ($post['type'] == 'link') {
  $content .= "
" . $post['message'] . "
";
  $content .= "
";
  $content .= "

";
  $content .= "
" . $post['name'] . "
";
  $content .= "
";
  $content .= "
Posted on: " . date("jS M, Y", (strtotime($post['created_time']))) . "
";
}
...

return $content;

Comment: Ahhh, Thanks! I will give this a try on Monday but that makes sense. Will mark this if I succeed but I think this will do it.
Answer: Your function facebook_main_contents should return the HTML code.
Replace all your "echo" by a variable which will contain your HTML.
In fact, in drupal, you should never use an echo or a print in a file other than a template (*.tpl.php in drupal).

Custom Block Content with HTML and PHP


Filtering in pandas dataframe is not working

Question: I'm trying to combine 3 CSV into one by using panda data frame. Consider below example

So I need to combine above the csv into one. This is implemented using below code
if os.path.isfile(data1.csv) and os.path.isfile(data2.csv) and os.path.isfile(data3.csv):
    df1 = pd.read_csv(data1.csv)
    df2 = pd.read_csv(data2.csv)
    df3 = pd.read_csv(data3.csv)
    self.combined_data_frame = pd.concat([df1, df2, df3], ignore_index=True)
    self.combined_data_frame = pd.DataFrame(self.combined_data_frame, columns=['col1', 'col2', 'col3'])
    result = self.combined_data_frame.loc[(self.combined_data_frame['col3'] == 'FALSE')]
    result.to_csv(data4.csv)

Even though am able to combine the CSV into one, could not filter the rows based on the condition. When I tried above code snippet I got below warning and data4.csv does not contain anything except the headers
(venv) C:\Users\edward_arrow\path_to_location>python runscript.py
C:\Users\edward_arrow\path_to_location\venv\lib\site-packages\pa
ndas\core\computation\expressions.py:68: FutureWarning: elementwise comparison f
ailed; returning scalar instead, but in the future will perform elementwise comp
arison
  return op(a, b)

May I know how can I resolve this issue in order to achieve my requirement or else is there any other method to implement using python.
Your  hints & solution are appreciated
#UPDATE
This is the excepted output
Answer:
Use pathlib to find the files
Use a list-comprehension with pandas.read_csv to create a list of dataframe and combine them all with pd.concat

Note that 'FALSE' and 'TRUE' have been converted to False and True respectively, and are bool, not str type.
Alternatively, use pd.concat([pd.read_csv(file, dtype={'col3': str}) for file in files]), which will maintain col3 as a str, and then still filter for 'FALSE'.

Filter the dataframe with Pandas: Boolean Indexing

The filter must filter for False, not 'FALSE'.

Save the dataframe with pandas.DataFrame.to_csv
The current version of pandas is 1.1.0.

from pathlib import Path
import pandas as pd

# find the files
files = Path('c:/users/some_path/to_files').glob('data*.csv')

# create a dataframe of all the files
df = pd.concat([pd.read_csv(file) for file in files]).reset_index(drop=True)

# display(df)
    col1  col2   col3
0      1     2  False
1      1     2  False
2      1     2   True
3      1     2  False
4      3     4  False
5      3     4   True
6      3     4   True
7      3     4   True
8      6     7  False
9      6     7  False
10     6     7  False
11     6     7  False

# filter the data for False
df_false = df[df.col3 == False]

# save the file
df_false.to_csv('false.csv', index=False)

Answer: It looks like you have an extra set of parenthesis in the statement:
result = self.combined_data_frame.loc[(self.combined_data_frame['col3'] == 'FALSE')]

Try using this instead :
result = self.combined_data_frame.loc[self.combined_data_frame['col3'] == 'FALSE']

Comment: you want: `result = self.combined_data_frame.loc[~self.combined_data_frame['col3']]`
Answer: Ok, I will take this 3 DataFrame, concatenated them, and filter with ~ for col3:
import pandas as pd

df1 = pd.DataFrame({
           'col1':[1,1,1,1],
           'col2':[2,2,2,2],
           'col3':[False, True, False, True]
         })
print(df1)
   col1  col2   col3
0     1     2  False
1     1     2   True
2     1     2  False
3     1     2   True

df2 = pd.DataFrame({
           'col1':[3,3,3,3],
           'col2':[4,4,4,4],
           'col3':[False, True, True, True]
         })
print(df2)
   col1  col2   col3
0     3     4  False
1     3     4   True
2     3     4   True
3     3     4   True

df3 = pd.DataFrame({
           'col1':[6,6,6,6],
           'col2':[7,7,7,7],
           'col3':[False, False, False, False]
         })
print(df3)
   col1  col2   col3
0     6     7  False
1     6     7  False
2     6     7  False
3     6     7  False

combined_data_frame = pd.concat([df1, df2, df3], ignore_index=True)
print(combined_data_frame)
    col1  col2   col3
0      1     2  False
1      1     2   True
2      1     2  False
3      1     2   True
4      3     4  False
5      3     4   True
6      3     4   True
7      3     4   True
8      6     7  False
9      6     7  False
10     6     7  False
11     6     7  False

final_data_frame = combined_data_frame[~combined_data_frame.col3]
print(final_data_frame)
    col1  col2   col3
0      1     2  False
2      1     2  False
4      3     4  False
8      6     7  False
9      6     7  False
10     6     7  False
11     6     7  False

final_data_frame.to_csv('final_data_frame.csv', index=False)

The final file is according your expected output (index=False).


jQuery Cycle - creating pager links from link inside div

Question: I'm putting together a nav for the front page of a site and I'm trying to get Cycle to use a custom pager link from the link contained inside a div.
Here's my current code:
$('#nav-cycle').before('
').cycle({
    fx:     'turnLeft',
    speed:  'fast',
    timeout: 9001,
    pagerEvent: 'click',
    pauseOnPagerHover: 1,
    pager:  '#frontpage-nav',
    allowPagerClickBubble: true,
    pagerAnchorBuilder: function(idx, slide) {
         return '
' + slide.title + '
';
    }
});

I need it to use the href from the link that is contained in each slide's div as the pager link. I found a question that seemed similar to this but without needing to get the link inside.
HTML as requested, with all the PHP stripped:

(page description text)

(page title)

Answer: In the pagerAnchorBuilder function, "slide" refers to the current
. To get the href of each  tag within each div, just use a jQuery selector to find the child  and get it's href value:
$('#nav-cycle').before('
').cycle({
    fx:     'turnLeft',
    speed:  'fast',
    timeout: 9001,
    pagerEvent: 'click',
    pauseOnPagerHover: 1,
    pager:  '#frontpage-nav',
    allowPagerClickBubble: true,
    pagerAnchorBuilder: function(idx, slide) {
        var href = $(slide).children('span').children('a').attr('href');
        return '
' + slide.title + '
';
    }
});

BTW, I'm assuming you're missing a closing div in your HTML above.
Comment: Are you sure `prop` is appropriate? I think you should be using `attr.` http://api.jquery.com/prop/
Comment: This did not work for me until changing pagerEvent to mouseover, but now the transitions are gone when I mouse between the links. I still get them when moving the mouse from the slide to the link though.
Comment: @kkjelgard: I'm not sure I understand. What exactly doesn't work? As I understood your question, you want the pager links to contain the same `href` value as the `a` tags contained within the slides, correct? That's what the above code does. Here is a jsFiddle with an extremely simplified demo: http://jsfiddle.net/DVVrr/1/ Can you provide more detail about what it is you're looking for?
Comment: Your code works for what I am asking in this post, so I will mark it answered. Thank you for your help! The issue now (which I think may have been happening before as well) is that there is no transition when I drag my mouse between the pager links. I'll try to keep looking if you don't know of a quick fix.
Comment: @kkjelgard: I'm happy to help. I can't seem to replicate your latest problem though: http://jsfiddle.net/DVVrr/3/ When I mouseover each pager link, I see the next slide transition in from the left. Am I missing something? Can you create a jsFiddle that replicates the problem?
Comment: I searched around and found a fix for it - seems like padding can sometimes break the transitions. In that example I'm seeing it too, sometimes the transition is skipped when moving between the links depending on direction and how fast you're doing it.
Comment: @kkjelgard: Ah, well, I'm glad you got it figured out.


Order of children added to UniformGrid in WPF

Question: If you add a second child to a UniformGrid with 3 rows and 3 colomns, will it be added in the same row or to the same column? Thanks for your help.
Comment: Are you seriously asking this? It takes less than a minute to try it yourself.
Answer: The second child is added to the same row as the first child.
Generally speaking, the UniformGrid adds children like you would write English text: from left to right, and when you reach the end of the line (row), start at the beginning (left) of the next line (row).


semi direct of quaternionic group

Question: Hi I'm having trouble understanding why the quaternionic group cannot be written as a semi-direct product in a non-trivial way. Is there a proof of why this is the case?
Answer: The only non trivial subgroups of $\mathbf{Q}$ are $\{1,-1\}$, $\{i\}$, $\{j\}$ and $\{k\}$. Since one needs at least one group of order $2$ in the decomposition $\mathbf{Q}=GH$ it must be $\{1,-1\}$, but this group is the center of $\mathbf{Q}$ so cannot be a factor of the decomposition.

semi direct of quaternionic group


jquery plugin - how to make $(this) working in the context of a custom setting

Question: Below is a very simplified version of an idea of what I want to do.
I am trying to set a custom option  like this below  but how do I use $(this) as its in the wring context. how do I write it so that the  main object gets the used and not the this in the function, right now I get a fnode error.
beforeDOTHIS: function () {

                        $(this).css({color:'blue'});
                        alert($(this).text());

                    }

http://jsfiddle.net/Dpeae/
HTML

test1

test2

test3

javascript
  /* To be moved to own custom js plugin file ------------------------------------------- */

                //custom plugin
                $.fn.addMySpan = function (customOptions) {

                    var defaults = {
                        textColor: "#033",
                        beforeDOTHIS: function () {}
                    };

                    var settings = $.extend({}, defaults, customOptions);

                   return this.each(function () {

                       settings.beforeDOTHIS();

                  });

                };

        /* -----------------------------------------------------------------------------------------------------*/

        $(document).ready(function () {

            $('#One,#Two,#Three').addMySpan({
                textColor: "red",
                beforeDOTHIS: function () {

                    $(this).css({color:'blue'});
                    alert($(this).text());

                }
            });

        });

Answer: Store a reference to this then set it as the function's context with call:
            var self = this;

            var defaults = {
                textColor: "#033",
                beforeDOTHIS: function () {}
            };

            var settings = $.extend({}, defaults, customOptions);

            return this.each(function () {

               settings.beforeDOTHIS.call(self);

           });


Exibir registro quando outra tabela não existir referência

Question: Preciso que apenas exiba algum registro se o campo id da tabela noticias  não tiver referência no campo idnoticia da tabela fotos_noticias.
SELECT
    noticias.id,
    noticias.titulo,
    noticias.slug,
    fotos_noticias.foto
FROM noticias
INNER JOIN fotos_noticias
    ON noticias.id <> fotos_noticias.idnoticia
WHERE
GROUP BY noticias.id

Infelizmente este SQL acima exibe todos os registros sem restrição
Comment: Recomendo leitura: [Not IN ou Not EXISTS qual usar?](https://pt.stackoverflow.com/questions/62925/not-in-ou-not-exists-qual-usar)
Comment: Qual é o gerenciador de banco de dados: Oracle Database? MariaDB? PostgreSQL? SQL Server?
Answer: Gladison, Vejamos se eu entendi:
Você quer todos os registros da tabela noticias que não existam em fotos_noticias? Se sim o select seria esse:
SELECT noticias.id, noticias.titulo, noticias.slug, fotos_noticias.foto
  FROM noticias
 WHERE noticias.id not in ( select idnoticia from fotos_noticias)
 GROUP BY noticias.id

Answer: Analisando a seguinte imagem:

Você quer fazer um LEFT JOIN (o gráfico a esquerda, o de baixo) eliminando os resultados onde as tabelas se interseccionam. Para isso basta usar WHERE tabela_b.id IS NULL.
No seu exemplo ficaria assim:
SELECT
    noticias.id,
    noticias.titulo,
    noticias.slug,
    fotos_noticias.foto
FROM noticias
LEFT JOIN fotos_noticias
    ON noticias.id = fotos_noticias.idnoticia
WHERE fotos_noticias.idnoticia IS NULL
GROUP BY noticias.id

Answer: Na Teoria dos conjuntos o que você procura é C = A - B onde A são as notícias e B são as fotos.
Há várias formas de solucionar o que necessita. Segue algumas usando T-SQL.
-- código #1
SELECT id from noticias
except
SELECT idnoticia from fotos_noticias;

ou
-- código #2
SELECT N.id
  from noticias as N
       left join fotos_noticias as FN on FN.idnoticia = N.id
  where FN.idnoticia is null;

ou
-- código #3
SELECT N.id
  from noticias as N
  where not exists (SELECT *
                      from fotos_noticias as FN
                      where FN.idnoticia = N.id);

ou
-- código #4
SELECT N.id
  from noticias as N
  where not in (SELECT FN.idnoticia
                      from fotos_noticias as FN);

Não testei; pode(m) existir erro(s).


does multiplying a trigonometric functions in 2×2 matrix by a 2×1 matrix output a 1×2 matrix or a 2×1 matrix?

Question: the figure comes from this post

if I consider this vector
$$\left(
\begin{array}{c}
a_{1} \\
a_{2} \\
\end{array} \right)$$
as a 2 by 1 matrix
is the result on the right of the equation a 2 by 1 matrix which looks like
$$\left(
\begin{array}{c}
a_{2} \\
-a_{1} \\
\end{array} \right)$$
or a 1 by 2 matrix which looks like
$$\left(
\begin{array}{c}
a_{2}& -a_{1}
\end{array} \right)$$
Comment: The joke in the comic is that the rotation matrix changes the coordinates so that the **coordinate change corresponds to a rotation**, not visually rotating the mathematical notation of the coordinates (vector).
Comment: What's a trigonometric function of a matrix???
Answer: The result is $\left(
\begin{array}{c}
a_{2} \\
-a_{1} \\
\end{array} \right).$
Answer: Multiplying a $\color{red}2\times \color{blue}2$ matrix ($\color{red}2$ rows and $\color{blue}2$ columns) by a $\color{blue}2\times1$ matrix ($\color{blue}2$ rows and $1$ column) makes sense because the blue $\color{blue}2$'s are equal, and the result is a $\color{red}2\times 1$ matrix ($\color{red}2$ rows and $1$ column).
The mnemonic that I learned back in the day for working out the dimensions of matrices in a product looks like this:
$$
"(\color{red}2\times \color{blue}2)\cdot (\color{blue}2\times1) = \color{red}2\times 1"
$$
where the inner $\color{blue}2$'s are equal (otherwise the product doesn't make sense), and cancel out, while the outer $\color{red}2$ and $1$ stay where they are.


ipv6addr_secondaries not properly working centos7

Question: Hello I tried to configure additional ipv6 addresses on my centos 7 server but it seems different from centos 6.
this used to work on my centos6 server BUT NOT ON my CENTOS 7
IPV6ADDR_SECONDARIES="2602:fde2:0fc0:0128:1111:2222:1212:10/44 \
2602:fde2:0fc0:0028:1111:2222:1212:11/44"
Both of these ip's were not pingable with ping6.
However if I just add 1 ip it works
IPV6ADDR_SECONDARIES=2602:fde2:0fc0:0128:1111:2222:1212:10/44

this works for example.
But it's only 1 ipv6 how can I add more than 1 with IPV6ADDR_SECONDARIES.
EDIT:
this is my eth0 config
# Created by cloud-init on instance boot automatically, do not edit.
#
BOOTPROTO=none
DEFROUTE=yes
DEVICE=eth0
DNS1=220.127.116.11
DNS2=184.108.40.206
GATEWAY=23.XXX.32.65
IPADDR=23.XXX.32.94
IPV6ADDR=2602:fde2:fc0::37/44
IPV6INIT=yes
IPV6_DEFAULTGW=2602:fde2:fc0::1
NETMASK=255.255.255.224
ONBOOT=yes
TYPE=Ethernet
USERCTL=no
IPV6ADDR_SECONDARIES="2602:fde2:0fc0:0128:1111:2222:1212:10/44 \
2602:fde2:0fc0:0028:1111:2222:1212:11/44"
Comment: This should work fine. Exactly what did you put in the configuration?
Comment: @MichaelHampton I added my eth0 config from /etc/sysconfig/network-scripts/ifcfg-eth0. I checked it with ping6 and it doesn't work.
Comment: Do you actually have a backslash and newline in there, or did you add that when posting it here? The first thing I would do would be to get rid of them.
Comment: @MichaelHampton Thats it I deleted the backslash and it works now. Earlier when I was trying to configure it with just spaces as said in the manual I did not add the ip's inside the "" tags. Thanks alot I've been busy on this for several days already. Centos7  is so much different from centos 6
Answer: Ok so this is the solution for me. You have to delete the backslash.
Example
IPV6ADDR_SECONDARIES="2602:fde2:0fc0:0128:1111:2222:1212:10/44 \
2602:fde2:0fc0:0028:1111:2222:1212:11/44"
Becomes
IPV6ADDR_SECONDARIES="2602:fde2:0fc0:0128:1111:2222:1212:10/44 2602:fde2:0fc0:0028:1111:2222:1212:11/44"

I don't know why this is. If it is the difference between centos6 and 7 or if it is just the difference between my machines.
THanks @MichaelHampton for the solution.
Comment: BTW: IPv6 addresses by default have a /64 "netmask". one exception is ::1/128 but by definition IPv6 interface addresses use a prefix length of 64bits


How can I get latest version of nano (4.5) on CentOS 7?

Question: The latest version of the nano editor is 4.5 (https://www.nano-editor.org/)... I'm running 2.3.1 on my CentOS 7 server and want to upgrade. But no repos (EPEL, Remi, etc.) seem to have anything newer than 2.3.
How can I get the latest nano? Do I need to build it from scratch on the server? I'd rather be able to use yum to manage installs/upgrades, if possible.
I see lots of download options (packages, Open SUSE[?], distributions, blah blah) on the nano page but none of them seem to be the right thing for yum. I think.
Comment: What is driving your upgrade? Bug fixes, new features?
Comment: New features I need access to.
Answer: To get Nano 4 on a CentOS 7 machine it's fairly simple.

Head to https://www.nano-editor.org/dist/v4/ and grab the latest .xz (as of February 2020, v4.8 is the latest version).

cd to a suitable directory, e.g. cd /opt.

Make a subdirectory to store everything: mkdir -p /opt/apps/nano
As some people do, you can also download the matching GPG signature
and verify it.

Uncompress and untar into a subdirectory named nano-4.8: tar -Jxvf nano-4.8.tar.xz

CD to the extracted folder and run configure: cd nano-4.8 && ./configure.You may need to install ncurses; read the output of make and it will advise you if so.

Compile: make && sudo make install

Tidy up and symlink the nano binary (if you didn't specify install location during configuration).

This method could be improved but overall I'm happy with it.
By default, the configure script points the eventual install to the default location of /usr/local/bin. You can customise with the --prefix=PREFIX (where PREFIX is an absolute file path) passed to ./configure but I don't mind the default. More info's available with ./configure --help.
My machine doesn't include usr/local/bin in $PATH; for an easy life you can uninstall nano 2 with yum remove nano, or nano to nano2 and install a symlink if you want to keep both for reasons:
mv /bin/nano /bin/nano2
ln -s /usr/local/bin/nano /bin/nano
After doing this, note that some .nanorc config variables have changed, so if you use set const this needs updating to set constantshow.
I personally use
set softwrap
set constantshow
include "/usr/local/share/nano/*.nanorc"

The include enables syntax colouring and the other two are self-evident. Nano 4 now softwraps by default but I've left it in.
softwrap is beneficial, you'll avoid inadvertently inserting line breaks in files with lines breaking over the width limit).
You can define these in ~/.nanorc or do it globally via the global nanorc file. (location varies).
The one thing I've not been able to figure out is where this global config should go - the usual paths like /etc, /etc/default, /usr/local/etc, and so on, don't work. strace -e open nano shows nano is not even attempting to open a global config file in any of the common locations. Maybe it needs another flag specified at compile time, but nothing obvious sticks out on ./configure --help though. The docs also changed after version 3 and vaguely refer to a system-wide config file whose location varies.
It seems that compiling from source by default doesn't include a global config. I just use my ~/.nanorc and include the syntax highlighting files from there, works fine. Perhaps investigating the version compiled for the repo RPM would reveal what needs changing.
A full list of options for nanorc is available in the docs (man nanorc or at https://www.nano-editor.org/dist/v4/nanorc.5.html).
Some other syntax highlighting notes are worth reading on https://www.mc-guinness.co.uk/blog/20160307/configuring-nano-text-editor-in-ubuntu/ and a few other posts on SE, AskUbuntu etc.
Edit, Feb 2020: I've used scopatz' syntax highlighting auto-install script in 'lite' mode (sh -l instead of sh in the one-liner): https://github.com/scopatz/nanorc . Other syntax highlighting packs are available.
I also had to comment out set const as that particular syntax is deprecated, and nano 4 softwraps by default. As of nano 2.7 the syntax changed to set constantshow anyway.
Answer: EL 7 packages were established a few years ago, and their builds are still at 2.3 because it is a stable distro. Many repos will not replace packages from base EL.
To continue using a Red Hat RPM, consider upgrading the OS of your editor environment (could be a VM or a container).
EL 8 appears to be up to 2.9, based on the CentOS 8 nano.spec and the packages on the mirrors. Not the latest.
Fedora 30 is newer, 4.2.
Or, feel free to compile yourself, perhaps take the Fedora spec and rebuild. As usual, you take on more responsibility if building yourself.
Comment: Thanks, yeah, I ended up just building it from the source, which was surprisingly easier than I thought and didn't screw up anything. Was able to do the same with the latest version of `less` too.
Answer: According @Chris Woods answer - i made one line script (nano version 5.9)
$ sudo yum install gcc ncurses-devel && mkdir /opt/apps/nano && curl https://www.nano-editor.org/dist/v5/nano-5.9.tar.gz -o /opt/apps/nano/nano-5.9.tar.gz && cd /opt/apps/nano && tar -xvf nano-5.9.tar.gz && cd nano-5.9 && ./configure &&  make && sudo make install && mv /bin/nano /bin/nano2 && ln -s /usr/local/bin/nano /bin/nano

Comment: Very nice, haven't tested but will assume it works ;-) That's a cool oneliner. Only suggestion would be to amalgamate the two yum installs.
Comment: thank you  very much!
Answer: To install last version
yum remove nano -y
yum --nogpg install https://mirror.ghettoforge.org/distributions/gf/gf-release-latest.gf.el7.noarch.rpm -y
yum --enablerepo=gf-plus install nano -y
Show error after nano /some.file but work after press enter
Answer: You can't. Nano 4.5 has dependencies on packages that are not available in CentOS 7 repos. If you want bleeding edge with that CentOS feeling, use Fedora
Comment: I can't upgrade to the latest nano on CentOS 7? At all? Period? That seems... unbelievable.
Comment: you can self compile from source


Prove that $f(x)=\frac{1}{x}$ is not uniformly continuous on (0,1)

Question: So I'm having difficulties understand and utilizing the definition of uniform continuity:
$\forall \epsilon \gt 0,$ $\exists \delta>0 $ such that
$$ |x_1-x_2|\lt \delta  \Rightarrow |f(x_1)-f(x_2)|\lt \epsilon $$
Asides from plugging in the function I'm lost as to what to do. How do I decide on which $\delta$ or $\epsilon$ to pick? (not just for this question, but for similar questions as well)
I've looked at other posts but they seem to be using techniques way too advanced for my understanding.
Comment: What is the difference between continuity and uniform continuity? This is the crucial part.
Answer: Consider the elements $\{1/n^2 : n \geq 1\}$ of $(0,1)$. As $n$ goes to $\infty$ these elements converge to $0$ and get as close as you want. Therefore you'll satisfy the $|1/n^2-1/(n+1)^2|\leq \delta$ part. On the other hand if you take $f(1/(n+1)^2)-f(1/n^2) = 2n+1 \to \infty$. Thus, for any $\delta$ you find a counter example.

Another proof can be obtained using the answer to the following question: Prove if a function is uniformly continuous on open interval, it is continuous on closed.
Suppose that the function $f(x) = 1/x$ is uniformly continuous on $(0,1)$. Then by the answer in the linked question, it should be extendable by continuity on $[0,1]$. This is obviously false, since the limit in $0$ is $\infty$.

Another argument: Note that uniformly continuous function maps Cauchy sequences to Cauchy sequences (this fact was used to prove the claim in the question linked above). Thus the sequence $(1/n)$ needs to be mapped to a Cauchy sequence. Since $f(1/n) = n$ is not a Cauchy sequence we can see that $f$ is not uniformly continuous.


Express (1,...,n) as a product of 2-cycles

Question: In Alan F. Beardon's "Algebra and geometry" he asks in an exercise to express $(1\ \ldots\ n)$ as a product of two cycles:

Show that $(1\ 2\ 3\ 4)=(1\ 4)(1\ 3)(1\ 2)$. Express $(1\ 2\ 3\ 4\ 5)$ as a product of $2$-cycles. Express $(1\ 2\ \ldots\ n)$ as a product of $2$-cycles.

I assume that if we are working with the set of numbers $\{1,\ldots,n\}$ doing so is not possible. Since all of the numbers of the set will be part of the cycle $(1\ \ldots\ n)$ already. I am new in this subject, so I do not know if I am making a mistake. Thanks.
Comment: Note that it doesn't have to be two _disjoint_ cycles.
Comment: The problem was stated the way it was in order to helpfully guide you away from tackling the hardest part right away. Did you work out how $(1 2 3 4) = (1 4)(1 3)(1 2)$? Did you try to do a similar thing with $(1 2 3 4 5)$? What happened then?
Comment: aaaaah! Great, thanks
Comment: Are you sure it is not asking for a product of $2$-cycles? Either is possible, but the latter would be more generalizable.
Comment: You were precisely right @TobiasKildetoft. But how would you do it?
Comment: (12345) = (12) (13) (14) (15) according to my thinking, I'm working on the (1 2 3 ... n) I suppose that (12) (13) ... (1n) @DavidK
Comment: That's good progress. I recommend to edit the question to add those observations and ideas.
Answer: Because $(1\ n)(1\ n)$ is the identity, the $n$-cycle $(1\ 2\ \ldots\ n)$ is the product of the two cycles $(1\ n)$ and
$$(1\ n)(1\ 2\ \ldots\ n)=(1\ 2\ \ldots\ n-1).$$
Induction on $n$ now also shows that $(1\ 2\ \ldots\ n)$ is a product of $2$-cycles.
Comment: Yes, that is correct. A proof of this is given by a minor variation on my answer; in stead of the $n$-cycle, apply the same argument to any cycle $(k_1\ k_2\ \ldots\ k_n)$ with the $2$-cycle $(k_1\ k_n)$. You will find that
$$(k_1\ k_2\ \ldots\ k_n)=(k_1\ k_n)(k_1\ k_{n-1})\cdots(k_1\ k_2).$$
Comment: What I've been seeing is that actually any cycle can be decomposed into a product of 2-cycles. For example, if I take (3 7 5 8 ) then, it would be equal to (3 8) (3 5) (3 7). So I will always have to fix some number within the cycle and then cyclically put in the second part of the parenthesis the next one in the cycle until I finish. Is that correct? What would be the general notation?


How do you write log to the base e?

Question: I was given a question, find $f'(1)$ of $f(x) = \ln \sqrt{2-x}$.
So I wrote
$$1/2 \ln (2-x)^{(-1/2)(-1)} = -1/2 \ln (2-x)^{-1/2}$$
$$= -(1/2\ln)/\sqrt{2-x}$$
But when I sub in $x = 1$ I get a SYNTAX error, I realised log base e cannot be put in my calculator. I don't know how to put this into my calculator, can anyone help? Thanks!!
Comment: @MrYouMath Your editing has a mistake in the last mathematical expression: that backsla\sh does not belong there.
Comment: $\log_a b = \frac{\log_c b}{\log_c a}$. This is the change of base law.
Comment: Why do you change from $\;\ln\;$ to $\;\log\;$ in the middle of the calculations? That can only contribute to confusion. You can use $\;\log\;$ all the way from the beginning.
Comment: Please check my edit $\ln$ is the natural logarithm, hence $\log_e$
Comment: @DonAntonio: I just added dollar signs and turned the function like $\ln$ and $\sqrt{.}$ into LaTeX the last line was strange from the beginning :D. I hope the op does correct the last line.
Answer: Given,
$$ f(x) = \ln \sqrt{2-x} $$
Use chain rule to differentiate.
$$ f^{'}(x) = \frac{1}{\sqrt{2-x}}\frac{1}{2 \sqrt{2-x}} (-1) $$
So, at $x=1$,
$$f^{'}(1) = \frac{-1}{2} $$
Answer: $f(x)=\ln(\sqrt{2-x})=\frac{1}{2}\ln(2-x)$, hence $f'(x)=\frac{1}{2}\frac{1}{2-x}\cdot(-1)$.
Answer: Using the chain rule, and since
$$\begin{cases}\left(\sqrt{2-x}\right)'=-\cfrac1{2\sqrt{2-x}}\\{}\\
\left(\log x\right)'=\cfrac1x\end{cases}\implies\left(\log\sqrt{2-x}\right)'=-\frac1{2\sqrt{2-x}}\cdot\frac1{\sqrt{2-x}}=-\frac1{2(2-x)}$$
for $\;x<2\;$, certainly.

How do you write log to the base e?


Not sure what I'm doing wrong, Python number-guessing game

Question: import random

print("Hey there, player! Welcome to Emily's number-guessing game! ")
name=input("What's your name, player? ")

random_integer=random.randint(1,25)

tries=0
tries_remaining=10

while tries < 10:
  guess = input("Try to guess what random integer I'm thinking of, {}!   ".format(name))
  tries += 1
  tries_remaining -= 1

# The next two small blocks of code are the problem.

  try:
    guess_num = int(guess)
  except:
    print("That's not a whole number!   ")
    tries-=1
    tries_remaining+=1

  if not guess_num > 0 or not guess_num < 26:
    print("Sorry, try again! That is not an integer between 1 and 25!   ")
    break

  elif guess_num == random_integer:
    print("Nice job, you guessed the right number in {} tries!   ".format(tries))
    break

  elif guess_num < random_integer:
    if tries_remaining > 0:
      print("Sorry, try again! The integer you chose is a litte too low! You have {} tries remaining.   ".format(int(tries_remaining)))
      continue
    else:
      print("Sorry, but the integer I was thinking of was {}!   ".format(random_integer))
      print("Oh no, looks like you've run out of tries!   ")

  elif guess_num > random_integer:
    if tries_remaining > 0:
      print("Sorry, try again! The integer you chose is a little too high. You have {} tries remaining.   ".format(int(tries_remaining)))
      continue
    else:
      print("Sorry, but the integer I was thinking of was {}!   ".format(random_integer))
      print("Oh no, looks like you've run out of tries!   ")

I'll try to explain this as well as I can... I'm trying to make the problem area allow input for guesses again after the user inputs anything other than an integer between 1 and 25, but I can't figure out how to. And how can I make it so that the user can choose to restart the program after they've won or loss?
Edit: Please not that I have no else statements in the problems, as there is no opposite output.
Answer: Use a function.Put everything in a function and call the function again if the user wants to try again!
This will restart the complete process again!This could also be done if the user wants to restart.
Calling the method again is a good plan.Enclose the complete thing in a method/function.
Answer: This will solve the wrong interval
 if not guess_num > 0 or not guess_num < 26:
    print("Sorry, try again! That is not an integer between 1 and 25!   ")
    continue

For the rest, you can do something like this
create a method and stick in your game data
def game():
   ...
   return True if the user wants to play again (you have to ask him)
   return False otherwise

play = True
while play:
   play = game()

Comment: Thank you haha, I didn't even realize I'd forgotten that


how to get the current action id in Yii?

Question: I need a function to get the current action Id, for example if the url is /controller/view/5 I want to get the 5 which is the action Id, how I can do that in Yii?
Answer: Current action id can be taken like this,
  $id = Yii::app()->request->getParam('id');// param name

Comment: this returns the action name!
Comment: Yes I want the parameter
Answer: Your url is not consistent with the way Yii expects you to form a URL. The general form of a url is
http://www.application.com/your_controller/your_controller_action/parameter1_tag/parameter1_value/parameter2_tag/parameter2_value/.../parametern_tag/parametern_value

In your case:
 /controller/view/some_parameter_tag/5

if you want to hide the parameter_tag, you can customise your route, You can use
  '/'=>'/view',
Look here for some examples:
Hide GET parameter from URL


Problema para utilizar um "System.out" em um objeto

Question: Estou tentando dar um System.out.println em um objeto que eu tenho (mesmo com o toString() na classe)
estou obtendo:

Predio [nome=LS, aptos=[[Lmodel.Apartamento;@7ba4f24f,
  [Lmodel.Apartamento;@3b9a45b3, [Lmodel.Apartamento;@7699a589,
  [Lmodel.Apartamento;@58372a00, [Lmodel.Apartamento;@4dd8dc3]]

Meus models:
Predio:
package model;

import java.util.Arrays;

public class Predio {
    private String nome;

    private Apartamento[][] aptos;

    public Predio(int qtdAndares, int aptosPorAndar, String nome) {
        this.aptos = new Apartamento[qtdAndares][aptosPorAndar];
        this.nome = nome;
    }

    public void adicionarApto(int andar, Apartamento apto) {
        if (andar >= this.aptos.length) {
            throw new IllegalArgumentException("O prédio só tem " + this.aptos.length + " andares");
        }
        // encontra a primeira posição não preenchida
        int i = 0;
        while (i < this.aptos[andar].length && this.aptos[andar][i] != null)
            i++;
        if (i >= this.aptos[andar].length) {
            throw new IllegalArgumentException("Andar " + andar + " já está com todos os apartamentos cadastrados");
        }
        this.aptos[andar][i] = apto;
    }

    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }

    @Override
    public String toString() {
        return "Predio [nome=" + nome + ", aptos=" + Arrays.toString(aptos) + "]";
    }

}

Apartamento:
package model;

public class Apartamento {
    private Integer qtdQuarto, qtdBanheiro, qtdCozinha, qtdSala, numeroApt;

    public Apartamento(Integer numeroApt) {
        this.numeroApt = numeroApt;
    }

    public Integer getNumeroApt() {
        return numeroApt;
    }

    public void setNumeroApt(Integer numeroApt) {
        this.numeroApt = numeroApt;
    }

    public Integer getQtdQuarto() {
        return qtdQuarto;
    }

    public void setQtdQuarto(Integer qtdQuarto) {
        this.qtdQuarto = qtdQuarto;
    }

    public Integer getQtdBanheiro() {
        return qtdBanheiro;
    }

    public void setQtdBanheiro(Integer qtdBanheiro) {
        this.qtdBanheiro = qtdBanheiro;
    }

    public Integer getQtdCozinha() {
        return qtdCozinha;
    }

    public void setQtdCozinha(Integer qtdCozinha) {
        this.qtdCozinha = qtdCozinha;
    }

    public Integer getQtdSala() {
        return qtdSala;
    }

    public void setQtdSala(Integer qtdSala) {
        this.qtdSala = qtdSala;
    }

    @Override
    public String toString() {
        return "Apartamento [qtdQuarto=" + qtdQuarto + ", qtdBanheiro=" + qtdBanheiro + ", qtdCozinha=" + qtdCozinha
                + ", qtdSala=" + qtdSala + "]";
    }

}

meu main:
package main;

import java.util.Scanner;

import model.Apartamento;
import model.Predio;

public class app {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Digite o nome do Predio: ");
        String nomePredio = scanner.next();

        System.out.println("Digite a quantidade de Andares do Predio: ");
        int qtdAndares = scanner.nextInt();

        System.out.println("Digite a quantidade de Apartamentos por andar: ");
        int aptosPorAndar = scanner.nextInt();

        System.out.println("Digite o prefixo de numeração dos Apartamentos: ");
        int prefApt = scanner.nextInt();

        Predio predio = new Predio(qtdAndares, aptosPorAndar,nomePredio);

        for (int andar = 0; andar < qtdAndares; andar++) {
            for (int apto = 0; apto < aptosPorAndar; apto++) {
                int numero = andar * prefApt + apto;
                // leia todos os dados que um apartamento precisa e passe todos para o construtor
                predio.adicionarApto(andar, new Apartamento(numero));
            }
        }

        System.out.println(predio);
    }

}

Answer: Você está chamando esse toString() (que aceita um Object) porque não tem um método que manda imprimir a representação textual de depuração de um array de Apartamento, tem só um que imprime um array de Object que imprime exatamente isto que está aparecendo, afinal um Object é algo genérico. Se você quer algo diferente disto tem que escrever um código que percorra o array e imprima do jeito que você quer, até porque o toString() não serve para o que está achando que ele serve.
O uso do toString() está errado, mas como provavelmente aprendeu errado em algum lugar e as pessoas tendem a continuar fazendo errado o que aprenderam em primeiro lugar provavelmente não vai querer resolver isto. Espero que a resposta ali ajude entender que o conceito todo está errado.
A solução é ter um método diferente que monte para você os dados manualmente fazendo um laço e pegando o que deseja do array e dos elementos contidos nele. Esquece essa ideia de mandar imprimir o objeto e vai sair do jeito que deseja.
Inclusive não cometa o erro conceitual do objeto fornecer algo com layout específico, o objeto só deve fornecer os dados, o layout deve ser dado por algo externo, até porque para cada situação será um layout diferente.
Existe uma solução automática com reflexão, mas ela é lenta e fácil fazer errado, em geral é uso errado para economizar digitação e não resolverá seu problema de forma específica que é o que deseja.
Comment: Pode fazer, estamos aí pra isso.
Comment: Obrigado estou tentando modificar o codigo com suas dicas e removi o toString, mas com isso entrei em um outro problema, creio que terei de fazer uma nova pergunta.


How to define Move Error types in Sui blockchain

Question: Trying to understand the idiomatic way we should set Errors in Sui blockchain smart contracts.
From the provided examples it seems that we should define constants per different expected error i.e. in Marketplace smart contract two errors are defined:
// For when amount paid does not match the expected.
const EAmountIncorrect: u64 = 0;

// For when someone tries to delist without ownership.
const ENotOwner: u64 = 1;

Questions:

what is the idiomatic Move-language way to name the error constants,
starting with the E character then camel case?
what if a dev assigns the same number to two or more errors?
Answer:
what is the idiomatic Move-language way to name the error constants, starting with the E character then camel case?

That's right.

what if a dev assigns the same number to two or more errors?

The author of a Move module is free to assign the same number to more than one errors since they are no different from regular constants. It is up to the consumer of the Move module how to interpret the error codes returned from the Move VM. Sui Move itself doesn't prohibit two error constants from having the same value. We may, however, add a module to Sui stdlib defining an error standard in the future.
Comment: I meant something similar to the [Error module in Diem Framework](https://github.com/diem/diem/blob/main/diem-move/diem-framework/move-stdlib/sources/Errors.move), which defines some utility functions for constructing different Diem-specific categories of errors. But we haven't made any decision regarding if we'll add this module or what it will look like.
Comment: Thank you @emma, by "error standard" you imply some enum structure?


Dynamic query Django build

Question: create dynamic query set using Django query
this case performs "AND" operation. but some time value is blank or NULL.
example:- user model have name, age, and city three columns.
and perform operation filter but this and query is dynamic some time 3 fields available or sometimes one or maybe two how to write a dynamic query.
Answer: You can use Q()
from django.db.models import Q
query = Q()
if need_filter_name:
    query &= Q(name='my_name')
if need_filter_age:
    query &= Q(age='my_age')
if need_filter_city:
    query &= Q(city='my_city')

User.objects.filter(query)

If you need OR operator use query |= Q()
For AND operator use query &= Q()
Comment: thanks, but 'Q' use for OR query I have use AND operations.

Dynamic query Django build


convert byte array to uint numeric value

Question: Let's say I have array of bytes
byte[] byteArr = new byte[] { 1, 2, 3, 4, 5 };

I want to convert this array to get regular numeric variable of uint, so result will be
uint result = 12345;

So far all the example I've seen were with bytes, byte I don't need bytes, but numeric value.
Thanks...
Answer: It sounds like you want something like:
uint result = 0;
foreach (var digit in array)
{
    result = result * 10 + digit;
}

Or more fancily, using LINQ:
uint result = array.Aggregate((uint) 0, (curr, digit) => curr * 10 + digit);

Comment: @Stanislav: Well what did you *want* it to give? 10 isn't a digit. (This is why you really need to give clear requiremenst.)
Comment: Hey John, very important question, why is this works only for numbers until 10? If I will convert it from byte array 1, 2, 3, 4, 5, 6, 7, 8, 9 it will give me result 123456789, but if I will convert it from byte array 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 it will give me 1234567900 please need to know how to fix it?
Comment: well, got you right now... now know the mistake, thanks, was just a bit confused
Comment: but if you have quick answer on how to parse it if there is number higher than 9 and you can share would be great :)
Comment: A solution requires a problem. Maybe we should just ignore any values over 9. Maybe we should throw an exception. Maybe we should change it to a random number. Without requirements, it's impossible to suggest an implementation.


Start website with playing Flash, at the end continue with a regular website

Question: I want to start my website with a flash movie as an intro. When the flash is finished I want to proceed to my regular website.
I have the flash movie (Full screen) and I have the website. I just can't find the proper connection.
Anyone any idea's
Answer: Before realizing this, thing a little bit about SEO.
There a several ways to do realize this "seofriendly".
Here my solution:
Build your HTML page. Add then add your vidoa via "JW-Player" in fullscreen into a container e.G:

...your video...

Very important: The html should exist under your video.
JS-Player has a great JS framework which has a "onfinish_video" event. When your video finishs, you can just hide your container("#myvideo").
Answer: You can simply navigate away from your intro page after the intro animation is finished.
To do that, on the last Frame of your Flash Intro add the following code:
if you are using AS3:
navigateToURL(new URLRequest("*add your page's URL here*"),"_self");

if you are using AS2:
getURL("*add your page's URL here*", "_blank");

You can define a full http:// URL to your page, or if the html/php file is in the same directory just put the file name there :
navigateToURL(new URLRequest("abc.html"),"_self");


2015 Moderator Election Q&A - Question Collection

Question: In connection with the moderator elections, we will be holding a Q&A with the candidates.  This will be an opportunity for members of the community to pose questions to the candidates on the topic of moderation.  Participation is completely voluntary.

The purpose of this thread was to collect questions for the questionnaire. The questionnaire is now live, and you may find it here.

Here's how it'll work:

During the nomination phase, (so, until Monday, August 24th at 20:00:00Z UTC, or 4:00 pm EDT on the same day, give or take time to arrive for closure), this question will be open to collect potential questions from the users of the site. Post answers to this question containing any questions you would like to ask the candidates. Please only post one question per answer.
We, the Community Team, will be providing a small selection of generic questions. The first two will be guaranteed to be included, the latter ones are if the community doesn't supply enough questions. This will be done in a single post, unlike the prior instruction.
This is a perfect opportunity to voice questions that are specific to your community and issues that you are running into at current.
At the end of the phase, the Community Team will select up to 8 of the top voted questions submitted by the community provided in this thread, to use in addition to the aforementioned 2 guaranteed questions. We reserve some editorial control in the selection of the questions and may opt not to select a question that is tangential or irrelevant to moderation or the election. That said, if I have concerns about any questions in this fashion, I will be sure to point this out in comments before the decision making time.
Once questions have been selected, a new question will be opened to host the actual questionnaire for the candidates, containing 10 questions in total.
This is not the only option that users have for gathering information on candidates. As a community, you are still free to, for example, hold a live chat session with your candidates to ask further questions, or perhaps clarifications from what is provided in the Q&A.

If you have any questions or feedback about this new process, feel free to post as a comment here.
Answer: What is your opinion of the role of the Magento StackExchange in relation to third-party extensions--both free and commercial?
Answer: Do you think you can/should help keeping the answered question rate high as a moderator? If yes, how would you do that?
Answer: Moderators have a decisive vote when it comes to closing questions, opening questions, validating edits.
This means a moderator can close a question without the need for other 4 votes.
What's your view on that? Does it change anything, does it make you pay more attention to what you are reviewing? or it doesn't make a difference?
Answer: Here is a set of general questions, gathered as very common questions asked every election. As mentioned in the instructions, the first two questions are guaranteed to show up in the Q&A, while the others are if there aren't enough questions (or, if you like one enough, you may split it off as a separate answer for review within the community's 8).

How would you deal with a user who produced a steady stream of valuable answers, but tends to generate a large number of arguments/flags from comments?
How would you handle a situation where another mod closed/deleted/etc a question that you feel shouldn't have been?

In your opinion, what do moderators do?
A diamond will be attached to everything you say and have said in the past, including questions, answers and comments. Everything you will do will be seen under a different light. How do you feel about that?
In what way do you feel that being a moderator will make you more effective as opposed to simply reaching 10k or 20k rep?
Answer: Many users are not native English speakers, they are not confident (or seem hard) to post a completely question. How will you do to encourage them to post questions regardless language matters?
Answer: How would you react with users who shamelessly posted stupid question/doing this job for me type of question.
How would you react with those users?
Answer:
Moderators frequently have to deal with content from user new to Magento and to StackExchange. What will you regularly do as a moderator with regards to these users?
Comment: from the OP: "Please only post one question per answer." :)
Comment: "As a moderator, will you remove answers, delete comments, etc. when they point out you're an idiot?"
Comment: And I, as a moderator I will try to educate before taking distructive measures.
Answer:
Moderators have several tools at their disposal to educate users and to ensure the quality of content. How would you rank the various activities of moderators?
Answer: In phase 2 of the graduation, the "trusted user" privilege will be gained at 20K reputation instead of 4k.
This means, the number of users that can vote to delete questions and answers with negative score suddenly drops from 23 to 3 and the responsibility to decide about deletion is shifted more towards the moderators (at least for some time).
How do you feel about this responsibility and what's your policy on deleting posts?
Answer: What do you believe is your most important role as a moderator specifically for this exchange - in your personal opinion and from a community perspective?
Answer: On Magento StackExchange, there're many questions take time to write the answers. Some users are able to answer but they don't have time (or they think it would take much time) to write down, then they don't answer at all.
How will/would you do to deal with this?