How to add an image within a header?

Question:
I am new to Drupal and currently working on a theme from scratch. I have been using the tutorial How to create a simple Drupal 7 theme from scratch to help me. I have got most the things working required for the site I am working on apart from the header. I would like to add an image to the header which would be floated to the left of the text.
So far I have tried to create a content type with an image and assign it to the header block I have created. When I tried assigning a content type the header disappeared.
Any suggestions?
Comment: You might need to provide more information. Do you mean on node pages you want to show an image in the header that is specific to that node? Or something else?
Comment: Hello. Thanks for the reply. Sorry for my vagueness. I will try to explain in a little more detail. I want to try and create a header with an image floated to the left of the text that will only appear on the front page (I've worked out how to make the header only appear on the front page so that part is fine).  I've created an example of what I want my header to look like here http://bayimg.com/CALaeaaFM . I'm trying to do that on Drupal but the closest I can get to it is this http://bayimg.com/ealAhaAfM . Every time I apply a content-type with an image the header disappears.
Answer: I would not create a content type just for adding a single image to the header in any case, but even more so in this case as it appears that is you website's logo (is that right?).
If it is your logo then the best way to achieve this is via the settings of your theme. Almost all themes have a setting for the logo image.
Go to admin/appearance then click the settings link for your theme.
You will see a "Logo image settings" section on the settings form, which usually by default has a check box "Use the default logo", which will be checked by default.
You can un-check that check box and then enter a path to your logo image file, however the easier and better way is to leave that check box checked and then in your theme directory replace the default logo with your own, by renaming your logo image to logo.png and copying it over the one that is already there.
On that theme settings page there is also a section for "Toggle display".
In this section make sure that "Logo" is checked.
Then the site will be using your logo, which normally by default will be in the header already.
Then you just have to use a little css to position it as you want it, or if it is not in the right place for you, edit the page.tpl.php of your theme and move the logo to where you want it, then tweak styles with css as needed.
If you only want the logo on the home page, make a copy of your page.tpl.php in your theme and call it page--front.tpl.php - This means it will only apply to your front page (see drupal 7 template suggestions for more info).
Then you can have the logo printing on the front page but you can remove it from your normal page.tpl.php so it doesn't appear on other pages.
If I was wrong about it being your site logo or it is the logo but for some other reason you don't want to use the site logo setting, you can do one of a few things.
If the image is purely decorative, it is generally considered a good idea to make it a css background image, in which case just add the image to your theme's images directory and add some css to your theme to set it as the background image of your text block in your header and use padding so that the contents don't overlap the image.
If the image is not purely decorative and it actually has meaning to the user, you want screen readers to read it as an image so disabled users can see it.
In this case you need to use an img tag.
So you can do one of these things:
Make the page--front.tpl.php and manually add an img tag in the place you want it, put the image in the images directory of your theme, then style with CSS.
The other option is to create a custom block via the block UI.
To do this go to admin/structure/block and click the "Add block" link.
In the block body field add the img tag you want.
The easiest way to do this is make sure you have a wysiwyg text editor (for example, ckeditor or wysiwyg module) and use it for block creation.
Then you can upload an image directly via the wysiwyg editor instead of messing around uploading files manually to your server, which is not ideal.
In this way you can either make a block for your image and a block for the text to the right of it, or if they directly relate to each other you can add them in the same block.
Then in the block visibility settings you can make it so that it only shows on the home page (or you can use some other block management system to do that if you prefer).
Comment: Thank you for this very informative reply, I really appreciate it! After I added the logo to the page template and .info file everything was a breeze from there. I have managed to get the logo floated to the left of the text, just as I wanted it. Thanks! :)
Comment: No troubles. If you select one of the answers as correct (with the little tick icon) the system will mark this question as having a suitable answer.
Answer: The easier solution i can think of involves only CSS.
You can style the block to have that image as background, and set the left padding wide enough to keep the block content from covering it.
Comment: Hey. Thanks for the reply.
I think that is what I will do if I can't add the image with Drupal. I will try adding it to my page template.

How to add an image within a header?


Real world examples of the sleeping beauty paradox

Question: The Sleeping Beauty problem is a thought experiment concerning a participant, Sleeping Beauty, who is woken once or twice based on the flip of coin and is asked her degree of belief on the coin having come up heads. Extensive analysis here. It seems to me that this is a philosophical question about the nature of truth. The objective truth is that $Pr(H) = 1/2$ however Sleeping Beauty is best to operate under the belief that $Pr(H) = 1/3$ to win any kind of betting game. This belief is not just dependent on the nature of a coin but also subjectively depends on the situation in which she finds herself.
Now the Sleeping Beauty problem comes across as a very contrived problem. Are there any real world analogues to this problem? Either one you can devise or one that actually hapened?
Comment: I don't see anything *opinion-based* about this per se. It may be that this should be made CW, but I don't see an immediate need for closure. I'm voting to leave open.
Answer: My candidate for a real-world analogue: "How likely is it that there is intelligent life elsewhere in the universe?"
To simplify things, assume that God picked the fundamental physical constants at random. Assume that there was a 50% chance of picking values which would result in a universe hostile to life, where intelligence would only evolve on one planet (corresponding to Sleeping Beauty being woken up only once), and a 50% chance of picking values which would result in a universe friendly to life, where intelligence would evolve millions of times (corresponding to Sleeping Beauty being woken up multiple times.)
Then the question of whether the evolution of intelligence on our own planet should increase our probability that values friendly to life were picked corresponds to the question of whether Sleeping Beauty should consider her own waking up to be evidence that she is woken up multiple times.
To make my description of this scenario correspond better to reality, replace the random variable "which of these two hypothetical sets of physical constant values were picked" with the random variable "how probable is the evolution of intelligent life on a random planet given the laws of physics."
One objection to my argument would be: Sleeping Beauty knew going in that she would be woken up, but we didn't know that we would evolve until after we did. My reply: if we modify the Sleeping Beauty problem setup so that she doesn't initially know she's part of the experiment, and the experiment is only explained to her each time she is woken up, I don't think that fundamentally alters the paradox.
You could make the case that the question of how likely it is that we live in a computer simulation similarly corresponds to the Sleeping Beauty question.


Opening the last fragment view in Java Android Apps

Question: I created a bottom navigation for my app and was wondering how could I make it so when the user opens the app, it returns to the last fragment they were viewing? At the moment even if you just switch apps for a second, it reverts to the home page immediately. Thanks in advance!
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.MenuItem;

import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {
    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView bottomnav = findViewById(R.id.bottom_menu);
        bottomnav.setOnNavigationItemSelectedListener(navListener);

        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, new HomeFragment()).commit();

       mediaPlayer = MediaPlayer.create(this, R.raw.clickandboop);

    }

    private final BottomNavigationView.OnNavigationItemSelectedListener navListener =
            new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                    Fragment selectedFragment = null;

                    switch (menuItem.getItemId()) {
                        case R.id.nav_home:
                            selectedFragment = new HomeFragment();
                            mediaPlayer.start();
                            break;
                        case R.id.nav_favourites:
                            selectedFragment = new FavFragment();
                            mediaPlayer.start();
                            break;
                        case R.id.nav_trophies:
                            selectedFragment = new TrophiesFragment();
                            mediaPlayer.start();
                            break;
                        case R.id.nav_info:
                            selectedFragment = new InfoFragment();
                            mediaPlayer.start();
                            break;

                    }
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout, selectedFragment).commit();

                    return true;
                }
            };

Answer: Fragments already restore you back to exactly where you were.
This means that you need to wrap your replace() call with a check of savedInstanceState == null to avoid destroying the just recreated Fragment:
if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction()
        .replace(R.id.fragment_layout, new HomeFragment())
        .commit();
}

Answer: Just use sharedprefs and store the last fragment that the user was in. Use the onStop callback of the fragment to store it.
When the user opens the application just check this value if it's not set open homefragment otherwise just open the last fragment based on the value you have in your shared preferences


Can't find where to edit content

Question: I've recently inherited an Drupal 8 website.  www.berkslibraries.org  At the bottom of the site in the footer there is the word Contact and under it a link to Hours & Locations, email address, and a phone number.  I have searched through Drupal and can't find where that information in stored to change it.  It's not in the content section or in the custom blocks.  I was hoping someone might have some advice on where I can possibly look to change that info.
Thanks,
Answer: When you log in as admin. just hover your cursor over the words and you can do a quick edit. You might have tried create content. If you just click content, all content created will populate.
Comment: Thanks but that doesn't work.  This content seems to be embedded somehow into the page.  It's not one of your regular piece of contents like an article or basic page that you can edit.  It is not a custom block either.  I have a column 3 custom block that will add content right below the phone number if I enter data.
Answer: Judging from the lack of block or menu HTML wrappers around this section, it looks like this is embedded in the site's page template.  You will not be able to edit this from the GUI.  Instead, look in the theme directory, templates subdirectory for the files that need to be edited.
Comment: Thanks, yes I think it is somehow embedded into the website.  So you think I need I need shell level access to actually make the change?
Comment: Depends on your setup.  If the webserver is linked to a repository like GIT, then you will need access to that repository and info on how to push changes.  E.g. clone the repository locally, find the template file that needs to be changed, change and push /deploy to the site.  Alternatively, you could do the same thing with FTP, SFTP, or SCP access to the site files.  (Copy the site files down instead of clone).

Can't find where to edit content


Comment/Node Body Fields Not Applying Filters

Question: Hello ive been struggling for the past 24hrs getting my node body and comment body fields to use the text filters i have made. I wont go into the filter options just yet as the important thing here is that when i create a View html list with fields and Comment: Comment field, everything works well. I have paragraphs and my links convert so my text filters seem to be ok.
So i know its all to do with the Content Type's     comment_body    Long text   Text area (multiple rows) settings.
Filtered text (user selects text format) is checked. Text Fromat selected is my 'plaincustom' (originally plain text)
Web page addresses and e-mail addresses turn into links automatically.
Lines and paragraphs break automatically.
All seem to be available. When i view my node or comment though i just get it all in one big blob of text with no paragraphs or line converts.
Can anyone suggest anything that could help solve this issue? I do not know if this previous question i asked about changing text formats has any relevance to this issue. thinkign about it it might have. Then why does my view show ok?
Change Comment Text Format in phpmyadmin
Comment: i still cant get my head around why my html isnt showing paragraphs etc. I added a block here describign my woes and as you can see it displays the input filters ok http://www.onlinebanter.com/latest
Comment: even if i use full html as admin and us P tags about things it displays all in one line. It can only be to do with my content type field display. let me go back and see.
Comment: well i have managed to sort the node body field to work as expected. line breaks and converted urls. Just the body field now. Its using the same settings as the node body field. thats whats making it so strange for me.
Comment: ah hah my comment display was Plain Text. Simpel but...well im just glad i got there. Thanks.
Comment: If you found an answer yourself, it's good to post the answer below, and mark it as accepted so that everyone knows the issue is resolved.
Answer: my comment display was Plain Text.


Woocommerce - Add html to the single product page only if there are upsell products

Question: I wrote this code for display description tab on the left and upsell product on the right in the layout of woocommerce single product. But how avoid this html code if a product have no upsell products at all, and return to the original layout?
This is my custom code:
/*** Display description tab and upsell products side by side */

add_action( 'woocommerce_after_single_product_summary', 'ckde_open_container_desc_upsells', 0 );
function ckde_open_container_desc_upsells() {
  echo '

';
}

add_action( 'woocommerce_after_single_product_summary', 'ckde_close_open_col_desc_upsells', 15 );
function ckde_close_open_col_desc_upsells(){
  echo '

';
}

add_action( 'woocommerce_after_single_product_summary', 'ckde_close_col_upsells', 20 );
function ckde_close_col_upsells(){
  echo '

';
}

/*** Change number of upsells output  */

remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_upsell_display', 15);
add_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_upsells', 15);

if (!function_exists('woocommerce_output_upsells')) {
    function woocommerce_output_upsells() {
      woocommerce_upsell_display(6,3); // Display max 6 products, 3 per row
    }
}

For sure there is a hook or a conditional tag to do that, but I can't figure out what it can be.
I don't want to override woocommerce template file but do this in my custom functions file
I hope it is clear enough.
Thanks a lot for the help.
Answer: I solved in this way finally!
/*** Display description tab and up-sell products side by side when up-sell products are defined */

add_action( 'woocommerce_after_single_product_summary', 'ckde_open_container_desc_upsells', 0 );

function ckde_open_container_desc_upsells() {
  global $product;

  if ( isset( $product ) && is_product() ) {

    $upsells = $product->get_upsell_ids();

    if ( count( $upsells ) > 0 ) {

      echo '

';
    }
  }
}

add_action( 'woocommerce_after_single_product_summary', 'ckde_close_open_col_desc_upsells', 15 );

function ckde_close_open_col_desc_upsells() {

  global $product;

  if ( isset( $product ) && is_product() ) {

    $upsells = $product->get_upsell_ids();

    if ( count( $upsells ) > 0 ) {

      echo '

';
    }
  }
}

add_action( 'woocommerce_after_single_product_summary', 'ckde_close_col_upsells', 20 );

function ckde_close_col_upsells() {

  global $product;

  if ( isset( $product ) && is_product() ) {

    $upsells = $product->get_upsell_ids();

    if ( count( $upsells ) > 0 ) {

      echo '

';
    }
  }
}


Why Views Slideshow JCarousel plugin isn't available on view format settings?

Question: I've installed:

Views Slideshow
Views Slideshow Cycle
Views Slideshow Carousel

All required libraries are available. Status reports page is green.
I want to create slideshow view. I choose slideshow format, but on settings I have only Cycle as available slideshow type.
What can be wrong?
Comment: uninstall it and then try to use different version.
Comment: Do you mean [Views Slideshow JCarousel](https://www.drupal.org/project/views_slideshow_jcarousel)?
Answer: There is nothing wrong. jQuery Cycle is the default library used by the Views Slideshow Cycle module.
Look instead at "Widgets" on the format settings screen. The relevant configuration options will appear by selecting "Pager" under either Top Widgets or Bottom widgets.
From the Views Slideshow JCarousel project page:

Currently provides a JCarousel pager widget.

and

Under the Format heading, click "format" and select "slideshow". You
  should now be able to select and configure your jcarousel slideshow.
  Pager options are on this configuration screen, not under views "pager
  settings". To decide where you want your pager to go, you can tick the
  pager widget checkbox beneath the area you wish to show it. your
  choices are "top" or "bottom" of carousel.

Note: If using Views Slideshow Cycle, you will need to download the jQuery Cycle plugin.
Comment: Important thing: cycle plugin need to be enabled too.
Comment: The *Views Slideshow Cycle* submodule requires it, so you'd get loud warnings on your status page if you didn't have the plugin. That info really should be on the project page, though. Anyway, thanks for selecting my answer. :)
Comment: My status page was green so that's why I had no idea what is the problem
Comment: Weird. It's right here: [root/contrib/views_slideshow_cycle/views_slideshow_cycle.install](http://cgit.drupalcode.org/views_slideshow/tree/contrib/views_slideshow_cycle/views_slideshow_cycle.install). Maybe there's a bug.
Comment: I have trying different versions so maybe this in the reason
Comment: I've added a note in my answer.


Commerce Feeds - Taxonomy term processor Issue

Question: Using Commerce Feeds version: 7.x-1.3
I am running the "taxonomy term processor". I have tried every available combination for "Update existing terms" (Do not update existing terms, Replace existing terms, Update existing terms . . . even Skip hash check - 'checked' and Skip hash check - 'unchecked').
No matter what I do, the csv import file that I am uploading just adds to what I have already imported. If I am uploading the same file and have added additional terms, I would think there would be a way of JUST adding the new terms, not duplicating everything again.
Am I missing something or is this a bug?
Thank you!
Tom
Answer: Tom, I found your question today while fighting the same problem in the standard Feeds module.  In the Processor > Mapping setup, do you have fields set as unique targets in the "target configuration" column?
In my system, I found that even though I had tried to set the imported column to be a 'unique target', that setting had not been saved. After going through the process of setting unique targets, updating the column map, and saving again, the duplication problem has now been solved in my system.


Objective-C/IOS : Delete data in coredata

Question: I have 2 entities LETTER and LETTER.NUMBER example:

A - A.1 ,A.2 ,A.3 ,A.4 ,...
B - B.1 ,B.2 ,B.3 ,B.4 ,...
C - C.1 ,C.2 ,...
D - D.1 ,...

When i delete LETTER ,i also want to delete all the children data example:

Delete A ----> Delete A.1 ,A.2 ,A.3 ,A.4 ,...
Delete B ----> Delete B.1 ,B.2 ,B.3 ,B.4 ,...

In other database framework ,we can use primary key to achive that. But i don't know how to set primary key in Objective-C.
Can someone show me how to do that or suggest a tutoral that i can follow.
Answer: You need to cascade the deletion, https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075-CH2-SW1. Use the apple's document.
Answer: This is a very easy task. Open xcdatamodel in xcode. Then select the entity 'LETTER'. Here you must have a reltionship with entity 'LETTER.NUMBER'. Select the relationship, then in the data model inspector of xCode (the right most item in the right panel) set the delete rule to 'Cascade'.
Now when you delete your LETTER object, all LETTER.NUMBER objects associated with it will also be deleted
Comment: Thanks a lot ! btw for some need more info
[link](https://www.youtube.com/watch?v=dkesIrpmAug)


GET path not accepting 'dot' in it

Question: I have router path with a '.' in it, my path is downloads/pass.pkpass
I have defined the path in web.php as the following
$router->get('downloads/pass.pkpass', 'PassServerController@downloadPass');
but somehow it's not working. if I remove the '.' it's working fine. what might be the problem here?
It's was working before recently I updated lumen after that it's not working.
Comment: why you need dot in your url use "-" instead
Comment: Agree with afsal c . using a dot will only confuse servers and browsers since what normally follows is a domain ending (".com") or file extension when downloading files
Comment: @afsalc - it's a file to download, the file is creating on the fly.
Comment: Look at this: `https://laravel.com/docs/5.6/routing#route-group-name-prefixes`
Comment: It's a file I am setting some headers before make it download
Comment: use `return response()->download($pathToFile);` this download file
Comment: @ChamaraAbeysekara - I'm not able to call the function because of the dot in the path.
Answer: The . is the string concatenation operator in PHP.
example
<?php

$string1 = "Test";
$string2 = "working!";
$string = $string1 . $string2;

echo $string;

?>

this will print "Test working!"
You can get your route by this may be
$router->get('downloads/pass.'.'pkpass', 'PassServerController@downloadPass');

But this is some kind of hack we can say.

You can use _ instead of . parameter that will work for sure.
Comment: $router->get('downloads/pass'.'pkpass', 'PassServerController@downloadPass'); Iam not sure try this
Comment: `_` is working for me but not `.` It was woking fine before recently I updated my lumen after that the issue started.
Comment: I have researched and found that using  `.` is not the proper way. @Unnikrishnan
Comment: @ChiragPatel -  so what is the beast practice for a download file URL? If I have a on the fly PDF generation code how I should define the download path?

GET path not accepting 'dot' in it


Partition column is moved to end of row when saving a file to Parquet

Question: For a given DataFrame just before being save'd to parquet here is the schema: notice that the centroid0 is the first column and is StringType:

However when saving the file using:
      df.write.partitionBy(dfHolder.metadata.partitionCols: _*).format("parquet").mode("overwrite").save(fpath)

and with the partitionCols as centroid0:

then there is a (to me) surprising result:

the centroid0 partition column has been moved to the end of the Row
the data type has been changed to Integer

I confirmed the output path via println :
 path=/git/block/target/scala-2.11/test-classes/data/output/blocking/out//level1/clusters

And here is the schema upon reading back from the saved parquet:

Why are those two modifications to the input schema occurring - and how can they be avoided - while still maintaining the centroid0 as a partitioning column?
Update  A preferred answer should mention why /when the partitions were added to the end (vs the beginning) of the columns list. We need an understanding of the deterministic ordering.
In addition - is there any way to cause spark to "change it's mind" on the inferred column types?  I have had to change the partitions from 0, 1 etc to c0, c1 etc in order to get the inference to map to StringType. Maybe that were required .. but if there were some spark setting to change the behavior that would make for an excellent answer.
Comment: Maybe the answer here can help you: https://stackoverflow.com/questions/46657954/avoid-losing-data-type-for-the-partitioned-data-when-writing-from-spark
Comment: @shaido But what about the **re-ordering** of the column to the end?
Comment: Since the information about the column is stored in the filestructure, Spark will not know what it's original position in the dataframe was. Adding it in the beginning or the end are the simplest solutions and it seems the end was chosen in the implementation here.
Comment: I have seen other dataframes using the same `partitionBy()` method (and with one or more partitioning columns) in which the columns were retained at the *front* (original positions). If you run into any further documentation/explanation that provide some deterministic means to understand the ordering pls do comment or add an answer.
Comment: I tried to check the source code but unfortunatly I couldn't find anything regarding why the partition column/columns are not consitently added to either the beginning or end. Regarding the column types, wouldn't it work to simply `cast` the type to string after reading (as in the link in my first comment).
Comment: `cast` will not work because the error occurs upon initial access via `spark.read.parquet`
Comment: What error? Also, have you tried supplying a schema when reading the parquet? It's possible it would solve both the order and the type problem.
Comment: `spark.read.parquet(paths: String*)` does not take/require a schema since the schema is built in to the dataset itself
Comment: try `spark.read.schema(schema).parquet(paths)`.
Answer: When you write.partitionBy(...) Spark saves the partition field(s) as folder(s)
This is can be beneficial for reading data later as (with some file types, parquet included) it can optimize to read data just from partitions that you use (i.e. if you'd read and filter for centroid0==1 spark wouldn't read the other partitions
The effect of this is that the partition fields (centroid0 in your case) are not written into the parquet file only as folder names (centroid0=1, centroid0=2, etc.)
The side effect of these are 1. the type of the partition is inferred at run time (since the schema is not saved in the parquet) and in your case it happened that you only had integer values so it was inferred to integer.
The other side effect is that the partition field is added at the end/beginning of the schema as it reads the schema from the parquet files as one chunk and then it adds to that the partition field(s) as another (again, it is no longer part of the schema that is stored in the parquet)
Comment: Any idea why /when the partitions were added to the *beginning* vs the *end* of the columns list?  I need to understand  a deterministic ordering. thanks. I have updated the OP for a bit more on the info being sought.
Comment: you can always do a select with the columns in the order you'd like them to be and also cast to string just in case when reading the data. This is probably better anyway if the schema would evolve going forward to ensure this process has a fixed schema
Comment: Re-selecting is a non starter due to computational cost.
Comment: There's almost zero computational cost - it's a just a projection
Comment: That's not the case here since we're talking about directly after invoking `spark.read.parquet` : this will incur an additional full scan of the data. A full scan *is* costly for the datasets I work with.
Comment: no it wont - Spark will do the projection as it reads the data
Answer: You can actually pretty easily make use of ordering of the columns of a case class that holds the schema of your partitioned data. You will need to read the data from the path, inside which the partitioning columns are stored underneath to make Spark infer the values of these columns. Then simply apply re-ordering by using the case class schema with a statement like:
val encoder: Encoder[RecordType] = Encoders.product[RecordType]
spark.read
      .schema(encoder.schema)
      .format("parquet")
      .option("mergeSchema", "true")
      .load(myPath)
      // reorder columns, since reading from partitioned data, the partitioning columns are put to end
      .select(encoder.schema.fieldNames.head, encoder.schema.fieldNames.tail: _*)
      .as[RecordType]

Answer: The reason is in fact pretty simple. When you partition by a column, each partition can only contain one value of the said column. Therefore it is useless to actually write the same value everywhere in the file, and this is why Spark does not. When the file is read, Spark uses the information contained in the names of the files to reconstruct the partitioning column and it is put at the end of the schema. The type of the column is not stored, it is inferred when reading, hence the integer type in your case.
NB: There is no particular reason as to why the column is added at the end. It could have been at the beginning. I guess it is just an arbitrary choice of implementation.
To avoid losing the type and the order of the columns, you could duplicate the partitioning column like this df.withColumn("X", 'YOUR_COLUMN).write.partitionBy("X").parquet("...").
You will waste space though. Also, spark uses the partitioning to optimize filters for instance. Don't forget to use the X column for filters after reading the data and not your column or Spark won't be able to perform any optimizations.
Comment: Thanks for the answer. I have updated the OP for more specifics on what I am looking for.
Comment: Wouldn't a cast do the trick? `df.withColumn("centroid0", col("centroid0").cast("string")`
Comment: That will not work since the error occurs upon the initial read-back via `spark.read.parquet`


Is $S = \{ (x,y): x^2+y^2=\frac {1}{n^2}, n \in \mathbb N \wedge (x \in \mathbb Q \vee y \in \mathbb Q) \}$ countable?

Question: I am working on the following problem:

Is the set $S = \left\{ (x,y): x^2+y^2=\frac {1}{n^2}, n \in \mathbb N \wedge (x \in \mathbb Q \vee y \in \mathbb Q) \right\}$ countable?

My answer is yes.
Reason:
For a fixed $n$, let $S_n = \left\{ (x,y): x^2+y^2=\frac {1}{n^2}, n \in \mathbb N \wedge (x \in \mathbb Q \vee y \in \mathbb Q) \right\}$.
Then $S_n = (\mathbb Q \times \mathbb Q) \cup \bigcup\limits_{r\in \mathbb Q}\left(\pm r, \pm\sqrt {\frac {1}{n^2}-r^2}\right)$ where $r <\frac {1}{n^2} $.
Clearly each set forming $S_n$ is countable, its union ($S_n$) is also countable.
As $S=\bigcup\limits_{n\in \mathbb N} S_n$, $S$ is also countable.
Am I correct? Thanks in advance!
Comment: @user477343 post edited.....
Comment: Do you mean $(x,y)\in\mathbb{R}^2$? Or just $x,y\in\mathbb{R}$?
Comment: There should be a $\pm$ for $y$.
Comment: @Mikhail Katz post edited accordingly....
Comment: Is my answer correct?
Comment: The set of all pairs of rational numbers is countable and this set is a subset so, yes, of course, it is countable!
Comment: @user247327 It's not a subset of the set of pairs of rational numbers, but a subset of pairs in which one of them is rational. So the universe is $\mathbb{Q}\times\mathbb{R}\cup\mathbb{R}\times\mathbb{Q}$ which is uncountable.
Comment: @freakish yes because $a\lor b$ means $a$ **or** $b$. It's just that when we have an ordered group $(a_1, a_2,\ldots a_n)$, then if this group belongs to a set $X$, we write it as $X^n$, from what I'm taught. Unless it is not an ordered group and it is just individual members of the set $X$.
Answer: Actually you have
$$S_n=L_n\cup R_n$$
where
$$L_n=\bigg\{\bigg(r,\pm\sqrt{\frac{1}{n^2}-r^2}\bigg)\ \bigg|\ r\in \mathbb{Q}\text{ and }r^2\leq\frac{1}{n^2}\bigg\}$$
$$R_n=\bigg\{\bigg(\pm\sqrt{\frac{1}{n^2}-r^2},r\bigg)\ \bigg|\ r\in \mathbb{Q}\text{ and }r^2\leq\frac{1}{n^2}\bigg\}$$
Note the different order in $L_n$ and $R_n$ (that's the only difference between them). Those sets correspond to $x\in\mathbb{Q}\vee y\in\mathbb{Q}$ condition which is or, not and. And with this simple modification your reasoning is correct.
Comment: Should it not be  $S_n = L_n \bigcup R_n \bigcup Q_n $?
Comment: @shwetha No, $Q_n$ is the indexing set (see: $r\in Q_n$) used in the definition of $L_n$ and $R_n$. I could just remove $Q_n$ completely and say $r\in\mathbb{Q}$ whenever $\sqrt{\frac{1}{n^2}-r^2}$ is real.
Comment: Thank you! Got it!
Comment: @shwetha If you agreed to solution , accept one of solution that you find useful.
Comment: Sir, how does it follows that, $L_n$ and $R_n$ are countable? Please elaborate
Comment: @AkashPatalwanshi both are index (there's a surjection from) by $\{\pm 1\}\times \mathbb{Q}$ which is countable.
Answer: You made a minor formal mistake: when you say 'For a fixed $n$...' you should not insert the $(n\in\mathbb N)$ clause in the set definition as it means 'for any natural value of $n$'. Instead you might add it as a requirement to $n$ itself:

For a fixed $n\color{red}{\in \mathbb N}$, let $S_n = \left\{ (x,y): x^2+y^2=\frac {1}{n^2}, x \in \mathbb Q \vee y \in \mathbb Q \right\}$.

Apart from that your solution seems correct to me: there are countably many $n$ values (hence $x,y$ equations of circles), and each circle has countably many points with $x\in\mathbb Q$ and countably many points with $y\in\mathbb Q$ (these two sets not disjoint), hence $S$ is a union of countably infinite family of countably infinite sets. This implies it is equipollent with $\mathbb N^3$ and so it is countably infinite.
Answer: Given that $~S = \{ (x,y): x^2+y^2=\frac {1}{n^2}, n \in \mathbb N \wedge (x \in \mathbb Q \vee y \in \mathbb Q) \}~.$
So there doesn't exist any pair of $(x,y)$ other than $(1/n,0)$ and $(0,1/n)$, for all $n \in \mathbb N$, that satisfies the given condition.
Now we know that $~n \in \mathbb N ~$  is countable and countable union of countable sets is countable. Hence $~S=(1/n,0)\cup(0,1/n)~$ is countable.


Does K8S automatically ensure pod availability by health checking when re-run pods inside service?

Question: Let's say that I have a service with 2 pods (replicas). Each pod contains just one container that is a REST API war that runs on a Tomcat. Moreover, each pod has imagePullPolicy: Always so when there is a new version of the image, it will pull it.
When the container starts, obviously, Tomcat takes some seconds to start. This will happen in both containers.
Is it possible that in a particular time my REST API is not available? I mean, is it possible that both Tomcat aren't started yet and a request fails?
Does K8S use health checking on a pod before attemp to re-run the another one? If so, I could perform an http health checking against my REST API endpoint. Is it the right way?
Thanks in advance. Any advice will be appreciated.
Answer:
Is it possible that in a particular time my REST API is not available? I mean, is it possible that both Tomcat aren't started yet and a request fails?

Yes. You can prevent this from happening by making sure that at least one of your pods is ready to serve requests before creating the service (and then using rolling updates to avoid downtime as you upgrade you application).

Does K8S use health checking on a pod before attemp to re-run the another one? If so, I could perform an http health checking against my REST API endpoint. Is it the right way?

You should take a look at liveness and readiness probes. They are designed to capture the difference between a container running and the application inside the container being ready to serve requests.
Comment: Does 'rolling update' ensure that second pod won't be deployed while the first one is ready?
Comment: Rolling update will create a new pod before removing the old pod (and then repeat until all of the old pods are gone). This ensures that there is always a backend ready to service incoming requests. So it purposely deploys a new pod while the first one is ready, and then doesn't remove the first one until it's replacement is ready.
Comment: Perfect. Thank you very much :)


Are there modes beyond Lydian?

Question: I am learning music theory for fun and I am trying to understand different modes. I saw this video by David Bennett where he talked about how you can flatten an additional note in the Locrian mode to create a "Super-Locrian" mode.
This got me thinking, what would happen if we kept going and flattened everything? All that's left to flatten is the root note. However, when we flatten the root we just return to the major scale, starting on a lower note. So for C Super-Locrian, flattening the C just gives us B major. Flattening the root for the other modes seems to create a pattern:
If you start with C Super Locrian, flattening the root creates B major.
If you start with C Locrian, flattening the root creates B Lydian.
If you start with C Phrygian, flattening the root creates B Super-Lydian aka B Lydian augmented.
If you start with C Aeolian (C Minor), flattening the root creates a scale with the intervals 3H-H-W-W-H-W-H. I don't know what this is called and I couldn't find anything about it online, so maybe someone here can help me figure out what it is. It's like B Lydian Augmented, but the second degree is raised a half-step. It sounds dissonant, but not as dark and creepy as B Super-Locrian. Following the pattern as we have gone form major to Lydian to Super-Lydian, would this be B Super-Super-Lydian? B Hyper-Lydian?
Let's keep going. If you start with C Dorian, flattening the root creates a scale with the intervals 3H-H-W-W-W-H-H. B Triple-Super-Lydian? It sounds similar to the previous one.
Next, C Mixolydian. Flatten the C and we get the intervals 3H-W-H-W-W-H-H. Quadruple-Super-Lydian?
Finally, C major. I suppose the pattern stops here because we already have a B in the scale, so lowering the C to a B no longer creates 7 intervals. In other words, starting with B major, if we try to sharpen everything, we can't because sharpening the 7th just gives us the root.
My question is what are these modes or scales called (if they are even considered modes at all), and are there examples of them being used in music? Can they be useful or am I just arbitrarily creating weird-sounding intervals when I try to go beyond Lydian Augmented?
Comment: @DonHosek interesting that you should use the adjective "kosher" when middle eastern music is one of the most prominent of the traditions that are evoked by scales with augmented seconds.
Comment: That 3H interval is very common - it appears in every *harmonic* minor scale, between notes 6 and 7.
Comment: @CarlWitthoft - depends to which camp you belong. Some say modes only come from the major scale. I don't - modes use the existing notes from other scales, too - including the harmonic minor. And HHH then must exist in all seven modes thereof.
Comment: @phoog, yeah ironic! The Klezmer scale uses an augmented 2nd. I'm gonna say that's Kosher.
Comment: Generally, it's not considered "kosher" to have more than a whole step between steps in the scale. There are synthetic modes that may have more than 7 notes or fewer than 7 notes (e.g., the whole tone scale or the two diminished scales, whole-half and half-whole).
Comment: It's a strange interval, but I have found examples on Wikipedia of the 3H interval. Looking at [this](https://en.wikipedia.org/wiki/List_of_musical_scales_and_modes) page, there are plenty of examples of scales with a 3H. In fact, what I just noticed while scrolling through that list is that my "Super-Super-Lydian" scale has the same sequence of intervals as the Harmonic Major Scale, except it starts on the sixth. The usual modes are formed by starting on a different scale degree in the major scale, so maybe doing that with the harmonic major scale produces a new set of modes?
Comment: Adding on from the previous comment, I've also noticed that the Prometheus scale has the same intervals as the "Triple Super Lydian" (3H-H-W-W-W-H-H), but it starts on the fourth scale degree and has the seventh removed. The "Quadruple Super Lydian" (3H-W-H-W-W-H-H) looks similar to the Blues scale, if you flatten the fifth and remove the seventh.
Comment: After doing more reading, it looks like there are indeed more modes that can be created with harmonic or melodic minor/major scales. So to answer my own question, the "B super-super-lydian" scale is actually **B Lydian Augmented #2**, which is a mode of D# harmonic major. I'm still not sure how to name the other 2, though.
Comment: @Tim  true but the harmonic minor is not one of the 'standard' modes because you can't get to it from the major scale.
Comment: Let's see... if we go to extremes ,   HHH -tritone -   HHH  would be a heck of a mode!  Now someone's going to tell me there's a piece written that way :-(
Comment: @Tim  sounds good to me (the explanation, not necessarily the modes :-)  )
Comment: You might find some of the stuff I wrote about scales useful: http://cochranemusic.com/. The Scale & Arpeggio Resources PDF is probably going to be helpful in your journey. It's all free so make of it what you will.
Answer: As you've probably guessed, adding flats to existing scales isn't exactly the "standard" approach to constructing/discovering new scales. But as a teacher, I really like it when students explore theory through experimentation, because there are patterns in music. Often, repeating a somewhat arbitrary pattern enables you to "derive" existing musical devices in a new way. You've chanced upon many interesting sounds here, and while some of the scales you've mentioned are more obscure than others, most of them are equivalent to named scales and can be derived by other means. I will focus on supplying you with those names (the ones I know, at least) and suggesting how some of these scales can be applied to modern functional harmony.
For starters, recall that the C superlocrian scale can also be called the C altered scale or the C diminished whole-tone scale. The former name comes from the fact that the scale contains a C dominant chord with all the alterations: C7♭9♯9♯11♭13, or simply C7alt. The latter name comes from viewing it as the concatenation of a diminished scale (WHWHWHWH, 8 notes per octave) and a whole-tone scale (WWWWWW, 6 notes per octave). The altered scale can also be viewed as the seventh mode of the melodic minor. In this case, the C altered scale is (enharmonically) equivalent to the C♯  harmonic minor scale.
So, we have four names for this scale, which amount to four different derivations of it, all of which are valid and can help explain its characteristics and functional properties in their own way. In my opinion, the name "superlocrian" is actually the least descriptive of the four, because (to my knowledge) we don't use labels like sublydian, superaeolian, or what have you to refer to other scales. But it's worth knowing, even if only to inspire theoretical exercises like the one you've undertaken here.
By the same token, your first two scales

If you start with C Super Locrian, flattening the root creates B major.
If you start with C Locrian, flattening the root creates B Lydian.

amount to alternative derivations of known modes, as you have already identified.

If you start with C Phrygian, flattening the root creates B Super-Lydian aka B Lydian augmented.

I would argue that the simplest name for this is the third mode of the G♯ melodic minor scale. This could therefore be used over G7alt, Bmaj7♯5, or any other chord derived from the melodic minor.

If you start with C Aeolian (C Minor), flattening the root creates a scale with the intervals 3H-H-W-W-H-W-H.

I would call this the sixth mode of the E♭ harmonic major scale. Its most common use case will be in the key of E♭ major, when you have a minor IV chord, especially A♭min(maj7). It could also be used over B♭7♭9 and D°7, both of which have dominant functions in the key of E♭ major, or over dominant chords like G7♭9 in a C minor context.
(There's nothing intrinsically wrong with an augmented second in a scale. We have one between the ♭6 and ♮7 in the harmonic minor scale with no issue. In freshman theory, you are often taught to avoid having a single voice sing a step of an augmented second because it's hard to land in tune. But this can be accomplished by choosing good voicings and doesn't preclude the use of the harmonic minor scale itself.)

If you start with C Dorian, flattening the root creates a scale with the intervals 3H-H-W-W-W-H-H. B Triple-Super-Lydian? It sounds similar to the previous one.

Now we're getting into more obscure territory. I would say the unusual thing about this scale is, rather than the presence of the augmented second, the presence of two half steps in a row (between the notes A, B♭, and C♭). While I don't have a name for it, this is the scale I would play over the chord B♭maj7♭9. That is a highly unusual chord, but it can have a dominant function in an E♭ blues tonality when used with care. I wrote about the maj7♭9 sound here, if you're interested.

Next, C Mixolydian. Flatten the C and we get the intervals 3H-W-H-W-W-H-H. Quadruple-Super-Lydian?

Wow! I've got no dice here. But my impression of this scale is that it looks a lot like D dorian with the seventh omitted and passing tone inserted between the fifth and sixth degrees. I would most likely play this over a Dmin6 chord, or perhaps Bmin7♭5, where C is an "avoid" note.

As a general comment, I think you'd find it worthwhile to explore the chord qualities associated with the modes of the melodic and harmonic minor scales. There are many interesting sounds there, some of which appear in the scales you've derived in your question.
Comment: Thanks for that. I don't believe many (any?) good singer will consciously consider the subtle pitch difference between m3 and +2. They'll just pitch it right. I did for decades before I discovered the technical difference. Not sure I agree with the last sentence. It's a technical thing - note names and distances.
Comment: Very comprehensive (if advanced!) answer. +1. I'm incredulous that it's deemed hard to land in tune singing an aug.2. To me, that's like singing m3, say root to m3, or M3 to P5, or P5 to m7, or so many others. What's the problem?
Comment: The issue has to due with temperament. If you think of this +2 as being the same "distance" as other m3 leaps, you won't land in the right spot, because in a harmonic minor context, that +2 leap is taking you to the leading tone, which is the major 3 of the V7 chord (not the m3 of a minor chord or the 5 of a major chord) and needs to be sung slightly flat to get it in tune. This won't be any problem for a good singer, but that's the reasoning behind the rule, and also helps explain why we have different names for enharmonically equivalent intervals in the first place.
Comment: You're preaching to the choir (no pun intended)--I think pitching notes correctly is the singer's responsibility, not the composer's, and I'm baffled by many of the classical voice-leading rules that claim to exist for singers' comfort. But note that when our system of interval names was developed, AFAIK equal temperament hadn't taken hold yet and there was a quantitative difference between a m3 and a +2. (Counterpoint: there was also a difference between all of the various P5s and P4s but we don't have separate names for those.) This distinction has been revived in e.g. 17TET where D# =/= Eb.
Answer: I think you may want to start with understanding "mode" means "mode of a scale" or "rotation of a scale."
If you change the starting note of a diatonic scale (rotate through the letters of the gamut) you get the "modes" of the diatonic scale...

CDEFGABC   1st mode
 DEFGABCD  2nd mode
  EFGABCDE 3rd mode
   ...etc. etc.

The modes of the diatonic scale (or the major scale) are well known and have names. The second mode of the scale is "Dorian", the third mode is "Phrygian", and so on.
You can take the modes of any scale. It's common in jazz to use the modes of the ascending melodic minor scale. For example, the "altered" scale is the seventh mode of melodic minor. The Klezmer scale is the fifth mode of harmonic minor.
Sometimes that modes have names as distinct scales. Like the Klezmer scale. Some have a name that just makes a close match to a mode with a modifier, like the second mode of melodic minor is Dorian flat 2. If there isn't a well known name, just give the base scale and mode number.

you can flatten an additional note in the Locrian mode to create a "Super-Locrian" mode. ...This got me thinking, what would happen if we kept going and flattened everything?

There is something funny about that.
"Super Locrian" is another name for "altered scale" which is another name for "seventh mode of ascending melodic minor."
The funny thing is Locrian is diatonic, but ascending melodic minor is not. Depending on how the flats are added you can move through all the diatonic modes. Starting with a major scale flatten the seventh and then continue in perfect fifths.

C  D  E  F♯ G  A  B  C  Lydian

...we could start with a C Lydian scale, as above,
but for simplicity start with C Ionian, all naturals...

C  D  E  F♮ G  A  B  C  Ionian
C  D  E  F  G  A  B♭ C  Mixolydian
C  D  E♭ F  G  A  B♭ C  Dorian
C  D♭ E♭ F  G  A♭ B♭ C  Phrygian
C  D♭ E♭ F  G♭ A♭ B♭ C  Locrian

C♭ D♭ E♭ F  G♭ A♭ B♭ C♭ Lydian

...enharmonically re-spell C♭ Lydian to B Lydian...

B  C♯  D♯  E♯  F♯  G♯  A♯  B

(Theoretically you can loop through the gamut of letters endlessly in that way usings sharps to ascend and flats to descend, but you need to use double, triple, etc accidentals to keep repeating the loop. It's theoretically possible, but not practical. It ends up enharmonically repeating the same 12 things.)
The point is the various modes of the diatonic scale will remain diatonic if you apply the flats in a series of fifths. But making Super Locrian from Locrian doesn't follow that pattern of flattening by fifths, which would add the flat on the tonic and produce a Lydian scale. Instead it flattens the fourth degree, and that breaks out of the diatonic pattern creating the pattern of ascending melodic minor.
I think the reason this works in diatonic is because all the diatonic tones can be re-arranged as a series of ascending perfect fifths. Melodic minor ascending cannot be rearranged as a series of perfect fifths. You can flatten notes systematically in the diatonic scale, but it won't work that way with other scales. You may get other known scales, but not necessarily is a systematic way.

Are there modes beyond Lydian?


how to set directory permissions of windows server 2012 so Visual Basic 2015 windows app 'kill' doesn't get file permission error

Question: I have a Visual-Basic windows app that reads incoming SMTP email files from C:\inetpub\mailroot\Drop\ and then moves them renamed to C:\primary\
I've set Windows file permissions of both directories C:\inetpub\mailroot\Drop\ and C:\primary\ to "everyone" full access.
I have a 2nd VB.NET Windows app that reads each file, processes it, then deletes it using kill(filepath) which gets the error:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in Microsoft.VisualBasic.dll

Additional information: Access to the path '\\<my server>\C\Primary\email@example.com #71615 1.TXT' is denied."

The files security permissions has "everyone" full access.
How do I set file permissions for the directories to prevent this error and be safe from hacker attack and not use "everyone" permission?
Answer: SOLUTION:   Changed \\C  to just "C:".

how to set directory permissions of windows server 2012 so Visual Basic 2015 windows app ‘kill’ doesn’t get file permission error


How to redirect custom ajax form to external url with headers

Question: When setting the form with ajax handler like this
  public function buildForm(array $form, FormStateInterface $form_state) {
    //...

    $form['actions']['submit'] = array(
      //...
      '#ajax' => [
        'wrapper' => 'custom_form_wrapper',
        'callback' => '::ajaxCallback',
      ],
    );
  }

function ajaxCallback() {
  $response = new AjaxResponse();
  $url = "www.example.com";
  $response->addCommand(new \Drupal\Core\Ajax\RedirectCommand($url));
}

can I set $headers = ['custom' => 123] and pass this header to the redirected url? like we do in RedirectResponse().
So I can see this custom header in www.example.com
Answer: No, you cannot set headers in the same way as you do in RedirectResponse() when using RedirectCommand in an AJAX callback. The reason is that RedirectCommand uses JavaScript to redirect the user to the specified URL, and JavaScript does not have the ability to set headers.
If you need to pass headers to the redirected URL, you will need to do so on the server-side. One way to achieve this is to create a custom controller that handles the redirect, and then use RedirectResponse() with the headers you need. Here's an example:
Create a custom controller that handles the redirect and passes the necessary headers:
use Symfony\Component\HttpFoundation\RedirectResponse;

class MyController {
  public function redirectWithHeaders() {
    $url = 'http://www.example.com';
    $headers = [
      'custom' => 123,
    ];
    return new RedirectResponse($url, 302, $headers);
  }
}

In your AJAX callback, use Url::fromRoute() to generate the URL for your custom controller, and then use RedirectCommand to redirect the user to that URL:
use Drupal\Core\Url;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\RedirectCommand;

function ajaxCallback() {
  $response = new AjaxResponse();
  $url = Url::fromRoute('my_module.redirect_with_headers');
  $response->addCommand(new RedirectCommand($url->toString()));
  return $response;
}

Note that you will need to define a route for your custom controller in a my_module.routing.yml file. Here's an example:
my_module.redirect_with_headers:
  path: '/redirect-with-headers'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyController::redirectWithHeaders'
  requirements:
    _permission: 'access content'

Comment: Yes, using controller is the work around I have done. But there will be 2 redirects and this will affect in referrer path while getting analytics.  But excluding analytics this can be the possible way. Thanks @Vikram8888


Kotlin Firebase read child of child data

Question: Hi I have some issue with calling firebase data from the server.
I can call the single child of data but if I call a nasty child of data(ex: multiple branch of child data), It is not working on kotlin side.
I used ".child()" function on Swift side by just adding ".child()" afterward and it worked on IOS side but I do not understand why the kotlin is not working like that.
Does anyone knows how to solve this problem? I've been searching this problem many days but nobody has a clear solutionenter image description here
Comment: Can you please share you code to help you? :-)
Comment: @GSepetadelis Hi I cant put the code here. It says too long
Comment: @Dwwon Lee Please upload a photo from your database
Comment: Please edit your question and add your database structure as a JSON file. You can simply get it by clicking the Export JSON in the overflow menu (⠇) in your [Firebase Console](https://console.firebase.google.com/u/0/project/_/database/data). Please respond with @AlexMamo
Answer: Here the issue is of synchronous values, basically onDataChange is called on a different thread.. long story short try calling sectionRecyclerView.adapter line inside the for loop that or this will do the trick.
Comment: Hi so you mean that .child() fun is correct but I need to take care onDataChange in a different way right?
@Mihir Shah
Comment: @DowonLee not exactly child() is correct, the issue is that the fetching is executed in a different thread, so first try logging the values of user inside the for  loop and that will help you get the issue. Then try assigning SectionAdapter inside the for loop that will give you a better understanding of the situation.


load different methods from a single class with multiple routes in laminas mezzio

Question: I am trying to route to a single class and load different methods within that class.
Right now i can only manage to load handle() inside SearchInquiryHandler class. How can i also load loadThisMethod() inside SearchInquiryHandler from a different route. I am thinking if i can detect the routing url and with proper checking i can load loadThisMethod() from my handle() method. Any guidance will be hugely helpful.
For a single route here is routes.php
return static function (Application $app, MiddlewareFactory $factory, ContainerInterface $container) : void {

    $app->post('/api/search/inquiry', App\Handler\SearchInquiryHandler::class, 'api.search.inquiry');
}

here is my SearchInquiryHandler.php
class SearchInquiryHandler implements RequestHandlerInterface {
    protected $template = null;
    private $searchInquiry;
    private $containerName;

    public function __construct(TemplateRendererInterface $template, SearchInquiryresultForm $form, SearchInquiry $searchInquiry, $containerName) {

        $this->template = $template;
        $this->searchInquiry= $searchInquiry;
    }

    public function handle(ServerRequestInterface $request) : ResponseInterface
    {
        $result = $this->searchInquiry->setInquiryValues();
        return new HtmlResponse($this->template->render('app::search-inquiryresult', [
        'entry' => $result,
        ]));
    }

    public function loadThisMethod(ServerRequestInterface $request) : ResponseInterface
    {
        return new JsonResponse(['ack' => time()]);
    }

here is my SearchInquiryHandlerFactory.php
class SearchInquiryHandlerFactory {

    public function __invoke(ContainerInterface $container) : RequestHandlerInterface
    {
        $dependency   = $container->get(SearchInquiry::class);
        $template = $container->get(LaminasViewRenderer::class);
        $form = $container->get(SearchInquiryresultForm::class);
        return new SearchInquiryHandler($template,$form,$dependency,$container);
    }
}

here is my ConfigProvider.php
public function getDependencies() : array
{
    return [
        'invokables' => [
             ****Some Code here****
         ],
         'factories'  => [
              Handler\SearchInquiryHandler::class => Handler\SearchInquiryHandlerFactory::class,
         ],
    ];
}

Answer: Ok got it ! firstly I was not passing $request to $this->loadthismethod($request); inside handle()
Secondly if you wish to make multiple route pointing same
Class SearchInquiryHandler within handle()
you can specify the routes giving unique names
$app->post('/api/search/inquiry', App\Handler\SearchInquiryHandler::class, 'api.search.inquiry');
$app->get('/api/search/test', App\Handler\SearchInquiryHandler::class, 'api.search.test');
and inside handle() you can check routing URL and load different methods as per needs
$uri = $request->getUri();
$path = $uri->getPath();

if($path!='/api/search/inquiry'){
    return $this->postAjax($request);
}else{
    return new HtmlResponse($this->template->render('app::search-inquiryresult', [
        'entry' => $somedata,
    ]));
}

OR if you are only going to have only one http request method like GET or POST to all the methods of a single class, you can do something like this
$app->get('/api/search[/{action:inquiry|test}[/{id}]]', App\Handler\SearchInquiryHandler::class, 'api.search.inquiry',['GET']);
I am sure there are better ways to deal this


Create a rent product

Question: I'm using the Drupal Commerce module to build a Website to manage two Flats to be rented by days.
The visitor select one of the two flats and then select a date (let's say it the day: 15 January 2012) and make the payment for it.
After the payment the date of 15 January 2012 will not be available to be sold again until this day has passed (the 16 january).
I first thought of creating a product type called: Day to rent with a field called: date and then creating 365 'Day to rent' products, each one for each one of the days of the year, setting the field 'date' to the corresponding date.
Then, using the calendar module and views I would show the products in the calendar allowing the visitor to click in the 'add to cart' for the day they choose.
I'm a Newbie with the module, and I now see that I cannot get 'products' inside a view. Then, my idea fails.
Now I think that I should add the field called: date to the 'Product display' instead of the product itself, but I am not sure.
Before wasting hours, I just need to know if is there any way I can accomplish this with the commerce module.
Do I need an affiliated module? Do I need to develop a new module?
What is the best approach to do it?
Answer: Drupal Rooms module is a perfect solution to this. It is a booking and room management solution for hotels, vacation rentals and B&Bs. It integrates directly with Drupal 7 Commerce.

Create a rent product


SQLite database for Android app with potential multiple users

Question: I have an app with an SQLite database for storing information for a user's account. I designed the database on the assumption that the app would only have one user. As such, the user's ID isn't stored in the database (but it is stored in a central database on a server). However, it is possible to logout of the app and let another user log in, but the problem with this is at the moment, their data is downloaded and then appended to the other user's data. This is not what I want to happen, but I'm not sure how best to change the databse design to solve this.  I have thought about:

One database per user.  Could result in unecessary data storage if a user just logs in once on their friend's phone and never again.  Also I guess this could be hard to manage.
Add a user ID column to all tables, so appending doesn't cause a problem. Still has the unecessary data issue that (1) has, and loses 1's modularity.
Wipe the database when the user logs out.  If the user has a lot of data on the server, it will take a long time to sync the data when the application starts (this will be done on another thread, but it's still a pain).

Is one of these approaches good?  Or is there a better way to do this?
Answer: I would go for option 1. Keeping it as a separate file will ensure that there won't be any performance implication whatsoever by having multiple databases.
You can append the user ID to the database filename. You could have some sort of LRU system where you automatically delete the oldest database if you have more than 4 (or if you exceed a certain amount of data).
The specifics of this choice would be up to you, since you know how much data storage you'd like to use up, and how many users would be likely to use the app on the same device.
Comment: What is actually advantage of proposal 1 over proposal 2..? What "modularity" is lost? what "performance implications"? have somebody heard about normalisation and relation database principles? How upgrading / changing database structure will be executed for more than one database saved on device?
Comment: I like the LRU approach - I was thinking about keeping track of when they were modified but both your suggestions will be simpler to implement.  And I really doubt that more than 1 user will use the app on the same device, but you never know!  Thanks :)
Answer: That is really dependant on your requirements, however the 3rd option doesn't seem very practical.  If you wnated to do this then it's the same as uninstalling and reinstalling your app.
I would probably be more inclined to use option 2 but it depends on what you want to do within your database. e.g. if you want statistics or queries across all users rather than an individual and if there is common data that is shared between users.
If you are worried storage size then write a service that purges data belonging to any user that hasn't logged in with a certain time frame.


Example of non-uniqueness in ODEs

Question: I came across a proof that shows using the energy method that the ODE problem
$$ u - \frac{d}{dx}f(u_x) = 0;   \ \ \ \  u(0)=u(1) = 0 $$
has a unique solution if $f:\mathbb{R} \to \mathbb{R}$  is monotone increasing.
The notation here means
$$\frac{d}{dx}f(u_x) = f'(u_x)\cdot u_{xx} $$
e.g. if $f(x) = -x$, then $\frac{d}{dx}f(u_x)=-u_{xx}$
I couldn't find a decreasing function $f$ that shows that there might not be a unique solution. Is there any suggestion?
Answer: $u+u_{xx}/\pi^2=0$ has the solutions $u^{(1)}=0$ and $u^{(2)}=\sin(\pi x)$
Basically your attempt almost worked but you need to scale $f$.
(In fact, for almost all scalings of $f$ the solution is unique, as you'll learn in any course on PDE)

Example of non-uniqueness in ODEs


How to implement an example bolt with the Apache Storm javascript module?

Question: There's a javascript module/library for Apache Storm, but I don't recall seeing any examples using it. Looking at the library, I'm not sure how to implement an example BasicBolt that emits stuff. We have a custom Storm topology builder and manager, so I'm integrating and running a node.js bolt with that. I was able to get one running with the storm-node modules (https://www.npmjs.com/package/storm-node => https://github.com/STRML/storm-node, https://github.com/Lazyshot/storm-node). But I'd prefer to use the barebones main Apache Storm library if possible. I got as far as follows below. Am able to log a message to storm, but not able to emit data to the next bolt in the topology to consume. I'm thinking I am not calling the emit() function correctly. With storm-node, it was much easier to emit what I wanted. Any ideas what I'm doing wrong or missing?
<code>var ExampleBolt = require("./storm.js").BasicBolt;

ExampleBolt.prototype.process = function(tuple, done) {
    this.log("loggedamessage");
    var data = JSON.stringify(tuple.values);
    //originally tried something like this...
    //this.emit([data]);
    this.emit({'tuple':data,'anchorTupleId':tuple.values},function taskIdHandler(taskId){ return; });
    done();
};

var bolt = new ExampleBolt();
bolt.run();
</code>
And unfortunately, the storm infrastructure I'm using does not report any useful runtime errors regarding the node bolt for me to figure out the problem.
Comment: Here is an [example](https://github.com/apache/storm/blob/master/examples/storm-starter/multilang/resources/splitsentence.js) and pay attention to the storm version you are using
Comment: I am not familiar with javascript stuff, but in Java `BasicBolt` provides an collector object that is used to emit data: https://storm.apache.org/javadoc/apidocs/backtype/storm/topology/IBasicBolt.html
Answer: https://github.com/apache/storm/blob/master/examples/storm-starter/multilang/resources/splitsentence.js
is a test split sentence bolt that is used as part of our tests.  It should give you a good place to start.
Comment: i have tried this example...but i don't know how to feed input to created storm bolt. And how to submit topology in node.js to storm?


If $\sum_{n=1}^\infty a_n$ converges, prove that $\lim_{n\to \infty} (1/n) \sum_{k=1}^n ka_k = 0$.

Question: the series $a_n$ is any arbitrary converging series.
My thought process was that the $1/n$ will definitely go to zero as n approaches infinity; however, the series $k*a_k$ seems to approach infinity at the same rate. This confuses me because if both the numerator and denominator approach infinity, I think that the overall equation will equal 1, not zero.
I also considered that the sum is geometric, but I do not believe that is the case, because both $a_k$ and $k$ are variables that are not constant. I was thinking that I could argue if the series $a_k$ converges to a point, eventually the terms of the sequence will be so close to each other that it resembles a constant multiplier, but that argument is not very strong.
Any tips, hints, or leads at the solution are appreciated!
Comment: What is $\sum_{n=1}^{\infty}a_n$?
Comment: it is an arbitrary sequence that converges
Comment: And where does $x$ come in? You meant $n$ I suppose.
Comment: you're right, I'm new to MathJax
Comment: And you also meant $k*a_k$? Because $\lim_{n \to 0} a_n$ doesnt make much sense. I'm not trying to be rude, I'm just trying to understand the question so I could maybe help.
Comment: I'm so embarressed, the limit as n goes to infinity, not zero
Comment: Even with $k.a_k$, it's wrong, take $a_n = \frac{1}{n^2}$
Comment: okay, now everything seems in order, thank you for the updates!!
Answer: Let $x_n=\sum_{k=1}^n a_k$. The hypothesis is that $x_n$ converges to some $x$. Note that $\sum_{i=1}^n x_i = \sum_{k=1}^n (n-k+1)a_k$, and recall (or if necessary, prove) that if $y_n\to y$ then $$\hat y_n=\frac{1}{n}\sum_{i=1}^n y_i\to y$$
Answer: Hint: from the convergence of $\sum_{n\geq 1}a_n$, we know that the sequence $\{a_n\}_{n\geq 1}$ has bounded partial sums. We have:
$$ \frac{1}{n}\sum_{k=1}^{n} k\,a_k = \sum_{k=1}^{n}\frac{k}{n}\,a_k = \sum_{k=1}^{n} a_k - \sum_{k=1}^{n}\left(1-\frac{k}{n}\right)a_k. $$
Now apply Dirichlet's criterion to the last sum regarded as a series.
Once you know that $\frac{1}{n}\sum_{k=1}^{n} k\,a_k$ is convergent, convergence to zero follows from the dominated convergence theorem.
Comment: I'm not convinced Dirichlet is applicable here, since you do not know that $a_n \geq a_{n+1}$.
Comment: @OriaGruber: the other way. $\{a_n\}_{n\geq 1}$ has bounded partial sums and $\left(1-k/n\right)$ is decreasing to zero.
Comment: That only shows convergence - not convergence to 0.
Comment: @A.S.: once you know that convergence holds, the other part is easy.
Answer: Let $S_k = \sum_{j=1}^{k}a_j.$ We are given $S_k \to$ some $L.$ Summing by parts, we get
$$\sum_{k=1}^{n}ka_k = nS_n - \sum_{k=1}^{n-1}S_k.$$
Dividing by $n$ gives $S_n$ minus $(n-1)/n$ times the $(n-1)$st Cesaro mean of the $S_k,$ which also converges to $L.$ Our limit is therefore $L-L=0.$
Comment: You had an incorrect solution, which you deleted. I didn't see your new solution, which was posted 27 seconds before mine. I think I'll leave mine up.
Comment: Hehe, no problem.
Comment: (The solution had a typo, to be fair =) )


.preventDefault() only working on first click

Question: I have an image gallery where the image and the previous/next links under the image are repopulated using AJAX. I want to prevent the links for working here when the user has JS (so that the AJAX method is used), but only when the page is loaded the first time is this working.
This is the code that I have on the page to stop the links working -
/** Prevent the default links from working when clicking on an ajax link */
$('#attachment-body a').click(function(e){
    e.preventDefault();
});

And here is an example of one of the links -
<a href="<?php echo get_permalink($attachment->ID); ?>" title="<?php echo $attachment->post_name; ?>" rel="attachment" onclick="set_centre_image(<?php echo $attachment->ID; ?>, <?php echo $value_for_writing; ?>)">
    <img src="<?php echo $img_src[0]; ?>" />

I'm guessing that this has something to do with the elements that should have their defaults disabled being reloaded with AJAX, but if that is the case, is there a way around it. And if it is not the case, does anybody know what I am doing wrong?
Thanks.
Answer: When your elements get replaced, your click handlers get trashed. You can overcome this problem by making use of event delegation. I suggest the use of .delegate:
$('#attachment-body').delegate("a", "click", function(e){
    e.preventDefault();
});

http://api.jquery.com/delegate/
Comment: Thanks Karim, that seems to mostly work, but in IE only the first link within `#attachment-body` is not reloading the whole page. The other links are evern ignoring the `prevenDefault()` command before the content has been refreshed with AJAX. Every other browser is fine. Thanks.
Answer: Do the ajax requests add new DOM elements? If so you can try this:
$('#attachment-body a').live("click", function(e){
    e.preventDefault();
});

Comment: `attachment-body` is already on the page. It first has it's content emptied and then is repopulated with the AJAX content. However, taking your example and repeating it for every element that I wish to stop loading on seems to have work in all browsers, with the exception of one small error in IE that I am trying to fix. Thanks.


Every non-square number is given by the sequence $a(n) = n + \Big\lfloor \frac 12 + \sqrt n\Big\rfloor$

Question: Prove that every non-square number is given by the sequence $$a(n) = n + \Big\lfloor \frac 12 + \sqrt n\Big\rfloor$$ where $\lfloor x \rfloor$ represents the greatest integer less than or equal to $x$.
Attempt: Let $n$ be some natural number. Then, we know that up to $n$, there are $\Big\lfloor \sqrt{n}\Big\rfloor$ perfect squares.
That means, the $nth$ non square number will in the range greater than or equal to $n+\Big\lfloor{\sqrt{n}}\Big\rfloor$. But some of the numbers in this range might also turn out to be square numbers! The challenge would be to weed out these square numbers.
Now, for any $n:\Big\lfloor \frac 12 + \sqrt {n}\Big\rfloor$ represents the nearest integer to $\sqrt{n}$. But, still thinking how I can use this result to prove the result above.
Any hints please? Thanks!
Comment: This has been asked before: https://math.stackexchange.com/q/1079126/42969,  https://math.stackexchange.com/q/1693033/42969, https://math.stackexchange.com/q/3771037/42969, https://math.stackexchange.com/q/850483/42969 – all found [with Approach0](https://approach0.xyz/search/?q=OR%20content%3A%24a(n)%20%3D%20n%20%2B%20%5CBig%5Clfloor%20%5Cfrac%2012%20%2B%20%5Csqrt%20n%5CBig%5Crfloor%24)
Comment: "Now, for any $n:\Big\lfloor \frac 12 + \sqrt n\Big\rfloor$ represents the nearest integer to $n$." This is certainly false.
Comment: @Gary Corrected it
Answer: The sequence can only skip over an integer between $a(n)$ and $a(n+1)$ if $\Big\lfloor \frac{1}{2} + \sqrt n\Big\rfloor$ increases, i.e., there is some integer $m$ with $$\frac{1}{2} + \sqrt{n}<m\leq \frac{1}{2} +\sqrt{n+1}\text{.}$$
Subtracting $\frac{1}{2}$ and squaring gives
$$n<m^2-m+\frac{1}{4}\leq n+1\text{,}$$
whereby
$$n\leq m^2-m<n+1,$$
which implies $n=m^2-m$.
In this case, since $\sqrt{n+1}-\sqrt{n}\leq 1$ always, we also have
$$\Big\lfloor \frac{1}{2} + \sqrt n\Big\rfloor=m-1$$
and $$\Big\lfloor \frac{1}{2} + \sqrt{n+1}\Big\rfloor=m.$$
Therefore,
$$a(n)=n+\Big\lfloor \frac{1}{2} +\sqrt{n}\Big\rfloor=m^2-m+m-1 = m^2-1,$$ and $$a(n+1)=n+1+\Big\lfloor \frac{1}{2} +\sqrt{n+1}\Big\rfloor=m^2-m+1+m=m^2+1,$$
so only $m^2$ is skipped.
Therefore, since the sequence certainly increases without bound, and begins with the first non-square number $a(1)=2$, it must hit all non-square numbers.
Comment: Strictly speaking, this only proves that the sequence gives every non-square number *starting at some minimum value*. In order to verify that it gives *every* non-square number, you also need to show that $a(1) = 2$ is the smallest non-square number.
Comment: @tparker touché.


Listing key signatures

Question: I'm currently creating a program to assist with realtime sheet music display from midi input (similar to what you see on many digital piano displays).
What is the most logical way for a user to select a key? Should I just list the major keys? I understand that some keys can be expressed as sharp or flat. Which is better to list? Or should I list both?
Below is the structure I've used currently.
I'm currently targetting piano/ keyboard, if that makes any difference.
<code>const signatures =
[
  { id: 'C',  key: 'C major', sharps: [], flats: [] },
  { id: 'G',  key: 'G major', sharps: [ 'f' ], flats: [] },
  { id: 'D',  key: 'D major', sharps: [ 'f', 'c' ], flats: [] },
  { id: 'A',  key: 'A major', sharps: [ 'f', 'c', 'g' ], flats: [] },
  { id: 'E',  key: 'E major', sharps: [ 'f', 'c', 'g', 'd' ], flats: [] },
  { id: 'B',  key: 'B major', sharps: [ 'f', 'c', 'g', 'd', 'a' ], flats: [] },
  { id: 'F',  key: 'F major', sharps: [], flats: [ 'b' ] },
  { id: 'Gm',  key: 'G minor', sharps: [], flats: [ 'b', 'e' ] },
  { id: 'Cm',  key: 'C minor', sharps: [], flats: [ 'b', 'e', 'a' ] },
  { id: 'Fm',  key: 'F minor', sharps: [], flats: [ 'b', 'e', 'a', 'd' ] },
  { id: 'DfM', key: 'D-flat major', sharps: [], flats: [ 'b', 'e', 'a', 'd', 'g' ] },
  { id: 'GfM', key: 'G-flat major', sharps: [], flats: [ 'b', 'e', 'a', 'd', 'g', 'c' ] },
  { id: 'CfM', key: 'C-flat major', sharps: [], flats: [ 'b', 'e', 'a', 'd', 'g', 'c', 'f' ] },
];
</code>
Comment: The MIDI values will be the same for F# and Gb, but the notation will obviously be different since one is a sharp key and the other is a flat key. If you want to be as flexible as possible, then you should list all of the enharmonic variants. If you provided more detail in your question I think we'd be able to help you more. By the way, I'm also a programmer who develops midi-based apps (objective C for the Mac).
Comment: I'm still not entirely sure about the purpose behind all of this. You can handle it programmatically. For instance, if you have an array that stores the distance (in semitones) between each degree of a major scale, you can construct any major scale. It might look like this: `{2, 4, 5, 7, 9, 11}`.
Comment: Where are F sharp major and C sharp major, especially since C flat major is fair game in your structure?
Comment: You *must* list both sharp and flat keys. For example, whilst Gb and F# majors will sound pretty much the same - exactly in 12edo, they are deemed to be different keys.  Omitting them from the notation when they're in the key sig. is exactly how they work in real music!
Comment: Thanks @02fentym, I guess my question is: What is the most logical way to list these (for selection by a user), and store their associated sharps and flats? My goal being to ommit the sharps and flats from the notation if they are in the selected key signature.
Comment: " Should I just list the major keys?" Not if you want to be user-friendly and the user's piece is in a minor key! You could save space by pairing the major and relative minor, e.g. CM/Am. GM/Em. etc, or just let the user select the number of sharps or flats (which IIRC is all that  standard MIDI files "know" about key signatures - not whether the key is major or minor).
Comment: Thanks all. All your comments were helpful and I have used a combination of your feedback.

There are two goals of storing this information:

1) When a user selects a key signature, the relevant sharps and flats are displayed in the key signature.

2) When a user plays a key (for instance, F#), by default this would display an F with a # symbol. If we are in a key with an F#, and then we do not want to display the # symbol in the live music display.

Once I have a full working solution (still a work in progress), I'll post the source here.
Answer: This observation may or may not be helpful. I have found it useful when teaching the piano, especially to beginners, always to use seven accidentals in every key-signature. Firstly, I usually teach the player how to play a chromatic scale (because it's easy) from D to D (because it is symmetrical when played in contrary motion and both hands can be used at the same time. Most children and adults can soon work out that it also works from A flat. Most children learn C major first, but it is a difficult scale to play, particularly for smaller hands. However, pieces using two hands in the key of C can be excellent starters, especially if they utilise simple five-finger positions. I also encourage improvisation on the black keys using fingers 2 and 3 of each hand on the groups of two black keys, and fingers 2,3 and 4 on the groups of three.
So here are the main points:

C major has seven naturals. A beginner is soon able to play and name them. With knowledge of the chromatic scale, they can easily learn the simple structure of a major scale. (I introduce the naturals in the same order as the sharps: F,C,G,D,A,E,B - for fun we use a mnemonic 'Father Charles Goes Down And Ends Battle')
Every major scale has a NATURAL minor 'hidden inside' beginning on the 6th note. Whilst this is a great opportunity to begin playing with major/minor triads, there is no need to introduce harmonic or melodic variations for ages (although AB theory books and most piano examining boards do not seem to acknowledge the existence of the natural minor scale in the early grades). It is simple for the beginner to really understand the relationship between the major and relative minor scales (i.e. they are both the same, sharing the same selection of notes, and the same key-signature).
The first major scale played is C FLAT major. This is simple to play compared with C major, and the key-signature equally straightforward because all the naturals become flats. The only thing to remember is that the order is reversed when flats are used ('Battle Ends And Down Goes Charles' Father'). The reason for using C flat major is so that the basic finger patterns for playing all scales can be learned easily (i.e. 1,2,3 OR 1,2,3,4). In the right hand this scale should be learned ASCENDING first (showing the use of the next available [5th] finger to complete the final octave); the left hand should be learned DESCENDING first (showing how the final group of 1,2,3 is also completed by the next available finger [4th].
The next scale learned is C SHARP major. Again, the key-signature is easy - just convert all the naturals from C major into sharps. No need any more to change the order. This scale is as easy to play as C flat major, and provides the first opportunity to learn that although all major (and minor) scales follow the same finger pattern, it doesn't necessarily begin with the thumb [1st].
It doesn't really matter where you go after this as the main principles have been learned, but I would probably opt for F major (RH) which follows the same pattern as C flat major (LH) and where the thumb passes under the 4th finger when it is on a black key. Notice that the black keys have their own dedicated finger (see above} so Bb is still played with the 4th finger (RH) and the 2nd (LH) even though it's the only black key in the scale. The key signature is the same as it was for C flat major, but this time the first flat {Bb) is retained and the remaining six become naturals. After exploring a nice new piece in D minor (relative) it would be great to use the same transposition technique and learn F SHARP major next. Easy to play, just remember the notes are the same as F major, but everything is sharpened, including the Bb which becomes the only natural in what was the C sharp major key signature.
Eventually, all major and minor key-signatures can be covered simply, without having to resort to any weird complications (e.g. the cycle of 5ths).

I wonder if a computer program might emphasise the 'usual' key-signature in one colour (maybe jet black) and the naturals in a different colour (maybe mid-blue or grey) with an option to miss out the naturals for more advanced users.

Listing key signatures


Will unused CTE in a SQL statement be run

Question: I have a question about CTEs. You can start of a sql statement by WITH and then you can construct one or multiple CTE queries, which you then in the end can make (in this case) a select on.
My question is: will all CTE queries be executed or only the ones who are being used?
E.g.
WITH cte_1
as (
 Select * from table1
),
cte_2
as (
 Select * from table2
)
Select * from cte_1

Will this mean that a select will be executed on table1 and table2?
Comment: I would assume the early "rephrasing query phase" would automatically strip it out, but I can be wrong.
Comment: I do not think table2 will be accessed in your query. Only data will be selected form table1 since you are using it in your final/ select
Comment: A quick test.  The execution plan will ignore the 2nd cte
Comment: Everything that the optimizer is able to prove as having no effect will be eliminated. That includes not actually fetching columns from subqueries that are not required later in the chain, and removing left joins whose columns are not required and that do not change the number of rows.
Comment: You could probably construct a query that would fool the optimizer. Most of the time this shouldn't cause of problem though and unnecessary ctes will be disregarded. You also shouldn't think of it as being "executed" as any kind of discrete step in the larger query.
Answer: To complete Master Gordon's answer (I dare) :
if you declare 2 cte, and use none of them, you also get that error message
with cte as (select 1/0 as val), cte2 as (select 1/0 as val)
select 1

Msg 422 Level 16 State 4 Line 2
Common table expression defined but not used.

But if you use at least one, the statement is accepted :
with cte_divide_by_zero as (select 1/0 as val), cte_legit as (select 'it works' as val)
select * from cte_divide_by_zero

Msg 8134 Level 16 State 1 Line 1
Divide by zero error encountered.

And if you select the other CTE, it proves that your unused CTE is never executed as no error occurs :
with cte_divide_by_zero as (select 1/0 as val), cte_legit as (select 'it works' as val)
select * from cte_legit

val
--------
it works

Comment: It also works if you declare a table variable before the cte, and select from that. I imagine it'll work if you select from any other table too. Cte's are treated just like a subquery, and are joined to the outer query. If there is nothing to join to, it's an obvious error. You can't select from just a subquery
Answer: I get this message:

Msg 422 Level 16 State 4 Line 2
Common table expression defined but not used.

when running:
with cte as (select 1/0 as val)
select 1

Here is a db<>fiddle.
Comment: Interesting, it works when main query is `SELECT * FROM tab` or `OPTION (FORCE ORDER)` is applied [db<>demo](https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=ba70a62f620e23bf91625c168477f7d5)
Comment: See my further experiment gordon :)


What is the year of the Tour de France poster

Question: In the movie Triplets of Belleville there appears a Tour de France poster that is hanging near the Champion's bed (a picture from the movie that I found is this one, the poster is the one with the blue-white-red map of France). Which Tour de France had that particular poster? Where can I find the image?
Comment: This seems to be more of a movie trivia question than a sports question...
Comment: BTW there also exists [movies.SE](http://movies.stackexchange.com/).
Answer: According to IMDB:

The yellow-jerseyed leader of the Tour de France depicted in the film
  is a caricature of five-time tour winner Jacques Anquetil. It would
  appear that the year is 1957, the year of Anquetil's first win and the
  only year he participated which featured a stage finish in Marseilles.


Installing MS debug DLLs for remote debugging

Question: I have a .NET app that I would like to install on a VM for remote debugging purposes.
The app uses a native VC++ DLL which links to MFC and the MSVC runtime libraries via DLL.
When I run depends on the VM, it says that the DLL needs the following DLLs:
<code>mfc90d.dll
msvcm90d.dll
msvcp90d.dll
msvcr90d.dll
msjava.dll
</code>
Also, it reports the following error:

Error: The Side-by-Side configuration information for [dll path] contains errors.
      This application has failed to start because the application configuration is incorrect.
      Reinstalling the application may fix this problem (14001).

I'd prefer not to have to install the complete Visual Studio 2008 on the VM just to debug this.
What is the best method for installing the required DLLs onto the VM?
Answer: The debug DLLs are provided in the vc\Debug_NonRedist subdirectory.  Properly deploying them is explained in this MSDN Library article.
Comment: The easiest way is copying the DLLs right next to your app (in the same dir as the executables). No more problems :)
Comment: The link is dead. See [this learn.microsoft.com article](https://learn.microsoft.com/en-us/cpp/windows/preparing-a-test-machine-to-run-a-debug-executable).
Answer: There is/was a bug in vs2008 after the SP1 update where the manifest versions were not updated. To get around this I had to do this on the remote machine:
edit Microsoft.VC90.DebugCRT.manifest
change
version="9.0.30729.4148"
 to
version="9.0.21022.8"
edit Microsoft.VC90.DebugMFC.manifest
change
version="9.0.30729.4148"
 to
version="9.0.21022.8"
[update] In looking for a reference for this I found

Important: If you do this with Visual Studio 2008 SP1, make sure you put the following in your precompiled header:
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1

http://qualapps.blogspot.com/2008/07/visual-studio-2008-c-redistributable.html
Comment: This is probably the right answer iff you have VS2008 with SP1: Indeed your linked debugging DLLs, EXEs refer to version 9.0.21022.8 within their manifest -- instead of 9.0.3xxx. So just deploy msvcrt from your ...\Microsoft Visual Studio 9.0\VC\redist\Debug_NonRedist\x86\Microsoft.VC90.DebugCRT and edit the manifest file as explained above.
Answer: It is possible to install the debug redistributable files for VC++. Microsoft even gives them to you. You just have to stay clear of the ones found in system32 directory as they don't work by simply copying them over to another machine.
Check out this blog:
http://wdy501.blogspot.com/2010/07/dealing-with-visual-studio.html
And I used the blog to find the debug .dlls for VS 2012 and was successful in copying them over to another machine and running a debug version. Just be aware that MS puts the "debug_nonRedist" files in a directory structure labeled "Microsoft Visual Studio 11.0". Here is the full path I found the CRT debug dlls I needed:
C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\redist\Debug_NonRedist\x86\Microsoft.VC110.DebugCRT
The only benefit I see for myself in using the debug versions is that I can stay in debug mode on my developing computer and quickly take the code over to another computer for testing under a slightly different environment. I see no good reason to use a debug version in the final release.