Template override doesn't work

Question: I am trying to develop a Drupal 8 module in which I have to override the html.html.twig template. The idea is that I do not want any of the default html.html.twig template returned instead I only want the custom template returned. I have been spending hours Google hunting and trying to make sense of the many examples and I have gotten myself totally confused.
What is happening is the content of my custom template are being displayed in the default html template so I am seeing the custom content inside the default html template rather than overriding the default content.
For the sake of getting this template override working I have simplified the module as much as possible and simply want to return the contents of a variable into a placeholder in the twig template. Once this override is working I can go back and add the code that will create the correct content to be output into a number of variables in the template.
What I do not understand is exactly how to I override the html.html.twig template.
My module is called unsw_blocks and in the unsw_blocks.module I have the following
function unsw_blocks_theme() {

$theme = [
'unsw_blocks' => [
     'variables' => ['test_var' => NULL],
    ],
];

return $theme;
}

In the Unsw_blocksController.php have the following
class Unsw_blocksController extends ControllerBase {

  public function unsw_blocks($name) {
  return [
    '#theme' => 'unsw_blocks',
    '#test_var' => $this->t('The variable called test_var simply passes this text itself to the theme template'),
  ];
  }
}

In the custom modules templates directory I have unsw-blocks.html.twig which simply contains

Testing Template

test_var: {{ test_var }}

Answer: HI please follow the below steps.
Step 1: create routing file
docroot\modules\custom\product\product.routing.yml
product.custom_form:
  path: '/product/details/{product}'
  defaults:
    _controller: '\Drupal\product\Controller\ProductDetailsController::details'
    _title: 'Product Details'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      product:
        type: entity:node

Step 2: Create a controller: modules\custom\product\src\Controller\ProductDetailsController.php
   /**
   * Callback for route product.custom_form.
   */
  public function details($product)

    return [
      '#theme' => 'product-details',
      '#content' => [
        '#contextual_links' => [
          'node' => [
            'route_parameters' => ['node' => $product->id()],
          ],
        ],
      ],
      '#product' => $product,

    ];
  }

Step 3: In your theme create a file following the directory themes\custom\mytheme\templates\product-details.html.twig

{{ product.title.value }}

            {% if product.field_title_description %}
                {{ product.field_title_description.value }}
            {% endif %}

Answer: AFAIK you can't override html.twig in a module, but you can create module with a route and a controller that returns a Symfony response to bypass this limitation. There is background-information and a code example in this question:
Override html.twig.html within custom module

Template override doesn't work


Content Types and the db tables they create

Question: I'm creating an application where I want a content type with quite a few extra fields.
When I try and retrieve this type programatically the DB is showing that each of the extra fields are stored in their own table. This is fine I guess but will mean my queries/views will be quite long and any changes to the fields via the admin console will require a bit of back end work.
Is this just a price I have to pay or is there another option?
If possible I want to be able to administer the fields as normal (changing their names say and maybe adding new ones) and not have this affect my code too much - so in essence I want my cake and eat it!
As always, thanks again...
(drupal-7.14 Lamp)
Answer: You can use views to create the queries for you so you can easily change your views in the back-office without the need of messing with custom code.
Or if you want to write the views yourself use the EntityFieldQuery class to create custom views without writing joins yourself because this is defenitivly not the way to do it.
You can load the full node object programmaticly by using node_load() and filter the fields you need. This loads the full node object so this can slow down the system when loading lots of nodes using node_load_multiple().
And finally if you think this isn't straightforward enough consider writing your own entity where you can add all fields inside your custom table(s) and get the entity data with simple queries.
When using the views module you can add your entity to the views data by using hook_views_data. There is also the possibility of adding fields to your entity so this opens a lot of opportunities if really needed. It's a bit of extra work to install, especially the first time u use entities so you have to see if the budget allows room for testing and debugging.
An introduction to entities
Comment: Many thanks for the speedy and considered reply Jurgen. Better get my gloves off and start exloring these options.


Representative transaction KPIs - what method to chose (average, median...) / how?

Question: In my dataset i have about 30k of transactional data. For analysis, I want to show the end user some important KPIs:

Average of transactions with loyalty cards
Average turnover of these transactions

The problem is, with a simple average i get "1,43..." as the result. The median of the dataset is 4. The highest number is 230, "normal" values are 10-20 transactions, most of them are 1-5.
Now i look for a solution for this problem. What would be the best to show the user a "representative" value for the average loyalty card transactions?
Answer: The Average is a good measure when a dataset contains values that are relatively evenly spread with exceptionally NO high or low values.
You can use 'Median' if you find extreme values in your dataset. It ignores the extreme values (outliers).
You may want to plot a histogram / box plot to check for outliers and decide which one to use.
For more understanding please refer this link. Hope this helps !


How is Beethoven able to make so many sudden shifts in key?

Question: I know of 2 very common modulations that classical music composers of all ages have done. Those 2 are relative modulation and parallel modulation respectively. I myself have done those and I see both of these types of major/minor shifts in Beethoven's music all the time. Even his fifth symphony which for the first movement mostly stays in C minor, has both the parallel and relative major in it. But there are some other modulations that I hear in Beethoven all the time that I likely would not hear in Chopin, Mozart, or even Schubert, at least not often. The Pathetique Sonata is a good example of one of them.
Here is the modulation sequence of the Pathetique Sonata up to the development section:
Cm -> Eb -> Gm -> Em
That last one, the only way I could really describe it besides a direct modulation is modulating to the relative minor of the parallel major. It has both a relative modulation and parallel modulation but they occur simultaneously. The reason I hear it this way primarily has to do with all the B naturals at the end of the G minor section.
But there is one Beethoven piece which tops that in terms of the number of direct modulations and is even more famous. That of course being his ninth symphony. Just in the first movement alone there are shifts back and forth between these 4 keys:

D minor
F major
Bb major
C minor

D minor to F is very common. D minor to Bb is much less common. Even less commonly I hear Bb modulating to C minor directly and there are several moments in the symphony where there is a direct modulation between Bb major and C minor. And of course, in other movements there is modulation to D major as well. That is at least 4 different modulations, only 2 of which are expected modulations(the relative and parallel respectively).
Now I think the reason he is able to make all those direct modulations in his ninth symphony is because he is dealing with a large orchestra and modulations in an orchestra tend to sound smooth, almost as if they are expected, even when they aren't. Conversely, if I were to modulate from D minor to C minor and have it sound smooth, this is probably what I would do for a piano solo work:
D minor -> G minor -> C minor
Or have the melody change key while the harmony stays the same until I reach  C minor at which point, I have the harmonic change occur. I have done that melodic change before and it works as long as you aren't modulating to a key that has an altered version of the original tonic. So this would work equally well for going to F# minor or even to A major. But it wouldn't work for Ab major or E major unless I had a second harmonic change, at which point I have covered every key in the circle of fifths.
But why is Beethoven able to make these surprising direct modulations in his piano sonatas and other works besides his symphonies and have it all sound as though it was expected?
Comment: I know. I have even seen and heard piano solo versions of those symphonies transcribed by Liszt. I have even tried learning the Liszt transcription of Beethoven's fifth symphony.
Comment: Have you figured out whether Beethoven uses pivot chords at these modulation points? (IMO, the Gm-to-Em shift in the 1st movement of the Pathetique Sonata is **not expected** but probably uses a pivot chord.)
Comment: I think Beethoven could have made what ever he liked ... after he is accepted as one of the greatest composers the audience had 200 years to get adapted to any of his caprioles :)  Couldn't one answer be: we expect what we are used to expect what Beethoven will do?
Comment: I haven't yet figured out if he uses pivot chords to make these sudden modulations. It would be easy to figure that out for the Pathetique Sonata though. But with all the staves of an orchestral work, it becomes much harder to see the harmony underlying those melodies and countermelodies, and thus harder to know how Beethoven.made all those modulations in his ninth symphony.
Comment: for your latter concern there are four hand piano editions of Beethoven symphonies .
Comment: I hope to see some good answers; this is a question I'm curious about.
Comment: Well for the Pathetique Sonata at least, I think I have figured out how Beethoven is able to go from Gm to Em. It all has to do with one chord. And this chord actually appears twice in the G minor section. This being F#dim7 with the D# enharmonically spelt as Eb to fit with the 3 flats key signature, the vii°7 of G minor and the ii°7 of E minor respectively.
Answer:
D minor to F is very common. D minor to Bb is much less common. Even less commonly I hear Bb modulating to C minor directly and there are several moments in the symphony where there is a direct modulation between Bb major and C minor. And of course, in other movements there is modulation to D major as well.

All of those combinations differ only by one flat in the key signatures. By that measure they are closely related keys. Not sure about the change to D major, but from your description it would seem to be a parallel key change referring back to the D minor.
About the Pathetique and Gm to Em. Disregard the technical details of the harmony mm. 132-135 which takes us to the dominant of Em, and think about the expression markings. It goes from grave to allegro molto e con brio. The whole point is a dramatic change in expression! Moving to a distant key is part of creating the expressive effect.
The treatment of modulations whether smoothed out with pivot chords or direct, or whether to closely related or distant keys, is all a matter of how the composer wants the modulation to be felt. Beethoven and the Romantics that followed him wanted their music to have a different dramatic impact that the music of someone like Haydn and their modulations reflect that.
Answer: Beethoven's aim wasn't to be smooth, it was to be dramatic.  He exploited the fact that music could go ANYWHERE!   As @Divide1918 said, one of his favourite tools was the diminished 7th chord, which can act as a dominant leading to four different keys.  Every note in a dim7 can act as a leading note.
Whole books have been written on the subject.  Here's one. (You can click through to the download without signing up.  They're not trying to fool you.)
https://www.researchgate.net/publication/324656635_Modulation_in_Beethoven's_sonatas
Answer: In Pathetique sonata first movement bar 134, Beethoven wrote an F#dim7/C resolving to the first inversion of Gm. The next bar is almost identical, except the F#dim/C is spelled a little differently: The top note E flat is now notated as D sharp, which makes the chord, in some sense, the third inversion of D#dim7. Beethoven then "naturally" resolves this to Em, thus modulating into E minor.


linode centos 7 firewalld change-interface command failed

Question: I just build centos7, and tried to setup firewalld, when I type command
firewall-cmd --zone=internal --change-interface=eth0

I got error : Error: COMMAND_FAILED
I already start it by
systemctl start firewalld.service

and firewall-cmd --state it's running
I don't know why ? and I can't find how to solve it ...
is there anything wrong with this centos version or do I miss something??
I don't see any command before , related  this firewalld setup error, list all:
yum update

update gcc
yum install centos-release-scl
yum install devtoolset-3-toolchain
scl enable devtoolset-3 bash

install nginx
yum install epel-release
yum install nginx
systemctl start nginx
systemctl enable nginx

install postgres
yum install https://download.postgresql.org/pub/repos/yum/9.5/redhat/rhel-7-x86_64/pgdg-centos95-9.5-2.noarch.rpm
yum install postgresql95-server postgresql95
/usr/pgsql-9.5/bin/postgresql95-setup initdb
systemctl start postgresql-9.5.service
systemctl enable postgresql-9.5.service

install mongodb
...

install nodejs
...

firewalld
systemctl start firewalld.service
systemctl enable firewalld.service

firewall-cmd --zone=internal --change-interface=eth0

UPDATE
after I tried firewald reload  , I can't use ssh connect now,
ssh: connect to host ... port 22: Connection refused

how to connect and fix firewalld ??
Answer: To reconnect to your server, you can go to "Remote Access" tab on your linode machine, and go to "Launch Lish Console",
Please check this issue looks similar to yours, as linode's kernel mismatch the firewall required modules,
Comment: thanks for reply I login success, stop and disable firewalld. I read that post before, and I tried `yum install kernel` it shows already installed, nothing happen, still same error ...
Answer: You have a few questions to answer. Seems like you followed a tutorial and did not get everything right.

Are you sure the name of your interface is eth0 . Find out.
As suggested go to Linode's Networking tab in the management portal and launch lish for remote access. This is like KVM so even if you an't SSH you can directly access the terminal.
unless you specify --permanent parameter to your firewall-cmd it is not really permanent. Restarting the firewall will reset to original defaults.
Check your existing rules with firewall-cmd --list-all-zones Some basic ports are unblocked usually
optionally alias the firewall-cmd to something short. Looks like you will be using a lot of it :)
Comment: Thanks for reply, - I tried find out eth0, it is.  - I login via lish, stop and disable firewalld, then I can use ssh login now.  - I still don't know why got error, I paste all command I type in question, and it's new disk (I also tried rebuld and do it again, got same result) . The weird thing is I did this couple month ago in another I canceled linode account, and it works.


How to make a mini amp sound like rock (distorted/ overdrive)

Question: I'm a beginner and have been getting some trouble with my mini amp. It's the borne strike g30 (brazilian brand) and its settings are: a drive switch (which honestly just seems to be making the volume louder) gain, bass, treble and volume. I've been messing around with them but can't seem to get a nice distorted sound (especially without a mid knob). Can I alter something on my amp instead of buying pedals?  Thanks!
Comment: Distortion usually relies on nonlinear amplification (so if we double the level of the input the output is less than doubled). This then distorts the waveform. Usually that behaves in such a way that the behaviour is less linear the higher your input level is. So to get high distortion you need a high input level. This is then what the gain control is for.

Basically there is another amplifier at the beginning that allows you to effectively increase the input level.
Comment: Thus you should probably start by activating drive and turning the gain control all the way up. If this does not give you a satisfying amount of distortion then probably something is broken (as this is the most that is possible). If this does give you a decent amount of distortion continue by lowering the gain control until you get the amount if distortion you want.
Comment: Hi Marcela V, welcome to the site. You have two interesting questions here, but please open them separately. One of the site conventions is to have only one question per post.
Comment: Perfect. One other suggestion: consider removing your age from the other post. It's enough just to say you don't know how to deal with electrical wiring issues. There's no rule in that regard, just a safety precaution, since your age doesn't affect the problem or the solutions.
Comment: Hello Marcela, for troubleshooting it would be preferable to use chat, but SE does not allow one to talk in chat under 20 reputation. So this has to somehow do. The bass/treble control probable go two way (boost and shelf), so the neutral position is probably at 5. Try to work from that position.
Comment: Also make sure that the signal output from the guitar is not extremely low (which would be if you need to turn up the volume switch very high to hear something). If it is very low, check if the volume control is turned down, or on an active instrument if the battery is empty.
Answer: Well, I wouldn't expect too much from a basic small amplifier... but the steps should be the following:

make sure you set volume and tone knobs on the guitar to the maximum setting
press the drive button on the amplifier
turn up the gain knob on the amp. Don't be afraid to go to maximum
adjust the volume with volume knob on the amplifier
adjust the tone with bass/treble knobs on the amplifier

In the amp there is some component that operates linearly in some range, which results in clean tone, and non-linearly for larger signals, resulting in overdriven sound. This is why you need large input signaln for overdrive. The gain knob adjusts volume of the signal coming into the amp. Overdrive won't occur if the input signal is too low.
Most amplifiers and overdrive/distortion pedals have quite large range of gain adjustments. This video shows a blues tone with just 1/4 of the gain knob setting in the amp:

I guess you can get more rock-style overdrive with higher settings.


Continous Parent and Discrete Child Conditional with Observed Data in PyMC

Question: I am new to PyMC and trying to set up the simple conditional probability model: P(has_diabetes|bmi, race).  Race can take on 5 discrete values encoded as 0-4 and BMI can take on a non-zero positive real number.  So far I have the parent variables setup like this:
p_race = [0.009149232914923292,
          0.15656903765690378,
          0.019637377963737795,
          0.013947001394700141,
          0.800697350069735]
race = pymc.Categorical('race', p_race)

bmi_alpha = pymc.Exponential('bmi_alpha', 1)
bmi_beta = pymc.Exponential('bmi_beta', 1)
bmi = pymc.Gamma('bmi', bmi_alpha, bmi_beta, value=bmis, observed=True)

I have observed data that looks like:

| bmi | race | has_diabetes |
  |      21.7 |    1 |            0 |
  |      45.3 |    4 |            1 |
  |      18.9 |    2 |            0 |
  |      26.6 |    0 |            0 |
  |      35.1 |    4 |            0 |

I am attempting to model has_diabetes as:
has_diabetes = pymc.Bernoulli('has_diabetes', p_diabetes, value=data, observed=True)

My problem is that I am not sure how to construct the p_diabetes function since it is dependent on the values of race and and the continuous value of bmi.
Answer: You need to construct a deterministic function that generates p_diabetes as a function of your predictors. The safest way to do this is via a logit-linear transformation. For example:
intercept = pymc.Normal('intercept', 0, 0.01, value=0)
beta_race = pymc.Normal('beta_race', 0, 0.01, value=np.zeros(4))
beta_bmi = pymc.Normal('beta_bmi', 0, 0.01, value=0)

@pymc.deterministic
def p_diabetes(b0=intercept, b1=beta_race, b2=beta_bmi):

    # Prepend a zero for baseline
    b1 = np.append(0, b1)

    # Logit-linear model
    return pymc.invlogit(b0 + b1[race] + b2*bmi)

I would make the baseline race be the largest group (it is assumed to be index 0 in this example).
Actually, its not clear what the first part of the model above is for, specifically, why you are building models for the predictors, but perhaps I am missing something.
Comment: Thanks for the response. I do have a quick question about the logit-linear model.  Why have a baseline race instead of having the race linear factor be sampled from a normal, i.e. have  `beta_race = pymc.Normal('beta_race', 0, 0.01, value=np.zeros(5))`
Comment: That is an alternative parameterization. Its true, you can simply have a separate intercept for each race, and this works well if the counts within each racial group are similar. Often, one race is considerably more frequent than others, in which case my parameterization tends to work better.


How do I keep Centos at version 6.3?

Question: I have the following:

Bunch of guest VM's that are running Centos 6.3
Host running Centos 6.3.
Recently I created a new Centos 6.3 VM to test out something
Ran yum update after a fresh install of a minimal server
Noticed Centos is now at 6.4

I would like to keep the version unchanged as I understand that untested changes have the ability to introduce instability (I'm learning server admin/Centos so that I can develop my own applications that automate various 'needs', one such need is to download data, another is to perform analysis on the downloaded data, and yet another need is to execute certain actions based on the analysis).
I'm in the Dev phase of Dev -> Test -> Prod with respect to implementing what I'm doing, so up-time and stability isn't "necessary" at this stage, however, I would like to ensure I've done all I can to ensure up-time/stability will be solid when time does come to have a Prod environment. So, I would like to keep my guest and host KM's running 6.3 until I decide that an upgrade is necessary and/or provides significant benefit(s).
A few questions:

How do I prevent automatic upgrades from occurring to versions of the server OS when performing yum update?
Is there a "standard" location on the internet for finding what changes occur in a version upgrade?
Am I being paranoid about server version changes with respect to stability?
Comment: "untested changes have the ability to introduce instability" You know what else introduces instability? Un-patched vulnerabilities and aging/outdated software. :)
Comment: You're being _way_ overly paranoid.
Comment: First, it's not a major upgrade, more like a service pack. Second, if you go down this road, your systems will be running 6.3 ten years from now, about seven years after they should have gotten an _actual_ major upgrade....
Comment: You're not necessarily being overly paranoid.  I just lost a day trying to install vendor software that requires specifically 6.3, because `yum update` moved me to 6.4.  I blame the vendor, but CentOS is what I can control for now.
Comment: Ironically, I just spent an hour this evening fixing a broken CentOS 6.3 box that was broken precisely _because_ someone attempted to prevent the system from being updated. By naively blacklisting `kernel*`, which has a lot of nasty side effects...
Comment: @MichaelHampton Why?
Comment: If you want to keep the packages you use at a particular version, you'll need to build a stack that has localized or contained builds of those packages. That way the stack always uses its own version of say... Java or some other library, and doesn't rely on what the system has. However... this is hard to maintain, and updates to things like the kernel or drivers may break it.
Comment: Just upgrade and face any problems before rather than after.
Comment: Thank you very much all for your comments, you've taught me a lot in just a short space of time.
Answer: yum --releasever=6.3 update

will stick to 6.3 repo.
Comment: +1 for a direct answer, even if it's not recommended to do so...
Answer:
How do I prevent automatic upgrades from occurring to versions of the server OS when performing yum update?

The upgrade from CentOS 6.3 to CentOS 6.4 is a point release. As the link says

Old point releases are never supported. If you want/need to "freeze" at an old point release you are on your own.

What this means is that if you want to stick at C6.3 then no updates will be provided so what you might as well do is disable all the yum repositories. You can do this by adding enabled=0 (or changing the enabled=1 to 0) to each of the [...] sections of the files in /etc/yum.repos.d.
This is a really bad idea. You're on your own. You don't get bug fixes, backported security fixes and updates etc.; you lose your herd immunity.

Is there a "standard" location on the internet for finding what changes occur in a version upgrade?

You can subscribe to the CentOS Announce mailing list which will provide you with a list of updates. The answer to this question is relevant here too. You can check the Centos release notes pages.

Am I being paranoid about server version changes with respect to stability?

No, like all software systems operating systems have their bugs and vulnerabilities. Just like any other piece of software you should evaluate and test proposed changes in your environment before deploying them to your production systems.
You need to evaluate the risks of 'fixing' your OS version and receiving no updates (which over time leaves you open to increased numbers of vulnerabilities) against the risks of updating via a testing process to ensure that nothing breaks when an update is applied.
Comment: Excellent answer, thank you very much for providing the information on how to freeze, and also clarifying why things should/should not be done. Very clear.
Comment: -1 from me... You didn't answer his first question directly nor clearly. He didn't ask if he should do it or not and why, he asked how to do it. The next answer is the best one, but yours explain why you should "not" do it. Still, some companies will still want to lock a system to a certain point release even it's a bad idea, so giving a straight answer is always appreciated despite the reason behind the question.
Comment: Thanks for leaving the comment, I wouldn't have noticed otherwise. I'll carry in not caring too if you don't mind.
Comment: Down-voting an answer without commenting on why is rude and against the site's code of conduct, which is why I explained. Feel free to care or not, no harm intended.
Comment: None taken. It's not against the code of conduct BTW. There is no requirement to explain a DV only a request that you consider doing so. And this has been CW for a long time so I really wouldn't have known with out the comment.
Answer: For CentOS 7.x, the yum --releasever=X update method does not seem to (always) work. This is what I had to do instead:
Stick to version

Check http://vault.centos.org/ for available versions (eg: 7.3.1611)
Edit /etc/yum.repos.d/CentOS-Vault.repo so that it includes a full set of repo definitions for the chosen version (7.3.1611 in our case). You should have 5 repos named [C7.3.1611-X].
Disable all CentOS repos: yum-config-manager -v --disable CentOS\*
Enable the 7.3 repos you added: yum-config-manager --enable C7.3\*
yum update

Obviously this will prevent any security updates.
Unstick

yum-config-manager --disable C7.3*
yum-config-manager  --enable base

(YMMV with these instructions depending on what was disabled above)
Comment: I would comment instead as that makes more sense, but my "reputation" doesn't allow for it. I agree with the above answer re: CentOS 7.x, but I suspect that the reason that --relasever doesn't work is that most installations use a "mirrorlist", which does not support using a minor version (if you feed it into the mirrorlist URL, you get an error). I was able to use mirrors.centos.org instead of vault.centos.org, however, just so long as I did not try to use a mirrorlist.
Comment: This is the correct answer for CentOS 7. I recently encountered a pango ABI incompatibility issue so that I need an old version of pango from CentOS 7.4, instead of the current 7.6 version. Enabling CentOS Vault and downgrade from it fixed my issue.

How do I keep Centos at version 6.3?


Questions about ModelViewPreseneter pattern

Question: Lately I've been studying mvp design pattern and have some questions about it:

I've read that it's recommended to not use this design in simple applications. So I'd like to know when an application can be marked as "simple"?:
a) Based on what we meassure coplexity of an application?
b) How can we be sure that developed application will be still simple in the future (Especially due to the agile development when the application can grow unpredictably)

Should business logic sit in the presenter? Or business logic should be a concern/responsibility of a different part of a solution?

Is model something that is also implemented (module, class) or it's only an abstraction for a real world data storage (DB, disk) we get data from?
Answer:
MVC is a standard pattern used in most technologies out the box, in .net as an example it would be hard to get away from using MVC. In my opinion all applications should be built with some framework at it's core this one of those thing to always implement.

Most applications (bottom up stack) are the Database / Data Access (Models/Business Logic) / Controllers / Presentation
The Presentation could be anything, mobile app, website, integrated app and should interact with an API (or controllers) that should be as light weight as possible that call the data/access or logic beneath.

The term models can use for various things but there are two main areas where "models" are  found, the models that represent data related to data access, ie models that represent tables or stored objects used in the data access side or models that are used on the front end to present specific data based on views/behaviour on the front end; ViewModels or Models (DTO objects) exposed via the API/controllers.


Where Clause operator expected Linq

Question: Hi guys I have a linq query as you can see below but my code give error like  ')' or operator expected  what is wrong with me?![This is my code][1]
https://i.stack.imgur.com/SsPQf.png
And also my query builder this code
string query = "";
foreach (var bud in budget)
{
    if (budget.Count >= 1)
    {
        if (bud == "1")
        {
            if (budget.Count>1)
            {
                query = "(Budget Between 20000 and 34999 ";
            }
            else
            {
                query = "( Budget Between 20000 and 34999 )";
            }
         }
     }
}

Comment: You should post your code, not a link to an image of your code.
Comment: Your question is describing a compile time error, yet the image you posted is of code running in the debugger.  For it to be running, it would have had to have compiled successfully.
Comment: well I add my code completely
Answer: The argument passed to the Where() method cannot be a string, it must be a Func<TSource, Boolean>. Your method that generates the query will need to be defined as:
Expression<Func<Car, bool>> query = null;

Then whenever you want to set the value of query you would set it using:
query = car => car.Budget >= 20000 && car.Budget <= 34999;

Now you can use the query variable in your Where() method call.

Where Clause operator expected Linq


Term reference field - print as other format

Question: I'm using term reference field, which is displaying as entity.
I want to print this in the other place of node.tpl, not full entity but only names.
Is this possible?
I've tried
<?php print render($content['event_speakers']['und'][0]['value']); ?>

But it doesn't print anything
Comment: use dpm($content) in your file then check which value you want to display add this field in your file
Comment: It just shows field collection item #markup with code from my .tpl file, with names already printed.
Answer: EDIT: I didn't completely get your question initially. To do this you will need to fetch the term names yourself, and make them available to your node template file. This means you'll have to use hook_preprocess_node() implementation.
Here's the code you'd use:
function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['node']->type == 'YOUR_CONTENT_TYPE' && isset($variables['node']->field_event_speakers[LANGUAGE_NONE][0]['tid'])) {
    $event_speakers = array();
    foreach ($variables['node']->field_event_speakers[LANGUAGE_NONE] as $event_speaker) {
      $term = taxonomy_term_load($event_speakers['tid']);
      // Just to display the name:
      $event_speakers[] = $term->name;
      // To display linked name instead, use this:
      // $event_speakers[] = l($term->name, 'taxonomy/term/' . $term->tid);
    }
    // This will separate names with a comma, and a space.
    $variables['event_speakers'] = implode(', ', $event_speakers);
  }
}

You can then use this as many times as you want in the template; example:

<?php print $event_speakers; ?>

<?php print $event_speakers; ?>

Comment: It doesn't print anything sir :(
Comment: My bad; you need to pass different argument to the `render()` function; check the code now, I updated the answer.
Comment: It's printing the whole term reference entity. I just need the names of it.
Comment: Updated. I think I got what you were asking for now.


jquery how to print array value by key

Question: I have array for exchange rate currencies:
var mainCCexArr = [{EUR: 0.80 , GBP: 3.50}];

how do i alert array value by key?
for instant - i need value for key "GBP" -> 3.5
Can i do it without array LOOP (for, while, etc) ?
HTML:
<select name="def_cc">
    <option value="GBP">UK</option>
    <option value="USD">USD Dollar</option>
</select>

I tries this:
  var def_cc_code = $('select[name="def_cc"] option:selected').val();
  var ex_cc = mainCCexArr[def_cc_code].value;

  alert("ex_cc: " + ex_cc);

Thank you in advance
Comment: Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) or https://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string (or any of the other linked questions)
Comment: You currently (see what I did there) have an "array" with only one entry - are there more entries in the array?   Are you trying to get out just GBP for the first entry?    Is there a reason you can't use *any* form of loop (eg `.map()` can be considered a loop).  Did you mean for it to be in an array?  Can you provide a more detailed example with other array entries and what you want out when there's more entries?
Comment: `var ex_cc = mainCCexArr[0][def_cc_code]` - of course, it will only work if you match the keys (`"GBP" !== "GPB"`) https://jsfiddle.net/de4bnks8/
Comment: @freedomn-m - i see what you did, and it's working in your example, but in mine i have a little change and it doesn't works. `var def_cc_code = $('select[name="def_cc"] option:selected').val();`
Comment: Works fine: https://jsfiddle.net/sg1ahmet/2/  of course I had to add USD to the array
Answer:

var mainCCexArr = {USD: 0.80 , GBP: 3.50};
$('select').on('change', function(){
  var select_val = $(this).val();
  alert(mainCCexArr[select_val]);
});

<select name="def_cc">
    <option value="">Select Value</option>
    <option value="GBP">UK</option>
    <option value="USD">USD Dollar</option>
</select>

jquery how to print array value by key


Generating Radiobutton grid menu from an Array in Tkinter, Python

Question: Edit: Sorry I can't answer my own post since I'm new but I figured it out: If you remove the line "tki.Button(master,..." (2nd to last code line), then the code runs perfectly fine. I guess the grid and the button don't work the way I put it.
sorry to bother but I'm having a little trouble figuring out what's off here. Basically I have an array that I want to loop through and set each of the values as a radiobutton IN A GRID. Later I'm going to loop through several arrays to generate a larger grid menu, but I can probably figure that out once I get this first loop working.
Here is my code:
import Tkinter as tki

master = tki.Tk()
frm = tki.Frame(master, bd = 16, relief = "sunken")
frm.grid()

tType = tki.StringVar()
tColumn = tki.IntVar()
tRow = tki.IntVar()
compType = ["iMac ", "Mac Mini ", "Mac Pro ", "Macbook ", "Macbook Air ", "Macbook Pro "]
tColumn.set(0)
tRow.set(0)

def radioCreate(typeArray):
    for t in typeArray:
        b = tki.Radiobutton(frm, text = t, variable = tType)
        b.config(indicatoron = 0, bd = 4, width = 16, value = t)
        b.grid(row = tRow.get(), column = tColumn.get())
        tRow.set((tRow.get() + 1))  #increment tRow for next run-through

def p():
    print tType.get()

radioCreate(compType)
tki.Button(master, command = p, text = "Display").pack()

master.mainloop()

Now remember, I'm trying to get this working in a grid, because I'm going to populate other columns with other data from different arrays.
Answer: The problem is i. These two lines:
frm.grid()
...
tki.Button(...).pack()

While it's perfectly acceptable to use pack and grid in the same application, you can't use them on two widgets that share the same master.
Grid will potentially change the size of a widget or its master depending on its options. Pack will notice the change, and may itself try to resize one or more widgets and/or the master based on its options. Grid will notice the change, and may resize... Pack will notice the change and resize, ...


How do I solve this inequality $126-21x < 112-16x$?

Question: How do I solve this inequality $126-21x < 112-16x$?
If there were this sign $=$ , I would be able to solve it easily. But I am not able to do it because there is $<$. How can I find the value of $x$? Please help.
Comment: Re: answerers: How many ways to say $x \gt \frac {14}{5}$.  This is not the kind of question that warrants five answers saying pretty much the same thing, and I see many of you, due to your invested interested of gaining rep, upvoted the question.
Comment: Bring the $21x$ to the RHS, the $112$ to the LHS, divide. As a caution (not a problem here), always watch dividing/multiplying by a negative when solving these as it swaps the inequality direction. Now, resolve it by bringing the $16x$ to the LHS.
Comment: Operations on inequalities work similar to the operations on equalities. You only need to be careful, when multiplying or deviding by something negative. Then the inequality sign must be switched.
For example:
$3>1$ but $-3<-1$ (here I multiplied by $-1$).
Comment: You have correctly realized that this *thing* has $<$ instead of $=$. Hence this *thing* is called an inequation instead of an equation. Just for terminology sake.
Comment: What properties about inequality do you know?
Comment: In general, it is advised to [provide some context](http://meta.math.stackexchange.com/questions/9959/how-to-ask-a-good-question/9960#9960) for the question. If you do not have other idea how to add context, showing your own work or what you know what be probably enough. Since you wrote you can solve $$126-21x = 112-16x$, I suppose adding the solution of this equation would not be too much work for you. And I guess you would not get that many downvotes and close votes, if you had done that.
Answer: This is an inequality. Instead of just solving it for one value of $x$ (like what you would do if you had an "$=$" sign, we solve for any value of $x$ that makes the statement given true.). We can solve this almost like an equation. There are only a couple caveats:
$$
126-21x < 112-16x\iff 126<112-16x+21x\iff 126-112<5x\\
\iff 14<5x\iff \frac{14}{5}< x
$$
So, we now know that any value of $x$ greater than $\frac{14}{5}$ will make the inequality true.
For example, $x=6$, we have $126-21\cdot 6=126-126=0$ for the left hand side and $112-16\cdot 6=112-96=16$ for the right hand side which is indeed greater than the left hand side. You could also check this for $x=5,7, 5.5, 5.1, 100, etc.$.
The caveat that I mentioned above is if we have something like $$-5x<10$$
Then, when we divide by a negative number, we have to "flip" the inequality sign like so: $$-5x<10\iff x> -2$$
You should think about why this is and it may help to have a number line nearby if you're not too familiar with this. Also, this is true for multiplication by negative numbers (multiplication and division are practically the same thing).
Comment: If you use left-to-right implications, you show only that *if* there is a solution $x$, then $x>\frac{14}{5}$. To show that *every* $x$ with $x>\frac{14}{5}$ is a solution, you need the right-to-left implications (of course, these hold as well in this case).
Comment: @Uwe Feel free to edit it. I didn't mean the implications as strictly "if"'s, but just as "here is the next step". Of course, technically, you're correct Thank you
Answer: This equation can be solved for $x$ using rules you already learnt for elementary algebra.
We have: $126-21x<112-16x\Leftrightarrow 126<112+5x$
$\hspace{61 mm}\Leftrightarrow 14<5x$
$\hspace{61 mm}\Leftrightarrow \dfrac{14}{5}<x$
It's conventional to express equations with the variable on the left-hand side.
We just flip the direction of the inequality:
$\hspace{61 mm}\Leftrightarrow x>\dfrac{14}{5}$
Therefore, the solution to the equation is $x>\dfrac{14}{5}$.
Comment: You should use equivalence arrows, not just implication arrows.
Answer: You can handle these inequalities pretty much like equalities, except that when you multiply or divide both sides by a negative number, the direction of the operator flips, e.g. from $<$ to $>$.
\begin{align}
126 - 21 x &< 112 - 16 x \iff \\
126 &< 112 - 16 x + 21 x = 112 + 5 x \iff \\
126 - 112 = 14 &< 5 x \iff \\
14/5 &< x
\end{align}
Answer: $126-21x\lt 112-16x$
$\implies 14\lt 5x$
$\implies x\gt \frac{14}{5}$
so all values grater than $\frac{14}{5}$ are the solutions of given inequality
Comment: That's the third answer within 25 minutes that gets the implication arrows wrong (see @anonymaker000010001 and @TazwarSikder).
Answer: You could treat it as an equation and solve it for $x$. Afterwards try something smaller or something bigger than your solution (best try would be $0$).
The solution of the inequality then are all numbers smaller or bigger than $x$ according to which gave you a true result for your original inequality.
e.g. $52 - 3x < 10 +4x$.
Treat it as an equation: $52-3x=10+4x$ and get $x=6$. Try something smaller $x=0$:
$$52-3\cdot 0 = 52 < 10 = 10 + 4 \cdot0$$ is not true, so the solution to the problem $52 - 3x < 10 +4x$ are all numbers greater than $6$.


Tomcat6 Decompressing GZip Request

Question: Since Tomcat has the option to compress its response to GZip.
Is there a way to configure Tomcat 6 to decompress gzipped requests without putting it behind an Apache server with mod_deflate enabled, or creating a GZip filter on the application level?
Answer: I turned out to use a 2Way filter on the application level to compress and decompress
I removed the tomcat configuration

Tomcat6 Decompressing GZip Request


Sampling prior covariance matrices - nested sampling

Question: I am trying to fit a multivariate Gaussian with a non-diagonal covariance matrix $\Sigma$ using nested sampling.
Usually, in other Bayesian analyses, we would use a Inverse Wishart or LKJ prior on the covariance matrix and compute the posterior using the analytical form of the prior.
However, in nested sampling, we cannot do this. We must specify the prior in terms of a transform from uniform uncorrelated samples. For instance, for a 1d normal prior, the prior transform would be the percent point function of the normal (the inverse of the CDF). norm.ppf(uniform_samples) gives you samples from the prior.
Unless I am mistaken, there is no function to transform uniform samples into a Wishart or LKJ prior.
Is there a better prior for covariance matrices that has a usable transform? Or is there a technqiue to estimate these transforms? Using a uniform prior on covariance matrix elements seems foolish.
Thanks
Answer: Have a look at codes generating random inverse wishart matrices (e.g, Jones 2007).
For example, the scipy implementation (https://github.com/scipy/scipy/blob/v1.6.0/scipy/stats/_multivariate.py#L2754 functions rvs, _rvs and _standard_rvs) use chi² and normal random draws and combines them with linalg.
You can take each normal/chi² variable based on a transform of the unit cube, and then follow the same procedure to obtain the matrix.


Are these two events independent (Comey and Mccabe tax returns)? How would we tell?

Question: The NYT reports:

The former F.B.I. director and his deputy, both of whom former
President Donald J. Trump wanted prosecuted, were selected for a rare
audit program that the tax agency says is random.
The odds of being selected for that audit in any given year are tiny —
out of nearly 153 million individual returns filed for 2017, for
example, the I.R.S. targeted about 5,000, or roughly one out of
30,600.

I'm trying to understand how we can know if these are independent events -- just in terms of the statistics, without knowing anything more about the case.
If we say independence means: P(XY) - (P(X) + P(Y)) = 0
Then we are saying: the probability of the joint occurrence is equivalent to the linear addition of the individual probabilities.
So is this true?
Let's say the process of selection is not random but is instead corrupt and the two have not yet been selected for tax audit. It's 2017, and the probability of joint occurrence (P(XY)) is high, say 95%.
On the face of it, the probabilities do not seem independent. However, maybe they are. We could say that the probability that one gets audited is 1/30,600 (P(X)) and the other is also 1/30,600 (P(Y)).
That implies dependence by our definition, even though this doesn't intuitively make sense to me. Is it correct to think about the joint probabilities this way?
It seems intuitively that once you know that one is selected, the odds the other is selected goes up massively. So there's some dependence.
But should we simply consider the individual probabilities so low -- or should they also be much higher because each person has a high chance of being audited, jointly or not? I'm confused how we rate individual probabilities in this instance and how it connects to independence.
Comment: You left out the part where they were picked in *different* draws, which changes the question ("how likely is it that two people are *ever* both picked for audit?", similar to birthday paradox). Also, "random" is not necessarily uniformly random, and "corruption" is not the only alternative. This is some kind of "special" deep audit and the article does *not* say that the returns chosen are selected from the *entire* pool of returns; they could be pre-selected according to some features which, for two people working essentially the same job at the same employer, could be highly correlated.
Comment: I asked a related question at https://stats.stackexchange.com/questions/581157/probability-that-two-specific-people-are-selected-for-irs-audit-within-4-year-pe in case you're interested
Comment: @ChrisHaug Yes, fair enough. I simplified heavily for my example :)
Answer: If two events $X$ and $Y$ are independent then
$$
P(X \cap Y) = P(X)P(Y),
$$
where $X\cap Y$ is the event that both $X$ and $Y$ do happen.
IIUC, you want to know how likely it is to have both being selected for the audit provided the selection is completely random (i.e. in particular independent) and $P(X) = P(Y) = 1/30,600$. According to the above formula, that probability is:
$$
P(X\cap Y) = P(X)P(Y) = \frac{1}{30,600}\cdot \frac{1}{30,600} = \frac{1}{936,360,000} \approx 0.000000001.
$$
By the way, if the selection of both is independent, then knowing that one is selected will not change the probability that the other one is selected, that is the very meaning of independence.
Comment: @Learningstatsbyexample The individual probability doesn't change, it is still $1/30,600$. But without independence, the product formula doesn't hold anymore. Rather, $P(X\cap Y) = P(X|Y)P(Y)$, and $P(X|Y)$ is probably rather difficult to come by.
Comment: This is a great follow-up.. https://www.nytimes.com/2022/07/07/upshot/comey-mccabe-tax-audits.html
Comment: I guess it doesn't seem like they are random. So I'm wondering how to estimate the individual and joint probabilities in that case.


Script criado no Pycharm fecha ao apertar a tecla "enter" dentro do terminal

Question: É o seguinte. Sou novo no meio da programação.
Uso o PyCharm para estudar python.
Quando tento executar um script criado no PyCharm pelo IDLE, logo após eu apertar a tecla "enter" a janela fecha. Os scripts criados no IDLE executam normalmente até o fim.
Por exemplo. Eu dou dois cliques no o script que eu criei no PyCharm, vai abrir aquela janela do terminal, a primeira linha do código é um input vamos supor. Logo após eu escrever algo e apertar o "enter", a janela ja fecha. Mas se eu pegar o mesmo código, salvar o script pelo IDLE, o programa funciona normalmente. Por que será que isso acontece?
Séra que é algum bug do próprio PyCharm? Sou um pouco leigo ainda, se alguém puder me ajudar eu agradeço.
Answer: sem ver o teu código fica um pouco difícil te ajudar, mas acredito que o que está acontecendo é algo normal:

o programa executa o código
para pra receber uma informação
realiza todos os passos seguinte e finaliza tão rápido (como obviamente tem de ser) que vc não vê o que está acontecendo.

Você consegue visualizar pelo PyCharm porque ele foi feito pra vc desenvolver qualquer programa, já o terminal não é exatamente uma interface gráfica ideal pra vc utilizar.
Se você quiser escrever um programa que tenha interação com o usuário, existem frameworks pra isso como o PyQt, Tkinter, wxPython, PySide... e vários outros.
Espero que isso te dê um norte, caso contrário, edita sua pergunta e deixa a gente entender melhor o que está passando na sua cabeça


MySQL update table with data from another table based on field

Question: I have a database that looks like this
 leads
 name         zip          city      county     state
 Bill         84058
 Susan        90001

 FullUSZipCodes
 ZipCode       City        County       State
 84058         Orem        Utah         Utah
 90001         Los Angeles South        California

As you can see, in the leads database the city, count and state are empty, i'm trying to merge the data so that the first table would look like this:
 leads
 name         zip          city      county     state
 Bill         84058        Orem      Utah       Utah
 Susan        90001        Los Angeles South    California

This is the first query I tried:
UPDATE leads SET leads.county = FullUSZipCodes.County WHERE leads.zip = FullUSZipCodes.ZipCode

which didn't work, and here is the 2nd query:
UPDATE leads INNER JOIN FullUSZipCodes ON leads.zip = FullUSZipCodes.ZipCode SET leads.county = FullUSZipCodes.County, leads.city = FullUSZipCodes.City, leads.state = FullUSZipCodes.State

Answer: Your second query looks like it should work, but I would write it slightly differently:
UPDATE leads t1
INNER JOIN FullUSZipCodes t2
    ON t1.zip = t2.ZipCode
SET
    t1.city = t2.City,
    t1.county = t2.County,
    t1.state = t2.State
WHERE
    t1.city IS NULL OR t1.county IS NULL OR t1.state IS NULL;

If the leads table has a lot of records, and performance is a concern, you can try adding a WHERE clause to the update query which targets only those records which are missing one or more pieces of address information.  I think there is nothing wrong with always updating all three columns together, because typically this information tends to be grouped together.
Comment: That is the 2nd query I tried, it just kept processing the query but didn't seem to ever finish
Comment: You can also add a `WHERE` clause to try and target records which are missing data.
Comment: About 50,000 records, all of them are missing the data
Comment: Possibly, it's been running the query for 20min I knew it would take time, didn't realize it would take that long


slapd not running

Question: I am new to Red Hat Enterprise Linux 5.3(Tikanga) as well as to open ldap.As openldap comes by default with the red hat.So i have installed berkeley database db-5.3.15.tar.gz
Version of already installed OpenLdap: openldap-2.3.43-3.el5
When I am running slapd by command:
service ldap start
It is showing
Starting slapd:                                            [  OK  ]
but no slapd process is starting. Please suggest what is the problem.
Thanks.
Comment: Any relevant log records?
Comment: where can i see the log?
Comment: besides this already installed openldap. I have installed both openldap and berkley db and tried to run it through slapd instead of service ldap start but that is also not running. Is it something like on red hat linux we can run openldap through "service ldap start" only?
Answer: first off, are you sure its not running by checking the following commands;
You can check that the ldap is actually running by using the command netstat -lntp | grep 389 and it should show something like this;
# netstat -lntp | grep 389
tcp        0      0 0.0.0.0:389                 0.0.0.0:*                   LISTEN      28783/slapd
tcp        0      0 :::389                      :::*                        LISTEN      28783/slapd

If it is not running then try and start the command from the command line (so you can see any error messages to standard outout/error) like so;
# /usr/sbin/slapd -d 1
@(#) $OpenLDAP: slapd 2.3.43 (Feb 22 2012 15:59:04) $
        email@example.com:/builddir/build/BUILD/openldap-2.3.43/openldap-2.3.43/build-servers/servers/slapd
daemon_init: listen on ldap:///
daemon_init: 1 listeners to open...
...
slapd starting

my log file seems to be located by default in /var/log/slapd.log , so that is the first place to look for additional information.
If it is definitely not starting, then you can edit the /etc/openldap/slapd.conf file to increase the logging activity with the loglevel command;
#<http://www.zytrax.com/books/ldap/ch6/#loglevel>
#loglevel 3333
#loglevel filter
#loglevel stats
#loglevel ACL

Comment: put something like `SLAPD_OPTIONS="-h ldap://localhost:12345"` in `/etc/sysconfig/ldap`
Comment: Thanks for the valuable information. It really helped me.Can you please guide how can I change the default port?
Comment: there is no such directory/file named ldap i.e. i am only able to get /etc/openldap/ Inside this there is not ldap options. Any idea?
Comment: i have run the following command and it worked: slapd -h ldap://localhost:12345 -f usr/local/openldap_2.4/slapd.conf. But now i have another query how can i know which BDB it is referring as there are two bdb one is default and other is installed by me?
Comment: Its dependent on how you configured the additional root. I'd need to see the slapd.conf file. You can award this answer and paste the slapd.conf in another question and link to it here, and ill take a look.
Comment: I have raised another question: http://serverfault.com/questions/382893/how-to-know-which-berkley-db-openldap-is-refering-to  Please have a look and provide your suggestion.
Comment: re the `/etc/sysconfig/ldap`  its not there by default, but you can create it and the `service ldap start` script looks in that file for addition options. You can open the `/etc/init.d/ldap` in a text editor and search for the `/etc/sysconfig` and `SLAPD_OPTIONS` strings for details on how those values are used.
Comment: the filename is actually `/etc/sysconfig/slapd` instead of `/etc/sysconfig/ldap`

slapd not running


What are Best Practices for setting a https node server via a reverse-proxy without using Apache or Nginx

Question: I am trying to get a Node https server accessed through a node proxy.
I bought certificates and got a standalone https server working fine. Initially there were some hiccups because of multiple certs in one file but this post helped:
 http://stackoverflow.com/questions/16224064/running-ssl-node-js-server-with-godaddy-gd-bundle-crt.

Earlier I had all connections through a node-based reverse proxy nodejitsu's http-proxy module, which effectively proxied http -> http.
Now, as expected, after getting the target server changed to https, the proxy does not work as it is basically:
 client -> http-proxy(public IP) -> https connection(local IP)

which is effectively the man-in-the-middle scenario which is what https seeks to eliminate.
Additionally, I got the following error from the https server:
 Error: Hostname/IP doesn't match certificate's altnames

The certificates are just fine because https works well without the proxy in the middle.
From reading some of the posts, I realized that the following should work:
 client -> https-proxy (Public IP) -> http connection (local IP)

Where the actual local server is running http and the public https. This is based on the explanation in http-proxy documentation:
 https://github.com/nodejitsu/node-http-proxy

and in this post:
 https://nadeesha.silvrback.com/creating-a-https-proxy-in-node-js

In the http-proxy module documentation, there appears to be an explanation for a client -> https (proxy on public IP) -> https (proxy on local IP).  If so, what certs do I need to set up on the target https server?
Before I try any of these possibilities, I would like to know: What are standard best-practices to handle this requirement and how to implement it/them under node. I do not want to introduce Nginx or Apache just for handling this. Am I totally off-track here?
Comment: Not enough data on what is actually the requirements. Why would you want to have https between your front-end proxy and back-end server? There are some valid reasons for doing this (two different public servers for example where the back-end can be reached over the public network), but it's not clear in your post what you're set up is.
Answer: client -> https-proxy (Public IP) -> http connection (local IP)
This is perfectly valid installation, provided that https-proxy (Public IP) -> http connection (local IP) is over a secure network - i.e. your backend server isn't exposed to a public network.
client -> https-proxy (Public IP) -> httpS connection (local IP)
This is unnecessary if you are within a private network and just "overworks" your back-end server and front-end proxy by having to do encryption/decryption steps. However, it may be required in some scenarios and also, modern computers don't choke as much doing doing encryption/decryption as it used to be. But again, whether you're going to feel it or not depends on the volume of traffic.
Comment: The docs in node-proxy got me wondering about https->https proxying. I do not have the back-end server accessible through another public network/server. My proxy has two interfaces. One has multiple public IP addresses and domain DNS A records of a larger set of domains pointing to them. The other interface is for local servers to which the requests are targeted. I am also thinking of port DNATing using Iptables so that the proxy itself is not running on 80 or 443.  I will wait for a day to see what other opinion comes in before marking your answer as accepted. Certainly helpful.


XRDP and VNC freezes Debian 9 VM on VMware ESXi

Question: I've installed Debian 9.3 stable on a VM in ESXi 6.5.0d. I'm running XFCE 4 as the desktop environment and have XRDP installed. I'm using the default configuration with exception of setting the session using:
echo "xfce4-session" > ~/.xsession

and changing the file /etc/X11/Xwrapper.config to set the flag:
allowed_users=anybody

After a reboot of ESXi, Remote Desktop Clients from Windows 10 appear to be able to connect once or twice but after that the VM will freeze up when trying to connect to it. (When loging in though, it does not show a desktop, just the default cyan / blue screen.) If I restart ESX the same behavior can be reproduced. Once the VMs start to freeze they always freeze until ESXi is restarted. While the VM is frozen, ESXi is still responsive however.
Debian seems to be in a infinite loop as the CPU allocated to it is maxed out at 100% and stay like that until I  reset the VM. Unfortunately all services on the Debian host dies and it does not accept and IO or SSH connections etc. Any existing SSH connections time out not leaving much room for debugging.
XRDP is set to DEBUG log levels however there appears to be nothing of value (errors, warnings, etc) in /var/log/xrdp.log, /var/log/xrdp-sesman.log or /var/log/syslog. I've also enabled Debug Logging for the VM in ESXi, but I can't see anything of value in there either.
TightVNC seems to behave similarly, however it freezes the VM immediately.
Google and I am out of ideas. Any thoughts on where to go from here or what to try?
Answer: Did you happen to see this post?
I'm literally doing the same thing you are, and I've been having trouble keeping a stable connection. I tried the recommended solution on there regarding changing the network adapter from the default "VMXNET 3" to "E1000e" in VMWare, and so far so good.
I'll update this post if I lose connection again.
Comment: No, other applications like SSH seemed to run fine so I was fixated on searching for xrdp / vnc related issues. Changing to E1000e (and testing for a few hours) seem to have fixed it Thanks!
Answer: I was running into a similar issue with Debian -- the only thing that eventually remediated this for me was to update ESXi to a newer patch. It looks like the same issue was hit by this person as well -- https://askubuntu.com/questions/957660/ubuntu-16-4-lts-freezes-when-running-as-a-virtual-machine-under-esxi-6-5


Amazon S3 Write Only access

Question: I'm backing up files from several customers directly into an Amazon S3 bucket - each customer to a different folder. I'm using a simple .Net client running under a Windows task once a night. To allow writing to the bucket, my client requires both the AWS access key and the secret key (I created a new pair).
My problem is:

How do I make sure none of my customers could potentially use the pair to peek in the bucket and in a folder not his own? Can I create a "write only" access pair?
Am I approaching this the right way? Should this be solved through AWS access settings, or should I client-side encrypt files on the customer's machine (each customer with a different key) prior to uploading and avoid a the above mentioned cross-access?
Answer: I just created a write-only policy like this and it seems to be working:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME/*"
            ]
        }
    ]
}

I think creating a drop like that is a much neater solution.
Comment: This worked for me when I changed the action to: "s3:PutObject*" (ie added an asterix) HTH
Answer: Use IAM to create a separate user for each customer (not just an additional key pair), then give each user access to only their S3 folder. For instance, if the bucket is called everybodysbucket, and customer A's files all start with userA/ (and customer B's with userB/), then you can grant permission to everybodysbucket/userA/* to the user for customer A, and to everybodysbucket/userB/* for customer B.
That will prevent each user from seeing any resources not their own.
Use can also control specific S3 operations, not just resources, that each user can access. So yes, you can grant write-only permission to the users if you want.
Comment: yep. But I managed to find the problem - somewhere in the code some genius decided to check whether the directory structure exists by using GetObject, so he was basically looking for the parent folder - for which the user has no permission. Thanks for your answer - it solved my issue.
Comment: So does that mean I'll use the same key pair for all users, or will I generate a new pair per IAM user?
Comment: Each IAM user will have a different key pair.
Comment: I tried what you suggested, created a user, added a policy with  various "S3::" actions to a resource "arn:aws:s3:::my_bucket/folder/user/*" and I get "access denied" errors. If I change the user policy to "arn:aws:s3:::*" it works. Do I also need to set a bucket policy to allow a user to write to his folder?
Comment: I just tried it, and it worked. My user had a single S3 permission: `PutObject`, with the ARN similar to the one above. I was able to create an object in that folder. Are you sure that the object you are creating in "my_bucket" is named "folder/user/somethingorother"?
Comment: Note, however, you can only have a [maximum of 500 API keys per account per region](https://docs.aws.amazon.com/apigateway/latest/developerguide/limits.html) (in case you want to use this technique on a larger number of customers)
Answer: As a variation on the approach recommended in Charles' answer, you can also manage access control at the user level via SFTP.  These users can all share the same global IAM policy:

SFTP does support user-specific home directories (akin to "chroot").
SFTP allows you to manage user access via service managed authentication or via your own authentication provider.  I am unsure if service managed authentication has user limits.
If you wish to allow users to access uploaded files using a client, SFTP provides it very cleanly.

Amazon S3 Write Only access


"uninitialized local variable" error when using pointers for function arguments

Question: I have a function:
VOID GetOSVersion(PDWORD major, PDWORD minor, PDWORD build)
{
    OSVERSIONINFO osver;
    ZeroMemory(&osver, sizeof(OSVERSIONINFO));
    osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osver);
    if(major)
    *major = osver.dwMajorVersion;
    if(minor)
    *minor = osver.dwMinorVersion;
    if(build)
    *build = osver.dwBuildNumber;
}

And I wanted to invoke it like this:
PDWORD major;
PDWORD minor;
PDWORD build;
GetOSVersion(major, minor, build);

I get an error for all the three arguments:

uninitialized local variable

In my head it went like: I declare major, minor, build, and they get filled in the function. Space is already allocated for them during the first three lines of the invoking code.
I am surely missing something here. Could somebody please explain this for me?
Comment: You pass all the three variables major, minor and build as non-reference to the function, without initialising them. Since the function deals with the values of those variables this doesn't make much sense.
Answer: You are making the mistake that many make when it comes to functions that require pointer arguments.
When a function requires a pointer as an argument, it doesn't mean you blindly declare a pointer and pass it to the function.  What the function is asking for is an address-of an existing, valid, entity.
DWORD major, minor, build;
GetOSVersion(&major, &minor, &build);

The DWORD's above are valid, and all that is done is pass the address of these variables to the function.
The other mistake that is related to this (not a bug, as it will give the desired results, but still a "mistake") is to declare a pointer, have it point to somewhere valid, and then pass it to the function.  In other words:
PDWORD major, minor, build;
major = new DWORD;
minor = new DWORD;
build = new DWORD;
GetOSVersion(major, minor, build);
delete major;
delete minor;
delete build;

or
PDWORD pmajor, pminor, pbuild;
DWORD major, minor, build;
pmajor = &major;
pminor = &pminor;
pbuild = &build;
GetOSVersion(pmajor, pminor, pbuild);

I have seen code written in this manner.  This indicates that the programmer does not have a clear understanding of what it means when a function requires a pointer as an argument.  The programmer erroneously believes that a pointer must be declared, have it point somewhere valid, and then pass this pointer.
Yes, you get the results without crashing, but it is a waste of time to call the allocator (new / delete), or if not calling the allocator, create unnecessary pointer variables which unnecessarily obfuscates the code.
So the easiest way is the first example above.  Just declare non-pointer types, and just pass the address.
Comment: +1 If any here, I think this answer explains best, what the probable misconception of the OP is!
Answer: the problem is there:
DWORD major;
DWORD minor;
DWORD build;
GetOSVersion(&major, &minor, &build);

Fix:
VOID GetOSVersion(PDWORD major, PDWORD minor, PDWORD build)
{
    OSVERSIONINFO osver = {};
    osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osver);
    if(major)
    *major = osver.dwMajorVersion;
    if(minor)
    *minor = osver.dwMinorVersion;
    if(build)
    *build = osver.dwBuildNumber;
}

DWORD major = 0;
DWORD minor = 0;
DWORD build = 0;
GetOSVersion(&major, &minor, &build);

PDWORD is pointer to DWORD. All three parameters are output parameters. In C/C++, it's a common usage: if you want to return more then one value from a function, you need pass pointer (or reference too in case of c++) to a variable:
int var = 0;
if(some_function_that_can_fail_and_write_result(&var))
 ;//do something

In your case you are passing uninitialized pointer to a function by value. It's the same as:
void foo(int parameter);
// ...
int a;
foo(a);

You have a lot of ways:
Pass uninitialized pointer by reference:
VOID GetOSVersion(PDWORD& major, PDWORD&, PDWORD&)
{
//...
major = new DWORD(osver.dwMajorVersion);

}
// usage:
PDWORD major;
GetOSVersion(major, ....);

//...
delete major;

Pass all parameters by reference:
VOID GetOSVersion(DWORD& major, DWORD&, DWORD&)
{
//...
major = osver.dwMajorVersion;

}
// usage:
DWORD major = 0;
GetOSVersion(major, ....);

Use your version of GetOSVersion(), but with the fix in this answer on the beginning
Comment: Your answer could be greatly improved by showing a simple sample how to initialize those variables properly.
Comment: Yes, I have tried that, the compiler says: "Cannot convert parameter 1 from PDWORD to PDWORD"
Comment: @user3718333 Is that really the error you get from the compiler? That seems strange. Can you paste the *exact* code?
Comment: @David Schwartz That is what I got when invoking with the code sample in the comment's first grey box. The code was exactly that + the function
Comment: @user2451677 You're going into a worse direction. Pointer references and `new()` aren't necessary here.
Comment: @David Schwartz no sorry, I misread it. I still declared the variables of type PDWORD just passed them as reference like &major. I did it wrong the answer is 100% correct.
Comment: @user3718333 **Consciously** select what you accept as an appropriate answer! Explain why you really need those `PDWORD major;` etc. pointers in 1st place.
Answer: You probably meant to have your variable declarations and to call your function like this
DWORD major;
DWORD minor;
DWORD build;
GetOSVersion(&major, &minor, &build);

You use pointers to reference the output parameters, thus these need to point them to valid memory addresses. You can refer to those variables to get a valid pointer using the 'address-of' (&) operator as shown above.

With c++ you can use by reference parameters, which will make things a bit clearer
VOID GetOSVersion(DWORD& major, DWORD& minor, DWORD& build) {
    OSVERSIONINFO osver;
    ZeroMemory(&osver, sizeof(OSVERSIONINFO));
    osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osver);
    // Note there's no check needed if the pointers are valid!
    major = osver.dwMajorVersion;
    minor = osver.dwMinorVersion;
    build = osver.dwBuildNumber;
}

DWORD major;
DWORD minor;
DWORD build;
GetOSVersion(major, minor, build);

No need to call the new() allocator (and bother with correct dynamic memory allocation management) with any of the above samples in 1st place.
Answer: Those are pointers. They are not pointing at any memory you have allocated. They do not get "filled" in the function, they get used to access (uninitialized) memory.
Answer: You are probably not getting an error but a warning (but you might have configured your complier to treat warnings as errors).
If executed, your program will segfault because you are writing to the memory pointed to by them but as they are uninitialized they contain invalid/random addresses.
Possible solution
PDWORD major = new DWORD;
PDWORD minor = new DWORD;
PDWORD build = new DWORD;

assuming PDWORD is defined to be *DWORD.
Do not forget the deletes!
edit: Actually its much more sensible to allocate these on the stack – see user2451677's answer.
Comment: That is a bad solution.  It gives the impression that pointer arguments means that you must actually declare pointers.  You are needlessly calling the allocator.
Comment: Thanks @wonce. I before posting i tried allocating them as new PDWORD and now I get the point. Really a complete answer, thanks a lot!
Comment: -1 **No, No, No that's veeeery bad advice!** And certainly shouldn't be accepted! Think twice!


Table Conversion- Oracle

Question: I have a table with this structure:
date  colname   value
----------------------------
date  col1name  col1's value
date  col2name  col2's value
date  col3name  col3's value

Now I need to convert it into this structure:
date col1name       col2name      col3name
-----------------------------------------------
date col1's value   col2's value  col3's value

Is it possible?
Comment: @OMG Thanks for the editting, that's just what I am asking for.
Answer: You want a pivot table:
  SELECT t.date,
         MAX(CASE WHEN t.colname = 'col1name' THEN t.value END) AS col1name,
         MAX(CASE WHEN t.colname = 'col2name' THEN t.value END) AS col2name,
         MAX(CASE WHEN t.colname = 'col3name' THEN t.value END) AS col3name
    FROM TABLE t
GROUP BY t.date

If you want to make it dynamic based on the colname value, you'll need to use dynamic SQL because you need to get the list of colname values first before constructing the actual query.
Oracle didn't add PIVOT/UNPIVOT support until 11g.  The CASE expression is supported 9i+; prior to 9i you'd have to use DECODE...
Comment: Hi Ponies. Thanks for your reply. But it is not about order, it is about flatten the previous table. i.e. 'importing the data' in your answer, I am not sure how to do that.
Comment: @sarahTheButterFly: Updated when I saw you change the formatting.

Table Conversion- Oracle


Use of Proper data Structure

Question: I have developed a dictionary application with offline database support.Everything works fine for me but the application is taking time in retrieving the definition of the words.I know there is the problem with the data structure.I only knew the implementation of ArrayList but I do not know how to implement any other data structures(HashMap, TRIE or any other) in my application.I have tried the Oracle documentations for the same but all my efforts went in vain.I just want some help regarding how to implement HashMap or any other data structure in my application.
Thanks in advance...
DMainActivity.java
public class DMainActivity extends AppCompatActivity {
private EditText filterText;
private ArrayAdapter<String> listAdapter;

private TextView textView2;
private TextView textView3;
private TextView textView4;
private TextView textView5;
private TextView textView6;
private TextView textView7;
private TextView textView8;
private TextView textView9;
private TextView textView10;
private TextView textView11;
private TextView textView12;
private TextView textView13;
private TextView textView14;
private TextView textView15;
private TextView textView16;
private TextView textView17;

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

    filterText = (EditText)findViewById(R.id.editText);
    final ListView itemList = (ListView)findViewById(R.id.list_view);
    itemList.setVisibility(View.GONE);

    textView2 = (TextView)findViewById(R.id.textView2);
    textView3 = (TextView)findViewById(R.id.textView3);
    textView4 = (TextView)findViewById(R.id.textView4);
    textView5 = (TextView)findViewById(R.id.textView5);
    textView6 = (TextView)findViewById(R.id.textView6);
    textView7 = (TextView)findViewById(R.id.textView7);
    textView8 = (TextView)findViewById(R.id.textView8);
    textView9 = (TextView)findViewById(R.id.textView9);
    textView10 = (TextView)findViewById(R.id.textView10);
    textView11 = (TextView)findViewById(R.id.textView11);
    textView12 = (TextView)findViewById(R.id.textView12);
    textView13 = (TextView)findViewById(R.id.textView13);
    textView14 = (TextView)findViewById(R.id.textView14);
    textView15 = (TextView)findViewById(R.id.textView15);
    textView16 = (TextView)findViewById(R.id.textView16);
    textView17 = (TextView)findViewById(R.id.textView17);

    final DbBackend dbBackend = new DbBackend(DMainActivity.this);
    String[] terms = dbBackend.dictionaryWords();
    listAdapter = new ArrayAdapter<String>(this, R.layout.custom_textview,R.id.tv, terms);

   // listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, terms);

    itemList.setAdapter(listAdapter);
    itemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // make Toast when click
           String word = listAdapter.getItem(position);
            String[] words = dbBackend.dictionaryWords();

            for(int i=0; i < words.length; i++)
                if(words[i].contains(word))
                    position = i;

            Toast.makeText(DMainActivity.this, word + " " +position , Toast.LENGTH_SHORT).show();
            //Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_LONG).show();
            Intent intent = new Intent(DMainActivity.this, DictionaryActivity.class);
            intent.putExtra("DICTIONARY_ID", position);
            startActivity(intent);
        }
    });

    filterText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //MainActivity.this.listAdapter.getFilter().filter(s);
        }
        @Override
        public void afterTextChanged(Editable s) {
            if (s != null && s.toString().trim().length() > 0) {
                itemList.setVisibility(View.VISIBLE);
                //textView1.setVisibility(View.GONE)
                textView2.setVisibility(View.GONE);
                textView3.setVisibility(View.GONE);
                textView4.setVisibility(View.GONE);
                textView5.setVisibility(View.GONE);
                textView6.setVisibility(View.GONE);
                textView7.setVisibility(View.GONE);
                textView8.setVisibility(View.GONE);
                textView9.setVisibility(View.GONE);
                textView10.setVisibility(View.GONE);
                textView11.setVisibility(View.GONE);
                textView12.setVisibility(View.GONE);
                textView13.setVisibility(View.GONE);
                textView14.setVisibility(View.GONE);
                textView15.setVisibility(View.GONE);
                textView16.setVisibility(View.GONE);
                textView17.setVisibility(View.GONE);

            } else {
                itemList.setVisibility(View.GONE);
                // textView1.setVisibility(View.VISIBLE);
                textView2.setVisibility(View.VISIBLE);
                textView3.setVisibility(View.VISIBLE);
                textView4.setVisibility(View.VISIBLE);
                textView5.setVisibility(View.VISIBLE);
                textView6.setVisibility(View.VISIBLE);
                textView7.setVisibility(View.VISIBLE);
                textView8.setVisibility(View.VISIBLE);
                textView9.setVisibility(View.VISIBLE);
                textView10.setVisibility(View.VISIBLE);
                textView11.setVisibility(View.VISIBLE);
                textView12.setVisibility(View.VISIBLE);
                textView13.setVisibility(View.VISIBLE);
                textView14.setVisibility(View.VISIBLE);
                textView15.setVisibility(View.VISIBLE);
                textView16.setVisibility(View.VISIBLE);
                textView17.setVisibility(View.VISIBLE);
            }

            listAdapter.getFilter().filter(s);
        }

    });
}

}

DbBackend.java
public class DbBackend extends DbObject{

public DbBackend(Context context) {
    super(context);
}

public String[] dictionaryWords(){
    String query = "Select * from words";
    Cursor cursor = this.getDbConnection().rawQuery(query, null);
    **ArrayList<String> wordTerms = new ArrayList<String>();
   // HashMap<String,ArrayList<String>> hashMap = new HashMap<String, ArrayList<String>>();**
    if(cursor.moveToFirst()){
        do{
            String word = cursor.getString(cursor.getColumnIndexOrThrow("word"));
            wordTerms.add(word);
        }while(cursor.moveToNext());
    }
    cursor.close();
    String[] dictionaryWords = new String[wordTerms.size()];
    dictionaryWords = wordTerms.toArray(dictionaryWords);
    return dictionaryWords;
}

public QuizObject getQuizById(int quizId){

    QuizObject quizObject = null;
    String query = "select * from words where _id = " + quizId;
    Cursor cursor = this.getDbConnection().rawQuery(query, null);
    if(cursor.moveToFirst()){
        do{
            String word = cursor.getString(cursor.getColumnIndexOrThrow("word"));
            String meaning = cursor.getString(cursor.getColumnIndexOrThrow("defn"));
            quizObject = new QuizObject(word, meaning);
        }while(cursor.moveToNext());
    }
    cursor.close();
    return quizObject;
}
}

DictionaryActivity.java
public class DictionaryActivity extends ActionBarActivity{
private TextView wordMeaning;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.dict_activity);
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    int dictionaryId = bundle.getInt("DICTIONARY_ID");
    int id = dictionaryId + 1;

    TextView word = (TextView)findViewById(R.id.word);
    wordMeaning = (TextView)findViewById(R.id.dictionary);
  //  Button textToSpeech = (Button)findViewById(R.id.button);

    DbBackend dbBackend = new DbBackend(DictionaryActivity.this);
    QuizObject allQuizQuestions = dbBackend.getQuizById(id);

    word.setText(allQuizQuestions.getWord());
    wordMeaning.setText(allQuizQuestions.getDefinition());

}

}
Answer: You are interested to find the id of the words in your database (you call it position).  Therefore you should create a Map that maps a word to its id, this Map would look like:
Map<String, Integer> wordsToIdMap = new HashMap<>();

In order to fill the map:
    do {
        String word = cursor.getString(cursor.getColumnIndexOrThrow("word"));

        // Unsure about this line, change it as needed:
        int id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));

        wordsToIdMap.put(word, id);
    } while(cursor.moveToNext());

Now you can get the id by doing a super fast call like this:
 int id = wordsToIdMap.get(word);

Comment: Tnxx for the explanation Sir...That was really beneficial.Just the last query.Where do I put the last line i.e. int id = wordsToIdMap.get(word);
Comment: I would put that where you call the dbBackend for dictionary words.  Make a method in dbbackend that accepts a word and then gets it from the wordsToIdMap.

Use of Proper data Structure


$H_{n}:Comp(\mathcal{C}) \to \mathcal{C}$ is an additive functor implies $H_{n}:K(\mathcal{C}) \to \mathcal{C}$ is an additive functor.

Question: We know that if $\mathcal{A}$ is an abelian category, then the homology functor $H_{n}:Comp(\mathcal{C}) \to \mathcal{C}$ is an additive functor for every $n \in \mathbb{Z}$. One can find a prove of this statement in Rotman´s Homological Algebra Proposition 6.8. But sometimes why the same holds for $H_{n}:K(\mathcal{C}) \to \mathcal{C}$,  where $K(\mathcal{C})$ is the homotopy category ? Maybe my question is simple and silly but for example if I have $[f],[g] \in K(\mathcal{C})$ I need to prove among other things that $H_{n}([gf])=H_{n}([g])H_{n}([f])$ or that as  $K(\mathcal{C})$ is also an additive category then $H_{n}([f+g])=H_{n}([f])+H_{n}([f])$. Is there a way to easily prove this if its already proved in the category of complexes. Also how I know $H_{n}([f])$ is well defines if I already know that the assignation $H_{n}(f)$ is well defined. Thanks.
Answer: I'm a little more comfortable working with cohomology, so I'm going to answer this question in that language; of course the concepts are dual, so simply dualizing gives you the corresponding result for homology. The easiest way (in my opinion, anyway) to see that the cohomology functors
$$
H^n:K(\mathscr{A}) \to \mathscr{A}
$$
are additive for any Abelian category $\mathscr{A}$ is to use the universal property of the homotopy category. By definition, the category
$$
K(\mathscr{A}) = \mathbf{Ch}(\mathscr{A})_{/\text{homotopy}}
$$
is a strict localization, i.e., it is given by inverting a congruence relation. It also follows from the bilinearity of chain homotopies (i.e. if $f \simeq g$ and $h \simeq k$ then $f + g \simeq f + k \simeq g + h \simeq h + k$) that the quotient functor
$$
q:\mathbf{Ch}(\mathscr{A}) \to K(\mathscr{A})
$$
is also additive. Now recall that applying the universal property of a localization of categories says that in our case if you have a functor $F:\mathbf{Ch}(\mathscr{A}) \to \mathscr{C}$ which kills homotopy (so if $g \simeq h$ then $Fg = Fh$) then there exists a unique functor $\overline{F}:K(\mathscr{A}) \to \mathscr{C}$ making the diagram
$$
\begin{array}{ccc}
 \mathbf{Ch}(\mathscr{A}) & \xrightarrow{F} & \mathscr{C} \\
 q\downarrow & \nearrow & \\
 K(\mathscr{A})
\end{array}
$$
where the diagonal arrow is $\overline{F}$. In the case we actually care about, we use the functor $H^n:\mathbf{Ch}(\mathscr{A}) \to \mathscr{A}$ and produce the commuting diagram of categories
$$
\begin{array}{ccc}
\\
 \mathbf{Ch}(\mathscr{A}) & \xrightarrow{H^n} & \mathscr{A} \\
 q\downarrow & \nearrow & \\
 K(\mathscr{A})
\end{array}
$$
where in this case the diagonal arrow is the cohomology functor on the homotopy category (which I will denote $\overline{H}^n$ for the moment. To see that this is additive, we just need to prove that $\overline{H}^n$ preserves finite products. For this we first consider the zero object $0_K \in K(\mathscr{A})_0$ and note that $0_K \cong q(0_C)$ for $0_C$ the zero object in $\mathbf{Ch}(\mathscr{A})$. Then
$$
\overline{H}^n(0_K) \cong \overline{H}^n(q(0_C)) = H^n(0_C) \cong 0_{\mathscr{A}}.
$$
Now fix two arbitrary complexes $A^{\bullet}, B^{\bullet} \in \mathbf{Ch}(\mathscr{A})_0$ and consider the product $A^{\bullet} \times B^{\bullet}$. We note that because $q$ is additive and acts as the identity on objects, we have that
$$
A^{\bullet} \times B^{\bullet} = q(A^{\bullet}) \times q(B^{\bullet}) \cong q(A^{\bullet} \times B^{\bullet}).
$$
Now using the additivity of $H^n$ and the fact that $H^n = \overline{H}^n \circ q$ gives
$$
\overline{H}^n(A^{\bullet} \times B^{\bullet}) \cong \overline{H}^n(q(A^{\bullet} \times B^{\bullet}) = H^n(A^{\bullet} \times B^{\bullet}) \cong H^n(A^{\bullet}) \times H^n(A^{\bullet}) \cong \overline{H^n}(q(A^{\bullet})) \times \overline{H^n}(q(B^{\bullet})) = \overline{H}^n(A^{\bullet}) \times \overline{H}^n(B^{\bullet}),
$$
which proves that $\overline{H}^n$ preserves finite products. We can thus conclude that $\overline{H}^n$ is an additive functor, as was desired.
Comment: Thanks so much!!! Your proof was very clear, just wondering if there is any book where they claim $H_{n}$ or $H^{n}$ is an additive funtor for $K(\mathcal{C})$ instead of complexes, to reference. @Geoff
Comment: @Cos this is done, for instance, in Kashiwara-Schapira's book ``Categories and Sheaves.'' I think the overkill explicit reference you would want is Corollary 12.3.4, to be a little more precise.


SELECT filtrando os primeiros resultados

Question: tenho o campo DESTACAR  (sim) (nao)
Gostaria de Exibir os resultados retirando os 4 primeiros resultados DESTACAR (sim) e exibir o restante dos registros tanto os (sim) a partir do 4º quanto os (nao)
ja tentei usar LIMIT OFFSET mais nao funcionou
SELECT * FROM noticias WHERE status='Publicado' ORDER BY idnoticia DESC LIMIT 6,4

alguma alternativa?
Comment: Poste o que tentou e não funcionou. `LIMIT OFFSET` é o mais apropriado. Qual banco esta utilizando? Adicione também um exemplo, para ficar mais claro.
Comment: Você está usando mySql?
Answer: Use a operação UNION para unir o resultado de duas consultas diferentes em uma só.
A consulta antes do UNION teria apenas os resultados destacados, enquanto que a consulta após seria complementada com os resultados não-destacados.
SELECT *
FROM noticias
WHERE status='Publicado'
AND destacar='sim'
ORDER BY idnoticia DESC LIMIT 4
UNION
SELECT *
FROM noticias
WHERE status='Publicado'
AND destacar='nao'
ORDER BY idnoticia DESC

Daí em diante basta implementar uma paginação à sua maneira, usando LIMIT e OFFSET.
Comment: Mas nesse caso a 2ª query não vai exibir os `destacar='sim'` que estiverem abaixo da quarta posição, não é? Não seria o caso da 2ª query exibir todos registros menos os ID'S que forem listados na 1ª query?
Comment: @PapaCharlie pelo que eu entendi as linhas da tabela possuem 'sim' ou nao' na coluna, o que significa que não haveria repetição entre os resultados de ambas as consultas. Depende um pouco da estrutura da tabela também.
Comment: Pelo que eu entendi ele queria subir os 4 `sim` e manter o resto em ordem. Foi só a interpretação :)
Comment: Então, essa consulta lista todos o `sim` menos os 4 primeiros, e faz uma união com a consulta que retorna todos os `não`, só não sei dizer qual é mais performatica, se essa com union ou a anterior com subconsulta.
Comment: mais no caso a segunda consulta teria que pegar os outros destacar=sim -os 4 primeiros juntamente com os destacar=nao. Resumidamente seria uma consulta geral retirando os 4 primeiros ID com destacar sim
Answer: Utilize a seguinte subconsulta:
SELECT *
FROM noticias n
WHERE id NOT IN (
  SELECT * FROM (
    SELECT id
    FROM noticias
    WHERE destacar = 'Sim'
    ORDER BY id LIMIT 4
  ) p);

Exemplo funcionando no SQL Fiddle.
Comment: nesse caso se eu tivesse 100 noticias 50 sim e 50 nao as NAO nem apareceriam nos resultados
Comment: Editei a resposta, veja se é isso @ArsomNolasco
Comment: Se não for MYSQL pode utilizar o TOP 4 na subconsulta, se não estou enganado
Comment: funcionou, porem tentei colocar um limit no final so que deu erro ...  ORDER BY id LIMIT 4 ) p) ORDER BY DESC LIMIT 6; ... sabe pq o erro?
Comment: Você precisa informar o campo após o comando `ORDER BY`, ficaria assim: `... ORDER BY id DESC LIMIT 6` @ArsomNolasco
Answer: Pra fazer isso é mais fácil programando.
Faça uma select normal com os items que você quer e depois verifique se o campo é sim e remova
resultados = query(Select....

Contador = 0
Para Cada resultado Em resultados
{
    Se resultado.destaque == sim E Contador < 4 {
        remova resultado de resultados;
        Contador++
    }
}

Comment: $sql = "SELECT * FROM noticias WHERE ORDER BY idnoticia DESC LIMIT 3 "; $stmt->execute();
$exibe = stmt->fetchAll();foreach ($exibe as $u) {if $exibe.destacar == Destacado AND $Contador < 4 { Qual a funcao de remover resultado ?? $Contador++ }} echo


Partial derivative of a function with respect to product of variables

Question: If I have a function $f(x,y)$, and all I know about this function is its partial derivatives $\frac{\partial f(x,y)}{\partial x}$ and $\frac{\partial f(x,y)}{\partial y}$ as well as the position $(x_i, y_i)$ at which these partial derivatives were obtained, is it possible to obtain the partial derivative of $f(x,z)$ with respect to a new variable $z = x y$ while keeping $x$ constant, i.e. $\frac{\partial f(x,z)}{\partial (z)}$ at the same point $(x_i, y_i)$, or $(x_i, x_i y_i)$?
Comment: Instead of "is it possible?", the question you should ask yourself is what do you even **mean** by $\partial f/\partial (xy)$?
Comment: Ah, that makes sense, thank you. Yes, I see now why I need to specify that I do indeed want to keep $x$ constant. I will amend the question above accordingly.
Comment: @HansLundmark I feel like I don't know what I don't know here. What is arbirary about that notation? In my example, $f$ could be expressed either as $f(x,y)$ or as $f(x,z)$ where $z = x \cdot y$. It can't feasibly be differentiated analytically, so the partial derivatives that I have are numerically derived and I'm interested in finding $\frac{\partial f }{\partial z}$ without calculating it separately in order to save computational time.
Comment: OK, if you say that you express $f$ as a function of $x$ and $z$, it becomes clear. The thing is that when you write $\partial f/\partial z$, it must be understood from context what *other* quantity that should be held constant as $z$ is varied. So in this case, it seems that you want to keep $x$ constant as $z$ varies. You could also imagine, for instance, introducing new variables $(w,z)=(x^2-y^2,xy)$ or something like that, and write $\partial f/\partial z$ to mean that $w$ is to be held constant as $z$ varies, and that would be something completely different!
Answer: Let's be a bit careful with notation and write
$$
f(x,y) = g(x,xy)
,
$$
using different letters for the two functions $f(x,y)$ and $g(x,z)$. Then the derivative that you seek is $g_z(x,xy)$, that is, $\partial g/\partial z$ evaluated at the point $(x,z)=(x,xy)$. (I'll use subscripts to denote partial derivatives, since it's faster to type.)
The multivariable chain rule gives
$$
f_x(x,y) = g_x(x,y) + g_z(x,xy) \, y
,\qquad
f_y(x,y) = g_z(x,xy) \, x
,
$$
so the answer is simply (from the second of those two equations)
$$
g_z(x,xy) = \frac{f_y(x,y)}{x}
.
$$
(Which makes sense, since if you're holding $x$ fixed, varying $z=xy$ is basically the same thing as varying $y$; the only thing that differs is the scaling factor $x$.)


How can paging in nested array Mongodb

Question: i want to paging in structure. params are id = 558186caa6df1a2194422949 and Question is = 55818779a6df1a219442294d and get first 2 rows in Question datasource.
How do I resolve it?
Below is MongoDB document structure:
/* 1 */
{
    "_id" : ObjectId("558186caa6df1a2194422949"),
    "Questions" : [
        {
            "_id" : ObjectId("55818779a6df1a219442294d"),
            "DataSource" : [
                {
                    "_id" : ObjectId("55818796a6df1a2194422950"),
                    "Text" : "Q1-1",
                    "Value" : "Q1-1"
                },
                {
                    "_id" : ObjectId("5581879aa6df1a2194422951"),
                    "Text" : "Q1-2",
                    "Value" : "Q1-2"
                },
                {
                    "_id" : ObjectId("5581879ea6df1a2194422952"),
                    "Text" : "Q1-3",
                    "Value" : "Q1-3"
                }
            ]
        },
        {
            "_id" : ObjectId("55818774a6df1a219442294c"),
            "DataSource" : [
                {
                    "_id" : ObjectId("55818788a6df1a219442294e"),
                    "Text" : "Q2-1",
                    "Value" : "Q2-1"
                },
                {
                    "_id" : ObjectId("5581878fa6df1a219442294f"),
                    "Text" : "Q2-2",
                    "Value" : "Q2-2"
                }
            ]
        }
    ],
    "Name" : "test"
}

Answer: The challenge is that regular find() operators on arrays that yield a match in the array will return the whole array , so querying for Questions._Id = 55818779a6df1a219442294d will yield the whole Questions array including the second item 55818774a6df1a219442294c which you probably don't want to deal with.
You can use the aggregation pipeline and $unwind to "dig through" the arrays of arrays and then ultimately use $skip and $limit stages to achieve the pagination you seek, as follows:
    db.foo.aggregate([
    {$match: { "_id": ObjectId("558186caa6df1a2194422949") }}
    ,{$unwind: "$Questions"}
    ,{$match: { "Questions._id": ObjectId("55818779a6df1a219442294d") }}
    ,{$unwind: "$Questions.DataSource"}
    ,{$skip: 1}
    ,{$limit: 2}
                      ]);

In general, one must be careful about multiple $unwind operators because it could result in an explosion of data but here, our first $match always results in a single document because _id is unique.  The second $match also seems to cut down the input set significantly so the second $unwind is probably deal with order 100 or 1000 datasource items to skip and limit, not millions.

How can paging in nested array Mongodb


How to update a variable when target is called?

Question: I have a variable that should not be evaluated prior to calling a phony target because it will have an empty value, for example:
VAR = /home/directory/file

.PHONY: target
target:
  $(mkdir -p /home/directory)
  $(touch /home/directory/file)

Comment: Err, this makefile does nothing: you don't want to use `$(mkdir -p /home/directory)`, that tries to expand a make variable named, literally, `mkdir -p /home/directory` which doesn't exist so it expands to the empty string and is ignored.  You just want to write shell commands directly, not include them in `$(...)`.
Comment: I think this is an XY problem.  I think what you're trying to do is probably not a great way of doing things, but you didn't give us enough detail about your actual goals to help.
Answer: Put an eval right after the target::
target:
    $(eval VAR = /home/directory/file)

and remove the first line (VAR = ...).