How to use SoapUI's xml in php

Question: I have SoapUI working with this xml, but I need to consume that data on my server using php 5.3. I think I need to convert my $string into an array. the $xml = (array)simplexml_load_string($string); isn't throwing any errors, but the response from the call is NULL.
$string =   '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tran="http://www.cornerstoneondemand.com/Webservices/TranscriptAndTask">
    <soapenv:Header>
        <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsse:UsernameToken wsu:Id="UsernameToken-115E54B97689076253912">
                <wsse:Username>me</wsse:Username>
                <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">word</wsse:Password>
                <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">dvhXLFiL4Aoi2KQ==</wsse:Nonce>
                <wsu:Created>2016-10-19T15:26:02.539Z</wsu:Created>
            </wsse:UsernameToken>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body>
      <tran:GetTranscriptAndTasks>
         <tran:request>
            <Request corpName="learning">
                <User id="me">
                    <RequestTypes>
                        <Inbox/>
                        <Transcript inprogressOnly="false" pageNumber="1"/>
                        <Session pageNumber="1" upcomingOnly="true"/>
                        <Assigned assignedOnly="true"/>
                        <Approval approvalDateRequested="1967-08-13"/>
                        <Task pendingTasksOnly="true"/>
                        <SuggestedTraining pageNumber="1"/>
                    </RequestTypes>
                </User>
            </Request>
         </tran:request>
      </tran:GetTranscriptAndTasks>
    </soapenv:Body>
</soapenv:Envelope>
';

$xml = (array)simplexml_load_string($string);

$soapClient = new SoapClient($wsdl, array('trace' => 1));

$response = $soapClient->GetTranscriptAndTasks($xml);
var_dump($response);

Any help is greatly appreciated!
Edit:  I found https://github.com/sapankumarmohanty/lamp/blob/master/Crate-XML-2-Array that turns the xml into a nice array. But my result is still NULL...
I copied the WSDL here http://www.markforsyth.com/TranscriptAndTaskService.wsdl if it helps.
Answer: You can actually use xml code from SoapUI allmost direct.
Here are some code fragments from a code of mine:
Constructor for my class, that servs as a interface to a web service. wsdl is defined as a constant in the class:
public function __construct($username, $password) {
    $this->client = new SoapClient(self::wsdl);
    $this->client->__setSoapHeaders(self::securityHeader($username, $password));
}

Function in my class that return a security header used in the constructor:
private static function securityHeader($username, $password) {
    $nsWSSE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
    $nsWSU = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
    $nonce = 'xxxxx';

    $xml = '<nsWSSE:Security xmlns:nsWSSE="' . $nsWSSE . '" xmlns:nsWSU="' . $nsWSU . '">'
        . '<nsWSSE:UsernameToken>'
        . '<nsWSSE:Username>' . $username . '</nsWSSE:Username>'
        . '<nsWSSE:Password>' . $password . '</nsWSSE:Password>'
        . '<nsWSSE:Nonce>' . $nonce . '</nsWSSE:Nonce>'
        . '<nsWSU:Created>' . gmdate('Y-m-d\TH:i:s\Z') . '</nsWSU:Created>'
        . '</nsWSSE:UsernameToken>'
        . '</nsWSSE:Security>';

    $securityToken = new SoapVar($xml, XSD_ANYXML);

    return new SoapHeader($nsWSSE, 'Security', $securityToken);
}

A function in my class, that makes a request to the WS-function "abc":
public function abc() {
    $xml = ... paste your xml code from SoapUI here ...
    $param = new SoapVar($xml, XSD_ANYXML);
    return $this->client->abc($param);
}

Comment: This has gotten me closer than ever! Now instead of NULL I get back <Result xmlns="" errCode="-1" errDescr="Request xml is empty".  if I enter the SoapUI xml in the GetTranscriptAndTasks() or nothing, I get the same error.
Comment: Now I'm just guessing:
Your copy-past of the xml code should start at ``. But by starting at this point you mis the definition of the "tran" namespace, besause it is defined in the start of the xml code. Solution: add `xmlns:tran="http://www.cornerstoneondemand.com/Webservices/TranscriptAndTask"` to the `` item
Comment: @kurt-larson hopefully you can turn your smarts loose on this one too [link](http://stackoverflow.com/questions/40599636/php-calling-soap)

How to use SoapUI's xml in php


Warning: Exported activity does not require permission

Question: I recently created a project and added a splash and a main activity. I edited the manifest file and added the splash activity and the main activity in to it. After adding the main activity, it gives me a warning "Exported Activity Does not Require Permission". What is this warning that it gives me? my API version is android:15.
Please help,
Thank you!
this is my manifest file!
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sliit.droidman"
android:versionCode="1"
android:versionName="1.0">

<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="15" />

<application android:label="@string/app_name"
    android:icon="@drawable/ic_launcher"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SplashActivity"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
        android:name="com.sliit.droidman.main.MainActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="com.sliit.droidman.main.MAINACTIVITY" />
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
    </activity>
</application>

</manifest>

Comment: Now I did try something. for the second activity, the warning was not given when I delete the category tag! I recently updated my android SDK too!
Comment: I think this happens only if you have two or more opened projects in your Eclipse. If you close all other projects and you clean workspace, you will lose those warnings.
Answer: add this to your activity definition
android:exported="false"

Answer: This warning means that your activities are exposed to different-process apps that might instantiate them without any required permission.
for details see:
http://developer.android.com/guide/topics/manifest/activity-element.html
http://developer.android.com/guide/topics/manifest/activity-element.html#prmsn
Comment: and how to make it only my app instatiates them?
Answer: It could be due to the <action android:name="com.sliit.droidman.main.MAINACTIVITY" />. I don't know why you add that intent filter?
You normally don't need an intent-filter for other normal activities.
Comment: I actually followed a youtube tutorial on creating a simple android app. In that, the tutor just noted to put an intent filter. he dint mention the reason. :( that's why I put the intent filter, nd now Iget that I really dnt need an intent filter for the component! :) I just went thru the android developer zone! :) thank you for your time!
Comment: When I remove intent-filter, the application force closed. When I re insert it, it works fine.. Why?


Only require some folders from Composer and install to custom path

Question: I am starting to work on a new, longer running php project. I want to separate my files from the frameworks files as good as possible, to be able to update the framework without having to separate my files from the framework's files.
In Java, I'd use maven and have everything put in a lib folder. From there, I'd import the libs into my code. I learned that the same tool for php is composer (or I suspect so ;)) but I struggle to start using it.
I configured the project and composer in phpstorm and added a composer.json file, which looks like this (I removed the personal information):
    {
  "name": "example",
  "description": "description_text",
  "minimum-stability": "stable",
  "license": "proprietary",
  "authors": [
    {
      "name": "author's name",
      "email": "firstname.lastname@example.com"
    }
  ],
  "require": {
    "twbs/bootstrap": "v4.0.0-alpha.*",
    "laravel/laravel": "v5.2.*",
    "components/jquery": "2.2.*",
    "components/font-awesome": "4.6.*"
  },
  "config": {
    "vendor-dir": "laravel/laravel/public"
  }
}

As you can see, I tried to move everything into laravel's public folder, where Bootstrap and jQuery belong AFAIK (the path is basing on the observation, that laravel itself is placed in vendor/laravel/laravel). But of course, then laravel also gets put there.
On top of that, composer downloads more than I need. For example, I only need the content of bootstraps dist folder (css and js for bootstrap 4(and from them, only the min files)) but it also installs docs etc.
Because I'm not experienced in this, I don't know if what I want is possible or how to do it. I suspect that many of my problems come from the fact that I try to install laravel and the other stuff all in the same composer.json file.
Could you help me? :)
Regards
Christian
Comment: Aren't you supposed to use `composer.json` for **php** stuff and `jspm` for JS related code? Why are you mixing it all with php package manager? With `jspm` this is trivial, look it up.
Answer: Referencing this Laravel doc you want to place all "frameworks" in vendor dir which yes includes Laravel so remove your config composer.json.

The vendor directory contains your Composer dependencies.

Where you are trying to place items is for your resources

The public directory contains the front controller and your assets (images, JavaScript, CSS, etc.).

app is where you would place your classes and such.
As for these frameworks being bloated a bit with unneeded files I have not found a great way to clean them up outside of manually removing them all.
I was trying to draw a conclusion between maven and composer but it was making the post way bigger then I'd like. You are correct that this is the closest thins to a PHP maven.
EDIT
A better answer to your question as I re-read it is that your code is as tied to a framework version as it needs to be. I doubt any version during development will break backwards compatibility. At least I hope not and if you know of a new version coming maybe get on a beta/dev/nightly release.
As for my above statement is that composer is designed to work with this structure in the way described. When you want to use the psr-4 autoloading portion of composer as well this will help you greatly.
In any case think of vendor as your .m2 local repo.
Comment: Hi nerdlyist and thank you for your reply! Okay, if I understand you right, you are proposing to download laravel "in the normal way" and THEN modify the composer.json of the downloaded copy to require bootstrap and jQuery?

I don't know if this would be a "cleaner" way to go, but a possibility I imagine is using git submodules. With this, I could also keep laravel up to date during development, but I wouldn't get rid of the excess files as well.
Comment: @Christian no from what I can see in the Laravel doc there is a `bootstrap` directory that should handle the bootstrap need for you. Anything else you deem needed as frameworks will be added with composer install to `vendor`.


What is the simplest git workflow to replace copy-paste

Question: I am new to development and version control.
My present workflow to make changes to the project:

I created index.html with minimum features. Being new, I don't have enough confidence on various CSS tags that break a page, by changing something small. For now I am using Bootstrap, which is simple to use, but with limited features.
To add some new content I copy index.html to index_.html and change index.html. This is purely for a fear that if the page breaks, I instantly copy index_.html to index.html and have a sigh of relief. This is my workflow, which would change when I have a little experience.

How do I use Git just to this and nothing else for now. I don't want to copy index.html.
I have already read progit and seen following posts. They seem to point to a multiple users, versions and so on. It would take me a while to reach there. But if I know Git now, I can reach there in shape.
Workflow best practice with git and github?
Git Workflow Best practices
http://news.ycombinator.com/item?id=1826279
http://gweezlebur.com/2009/01/19/my-git-workflow.html
http://yehudakatz.com/2010/05/13/common-git-workflows/
http://reinh.com/blog/2009/03/02/a-git-workflow-for-agile-teams.html
http://nvie.com/posts/a-successful-git-branching-model/?
http://thinkvitamin.com/code/source-control/git/our-simple-git-workflow/
(I have placed all these links, so that someone knows I have read enough and does not pull this post down.)
None of them seem to answer my stupid question that is important for my evolution.
Comment: I'm trying to understand your problem / question. Could you make it more clear? Besides that you're not familiar with git.
Answer: To set up your repository for the first time:
git init
git add index.html
git commit

That saves a snapshot of your index.html exactly as it is now. Whenever you want to try something new, make changes directly to index.html.
If the page breaks, just do this:
git checkout index.html

That throws away your most recent changes and restores the last saved snapshot of index.html.
But if the change goes well, do this instead:
git commit index.html

That saves a new snapshot, so that you can go back to it if the next change breaks.
Now, as you know, git has a lot more power to it. You may find a better workflow that has advantages over the way you do it now. But if you want to start with an analogy to your familiar pattern, that's how to do it.
(By the way, whenever you run "git commit" a screen will appear asking you for a commit message -- you can use that to describe the changes so you can keep track of them. Nobody sees it but you, so if that doesn't sound useful, you could decide to ignore it.)
Comment: If it just said `git commit`, you'd be right. In the interest of keeping it simple, I passed the filename as an argument, which ignores the index and commits the file directly, as long as the file is already in the repo.
Comment: This is a perfect answer. I was thinking a branch is needed to do it. But this is a very simple solution. +1
Comment: Glad to hear it! One of the nice things about branching is that, if your change doesn't work right away, you can switch back to the working version without needing to completely throw away your attempt. But save that for another day, if you'd rather.
Comment: Etaoin - in your answer after "But if the change goes well, do this instead:" is missing a git add index.html before the git commit index.html.  If you commit without the add, there will be nothing to commit.


If $a\mid b$ iff $b = ak$, then if $a \nmid b$ could you also say that $b \ne ak$

Question: I am wondering if it's correct to say that if $x \nmid y$ then $y \ne xk$. In this scenario $x$ and $y$ are integers. I know that if $x \nmid y$ you're basically saying that there is no way that $x$ can be multiplied by another integer to equal $y$ and there be no remainder. Would this be the correct way to express that?
Comment: I suggest making the title a bit more clear
Comment: There is only one correct way to express mathematical sentences, and it is *with quantifiers*. Once you have done that for the case at hand, you'll see the semantical shortcomings of your current considerations.
Comment: [Here's a MathJax tutorial](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) :)
Comment: "you're basically saying that there is no way that $x$ can be multiplied by another integer to equal $y$ $\require{cancel}$  $\cancel{\text{ and there be no remainder}}$".  You do not need to talk of remainders when you are *multiplying* numbers.  But otherwise, that is exactly correct.
Answer: Yes.
$x \nmid y$ means that there are prime factors (along with their multiplicity) in $x$ that don't exist in $y$. So no matter what you multiply with $x$, it will not create those prime factors in $y$.
The logical proposition would be something equivalent to this:
$$
\forall x,y \in \mathbb{Z} \;\;\; \Bigl [x \nmid y \iff \lnot\exists k \in \mathbb{Z} : y=kx \Bigr]
$$
Comment: `$\nmid$` produces $\nmid$
Answer: When you introduce $k$ out of no-where you need to introduce it.
To say quote "$a|b$ iff $b=ka$" unquote, is meaningless nonsense as we have never claimed what $k$ is and $k$ can be anything.  For example, $3|12$ but $12 \ne 3\cdot 516$.  What you meant to say, and the correct thing to say is $a|b$ iff there exist an integer $k$ so that $a=bk$.  In that way $3|12$ and there exists an integer $k$ so that $12 = 3k$.  That integer happens to be $4$ and does not seem to have anything to do with $516$ or any other integer..
.......
Okay.... that was a little pet peeve of mine.
Now to your question.
.....
The definintion of $a|b$ means that there exists an integer $k$ so that $b=ak$.
So if $a\not \mid b$ that there does not exist any integer $k$ so that $b = ak$.  And if there doesn't equal any integer $k$ so $b=ak$ that means for any integer at all, if we label that integer as $k$ then $b\ne ak$.
So we can say if $a\not \mid b$ then for any integer $k$ we have $b\ne ak$.  For instance, $3\not \mid 13$ so $13 \ne 3k$ for any integer $k$.  If $k=4$ then $13 \ne 3\cdot 4$.  If $k =5$ then $13 \ne 3\cdot 5$.  If $k = 516$ then $13 \ne 3\cdot 516$.
Because if there were an integer $k$ so that $13=3k$ then.... well, that is the definition $3|13$.
And if we know that for $a,b$ that there can not be any integer $k$ so that $b=ak$ then $a\not \mid b$.  Because if $a\mid b$ then we'd know there was such an integer.
So....
yes.
$a\not \mid b \iff$ for any integer $k, b \ne ak$.
========
By the way notice if you have and  $A \iff B$ statement.  You always have a $A$ is not true $\iff B$ is not true statement.
Because if $A$ not true, then if $B$ were true we'd have $A$ is true (because $A\iff B$).  But $A$ is not true (because we were told that) so $B$ is not true.  So $A$ is not true $\implies B$ is not true.
And if $B$ is not true, the we can not have $A$ being true (because that would imply by $A\iff B$ that $B$ is true) so $A$ is not true.  So $B$ is not true $\implies A$ is not true.
So  $A$ is not true $\iff B$ is not true.
....
And $A \iff B$ implies the exact same thing as: not $A \iff $ not $B$


How to support 20 feet of 4 inch pvc drain pipe horizontally along a concrete wall?

Question: I need to run 20 feet of 4 inch drain pipe horizontally along a concrete wall. Someone suggested saddle clamps and anchors. I am not sure exactly what type to use, especially if the pipe is full of rain water.
Comment: I think we can safely assume that the word was used to differentiate from a vertical section. It's a useful descriptive hint with no obvious alternative.
Comment: If a tiny bit tilted so it drains, that may reduce mosquito problems.
Answer: Any of the pipe hangers available at your local big-box home improvement store are designed to support a full pipe. They would be just decorations if they didn't...
Pick a type that seems simplest to you to use, get appropriate fasteners (you're attaching this to concrete, a simple screw or nail isn't going to do the trick), ensure you've got the proper 1/4" per foot of run slope (i.e. the drain end needs to be 5" lower than the input end after 20') and have at.
You can use J-hooks, saddle clamps, or just about anything else designed for the purpose.
Comment: Pipe hanger strap is another method, if "cost effective but relatively ugly" is OK in the application.
Comment: Very true, @Ecnerwal. I'd go with a few extra hangars if using just strapping, but that's me...
Answer: If you want a robust solution, sprinkler pipe hangers with hex bolts would do well. You could install simple angle brackets on the wall (with the horizontal portion at the top) and drill for these. This would also give you some degree of adjustment in case your brackets weren't exactly positioned.


I have installed kde plasma on Ubuntu 20.10 but after I logged out, there is no option to login back to kde. What can I do to have kde back?

Question: Which command can I execute to get back to kde plasma from ubuntu's terminal? Thanks
Comment: On the GDM login screen, click on your user name. Before entering the password, in the bottom right of the GDM screen, click on the gear icon. When you click this, do you see an option for KDE?
Answer: It seems that you have incomplete installation of KDE Plasma.
The complete set of packages is provided by the kubuntu-desktop task package.
To install it use command below:
sudo apt-get install kubuntu-desktop^

then confirm sddm login manager selection, reboot and login to Plasma.


How to remove XML parent node based on child conditions PHP

Question: Hi I am trying to clean up xml file out of positions I dont need. Here is my code so far:
<?php
    $doc = new DOMDocument;
    $doc->load('merg.xml');

    $xpath = new DOMXPath($doc);

    $products = $xpath->query('//offer/products/*');

    printf('There is %d products

', $products->length);

    function findStopPointByName($xml, $query) {
      $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZĄŻŚĆŹĆÓŁ";
      $lower = "abcdefghijklmnopqrstuvwxyzążśćźńół";
      $arg_query    = "translate('$query', '$upper', '$lower')";

      return $xml->query("//offer/products/product/description/name[contains(text(),$arg_query)]");
    }
    foreach(findStopPointByName($xpath,'Skór') as $node)
    {
        $node->parentNode->removeChild($node);
    }

    $doc->save('merg_fixed.xml');
?>

Structure of XML:
<offer>
 <products>
  <product>
   <description>
    <name>Name of the product</name>
     ...
    </name>
     ...
   </description>
  </product>
 </products>
</offer>

I am trying to remove all PRODUCT where its NAME contains 'Skór' in any case (Skór, skór, SKÓR - is enough). Funcion findStopPointByName returns DOMNodeList of correct length, but nothing is removed from actual XML file, please help.
Comment: Try using this XPath query instead : `//offer/products/product[description/name[contains(.,translate('$query', '$upper', '$lower'))]]`
Comment: It produces exactly same result. Do I try to remove nodes in a correct way?

Maybe it will be simpler to write 3 querries for there type of case - Skór, skór, SKÓR ?
Answer: First, you can directly find node product with the condition
Second, to make search case insensitive, you can translate node text in any case but should use pattern in the same case. As the result, your code may be so
 function findStopPointByName($xml, $query) {
  $upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZĄŻŚĆŹĆÓŁ";
  $lower = "abcdefghijklmnopqrstuvwxyzążśćźńół";
  $arg_query    = "translate(text(), '$upper', '$lower')";
  $q = "//product[description/name[contains($arg_query, '$query')]]" ."\n";
  return $xml->query($q);
}

$doc = new DOMDocument;
$doc->load('merg.xml');
$xpath = new DOMXPath($doc);
foreach(findStopPointByName($xpath,'skór') as $node)
    $node->parentNode->removeChild($node);

echo $doc->saveXML();

Demo on eval.in
Comment: Thank you for your answer!
I have tried it and it is not working on my file maybe the reason is different construction of `` node `Skórzane BUTY CZARNE z KLAMRĄ Moda i STYL`
Comment: I am sorry I have made a small typo when converting your answer to my code. It works like a charm. Thank you!


PHP included HTML relative path of external JS & CSS

Question: I am trying to use PHP to read, then modify and echo an HTML file.
The included HTML file contains external JS, CSS references - all relative paths
for example...

Problem :
The location of the PHP modifier file is not the same as the location of the included HTML file, and therefore the external includes are not loaded. I guess...
The solution of using absolute paths to reference external resources in the HTML file is not ideal to say the least...
What can be done to tell PHP that the path context of the included HTML file is the same as the directory from which it is being included and NOT the directory of the modifier file?
Thanks!
Comment: Maybe add a `/` prior to the path? like `/js/myJavascript.js` and then it would related to the current path.
Comment: I think you would need an HTML parser to change the DOM of the `src` attributes in your included HTML.
Comment: Well, the only solution I can think of is either changing the dom or creating a function that returns the relative path, then, adding that function to all your included HTMLs
Comment: @OfirBaruch - tried, not working... thanks!
Comment: @odedta - not an ideal solution, further referencing of js, css can occur after the page was loaded... thanks anyway!
Answer: Found a solution!
<base href="path_to_the_html" target="_blank">

according to W3Schools :
This would specify a default URL and a default target for all links on a page...
Comment: @odedta - I found some more info on the outcomes of using this approach here : http://stackoverflow.com/questions/1889076/is-it-recommended-to-use-the-base-html-tag


Tab android content sometime gone or dissapear

Question: I'm working on android tab right now, i was wondering why sometime content of my tab is gone,,by default android initializing and create 2 first tab content, i check by print the log in console, and when i click the third tab it will attach and initialize,, and sometimes when i clicked back in first tab or second tab, my content is gone like invisible or something, here my code
<code>        ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
        adapter.addFragment(ArticleFragment.newInstanceFeatured(1, ArticleFragment.FEATURED_LATEST), ArticleFragment.FEATURED_LATEST.toUpperCase());
        adapter.addFragment(ArticleFragment.newInstanceFeatured(1, ArticleFragment.FEATURED_POPULAR), ArticleFragment.FEATURED_POPULAR.toUpperCase());
        adapter.addFragment(ArticleFragment.newInstanceFeatured(1, ArticleFragment.FEATURED_TRENDING), ArticleFragment.FEATURED_TRENDING.toUpperCase());

        // Set up the ViewPager with the sections adapter.
        viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);
        viewPager.setAdapter(adapter);

        tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
</code>
here my adapter for the tab content
<code>    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
</code>
I have Latest, Popular, and Trending Tab, each tab contain recyclerview, i retrieve data from my API and put them on it.., i know my code is working perfectly i completely success to retrieve and set the list but sometime if I change tab from one to another it happen, like  the content gone or missing or something, I implement swipe refresh too, sometime i try to swipe to refreshing the data and the Recycler view back and sometime it given null value... i have no idea what i gonna do, i think it work in the process but i don't know why.. please if you have same experience i would love to hear it.. thanks...
Answer: i found something, turns out it not tab but my recycler reinitialize each tab clicked,,,
Answer: <code>ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
</code>
Comment: Weclome to SO. Please not that code only answers do not fulfill the standards of SO. See http://stackoverflow.com/help/how-to-answer


Trying to arrange sums in neat way

Question: I am trying to write the following summations as compactly as possible using summation and enumeration:

$$\frac{y_1}{1+y_2+y_3+y_4+y_5}+\frac{y_2}{1+y_3+y_4+y_5}+\frac{y_3}{1+y_4+y_5}+\frac{y_4}{1+y_5} \leq 1$$
$$\frac{y_1+y_2}{1+y_3+y_4+y_5}+\frac{y_2+y_3}{1+y_4+y_5}+\frac{y_3+y_4}{1+y_5} \leq 1$$
$$\frac{y_1+y_2+y_3}{1+y_4+y_5}+\frac{y_2+y_3+y_4}{1+y_5}\leq 1$$
$$\frac {y_1+y_2+y_3+y_4}{1+y_5}\leq 1$$

I wrote it as following:
$$\sum_{k=1}^4 \frac {y_k}{1+y_{k+1}+...+y_5} \leq 1$$
$$\sum_{k=1}^3 \frac {y_k+y_{k+1}}{1+y_{k+2}+...+y_5} \leq 1$$
$$ \sum_{k=1}^2 \frac {y_k+y_{k+1}+y_{k+2}}{1+y_{k+3}+...+y_5} \leq 1$$
$$ \frac {\sum_{k=1}^4 y_k}{1+y_5} \leq 1$$

Is there any enumeration to combine the $4$ summations?
Answer: If I'm not mistaken, the following should be an equivalent expression:
$$\forall i \in \{1,2,3,4\}: \sum_{k=1}^{5-i} \frac{\sum_{j=k}^{k+i-1} y_j}{1+\sum_{j=k+i}^{5} y_j} \leq 1.$$
It is obviously way less clear and intuitive than the original, though.
Comment: +1. Please, do the same at the denominator. :)
Answer: What you gain it compactness you lose (massively) in comprehsion but:
$\frac {y_1}{1 + y_2 + ... + y_5} + .... = \sum_{k=1}^4 \frac {y_k}{1+\sum_{j=k+1}^5 y_j}\le 1$
And $\frac{y_1+y_2}{1+y_3+y_4+y_5}+\frac{y_2+y_3}{1+y_4+y_5}+\frac{y_3+y_4}{1+y_5} = \sum_{k=1}^{5-1}\frac {y_k + y_{k+1}}{1+\sum_{j=k+2}^5 y_j}\le$
And then you get
$[\sum_{k=1}^{5-m}\frac {\sum_{i=k}^{k+m-1} y_i}{1+\sum_{j=k+m}^5 y_j}  \le 1]|_{m=1}^4$
But really, if a were a reader  and I came across that... I'd hit you.

Trying to arrange sums in neat way


Do all Linux distros use the same kernel?

Question: By "the same kernel", I mean the one which was originally created by Torvalds and then updated by people here: http://www.kernel.org
Is it true that different distros all keep the kernel unchanged(of course they will update the kernel when there is a new version from the above site), and only make changes to the various utilities of their own?
Answer: All distros use the same "Linux" kernel, however all distros make slight changes to it in order make the kernel work best for them, however these changes will almost always get uploaded back to the top where Linus will merge them himself. So all use the Linux kernel, however they all have a few different lines of code in them to make them work best for that distro. It is also worth noting that distros will ship with the version of the kernel that they see fit for each version. Some distros choose a newer kernel then others. The main pro of a new kernel are improvements in driver's and hardware compatibility. The con is a loss in stability as all new code has bugs in it. So you trade features for stability. This is why distros known for being more stable will usually always ship an older kernel than the more risky distros. To find what kernel you are running enter:
<code>uname -r
</code>
This will show you what you are running in the version of Ubuntu you have on your computer currently. Hope you enjoy!
Answer: Yes and No will be the answer.
"The Linux kernel" is a fairly complicated piece of software which can be compiled in a number of different ways. Basically, a configuration file is set up with a laundry-list of options, and this file subsequently determines exactly which blocks of source-code are or are not included in "the Linux kernel" for your system. (The same process also determines which kernel modules are built.)
Generally speaking, a distro writer will do all of that "heavy lifting" for you:
They'll compile one or more kernels, using config options that they have carefully selected, and include those (in binary form) in their distributions. They might even include custom patches.
So, the answer to your question is both 'yes' and 'no'.

Yes, several distros might use "Linux version X.Y.Z."
No, they might not use the same configuration options when building it.

Courtesy: sundialsvcs' comment here.
Also check out this post on stackoverflow for some more related information.
Answer: Yes, It is true, Ubuntu uses same kernel which was originally created by Linus Torvalds, but of course the updated version.
The kernels of Linux Distributions are updated from the original one and See this link to get the view of kernel version changes.
Ubuntu is based on latest stable linux version released, more correctly, it is based on the kernel of debian (more correctly, from debian unstable release, except the LTS's which are derived from Debian testing) and then add some more distro specific customization.
See these links for more information

https://help.ubuntu.com/community/Kernel/
http://en.wikipedia.org/wiki/Linux_kernel
Comment: They don't make changes to the kernel, or add anything at all? hmmm, if so, why ubuntu is using `upstart` while other distros use `sysvinit` for initiation? The kernel does include the system initiation function, does it?
Comment: @xczzhh Yes, I said they *change*. I didn't say that, the don't change. Please read the answer again
Comment: @xczzhh: in any case, the system init function is not part of the kernel. init is the first user space program that the kernel executes. It's not part of the kernel.
Answer: They do use the same kernel uploaded at http://www.kernel.org.
But as per distribution , goals of their respective projects , to what Systems are they targeting their releases shapes the customization of their respective kernels.
For a rolling release it will be bleeding edge kernels , for a stable release it will based on Upstream stable release.
For example 3.5 is currently in Quantal release but 3.2 is for Stable Precise release and its future updates..
Ubuntu customized kernels are provided at  http://kernel.ubuntu.com/~kernel-ppa/mainline .
fedora customized kernels https://admin.fedoraproject.org/updates/kernel .

The best way to understand is for example following Ubuntu Kernel team development.
rolling kernel upgrade policy for 14.04
Canonical Kernel Team Voices
Kernel Roadmap
Answer: Kernel get changes as per features requirement in different Linux distros. Linux kernel is developed by Linux Foundation community. You can get Latest Kernel here.


Joint probability distribution of two Bernoulli r.v. with a correlation $r$

Question: Suppose we have $X \sim Be(p_1)$, $Y \sim Be(p_2)$ and $corr(X,Y) = r$.
How does the joint distribution table look like?
For example, if $r = 0$ it is
$$
\begin{array}{c|c|c}
\cdot & T & F
\\
 \hline
T & p_1p_2 & p_1(1-p_2)
\\
 \hline
F & (1-p_1)p_2 & (1-p_1)(1-p_2)
\\
\end{array}
$$
Answer: Let $R=Cov(X,Y)= r*\sqrt{p_1(1-p_1)}*\sqrt{p_2(1-p_2)}$
Let $0\leqslant a,b,c,d \leqslant 1$ be the respective probabilities of TT, TF, FT and FF.
We need to solve the system:
$a+b=p_1$
$a+c=p_2$
$a+b+c+d=1$
$a=R+p_1p_2$
We get:
$a=R+p_1p_2$
$b=p_1(1-p_2)-R$
$c=p_2(1-p_1)-R$
$d=1+R-p_1-p_2+p_1p_2$
Thanks to @Henry for corrections.
Comment: @Veliko: given $p_1$ and $p_2$ and letting $s=\sqrt{p_1(1-p_1)p_2(1-p_2)}$ it may be that $r$ is constrained to
$$\max\left(-1,-\dfrac{ p_1p_2}{s},-\dfrac{(1-p_1)(1-p_2)}{s}\right) \le r \le \min\left(1,\dfrac{p_1(1-p_2)}{s},\dfrac{(1-p_1)p_2}{s}\right)$$
Comment: I suspect it may be more complicated than $a=r+p1p2$: consider $p1=p2=\frac12$ and $r=1$.  Perhaps something like $a=p1p2 + r \sqrt{p1(1-p1)p2(1-p2)} $ *unchecked*
Comment: @Veliko: Yes - I think your example would give $a=0.5985$ and $b=-0.0985$ with the latter number being clearly impossible.  I suspect with $p_1=0.5,p_2=0.9$ then you must have $-\frac13 \le r \le \frac13$
Comment: Your $a+d=r+p1p2$ looks unlikely if $r=0$, or if $r=1$ and $p1=p2$
Comment: @Henry : thanks, corrected.
Comment: Oh yeah, I used covariance instead of correlation...
Comment: @Henry, do you think that there is some restriction on the values $p_1$ and $p_2$ depending on the $r$? For example is it possible   that $r = 0.99$ and $p_1 = 0.5, p_2 = 0.9$?
Comment: @Henry, I think the s should go inside the min but the 1 must stay without $s$.
Comment: @Evargalo $d = 1 +R -p_1-p_2-p_1 p_2$.
Comment: @Veliko, Yes - I will delete my earlier comment.
Comment: @Evargalo For sure $d = (1-p_{1})(1-p_{2}) + R$ in order for the margin probabilities to be correct. The sign of R is mistaken in your nice answer.
Answer: Hint:
Note that here $\Pr(X=1\wedge Y=1)=\mathbb EXY$ and that the other $3$ probabilities can easily be deduced from this one.
So it is enough to find $\mathbb EXY$ and for this you can use the equality:
$$\mathbb EXY-\mathbb EX\mathbb EY=\text{Cov}(X,Y)=\text{Corr}(X,Y)\sqrt{\text{Var}X\text{Var}Y}$$
Comment: Yes. With the mentioned values of $p_1,p_2$ we arrive at $p=0.15r+0.45$ where $p:=\mathbb EXY=P(X=1=Y)$. This however with $p\leq\min(p_1,p_2)=0.5$. Then $r$ cannot take value $0.99$ (since that leads to $p>0.5$).
Comment: This is a good idea, thank you.
Comment: Do you think that there is some restriction on the values $p_1$ and $p_2$ depending on the $r$? For example is it possible   that $r = 0.99$ and $p_1 = 0.5, p_2 = 0.9$?


reading ipv6 instead of IPv4 in PHP

Question: When my PHP website reads my visitor IP address it shows in the IPv4 format.
However when I go to a third party site (such as https://www.whatismyip.com/) my visitor address shows an IPv6 format.
How do I get my PHP website to read/listen for/display the longer IPv6 format of the visitor IP address?
Comment: you'd only get that if someone visited your site using ipv6. if they're connecting with ipv4, there will be NO ipv6 address to capture, and vice versa. just because YOU are capable of using ipv6 doesn't mean THEY are as well...
Comment: To build on what @MarcB said, that's why its `$_SERVER['REMOTE_ADDR']` instead of something like:  `$_SERVER['REMOTE_IPV4']`
Comment: So...someone visiting my site needs to be connected using ipv6.

That makes sense.

So why do I see two different IP addresses if I go to two sites (mine and whatismyip.com) and one gives me an ipv4 address and the other gives ipv6?
Comment: Here is what I see: http://imgur.com/ZGQtKv5
Comment: because you connected to the "mine" site with ipv4 for whatever reason, and ipv6 with the whatismyip one. even if your server is configured for ipv6, all of the routers between you and that server have to support ipv6 as well, or be using an ipv6-over-v4 tunnel
Comment: Thanks, Marc. That makes sense.
Answer: If you get IPv4 addresses in IPv6 format this is probably because your webserver is listening for all requests (IPv4 and IPv6) on a single IPv6 interface. In that case when it reads the peer address it always gets an address in IPv6 format resulting IPv4 addresses to be mapped by prepending ::ffff: to the IPv4 address.
So this is a configuration of your webserver and not of PHP.
If you want to have the IPv4 addresses in that format, you can just prepend the IPv4 address with the fixed string "::ffff:". But why would you want to do this?
Also you will always get the IP address for the IP version you used to connect to the server. So when you wonder why you don't get a real (not a mapped) IPv6 address it's probably because your browser connected to the server using IPv4. Either because your server is not able to listen to IPv6 requests or because its IPv6 connectivity is much slower than the IPv4 connectivity. In that case browsers often fall back to use IPv4 to provide better performance to their user.
Comment: If you want the IPv6 addresses of your users: update your server to support connections by IPv6. Therefore you need IPv6 connectivity and an AAAA entry for your domain in the DNS.
To make sure dual users connect by IPv6 you can also use a subdomain only accessible via IPv6 and connect to this using a JavaScript snippet in your page.
Comment: I'm starting to understand. I thought if you were connected via IPv6, then all websites would be able to see the IPv6 address.

Note: I wanted the true IPv6 if available because it would give me a more accurate reading of the end users location.
Comment: Thank you! Holy cow. This is what I have been looking for:

• "update your server to support connections by IPv6"
• "IPv6 connectivity"
• "an AAAA entry for your domain in the DNS".
• "To make sure dual users connect by IPv6 you can also use a subdomain only accessible via IPv6 and connect to this using a JavaScript snippet in your page."

I knew there was a way.

reading ipv6 instead of IPv4 in PHP


Simplify the trigonometric expression

Question: Simplify the expression $$\left(1-\frac{\cos61^{\circ}}{\cos1^{\circ}}\right) \left(1-\frac{\cos62^{\circ}}{\cos2^{\circ}}\right)\cdot ...\cdot \left(1-\frac{\cos119^{\circ}}{\cos59^{\circ}}\right)$$
Answer: We have
$$\begin{align}\prod_{i=1}^{59}\left(1-\frac{\cos(60^\circ+i^\circ)}{\cos i^\circ}\right)&=\prod_{i=1}^{59}\frac{\cos i^\circ-\cos (60^\circ+i^\circ)}{\cos i^\circ}\\&=\prod_{i=1}^{59}\frac{-2\sin(30^\circ+i^\circ)\sin (-30^\circ)}{\cos i^\circ}\\&=\prod_{i=1}^{59}\frac{\sin(30^\circ+i^\circ)}{\cos i^\circ}\\&\color{red}{=}\prod_{i=1}^{59}\frac{\sin(90^\circ-i^\circ)}{\cos i^\circ}\\&=\prod_{i=1}^{59}1=1.\end{align}$$
The equality "$\color{red}{=}$" comes from that the numerator is
$$\sin31^\circ\sin 32^\circ\cdots\sin89^\circ=\sin89^\circ\sin88^\circ\cdots\sin31^\circ.$$
Answer: Hint
Reduce each piece of the product to the same denominator and use $$\cos(p)-\cos(q)=-2\sin[(p+q)/2] \sin[(p-q)/2]$$ Some nice things would come out.
I am sure that you can take from here.

Simplify the trigonometric expression


Keep Firefox as default browser but open youtube links in Chrome

Question: Is there a possibility to open Youtube/Twitch/... - Links in Chrome instead of my default browser (Firefox)?
The reason is, that all browsers are very slow on my (fresh) installation of 15.10 but things like Youtube, Twitch, Google maps are unusable in Firefox. So, if I click on a link that's on Youtube, I'd like it to be opened in Chrome instead of Firefox. Especially, when I click on links in my RSS in Thunderbird. I tried the "Open with" Extension in Thunderbird, but when I right click on the link on the URL it only gives me "Copy Link location".
Comment: There's an addon called "open with".
Comment: Thanks, but as I wrote in the last sentence, when I right click on the link on the URL it only gives me "Copy Link location".
Comment: You could set your default browser to a shell script that determines based on the URL what browser to open.
Answer: One solution is to go ahead and copy the link location. Then paste the URL into the address bar in Chrome. To save time,have Chrome running the background before you open Thunderbird.
Probably better, though, is to install the add-on called "Open-With" by Geoff Lankow. This allows you to select on the fly the browser you want to open a particular link. You can find it for Thunderbird here. There is also Firefox version here.
Comment: Thanks, but as I wrote in the last sentence, when I right click on the link on the URL (using the Open with extension) it only gives me "Copy Link location"


Android Identifying Multiple Button

Question: I have morethan 100 button in my MainLayout.xml and i want to handle click on each. I want to group all the button and then listen to click of the group button, get the ID and put it into String and then use it as my base id to query from my Sqlite Databse Table. How can i do this? so far i have this on my MainClass.java.
MainClass.java
public class MainClass extends AppCompatActivity implements View.OnClickListener {
    Button B0,B1,B2,B3....;
    String baseId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        buttonInitializer();
    }

     public void buttonInitializer(){
        B0 = (Button)findViewById(R.id.B0); B0.setOnClickListener(this);
        B1 = (Button)findViewById(R.id.B1); B1.setOnClickListener(this);
        ...
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.B0:
                baseId = "B0";
                break;
            case R.id.B1:
                baseId = "B1";
                break;
            ..........
            default:
                break;
        }
        QueryFire(); // Fire a query
    }

   Public void QueryFire(){
      //Fire the query with id of the clicked button
   }
}

As you can see if i continue doing this, i will have Long Code, i want to shorten my code, instead of the above code, i'd like to group the button and then listen of each click just like RadioButton, but NOTE. i dont want to use RadioButton. I'm trying to implement this seudo code.
// Put the button into RelativeLayout or something and use it to group the button
// OnClick of Each Button inside the GroupButton:
   // Get the ID of the Clicked Button:
   // Put the ID of Button into String:
   // and FIRE my query with ID of Button

Any help woul be appreciated! Thank You Very Much!!!
Answer: You should be able to specify a String for the "android:tag" attribute for each button in your xml layout, as well as an "android:onclick" attribute. This should eliminate the need for all of the findViewById() and setOnClickListener() calls.
Then, in your onClick method, you can just do something like baseId = (String) view.getTag()
Answer: Might be a bit of a stretch but why not use a ListView with a custom adapter? each adapter will hold a button (or whatever you want) and with every click on button you will get the id (the position of clicked element). Its far more easy on the memory as well :)

Android Identifying Multiple Button


Concatenate 2 dictionaries and Add parent to it

Question: I have multiple dictionaries which i need to concatenate and add a parent in the end. How do i achieve this
dict1 = { "project":"test1", "summary": "A Test","issuetype": {
          "name": "Test"
       }}

dict2 = { "project":"test2", "summary": "B Test","issuetype": {
          "name": "Test"
       }}

I need it in format
dictParent = {fields: {
{ "project":"test1", "summary": "A Test","issuetype": {
          "name": "Test"
       }}
{ "project":"test2", "summary": "B Test","issuetype": {
          "name": "Test"
       }}
}}
}

I used below code
dictParent = {}
dictParent["fields"] = dict1, dict2

it kind of works the problem is it comes as as array but i want fields to be parent object not array
{fields: [
{ "project":"test1", "summary": "A Test","issuetype": {
          "name": "Test"
       }}
{ "project":"test2", "summary": "B Test","issuetype": {
          "name": "Test"
       }}
}}
]

Comment: You want your fields key to have some values. If you don't want them as a list what's the expected format for the value then? It can be any container like set, tuple or even an iterator, etc. Please specify what's the exact expected output and preferably why!
Comment: dictParent = {fields: {
{ "project":"test1", "summary": "A Test","issuetype": {
          "name": "Test"
       }}
{ "project":"test2", "summary": "B Test","issuetype": {
          "name": "Test"
       }}
}}
}

In the baove format filed contains a dict of values but no keys for it

So the format is completly wrong
Answer: This

dictParent = {fields: {
{ "project":"test1", "summary": "A Test","issuetype": {
          "name": "Test"
       }}
{ "project":"test2", "summary": "B Test","issuetype": {
          "name": "Test"
       }}
}}
}

is invalid python:

dictionary are key:value pairs -your second dictionary has no key
your fields is not a string but a vairable specifier - my guess is you missed the 'fields' around it

You can store your data like this (content shortened to stay below 80 char/line):
dictParent = {"fields": [ {"project":"t1", "summary":"A", "issuetype": {"name": "Test"}},
                          {"project":"t2", "summary":"B", "issuetype": {"name": "Test"}}] }

wich would make dictParent a dictionary with 1 key ('fields') that has a list of dictionaries as value.
You can create it from dict1 and dict2 like so:
dictParent = { "fields": [dict1, dict2] }

Or you can specify different keys  (content shortened to stay below 80 char/line):
dictParent = {"fields_1": {"project":"t1", "summary":"A", "issuetype": {"name": "Test"}},
              "fields_2": {"project":"t2", "summary":"B", "issuetype": {"name": "Test"}}}

which would make dictParent a dictionary of dictionaries:
dictParent = { "fields_1":dict1, "fields_2":dict2] }

Comment: Thanks after digging more i figured out that i was i needed array not the format i originally posted. Thanks for the help


rails - assets are still served even if commented in app.js

Question: I am trying to use react-bootstrap but I'm struggling with the following error:

Uncaught Invariant Violation: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded

I read that it has something to do with the fact that react is referenced multiple times and I'm trying to figure out why and where I did this mistake.
So, in order to solve this, I tried uncommenting some lines in application.js, maybe there is the problem (I thought some lines have imported inside react - but I think the scope would be only that file so it wouldn't matter anyway)
This is my application.js
//#= require jquery
//#= require bootstrap-sprockets
//#= require underscore
//#= require backbone
//#= require backbone_rails_sync
//#= require backbone_datalink
//#= require react
//#= require react_ujs
//#= require react_bootstrap
//= require utils
//= require components

components.js
//#= require underscore
//#= require backbone
//#= require react-server
//= require components/admin/general
//#= require components/admin/settings

Initially they were all uncommented, but now I commented some of them. I ran
rake assets:clean
rake assets:precompile

once and the second only rake assets:clean but Rails is still serving old assets. Why?
I changed the following inside development.rb
config.assets.digest = false
config.assets.debug = true

and inside my console when I start rails server and navigate to some path, it references all my scripts, which I do not want..
In the following application.js, react is commented so any code that references React inside components SHOULD NOT WORK, but IT WORKS.
How to tell Rails to reset assets mentioned in application.js?
Answer: Well..nevermind
I found out that comment is done by removing the equal sign, not adding #


Command to know software version from terminal before installing

Question: Am trying to install Bibletime v2.9.2. I purged v2.8, added the crosswire ppa (ppa:pkgcrosswire/ppa) to my software sources and did a sudo apt-get update.
Since I don't have a fast internet connection, I wanted to know the Bibletime version available before installing it via terminal. I'd be glad if anyone can point me in the right direction.
Thanxs.
Answer: Try sudo apt-cache policy bibletime.
This command will also tell you which source ships what version. Additionally, you'll see the priorities of the sources.


How do I get a SAA7231 TV Tuner card working?

Question: I have recently bought a new pc and installed Ubuntu (as you do) all works well but my tv tuner isn't being detected.
The model is a SAA7231, can someone please help me install it.  What steps do I need to take firstly to give you all the correct info?
Thanks in advance.
Answer: For a bunch of DVB cards you usually need to install the firmware and then a TV application like TVtime:

linux-firmware-nonfree
tvtime

Unfortunately this is the best source for a driver that I could find, which appears unmaintained. Looks like some guys tried to get it working in SUSE but also it didn't look good.
Comment: I have winfast TV tuner, tvtime didn't help, can you suggest some driver? Thanks.
Comment: @umprirsky It's probably best to ask a separate question for that card.
Comment: That driver is a 404 now.


Apollo-Server, can I change AWSDateTime to Date when serving locally?

Question: I have a graphql server on AWS AppSync that I'm trying to create a local Apollo-Server for to test locally. When I start the local server on a test file (localSchema.ts) I get the error: Unknown type "AWSDateTime". the date needs to be AWSDateTime for AppSync, is there a way to conditionally make that a Date type?
Here is the schema:

const typeDefs = gql`
  directive @aws_api_key on OBJECT
  directive @aws_cognito_user_pools on OBJECT
  directive @aws_api_key on FIELD_DEFINITION
  directive @aws_cognito_user_pools on FIELD_DEFINITION

  enum DeliveryMethodEnum {
    PRINT_BACK
    DELIVERY
    DELIVERY_WITH_REPORTS
    PICKUP
  }

  enum CompanyStatusEnum {
    ON_BOARDING
    ACTIVE
    TERMINATED
    FROZEN
    NSF
    PENDING_1ST_PAYROLL
    TEST
  }

  type Company @aws_api_key @aws_cognito_user_pools {
    id: Int!
    companyNo: String
    legalName: String
    dba: String
    fein: String
    companyStatus: CompanyStatusEnum
    companyType: String
    logoKey: String
    hubspotId: String
    productTourStarted: Boolean
    productTourDashboardStarted: Boolean
    hasWatchedDemoVideo: Boolean
    groupId: Int
    createdBy: String
    createdAt: AWSDateTime
    updatedBy: String
    updatedAt: AWSDateTime
  }

  type CompanySingleResponse @aws_api_key @aws_cognito_user_pools {
    resCode: Int!
    resMessage: String
    data: Company
  }

  type Query {
    getCompanyById(id: ID): CompanySingleResponse
      @aws_api_key
      @aws_cognito_user_pools
  }
`;

export default typeDefs;```

Answer: It seems like I need to define it with scalar AWSDateTime
Comment: If you mean defining the scalar I was able to do it in the .graphql file
Comment: Where is this configured?


dpkg-query: error: package 'grub-legacy-ec2' is not installed

Question: root@sites:~# apt-get update
Reading package lists... Done
root@sites:~# apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages were automatically installed and are no longer required:
  linux-modules-4.15.0-62-generic linux-modules-4.15.0-64-generic linux-modules-4.15.0-65-generic
  linux-modules-4.15.0-66-generic linux-modules-4.15.0-70-generic
Use 'apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up linux-image-4.15.0-72-generic (4.15.0-72.81) ...
Setting up linux-image-unsigned-5.4.2-050402-generic (5.4.2-050402.201912042231) ...
Processing triggers for linux-image-4.15.0-72-generic (4.15.0-72.81) ...
/etc/kernel/postinst.d/initramfs-tools:
update-initramfs: Generating /boot/initrd.img-4.15.0-72-generic
cryptsetup: WARNING: failed to detect canonical device of /dev/sda1
cryptsetup: WARNING: could not determine root device from /etc/fstab
/etc/kernel/postinst.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... Generating /boot/grub/default file and setting the default boot entry to 0
Testing for an existing GRUB menu.lst file ...

Could not find /boot/grub/menu.lst file. Would you like /boot/grub/menu.lst generated for you? (y/N) /usr/sbin/update-grub-legacy-ec2: line 1101: read: read error: 0: Bad file descriptor
run-parts: /etc/kernel/postinst.d/x-grub-legacy-ec2 exited with return code 1
dpkg: error processing package linux-image-4.15.0-72-generic (--configure):
 installed linux-image-4.15.0-72-generic package post-installation script subprocess returned error exit status 1
Processing triggers for linux-image-unsigned-5.4.2-050402-generic (5.4.2-050402.201912042231) ...
/etc/kernel/postinst.d/initramfs-tools:
update-initramfs: Generating /boot/initrd.img-5.4.2-050402-generic
cryptsetup: WARNING: failed to detect canonical device of /dev/sda1
cryptsetup: WARNING: could not determine root device from /etc/fstab
/etc/kernel/postinst.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... Generating /boot/grub/default file and setting the default boot entry to 0
Testing for an existing GRUB menu.lst file ...

Could not find /boot/grub/menu.lst file. Would you like /boot/grub/menu.lst generated for you? (y/N) /usr/sbin/update-grub-legacy-ec2: line 1101: read: read error: 0: Bad file descriptor
run-parts: /etc/kernel/postinst.d/x-grub-legacy-ec2 exited with return code 1
dpkg: error processing package linux-image-unsigned-5.4.2-050402-generic (--configure):
 installed linux-image-unsigned-5.4.2-050402-generic package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 linux-image-4.15.0-72-generic
 linux-image-unsigned-5.4.2-050402-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

root@sites:/boot/grub# cp * backup
cp: -r not specified; omitting directory 'backup'
cp: -r not specified; omitting directory 'fonts'
cp: -r not specified; omitting directory 'i386-pc'
cp: -r not specified; omitting directory 'locale'
root@sites:/boot/grub# rm menu.lst
root@sites:/boot/grub# rm default
root@sites:/boot/grub# mv /etc/kernel/postrm.d/x-grub-legacy-ec2 backup
root@sites:/boot/grub# dpkg --configure -a
Setting up linux-image-4.15.0-72-generic (4.15.0-72.81) ...
Setting up linux-image-unsigned-5.4.2-050402-generic (5.4.2-050402.201912042231) ...
Processing triggers for linux-image-4.15.0-72-generic (4.15.0-72.81) ...
/etc/kernel/postinst.d/initramfs-tools:
update-initramfs: Generating /boot/initrd.img-4.15.0-72-generic
cryptsetup: WARNING: failed to detect canonical device of /dev/sda1
cryptsetup: WARNING: could not determine root device from /etc/fstab
/etc/kernel/postinst.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... Generating /boot/grub/default file and setting the default boot entry to 0
/usr/sbin/update-grub-legacy-ec2: line 556: grub-set-default: command not found
run-parts: /etc/kernel/postinst.d/x-grub-legacy-ec2 exited with return code 127
dpkg: error processing package linux-image-4.15.0-72-generic (--configure):
 installed linux-image-4.15.0-72-generic package post-installation script subprocess returned error exit status 1
Processing triggers for linux-image-unsigned-5.4.2-050402-generic (5.4.2-050402.201912042231) ...
/etc/kernel/postinst.d/initramfs-tools:
update-initramfs: Generating /boot/initrd.img-5.4.2-050402-generic
cryptsetup: WARNING: failed to detect canonical device of /dev/sda1
cryptsetup: WARNING: could not determine root device from /etc/fstab
/etc/kernel/postinst.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... Generating /boot/grub/default file and setting the default boot entry to 0
/usr/sbin/update-grub-legacy-ec2: line 556: grub-set-default: command not found
run-parts: /etc/kernel/postinst.d/x-grub-legacy-ec2 exited with return code 127
dpkg: error processing package linux-image-unsigned-5.4.2-050402-generic (--configure):
 installed linux-image-unsigned-5.4.2-050402-generic package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 linux-image-4.15.0-72-generic
 linux-image-unsigned-5.4.2-050402-generic
root@sites:/boot/grub#

 dpkg -l | grep grub
ic  grub-common                                2.02-2ubuntu8.14                                         amd64        GRand Unified Bootloader (common files)
ic  grub-pc                                    2.02-2ubuntu8.14                                         amd64        GRand Unified Bootloader, version 2 (PC/BIOS version)

Can't remove or install or anything... I'm kinda stuck.
root@sites:/# apt install --reinstall initramfs-tools
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
  linux-modules-4.15.0-62-generic linux-modules-4.15.0-64-generic linux-modules-4.15.0-65-generic
  linux-modules-4.15.0-66-generic linux-modules-4.15.0-70-generic
Use 'apt autoremove' to remove them.
The following packages will be REMOVED:
  linux-image-4.15.0-62-generic linux-image-4.15.0-64-generic linux-image-4.15.0-65-generic linux-image-4.15.0-66-generic
  linux-image-4.15.0-70-generic
0 upgraded, 0 newly installed, 1 reinstalled, 5 to remove and 0 not upgraded.
7 not fully installed or removed.
Need to get 9,568 B of archives.
After this operation, 41.9 MB disk space will be freed.
Do you want to continue? [Y/n] y
Get:1 http://us.archive.ubuntu.com/ubuntu bionic-updates/main amd64 initramfs-tools all 0.130ubuntu3.9 [9,568 B]
Fetched 9,568 B in 0s (56.6 kB/s)
(Reading database ... 211144 files and directories currently installed.)
Removing linux-image-4.15.0-62-generic (4.15.0-62.69) ...
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.15.0-62-generic
/etc/kernel/postrm.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-5.4.2-050402-generic
Found kernel: /boot/vmlinuz-5.2.14-050214-generic
Found kernel: /boot/vmlinuz-4.15.0-72-generic
Found kernel: /boot/vmlinuz-4.15.0-70-generic
dpkg-query: error: package 'grub-legacy-ec2' is not installed
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 10
dpkg: error processing package linux-image-4.15.0-62-generic (--remove):
 installed linux-image-4.15.0-62-generic package post-removal script subprocess returned error exit status 1
Removing linux-image-4.15.0-64-generic (4.15.0-64.73) ...
/var/lib/dpkg/info/linux-image-4.15.0-64-generic.postrm ... removing pending trigger
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.15.0-64-generic
/etc/kernel/postrm.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-5.4.2-050402-generic
Found kernel: /boot/vmlinuz-5.2.14-050214-generic
Found kernel: /boot/vmlinuz-4.15.0-72-generic
Found kernel: /boot/vmlinuz-4.15.0-70-generic
dpkg-query: error: package 'grub-legacy-ec2' is not installed
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 10
dpkg: error processing package linux-image-4.15.0-64-generic (--remove):
 installed linux-image-4.15.0-64-generic package post-removal script subprocess returned error exit status 1
Removing linux-image-4.15.0-65-generic (4.15.0-65.74) ...
/var/lib/dpkg/info/linux-image-4.15.0-65-generic.postrm ... removing pending trigger
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.15.0-65-generic
/etc/kernel/postrm.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-5.4.2-050402-generic
Found kernel: /boot/vmlinuz-5.2.14-050214-generic
Found kernel: /boot/vmlinuz-4.15.0-72-generic
Found kernel: /boot/vmlinuz-4.15.0-70-generic
dpkg-query: error: package 'grub-legacy-ec2' is not installed
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 10
dpkg: error processing package linux-image-4.15.0-65-generic (--remove):
 installed linux-image-4.15.0-65-generic package post-removal script subprocess returned error exit status 1
Removing linux-image-4.15.0-66-generic (4.15.0-66.75) ...
/var/lib/dpkg/info/linux-image-4.15.0-66-generic.postrm ... removing pending trigger
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.15.0-66-generic
/etc/kernel/postrm.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-5.4.2-050402-generic
Found kernel: /boot/vmlinuz-5.2.14-050214-generic
Found kernel: /boot/vmlinuz-4.15.0-72-generic
Found kernel: /boot/vmlinuz-4.15.0-70-generic
dpkg-query: error: package 'grub-legacy-ec2' is not installed
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 10
dpkg: error processing package linux-image-4.15.0-66-generic (--remove):
 installed linux-image-4.15.0-66-generic package post-removal script subprocess returned error exit status 1
Removing linux-image-4.15.0-70-generic (4.15.0-70.79) ...
/var/lib/dpkg/info/linux-image-4.15.0-70-generic.postrm ... removing pending trigger
/etc/kernel/postrm.d/initramfs-tools:
update-initramfs: Deleting /boot/initrd.img-4.15.0-70-generic
/etc/kernel/postrm.d/x-grub-legacy-ec2:
Searching for GRUB installation directory ... found: /boot/grub
Searching for default file ... found: /boot/grub/default
Testing for an existing GRUB menu.lst file ... found: /boot/grub/menu.lst
Searching for splash image ... none found, skipping ...
Found kernel: /boot/vmlinuz-5.4.2-050402-generic
Found kernel: /boot/vmlinuz-5.2.14-050214-generic
Found kernel: /boot/vmlinuz-4.15.0-72-generic
Found kernel: /boot/vmlinuz-4.15.0-70-generic
dpkg-query: error: package 'grub-legacy-ec2' is not installed
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 10
dpkg: error processing package linux-image-4.15.0-70-generic (--remove):
 installed linux-image-4.15.0-70-generic package post-removal script subprocess returned error exit status 1
Errors were encountered while processing:
 linux-image-4.15.0-62-generic
 linux-image-4.15.0-64-generic
 linux-image-4.15.0-65-generic
 linux-image-4.15.0-66-generic
 linux-image-4.15.0-70-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

Comment: `dpkg -l | grep grub` Please edit your question for that.
Comment: Edited. Seems to be running Grub v2
Answer: Safety first. Make backup, make backup, make backup.
sudo rm /boot/grub/menu.lst

and
sudo rm /etc/kernel/postrm.d/x-grub-legacy-ec2, also
sudo rm /boot/grub/default
Then try sudo dpkg --configure -a No ,error?
 sudo apt install --reinstall grub-common grub-gfxpayload-lists  grub-pc grub-pc-bin grub2-common

Afteer that, we install the boot code in the MBR sudo dpkg-reconfigure grub-pc
 If you have only one harddrive  /dev/sda is the right place.
Comment: See above ... I ran the command but got errors on dpkg --configure -a
Comment: I'm not sure what changed. I copied everything to a backup folder and then ran dpkg --configure -a but I'm getting errors on dpkg --configure -a -- tc/kernel/postinst.d/x-grub-legacy-ec2 exited with return code 127 dpkg: error processing package linux-image-4.15.0-72-generic
Comment: @Jefferson Nunn backup is not mean as command, i mean you should save your important data.  I made an edit to my answer, it was wrong formated, and I forgot something to write.
Comment: See above ... I am getting errors even after reinstall of grub.
Comment: After removing x-grub-legacy-ec2 I was able to do apt-get upgrade and apt-get autoremove and we're set.
Answer: The errors you are hitting are pretty self-explanatory:
dpkg-query: error: package 'grub-legacy-ec2' is not installed

I think you really need to install that package.  Try doing that and trying again?  sudo apt install grub-legacy-ec2
Comment: That doesn't work. Here's the output. sudo apt install grub-legacy-ec2
Found kernel: /boot/vmlinuz-5.4.2-050402-generic
Found kernel: /boot/vmlinuz-5.2.14-050214-generic
Found kernel: /boot/vmlinuz-4.15.0-72-generic
Found kernel: /boot/vmlinuz-4.15.0-70-generic
dpkg-query: error: package 'grub-legacy-ec2' is not installed
run-parts: /etc/kernel/postrm.d/x-grub-legacy-ec2 exited with return code 10
dpkg: error processing package linux-image-4.15.0-62-generic (--remove):
 installed linux-image-4.15.0-62-generic package post-removal script subprocess returned error exit status 1) ...
Comment: It worked for me, had the issue during upgrade from 18.04 to 20.04
Answer: In my case I had a slight variation to the above:

I deleted /etc/kernel/postinst.d/x-grub-legacy-ec2 in addition to postrm.d

The 4.15 kernel seems to come from linux-image-virtual -package. I had it removed, but the error persisted. Then I edited /boot/grub/menu.lst and removed all entries that stated kernel version 4.15 (that pointed to non-existent files).


Remove the column tendency from HTML tables

Question: I'm working on designing up a table with 7 images in it that are all roughly the same size. Basically, I was wondering if there is a way (other then splitting each row into a different table) to change the HTML tendency to put everything in columns, and force it to lay it out based on rows.
Here is a jsfiddle of what it is. (I used Lorem Ipsum instead of the images) I would like the top and bottom row centered.
I know I can do this if I was to split it into three tables and set each one to have a width:xxxpx and margin: 0 auto, but would rather not do that.
Any suggestions are appreciated.
Comment: Are you sure [a table is the right tool for the job](http://www.hotdesign.com/seybold/)?
Comment: Love that site. Seriously, I normally steer really clear of tables, but thought it would be easiest in this situation. I'll see how the non-table comes together.
Answer: Why do you even bother creating multiple cells per row? Just put all your images that go in one row in the same cell, next to each other.
Comment: That does work nicely. I found that I had to put divs in there to keep it centered. Thanks!
Answer: See the vertical-align property.
Answer: Yeah, it might be better to go with multiple divs for this issue. Is it possible to do something like the following:
HTML:

CSS:
.rows{
  margin:10px;
}

.top, .bottom{
  padding-left:85px;
  padding-right:85px;
}

.top, .bottom, .middle
{
  width:520px;
}

.rows img
{
  margin: 10px;
  width:150px;
}

Basically, let the normal flow of images control their positioning, and instead use margins and padding to equalize the spacing.
Comment: Thanks you all for the help! @Zensar I took your suggestion but opted to use `width:66%` (and `100%` every even row) in conjunction with `margin:0 auto;` and selecting every even row with a `:nth-child(even)` pseudo class. Here's the finished product which ended up being very extensible http://dev.dropletirrigation.com/irrigation-suppliers.html


Javascript - RegExp - Replace last occurrence of non-number

Question: So this is my code:
function PlusMinus() {
  str = str.replace(/([^\d\.](?!.*[^\d\.]))/, function(m, $1) {
    if ($1 == "-") return "";
    return $1 + "-";
  });
}

And it isn't working.
What I want to do, is to find the last occurrence of any character that is not a number (0-9) or a dot (.) and then if it is a "-", remove it, if it isn't replace the char with the char + "-".
Simply like a calculators -/+ button.
Examples:
"" -> "-"
"-" -> ""
"abc2-3" -> "abc23"
"a2-" -> "a2"
"s23.3" -> "s-23.3"
"4f" -> "4f-"

And yes, I've seen this: JavaScript RegExp: Can I get the last matched index or search backwards/RightToLeft? but I can't get it to work for chars in brackets
Comment: Provide some examples.
Comment: I guess you know that `.replace()` returns the new string instead of modifying the input one? That is to say, you need a left var: `anyVar = str.replace(...);`.
Comment: @sp00m Ik, but that wasn't the problem, edited though.
Answer: I would say something like this:
str.replace(/(?:^|.)(?=[\d.]*$)/,function(c) {
    return c == "-" ? "" : c+"-";
});

This will find a character such that all the characters after it are either numbers or a dot. Due to the greedy nature of quantifiers and the left-to-right processing of regexes, this will be the first such character found, which will be the last non-digit, non-dot character.
However, be sure to return or otherwise do something with the result! Otherwise you're just discarding it.
Comment: I upvoted your answer, because I initially thought it was the same as my idea, but there are issues with your regular expression.
Comment: Well,  with `(/.(?=[\d.]+)$/` it's not working at all since the `$` is outside the lookahead, but there are also other issues, since for exemple, in `333`, the first `3` would be matched by your `.`. You also do not consider the case where `''` must yield `'-'`.
Comment: @plalx Gotcha. Thanks, now fixed I believe.
Comment: Also, your code doesn't work?? Have you tried with the examples?
Comment: @Murplyx Ah, I see. I (wrongfully) assumed that there would actually be a number for your +/- to apply to. Edited. [See tests](http://jsfiddle.net/pdp6w30h/)
Comment: Wait.. "4f" -> "-4f", should be "4f-"
Comment: @Murplyx And so it is. I forgot to add that test, but you can add it yourself easily enough to see that it does become `4f-`
Answer: plusMinus(''); //'-'
plusMinus('-'); //''
plusMinus('abc2-3'); //'abc23'
plusMinus('a2-'); //'a2'
plusMinus('s23.3'); //s-23.3

function plusMinus(str) {
    return str.replace(/(^|[^\d\.])(?=[\d\.]*$)/, function ($0) {
        return $0 === '-'? '' : $0 + '-';
    });
}

I am just unsure about what to do with something like 33, because now it will return -33. Is this the desired behavior?
Comment: Yes it is, also, does $0 actually work??? Like, shouldn't the arguments be (match, $1, $2, $3...)
Comment: @Murplyx It's just the argument name. It could have been anything, but usually `$0` is considered as full match so I chose this argument name. You could change it to `match` if you like it better.
Comment: As well, is there anyway to make this work for "abc123Infinity" -> "abc123-Infinity"
Comment: Is this: /(^|[^\d\.]|^Infinity)(?=[\d\.]|(Infinity)*$)/ correct then?
Comment: @Murplyx Will Infinity always be at the end? What would be the rule?
Comment: "Infinity" -> "-Infinity", "Infinity2" -> "Infinity-2", "Infinityabc" -> "Infinityabc-"
Comment: Wait.. "4f" -> "-4f", should be "4f-"


Open image that user clicked

Question: I have two images. However, when I click to open one, it opens both. In addition, I made a code that takes the image that has the same src, but when opening one, it opens two identical images. I want you to open only one and exclusively the one the user clicked on.

$(document).ready(function() {
  $('.img-min').on("click", function() {
    // $(this).toggleClass('img-max')
    const min = $(this).attr('src');
    const max = $('img').attr('src', min);
    $('div').removeClass('hide');
    $('#close-img').removeClass('hide');
    $("body").addClass("sem-scroll");
  });
})
.img-min {
  height: auto;
  width: 10%;
}

.hide {
  display: none !important;
  transition: all 0.5s;
}

.hide:hover {
  transition: all 0.5s;
}

.overlay {
  background-color: black;
  opacity: 0.8;
  position: fixed;
  font-family: Arial, Helvetica, sans-serif;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1;
}

.sem-scroll {
  overflow: hidden;
  user-select: none !important;
}

Lorem Ipsum

Answer: The line
const max = $('img').attr('src', min);

Changes all img tags' src attributes to the same value (const min). That is why you have two identical images.
With selector $('img.img-max[src="'+min+'"]') you should get only the img-max element with correct src. Then shiw only that element and hide others.
Comment: I moved to `const max = $('.img-max').attr('src', min);`. Not work.
Comment: That effectively does the same thing.
Comment: The attr-function changes the attribut. You should use correct selector. See my edits (sorry, on mobile so they might be little off).
Comment: Smoothly. Anyway, it doesn't work. He takes the two different images
Comment: I am afraid you have more issues in your code. Use the browser debugger tools and try to find the correct selector so that you only control the desired html element.
Comment: For example not anywhere in the original code do you hide all/other img-max elements. You just unhide everything.

Open image that user clicked


Calculate sum of Single column on the Basis of another column in MySQL

Question: I want to get two(2) different SUM of Single Column "Amount" on the Basis of "Type" Column.
mysql>select * from tbl;
+--------+----------+----------+----------+
|   id   |  CustID  |  amount  |   type   |
+--------+----------+----------+----------+
|      1 | 1        | 100      | 0        |
|      2 | 2        | 200      | 0        |
|      3 | 3        | 200      | 0        |
|      4 | 1        | 100      | 1        |
|      5 | 1        | 100      | 0        |
|      4 | 3        | 100      | 0        |
|      5 | 1        | 300      | 1        |
|      6 | 2        | 100      | 1        |
+--------+----------+----------+----------+

mysql>Query Result (Want this Result);
+-------------+-------------+-------------+
|    CustID   |   amount1   |   amount2   |
+-------------+-------------+-------------+
| 1           | 200         | 400         |
| 2           | 200         | 100         |
| 3           | 400         | 0           |
+-------------+-------------+-------------+

Means to say that in above example there is Type column which only have 0 or 1 and I want to get sum of "Amount" column group by "CustID".
Comment: `SUM(IF(type=0,amount,0)),SUM(IF(type=1,amount,0))`, or a `CASE` statement if you want more portable syntax.
Comment: Wow! That's just Mind Blowing for Me Man. Thanks Alot, I can't believe. I just learnt it. Love you man. So Fast also.
Answer: SELECT CustID,SUM(CASE WHEN `type` =0 THEN amount ELSE 0 END) AS amount1,
              SUM(CASE WHEN `type` =1 THEN amount ELSE 0 END) AS amount2
FROM tableName GROUP BY CustID

Answer: seems that is the query you are looking for.
SELECT
    CustID,
    SUM(IF(type=0,amount,0)) as amount1,
    SUM(IF(type=1,amount,0)) as amount2
FROM
    tbl
GROUP BY
    CustID;


Cray compiler asks for a flag, then doesn't recognize it

Question: I am trying to compile a code with crayftn.
I get an error message
/opt/cray/pe/cce/10.0.1/binutils/x86_64/x86_64-pc-linux-gnu/bin/ld: failed to convert GOTPCREL relocation; relink with --no-relax

So it wants the flag --no-relax?  OK, I can do that.  So I re-link with that flag, and then it tells me
ftn -O3 --no-relax -dynamic -h pic -h omp -o stream_cray stream_mpi.o mysecond.o
ftn-2115 crayftn: ERROR in command line
  "-no-relax" is an invalid command-line option.

So it asks for "--no-relax", but then it doesn't understand it.  Anyone know of a way out of this conundrum?  Or another way of solving the root problem in the first place?
Comment: @JonatanÖström: perhaps if the OP typed `-mooseturd`, it might say `"mooseturd" is an invalid command-line option`.  The real issues:  Q1: does the *linker* understand "---no-relax"? Q2: If so, is "---no-relax" ever actually *passed* to the linker?  SUGGESTION: wrap the option with `-Wl,--no-relax` to ensure it's passed *ONLY* to the linker.
Comment: Q: Have you been able to successfully compile, link and run *ANY* program with your crayftn?   Q: What version of crayftn?  10.0.1?   Q: What platform?  Where is x86_64-pc-linux coming from?  Just curious...
Comment: It's strange that it says `"-no-relax" is an invalid command-line option` with a single `-` in the flag.
Comment: @JonatanÖström   If I give the flag with a single `-`, then it complains that `no-relax` is invalid.  Apparently, it drops the leading `-` in its reporting.
Comment: @paulsm4 About the `-`, sure;)  Yeah, I agree, the linker is complaining, not the compiler, so it would seem like cray might have missed passing that flag to the linker. It might even be possible to link the program using `gfortran` or `gcc` or `ld` since it seems to be a `gnu` linker. But if passing with `-Wl,--no-relaxed` works that's nicer.
Answer: I found this link:

https://bb.cgd.ucar.edu/cesm/threads/failed-to-convert-gotpcrel-relocation-relink-with-no-relax.4494/
PROBLEM:
Hi, I get the following error message for CLM5.0 compilation with
Intel compilers, during the final cesm bld ..ld: failed to convert GOTPCREL relocation; relink with --no-relax
SOLUTION:
Hi, Seems like found a solution to fix the compilation ...Adding of
"-Wl,--no-relax" in LDFLAGS does not solve this problem, but
"-mcmodel medium" in FFLAGS fixes this issue, after searching for
"Relocation truncated to fit" in google search engine, it comes up
with this link which was helpful to solve the issue
"https://software.intel.com/en-us/forums/intel-fortran-compiler-for-linux-and-mac-os-x/topic/268394"
Best Regards,Prabhakar

See also:

https://community.intel.com/t5/Intel-Fortran-Compiler/relocation-truncated-to-fit/td-p/1146616
This looks like mixing compilers and libraries from different systems
mixed up, either 32bit vs. 64bit or installations for ifort and
mpiifort based on different glibc or something similar.

I'm still curious about your "development environment":

Q: Have you been able to successfully compile, link and run ANY
program with your crayftn? Q: What version of crayftn? 10.0.1? Q: What
platform? Where is x86_64-pc-linux coming from? Just curious...
Comment: Well, I guess I should have mentioned that the "mcmodel" doesn't work either.  Intel and GNU recognize it but not Cray.  I am using 10.0.1.  No idea about the x86_64-pc-linux.  I have successfully compiled several times here.  I *think* the problem stems from a particularly large array in this code.  Thanks.
Comment: FYI, the 2nd link I cited also talks about "large arrays" with respect to the "GOTPCREL relocation" error.  Check it out :)
Comment: Q: Did you resolve the problem?  1) If you "successfully compiled several times", then your environment is probably "OK". 2) Your [toolchain](https://support.nesi.org.nz/hc/en-gb/articles/360000329015-Compiling-software-on-Mahuika) has several elements, so it's sunsurprising there are  "differences" in CLI options.  3) Try also `"-Wl,--no-relax" `.  4) "Large arrays" sounds most promising; https://sourceware.org/legacy-ml/binutils/2017-09/msg00052.html,


root pages#home or root posts#index?

Question: I am a beginner on Ruby on Rails and I have a small question.
I am currently creating an application allowing me to list my posts with an upvote system,... . Currently I create my homepage with root pages#home.
But I have the impression that I may have to do my homepage with root posts#index ..
Because when I look at some tutorials I feel that it's easier to put the infinite scroll, search filters with ajax, ranking by popular or newest, opening my posts in modal bootstrap, ... with root posts#index ...
So I hesitate to change everything ... opinions? :)
What is better for the long term ?
Thank you in advance !
Comment: You can specify any page you want as the root.   The naming has nothing to do with how it works, just a convention with common setups.  You could root to `posts#new` if you wanted.
Comment: @RockwellRice Actually but I asked myself this question (as a beginner) because I encountered some problems by wanting to add on my homepage an infinite scroll or an ajax filter for example.

And I noticed that most of the tutorials or explanations about this still had for root posts#index.

As Ryan Brunner and Michael Arkhipov say it may make more sense to work with root posts#index if my homepage only includes listings.
Answer: Technically speaking, either approach will work and there's no functionality gained or lost by using a "generic" page or a resourceful route (which is what you're getting when you say posts#index)
Semantically though, you should organize your controllers in a way that corresponds to the function of a page. pages#home carries little or no semantic meaning. Someone reading the contents of rails routes is not going to be able to infer anything about what that page is beyond "a home page". posts#index does carry more semantic meaning - it strongly implies that the main purpose of this page is to list posts.
If your site is structured like this, i.e. your "home" page is mostly concerned with listing posts, then using posts#index makes sense. If it's more of a generic dashboard that does a bunch of things (including listing posts), something like pages#home might make more sense to use.
Answer: If you have another page with posts, you should use pages#home, but if you show posts only on home page, using root on posts#index make sense.
Comment: I use other pages with posts like library or statistics but they are pages specific to the current user.

But I only display posts on the home page with categories.

So I think it's better to go back to a posts#index.

thank you for your reply

root pages#home or root posts#index?


Analyzing the data structure in SQL Server

Question: I am having a hard time understanding why I am getting multiple entries on the following when analyzing the row structure.
First, I set up two tables.
I am digging into the Row/Page structure using the below query.
CREATE TABLE [Table1]
(
    [Column1] INT IDENTITY PRIMARY KEY,
    [Column2] VARCHAR (100),
    [Column3] VARCHAR (20)
)

CREATE TABLE [Table2]
(
    [Column1] INT IDENTITY
        FOREIGN KEY REFERENCES [Table1]([Column1]),
    [Column4] VARCHAR (1000)
)

Then, I insert 1 million rows using the following
BEGIN TRANSACTION

INSERT INTO [Table1] ([Column2], [Column3])
VALUES (REPLICATE ('2', 50), REPLICATE('3', 20))

INSERT INTO [Table2] ([Column4])
VALUES (REPLICATE ('4', 1000))
GO 1000000

COMMIT TRANSACTION

Then, using the following query, I try to see how many pages make up the table.
SELECT
    [alloc_unit_type_desc] AS [Data Structure],
    [page_count] AS [pages],
    [record_count] AS [Rows]
FROM
    SYS.dm_db_index_physical_stats (DB_id(), OBJECT_ID (N'Table1'), NULL, NULL, N'detailed')

Here is my question: where are these other 41 pages coming from? When they clearly do not contain the same data? I do not see them on the select table either.
Comment: What is the result of the query?
Answer: If you add index_level to your query you will see
SELECT [alloc_unit_type_desc] AS [Data Structure],
       [page_count]           AS [pages],
       [record_count]         AS [Rows],
       index_level
FROM   sys.dm_db_index_physical_stats (DB_id(),
                 OBJECT_ID (N'Table1'), NULL, NULL, N'detailed')

The table is created with a primary key. This will be the clustered index by default. The B-tree index to support this has a single root page and 40 intermediate pages between the root and the 11,112 leaf level pages at level 0.
(Structure of a clustered index from here)


How to associate a subscriber to an event

Question: I'm trying to make that a subscriber, sub to an certain event
with the following url per example:
http://localhost:3001/events/1/subscribers/new

but I don't know how to associate event_id when creating a new subscriber
for the moment i'm getting this error:
Couldn't find Event with 'id'=

in the routes:
 resources :events do
    resources :subscribers #url/events/:events_id/subscribers/new
  end

  resources :events
  root 'events#index'

in the subscribers controller:
def show
  end

  # GET /subscribers/new
  def new
    #puts "Look for me in console\n"
    #puts params.inspect
    @event = Event.find(params[:events_id])
    @subscriber = @event.Subscriber.new
  end

  # GET /subscribers/1/edit
  def edit
  end

  # POST /subscribers
  # POST /subscribers.json
  def create
    @event = Event.find(params[:order_id])
    @subscriber = @event.Subscriber.new order_params
    #@subscriber = Subscriber.new(subscriber_params)

    respond_to do |format|
      if @subscriber.save
        SubsMailer.new_subscriber(@subscriber).deliver
        format.html { redirect_to @subscriber, notice: 'Subscriber was successfully created.' }
        format.json { render :show, status: :created, location: @subscriber }
      else
        format.html { render :new }
        format.json { render json: @subscriber.errors, status: :unprocessable_entity }
      end
    end
  end

in the new.html.erb:

New Subscriber

<%= render 'form', subscriber: @subscriber %>

<%= link_to 'Back', subscribers_path %>

model association:
event.rb:
class Event < ApplicationRecord
  has_many :subscribers, dependent: :destroy
end

subscriber.rb:
class Subscriber < ApplicationRecord
  belongs_to :event
  validates :email, presence: true,
                    format: /\A\S+@\S+\z/,
                    uniqueness: { case_sensitive: false }
end

Comment: Maybe there is a better way, but why not use a hidden field in the form getting the required param from the url?
Comment: have u set model associations ?
Comment: @GaganGupta Yeah, look I've edited it to the question.
Comment: okay. Model associations are set pretty well but there's a problem with controller methods. So, wherever you've set `@event.Subscriber.new` change it to `@event.subscriber.new`
Comment: and also. Make it `@event = Event.find(params[:event_id])`
Comment: @GaganGupta I've changed it, and still the same error :/
Comment: can you share generate routes as well ?
Comment: @GaganGupta what do you mean by generate routes ?
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170223/discussion-between-gagan-gupta-and-arb).
Answer: Well, I think this documentation will help you to understand what you need to do.
If briefly at first you need to change your models. You could have many to many for Event -> Subscriber association or one to many. One to many is the simplest to show so you need to add this to your Subscriber model:
belongs_to :event

And this to your Event model:
has_many :subscribers

Add new migration:
def change
  remove_column :subscribers, :events_id
  remove_column :subscribers, 'Event_id'
  add_column :subscribers, :event_id, :integer
end

Then in your controller, you should change method calls, as Subscriber is a class, not the method.
def new
  @event = Event.find(params[:event_id])
  @subscriber = @event.subscribers.build
end

And you should be sure that in your database you have Event with this id.
To check it you can try to debug your controller code:
def new
  puts "Event ids: " + Event.all.map(&:id).inspect
  @event = Event.find(params[:event_id])
  @subscriber = @event.subscribers.build
end

In your logs you should have something like:
Event ids: [1]

Comment: Hey thanks, for the model association I've edited them to the question after Gagan comment,  for the new migration: something is missing the variable t is undefined, should I do: change_table :subscribers do |t| before ?
Comment: I think there already event_id in the subscribers, because i'm getting this error while trying to migrate : duplicate column name: event_id: ALTER TABLE "subscribers" ADD "event_id" integer
/Users/abderrahmane/workspace/Eventmanager/db/migrate/20180502095034_addevent_id
Comment: So you have it in your db, and you don't need additional migration. It would be great if you expose this part of the `schema.rb` to be sure.
Can you show current error with backtrace?
Comment: BTW, if you get "unknown attribute 'event_id' for Subscriber" it is possible that you didn't run migration for this environment.
So if you get this error in tests please do:
`RAILS_ENV=test rake db:migrate`
Comment: I think like said Anton I have Event_id not event_id, here is my shema.rb  for the subscribers :
  create_table "subscribers", force: :cascade do |t|
    t.integer "Event_id"
    t.string "name"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "events_id"
    t.index ["Event_id"], name: "index_subscribers_on_Event_id"
    t.index ["events_id"], name: "index_subscribers_on_events_id"
  end
Comment: Changed migration to make a proper database structure. Please try and let me now about any issues
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170226/discussion-between-arb-and-alexander-sysuiev).
Answer: I think you just have a typo in your new method. You call params[:eventS_id] when it should be params[:event_id]. Also you don't properly reference your association. it should be event.subscribers.new:
def new
  #puts "Look for me in console\n"
  #puts params.inspect
  @event = Event.find(params[:event_id])
  @subscriber = @event.subscribers.build
end

Migration:
def up
  change_table :subscribers do |t|
    t.remove :Event_id
    t.references :event
  end
end

def down
  change_table :subscribers do |t|
    t.remove :event_id
    t.add :Event_id, :integer
  end
end

Keep me posted whether this helps and if you have any additional issues
Comment: When I do that I get an error on the next line (@subscriber = @event.subscriber.new ) saying : undefined method `subscriber' for # Did you mean? subscribers subscribers=
Comment: Yes, you are right, but if you check my code you will see, that I wrote not `subscriber`, but `subscriberS`. Just copy it properly
Comment: If that helps I sincerely ask you to mark my answer with a tick and upvote for future searches by other people. Thanks in advance :)
Comment: After I added the S, I'm getting this error: unknown attribute 'event_id' for Subscriber.
Comment: Paste please a migration, that was used to create subscriptions table
Comment: Need to add migration and use `build` instead of `new`
Comment: @AlexanderSysuiev Yes, you are right. Updating my answer
Comment: @AlexanderSysuiev here is the migration that was used to create the Subscribers table:
class CreateSubscribers < ActiveRecord::Migration[5.1]
  def change
    create_table :subscribers do |t|
      t.belongs_to :Event, foreign_key: true
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end
Comment: Check your `subscribers` table. It looks like you have `Event_id` field, when it should be `event_id`. In fact... just check all the fields that you have in your Event and paste it here
Comment: @AntonTkachov Yes you're right it is Event_id, to change it I need to do a new migration or just change it in the schema.rb ?
Comment: `schema.rb` is just an info file. You can change it in any way, but it will not make any real changes to db. Yes, go with a new migration -- `rails g rename_Event_id_to_event_id_in_subscriptions`
Comment: @AntonTkachov I'm doing this in the migration:     rename_column :subscriber, :Event_id, :event_id
but I get this error: SQLite3::SQLException: duplicate column name: event_id: ALTER TABLE "subscribers" ADD "event_id" integer
Comment: @Arb Strange... do you have any data in your subscribers model or is it blank? Added a migration in my answer, that I would use in such case. But it's destrutive and should be used only in case you have no real data in `Subscriber`


Cmake set option back to default

Question: I am building a C++ project using CMake on Windows. I have an option which is OFF by default and I'm overriding it to ON using CMake command line arguments. I build my project using the following commands:
cmake.exe --config "Release" . -DANALYSIS=ON
cmake.exe --build ./ -- /p:configuration=Release

If the option ANALYSIS is ON I do some additional things and want to set the ANALYSIS back to default value (OFF). How can I do this?
Answer: You can set ANALYSIS to OFF from your CMakeLists.txt:
set(ANALYSIS OFF CACHE INTERNAL "" FORCE)

Using set(<var> <value> CACHE ...) without FORCE does not update cache variables, it's a no-op if the variable already exists.
It's also possible to remove ANALYSIS
unset(ANALYSIS CACHE)

You can still test it with if(ANALYSIS) which will give the expected result.
Answer: The option ANALYSIS is cached in your CMakeCache.txt file. There are multiple ways how you can override the entry in your cache. For example use ccmake from the build directory to start interactive CMake GUI and modify the ANALYSIS option back to OFF.

Cmake set option back to default


Stack trace using Javascript function.caller in recursive code?

Question: In javascript, I can use foo.caller to get a reference to the function above foo in the stack trace. However, that doesn't work when a function appears multiple times in the same stack trace, foo.caller just returns foo.
Is there a stable, cross-platform method of getting a full stack trace in Javascript? I do not want to get a printable stack trace; rather, I'm doing stack inspection to see if a certain method is anywhere above me in the stack.  Here's my current code:
<code>function inFunction(foo) {
    var caller = inFunction.caller;
    var maxDepth = 20;
    while(caller && --maxDepth > 0) {
        if(caller == foo)
            return true;
        caller = caller.caller;
    }
    return false;
}
</code>
Any ideas how to deal with a function existing multiple times in the stack trace?
Comment: Did you check out http://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760#235760
Comment: For a quick reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller
Answer: Sorry, but there's not.  Once you hit a recursive function in the trace it is impossible to get to the calling function.
I spent several days trying to come up with work-arounds to this while writing an IDE in JavaScript for Sun Microsystems.  There are none.