text:
Q: Why does the root object implement equality? In many object oriented languages such as Java, the .NET family, Python, Ruby, and I'm sure a host of others, the root object class from which all other classes inherit defines an equality checking method. However, in my experience, many of the classes I create really don't need an equality check or I (or co-workers) don't bother overriding the default method because we don't intend to use it. In the latter case, the default equality method doesn't represent equality very well for that class. So why do so many languages provide this method as part of the definition of the root object class when it seems like many classes should not? Why not leave off the equality method and force users to define it when they need it?

A: For any objects references X and Y, regardless of their types, it is possible to meaningfully ask and answer the question "Is the object referred to by X equivalent to the one referred to by Y".  If X represents a Porche 911 automobile and Y represents a cast-iron park bench, the answer would simply be "no".  To be sure, if one knew that X was a car and Y a bench, one likely wouldn't bother asking, but suppose X, Y, or both, were "things that one may be asked to paint".  One might not know whether or not X and Y are of the same type, and the objects are not equivalent, one may not care.  Having a universal means of asking equivalence saves code the trouble of having to worry about objects' exact type.
The reason to have all objects implement Equals as a virtual method is that it's the easiest mechanism by which objects can supply a definition of equivalence that is broader than referential equality.  It is often useful to have immutable objects report themselves as equivalent to other objects which have the same immutable state [e.g. having two strings, both holding the six characters "GEORGE", reported each other as equivalent]  Having all objects implement Equals as a virtual method, and having mutable objects' implementation simply report referential equality,  is generally easier than having an Equals function which can only be used on immutable objects.  After all, it's not hard for an mutable object to simply report itself as unequal to anything other than itself.


text:
Q: Adding network-fault tolerance to drbd or drbd alternatives I've been working with drbd for about a year now, and at this point I'm tearing my hair out in frustration. Every time there is a network fault (something that is disappointingly common in the environment I'm working in) a critical pair of servers split-brains and I have to manually intervene.
For some background, these servers are in a master-slave configuration, and they perform hashing operations on files before distributing them to other servers around the world. They receive new files every 2-5 minutes, and the two must always be in sync so that should service fail over, the other server is not serving stale data. While this server-pair isn't in production yet, it's frustrating, since it's causing stale data to appear on one node every time there is a network issue. (alarmingly frequent, sadly)
How can I make drbd not split-brain every time there is a network issue? Or automate recovery?
Here is the config for my drbd resources. I have it controlled by a cman stack.
resource foo {
    handlers {
            split-brain "/usr/local/bin/notify-split-brain.sh root";
    }
    protocol C;
    meta-disk internal;
    device /dev/drbd0;
    net {
            after-sb-0pri discard-younger-primary;
            after-sb-1pri discard-secondary;
            after-sb-2pri disconnect;
    }
    on nodea {
            disk /dev/sdb;
            address x.x.x.1:7789;
    }
    on nodeb {
            disk /dev/sdb;
            address x.x.x.2:7789;
    }
}

This is running on CentOS Linux release 7.2.1511 (Core).

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP - Array to string conversion error I'm trying to insert a rgb colors values to my database.
I have an array of strings as you can see here:
array(4) {
    [0]=> string(15) "rgb(39, 32, 32)"
    [1]=> string(15) "rgb(96, 46, 46)"
    [2]=> string(16) "rgb(210, 70, 70)"
    [3]=> string(18) "rgb(246, 208, 208)"
}

But when I try to put it through the foreach cycle, it throws an array to string conversion exception. Can someone help me with this?
Here is the foreach cycle:
foreach ($colors as $color) {
    $sql = "INSERT INTO colors SET ID_Palette = :id_palette, Type = 'RGB', Code = :code";
    $statement = $conn->prepare($sql);
    $result = $statement->execute([
        ":id_palette" => $ID_Palette,
        ":code" => $color
    ]);

    if (!$result) {
        var_dump($statement);
        $proceed = false;
    }
    else {
        $proceed = true;
    }
}

This is the error I'm getting:
Notice: Array to string conversion in C:\xampp\htdocs\Paletky-new\action\create-palette.php on line 33

object(PDOStatement)#2 (1) {
    ["queryString"]=> string(69) "INSERT INTO colors SET ID_Palette = :id_palette, Type = 'RGB', Code = :code"
}


text:
Q: Spring MVC mapping query parameters instead of URI templates values with @PathVariable @RequestMapping(value = "/account/{id}", method = RequestMethod.GET)
public ModelAndView getAccount(@PathVariable String id)
        throws ProfileNotFoundException {
   System.out.println(id);
   return null;
}

.../account/12345 results in null
.../account/test?id=12345 '12345' results in 12345
Not sure how to fix this but I'd like the first link to work instead of the second.  Here is my webmvc-config.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

    <context:component-scan base-package="com.twheys.lexika.web.**"
        use-default-filters="false">
        <context:include-filter expression="org.springframework.stereotype.Controller"
            type="annotation" />
    </context:component-scan>

    <mvc:annotation-driven/>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

A: Just specify it as @PathVariable("id") - without that the HandlerMethodArgumentResolver responsible for resolving the value of the argument tries to figure out the parameter value by parameter name, the parameter name (id) gets lost during compilation though(unless debug symbols are on during compilation, which typically it is not).

A: @RequestMapping(value = "/authors/{authorId}")
public ModelAndView getAuthorById(@PathVariable String authorId) {
    Author author = bookService.getAuthorById(authorId);
    ModelAndView mav =
        new ModelAndView("bookXmlView", BindingResult.MODEL_KEY_PREFIX + "author", author);
    return mav;
}

Above Code works fine for me. Kindly use in similar manner.


text:
Q: Collapse / expand a balance sheet using an OpenerView I am a relatively inexperienced Mathematica user, so I apologise if there is a simple answer to this question. I would like to create a balance sheet that can be collapsed/expanded as necessary.
I have been trying to modify the code that has been shared here by user faysou, but so far I've been unable to get the results I want.
Essentially I'd like to be able to replicate grouping as in Excel like this:

Any help or pointers would be greatly appreciated.
Update
Here is a link to my code
I can't figure out how to modify gg and oo so that it will accept the format of {"Cash at bank", 20, 30}.


text:
Q: The difference between "if" and "even if" I've tried to figure out the difference between "if" and "even if".
My reasoning is as follows. Do I correctly understand?

*

*Even if your partner were a saint, he would not accept your
proposal.

=Even your partner is a saint. Regardless of it, he doesn't accept your proposal.

or

=Even your partner will be a saint. Regardless of it, he will not accept your proposal.

.

*Even if you had not seen the message, you could have imagined what
it meant.

=Even you didn't see the message. In spite of it, you imagined what it meant.

.------------------------------------------------------------------------------------.
The reason why I thought as above is because of the following.
When "If" is used in second type conditional, If clause has an unreal or hypothetical condition/situation, and a main clause is a possible result from if clause.
It is kind of < cause-and-effect relationship >.
No condition in If clause take places and then no result in the main clause follows.
e.g.)

If I had a partner, I would go to a dancing party.
=I don't/will not have any partner, and I cannot go to a dancing party.

However, "even if" is a condition but is not one relevant to a main clause. They are NOT < cause-and-effect relationship.>.
Even if clause doesn't impact on a content of a main clause.
The under-written "even if clause + main cause" can be paraphrased like these with indicative moods.

*

*Even if your partner were a saint, he would not accept your
proposal.

=Even you are partner are a saint. Regardless of it, he doesn't accept your proposal.

.

*Even if you had not seen the message, you could have imagined what
it meant.

=Even you didn't see the message. In spite of it, you imagined what it meant.

A: It looks like you have an idea of the difference here, but it is hard to tell with some of the grammatical errors.
"Even if [condition], [clause]" means that--regardless of whether or not the condition is true--the clause will still be true/happen. It is often used with hypothetical conditions. "Even if" implies that the condition is not true.
E.G.
"Even if your partner were a saint, he would not accept your proposal."
Can be paraphrased as "If your partner was magically turned into a saint, he would still refuse your proposal".
In this case, "your partner" is not a saint, and "even if" can be used because no matter the condition of sainthood, "your partner" will not accept the proposal.
"If [condition], [clause]" means that the clause will be true/happen if the condition is true. It does not imply that the condition is false or hypothetical.
E.G. "If I had a partner, I would go to a dancing party."
Can be roughly paraphrased as "If I get a partner, I will go to the dancing party."
In this case, the speaker may find a partner and the clause may become true (i.e. he will go to the party), whereas "Even if I had a partner, I wouldn't go to the dancing party" would mean that the speaker will never go to the dancing partner, regardless of whether or not he gets a partner.

A: "Even if" is a way to express a definiteness of an outcome. It is a way to say:

"In the scenario in which these things happen, they will still have no impact on the outcome" .

"Even if" can be used to refute an argument.

"If he were a saint, he would marry me!" - "No, he would not marry you, even if he were a saint"

"Even if" can be used to shift responsibility.

"He was drunk, that is why he crashed the car" - "No, because the pedal was broken, He would have still crashed the car, even if he were not drunk"

"If" expresses a basic conditional relationship that can be used in a number of ways and modified in other ways, such as "Even if".


text:
Q: How to get the return value of IStaticPortMappingCollection.Add return or not? I use seattle in windows 10 64 bit.
I try to forward a port by upnp and get the return value. The port forwarding works well but the following line makes 'could not convert variant of type (dispatch) into type (integer)' window.
_hResult := _Ports.add(_PortNumber, 'TCP', _PortNumber, Edit1.Text, True, _PortName);

You can find the return value type in the following msdn webpage.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa366148(v=vs.85).aspx
The whole code is
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Win.ComObj, Vcl.StdCtrls;

procedure TForm1.FormClick(Sender: TObject);
var
  _NAT: Variant;
  _Ports: Variant;
  _PortNumber: Integer;
  _PortName: string;
  _hResult: HRESULT;
begin
  _NAT := CreateOleObject('hnetcfg.natupnp');
  _Ports := _NAT.staticportmappingcollection;

  _PortNumber := 8000;
  _PortName := 'test';

  if VarIsClear(_Ports) then // $00000000
  begin
    Caption := 'error';
  end
  else
  begin
    _hResult := _Ports.add(_PortNumber, 'TCP', _PortNumber, Edit1.Text, True, _PortName);

    if _hResult = S_OK then
    begin
      Caption := 'succeeded';
    end;
  end;
end;

A: Ports.Add() returns an IStaticPortMapping interface. So you should write:
var
  _Port: Variant;
....
_Port := _Ports.Add(..._);

You've been looking at documentation that shows Add returning an HRESULT, and the IStaticPortMapping as an out parameter. But the method has been subject to parameter re-writing. The framework, in the COM method dispatch, does check the actual return value and raise an exception in case of failure. But that is all done in the background.


text:
Q: Post Templates and Post ID's I am trying to make use of the Single template for single posts ( I have a custom one). But for some reason my posts get overridden instead of displaying new data.
This is the setup I have right now

<?php global $post;
 $category_id=get_the_category($post->ID);

$announcements = new WP_Query();
$announcements->query('showposts=1&cat=$category_id');
while ( $announcements->have_posts() ) :  $announcements->the_post(); ?>

Published by:<?php echo
get_post_meta($post->ID, 'Publisher','true');?>

<?php endwhile;?>

A:
But for some reason my posts get overridden instead of displaying new
  data.

The problem is here: $announcements->query('showposts=1&cat=$category_id');
You are trying to use a variable inside a single quote string. Variables do not expand inside single quotes so instead of asking for cat=1, or cat=2, you are literally asking for cat=$category_id-- just like that, spelled out in full.
What you need instead are double quotes: $announcements->query("showposts=1&cat=$category_id");. Variables do expand in double quote.
Or better, an array-- far more readable and maintainable:
$args = array(
  'posts_per_page' => 1,
  'cat' => $category_id,
);

Note: showposts is deprecated. Use posts_per_page.

A: You need to Pass arguments into the new Object like so.
$category_id = get_the_category( $post->ID );

$args = array(
    'posts_per_page' => 1,
    'category'       => $category_id
);

$announcements = new WP_Query( $args );

This page should shine some light on your code for you, I think you've got a few typo's within it and how you call the loop is in the slightly wrong order. WP_Query in Codex.

A: I tried that, but it still overrides for instance
the_title(), get_post_meta($post->ID, 'key', 'true'), the_post_thumbnail(),

and pretty much all of them gets overriden(What I mean is when I make two posts using the same template, the fields, titles and images get overridden.) Here is how I did it:
<?php
$category_id = get_the_category( $post->ID ); $args =

array('posts_per_page' => 1, 'category' => $category_id); $announcements =
new WP_Query( $args );

while($announcements->have_posts()): $announcements->the_post();

?>

<?php the_post_thumbnail(); ?>

<?php the_title();?>

<?php endwhile;?>


text:
Q: Multiple parameter packs in a single function? I'm trying to create a function that takes two parameter packs of objects. There are two templated base classes and I'd like to pass instances of derived classes to this function. Consider this example.
template <int N>
struct First {};

template <int N>
struct Second {};

// there are a few of these
struct FirstImpl : First<5> {};
struct SecondImpl : Second<7> {};

template <int... firstInts, int... secondInts>
void function(float f, First<firstInts> &... first, Second<secondInts> &... second) {
  // ...
}

What I would like to do is call function like this
FirstImpl firstImpl;
OtherFirstImpl otherFirstImpl;
SecondImpl secondImpl;
OtherSecondImpl otherSecondImpl;
function(9.5f, firstImpl, otherFirstImpl, secondImpl, otherSecondImpl);

but this example won't compile. The compiler seems to be trying to pack everything into the second parameter pack and failing because FirstImpl can't be implicitly converted Second<N>.
How do I get around this?

A: It's pretty much next to impossible to define something with two variadic parameter packs. Once a variadic parameter pack gets encountered, it likes to consume all remaining parameters, leaving no crumbs for the second pack to feed on.
However, as I mentioned, in many cases you can use tuples, and with deduction guides in C++17, the calling convention is only slightly longer than otherwise.
Tested with gcc 7.3.1, in -std=c++17 mode:
#include <tuple>

template <int N>
struct First {};

template <int N>
struct Second {};

template <int... firstInts, int... secondInts>
void function(std::tuple<First<firstInts>...> a,
          std::tuple<Second<secondInts>...> b)
{
}

int main(int, char* [])
{
    function( std::tuple{ First<4>{}, First<3>{} },
          std::tuple{ Second<1>{}, Second<4>{} });
}

That's the basic idea. In your case, you have subclasses to deal with, so a more sophisticated approach would be necessary, probably with an initial declaration of two tuples being just a generic std::tuple< First...> and std::tuple<Second...>, with some additional template-fu. Probably need to have First and Second declare their own type in a class member declaration, and then have the aforementioned template-fu look for the class member, and figure out which superclass it's dealing with.
But the above is the basic idea of how to designate two sets of parameters, from a single variadic parameter list, and then work with it further...

A: Let's first code a variable template which determines whether a type derives from First or not:
template <int N>
constexpr std::true_type is_first(First<N> const &) { return {}; }
template <int N>
constexpr std::false_type is_first(Second<N> const &) { return {}; }

template <class T>
constexpr bool is_first_v = decltype( is_first(std::declval<T>()) )::value;

And a struct Split which collects the indices of the First and Second types:
template <class, class, class, std::size_t I = 0> struct Split;

template <
    std::size_t... FirstInts,
    std::size_t... SecondInts,
    std::size_t N
>
struct Split<
    std::index_sequence<FirstInts...>,
    std::index_sequence<SecondInts...>,
    std::tuple<>,
    N
> {
    using firsts = std::index_sequence<FirstInts...>;
    using seconds = std::index_sequence<SecondInts...>;
};

template <
    std::size_t... FirstInts,
    std::size_t... SecondInts,
    std::size_t I,
    typename T,
    typename... Tail
>
struct Split<
    std::index_sequence<FirstInts...>,
    std::index_sequence<SecondInts...>,
    std::tuple<T, Tail...>,
    I
> : std::conditional_t<
    is_first_v<T>,
    Split<std::index_sequence<FirstInts..., I>,
          std::index_sequence<SecondInts...>,
          std::tuple<Tail...>,
          I + 1
    >,
    Split<std::index_sequence<FirstInts...>,
          std::index_sequence<SecondInts..., I>,
          std::tuple<Tail...>,
          I + 1
    >
> {};

And like I told you in the comments, adding a member value to First and Second (or inheriting from std:integral_constant), this allows us to write the following:
template <std::size_t... FirstIdx, std::size_t... SecondIdx, typename Tuple>
void function_impl(float f, std::index_sequence<FirstIdx...>, std::index_sequence<SecondIdx...>, Tuple const & tup) {
    ((std::cout << "firstInts: ") << ... << std::get<FirstIdx>(tup).value) << '\n';
    ((std::cout << "secondInts: ") << ... << std::get<SecondIdx>(tup).value) << '\n';
    // your implementation
}

template <class... Args>
void function(float f, Args&&... args)  {
    using split = Split<std::index_sequence<>,std::index_sequence<>, std::tuple<std::decay_t<Args>...>>;
    function_impl(f, typename split::firsts{}, typename split::seconds{}, std::forward_as_tuple(args...));
}

Demo

A: Why won't you simply pass the class itself as template parameter? Like this:
template <int N>
struct First {};

template <int N>
struct Second {};

// there are a few of these
struct FirstImpl : First<5> {};
struct SecondImpl : Second<7> {};

template <typename FirstSpec, typename SecondSpec>
void function(float f, FirstSpec & first, SecondSpec & second) {
  // ...
}

A: Not exactly what you asked but... you could unify the two list using a variadic template-template int container (Cnt, in the following example) and next detect, for every argument, if is a First or a Second (see the use of std::is_same_v)
The following is a full working example
#include <string>
#include <vector>
#include <iostream>
#include <type_traits>

template <int>
struct First {};

template <int>
struct Second {};

// there are a few of these
struct FirstImpl : First<5> {};
struct SecondImpl : Second<7> {};

template <template <int> class ... Cnt, int... Ints>
void function (float f, Cnt<Ints> & ... args)
 {
    (std::cout << ... << std::is_same_v<Cnt<Ints>, First<Ints>>);
 }

int main()
 {
   FirstImpl firstImpl;
   FirstImpl otherFirstImpl;
   SecondImpl secondImpl;
   SecondImpl otherSecondImpl;
   function(9.5f, firstImpl, otherFirstImpl, secondImpl, otherSecondImpl);
 }


text:
Q: List available versions from sonatype nexus with aether-api my goal is to develop an internal tool for artifact deploying. The artifacts are located in a local repository management system (sonatype nexus). After researching, I tried to implement the task, with Aether-Api. But I failed at reprogramming one of their examples at my own. I can't evaluate the error.
public class SourceMaven
{
    private static RepositorySystem newRepositorySystem()
    {
        DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
        locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
        locator.addService(TransporterFactory.class, FileTransporterFactory.class);
        locator.addService(TransporterFactory.class, HttpTransporterFactory.class);

        return locator.getService(RepositorySystem.class);
    }
    private static RepositorySystemSession newSession(RepositorySystem system)
    {
        DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
        LocalRepository localRepo = new LocalRepository("/usr/local/home/myusername/tmp/aether");
        session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));

        return session;
    }
    private static List<RemoteRepository> newRepositories( RepositorySystem system, RepositorySystemSession session)
    {
        return new ArrayList<RemoteRepository>(Arrays.asList(newCentralRepository()));
    }
    private static RemoteRepository newCentralRepository()
    {
        return new RemoteRepository.Builder("sonanexus", "default", "http://ournexusservername:8081/nexus/#nexus").build();
    }

    public List<String> getReleaseList(String url)
    {
        RepositorySystem system = newRepositorySystem();
        RepositorySystemSession session = newSession(system);

        Artifact artifact = new DefaultArtifact("org.eclipse.aether:aether-util:[0,)");

        VersionRangeRequest rangeRequest = new VersionRangeRequest();
        rangeRequest.setArtifact(artifact);
        rangeRequest.setRepositories(newRepositories(system, session));

        try
        {
            VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest);
            List<Version> versions = rangeResult.getVersions();

            System.out.println("available versions " + versions);
        }
            catch (VersionRangeResolutionException ex)
        {
            System.out.println("failed ...");
        }

        return null;
    }
}

As output I only get an empty List without an error.

available versions []

The requestested artifact coordinates are linked in our nexus and can be found in the webinterface.

A: Code above is working.
It is important to clarify the url more specific so instead of
http://hostname:8081/nexus/#nexus
i needed to change it to:
http://hostname:8081/nexus/content/groups/public


text:
Q: Toggle effect don´t work I have a problem adding toggle effect.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('.contactpic').hide();
    $('.menu-item-54').click(function() {
        $('.contactpic').toggle( "slide", {direction: "left"}, 1000);
        return false;
    });
});
</script>

With this code the element (contacpic) dissapear.
If i remove the effect:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('.contactpic').hide();
    $('.menu-item-54').click(function() {
        $('.contactpic').toggle(1000);
        return false;
    });
});
</script>

Then, works correct.
I really appreciate any help.
Thank you.


text:
Q: Filemaker - how/where to use custom function? I have downloaded the BaseElements plugin for Filemaker and managed to get it installed, I have downloaded this specifically to make use of "BE_ExportFieldContents" (https://baseelementsplugin.zendesk.com/hc/en-us/articles/204700538-BE-ExportFieldContents) which basically allows me to export from a Container field on a server side script. I have looked through the documentation and cannot seem to find help.
Now I have the function, I'm completely at a loss on how to actually call the function? I want to export something from the container file to the filemaker documents path - so my question is, where and how the hell do I use this function in Filemaker? Apologies in advance for the noob question.

A: You make a script where you call this function from the record in question. This script can be run in the client, or via a schedule on FileMaker Server or via the Perform Script on Server script step.
The syntax is like this:

BE_ExportFieldContents ( field ; outputPath )

Where the 'field' parameter is the container field and the 'outputPath' is where you want the file to end up.
Usually you call such functions via the Set Variable script step. After the execution the variable contains any error or result from the call.
Note that the plugin needs to be installed and enabled on the server for it to work there.


text:
Q: Matplotlib tick labels Is there a way to render the tick labels just right inside the axes, i.e, something like the direction property there is on the ticks themself?
Right now I'm setting the x property to a positive value on the ticklabels to draw them inside of the axis, i.e.,
ax2.set_yticklabels(['0', '2500', '5000', '7500'], minor=False, x=0.05)

But this doesn't really work on resizable plots, as the 0.05 figure is absolute (and too big on big plots).
Any ideas?

A: I'm assuming that ax2 is constructed as ax2 = ax.twinx(), which is to say that it is on the right side of the axes.
You could do something like the following:
ax2.set_yticklabels(['0', '2500', '5000', '7500'], minor=False, horizontalalignment='right')
for tick in ax2.yaxis.get_major_ticks():
        tick.set_pad(-8)

If you want the left side axis on the inside too, then you'd simply switch the horizontal alignment to 'left' and change the pad from -8 to -25.
The two numbers might not be exact and could depend on other matplotlib settings you might have (e.g. length of major ticks) so you may want to increase or decrease those values slightly.


text:
Q: Specify JsonConverters with attributes in Json.net? I am receiving JSON data to my server with dates represented like this:
{
    "startDate": {
        "d": "/Date(1346454000000)/"
    },
    "slots": [
        {
            "d": "/Date(1347058800000)/"
        },
        {
            "d": "/Date(1347145200000)/"
        }
    ]
}

Its serialized to a simple object:
public class SlotsVm
{
    public DateTime StartDate { get; set; }

    public DateTime[] Slots { get; set; }
}

Because the date format is strange, I had to write a custom JsonConverter to process it. To deserialize, I use code like this:
var slotsVm = JsonConvert.DeserializeObject<SlotsVm>(body,
    new CustomDateTimeConverter());

If possible, I would like the need for the converter to be defined on the SlotsVm class, rather than in the code that actually makes the conversion. This is possible for the startDate property using attributes:
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime StartDate { get; set; }

but it is not possible for Slots, which is an array instead of a simple DateTime.
It would be best for me to be able to define the converters that the class needs on the class itself:
[JsonConverters(typeof(CustomDateTimeConverter), ...]
public class PutDealVm
{

}

but there doesn't seem to be a way to do this.
Can you think of a solution? Is there some way to define converters for a class that I have missed? Alternatively, is it possible to define the converter that an array should user for each of its elements?

A: What about something like this? I appreciate that this may not directly answer your question, but I was too lazy to recreate the CustomDateTimeConverter class, so came up with this instead, which is arguably simpler, as there is no need for a custom converter.
string json = "{\"startDate\": {\"d\": \"/Date(1346454000000)/\"},\"slots\": [{\"d\": \"/Date(1347058800000)/\"},{\"d\": \"/Date(1347145200000)/\"}]}";

SlotsVmDeserialized slotsVmDeserialized =
    JsonConvert.DeserializeObject<SlotsVmDeserialized>(json);

SlotsVm slotsVm = new SlotsVm()
{
    Slots = slotsVmDeserialized.Slots.Select(d => d.Date),
    StartDate = slotsVmDeserialized.StartDate.Date
};

....

public class SlotsVm
{
    public DateTime StartDate { get; set; }
    public IEnumerable<DateTime> Slots { get; set; }
}

public class SlotsVmDeserialized
{
    public DateObject StartDate { get; set; }
    public IEnumerable<DateObject> Slots { get; set; }
}

public class DateObject
{
    [JsonProperty("d")]
    public DateTime Date { get; set; }
}

What I've done here is firstly deserialized to the SlotsVmDeserialized class, which is used to hold a single DataObject and an IEnumerable of them. The DateObject class is essentially my alternative/workaround to the custom converter. I could have done all this without any attributes by removing [JsonProperty("d")] and renaming Data to D.
Once deserialized, I then create a new SlotsVm object based on the properties of the SlotsVmDeserialized object.


text:
Q: Why does the default GRU implementation in pytorch and keras differ significantly? After implementing my own GRU cell, I was trying to validate it with the default implementation available on pytorch and keras. My implementation was very close to pytorch but significantly different from keras. So, I first decided to compare the implementations available in pytorch and keras against each other and found that they both were significantly different. Here is some code:
import numpy as np
import torch as tt
import torch.nn as nn
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# data generation
input_size = 2
seq_len = 4
hidden_size = 3
batch_size=1

rng = np.random.default_rng(10)

xx = rng.uniform(size=(batch_size, seq_len, input_size)).astype(np.float32)
print(xx.shape)

output:
(1, 4, 2)

First created a keras gru layer and do one forward pass to get the output
gru_keras = layers.GRU(hidden_size, return_sequences=True)
out_gru_keras = gru_keras(xx)
out_gru_keras

output:
<tf.Tensor: shape=(1, 4, 3), dtype=float32, numpy=
array([[[0.05563376, 0.22639018, 0.14037813],
        [0.05021746, 0.27509487, 0.17843583],
        [0.0273784 , 0.23740683, 0.1731183 ],
        [0.10505023, 0.38027072, 0.31583947]]], dtype=float32)>

Then check the weights in keras gru
gru_keras_weights = gru_keras.get_weights()
print(f'{len(gru_keras_weights)=}')
for w in gru_keras_weights:
    print(w.shape, w.dtype, w)

output:
len(gru_keras_weights)=3
(2, 9) float32 [[ 0.38249677 -0.67729133 -0.28855678  0.3081903  -0.530349    0.1531434
   0.09444886  0.2978403   0.1516701 ]
 [ 0.0833146   0.27516943  0.4720915  -0.7370237  -0.20921749  0.38180763
   0.23018956  0.39872426  0.5722596 ]]
(3, 9) float32 [[-0.21449113  0.2944518  -0.25759113  0.2292317   0.35174483  0.42021522
  -0.5116475   0.42759803 -0.05884372]
 [-0.3477073  -0.15120703  0.7333025   0.418491   -0.07980055 -0.21007833
  -0.1924745   0.20504965  0.11737184]
 [ 0.01270523  0.15124948  0.4014033  -0.568793    0.4513449  -0.03860948
  -0.39513308 -0.36090007 -0.02702253]]
(2, 9) float32 [[0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]]

Now, create a pytorch gru and check its weights
gru_torch = nn.GRU(
    input_size=input_size,
    hidden_size=hidden_size,
    bias=True,
    batch_first=True,
    num_layers=1,
    dropout=0.0,
    bidirectional=False,
    dtype=tt.float32
)
sd_gru_torch = gru_torch.state_dict()
for k,v in sd_gru_torch.items():
    print(f'{k}, {v.shape}')

output:
weight_ih_l0, torch.Size([9, 2])
weight_hh_l0, torch.Size([9, 3])
bias_ih_l0, torch.Size([9])
bias_hh_l0, torch.Size([9])

Clearly, pytorch implements two separate bias bias_ih_l0 and bias_hh_l0 while keras has a concatenated bias (which is zero). Now I copied the weights accordingly.
with tt.no_grad():
    gru_torch.get_parameter('weight_ih_l0').copy_(tt.tensor(gru_keras_weights[0].T))
    gru_torch.get_parameter('weight_hh_l0').copy_(tt.tensor(gru_keras_weights[1].T))
    gru_torch.get_parameter('bias_ih_l0').copy_(tt.tensor(gru_keras_weights[2].T[:,0]))
    gru_torch.get_parameter('bias_hh_l0').copy_(tt.tensor(gru_keras_weights[2].T[:,1]))

... and check the parameters again
with tt.no_grad():
    for p in gru_torch.parameters():
        print(p.shape, p)

output:
torch.Size([9, 2]) Parameter containing:
tensor([[ 0.3825,  0.0833],
        [-0.6773,  0.2752],
        [-0.2886,  0.4721],
        [ 0.3082, -0.7370],
        [-0.5303, -0.2092],
        [ 0.1531,  0.3818],
        [ 0.0944,  0.2302],
        [ 0.2978,  0.3987],
        [ 0.1517,  0.5723]], requires_grad=True)
torch.Size([9, 3]) Parameter containing:
tensor([[-0.2145, -0.3477,  0.0127],
        [ 0.2945, -0.1512,  0.1512],
        [-0.2576,  0.7333,  0.4014],
        [ 0.2292,  0.4185, -0.5688],
        [ 0.3517, -0.0798,  0.4513],
        [ 0.4202, -0.2101, -0.0386],
        [-0.5116, -0.1925, -0.3951],
        [ 0.4276,  0.2050, -0.3609],
        [-0.0588,  0.1174, -0.0270]], requires_grad=True)
torch.Size([9]) Parameter containing:
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0.], requires_grad=True)
torch.Size([9]) Parameter containing:
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0.], requires_grad=True)

Now the weights are matching exactly. Taking a forward pass through torch with the same data
with tt.no_grad():
    out_gru_torch, _ = gru_torch(tt.tensor(xx))
print (out_gru_torch.shape, out_gru_torch)

output:
torch.Size([1, 4, 3]) tensor([[[0.0638, 0.2232, 0.1145],
         [0.0553, 0.2741, 0.1618],
         [0.0306, 0.2399, 0.1644],
         [0.1231, 0.3970, 0.3153]]])

But it can be seen that the outputs are different in value
out_gru_torch.numpy() - out_gru_keras.numpy()

output:
array([[[ 0.00813178, -0.00323714, -0.02592391],
        [ 0.0050362 , -0.000976  , -0.01662555],
        [ 0.00321813,  0.0024882 , -0.00869839],
        [ 0.0180769 ,  0.01671427, -0.00050169]]], dtype=float32)

summing up the differences
np.sum(np.abs(out_gru_torch.numpy() - out_gru_keras.numpy()))

output:
0.10962818

Why is there such a significant difference?
I also tried the same thing with LSTMs but found that the difference was insignificant. This can be attributed to floating point rounding errors maybe. Here is some code.
Make a keras LSTM
lstm_keras = layers.LSTM(hidden_size, return_sequences=True)
out_lstm_keras = lstm_keras(xx)
out_lstm_keras

output:
<tf.Tensor: shape=(1, 4, 3), dtype=float32, numpy=
array([[[-0.12176377, -0.07746243, -0.08807365],
        [-0.17760691, -0.11547467, -0.12406464],
        [-0.16980645, -0.1159803 , -0.12289675],
        [-0.16330168, -0.08463871, -0.18625976]]], dtype=float32)>

check keras LSTM weights
lstm_keras_weights = lstm_keras.get_weights()
print(f'{len(lstm_keras_weights)=}')
for w in lstm_keras_weights:
    print(w.shape, w.dtype, w)

output:
len(lstm_keras_weights)=3
(2, 12) float32 [[-0.18769234  0.6526979   0.27196562 -0.23817068 -0.05964065 -0.11090988
  -0.6442989  -0.4168117  -0.344454    0.12466687 -0.6536666  -0.28540143]
 [-0.35713544  0.34027737  0.09951967 -0.21514818  0.47551024  0.305395
   0.16330504  0.22410381 -0.13371867  0.21646535  0.01366949  0.4818431 ]]
(3, 12) float32 [[-0.22128499 -0.17296375  0.03671373  0.16226508  0.19011612 -0.41836154
  -0.5816412  -0.32847112 -0.31468534 -0.27402246  0.05426207  0.24291728]
 [ 0.4650536  -0.57491106  0.01105271 -0.0380749   0.2271702   0.39930764
   0.11620218 -0.19071549 -0.30224687 -0.13937864 -0.27111995  0.08010413]
 [ 0.45147026  0.3288076  -0.37750363  0.35117835 -0.31541684 -0.1335725
  -0.0910389  -0.24736843  0.03350063 -0.27691114 -0.28898126 -0.27222085]]
(12,) float32 [0. 0. 0. 1. 1. 1. 0. 0. 0. 0. 0. 0.]

Now create a pytorch LSTM and check its weights
lstm_torch = nn.LSTM(
    input_size=input_size,
    hidden_size=hidden_size,
    bias=True,
    batch_first=True,
    num_layers=1,
    dropout=0.0,
    bidirectional=False,
    dtype=tt.float32
)
sd_lstm_torch = lstm_torch.state_dict()
for k,v in sd_lstm_torch.items():
    print(f'{k}, {v.shape}')

output:
weight_ih_l0, torch.Size([12, 2])
weight_hh_l0, torch.Size([12, 3])
bias_ih_l0, torch.Size([12])
bias_hh_l0, torch.Size([12])

It can be noted that in keras LSTM, only one bias is implemented (not a stack of 2 bias as done in GRU), so I choose one of the bias in pytorch LSTM and copied keras bias vector to it. It doesn't make much difference on which bias is copied to, the other bias is made zero. Here I choose bias_ih_l0 to copy to and bias_hh_l0 is made zero.
with tt.no_grad():
    lstm_torch.get_parameter('weight_ih_l0').copy_(tt.tensor(lstm_keras_weights[0].T))
    lstm_torch.get_parameter('weight_hh_l0').copy_(tt.tensor(lstm_keras_weights[1].T))
    lstm_torch.get_parameter('bias_ih_l0').copy_(tt.tensor(lstm_keras_weights[2]))
    lstm_torch.get_parameter('bias_hh_l0').copy_(tt.zeros(lstm_keras_weights[2].shape))

Checking the parameters again
with tt.no_grad():
    for p in lstm_torch.parameters():
        print(p.shape, p)

output:
torch.Size([12, 2]) Parameter containing:
tensor([[-0.1877, -0.3571],
        [ 0.6527,  0.3403],
        [ 0.2720,  0.0995],
        [-0.2382, -0.2151],
        [-0.0596,  0.4755],
        [-0.1109,  0.3054],
        [-0.6443,  0.1633],
        [-0.4168,  0.2241],
        [-0.3445, -0.1337],
        [ 0.1247,  0.2165],
        [-0.6537,  0.0137],
        [-0.2854,  0.4818]], requires_grad=True)
torch.Size([12, 3]) Parameter containing:
tensor([[-0.2213,  0.4651,  0.4515],
        [-0.1730, -0.5749,  0.3288],
        [ 0.0367,  0.0111, -0.3775],
        [ 0.1623, -0.0381,  0.3512],
        [ 0.1901,  0.2272, -0.3154],
        [-0.4184,  0.3993, -0.1336],
        [-0.5816,  0.1162, -0.0910],
        [-0.3285, -0.1907, -0.2474],
        [-0.3147, -0.3022,  0.0335],
        [-0.2740, -0.1394, -0.2769],
        [ 0.0543, -0.2711, -0.2890],
        [ 0.2429,  0.0801, -0.2722]], requires_grad=True)
torch.Size([12]) Parameter containing:
tensor([0., 0., 0., 1., 1., 1., 0., 0., 0., 0., 0., 0.], requires_grad=True)
torch.Size([12]) Parameter containing:
tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], requires_grad=True)

Now do a forward pass through pytorch LSTM with the same data
with tt.no_grad():
    out_lstm_torch, _ = lstm_torch(tt.tensor(xx))
print (out_lstm_torch.shape, out_lstm_torch)

output:
torch.Size([1, 4, 3]) tensor([[[-0.1218, -0.0775, -0.0881],
         [-0.1776, -0.1155, -0.1241],
         [-0.1698, -0.1160, -0.1229],
         [-0.1633, -0.0846, -0.1863]]])

Taking absolute difference
np.sum(np.abs(out_lstm_torch.numpy() - out_lstm_keras.numpy()))

output:
2.7567148e-07

The difference is significantly less. I also found that the initial hidden states are assumed to be all zeros by both pytorch and keras so I don't need to set it manually.


text:
Q: Log Likelihoods of Exponential Families How can one derive the log-likelihood of the saturated model of an exponential family in general?
Differentiating the log likelihood w.r.t $\theta$ gives $y_i=\hat{\mu_i}$ but I don't think replacing $y_i$ with $\hat{\mu_i}$ in the equation for the general log-likelihood would be helpful? Also what about maximising w.r.t $\phi$?

A: for $\exp\Big(\frac{y_i\theta_i-b(\theta_i)}{\alpha(\varphi)}+c(y_i,\varphi)\Big)$

log-likelihood of the saturated model of an exponential family in general is

$\sum_i\Big(\frac{y_i\hat\theta_i-b(\hat\theta_i)}{\alpha(\varphi)}+c(y_i,\varphi)\Big)$ where $\hat\theta_i=g(\mu_i)$ and put $\mu_i=y_i$
we maximize the log-likelihood, if we need to estimate any of a parameters and maximize w.r.t. that parameter. Otherwise, not to get saturated model.
to get log-likelihood of the saturated model, we just see the perfect fit(i.e all $\mu_i=y_i$)..... log-likelihood of the saturated model is useful to compare scaled deviance from observed model. we don't maximize it.


text:
Q: MultiAxisChart In Jasper report both axis are coming left side I was able to start with MultiAxis Chart with Jasper report using Link : create MultiAxis Chart with Jasper report.
I was able to creat the chart as well but not completely formatted. I was having Axis Problem. Both X-axis are coming on left side. How do I move one Axis of bar chart on right side. Following is the picture of my current problem:

Following is my jrxml content.
            <?xml version="1.0" encoding="UTF-8"?>
            <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="cutting_indicator_cutter" language="groovy" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
                <property name="ireport.zoom" value="1.0"/>
                <property name="ireport.x" value="0"/>
                <property name="ireport.y" value="48"/>
                <subDataset name="chart1">
                    <queryString language="SQL">
                        <![CDATA[select Q.proddate,NVL(Q.m2NetReel,0)
            ,case when Q.HMO <> 0 then
                                                      NVL((Q.m2NetReel/Q.HMO),0)
                                                  end  as m2NETBYHMO,
                                                  Q.Objectif_HMOBY1000
            from (

            SELECT
              PROD_DATE as proddate,
              case when CUTTING_PRODUCTIVITY.REMAKE_CUT_SQM  is null then CUTTING_PRODUCTIVITY.CUTTER_NET_SQM
              else
                   CUTTING_PRODUCTIVITY.CUTTER_NET_SQM +  CUTTING_PRODUCTIVITY.REMAKE_CUT_SQM
              end as m2NetReel,
               (CUTTING_PRODUCTIVITY.MACHINE_WORKING_HOURS_NORM * CUTTING_PRODUCTIVITY.USER_QUANTITY ) as HMO,
               1000/(CUTTING_MACHINE.CADENCY*19.26) as Objectif_HMOBY1000

            FROM  CUTTING_PRODUCTIVITY CUTTING_PRODUCTIVITY
            INNER JOIN  CUTTING_MACHINE CUTTING_MACHINE
            ON CUTTING_MACHINE_ID=CUTTING_MACHINE.CUTTING_ID where trunc(CUTTING_PRODUCTIVITY.PROD_DATE) >= '1-May-15' and trunc( CUTTING_PRODUCTIVITY.PROD_DATE ) <='31-May-15'
            ORDER BY CUTTER) Q]]>
                    </queryString>
                    <field name="PRODDATE" class="java.sql.Timestamp"/>
                    <field name="NVL(Q.M2NETREEL,0)" class="java.math.BigDecimal"/>
                    <field name="M2NETBYHMO" class="java.math.BigDecimal"/>
                    <field name="OBJECTIF_HMOBY1000" class="java.math.BigDecimal"/>
                </subDataset>
                <queryString>
                    <![CDATA[SELECT EST_CUTTER_GLASSES_QTY,
              CUTTER_NET_SQM,
              REMAKE_CUT_QTY,
              PROD_DATE,
              REMAKE_CUT_SQM,
              CUTTING_MACHINE.CADENCY,
              USER_QUANTITY,
              CUTTER,
              MACHINE_WORKING_HOURS_NORM
            FROM  CUTTING_PRODUCTIVITY CUTTING_PRODUCTIVITY
            INNER JOIN  CUTTING_MACHINE CUTTING_MACHINE
            ON CUTTING_MACHINE_ID=CUTTING_MACHINE.CUTTING_ID
            where trunc(CUTTING_PRODUCTIVITY.PROD_DATE) >= '1-May-15' and trunc( CUTTING_PRODUCTIVITY.PROD_DATE ) <='31-May-15'
            ORDER BY CUTTER]]>
                </queryString>
                <field name="EST_CUTTER_GLASSES_QTY" class="java.math.BigDecimal"/>
                <field name="CUTTER_NET_SQM" class="java.math.BigDecimal"/>
                <field name="REMAKE_CUT_QTY" class="java.math.BigDecimal"/>
                <field name="PROD_DATE" class="java.sql.Timestamp"/>
                <field name="REMAKE_CUT_SQM" class="java.math.BigDecimal"/>
                <field name="CADENCY" class="java.math.BigDecimal"/>
                <field name="USER_QUANTITY" class="java.math.BigDecimal"/>
                <field name="CUTTER" class="java.lang.String"/>
                <field name="MACHINE_WORKING_HOURS_NORM" class="java.math.BigDecimal"/>
                <group name="CUTTER">
                    <groupExpression><![CDATA[$F{CUTTER}]]></groupExpression>
                    <groupHeader>
                        <band height="325">
                            <frame>
                                <reportElement x="0" y="0" width="555" height="325" printWhenGroupChanges="CUTTER"/>
                                <multiAxisChart>
                                    <chart renderType="svg" theme="generic">
                                        <reportElement x="24" y="0" width="486" height="325">
                                            <property name="net.sf.jasperreports.chart.range.axis.tick.interval" value="2"/>
                                        </reportElement>
                                        <chartTitle/>
                                        <chartSubtitle/>
                                        <chartLegend position="Bottom"/>
                                    </chart>
                                    <multiAxisPlot>
                                        <plot/>
                                        <axis>
                                            <lineChart>
                                                <chart renderType="svg">
                                                    <reportElement x="0" y="0" width="0" height="0" backcolor="#FFFFFF"/>
                                                    <chartTitle color="#000000"/>
                                                    <chartSubtitle color="#000000"/>
                                                    <chartLegend textColor="#000000" backgroundColor="#FFFFFF" position="Bottom"/>
                                                </chart>
                                                <categoryDataset>
                                                    <dataset>
                                                        <datasetRun subDataset="chart1">
                                                            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                                                        </datasetRun>
                                                    </dataset>
                                                    <categorySeries>
                                                        <seriesExpression><![CDATA["WEIGHTAVG"]]></seriesExpression>
                                                        <categoryExpression><![CDATA[$F{PRODDATE}]]></categoryExpression>
                                                        <valueExpression><![CDATA[$F{NVL(Q.M2NETREEL,0)}]]></valueExpression>
                                                    </categorySeries>
                                                    <categorySeries>
                                                        <seriesExpression><![CDATA["OBJECTIF"]]></seriesExpression>
                                                        <categoryExpression><![CDATA[$F{PRODDATE}]]></categoryExpression>
                                                        <valueExpression><![CDATA[$F{OBJECTIF_HMOBY1000}]]></valueExpression>
                                                    </categorySeries>
                                                </categoryDataset>
                                                <linePlot isShowLines="true" isShowShapes="true">
                                                    <plot labelRotation="-45.0"/>
                                                </linePlot>
                                            </lineChart>
                                        </axis>
                                        <axis>
                                            <barChart>
                                                <chart renderType="svg">
                                                    <reportElement x="0" y="0" width="0" height="0" backcolor="#FFFFFF"/>
                                                    <chartTitle color="#000000"/>
                                                    <chartSubtitle color="#000000"/>
                                                    <chartLegend textColor="#000000" backgroundColor="#FFFFFF" position="Bottom"/>
                                                </chart>
                                                <categoryDataset>
                                                    <dataset>
                                                        <datasetRun subDataset="chart1">
                                                            <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                                                        </datasetRun>
                                                    </dataset>
                                                    <categorySeries>
                                                        <seriesExpression><![CDATA["M2NetHMO"]]></seriesExpression>
                                                        <categoryExpression><![CDATA[$F{PRODDATE}]]></categoryExpression>
                                                        <valueExpression><![CDATA[$F{M2NETBYHMO}]]></valueExpression>
                                                    </categorySeries>
                                                </categoryDataset>
                                                <barPlot>
                                                    <plot/>
                                                    <itemLabel/>
                                                </barPlot>
                                            </barChart>
                                        </axis>
                                    </multiAxisPlot>
                                </multiAxisChart>
                            </frame>
                        </band>
                    </groupHeader>
                </group>
                <background>
                    <band splitType="Stretch"/>
                </background>
                <title>
                    <band height="50"/>
                </title>
            </jasperReport>

How do I move my bar chart axis to right?

A: To move an axis to the right side of the chart in jasper reports, you'll need to create a Customizer for your chart. Once you do that, the following commands in your customizer will move your axis to the right side of the chart:
// get plot from chart object
CategoryPlot plot = (CategoryPlot) chart.getPlot();

// move axis to right side of chart
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);


text:
Q: Does the scale factor evolution in a matter dominated universe allow for acceleration? One probably very trivial issue which is bothering me.
Standard cosmology says that in a FRW metric, in a matter dominated flat universe (Pressure $P = 0$ and $K = 0$), the scale factor, $a \propto t^{2/3}$.
This gives $\dot{a} \propto \frac{2}{3}t^{-1/3}$ and $\ddot{a} \propto \frac{-2}{9}t^{-4/3}$.
In other words, $\ddot{a} < 0$, always.
Now, if current observations indicate that the universe is accelerating i.e. $\ddot{a} > 0$, does it imply that the good old result $a \propto t^{2/3}$ is incorrect?
Or am I interpreting something incorrectly?

A: The result you quote is for a matter dominated universe, but the universe is dark energy dominated in the accelerating epoch. You could say that matter domination tried to halt expansion, but failed: dark energy started to dominate before expansion halted.


text:
Q: How to insert the information of a cookie in a form I have a problem with my php script. I would like to print the value of my cookie, as "value" in the form I have created. But it does not print it and my website does not look like I want. Here is my code. And the error I got is:
Notice: Undefined index: pseudo in C:\xampp\htdocs\OpenClassroom\index.php on line 4
Thanks in advance.

<?php
if (isset($_COOKIE['username']))
{
    setcookie('username', htmlspecialchars($_POST['pseudo']), time() + 31536000, null, null, false, true);
}
else
{
    setcookie('username', 'NewUsername', time() + 365*24*3600, null, null, false, true);
}
?>

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Mini-chat</title>

    <form action="commentaires.php" method="post">

        Pseudo : <input type="text" value="<?php echo $_COOKIE['username'] ; ?>" name="pseudo" id="pseudo" />

        Message :  <input type="text" name="message" id="message" />

        <input type="submit" value="Envoyer" />

    </form>

A: $_COOKIE doesn't set the cookie when using setcookie() on the first request according to the documentation:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.

So...subsequent requests will show properly. A quick and dirty solution is to set it manually the first time:
<?php
if (isset($_COOKIE['username']))
{
    setcookie('username', htmlspecialchars($_POST['pseudo']), time() + 31536000, null, null, false, true);
}
else
{
    setcookie('username', 'NewUsername', time() + 365*24*3600, null, null, false, true);
    $_COOKIE['username'] = 'NewUsername';
}
?>


text:
Q: Android (MapView): How to set Zoom level of 4 miles in the mapview? I have a latitude and longitude(GeoPoint) which is the center of map.
I want to set zoom level of 4miles distance from latitude and longitude that I have.
Thanks in Advance,

A: You can use the setzoom()-function to do so. The code below can be found in this example.
mc = mapView.getController();
String coordinates[] = {"1.352566007", "103.78921587"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);

p = new GeoPoint(
    (int) (lat * 1E6),
    (int) (lng * 1E6));

mc.animateTo(p);
mc.setZoom(17);

A: SOLVED :
from Androd google API :
zoomlevel sets the zoomlevel of the map. The value will be clamped to be between 1 and 21 inclusive, though not all areas have tiles at higher zoom levels. This just sets the level of the zoom directly;
Parameters:
zoomLevel - At zoomLevel 1, the equator of the earth is 256 pixels long. Each successive zoom level is magnified by a factor of 2.
Returns:
the new zoom level, between 1 and 21 inclusive.
So
given the Equator E = 40075 Km or 21.638,8 miles
given the distance to zoom D = 20 km or miles
the zoom level : L = log2(E/D)+1
This is the simple method I've used
remember to set E= 21.638,8 if you want to use the miles...
public static byte zoomLevel (double distance){
    byte zoom=1;
    double E = 40075;
    Log.i("Astrology", "result: "+ (Math.log(E/distance)/Math.log(2)+1));
    zoom = (byte) Math.round(Math.log(E/distance)/Math.log(2)+1);
    // to avoid exeptions
    if (zoom>21) zoom=21;
    if (zoom<1) zoom =1;

    return zoom;
}

A: Play with the .setZoom(int); parameter of your map. i think its around 15:
so myMap.setZoom(15);


text:
Q: SQL WHERE clause needs to be dynamic I am working on a stored procedure to get accounts for a case. If the @accounts parameter is NULL, I want to get all the accounts for the case. If @accounts is NOT NULL, then it will be a comma separated string of accountid's. I would like to have a single where clause that can handle this. Something that says if @accounts is NULL then grab all the accounts for the case. Otherwise, use the @accounts parameter and grab the accounts with the account id's specified. I would like to avoid a big IF statement that would require me to have the query twice with 2 different WHERE clauses.
DECLARE @caseId BIGINT,
    DECLARE @accounts VARCHAR(255)

    SELECT TOP 1 @userId = userId FROM TblTraceCur t
    WHERE caseId = @caseid
    ORDER BY processDate DESC

    SELECT
              .... (select logic) ...
    WHERE
              t.caseId = @caseID AND
              t.userId = @userId AND
              t.shortStock = 0 AND
              ... (where I need the new logic) ...
    order by t.tracln ASC

Thanks a lot!

A: This worked for me. Add (@accounts IS NULL OR @accounts LIKE ('%,' + CAST(t.caseId AS VARCHAR(255)) + ',%')) where you indicated in your post. Of course you have to make sure that your first character and last character in @accounts are commas for this to work but it's the easiest I think. Not having the commas would return ids falsely for example: having @accounts = 12 would return ids 1, 2, and 12. Using commas and making sure they're the first and last characters prevent this from happening.


text:
Q: PHP Files downloading (source code) instead of running, sometimes I'm running Uniserver on windows 7, and it's been extremely difficult so far.
At first, only files in subdirectories would not run properly. Now though (after a restart), all files do not work.
Basically, instead of running, the source file is downloaded in my browser (unless the server isn't on - then I simply get the "Problem Loading Page" message).
When it was working, other problems occured, such as include files being echo'd instead of run.
Can someone guide me w/ regards to getting Uniserver to run cleanly and properly?
Thanks!

Edit:
Now when I browse to http://localhost, it shows a directory browsing interface like this: http://www.gobalakrishnan.com/wp-content/uploads/2008/04/directory-browsing.jpg
Edit: I reinstalled Uniserver and it's the same, except now the admin panel is working!

A: That's literally what you get when all you do is browse to http://localhost/ and NOTHING else?
I believe this means that you have a redirect either in the core Apache configuration, or in your private .htaccess file, because you're being taken all the way into a WordPress directory that's not meant to be directly accessed.
Two Solutions to this current problem:
(1) Review your .htaccess file (perhaps temporarily rename it, or delete it AFTER MAKING A BACKUP!!!!
(2) Turn off "indexes" or "Directory indexes" (indexing?) in the Uniserver configuration.

A: Your image looks to me like you dis-configured virtual dir in IIS.
Try in IIS to uncheck "Directory browsing" checkbox
Also, configure your browser to permit running active content/ scripts, etc.


text:
Q: How to get IsHighlighted to false at a top level menu item? Here you can see the inital situation, menu item "Encoding" is highlighted:

Now I want to get rid of the highlighted state programmatically.
This is working but flickering:
WindowState stateOfWindowContainingTheMenu = win.WindowState;
win.WindowState = WindowState.Minimized;
win.WindowState = stateOfWindowContainingTheMenu;

The IsHighlighted setter of a menu item is protected and I want to avoid subclassing.
I'm looking for a C# window freeze or other solution (though I don't have a Xaml solution).

A: I'm glad to have finally found the solution: The highlighting disappears if I first focus the MenuItem and then the Window:
topLevelMenuItem.Focus();
windowContainingTheMenu.Focus();


text:
Q: Is it possible to fix this? ft-rockey.rules:1 Kubuntu 15.10 - Single OS - Desktop
Emergency Mode - journalctl -xb read out - red text

Can I fix this to get my Kubuntu back up and running?
unknown key 'BUS' in /etc/udev/rules.d/ft-rockey.rules:1
invalid rule '/etc/udev/rules.d/ft-rockey.rules:1'

A: Solved -
rm -rdfv /etc/udev/rules.d/ft-rockey.rules
I have no idea what rockey was, but i do know that with mr rockey gone Im back up and running again without emergency mode - kudos to askubuntu and internet searches!!


text:
Q: Why is my function not working- pop up image gallery I'm trying to make a standard effect, where clicking on an image in a gallery will enlarge the image, put it at the center of the screen (in front of everything else), and darken the background. I haven't set up the slideshow part yet (so it won't change images), but the aim is to create an index so that I can do that in the future. I'm following a tutorial and trying to adapt it to my backend, but I'm missing a beat. It's not registering which image has been clicked (and I'm getting two errors in the console- 404, and 500). I'm using Nextjs as my frontend, Sanity for my backend.
import React, { useState } from 'react';
import { client, urlFor } from '../lib/client';
import { Header, Footer, Modal } from '../components';

const sets = ({setData, imagesData}) => {

  const [clickedImage, setClickedImage] = useState(null);
  const [currentIndex, setCurrentIndex] = useState(null);

  const handleClick = (imagesData, index) => {
    setCurrentIndex(index);
    setClickedImage(imagesData.image);
  };

  const handleRotationRight = () => {
    const totalLength = imagesData.imageItems.length;
    if(currentIndex + 1 >= totalLength){
      setCurrentIndex(0);
      const newData = imagesData.imageItems[0];
      setClickedImage(newData);
      return;
    }
    const newIndex = currentIndex + 1;
    const newData = imagesData.imageItems.filter((image) => {
      return imagesData.imageItems.indexOf(image) === newIndex;
    });
    const newItem = newData[0].image;
    setClickedImage(newItem);
    setCurrentIndex(newIndex);
  };

  return (

{setData.set_name}

            {imagesData.imageItems && imagesData.imageItems.map((imagesData, index) => (

                 handleClick(imagesData, index)}
                />

            ))}

        {clickedImage && (
          <Modal
            clickedImage={clickedImage}
            handleRotationRight={handleRotationRight}
            setClickedImage={setClickedImage}
          />
        )}

  )
}

export default sets

export const getServerSideProps = async (pageContext) => {
  const setSlug = pageContext.query.slug;

  const setQuery = `*[_type == 'set' && slug.current == $setSlug][0]`;
  const imagesQuery = `*[_type == 'set' && slug.current == $setSlug][0]{'imageItems':set_images[]{image{
    asset->{_id, url}, alt, name, date, size, materials}}}`;

  const setData = await client.fetch(setQuery, {setSlug});
  const imagesData = await client.fetch(imagesQuery, {setSlug});

  return {
    props: {setData, imagesData}
  }
}

Heres the Modal component:
import React from 'react'

const Modal = ({clickedImage, handleRotationRight, setClickedImage}) => {

    const handleClick = (e) => {
        if(e.target.classList.contains("dismiss")){
            setClickedImage(null);
        }
    }

    return(
        <>

            x

        </>
    )
};

export default Modal;


text:
Q: Can't SSH via router port-forward when openvpn client running I have a debian PC on my home network.  I use a dynamic DNS service so I can SSH to the PC from elsewhere on the internet.  I also use port-forwarding on the router, so I map from (say) 2222 at the dynamic address to 22 on the PC.
This all works fine, until I run an openvpn client on the PC.  Then I cannot make the SSH connection.
However, I can make an SSH connection from any other PC on the home network direct to the debian PC.  It's just the router's port forward that doesn't work.
Why does the PC see the connection coming from the router to port 22 differently to how it sees a direct connection attempt to port 22?  And why doesn't the connection work?  Ideas welcome!

A: Routes
Most VPN software is smart enough to set up routes that ignore Local Area Network (LAN) traffic, so that's why SSH works from your other PCs on your home network.
However, all Internet-destined traffic is still routed out via the VPN interface by default.  This includes connections via port forwarding.  So the SSH traffic enters through your router, but then gets answered through the VPN (which messes it up, since the VPN server has a different IP address.)
One way to solve this would be to set up some iptables firewall rules on your debian PC to send SSH traffic out the normal network interface, and not through the VPN interface.

Example
I've tried adapting this answer to this situation (assuming your home router is 192.168.0.1, and your debian PC is 192.168.0.20):

Edit /etc/iproute2/rt_tables and add a new table by appending the
  following line:
200 eth-route

You then need to configure your new routing table named eth-route
  with a default gateway and create rules to conditionally send traffic
  to that table.
# Populate secondary routing table
ip route add default via 192.168.0.1 dev eth0 table eth-route
# Anything with this fwmark will use the secondary routing table
ip rule add fwmark 0x1 table eth-route
# Mark these packets so that iproute can route it through eth-route
iptables -A OUTPUT -t mangle -o tun0 -p tcp --dport 22 -j MARK --set-mark 1
# now rewrite the src-addr
iptables -A POSTROUTING -t nat -o eth0 -p tcp --dport 22 -j SNAT --to 192.168.0.20

Making this automatic would involve either adding these commands to the end of /etc/rc.local or making openvpn do this stuff when it starts up.
Cross your fingers...


text:
Q: Inaccurate click to open an app from Launchpad: closes Launchpad I'm surprised how much I use Launchpad after upgrading to Lion both to launch and switch to applications, to the extent that I rarely find myself showing the Dock anymore. I do have one problem, however:
In Launchpad, when one clicks on an application icon, the computer exits the Launchpad screen and launches or switches to the application. When one clicks near but not on an application icon, the computer exits the Launchpad screen and returns to the frontmost application before Launchpad was activated. These are two very different behaviors separated by a small space in terms of pixel targets.
Is there a way make a missed click in Launchpad result in remaining in Launchpad, or to expand the clickable target around the icons?
If the answer is no, that isn't possible, I'd be happy to accept that as correct; I just want to know if there's something I can do to make Launchpad more usable by reducing the wondering after I clicked whether I hit the target or not.

A: The behaviour is intentional, and works much the same within Expose and Mission Control etc.
It's the way out of Launchpad, and if clicking elsewhere other than on an icon doesn't exit you from it, then the only way would be to start a new program or use a keyboard shortcut or mouse gesture.
If you know the gesture or keyboard shortcut that starts it without having to use the dock, then you will likely know how to reverse the action.  But for the (possibly majority) users who happily enter it from the Dock icon this could be very confusing and frustrating as the Dock is removed while Launchpad is displayed, depriving the user of the chance to use it.  The fact that there is a new icon for it suggests that Apple expect people to learn about the feature, and at least start using it, via the dock.
If you find yourself regularly missing the icons, perhaps you could look into scaling them up, that may be a possibility, they are huge on my 24", but I'm not sure if this is user customisable.

A: No, unfortunately this isn't possible, but I agree it is annoying. File a bug if you'd like to see this changed (developer account required, I believe).


text:
Q: Getting Promise in console It is a React (Ts) project and I am getting a Promise<Pending> problem when I try to get request in Axios. Thank you in advance for your help!
import axios from 'axios';

interface song {
  name: string;
}

interface playlist {
  playlistname: string;
  songs: song[];
}

async function getsongs(): Promise<song[]> {
  const url = 'https://be-ask.tanaypratap.repl.co/playlist';
  const response = await axios.get<playlist>(url);
  return response.data.songs;
}

export const finaldata = getsongs();

A: Since getsongs is also async function, it will return a promise, and thus when you print finaldata, it consoles Promise.
Not sure what you are trying to achieve but if you just want to print the data, print after the await in the function getsongs.

A: I believe you should change this line
export const finaldata = getsongs();

to
export const finaldata = await getsongs();

A: Apparently, you are trying to consume the result of the async operation before it's even finished


text:
Q: Websockets - Building a chatting system in Laravel I need to build a conversations (chatting) feature on top of Laravel using Pusher.js.
To do this, I would need websockets for the real time chatting.
However, I am not sure at what would be the correct approach towards solving this in a professional manner.
My current planned approach is:
I plan on having multiple Pusher channels. Each Conversation (DB Model) would have a channel_ID column which would be the Pusher channel name, only accessible by Sender / Recipient. Front-end would be a chatting app with multiple conversations shown. Once user clicks on conversation A, it would subscribe to that conversation's channel_ID (Pusher Channel). Once they click on conversation B, it would unsubscribe from channel A and subscribe to channel B.
My issues in the approach is following:
In Laravel, each Broadcast Event (mine is called message) has a function broadcastOn(). However I do not know how would I make this work for say, 10 000 conversations with all having a different channel name? I don't know if this is optimal, it does not seem too good to me.
I've already Googled for a couple of days and looked up many websocket related guides. Many of them go into detail how to create a public chat with everyone receiving the event, but none of them really go into detail how to create an user-to-user secure chatting feature.


text:
Q: Check if material2 sidenav is open Is there a way to check if the sidenav element is open? According the API documentation, there is a isOpen? parameter, but in my case it throws an exception: EXCEPTION: Error in ./AppComponent class AppComponent - inline template:2:2 caused by: this.sidenav.isOpen is not a function
import { Component, OnInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-sidebar',
  template: `
  <md-sidenav #sidenav mode="side" class="app-sidenav">
      Sidenav
  </md-sidenav>
  `,
  styleUrls: ['./sidebar.component.css'],
  host: {
      '(document:click)': 'onClick($event)',
  }
})
export class SidebarComponent implements OnInit {

  constructor(private sidenav: ElementRef) { }

  ngOnInit() {
  }

  onClick() {
     if (this.sidenav.isOpen()) {
         this.sidenav.close();
     }
  }

}

A: You misunderstand the documentation, isOpen? is an optional parameter of the toggle function.
You can check it's property instead. This works for me:
@ViewChild('sidenav') sidenav: MatSidenav;
onClick() {
  console.log(`isOpen: ${this.sidenav.opened}`);
}

A: You have to use ViewChild to get control over sidenav
@ViewChild('sidenav') sidenav: any;
opened: any = false;
onClick() {
   console.log(this.sidenav.opened);
}

Plunkr


text:
Q: Interpreting the total-variance when the model lies over our data I know that:
$Variance_{Total}=Variance_{Explained} + Variance_{Unexplained}$,
but I am wondering how the $Variance_{Total}$ relates to the $Variance_{Unexplained}$ and the $Variance_{Explained}$ if the $Variance_{Explained}+Variance_{Unexplained}$ is larger than the $Variance_{Total}$, i.e. if the model we're checking against our null-model lies higher than the point we're checking against.

A: The part of unexplained variance is the variance of the residuals ($\hat y - y$) of your regression / total variance - that's $1-R^2$.
If you know for sure that your hypothesis function is relevant and well-fit to your data (eg in the case where you generated the data yourself), the unexplained variance will be noise only.
On your figure, for each point, the explained variance is represented by the distance from $\bar y$ (horizontal line, $\bar y$ is the mean of all data points) to $\hat y$ (the sinusoid). While the unexplained is the distance from $\hat y$ to $y$ (the data point).


text:
Q: QTimer : class has no constructors I just started using Qt and learned of QTimers. Unfortunately, they seem to give an error and I have not seen this error described online yet:
error: C2514: 'QTimer' : class has no constructors.
I have my QTimer declared in the private section of dialog.h :
QTimer* timer;
And I instantiate it as such:
timer = new QTimer(this);

in dialog.cpp.
As this error does not show many results in a google search I am convinced I did something unthinkably dumb, but I have no idea what it is that I did wrong. Could someone please explain to me what it was that I did?

A: So in your .h file you should have
QTimer * timer;

and in your constructor you should have
timer = new QTimer();

and at the top of your header file you should have:
#include <QTimer>

And you shouldn't have any of your own classes named QTimer.
Hope that helps.


text:
Q: Why can I not use text() in a plot? I'm using a plot() in a super simple way:
data <- matrix(c(9,13, 45, 47, 0, 1.5, 1.8, 1,"a", "b", "c", "d"), nrow = 4, ncol = 3)

plot(data[,1], data[,2], main='Ages', xlab='Age', ylab='Height')

index <- 0
for (age in data[,1]){
    index <- index + 1
print(age)
print(data[index,2])
    text(x=age, y=data[index,2], data[index, 3])

}

It draws the plot correctly, but not the text:

What am I doing wrong?
Thanks!

A: The x-range of the plotted data does not include 5.  You would need to extend the range to see the text. (Pretty common source of confusion for base plotting neophytes. I've fallen into it many times.  I think that maybe ggplot2 plotting routines might automagically expand the plotting dimensions.)
A further problem, already mentioned in the comments is that by including a character value in the matrix definition you changed all the digit values to character. Need as.numeric to revert to numeric class (or use a dataframe which would allow varying classes of columns.)
plot(data[,1], data[,2], main='Ages', xlab='Age', ylab='Height', xlim=c(0,50))

index <- 0
for (age in data[,1]){
    index <- index + 1
    print(age)
    print(data[index,2])
    text(x=as.numeric(age)+1, y=as.numeric(data[index,2]), data[index, 3])
    }

Added an offset to the x coordinate for the letters:


text:
Q: How can I make vertical fieldset scroll show up I have a fieldset inside a div that has div inside it, but as the content of div grows it overflows outside of fieldset, the scrollbar on fieldset shows up and works in Firefox but not in Chrome:

.outerdiv-class {
  max-height: 94%;
  position: absolute;
  right: 0;
  min-width: 240px;
}

.fieldset-class {
  overflow-y: auto;
  min-width: 0;
}

.innerdiv-class {
  height: inherit;
}

  <fieldset class="fieldset-class">

      ///content is KendoTreeview that overflows outside from fieldset in
         chrome

  </fieldset>

I don't want to give div a fixed height I want it to inherit from fieldset and outer div height to be responsive to window size.


text:
Q: Converting PHP var_dump array to JSON been looking for a solution. Couldn't find one so my last resort is of course here.
I am using an API from MessageBird. The intention of the code is to spit out a message list.
My Code:
require_once(__DIR__ . '/messagebird/vendor/autoload.php');
$MessageBird = new \MessageBird\Client('XXXXX'); // Set your own API access key here.
try {
$MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 30));
  //var_dump($MessageList);

} catch (\MessageBird\Exceptions\AuthenticateException $e) {
// That means that your accessKey is unknown
  echo 'wrong login';
} catch (\Exception $e) {
  var_dump($e->getMessage());
}

$json = json_decode($MessageList, true);

foreach($json as $item) {
  echo $item['body'];
}

This is the data "var_dump" outputs:
object(MessageBird\Objects\BaseList)#147 (6) {
  ["limit"]=>
  int(30)
  ["offset"]=>
  int(0)
  ["count"]=>
    int(24)
  ["totalCount"]=>
  int(24)
  ["links"]=>
  object(stdClass)#48 (4) {
    ["first"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
    ["previous"]=>
    NULL
    ["next"]=>
    NULL
    ["last"]=>
    string(56) "https://rest.messagebird.com/messages/?offset=0&limit=30"
  }
  ["items"]=>
  array(24) {
    [0]=>
    object(MessageBird\Objects\Message)#148 (16) {
      ["id":protected]=>
      string(32) "XXX"
      ["href":protected]=>
      string(70)
"https://rest.messagebird.com/messages/XXX"
      ["direction"]=>
      string(2) "mt"
      ["type"]=>
      string(3) "sms"
      ["originator"]=>
      string(5) "Test Sender"
      ["body"]=>
      string(416) "Hey Blah Blah Test Message."
      ["reference"]=>

I am unsure how to go about being able to convert the data to JSON so I can use foreach code to separate the records.

A:
I am unsure how to go about being able to convert the data to JSON so I can use foreach code to separate the records.

I think there is a fairly serious misunderstanding here. If you want to foreach over some data, you don't need var_dump or JSON, let alone both - you just need the data.
var_dump is a function for displaying structures to the programmer during debugging; it's not intended to be reversible, or ever used in production code.
JSON is a serialization format for representing data as text so you can transmit it from one program to another. You're not transmitting your object anywhere, so you don't need JSON.
What you want is this:
try
{
    $MessageList = $MessageBird->messages->getList(array ('offset' => 0, 'limit' => 30));
    foreach($MessageList->items as $item) {
      echo $item->body;
    }
}
// Your exception handling here - note that you can't do anything with `$MessageList` if an exception happened; it won't exist.


text:
Q: Why Does the Last Print Statement Not Require The Variable symbols In It? Trying to understand why the print statement of the outer for loop, does not require the variable symbol inside of its parenthesis.  This program ex is from a Python tutorial video by channel Bro Code.  It draws a rectangle based off of a certain amount of rows, columns, and symbol the user chooses.
rows = int(input("How many rows?: "))
columns = int(input("How many columns?: "))
symbol = input("Enter a symbol to use: ")

for i in range(rows):
    for j in range(columns):
        print(symbol, end="")
    print() # <------ (why is symbols not needed in () of print() )

A: That is just for a new line. By default, print()'s end parameter has a default value '\n'.
Simply putting print() will only add a new line.
That is what it is doing here.
for i in range(rows):
    for j in range(columns):
        print(symbol, end="")
    print() # <------ (Adding a new line)

If you don't put print(), all your output will be on 1 line. So prevent that, print is there


text:
Q: Access to Variable Outside of Function Logic    $(window).on("load resize", function () {
      if ($(window).width() < 768) {
          menuHeight = '0px';
          contactHeight = '100%';
      } else {
          menuHeight = ($('#desktop-menu').height() + 'px').toString();
          contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
      }
   });

I want to access these two variables (menuHeight, contactHeight) outside of this function to be used elsewhere. I'm measuring the top height for a modal, but wan't it to be responsive on resize, not just load (it seems a simple If/Else would work in that case.) I might need some schooling on scope here. Thanks!!

A: You define them outside the function. Also, since load happens fairly late in the page load process, you'll want to proactively initialize them, then update them in response to load and resize. That suggests you want a reusable function:
var menuHeight;                            // Defining...
var contactHeight;                         // ...them
grabHeights();                             // Proactive
$(window).on("load resize", grabHeights);  // And on events

function grabHeights() {
    if ($(window).width() < 768) {
        menuHeight = '0px';
        contactHeight = '100%';
    }
    else {
        menuHeight = ($('#desktop-menu').height() + 'px').toString();
        contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
    }
}

If your code isn't already in a scoping function, you probably want to put it in one:
(function() {
    var menuHeight;
    var contactHeight;
    grabHeights();
    $(window).on("load resize", grabHeights);

    function grabHeights() {
        if ($(window).width() < 768) {
            menuHeight = '0px';
            contactHeight = '100%';
        }
        else {
            menuHeight = ($('#desktop-menu').height() + 'px').toString();
            contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
        }
    }
})();

...since globals are a Bad Thing™. :-)
You'll see people telling you to just go ahead and hook the event, then trigger it manually:
$("selector").on("event", function() {
    // ...
}).triger("event");

I'm not a fan. If you need to call a function, just call it.

A: You need to define them before:
var menuHeight = '';
var contactHeight = '';

$(window).on("load resize", function () {
    if ($(window).width() < 768) {
        menuHeight = '0px';
        contactHeight = '100%';
    } else {
        menuHeight = ($('#desktop-menu').height() + 'px').toString();
        contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
    }
});

You can use a function:
function scroll() {
  var menuHeight;
  var contactHeight;

  if ($(window).width() < 768) {
    menuHeight = '0px';
    contactHeight = '100%';
  } else {
    menuHeight = ($('#desktop-menu').height() + 'px').toString();
    contactHeight = ($('.get-in-touch-home').outerHeight() + 'px').toString();
  }

  getHeight(menuHeight,contactHeight)

}

function getHeight(menuHeight,contactHeight) {
  console.log(menuHeight,contactHeight)
}

$(window).scroll(scroll);

For global access (not recommend)
window.menuHeight = '';
window.contactHeight = '';


text:
Q: I wanted to create an array whose members are part of other array .I am not being able to find out the error I tried to create an array whose members are from a strurcture . I tried the following way but it seems there is not the correct way to do! Please suggest me a better way to do ! at least the right way
int vertex [8][3]={{P1.x[0],P1.y[0],P1.z[0]},
                            {P1.x[1],P1.y[1],P1.z[1]},
                            {P1.x[2],P1.y[2],P1.z[2]},
                            {P1.x[3],P1.y[3],P1.z[3]},
                            {P1.x[4],P1.y[4],P1.z[4]},
                            {P1.x[5],P1.y[5],P1.z[5]},
                            {P1.x[6],P1.y[6],P1.z[6]},
                            {P1.x[7],P1.y[7],P1.z[7]}};

A: First of all you should be using P1[1].x instead of P1.x[1] as per P1 struct definition
And although it will work but the efficient way will be to use a for loop.
vertex[8][3]={0}; //Initialized to all 0s
for (i=0;i<8;i++)
{
   vertex[i][0]= P1[i].x;
   vertex[i][1]= P1[i].y;
   vertex[i][2]= P1[i].z;
}

A: Works for gcc -std=c99 -Wall -Wextra -c. (GCC 4.8.2)
Here is my test source:
typedef struct {
    int *x, *y, *z;
} P;

void foo(void) {
    P P1;

    int vertex [8][3]={
        {P1.x[0],P1.y[0],P1.z[0]},
        {P1.x[1],P1.y[1],P1.z[1]},
        {P1.x[2],P1.y[2],P1.z[2]},
        {P1.x[3],P1.y[3],P1.z[3]},
        {P1.x[4],P1.y[4],P1.z[4]},
        {P1.x[5],P1.y[5],P1.z[5]},
        {P1.x[6],P1.y[6],P1.z[6]},
        {P1.x[7],P1.y[7],P1.z[7]}
    };

    (void) vertex[0][0];
}


text:
Q: Laravel multiple route aliases I'm trying to create a route with an array of aliases, so when I call whois or who_is in the url it goes to the same route.
Then I don't need to keep repeating the code every time, changing only the alias.
I tried the code below.
Variables in the routes:
$path = 'App\Modules\Content\Controllers\ContentController@';
$aliases['whois'] = '(quemsomos|who_is|whois)';

Routes:
Route::get('{whois}', array('as' =>'whois', 'uses' => $path.'getWhois'))->where('whois', $aliases['whois']);

this one works as well
Route::get('{whois}', $path.'getWhois')->where('whois', $aliases['whois']);

Typing in the url my_laravel.com/whois or my_laravel.com/who_is or my_laravel.com/quemsomos will send me to $path.'getWhois' (which is correct).
But when I try to call it in the html on blade...
Who we are

The reference link goes to my_laravel.com//%7Bwhois%7D
How could I call route('whois') on my blade.php and make it work like when I type it on the url ?
I would like to use the route function` in my blade, so I can keep a pattern.

A: During route generation using the route function, Laravel expects you to set the value of the route parameter. You are leaving the parameter whois empty so the parameter capturing {whois} will not be replaced and results in the %7B and &7D for the accolades.
So in order to generate a route you will need to define what value you'd like to use for whois; {{ route('whois', ['whois'=>'whois']) }} for instance.


text:
Q: Machine architecture or computer architecture Please what is the difference between machine archictechture and computer architechture . Berkley give a webcast on machine architecture and I am thinking it might be related to computer architecture am I correct.
If not is this same thing about system architechture (i.e machine structure and system architecture)

A: From what I can recall from my GCSE science lessons, a machine is something that takes a force and changes that force's direction or magnitude.
In this context, Machine Architecture would refer to designing force altering mechanisms. This may be relevant to you interests as it could provide insight into design principles.
A computer could be seen as a complex set of interacting machines, if the above definition is correct (I'm recalling from 14 years ago, my memory isn't great).
In fact this definition states that a computer is a machine for automatically permforming calculations.
I'm not familiar with the Berkley webcast you refer to, however "machine" is often used as a colloquialism for computer, and so the webcast could indeed be about computer architecture.
Your best bet is to watch the webcast, you have nothing to lose and you could learn something interesting.

A: There is little difference.
Use of the phrase "machine architecture" implies a reference to a specific computer implementation, such as a desktop computer.
Use of the phrase "computer architecture" implies a general reference to the architecture of computers.
In both, "architecture" refers to the design and structure of a computer system.


text:
Q: Symfony Security bundle not loading (properly) Symfony 3.2.4 - Using the MicroKernelTrait
I have new \Symfony\Bundle\SecurityBundle\SecurityBundle() in my Kernel but no security related services are showing up in cache/appProdProjectContainer.php.
Basically there is no error but when I try to get a service, it tells me that it doesn't exist.
Example:
[Sun Feb 19 15:51:26 2017] PHP Fatal error:  Uncaught exception 'Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException' with message 'You have requested a non-existent service "security.password_encoder".' in ProjectPath/vendor/symfony/symfony/src/Symfony/Component/DependencyInjection/Container.php:298
Also, it doesn't look like it tries to parse the security configuration. If I edit it and make a typo in one of the keys, there is no parsing error.
Yes, I did try to clear all cache, of course! (deleted cache folder altogether)
Update: When I try to call denyAccessUnlessGranted(...) in a Controller, it tells me The SecurityBundle is not registered in your application. But I can clearly see it loaded!!!
Anyone has any idea?


text:
Q: Javascript: HackerRank function within a function is not a function This is one of those job interview tests on HackerRank that I am embarrassed to say I didn't complete within the allotted 20 minutes, and it's driving me nuts. Basically, you're given the following:
function myList() {
    // write code here
}

function main() {
    // You can't edit this function. This is just pseudo, from what I can remember
    const obj = myList();
    if (operation === "add")
        obj.add(item);
    else if (operation === "remove")
        obj.remove(item);
    else
        obj.getList();
    // Some more stuff here
}

So my first train of thought was to write the following inside myList():
let objList = [];
function add(item) {
    objList.add(item)
}
// etc., etc.
return {add, remove, getList};

Needless to say, the above didn't work, with the error: obj.add is not a function, in the main function.
I tried experimenting with this and the returns (only returning add, with or without {}), but didn't really get anywhere. What could I have done to get this working?

A: For obj, inside myList() you could have run a closure, that is a self invoking function returning, in this case, an object with your k:v exports, but with private access to the context of the now expired anonymous caller. With "const add = function" etc statements you can define values for your exports, while the objList goes in the private context.

A: As the answer from Attersson already suggested, you could use a closure inside the myList function. This would allow to only expose the three methods add, remove and getList while the original list cannot be accessed. Here is an example:
function myList() {
  return (() => {
    const obj = {itemList: []}
    const add = (item) => obj.itemList.push(item)
    const remove = (item) => obj.itemList = obj.itemList.filter(i => i !== item)
    const getList = () => obj.itemList
    return {add, remove, getList}
  })()
}


text:
Q: MS Excel VBA - Copying SpecialCells while keeping the destination formatting I would like to copy these special cells to a destination, while keeping the destination's formatting. I'm thinking I have to put .values somewhere in the lines. The code is as follows:
GRBReportSheet.Range("C" & GRBReportSheetFR & ":E" & GRBReportSheetLR).SpecialCells(xlCellTypeVisible).Copy Destination:=GRB.Range("C30")
GRBReportSheet.Range("F" & GRBReportSheetFR & ":J" & GRBReportSheetLR).SpecialCells(xlCellTypeVisible).Copy Destination:=GRB.Range("H30")

Thank you in advance for your time!

A: Try this.
GRBReportSheet.Range("C" & GRBReportSheetFR & ":E" & GRBReportSheetLR).SpecialCells(xlCellTypeVisible).Copy
GRB.Range("C30").PasteSpecial xlValues

GRBReportSheet.Range("F" & GRBReportSheetFR & ":J" & GRBReportSheetLR).SpecialCells(xlCellTypeVisible).Copy
GRB.Range("H30").PasteSpecial xlValues


text:
Q: Problema com retorno de SQL Tenho uma tabela que liga duas outras tabelas. "Solicitação" ela liga "Clientes" e "Solitação_descricao"
Possui a colunas de ligação cliente_id e solicitacao_descricao_id, preciso retornar os clientes que possuem mais de uma solicitação especifica da tabela conforme mostra na figura abaixo.

Eu preciso criar um sql que eu coloque "Where solicitacao_descricao_id = 19 and solicitacao_descricao_id = 8 and solicitacao_descricao_id = 13" e me retorne esse cliente 1. Mas não sei como fazer alguem pode me ajudar? Pq eu quero os clientes que possuem essas 3 solicitacoes juntas. Se eu uso o "OR" me retorna vários que não preciso e o AND não retorna nada!

A: Considerando a estrutura de sua tabela, para saber os IDs de clientes que aparecem mais de uma vez em sua tabela "solicitação", você poderia fazer da seguinte forma
select cliente_id from solicitacao group by cliente_id HAVING count(*) > 1

Você pode usar esta query como base para retornar os nomes dos clientes nesta situação fazendo desta forma:
select * from clientes where id in (select cliente_id from solicitacao group by cliente_id HAVING count(*) > 1)

Se você quer ver os clientes que aparecem mais de uma vez e as suas solicitações, pode tentar fazer assim:
select * from clientes, solicitacao where id = cliente_id and id in (select cliente_id from solicitacao group by cliente_id HAVING count(*) > 1)


text:
Q: chrome.storage.sync.get not functioning as expected with key-value pairs According to the documentation on Chrome Storage:
https://developer.chrome.com/extensions/storage
This is the proper way to set and get key-value pairs in synchronized storage:

   chrome.storage.sync.set({key: value}, function() {
     console.log('Value is set to ' + value);
   });

   chrome.storage.sync.get(['key'], function(result) {
     console.log('Value currently is ' + result.key);
   });

I have replicated this syntax for my code, but the result.key always ends up as undefined rather than returning the value for the key I specify.
I'm gathering the data for the key-value pair from a context menu, and that works properly. The log within the set operation shows the correct data, so I assume the set itself is working properly as well (but perhaps this is an incorrect assumption?).
For the get operation, I've temporarily forced a variable to 'data1' simply because that is a consistent string that I can select in the context menu to set for testing. But when I attempt to retrieve the value associated with that key, I get undefined.
let repUserSelected = item.selectionText;
let bColor = item.menuItemId;
chrome.storage.sync.set({repUserSelected: bColor}, function() {
          console.log(repUserSelected + ' is set to ' + bColor);
        });
//test - data1 should be a variable in the final code
let repUserTest = 'data1';
chrome.storage.sync.get(['repUserTest'], function(result) {
   console.log('Color for ' + repUserTest + ' currently is ' + result.repUserTest);
        });
});

Here is the console output I am getting:
data1 is set to #ff786f                 background.js:33
Color for data1 currently is undefined  background.js:38
data2 is set to #a0ffbd                 background.js:33
Color for data1 currently is undefined  background.js:38

I have attempted removing the quotes from repUserTest since I didn't want that to evaluate as an actual string in the get, but that didn't change anything. I don't feel like this is an asynchronous issue requiring a callback, because the problem persists even after subsequent sets are performed. But there must be something I'm not understanding about what is happening here, so any help would be appreciated.


text:
Q: android fragment getArguments returns null in oncreateView() I have two fragments and FilterFragment and LocationListFragment. when I am switching to LocationListFragment.java I am getting values in getArguments() and from LocationListFragment.java to FilterFragment.java getting null values by calling getArgument(); here is the details
In FilterFargment.java code is here for set values:
  LocationListFragment locationListFragment = new LocationListFragment();
             bundle = new Bundle();
            Log.e("",""+locationList.getLocationListFilter().size());
            bundle.putParcelable(Constant.LOCATION_LIST_FILTER, locationList);
            bundle.putString(Constant.FROM_DATE_FILTER, textView_time_from.getText().toString());
            locationListFragment.setArguments(bundle);
            ((DashbordActivity) getActivity()).switchFragment(locationListFragment, true);

In LocationListFragment.java (getting values)
 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle args = getArguments();
    if (args != null) {
        locationList = args.getParcelable(Constant.LOCATION_LIST_FILTER);
        getFromDate = args.getString(Constant.FROM_DATE_FILTER);}}

And here from LocationListFragment on button click send data to FilterFragment sending new values with bundle:
FilterFragment filterFragment =new FilterFragment();//.newInstance(getFromDate, getEndDate, getLocation, getCategories);
    Bundle bundle = new Bundle();
    bundle.putString(Constant.FROM_DATE_FILTER, getFromDate);
    bundle.putString(Constant.WHERE_FILTER, getLocation);
    filterFragment.setArguments(bundle);
    ((DashbordActivity) getActivity()).switchFragment(filterFragment, true);

and in FilterFragment.java while returning back getting null value for getArguments(); code is here:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_filter, container, false);
    Log.e("FilterFragment", "oncreateview");

    Bundle args = getArguments();
    Log.e("getArguments", "" + getArguments());//getting null here

Also, I have used this method for switching fragment,
    public void switchFragment(BaseFragment fragment, boolean keep) {
    FragmentManager manager = getSupportFragmentManager();

    boolean fragmentPopped = manager.popBackStackImmediate(fragment.getClass().getSimpleName(), 0);

    if (!fragmentPopped && manager.findFragmentByTag(fragment.getClass().getSimpleName()) == null) { //fragment not in back stack, create it.

        FragmentTransaction tr = manager.beginTransaction();

        tr.replace(R.id.container, fragment, fragment.getClass().getSimpleName());

        if (keep) {
            tr.addToBackStack(fragment.getClass().getSimpleName());
       Log.e("keep", "BaseAct:" + keep);
        }
        tr.commit();
    }
}

Can you tell me what I am missing? Any help will be appreciated.