Saída do comando echo com % e %%

Question: Ao resolver alguns exercícios em Shell Script, encontro este script:
x="Este texto para teste."
echo ${x% *}

Confesso que, ao realizar o teste de mesa, não consegui resolvê-lo. Ao rodar este script o resultado foi:
Este texto para

Entretanto se modificar o echo para echo ${x%% *}, o resultado será:
Este

Qual é a explicação para estes resultados, tanto com % quanto com %%? Existe algum uso prático nestas expressões ou sua ênfase é somente em  exercícios didáticos?
Answer: Essas são apenas duas das muitas formas de se manipular strings em Bash. No caso, ambas servem para remover um trecho do final de uma string.
A diferença é que % remove o menor trecho possível, enquanto %% remove o maior trecho possível. Por exemplo, se eu tiver:
texto='abcdefbxyz'

E fizer:
echo ${texto%b*z}

Ele vai remover o menor trecho do final da string que corresponde a b*z (a letra b, zero ou mais caracteres e a letra z). O menor trecho que satisfaz essa condição é bxyz, por isso resultado deste echo é abcdef.
Agora se eu fizer:
echo ${texto%%b*z}

Ele vai remover o maior trecho do final da string que corresponde a b*z (a letra b, zero ou mais caracteres e a letra z). O maior trecho que satisfaz essa condição é bcdefbxyz, por isso resultado deste echo é a.

No seu caso, a string é "Este texto para teste.". Ao fazer echo ${x% *}, ele remove o menor trecho do final da string que corresponde a um espaço seguido de zero ou mais caracteres. O trecho que satisfaz esta condição é  teste., por isso o resultado é Este texto para.
E o fazer echo ${x%% *}, ele remove o maior trecho do final da string que corresponde a um espaço seguido de zero ou mais caracteres. O trecho que satisfaz esta condição é  texto para teste., por isso o resultado é Este.
É um recurso bem útil (para qualquer situação que envolva remover um trecho final de uma string), muito longe de ser algo "somente para exercícios".
Na documentação tem alguns exemplos.
Comment: Obrigado! Ótima síntese, ao ler a  segunda linha já consegui compreender!

Saída do comando echo com % e %%


should i restrict portraitupdsidedown mode for ipad

Question: i think my ipad app does not require a upside down mode because it changes the side buttons' locations. am i correct ? this is not a game app. An app meant for reading documents.
Answer: The HIG strongly recommends supporting upside-down mode. I think that a document reader especially needs this mode.
http://developer.apple.com/library/ios/ipad/#qa/qa2010/qa1689.html


Is there a downloadable preconfigured LAMP stack?

Question: It seems to me like there was a site several years ago that pre-packaged LAMP stacks in groups of versions that played well together. I've had a difficult time finding that site or any other site like that.
If there isn't a site like that, is there at least a site that has a chart or something that shows stable builds of LAMP stacks?
I am aware of TurnekyLinux.org but it isn't really what I'm looking for.
Any input or suggestions would be appreciated.
Thanks!
Comment: `yum install httpd php-mysql mysql-server`
Comment: I'm not asking how to install a LAMP stack. I'm asking for a place to download or chart out stable version of LAMP stacks.
Comment: Look at what the distro versions come with. Those are (usually) stable.
Answer: Having packages that play well together under linux belongs to the domain of the package manager for your distro.
If you want a one click install, the most common trick i see (under debian) is to: aptitude install phpmyadmin - which should install the lamp stack for you. Otherwise you have to install a group of 8 or so packages.
Comment: nice trick ! i seriously never seen it that way, but it's obviously very sweet way to install that :)
Comment: Is there something similar for Ubuntu?
Answer: XAMPP By Apachefriends
There you go :-)
or simply (Debian based):
<code>apt-get install apache2 mysql-server mysql-client php5 php5-mysql
</code>
Then you have a fully functional Apache2 Server (DocumentRoot /var/www) and a MySQL 5.1 (as of today Debian Squeeze) Server.
PS: I'm not sure if this is a programming question. Maybe move to ServerFault
Comment: I think you're right, this would be better server at ServerFault. I'll see if I can move it.
Answer: Use apt to install or just automate the process with pretty old tasksel.
I found this guide: http://www.computersnyou.com/2012/05/how-to-install-lamp-stack.html
Answer: Have you tried Bitnami LAMP Stack?  We provide completely free, ready-to-run installers, virtual machines and cloud images (AWS/Azure). There are also Windows and Mac versions
Comment: The Bitnami LAMP stacks and AMIs are awesome. With the AMI you find the one you want, use it to spin up a new EC2 instance on AWS and away you go. They also have installers to set up single stacks on an existing server for LAMP, WAMP and MAMP.


Using HttpUrlconnection in Rss Reader causes Android to hang

Question: I put together an RSS reader that works as-is but, I want to setup the connection to the RSS URL using HttpUrlConnection method. When I tried it, the program locked up after I clicked Read Rss button:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            URL rssUrl = new URL(params[0]);
            HttpURLConnection urlIn = (HttpURLConnection) rssUrl.openConnection();
            InputStream in = new BufferedInputStream(urlIn.getInputStream());
            String line;
            feed = "";
            while ((line = in.toString()) != null) {
                feed += line;
            }
            in.close();
            return feed;
        } catch (MalformedURLException ue) {
            System.out.println("Malformed URL");
        } catch (IOException ioe) {
            System.out.println("The URL is unreachable");
        }
        return null;
    }

}

This is the connection method I am stuck using which works:
private class getRssFeedTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        try {
            URL rssUrl = new URL(params[0]);
            BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
            String line;
            feed = "";
            while ((line = in.readLine()) != null) {
                feed += line;
            }
            in.close();
            return feed;
        } catch (MalformedURLException ue) {
            System.out.println("Malformed URL");
        } catch (IOException ioe) {
            System.out.println("The URL is unreachable");
        }
        return null;
    }

}

Thanks for any help you can provide!
Answer: What you need to do is put it into a string I called it results. I have attached my code for the doInBackground. By adding it to a string it has a place to store the feed.  And it works for the rss reader.
public String doInBackground(String... urls){

        String result = "";
        try{
            URL url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream in = conn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = "";

            while((line = reader.readLine()) != null){
                result = result + line;
            }

            conn.disconnect();
        }
        catch(Exception e){
            Log.e("ERROR Fetching ", e.toString());
        }
        return result;
    }


add condition to mysql json_arrayagg function

Question: I have a json query that gives me json of a joined table of person and pets:
SELECT json_object(
  'personId', p.id,
  'pets', json_arrayagg(json_object(
    'petId', pt.id,
    'petName', pt.name
  ))
  )
FROM person p LEFT JOIN pets pt
ON p.id = pt.person_id
GROUP BY p.id;

my issue is that person can have 0 or more pets, and when a person have 0 pets I get list with 1 empty pet, and what I would like to get in that case is empty list.
this is what I get:
{
  "personId": 1,
  "pets": [
    {
      "petId": null,
      "petName": ""
    }
  ]
}

and I need:
{
  "personId": 1,
  "pets": []
}

is that possible?
Comment: Duplicate of https://stackoverflow.com/questions/49960156/mysql-json-arrayagg-with-left-join-without-results
Answer: The problem is that LEFT JOIN still returns columns from the table you're joining with, it just sets their values to NULL.
You can use IF to test COUNT(pt.id), as this won't count null values.
SELECT json_object(
  'personId', p.id,
  'pets', IF(COUNT(pt.id) = 0, JSON_ARRAY(),
             json_arrayagg(json_object(
                'petId', pt.id,
                'petName', pt.name
                )
            ))
  )
FROM person p LEFT JOIN pets pt
ON p.id = pt.person_id
GROUP BY p.id;

Comment: Working Perfect.. THanks
Comment: Thank you so much, **IF( COUNT(...), ... , ... )** is a really nice trick, it had to be an aggregated function but I couldn't figure out which and how to use! )
Answer: Another possibility is to put the aggregation in a correlated subquery and use coalesce() to replace it with an empty array if no rows exist.
SELECT json_object('personID', p.id,
                   'pets', coalesce((SELECT json_arrayagg(json_object('petId', t.id,
                                                                      'petName', t.name))
                                            FROM pets t
                                            WHERE t.person_id = p.id),
                                    json_array()))
       FROM person p;

Answer: Adding another option:
select IFNULL( /*expression of select ...JSON_ARRAYAGG(
                                    JSON_OBJECT(....*/,JSON_ARRAY()) jarrayaggAlias

Cleaner below:
IFNULL( expression, ,JSON_ARRAY()) jarrayaggAlias

Result:
/* { jarrayaggAlias: []  }*/

If you swap alt_value for IFNULL to select [], then all your results will be stringyfied.


How to alter page title "Create X" to "Add X" for all X?

Question: In Drupal 7, there was drupal_get_title()and drupal_set_title(). They're history.
I want to alter the page title "Create X" to "Add X" for all X, and I think hook_preprocess_page_title() in my .theme-file is the right place to do it. (If you disagree, please say so.)
I.e. I want it to be 'Add X' for any 'X' when it originally was 'Create X'. For example: 'Create article' should become 'Add article'. And if the title is 'Bar Article', I should be left as is.
Basically, I want to sniff the title string and if it starts with 'Create ', alter it to 'Add '.  This is so far I've gotten, and this is obviously incomplete:
/**
 * Implements hook_preprocess_page_title().
 */

First attempt:
function mytheme_preprocess_page_title(&$variables) {
  $request     = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title       = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
}

Second attempt, based upon suggestion by 4k4:
function mytheme_preprocess_page_title(&$variables) {
  $title = $variables['title'];
  if ($title instanceof TranslatableMarkup) {
    $title = $title->getUntranslatedString();
    $title = str_replace('Create', 'Add', $title);
    $variables['title'] = t($title);
  }
  else {
    $variables['title'] = Markup::create(str_replace('Create', 'Add', $title));
  }
}

The titles I want to change come from Drupal core and they are translatable, so its the instanceof TranslatableMarkup branch that gets executed, but I agree with having a fallback in case they're not, is a good idea.
However, while a good start, this is not a complete solution. It changes the rendered title of the add article form from "Create article" to "Add @name".

I've upvoted the answer by 4k4, as it goes much further towards a solution than my first attempt, but it is still not complete.
I don't want to use the String Overrides module for this for several reasons, mostly because this theme should work across translations without requiring extra configuration when deployed.
Comment: Untested, but you could try solving it via template file. [page-title.html.twig](https://api.drupal.org/api/drupal/core%21modules%21system%21templates%21page-title.html.twig/8.2.x) change `{{ title }}` to `{{ title|replace({'Create X': "Add X"}) }}`
Comment: Thanks @NoSssweat! Yes, it works.  I still hope for an answer explaining how to do it in PHP. This will not work with translated titles.
Comment: Hmm try `|replace({'Create X'|t: "Add X"|t})`
Answer:
I want to alter the page title "Create X" to "Add X" for all X, and I
think hook_preprocess_page_title() in my .theme-file is the right
place to do it. (If you disagree, please say so.)

You can only change the title displayed in the body tag, not the title metatag in the html tag.

$title = \Drupal::service('title_resolver')->getTitle($request,
$route_match->getRouteObject());

This gets you only the title from the route definition or callback, not a title set by #title in the rendered output.

$title is not a string. The string is somewhere in there, but how do I
extract it to see what it starts with?

It's a markup object. Either a plain one or a translatable one. See How do you edit content of a Drupal\Core\Render\Markup instance via a preprocess function in Drupal 8? or How do I change text on the submission button in the node form?

How do I actually change it in the context of a preprocess hook. I.e.
what is equivalent of drupal_set_title() in this context?

In a preprocess hook you can only change variables which the template is displaying, in this case:
$variables['title'] = 'Foo title';

If it contains HTML markup to avoid autoescaping:
$variables['title'] = \Drupal\Core\Render\Markup::create('Foo title');

If it is translatable:
$variables['title'] = t('Foo title');

Code example:
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_page_title().
 */
function mymodule_preprocess_page_title(&$variables) {
  $title = $variables['title'];
  if ($title instanceof TranslatableMarkup) {
    $title_untranslated = $title->getUntranslatedString();
    $title_replaced = str_replace('Create', 'Add', $title_untranslated);
    $variables['title'] = t($title_replaced, $title->getArguments());
  }
}

Comment: I've added the t() arguments for the placeholder. Also I've removed the fallback because the title variable can contain different content, also entire render arrays.
Comment: I want it translatable. However, I don't want the title to be 'Foo title', I want it to be 'Add X' for any 'X' when it originally was 'Create X'. (e.g. 'Create article' should become 'Add article'. And if the title is 'Bar Article', I don't want to do anything. I am going to take a closer look at the links you provide about markup objects, but I still haven't figured out how to figure out if the string starts with 'Create'.
Comment: OK, so you want to replace the original english version and then translate the replaced version. This is a bit more complicated because the translatable markup returns as string the already translated string and you have to use a method instead of casting it to a string. I add a code example, also with a fallback for the plain markup which works with string casting.
Comment: Great!  The last incarnation works.
Comment: BTW, the screenshot you've added is the node.add route. You could replace this title callback in the route definition and it works also in breadcrumbs and metatags: https://api.drupal.org/api/drupal/core%21modules%21node%21src%21Controller%21NodeController.php/function/NodeController%3A%3AaddPageTitle/9.2.x
Comment: Your guidance is much appreciated, but some of it goes way over my head. Could you please tell me where my route definition lives and how to change it (or point me towards a suitable tutorial).
Comment: See for example (you only have to replace the route name): https://drupal.stackexchange.com/questions/217680/override-user-edit-page-title


Need help with opening passage of the 4th mvt of Mozart Symphony No. 39, 1st violin part

Question:
Hi,
I'm having a bit of trouble practicing this section of the piece. I've tried playing it slowly and gradually increasing the tempo, but I just cannot get it and it's quite frustrating. The problem is mainly in my bow; my left hand is fine. Does anyone have any tips?
Answer: This is a standard "excerpt" used in orchestral auditions. William Preucil has an album with him talking through his advice about various excerpts and demonstrating them. I highly recommend buying the whole album, but here's what he has to say about this excerpt:

... and his demonstration:

If you're playing in an actual orchestra, you don't have your own choice about bowing (unless you're the concertmaster). And if you're taking an audition, I would play it exactly as printed in the Breitkopf and Hartel edition and not try to invent any improvements; the challenges presented by the bowing are an expected part of the audition.
As Preucil notes, those slurs are the problem. In general, in fast passagework, our left hand can manage much more dexterity and speed than the bow can, and our job is to manage the bow to keep up with the left hand. First of all, the slurs cross strings. Yes, you could play the first couple of bars (mm. 16-17) in second position; this would have the double benefit of putting the slur all on one string, and putting the entire measure on only two, with no trip to the A string for the B flat. BUT we have no such option in mm. 18-19 (the ones that start on F); short of some crazy scheme of shifting back and forth between positions (inadvisable) we have no comfortable way to keep all the pitches on only 2 strings, or to avoid a string-crossing during the slur. That being the case, I don't know that I'd even bother with 2nd position in mm. 16-17; better to get the bowing pattern set up from the start. (Plus, if you have any interest in historicity, I doubt Mozart would have shifted to avoid string crossings.)
Recognize that each subsequent measure will reverse bow directions (I would not advise doing anything to change that). Recognize that the actual physical movement you make during the slur is very different on a downbow than an upbow (think about the shape your right hand traces in the air—an arch, or an inverted arch). Get used to putting beats on upbows in the in-between measures.
The best bit of general advice is to use as little bow as you can and still sound good. The slurs will move you (slightly) out of the ideal spiccato spot of the bow and you must work to get back; the less bow you use the lesser this problem. The "scoopy" arch-shaped motion of the downward string crossing on a downbow is less unwieldy on a shorter bow. If you're practicing by starting at a slow tempo and gradually increasing the metronome (a good idea), consider: if you use 2 cm of bow per note at 80 bpm, you should use 1 cm at 160 bpm. Can you get away with 0.5 cm? Produce a good, clean, sound, but see how little bow you need to do so.
In the slurs, work on the timing of the string crossing. Don't just sort of "blur" from D string to G, moving in a continuous arc; "pop" from one string to the other at the exact timing of the 16th note, just as you would lift and drop your left hand fingers with precise timing. (This will help keep m. 20, a few measures later,
...from coming out simply as a measure of double-stops!)
Have you worked on collé? That is, a bow stroke that is powered by "squeezing" and extending the fingers? Although this passage doesn't use true collé, the finger motion that powers it is a magic ingredient in many (maybe all?) bowstrokes, from a beautiful lyrical legato to off-string strokes to string crossings. Consider minutely the way every part of your right arm, from shoulder to fingertip, contribute to the motion of this string crossing. You can accomplish a string crossing by moving the whole arm, from the shoulder; you can do it by moving only from the elbow; you could keep your forearm stationary and merely bend at the wrist; and you could even keep your whole arm and the palm of your hand in one plane and compress or extend your fingers to reach different strings. Start with this finger motion, and then add in as much of the larger motions as needed to stay natural and comfortable. In rapid passagework, do the most you can with the smallest muscles; nothing is worse than trying to whip your whole arm through these string crossings as if you're beating egg whites.
It's great that you're practicing slowly and then at increasing tempos; that's the best start. Since so much of what makes these measures challenging is the bowing, try practicing the pattern of open strings that you'll be playing, without using left hand at all, so you can concentrate on the bow mechanics (e.g. "Slur D to G; G; G; D; D; A; D"). Do the same for the left hand, moving your fingers without bowing.
Consider what you can do to keep your fingering efficient. E.g. in the measure starting with F, it doesn't have to be "Play 2, then 3, then 1, 3, 2, 4, 2, 4"; we think that way because of the dots on the page. Instead, look at your fingers moving in physical space. It could be: "Place 2 and 3 on the F and C. Raise 3 to play the Ab. Lower 3. 2 is still down; rock slightly so that it contacts A string as well. Lower 4. Keeping 2 and 4 down, go to A string to play the C, and come back to D string for another Ab."
One challenge in passages that are all the same note value is to keep them even and equal. One way to practice these is to superimpose rhythmic patterns on them; try a "long-short" patter, dotting the first 16th and turning the second into a 32nd. Much harder, try the opposite, short-long! One long, plus a triplet-y 3 short? "Short-long-long-short" for syncopation? One benefit of these schemes is that it forces you to think about timing in the first place, and about how the mechanics of these motions conspire to rush or obstruct the timing. Another is that the "short notes" force you to make very quick motions, while the "long notes" give you a moment to think, so by combining multiple patterns you get the benefit of practicing very quickly without having to be so hyper-alert.
Comment: Good answer, Andy, and useful links. Thanks. The missing staccatos made me think the OP was playing from a home-made score and that s/he might be a learner. Anyway. You say, "each subsequent measure will reverse bow directions (I would not advise doing anything to change that)". Yes, if it's a trusted edition, I agree. But I'd love to know if you could hear a difference if the bow directions didn't reverse? Would that be somehow _unorthodox_ bowing? Which way might be better for someone in a high school band, or for someone sight-reading at a recording session?
Comment: @OldBrixtonian I probably should have elaborated at that point. (And yeah, the image is from a full score, which does suggest the OP isn't learning it in orchestra or for an audition.) If you're learning it for your own initiative, you're of course free to make whatever changes you want. I'd feel more free to make these changes in a concerto solo part (where one is expected to "make it your own"), or in a less well-known passage. A concertmaster might well give out an altered bowing for performance. But...
Comment: ...  since this is such a "standard" audition excerpt, I'd argue that judges expect the "standard" bowing, and if one is bothering to learn it, one might as well learn the expected version. Another perspective is: as I mentioned, if one is interested in an angle of historicity, I'm pretty sure (without bothering to verify at the moment) that this is the original bowing. The whole thing would have been much easier (or different, anyway) on period instruments. Finally, on either period or modern instruments, I'm not so sure that the "double up-bow after the slur" pattern is actually easier;
Comment: personally, I would find it even harder to not only interrupt the detaché with a slur but then to follow that up with a "springing" double-up, *and* then switch to ordinary spiccato.
Comment: I didn't realize it was used at auditions. (I've got a few collections of audition excerpts, though not for violin. I should get one. They're useful.) Yes, you're right about "standard" bowing, concertmasters etc. and I agree it probably _is_ Mozart's bowing. I'm really pleased to learn that the '"springing" (excellent word!) double up-bow' thing is no easier than the original which, to a non-violinist, seems extremely difficult! I _have_ a violin but I'm afraid I only use it to check an occasional double stop. I wish I could use it to check the bowing but my right arm has no cunning!
Comment: I don't know why it would have been easier/different on period instruments, but I probably don't **need** to know that! Sorry for the delay, Andy, and thank you once again for your help.
Comment: @OldBrixtonian Well, it's personal opinion that the double-up bowing is "just as hard." Obviously whoever chose it in an edition was of the opposite opinion! The big difference about period equipment is that this is, to varying degrees based on tempo and preference, an off-the string stroke; it bounces. Gut strings are a bit bouncier (or maybe just "grippier"?) than modern synthetics (at least, that's especially true of unwound gut, though well before Mozart's time wound gut would be common for G and D strings). Then, the bow: a lot changed during Mozart's lifetime, from the "baroque bow"...
Comment: @OldBrixtonian ... to the modern "Tourte" bow. In between, we like to talk about "the transitional bow," but the truth is it was a time of such experimentation that there are as many "transitional bows" as there are extant examples, with a lot of variation. All of these would perform differently in an off-the-string stroke, but as long as they're lighter and/or springier than modern, they might be able to navigate more nimbly (at the expense of power in *fff*).
Comment: "...whoever chose it in an edition..." They didn't! It was _my own_ suggestion for someone I thought was a learner. "Grippier" is an excellent word and I know exactly what you mean. Interesting stuff about period instruments - thank you. And I've just been reading about Tourte, and the development of the modern bow and I now understand why violinists produce their second best bows whenever they see I've written a passage marked "_col legno battuto_"! Thanks again for your help.
Answer: How are you bowing it? In your picture it looks as if even-numbered bars are bowed differently from odd-numbered ones:
Dow-hown up down  Up down up down | U-hup down up  Down up down up
I doubt if that's what was intended.
In the edition I'm looking at, the third and fourth semiquavers in each bar have staccato marks. They could both be played with a bouncy up-bow. Then the bowing of odd/even bars would be consistent:
Dow-hown up up   Down up down up | Dow-hown up up   Down up down up


Hyperledger Fabric behind firewall/proxy

Question: My Hyperledger Fabric enironment is behind a firewall, and I have to establish a connection with another organization. I know that Hyperledger uses GRPC for communication, and my organization has a HTTP proxy to access the internet, and I don't know if HTTP proxy solves this problem.
Any idea?
Answer: IT teams of both the organizations need to open communication between each other. HTTP proxy is to cut your communication with actual internet. That is not going to work here, as both the orgs are individually controlled environments.
Once connectivity between orgs is established (like some n/w tunnel creation or something), you can work with the servers of the other org as if those are in your LAN. Your IT team should get involved here. All the best.


How to use SUM and GROUP BY(SQL) with Visual FoxPro in VB.NET?

Question: I do not have much experience with VB. I have built a VB app that can retrieve data from a table(FoxPro). The code is given below:
 Dim dBaseCommand As New System.Data.OleDb.OleDbCommand("SELECT * FROM inventory", con)
 Dim dBaseDataReader As System.Data.OleDb.OleDbDataReader = dBaseCommand.ExecuteReader(CommandBehavior.SequentialAccess)

But I need to run the following SQL instead of SELECT * FROM inventory
SELECT itemnumber, mfgr, SUM(qty) AS cqty, unitcost, description
FROM inventory
GROUP BY itemnumber

I replaced the SQL and it does not work. How can I implement that SQL or GROUP BY statement into my VB code?
Update:
The SQL was a sample sql from MySQL. But I have updated the SQL that I am now actually using in my VB app. It does not show any error or does not close the app itself and it does not generate the file which is supposed to be produced by this app. If I use the sql from first sample code, it generates the file nicely from that table.
I went to database explorer(data sources) to run this query too. The following issues came up. Any ideas? not supported by Foxpro or any other workarounds?
Executing SQL: "GROUP BY clause is missing or invalid"
Verify SQL syntax: This command is not supported by this provider
Does this have something to do with this link where group by is not there?
If I use ODBC data provider, will it support the SQL?
Update 2:
It looks like ODBC driver supports GROUP BY. But Microsoft recommends to use OLEDB data provider instead of ODBC which does not support GROUP BY. In Visual basic data connections, I dont see ODBC as available data provider. It has only SQL server data provider and OLEDB data provider. Is there any way so that I can use the ODBC data provider and then use the GROUP BY statement?
*My reputation did not allow me including more references for citing the last information.
Comment: How about a little more detail. How did it "not work"? No results? An Exception? A number you weren't expecting?
Comment: Doesn't work? what's the error?
Comment: Thanks for looking into this. Please see my updated question.
Answer: I had to change the SQL to the following code and it worked:
SELECT     itemnumber, SUM(qty) AS qty, description
FROM         inventory
GROUP BY itemnumber, description

From VFP 8, SELECT with GROUP BY clause can select only columns which are associated with either GROUP BY or fields with Aggregate functions. If we need to use GROUP BY clause, we need to be careful with those conditions. So if the "description" from GROUP BY clause is removed, then the SQL does not work. Similarly, if SUM function is removed from qty column, the SQL wont work.
These conditions explain why "GROUP BY clause is missing or invalid" popped up. The good thing is that we can verify the queries on Visual studio before embedding into application.
Answer: Remove the single quotes from around Inventory, to make the statement:
 SELECT partnumber, SUM(quantity) FROM inventory GROUP BY partnumber

Inventory is a SQL object, not a text literal.
Comment: @Basic: I believe the ANSI standard is double quotes like "inventory"; however they are only required when the table- or field-name is a keyword in the language.
Comment: They're backticks not single quotes - which are [used in MySQL](http://stackoverflow.com/a/9719904/156755) to indicate field and table names much like `[]` in T-SQL. I have no idea what FoxPro uses.
Comment: Thanks for looking into my question. Please see my updated question.


Change stepper's line color flutter

Question: I want to change color of line in stepper, Look at the below picture

my try here :
Theme(
        data: ThemeData(canvasColor: whiteColor),
        child: Stepper(
          type: StepperType.horizontal,
          steps: getSteps(),
          currentStep: currentStep,
          elevation: 2,
        ),
      ),

Please help to continue my code.
Answer: Let me be short and clear.
TO CHANGE STEPPER LINE COLOR
Unfortunately, the Flutter code for the Stepper does not support the change of the Stepper line color (_buildLine) and more.
So I created a custom stepper called CusStepper that uses CusStep
NOTE: This CusStepper has the same properties and behaves like the normal Stepper with the only difference of lineColor property.
Steps on how to use the CusStepper

Create a new .dart file to store the CusStepper code
Paste the code below for the CusStepper in the file.
Import it to the file you want to use it in.
Finally change the stepper line color with the lineColor params. on the CusStepper

CusStepper code to paste in the .dart file created in step 1
// THIS IS A CUSTOM STEPPER THAT ADDS LINE COLOR
import 'package:flutter/material.dart';

enum CusStepState {
  indexed,
  editing,
  complete,
  disabled,
  error,
}

enum CusStepperType {
  vertical,
  horizontal,
}

@immutable
class ControlsDetails {
  const ControlsDetails({
    required this.currentStep,
    required this.stepIndex,
    this.onStepCancel,
    this.onStepContinue,
  });
  final int currentStep;
  final int stepIndex;
  final VoidCallback? onStepContinue;
  final VoidCallback? onStepCancel;
  bool get isActive => currentStep == stepIndex;
}

typedef ControlsWidgetBuilder = Widget Function(
    BuildContext context, ControlsDetails details);

const TextStyle _kStepStyle = TextStyle(
  fontSize: 12.0,
  color: Colors.white,
);
const Color _kErrorLight = Colors.red;
final Color _kErrorDark = Colors.red.shade400;
const Color _kCircleActiveLight = Colors.white;
const Color _kCircleActiveDark = Colors.black87;
const Color _kDisabledLight = Colors.black38;
const Color _kDisabledDark = Colors.white38;
const double _kStepSize = 24.0;
const double _kTriangleHeight = _kStepSize * 0.866025;

@immutable
class CusStep {
  const CusStep({
    required this.title,
    this.subtitle,
    required this.content,
    this.state = CusStepState.indexed,
    this.isActive = false,
    this.label,
  });

  final Widget title;

  final Widget? subtitle;

  final Widget content;

  final CusStepState state;

  final bool isActive;

  final Widget? label;
}

class CusStepper extends StatefulWidget {
  const CusStepper({
    super.key,
    required this.steps,
    this.physics,
    this.type = CusStepperType.vertical,
    this.currentStep = 0,
    this.onStepTapped,
    this.onStepContinue,
    this.onStepCancel,
    this.controlsBuilder,
    this.elevation,
    this.margin,
    this.lineColor = Colors.grey,
  })  : assert(0 <= currentStep && currentStep < steps.length);

  final List<CusStep> steps;

  final ScrollPhysics? physics;

  final CusStepperType type;

  final int currentStep;

  final ValueChanged<int>? onStepTapped;

  final VoidCallback? onStepContinue;

  final VoidCallback? onStepCancel;

  final ControlsWidgetBuilder? controlsBuilder;

  final double? elevation;

  final EdgeInsetsGeometry? margin;

  final Color lineColor;

  @override
  State<CusStepper> createState() => _CusStepperState();
}

class _CusStepperState extends State<CusStepper> with TickerProviderStateMixin {
  late List<GlobalKey> _keys;
  final Map<int, CusStepState> _oldStates = <int, CusStepState>{};

  @override
  void initState() {
    super.initState();
    _keys = List<GlobalKey>.generate(
      widget.steps.length,
      (int i) => GlobalKey(),
    );

    for (int i = 0; i < widget.steps.length; i += 1) {
      _oldStates[i] = widget.steps[i].state;
    }
  }

  @override
  void didUpdateWidget(CusStepper oldWidget) {
    super.didUpdateWidget(oldWidget);
    assert(widget.steps.length == oldWidget.steps.length);

    for (int i = 0; i < oldWidget.steps.length; i += 1) {
      _oldStates[i] = oldWidget.steps[i].state;
    }
  }

  bool _isFirst(int index) {
    return index == 0;
  }

  bool _isLast(int index) {
    return widget.steps.length - 1 == index;
  }

  bool _isCurrent(int index) {
    return widget.currentStep == index;
  }

  bool _isDark() {
    return Theme.of(context).brightness == Brightness.dark;
  }

  bool _isLabel() {
    for (final CusStep step in widget.steps) {
      if (step.label != null) {
        return true;
      }
    }
    return false;
  }

  Widget _buildLine(bool visible) {
    return Container(
      width: visible ? 1.0 : 0.0,
      height: 16.0,
      color: widget.lineColor,
    );
  }

  Widget _buildCircleChild(int index, bool oldState) {
    final CusStepState state =
        oldState ? _oldStates[index]! : widget.steps[index].state;
    final bool isDarkActive = _isDark() && widget.steps[index].isActive;
    switch (state) {
      case CusStepState.indexed:
      case CusStepState.disabled:
        return Text(
          '${index + 1}',
          style: isDarkActive
              ? _kStepStyle.copyWith(color: Colors.black87)
              : _kStepStyle,
        );
      case CusStepState.editing:
        return Icon(
          Icons.edit,
          color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
          size: 18.0,
        );
      case CusStepState.complete:
        return Icon(
          Icons.check,
          color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
          size: 18.0,
        );
      case CusStepState.error:
        return const Text('!', style: _kStepStyle);
    }
  }

  Color _circleColor(int index) {
    final ColorScheme colorScheme = Theme.of(context).colorScheme;
    if (!_isDark()) {
      return widget.steps[index].isActive
          ? colorScheme.primary
          : colorScheme.onSurface.withOpacity(0.38);
    } else {
      return widget.steps[index].isActive
          ? colorScheme.secondary
          : colorScheme.background;
    }
  }

  Widget _buildCircle(int index, bool oldState) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      width: _kStepSize,
      height: _kStepSize,
      child: AnimatedContainer(
        curve: Curves.fastOutSlowIn,
        duration: kThemeAnimationDuration,
        decoration: BoxDecoration(
          color: _circleColor(index),
          shape: BoxShape.circle,
        ),
        child: Center(
          child: _buildCircleChild(
              index, oldState && widget.steps[index].state == CusStepState.error),
        ),
      ),
    );
  }

  Widget _buildTriangle(int index, bool oldState) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 8.0),
      width: _kStepSize,
      height: _kStepSize,
      child: Center(
        child: SizedBox(
          width: _kStepSize,
          height:
              _kTriangleHeight, // Height of 24dp-long-sided equilateral triangle.
          child: CustomPaint(
            painter: _TrianglePainter(
              color: _isDark() ? _kErrorDark : _kErrorLight,
            ),
            child: Align(
              alignment: const Alignment(
                  0.0, 0.8), // 0.8 looks better than the geometrical 0.33.
              child: _buildCircleChild(index,
                  oldState && widget.steps[index].state != CusStepState.error),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildIcon(int index) {
    if (widget.steps[index].state != _oldStates[index]) {
      return AnimatedCrossFade(
        firstChild: _buildCircle(index, true),
        secondChild: _buildTriangle(index, true),
        firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
        secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
        sizeCurve: Curves.fastOutSlowIn,
        crossFadeState: widget.steps[index].state == CusStepState.error
            ? CrossFadeState.showSecond
            : CrossFadeState.showFirst,
        duration: kThemeAnimationDuration,
      );
    } else {
      if (widget.steps[index].state != CusStepState.error) {
        return _buildCircle(index, false);
      } else {
        return _buildTriangle(index, false);
      }
    }
  }

  Widget _buildVerticalControls(int stepIndex) {
    if (widget.controlsBuilder != null) {
      return widget.controlsBuilder!(
        context,
        ControlsDetails(
          currentStep: widget.currentStep,
          onStepContinue: widget.onStepContinue,
          onStepCancel: widget.onStepCancel,
          stepIndex: stepIndex,
        ),
      );
    }

    final Color cancelColor;
    switch (Theme.of(context).brightness) {
      case Brightness.light:
        cancelColor = Colors.black54;
        break;
      case Brightness.dark:
        cancelColor = Colors.white70;
        break;
    }

    final ThemeData themeData = Theme.of(context);
    final ColorScheme colorScheme = themeData.colorScheme;
    final MaterialLocalizations localizations =
        MaterialLocalizations.of(context);

    const OutlinedBorder buttonShape = RoundedRectangleBorder(
        borderRadius: BorderRadius.all(Radius.circular(2)));
    const EdgeInsets buttonPadding = EdgeInsets.symmetric(horizontal: 16.0);

    return Container(
      margin: const EdgeInsets.only(top: 16.0),
      child: ConstrainedBox(
        constraints: const BoxConstraints.tightFor(height: 48.0),
        child: Row(
          children: <Widget>[
            TextButton(
              onPressed: widget.onStepContinue,
              style: ButtonStyle(
                foregroundColor: MaterialStateProperty.resolveWith<Color?>(
                    (Set<MaterialState> states) {
                  return states.contains(MaterialState.disabled)
                      ? null
                      : (_isDark()
                          ? colorScheme.onSurface
                          : colorScheme.onPrimary);
                }),
                backgroundColor: MaterialStateProperty.resolveWith<Color?>(
                    (Set<MaterialState> states) {
                  return _isDark() || states.contains(MaterialState.disabled)
                      ? null
                      : colorScheme.primary;
                }),
                padding: const MaterialStatePropertyAll<EdgeInsetsGeometry>(
                    buttonPadding),
                shape:
                    const MaterialStatePropertyAll<OutlinedBorder>(buttonShape),
              ),
              child: Text(themeData.useMaterial3
                  ? localizations.continueButtonLabel
                  : localizations.continueButtonLabel.toUpperCase()),
            ),
            Container(
              margin: const EdgeInsetsDirectional.only(start: 8.0),
              child: TextButton(
                onPressed: widget.onStepCancel,
                style: TextButton.styleFrom(
                  foregroundColor: cancelColor,
                  padding: buttonPadding,
                  shape: buttonShape,
                ),
                child: Text(themeData.useMaterial3
                    ? localizations.cancelButtonLabel
                    : localizations.cancelButtonLabel.toUpperCase()),
              ),
            ),
          ],
        ),
      ),
    );
  }

  TextStyle _titleStyle(int index) {
    final ThemeData themeData = Theme.of(context);
    final TextTheme textTheme = themeData.textTheme;

    switch (widget.steps[index].state) {
      case CusStepState.indexed:
      case CusStepState.editing:
      case CusStepState.complete:
        return textTheme.bodyLarge!;
      case CusStepState.disabled:
        return textTheme.bodyLarge!.copyWith(
          color: _isDark() ? _kDisabledDark : _kDisabledLight,
        );
      case CusStepState.error:
        return textTheme.bodyLarge!.copyWith(
          color: _isDark() ? _kErrorDark : _kErrorLight,
        );
    }
  }

  TextStyle _subtitleStyle(int index) {
    final ThemeData themeData = Theme.of(context);
    final TextTheme textTheme = themeData.textTheme;

    switch (widget.steps[index].state) {
      case CusStepState.indexed:
      case CusStepState.editing:
      case CusStepState.complete:
        return textTheme.bodySmall!;
      case CusStepState.disabled:
        return textTheme.bodySmall!.copyWith(
          color: _isDark() ? _kDisabledDark : _kDisabledLight,
        );
      case CusStepState.error:
        return textTheme.bodySmall!.copyWith(
          color: _isDark() ? _kErrorDark : _kErrorLight,
        );
    }
  }

  TextStyle _labelStyle(int index) {
    final ThemeData themeData = Theme.of(context);
    final TextTheme textTheme = themeData.textTheme;

    switch (widget.steps[index].state) {
      case CusStepState.indexed:
      case CusStepState.editing:
      case CusStepState.complete:
        return textTheme.bodyLarge!;
      case CusStepState.disabled:
        return textTheme.bodyLarge!.copyWith(
          color: _isDark() ? _kDisabledDark : _kDisabledLight,
        );
      case CusStepState.error:
        return textTheme.bodyLarge!.copyWith(
          color: _isDark() ? _kErrorDark : _kErrorLight,
        );
    }
  }

  Widget _buildHeaderText(int index) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        AnimatedDefaultTextStyle(
          style: _titleStyle(index),
          duration: kThemeAnimationDuration,
          curve: Curves.fastOutSlowIn,
          child: widget.steps[index].title,
        ),
        if (widget.steps[index].subtitle != null)
          Container(
            margin: const EdgeInsets.only(top: 2.0),
            child: AnimatedDefaultTextStyle(
              style: _subtitleStyle(index),
              duration: kThemeAnimationDuration,
              curve: Curves.fastOutSlowIn,
              child: widget.steps[index].subtitle!,
            ),
          ),
      ],
    );
  }

  Widget _buildLabelText(int index) {
    if (widget.steps[index].label != null) {
      return AnimatedDefaultTextStyle(
        style: _labelStyle(index),
        duration: kThemeAnimationDuration,
        child: widget.steps[index].label!,
      );
    }
    return const SizedBox.shrink();
  }

  Widget _buildVerticalHeader(int index) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 24.0),
      child: Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              _buildLine(!_isFirst(index)),
              _buildIcon(index),
              _buildLine(!_isLast(index)),
            ],
          ),
          Expanded(
            child: Container(
              margin: const EdgeInsetsDirectional.only(start: 12.0),
              child: _buildHeaderText(index),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVerticalBody(int index) {
    return Stack(
      children: <Widget>[
        PositionedDirectional(
          start: 24.0,
          top: 0.0,
          bottom: 0.0,
          child: SizedBox(
            width: 24.0,
            child: Center(
              child: SizedBox(
                width: _isLast(index) ? 0.0 : 1.0,
                child: Container(
                  color: widget.lineColor,
                ),
              ),
            ),
          ),
        ),
        AnimatedCrossFade(
          firstChild: Container(height: 0.0),
          secondChild: Container(
            margin: widget.margin ??
                const EdgeInsetsDirectional.only(
                  start: 60.0,
                  end: 24.0,
                  bottom: 24.0,
                ),
            child: Column(
              children: <Widget>[
                widget.steps[index].content,
                _buildVerticalControls(index),
              ],
            ),
          ),
          firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
          secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
          sizeCurve: Curves.fastOutSlowIn,
          crossFadeState: _isCurrent(index)
              ? CrossFadeState.showSecond
              : CrossFadeState.showFirst,
          duration: kThemeAnimationDuration,
        ),
      ],
    );
  }

  Widget _buildVertical() {
    return ListView(
      shrinkWrap: true,
      physics: widget.physics,
      children: <Widget>[
        for (int i = 0; i < widget.steps.length; i += 1)
          Column(
            key: _keys[i],
            children: <Widget>[
              InkWell(
                onTap: widget.steps[i].state != CusStepState.disabled
                    ? () {
                        // In the vertical case we need to scroll to the newly tapped
                        // step.
                        Scrollable.ensureVisible(
                          _keys[i].currentContext!,
                          curve: Curves.fastOutSlowIn,
                          duration: kThemeAnimationDuration,
                        );

                        widget.onStepTapped?.call(i);
                      }
                    : null,
                canRequestFocus: widget.steps[i].state != CusStepState.disabled,
                child: _buildVerticalHeader(i),
              ),
              _buildVerticalBody(i),
            ],
          ),
      ],
    );
  }

  Widget _buildHorizontal() {
    final List<Widget> children = <Widget>[
      for (int i = 0; i < widget.steps.length; i += 1) ...<Widget>[
        InkResponse(
          onTap: widget.steps[i].state != CusStepState.disabled
              ? () {
                  widget.onStepTapped?.call(i);
                }
              : null,
          canRequestFocus: widget.steps[i].state != CusStepState.disabled,
          child: Row(
            children: <Widget>[
              SizedBox(
                height: _isLabel() ? 104.0 : 72.0,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    if (widget.steps[i].label != null)
                      const SizedBox(
                        height: 24.0,
                      ),
                    Center(child: _buildIcon(i)),
                    if (widget.steps[i].label != null)
                      SizedBox(
                        height: 24.0,
                        child: _buildLabelText(i),
                      ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsetsDirectional.only(start: 12.0),
                child: _buildHeaderText(i),
              ),
            ],
          ),
        ),
        if (!_isLast(i))
          Expanded(
            child: Container(
              margin: const EdgeInsets.symmetric(horizontal: 8.0),
              height: 1.0,
              color: widget.lineColor,
            ),
          ),
      ],
    ];

    final List<Widget> stepPanels = <Widget>[];
    for (int i = 0; i < widget.steps.length; i += 1) {
      stepPanels.add(
        Visibility(
          maintainState: true,
          visible: i == widget.currentStep,
          child: widget.steps[i].content,
        ),
      );
    }

    return Column(
      children: <Widget>[
        Material(
          elevation: widget.elevation ?? 2,
          child: Container(
            margin: const EdgeInsets.symmetric(horizontal: 24.0),
            child: Row(
              children: children,
            ),
          ),
        ),
        Expanded(
          child: ListView(
            physics: widget.physics,
            padding: const EdgeInsets.all(24.0),
            children: <Widget>[
              AnimatedSize(
                curve: Curves.fastOutSlowIn,
                duration: kThemeAnimationDuration,
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: stepPanels),
              ),
              _buildVerticalControls(widget.currentStep),
            ],
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMaterial(context));
    assert(debugCheckHasMaterialLocalizations(context));
    assert(() {
      if (context.findAncestorWidgetOfExactType<Stepper>() != null) {
        throw FlutterError(
          'Steppers must not be nested.\n'
          'The material specification advises that one should avoid embedding '
          'steppers within steppers. '
          'https://material.io/archive/guidelines/components/steppers.html#steppers-usage',
        );
      }
      return true;
    }());
    switch (widget.type) {
      case CusStepperType.vertical:
        return _buildVertical();
      case CusStepperType.horizontal:
        return _buildHorizontal();
    }
  }
}

class _TrianglePainter extends CustomPainter {
  _TrianglePainter({
    required this.color,
  });

  final Color color;

  @override
  bool hitTest(Offset point) => true;
  @override
  bool shouldRepaint(_TrianglePainter oldPainter) {
    return oldPainter.color != color;
  }

  @override
  void paint(Canvas canvas, Size size) {
    final double base = size.width;
    final double halfBase = size.width / 2.0;
    final double height = size.height;
    final List<Offset> points = <Offset>[
      Offset(0.0, height),
      Offset(base, height),
      Offset(halfBase, 0.0),
    ];

    canvas.drawPath(
      Path()..addPolygon(points, true),
      Paint()..color = color,
    );
  }
}

EXAMPLE CODEBASE ON HOW TO USE THE CusStepper
import 'package:flutter/material.dart';
import 'package:tester/stepper/stepper.dart'; // this is the file path of where you store your `cusStepper`

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const App());
}

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Tester',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  int _index = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CusStepper(
          lineColor: Colors.red, // new line add for the color change
          currentStep: _index,
          onStepCancel: () {
            if (_index > 0) {
              setState(() {
                _index -= 1;
              });
            }
          },
          onStepContinue: () {
            if (_index <= 0) {
              setState(() {
                _index += 1;
              });
            }
          },
          onStepTapped: (int index) {
            setState(() {
              _index = index;
            });
          },
          steps: <CusStep>[
            CusStep(
              title: const Text('Step 1 title'),
              content: Container(
                  alignment: Alignment.centerLeft,
                  child: const Text('Content for Step 1')),
            ),
            const CusStep(
              title: Text('Step 2 title'),
              content: Text('Content for Step 2'),
            ),
          ],
        ),
      ),
    );
  }
}

OUTPUT

Leave a comment below if you have any questions or help on this.
Bye!
Comment: here Question is Change Stapper between line color change.
grey to another color.
Comment: @JEMISHVASOYA I just updated the answer. Feel free to review it! Thanks
Comment: Thanks for the explanation. But I only want to Change the stepper line color flutter. Look at the picture of q. please
Comment: I just updated the answer. The short answer is, **"not possible at the moment"**. Check my edited answer for more info on why.
Comment: it's not working please check and run this because you post an old code that not working now.
Comment: @HoRiz Check out my updated answer. I just made a custom `Stepper` based on your requirements.
Comment: @JEMISHVASOYA check out the custom `Stepper` and let me know if anything is missing. Thanks
Answer: The Flutter Default stepper Line has Static color use so can't change this.
chack below Image.

Here https://fluttergems.dev/stepper mention many stepper package used as you want.
Comment: Got it.  I have to use another package.
Comment: Actually, I took a look at the source code, and I don't think this is the correct line.
Comment: please see the updated answer. there is some flutter code that uses static color not use theme color not we can change this.

Change stepper's line color flutter


Change the background image of an element

Question: So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.
The HTML  looks like

    Hover over an image below to display here.

That's just the div element I want to change, alongside one of the images.
So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.
My current code is:
function upDate(previewPic){
    var div_element = document.getElementById('image').innerHTML;
    var picurl = "url(previewPic.getAttribute('src'))"
    div_element.style.backgroundImage = "url(picurl)";
 }

And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console.
If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?
Comment: why are you getting innerHTML?? obviously div_element has not style property
Answer: There are multiple issues with your code.

Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an  tag.
Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.

Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.
Change your code to:
function upDate(previewPic){
    var div_element = document.getElementById('image');
    var picurl = "url(" + previewPic.getAttribute('src') +")"
    div_element.style.backgroundImage = picurl;
}

This should work.
Answer: If I understand on some image hover you want to change div background?
I would do it with jquery:
$('img').hover(function(){

$('div').css(''background-image:'url("image_link")');

});

Comment: There is no jquery tag, and your code won't work because you're messing up the quotes. Not to mention, your answer is only a partial, if the OP doesn't know jquery, he probably doesn't know how to implement your solution into his code.


Escrever cada passo do cálculo de um fatorial

Question: Tenho um pedaço de código que calcula o fatorial de um número em JavaScript, porém queria que ele retornasse os passos de cada cálculo, ex:

3! = 1x2x3 = 6

Segue o código que fiz. Tentei "printar" decrementando a variável, mas não tenho a certeza do que estou fazendo.

var fatorial=1;
var num=parseInt(prompt("Digite um número: "));

for(var x=1; x<=num; x++)
{
  fatorial=fatorial*x;
}

document.write(num+"! = "+num+"x"+(num--)+"="+fatorial);
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: Para que serve um laço? Para repetir passos, certo?
É dentro dele que você calcula cada passo do fatorial, certo?
Depois que termina os passos você está mandando imprimir o resultado final, mas você quer imprimir cada passo!
Deu para entender onde tem que colocar a impressão? Se não, comece ler esta resposta de novo desde o começo, agora com mais atenção.
Obviamente que deve formatar como deseja, escolher o que deverá ser impresso. Pode ser que seja útil ter uma impressão inicial antes de começar os passos. E ainda precisará da impressão do resultado final. Faça testes.
Eu poderia ter dado a resposta pronta, mas acho que assim vai aprender melhor.
Coloquei no GitHub para referência futura.
Answer: Para retornar os passos de cada calculo, concateno em uma string a cada calculo realizado fincando dessa forma:

var fatorial=1;
var explicaFator = '';
var num=parseInt(prompt("Digite um número: "));
for(var x=1; x<=num; x++)
{
    fatorial=fatorial*x;
    if(explicaFator != ''){
      explicaFator += 'x';
    }
    explicaFator += x;

}
document.write(num+"! = "+explicaFator+" = "+fatorial);


Stop from going to node on content creation

Question: I would like for when I add of piece of content for it to stay on the admin back-end.. right now it forwards the user to the created node with a message saying it's been created, but the rest of the admin interface disappears so it's difficult to get back to adding more, and certain content types look very strange in that view.
I looked at actions/triggers, but I don't see a way to distinguish between content types, and I wouldn't want comments and user posts to forward to the admin interface so I don't see that as a solution.
Answer: The Add another module might come in handy for that:

Add another is designed to save time during repetitive content creation. It allows the content creator to add another node of the same type much faster.

It provides a 'Save and add another' button in addition to the standard 'Save' button on node forms.
Answer: The programming answer:
You can use hook_form_alter to alter redirect behavior.
Like so: (from linked thread)
<?php
function jeff_form_alter(&$form, &$form_state, $form_id)
{
     $form['#submit'][] = 'jeff_form_submit';
}

function jeff_form_submit($form, &$form_state)
{
     $form_state['redirect'] = 'process-your-donation';
}
?>

The contrib module answer:
Clive's recommendation of Add Another (compatible with D6 and D7) is a good one if you simply want to add another of the same type of node upon content submission.
Comment: I see I got a downvote. Is there an error in my answer?
Comment: T'wasn't me but there are a lot of errors in that code (function sig is wrong, using `$form['#id']` instead of provided `$form_id`, node form id has obliques instead of underscores, using `$form['#redirect']` instead of providing a submit handler and using `$form_state['redirect']`, etc.)
Comment: So, the problem is a best-practice violation, then? I'm not trying to argue, genuinely want to fix it. Is there documentation on how best to accomplish this in the code?
Comment: I think I've found a better example that's implemented more correctly and edited my answer. Is that what you had in mind?
Comment: It wasn't just best-practice violations, the function signature was incorrect which meant the whole thing would fall over...the new example looks good, except `$form_state` should be passed by reference (`&$form_state`). It doesn't matter in the example above but it's a good practice to get into :)
Comment: I fixed the problem, so can the downvoter please re-evaluate their downvote, and leave corrections instead of downvoting in the future?
Answer: A possible solution to answer this question is to enable the Rules module, and create a custom rule that looks like so:
{ "rules_show_new_article_link" : {
    "LABEL" : "Show New Article link",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Click \u003Ca href=\u0022[site:url]node\/add\/article\u0022\u003Ethis link\u003C\/a\u003E to add another article ..." } }
    ]
  }
}

Some details about this rule:

Rules Events: After saving new content.
Rules Condition: Content is of type article.
Rules Action: Show a message on the site, whereas the actual message content that will be shown is "Click this link to add another article ..." and with 'this link' being rendered as an hyperlink to relative path node/add/article.

If you have the Rules UI enabled, you can just import the above rule in your own site. Adapt content type article to custom_content (or whatever fits your needs).
With that, each time you edit or create a node of article, you'll get such  message (with appropriate link) in the Drupal message area. Obviously, you could add any applicable rules logic to further improve this prototype (e.g. to only show this for selected user roles). And should you want to do so, you could also add an extra Rules Action to perform a redirect to relative path node/add/article.
PS: this rule is my favorite sample to get started with the Rules module.


Por que uma expressão com resto e multiplicação está dando como resultado errado?

Question: Por que esse código está dando como resultado -2 e não 7?
<code> #include <stdio.h>

 main()
 {
   printf("%i\n", 105 % 3*4 - 3*4 % (101 / 10));
   system("pause");
 }
</code>
Answer: Eu fiz assim e deu 7:
<code>#include <stdio.h>

int main() {
    printf("%i\n", 105 % (3 * 4) - (3 * 4) % (101 / 10));
}
</code>
Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Provavelmente interpretou a expressão sem considerar a precedência e associatividade dos operadores. O operador de resto tem a mesma precedência da multiplicação e associatividade pela esquerda, então em uma expressão com os dois operadores o que aparecer primeiro será executado. Para aumentar a precedência de um operador deve usar o operador de parênteses que possui prioridade bem alta.
O segundo par de parênteses não é necessário, coloquei só para ajudar enxergar melhor a separação. O último par, que já existia, resolve o problema de precedência que poderia haver.


Change Pager-ItemsPerPage over URL argument

Question: I use Views to get Nodes in JSON format via REST service. I can switch the pages with;
http://myside/?q=my/path&page=1
but I want to change the limit of one page like;
http://myside/?q=my/path&limit=100.
Has anybody a good solution or one alternative.
Answer: there is default option in views pager as "EXPOSED OPTIONS" while adding pager to views.
You can add range output.

So you can show per page option. set results using URL argument like http://example.com/path?limit=100
Comment: clever answer :)


Prevent children divs from moving while div toggle

Question: I'm new and have I think very simple problem to solve.
I have 4 buttons to show/hide each panel. What should I do to prevent child divs from moving to te left while hiding some div?
I prefer them to stay at the initial position.
This is my code:
HTML:
    <button class="panel-button" data-panel="panel1">1</button>
    <button class="panel-button" data-panel="panel2">2</button>
    <button class="panel-button" data-panel="panel3">3</button>
    <button class="panel-button" data-panel="panel4">4</button>

1

2

3

4

JS:
        $(function() {
            $('.panel-button').on('click',function(){
                var panelId = $(this).data('panel');// attr('data-panel')
                $('#'+panelId).toggle();
            });
        });

CSS:
.wrapper {
    overflow: hidden;
    width: 420px;
}

.wrapper > div {
    width: 100px;
    height: 100px;
    background: green;
    float: left;
    margin-left: 5px;
    margin-top: 10px
}

Answer: Apply css rule opacity = 0; to the div, instead of hiding it.
Like this:
$('.panel-button').on('click',function(){
    var pnl = $('#' + $(this).data('panel'));
    pnl.css('opacity', pnl.css('opacity') == '0' ? '1' : '0');
});

Solution for clickability issue:
$('.panel-button').on('click',function(){
    var pnl = $('#' + $(this).data('panel'));
    if(pnl.is(':visible'))
        $('

').appendTo(pnl).width(pnl.width());
    else
        pnl.next().remove();
    pnl.toggle();
});

Comment: While this is a valid solution, their might be problems when there are  clickable items inside. The user would still be able to clik them.
Comment: No need for hacky javascript, use CSS `visiblity` instead combined with jquery's toggleClass() (see the other answer).
Answer: But still you can use another approach
You can use the visibility property in CSS to achieve this as shown in the below Fiddle link : link
JS Snippet:
$(function() {

  $('.panel-button').on('click',function(){
    var panelId = $(this).data('panel');// attr('data-panel')
    console.log($('#'+panelId).css('visibility'));
    if($('#'+panelId).css('visibility') === 'hidden') {
      $('#'+panelId).css('visibility','visible');
    }
    else {
      $('#'+panelId).css('visibility','hidden');
    }
  });
});

Answer: The CSS visibility is designed to keep the space a DOM object occupies, but not actually rendering it. Opacity changes its appearance, but not its behavior (eg. still clickable).
So instead of .toggle(), combine visibility with jQuery's .toggleClass():
jsFiddle solution
$(function() {
        $('.panel-button').on('click',function(){
            var panelId = $(this).data('panel');// attr('data-panel')
            $('#'+panelId).toggleClass('hideMe');
        });
    });

Comment: I took into consideration also toggleClass solution, but for me it doesn't work.
.hidden {
 opacity:0;
    var panelId = $('#' + $(this).data('panel'));
    panelId.toggleClass('hidden');
}
Comment: @kuba0506 The jsFiddle example clearly demonstrates it works perfectly


Como criar um ID para ser usado em outras classes

Question: Meu aplicativo vai fazer um get na primeira tela do ID do usuário, como faço para usá-lo em outras activities sem ser via intent ?
Answer: Você pode armazenar em um Shared Preferences, embora eu não tenha certeza que é a melhor opção:
// Inicializar
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref_key", Context.MODE_PRIVATE);

// Save Data
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("id", 1);
editor.commit();

//Pegar valor
int myIntValue = sharedPreferences.getInt("your_int_key", -1);

Answer: Cria uma classe pra setar e pegar o valor:
public class User extends Application {

private String Id;

public String getId()
{
    return Id;
}
public void setId(String Id)
{
    this.Id = Id;
}

}
E seta o id quando vc pegar ele pela primeira vez.
                User usuario = ((User)getApplicationContext());
            usuario.setId(id);//variável com o id

Pra recuperar(no exemplo, exibe a variável setada em um snackbar):
        User usuario = ((User)getApplicationContext());
        Snackbar snackbar = Snackbar
                .make(principal, "Bem Vindo, " + usuario.getId(), Snackbar.LENGTH_LONG);
        snackbar.show();


Biharmonic version of Poisson Integral

Question: Background
The Poisson Integral
$$ \tilde h(r e^{i \theta}) = \frac{1}{2 \pi}\int_{-\pi}^\pi h(e^{i \phi}) P_r(\theta - \phi) d\phi$$
takes an arbitrary continuous complex-valued function $h(e^{i \theta})$ defined on the unit circle and extends it to a function $\tilde h(z)$ defined inside the unit disk such that $\tilde h(z)$ is harmonic ($\Delta \tilde h(z) = 0$) and has boundary values $h(z)$ on the unit circle.
$P_r(\theta)$ is the so-called Poisson Kernel and, among other representations,
$$P_r(\theta) = \Re \left( \frac{1 + r e^{i \theta}} {1 - r e^{i \theta}} \right) , \ \ \ \ r e^{i \theta} \in \mathbb{D}.$$
Question
Is there a different kernel function I could use which would make $\tilde h(z)$ biharmonic instead of just harmonic inside the unit disk?  That is, I'd like to find something to replace $P_r(\theta)$ with so that $\Delta^2 \tilde h(z) = 0$.
Comment: I suggest to look at this paper https://www.researchgate.net/publication/228519408_A_new_biharmonic_kernel_for_the_upper_half_plane
Answer: After a tip from Conrad I was able to find a different paper (Tangential limit values of a biharmonic poisson integral in a disk) which gives the "Biharmonic Poisson Kernel" $\tilde P$ in terms of the regular Poisson Kernel:
$$ \tilde P_r(\theta) = \frac{1 - r^2}{2} (P_r(\theta) + P_r^2(\theta)) $$

Biharmonic version of Poisson Integral


Can eigenvectors of a symmetric circulant matrix be real?

Question: Since eigenvectors of a symmetric circulant matrix are related to the Fourier basis, I expect that they are complex.
But I do not find such statement in mathematical books, and so I think my supposition is wrong.
Can you help me to understand the correct reasoning?
Comment: This is true in the generic case, but when you have a matrix with repeated eigenvalues then one could have a linear combination of eigenvectors which is real-valued.  Since the eigenvalues of a symmetric matrix are real, this necessarily happens — I imagine they combine in conjugate pairs.
Comment: @Alessandro Whenever you have an eigenspace of dimension $\ge 2$ there are many ways to choose a basis of eigenvectors.  Just because the Fourier modes work for all circulant matrices doesn't mean that some circulants can't have real eigenvectors.
Comment: Yes, you can write the eigenvectors as
$(1, \cos (2\pi j/n), \cos (2\pi 2j/n), \dots, \cos (2\pi (n-1)j/n))$ and $(0, \sin (2\pi j/n), \sin (2\pi 2j/n), \dots, \sin (2\pi (n-1)j/n))$. It's quite the same as expressing $2\cos(\theta) = e^{i \theta} + e^{-i \theta}$.
Comment: The identiy matrix is circulant symmetric.
Comment: They must be real.
Comment: Thanks. But it does not match to the fact that eigenvectors of a symmetric circulant matrix are related to the Fourier basis.
Comment: @ErickWong Thanks for your explanation. Is there a link between real eigenvectors and the sine and cosine coefficients of the Fourier representation?
Answer: First of all, the eigenvalues and thus eigenvectors of  whatever symmetric real matrix are real. That the matrix happens to be circulant does not change this. But let's go through it for circulant specifically:
The eigenvalues of a circulant matrix (with first row $(c_0, \dots, c_{n-1})$) are given by (see the Wikipedia page)
$$\lambda(w)=c_0 +c_1 w + c_2 w^2 + \dots +   c_{n-1} w^{n-1}$$
where $w$ is some $n$-th root of unity.
For the matrix to be symmetric one needs $c_{n-i} = c_i$.
One can then rewrite
$$c_i w^i  + c_{n-i} w^{n-i}= 2c_i \Re(w^i).$$
Thus for odd $n$ one gets:
$$c_0 +  2c_1 \Re w + 2c_2\Re w^2 +   \dots +   2c_{(n-1)/2} \Re(w^{(n-1)/2})$$
which is always real (assuming a real matrix of course).
And for even $n$ one gets
$$c_0 + c_{n/2}w^{n/2} + 2c_1 \Re w + 2c_2\Re w^2 +   \dots +   2c_{(n-1)/2} \Re(w^{(n-2)/2})$$
which is also always real as $w^{n/2}$ is $\pm 1$.
The eigenvectors then can also be chosen to be real.
Let me further add that while $(1, w , \dots, w^{n-1})$ is always an eigenvector for the eigenvector $\lambda(w)$, as explained on the site above. One has  $\lambda(w)= \lambda(w^{-1})$  so that one has the eigenvectors $(1, w , \dots, w^{n-1})$  and $(1, w^{-1} , \dots, w^{-(n-1)})$. The sum of the two, twice the real part, is then a real eigenvector (same for the imaginary part).
Comment: How does one arrive at the conclusion that $(1,\omega^{-1},\ldots,\omega^{-(n-1)})$ is also an eigenvector from $\lambda(\omega)=\lambda(\omega^{-1})$? And also later that $2Re[(1,\ldots,\omega^{n-1})+(1,\ldots,\omega^{-(n-1)})]$?


Returning All Values (Including Duplicates) in SQL

Question: I am unable to return all values, including duplicates, for the following query:
select all field1, count(field1)
from tablename
where
  field2 in (
    abc,
    abc,
    def,
    ghi,
    ghi
  )
group by field1

There are over 500 values for field2 (which are zip codes), and I want to return each field1 (area) which is assigned to each field2 (zip code). If I run the above query, three areas are returned (for zip codes abc, def, ghi) instead of five. Below is a smaller version of the table I'm using; the actual table has ~500 rows.
I've a list of hundreds of zip codes (field2), which have all been assigned areas (field1). If, for example, I enter 400 non-distinct zip codes (field2), I would like to receive their 400 corresponding areas (field1). As of now, I'm only receiving the areas which correspond with the distinct zip codes.
      field2      field1
1    66666     north
2    77777     south
3    88888     east
4    99999     west
I know there's a simple solution to this, but I'm stumped. I'm using MS SQL Server; unfortunately, I do not have permission to create tables within the database.
Comment: Your question is a bit vague. However, it is very likely that an example table and the corresponding output would illustrate your goal better than any explanation.
Comment: Your select is characters but you sample in numbers.  You have not even taken the effort to run a real query and show actual results. Down vote.
Comment: Thank you for your response. If I knew how to write a "real query," I would have done so. Also, I have to partially disguise the results due to confidentiality. You were not born knowing this language...please be kind to those who seek your knowledge.
Comment: You only have three unique values in the in.
Comment: If you have confidential data then load some nonconfidential data to reproduce the problem.  Post the actual query and the actual output.
Answer: You have two issues.
1 - You are using GROUP BY which by definition removes duplicate rows in the grouped field(s)
2 - You are using IN, which short circuits.  This means it ignores dupes and just returns a boolean.
You probably should try something like:
CREATE TABLE t_Field2 (field2 varchar(10))
INSERT INTO t_Field2
VALUES
('abc'....) <insert all your rows here>

SELECT Field1, COUNT(Field1)
FROM MyTable t
INNER JOIN t_Field2 t2
ON t2.field2 = t.field2
GROUP BY Field1

An INNER JOIN will definitely give you dupes in this scenario, which for some reason is what you want it sounds like.
The GROUP BY will still eliminate duplicate Field1 values though.
Answer: Isn't it just this?
SELECT DISTINCT field1, field2
  FROM tablename
 WHERE field2 IN ( abc, def, ghi )

Also, your original query has an IN predicate that lists "abc" and "ghi" twice each.  The repetition does nothing; field IN ( abc, abc ) is logically equivalent to (field = abc OR field = abc)
Comment: Hi. This query returned just three instances of each field2, as opposed to including the extra two duplicate instances. The original table has more than 500 field2 values, including duplicates. Thank you for the tip about in vs. =, though.
Comment: I don't understand what you're asking for, then. The query I showed you will give you all combinations of field1 and field2 values in your table, such that their field2 value is either abc, def or ghi. If you're seeing just one row for abc in the result set, and there is more than one row in your table with field2 = abc, it means then that both rows must have the same value for field1.
Answer: I'm as stumped as the others as to quite what you're trying to do, but on the assumption that you're trying to provide a list of all the values (including duplicates) and the number of times each occurrs, it can be done with
SELECT a.field1, b.CountField
FROM   tablename a
    INNER JOIN (SELECT Field1, COUNT(*) AS CountField FROM TableName GROUP BY Field1) b
        ON a.Field1=b.Field1

But I can't for the life of me understand why you'd want that data over just
SELECT Field1, COUNT(*) AS CountField FROM TableName GROUP BY Field1

So, if you can clarify what you're trying to achieve, perhaps we can help more?


Meta viewport scale not working - responsive

Question: I have inserted:
<code><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
</code>
into the header of my website, but it is not disabling the SCALE function on my macbook (haven't tested elsewhere yet) like it should be. I have tried the exact same code that is used in another theme I used before but it still doesn't work.
What could be the reason for this and how do I fix it?
Comment: I thought meta view-port was more for zoom features on mobile devices rather than scrolling up and down pages, is the theme you are looking at either positioning the `` absolutely or hiding the overflow to stop the scroll?
Comment: Sorry, I meant scale not scroll. I think you are right, I'm new to view-port so excuse me. I have checked on my iphone and it has disabled the zoom, which is good.

I guess there is a different setting to disable the zoom on all devices? (computer screens)
Comment: If the browser's User Agent chooses to ignore the meta tag, there ain't a simple solution. See [this answer on SO](http://stackoverflow.com/questions/1713771/how-to-detect-page-zoom-level-in-all-modern-browsers) for a relatively complete list of options, but I'd highly advise against attempting to force non-zoom across all browsers.
Answer: another option is to use responsivem.js  It would require you to specify everything in em, but you could write a script to replace all the px with em.  check it out.


Why are journald logfiles so huge?

Question: When I do a journalctl --disk-usage it says something about 300MB size of the journal files but when I look at the actual text with journalctl | wc -c it's something about 28MB. Well, journald has compression and even considering the metadata like timestamp, uid, message hash and such things it seems to me like a ridiculous waste of disk space.
Can someone tell me why the journal files are so big compared to the actual text inside?
Answer: There are two reasons. First, as @Mella mentioned, there is the difference between the current-log vs all-logs.
Second, as documented in man journalctl, there a number of output formats. You were measuring the size of the most-compact/least-detailed. To see maximal data in the systemd journal, use:
journactl --output=verbose

In my case, the compact journal output returns 32 Megs of data, while 128 MB are returned with --output=verbose and 152M are found with journalctl --disk-usage, covering both active and archived journals.
See man journald.conf to learn how to limit how much disk space journald uses if you are concerned.
Comment: imho this answer is useful, but yet kind of misleading. While  true, that there is the larger *verbose* output, this cannot explain even larger on disk files. I checked an see `journald` `.journal` files being 8MiB however giving only about 56kiB **verbose** output. Clearly there has to be another explanation to why `journald` is so wasteful with disk storage ( see also https://unix.stackexchange.com/q/462266/24394 )
Answer:
They are huge, because its kind of a bug:

As it is indicated upstream and hence known to the developers of journald, the used in the binary log format is not at all very great (yet?).

They are huge, because maybe the Compression is not activated

There also is a option in /etc/systemd/journald.conf named Compress=yes, which might not be active on your system, so as there being effectively no compression.

The issue of archived journals does not matter here.

While in principle true that journald distinguishes between active and archived journal logs, this is a misleading reply of the other answers, as in man journalctl it states unequivically:

Output is interleaved from all accessible journal files, whether they
  are rotated or currently being written, and regardless of whether they
  belong to the system itself or are accessible user journals.

The other answer are hence misleading here.

They disk usage of journalctl is huge (i.e greater than plain text files with comparable level of information - that is fields) because of some file allocation, fragmentation, anti-corruption measures.

"file fragmentation/allocation issues"
On my box, journalctl --version == "systemd 239[...]" the journal files that contain the data exists in filesizes being a multiples of 8MiB. As a consequence on my system journal file, will be 8MiB big even when only a fraction (as in one case 56kiB) of data is actually stored in it.
"anti corruption issue"
According to Poettering one of the developers of journald and systemd in a case that a journal is considered to have become corrupted by journald, it wont be "fixed" but instead left as is, to prevent further problems. (see https://bugs.freedesktop.org/show_bug.cgi?id=64116#c3)
This of course means that there is a good chance that uncompressed, almost empty journal binary log files sit arround in your var log, making it effectively much much huger than a sane plaintext alternative.
Answer: journalctl without parameters (whose output you're measuring with wc -c) is only displaying journal entries in the active journal (I'm not sure offhand what prompts a turnover). journalctl --disk-usage is displaying the space used by the archived journals as well as the active journal.

Why are journald logfiles so huge?


Solve $\int{\frac{x-1}{x\sqrt{3x^2-4}}}\;dx$

Question: In solving the definite integral $$\int{\frac{x-1}{x\sqrt{3x^2-4}}}\;dx$$I tried to do $$\int{\frac{x-1}{x\sqrt{3x^2-4}}}\;dx=\int{\frac{1}{\sqrt{3x^2-4}}}\;dx-\int{\frac{1}{x\sqrt{3x^2-4}}}\;dx\Longrightarrow$$ If $x=\frac{2}{\sqrt{3}}\sec(u)\Longrightarrow dx=\frac2{\sqrt3}\tan(u)\sec(u)\;du$, then
$$\int{\frac{1}{\sqrt{3x^2-4}}}\;dx-\int{\frac{1}{x\sqrt{3x^2-4}}}\;dx=$$ $$\frac{2}{\sqrt3}\int\frac{\tan(u)\sec(u)}{2\sqrt{\left(\frac{\sqrt3}{2}\sec(u)\right)^2-1}}\;du-\frac1{2}\int\frac{\frac{\sqrt3}{2}}{\frac{\sqrt3}{2}x\sqrt{\left(\frac{\sqrt3}{2}x\right)^2-1}}\;dx=$$ $$\frac{1}{\sqrt3}\int\sec{u}\;du-\frac12\sec^{-1}\left(\frac{\sqrt3}{2}x\right)$$
In my feedback says that the result is $$\frac{1}{\sqrt3}\log\left|\sqrt3x+\sqrt{3x^2-4}\right|-\frac12\sec^{-1}{\left(\frac{\sqrt3}{2}x\right)}+C$$
It also says that I have to use this method of trigonometric substitution.
The path is this?
I know $\int\sec(t)dt=\log|\sec t+\tan t|$
Answer: You are essentially finished. We have $\sec u=\frac{\sqrt{3}x}{2}$ and $\tan u=\frac{\sqrt{3x^2-4}}{2}$. Thus your procedure gives as first term
$$\frac{1}{\sqrt{3}}\log\left|\frac{\sqrt{3}x+\sqrt{3x^2-4}}{2}\right|.$$
This is equal to
$$\frac{1}{\sqrt{3}}\log\left|\sqrt{3}x+\sqrt{3x^2-4}\right|-\frac{1}{\sqrt{3}}\log 2.$$
So the two versions differ by a constant, which can be absorbed in the constant of integration.
Answer: If $\tan t=\frac{\sqrt{3x^2-2}}{2}$ and $\cos t=\frac{2}{\sqrt{3}x} $, then $x=\frac{2}{\sqrt{3}}\sec t \Rightarrow dx=\frac{2}{\sqrt{3}}\sec t \tan t dt$ and so
$$\int \frac{x-1}{x\sqrt{3x^2-4}}dx=\int \frac{(\frac{2}{\sqrt{3}}\sec t-1)}{\frac{2}{\sqrt{3}}\sec t\cdot 2\tan t} \cdot \frac{2}{\sqrt{3}}\sec t\tan t dt=\frac{1}{\sqrt{3}}\int\sec t dt- \frac{1}{2}\int dt=$$
$$=\frac{1}{\sqrt{3}}\ln |\sec t+\tan t|-\frac{1}{2}t +c= $$
$$\frac{1}{\sqrt{3}}\ln |\frac{\sqrt{3}x}{2}+\frac{\sqrt{3x^2-4}}{2}|-\frac{1}{2}\arccos(\frac{2}{\sqrt{3}x})+c.  $$
Comment: Note that if $\arccos x=\alpha$, then $x=\cos \alpha$ and
then $\frac{1}{x}=\frac{1}{\cos \alpha}=\sec \alpha$ and so $\alpha=\text{arcsec}\frac{1}{x}$. So it makes both appear in response to the $\text{arcos} (\frac{2}{\sqrt{3}x})$ or the expression $\text{arsec}(\frac{\sqrt{3}x}{2})$.


For $d\mid m$, $\mathbb{Z}/d\mathbb{Z}$ is not an injective $\mathbb{Z}/m\mathbb{Z}$-module when some prime divides $d$ and $\frac{m}{d}$

Question: Suppose $d\mid m$. Show that $\mathbb{Z}/d\mathbb{Z}$ is not an injective $\mathbb{Z}/m\mathbb{Z}$-module when $\exists p$ prime with $p\mid d$ and $p\mid \frac{m}{d}$.
$\textbf{My attempt:}$
We have that $(a+m\mathbb{Z})(b+d\mathbb{Z}) \mapsto ab + d\mathbb{Z}$ defines $\mathbb{Z}/d\mathbb{Z}$ as a $\mathbb{Z}/m\mathbb{Z}$-module as usual.
Using Baer's criterion I want to show that there exists an ideal of $\mathbb{Z}/m\mathbb{Z},$ say $J$, and an $R$-module map $f:J \to \mathbb{Z}/d\mathbb{Z}$ which $\textbf{cannot}$ be extended to a map $f_*:\mathbb{Z}/m\mathbb{Z} \to \mathbb{Z}/d\mathbb{Z}$.
Take the ideal $\langle \frac{m}{d} \rangle$ in $\mathbb{Z}/m\mathbb{Z}$ and map $$f:\left\langle \frac{m}{d} \right\rangle \xrightarrow{\simeq} \mathbb{Z}/d\mathbb{Z}$$
$$ a\frac{m}{d} + m\mathbb{Z} \mapsto a + d\mathbb{Z}$$
Then this is a module isomorphism.
If we could extend this to a map $f_*$ then as $f$ is surjective we'd get the following short exact sequence:
$$ 0 \rightarrow ker(f_*) \xrightarrow{i} \mathbb{Z}/m\mathbb{Z} \xrightarrow{f_*} \mathbb{Z}/d\mathbb{Z} \rightarrow 0$$
This sequence splits because $f$ was an isomorphism (so $f_*\circ f^{-1} = f\circ f^{-1} = id$ witnesses the splitting) [$\textbf{is this logic valid?}$].
So $\mathbb{Z}/m\mathbb{Z}=ker(f_*)\oplus\mathbb{Z}/d\mathbb{Z}$ and $ker(f_*)$ as a submodule of $\mathbb{Z}/m\mathbb{Z}$ is of the form $\mathbb{Z}/e\mathbb{Z}$ for some $e.$ [$\textbf{Is this true?}$]
So that $\mathbb{Z}/m\mathbb{Z}=\mathbb{Z}/e\mathbb{Z}\oplus\mathbb{Z}/d\mathbb{Z}$. I want to show that this is the desired contradiction.
Now I want to use the condition $p\mid d$ and $p\mid\frac{m}{d}$ to show that $\mathbb{Z}/m\mathbb{Z} \ne \mathbb{Z}/e\mathbb{Z}\oplus\mathbb{Z}/d\mathbb{Z}$  but I'm not sure how. Tried using orders of elements but got a little muddled...
If I can do this (and I think it can be done), is this approach all ok, or have I made a mistake?
Comment: $\Bbb Z/e\Bbb Z\oplus\Bbb Z/d\Bbb Z$ has $p^2$ elements with $px=0$.
Comment: I think an easier approach is to find an exact sequence $0\to\Bbb Z/d\Bbb Z\to M\to N\to0$ which doesn't split.
Comment: I see, and that is equivalent to not being injective? (Just met this concept today). Is this approach valid even if slightly heavy handed?
Comment: See also [this question](https://math.stackexchange.com/questions/1888048/an-exercise-from-weibels-introduction-to-homological-algebra).
Answer: maybe we can calculate the injective:
First,we can show a fact: if $R$ is PID,then for any non-zero ideal $I$,$R/I$ is self-injective.and in this case $R/I$ is injective cogenerator of $R/I$ and every finite generated module canbe embedded into $\coprod_{i=1}^{s}R_i$ where $R_i=R$.
Second,if $m=p^lp_1^{l_1}…p_k^{l_k}$,where $p,p_1,…p_k$ are coprime ,then $\mathbb Z_m\cong \mathbb{Z}_{p^l}\coprod \mathbb Z_{p_1^{l_1}}\coprod …\coprod \mathbb Z_{p_k^{l_k}}$.
Remark that all $\mathbb Z_{p^l},…\mathbb Z_{p_k^{l_k}}$ are indecomposable since they have maximal submodule.
Hence,the summand given
 above are all indecomposable injective module.so all finite generated injective is finite direct sum of these indecomposable injective.
Since $p\mid d$ and $p\mid m/d$ we know it can't be injective.
Answer: I think the logic of your argument is correct. The first of your questioned logic is a straightforward computation, which you have written in your post. To elaborate the second of your question (the "Is this true?" part), note that $\ker(f_*)$ is a subgroup of the cyclic group $\mathbb Z/m\mathbb Z$ and it is also a cyclic group. Taking Lagrange theorem into account we'll see $\ker(f_*)=\mathbb Z/e\mathbb Z$ and $e\mid m$. Since $\mathbb Z/m\mathbb Z\simeq\mathbb Z/e\mathbb Z\oplus \mathbb  Z/d\mathbb Z$, the cardinality forces $e=\frac{m}{d}$. Note that $(d,\frac{m}{d})>1$ and thus the direct sum is not a cyclic group, a contradiction.

If you are allowed to use more homological-algebraic arguments, there is another approach to this problem. Firstly if we observe that $\mathbb Z/m\mathbb Z$ is quasi-Frobenius whenever $m>0$, then this problem is reduced to an equivalent form: if $d\mid m$ and $(d,\frac{m}{d})>1$, then $\mathbb Z/d\mathbb Z$ is not a projective $\mathbb Z/m\mathbb Z$-module. If $m$ is square-free, the problem is verified trivially. If $m$ is not square-free, it can be shown that for any decomposition $m=rs$, $$\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/r\mathbb Z)=\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/s\mathbb Z)-1$$ whenever $(r,s)>1$.
Then the problem is clear: if $\mathbb Z/d\mathbb Z$ is an injective (namely projective) $\mathbb Z/m\mathbb Z$-module, then we have $$0=\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/d\mathbb Z)=\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/\frac{m}{d}\mathbb Z)-1$$ and $$\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/\frac{m}{d}\mathbb Z)=\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/d\mathbb Z)-1=-1,$$
which leads to an obvious contradiction $\operatorname{proj. dim}_{\mathbb Z/m\mathbb Z}(\mathbb Z/\frac{m}{d}\mathbb Z)=1=-1$.
Comment: Thanks so much for this; currently working through a homological algebra course so hopefully will meet these concepts soon!


Why isn't $\nabla_X(e_j)$ automatically a flat section?

Question: My book is Connections, Curvature, and Characteristic Classes by Loring W. Tu (I'll call this Volume 3), a sequel to both Differential Forms in Algebraic Topology by Loring W. Tu and Raoul Bott (Volume 2) and An Introduction to Manifolds by Loring W. Tu (Volume 1).
I refer to Section 11.1 (page 79), Section 11.1 (page 80), Section 10.1 (page 72) and Section 10.2 (page 73).

Section 11.1 begins with describing $\nabla$ locally.

First question is about Tu's description: Please explain what's going on. Why isn't $\nabla^U_X(e_j)$ (written with $U$ omitted i.e. $\nabla_X(e_j)$) automatically a flat section?

1a. I think that $E|_U$ is a trivial tangent bundle, and so I think for page 80 that the first instance of the expression "$\nabla_X e_j$" should be the equation "$\nabla_X e_j$ = 0" (By definition in Example 10.3 in Section 10.1), and the second, third and fourth instances of "$\nabla_X e_j$" should be instead the expression "$\nabla_X s$" (as in $\nabla^U_X s$).
1b. Technically, the first equation in page 80 is true, but I think each $\omega^i_j(X)$ is automatically the zero element of $C^{\infty}U$.

Second question is asking verification for my own description: Local description of connection $\nabla$ of smooth vector bundle $\pi: E \to M$
Answer: You are mixing up different things. One question is whether on a given vector bundle, there is some linear connection. This is discussed in Section 10, and the first step is to prove that a local trivialization of the bundle give rise to a "local connection" on the domain of the trivialization. These can the be glued to obtain a connection on the vector bundle.
Once it is clear that a bundle admits one linear connection, it follows easily that there are many of them (the form an infinite dimensional family parametrized by all sections of some bigger vector bundle). So a connection should be viewed as an "additional chosen structure" on a vector bundle.
Section 11 deals with the problem of describing some fixed connection. You can use local trivializations in this description, but the connection you are studying is not related to the flat local connection given by the chosen trivialization.
Comment: This is basically correct. In addition, linear connections in general do not have parallel sections. When you do have a prallel section, then the curvature has to act trivially on it, so this imposes a restriction.
Comment: Do I understand this right?

Given a smooth trivial bundle of rank r $\sigma: F \to N$ and with trivialization $\phi$ and smooth global frame $\{e_{1,\phi}, ..., e_{r,\phi}\}$, we can have a connection $\eta_{\phi}$ such that $e_{i,\phi}$'s are flat ($(\eta_{\phi})_Q e_{i,\phi} = 0$ for all $Q \in \mathfrak X(N)$), but there are connections $\delta$ where the $e_{i,\phi}$'s are not flat. For Section 11.1, the connection $\nabla^U$ on $\pi_U: E|_U \to U$ that comes from some connection $\nabla$ on $\pi: E \to M$, may or may not be the connection $\Delta$ that comes from Example 10.3.
Comment: Specifically, $U$ may have trivialization $\varphi$, but I think we can give $U$ a different trivialization $\varepsilon$. In which case we can different frames for each of the two trivializations and then we use the frame of one trivialization, say $\varphi$ and plug in the frame from $\varphi$ to the connection formed from the frame $\varepsilon$. This doesn't have to be what's happening in Section 11.1, but this is an example of how we don't necessarily have $\nabla^U_X e_j = 0$
Comment: Thanks. I just started learning about parallel sections (which is introduced 3 sections later starting with parallel vector fields along curves), but anyway  parallel isn't a prerequisite for this, so that's that.


Trouble verifying Facebook publish_actions permission

Question: I have successfully logged into Facebook and asked for publish_actions permission. The permission is granted, as I can readily verify on https://www.facebook.com/settings?tab=applications and also by calling
-(void) whatPermissionsDoIHave
{
  [FBRequestConnection startWithGraphPath:@"/me/permissions"
    completionHandler:^(
      FBRequestConnection *connection,
      NSDictionary* result,
      NSError *error
    ) {
       //do checks in here
      }
  }];
}

So I know for certain that I have permission. However, whenever it's time to share, my permission check returns false. I will now show my permission check
+ (BOOL)hasWritePermissions
{
    if (!FBSession.activeSession.isOpen) return NO;
    NSLog(@"So the session is at least open");
    return [FBSession.activeSession.permissions indexOfObject:@[@"publish_actions"]] != NSNotFound;
}

So am I missing something else? Perhaps something I should have done in AppDelegate or such? Thanks for any insight.
Right now the only call I am making in AppDelegate is
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    // attempt to extract a token from the url
    return [FBAppCall handleOpenURL:url
                  sourceApplication:sourceApplication
                    fallbackHandler:^(FBAppCall *call) {
                        NSLog(@"In fallback handler");
                    }];
}

Answer: The permissions property is an array of strings, but you're calling indexOfObject on another array, which is probably why it can't find it. Try this instead:
return [FBSession.activeSession.permissions indexOfObject:@"publish_actions"] != NSNotFound;