text:
Q: Htaccess auth, based on server, not client information In a current project we have separate development and production. The code on both is in single SVN repository.
The problem lies in the access to the development environment from outside. Let's say we have two separate servers for prod and dev:
1.2.3.4 -> production
5.6.7.8 -> development

The idea is to use the same .htaccess with Auth on both servers, but the behavior must be:

*

*On Development server, the user must Auth himself before accessing the site

*On Production server, the user has full access, without Auth.

It should be something like this (pseudo code):
IF $SERVER_IP == 5.6.7.8 THEN
    require_auth
ELSE
    do_not_require_auth

We are trying to achieve this with the least possible amount of additional modules, but sadly we couldn't find any information on how to do a condition in .htaccess, based on the server information.
Is it even possible?

A: you should add these to your .htaccess authentication/authorization directives.
setenvif Server_Addr=1.2.3.4 okpublic
allow from env=okpublic
require valid-user
satisfy any

if the server address is 1.2.3.4 then we set an environment variable that we will use on the second line to allow access to anyone.
if server address is not 1.2.3.4 then users must authenticate.
if any of these 2 rules are satisfied then access is granted.
what I did is weird but oh well, if this is what you want :)
another solution, much more simpler would be to ignore the .htaccess file when doing svn update on the production server, using svn propedit svn:ignore. if you need to have different .htaccess file on prod and dev then maybe you want to look into branching, merging, etc. or maybe the multi-purpose .htaccess file is just better. I felt like mentioning svn controls as well.


text:
Q: Tailwindcss 100% dynamic width search box in the navbar Need some help with TailwindCSS making search box 100% resizable,
but it does not minimize after certain point

After that as you can see in the below image, GROW class in the parent FLEX paints over other UI elements even though there are more width of the input element that could be minimized.

TailwindCSS playground: https://play.tailwindcss.com/olAP85kNj5
What I am trying to achieve ideally, is search box to minimize until at a size of search icon, based on available space.
But I was not able to make it work
I tried setting max-width for different screen sizes but that makes it super hard to maintain because it needs to be adjusted all the time I add or remove UI elements.

        Authors

        Idea

        Standings

      <input id="search" type="search" placeholder="Search" class="form-input w-full appearance-none rounded border border-gray-400 bg-white py-1 pl-8 text-sm text-gray-500 placeholder-gray-400 focus:border-cyan-600 focus:outline-none xxs:pr-4" />

       [ 11 ]

      <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 508 508" style="enable-background:new 0 0 508 508" xml:space="preserve">
        <circle style="fill:#84dbff" cx="254" cy="254" r="254" />
        <path style="fill:#2b3b4e" d="M455 409a253 253 0 0 1-402 0l11-69 136-71v2l-36 39 22 16-27 15 95 149 95-149-27-15 22-16-36-39v-1l136 70 11 69z" />
        <path style="fill:#324a5e" d="m349 341-95 149 39-168 3 7s14-29 12-57l36 38-22 17 27 14zM159 341l27-15-22-16 36-39c-2 29 12 58 12 58l3-7 39 168-95-149z" />
        <path style="fill:#e6e9ee" d="m293 322-39 168-39-168c13-24 39-21 39-21s26-3 39 21z" />
        <path style="fill:#f1543f" d="M254 301zM278 307l-9 19h-30l-9-19c12-7 24-5 24-5s12-2 24 5z" />
        <path style="fill:#ff7058" d="m274 402-20 88-20-88 5-76h30z" />
        <path style="fill:#f9b54c" d="M296 244c-2 9-9 28-42 57-28-27-38-45-41-55 11 15 25 25 41 25s30-11 42-27z" />
        <path style="fill:#fff" d="M296 329c-12-31-42-28-42-28 32-29 40-47 42-56l2-3c23 32-2 87-2 87zM254 301s-30-3-42 28c0 0-26-56-2-87l3 4c3 10 13 28 41 55z" />
        <path style="fill:#ffd05b" d="M326 201c-4 6-9 10-13 11-12 32-34 59-59 59s-47-27-59-59c-4-1-9-5-13-11-6-9-6-20 0-24l2-1 5 19s5 10 7 18c-1-9-1-29 2-33 0 0 14-25 4-46 0 0 2-32 38-18 0 0 6 2 14 2l14-2c36-14 38 18 38 18-10 22 4 46 4 46 3 4 2 24 2 34 1-9 6-18 6-18 3-6 4-12 5-19l2 1c6 3 6 14 1 23z" />
        <path style="fill:#324a5e" d="M330 103c-2-3-12 2-12 2 2-7-3-23-3-23-1 5-8 6-8 6 1-5-5-19-5-19 1 6-8 13-8 13 1-6-11-24-11-24 2 3 1 11 1 11-4-9-17-18-17-18 0 2-1 5-3 7-3-6-9-9-10-10-2 0-8 4-11 10l-3-7s-12 9-17 18c0 0-1-8 1-11 0 0-12 18-10 24 0 0-10-7-8-13 0 0-7 14-6 19 0 0-6-1-8-6 0 0-4 16-3 23 0 0-10-6-12-2 0 0 9 9 5 18 0 0-4 49 6 74 0 0 6 10 7 18-1-9-1-29 2-33 0 0 14-25 4-46 0 0 2-32 38-18l14 2 14-2c37-14 39 18 39 18-10 22 4 46 4 46 3 4 2 24 2 34 1-9 6-18 6-18 11-26 7-74 7-74-4-9 5-19 5-19z" />
      </svg>

John Doe

          1800

•

ONLINE

A: You can solve this with theflex-grow, flex-shrink and flex-basic CSS properties or the shorthand  flex.

The flex CSS shorthand property sets how a flex item will grow or shrink to fit the space available in its flex container. MDN, Tailwind

In main section we can keep the width with the Tailwind property flex-[1_0_auto] if we have a small screens and remove it with xs:flex-none when the screen is large.

        Authors

        Idea

        Standings

      <input id="search" type="search" placeholder="Search" class="form-input w-full appearance-none rounded border border-gray-400 bg-white py-1 pl-8 text-sm text-gray-500 placeholder-gray-400 focus:border-cyan-600 focus:outline-none xxs:pr-4" />

       [ 11 ]

      <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 508 508" style="enable-background: new 0 0 508 508" xml:space="preserve">
        <circle style="fill: #84dbff" cx="254" cy="254" r="254" />
        <path style="fill: #2b3b4e" d="M455 409a253 253 0 0 1-402 0l11-69 136-71v2l-36 39 22 16-27 15 95 149 95-149-27-15 22-16-36-39v-1l136 70 11 69z"
        />
        <path style="fill: #324a5e" d="m349 341-95 149 39-168 3 7s14-29 12-57l36 38-22 17 27 14zM159 341l27-15-22-16 36-39c-2 29 12 58 12 58l3-7 39 168-95-149z"
        />
        <path style="fill: #e6e9ee" d="m293 322-39 168-39-168c13-24 39-21 39-21s26-3 39 21z" />
        <path style="fill: #f1543f" d="M254 301zM278 307l-9 19h-30l-9-19c12-7 24-5 24-5s12-2 24 5z"
        />
        <path style="fill: #ff7058" d="m274 402-20 88-20-88 5-76h30z" />
        <path style="fill: #f9b54c" d="M296 244c-2 9-9 28-42 57-28-27-38-45-41-55 11 15 25 25 41 25s30-11 42-27z"
        />
        <path style="fill: #fff" d="M296 329c-12-31-42-28-42-28 32-29 40-47 42-56l2-3c23 32-2 87-2 87zM254 301s-30-3-42 28c0 0-26-56-2-87l3 4c3 10 13 28 41 55z"
        />
        <path style="fill: #ffd05b" d="M326 201c-4 6-9 10-13 11-12 32-34 59-59 59s-47-27-59-59c-4-1-9-5-13-11-6-9-6-20 0-24l2-1 5 19s5 10 7 18c-1-9-1-29 2-33 0 0 14-25 4-46 0 0 2-32 38-18 0 0 6 2 14 2l14-2c36-14 38 18 38 18-10 22 4 46 4 46 3 4 2 24 2 34 1-9 6-18 6-18 3-6 4-12 5-19l2 1c6 3 6 14 1 23z"
        />
        <path style="fill: #324a5e" d="M330 103c-2-3-12 2-12 2 2-7-3-23-3-23-1 5-8 6-8 6 1-5-5-19-5-19 1 6-8 13-8 13 1-6-11-24-11-24 2 3 1 11 1 11-4-9-17-18-17-18 0 2-1 5-3 7-3-6-9-9-10-10-2 0-8 4-11 10l-3-7s-12 9-17 18c0 0-1-8 1-11 0 0-12 18-10 24 0 0-10-7-8-13 0 0-7 14-6 19 0 0-6-1-8-6 0 0-4 16-3 23 0 0-10-6-12-2 0 0 9 9 5 18 0 0-4 49 6 74 0 0 6 10 7 18-1-9-1-29 2-33 0 0 14-25 4-46 0 0 2-32 38-18l14 2 14-2c37-14 39 18 39 18-10 22 4 46 4 46 3 4 2 24 2 34 1-9 6-18 6-18 11-26 7-74 7-74-4-9 5-19 5-19z"
        />
      </svg>

John Doe

          1800

•

ONLINE

redpajama_set_name: RedPajamaStackExchange


text:
Q: python 3, differences between two strings I'd like to record the location of differences from both strings in a list (to remove them) ... preferably recording the highest separation point for each section, as these areas will have dynamic content.
Compare these
total chars 178. Two unique sections
t1 = 'WhereTisthetotalnumberofght5y5wsjhhhhjhkmhm Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentresultsduetodifferinglevelsofapxxxxxxxproximation,although'

and
total chars 211. Two unique sections
t2 = 'WhereTisthetotalnumberofdofodfgjnjndfgu><rgregw><sssssuguyguiygis>gggs<GS,Gs Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentrexxxxxxxsultsduetodifferinglevelsofapproximation,although'

I know difflib can do this but the output is bad.
I'd like to store (in a list) the char positions, perferably the larger seperation values.
pattern location
t1 = 'WhereTisthetotalnumberof  24  ght5y5wsjhhhhjhkmhm  43  Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentresultsduetodifferinglevelsofap  151  xxxxxxx  158  proximation,although'
t2 = 'WhereTisthetotalnumberof  24  dofodfgjnjndfgu><rgregw><sssssuguyguiygis>gggs<GS,Gs  76  Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentre  155  xxxxxxx  162  sultsduetodifferinglevelsofapproximation,although'

output:
output list = [24, 76, 151, 162]

Update
Response post @Olivier
position of all Y's seperated by ***
t1
WhereTisthetotalnumberofght5***y***5wsjhhhhjhkmhm Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentresultsduetodifferinglevelsofapxxxxxxxproximation,although

t2 WhereTisthetotalnumberofdofodfgjnjndfgu><rgregw><sssssugu***y***gui***y***gis>gggs<GS,Gs Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentrexxxxxxxsultsduetodifferinglevelsofapproximation,although

output after matcher.get_matching_blocks()
and string = ''.join([t1[a:a+n] for a, _, n in blocks])
WhereTisthetotalnumberof***y*** Thethreemethodsthatreturntheratioofmatchingtototalcharacterscangivedifferentresultsduetodifferinglevelsofapproximation,although

A: Using difflib is probably your best bet as you are unlikely to come up with a more efficient solution than the algorithms it provides. What you want is to use SequenceMatcher.get_matching_blocks. Here is what it will output according to the doc.

Return list of triples describing matching subsequences. Each triple
  is of the form (i, j, n), and means that a[i:i+n] == b[j:j+n]. The
  triples are monotonically increasing in i and j.

Here is a way you could use this to reconstruct a string from which you removed the delta.
from difflib import SequenceMatcher

x = "abc_def"
y = "abc--ef"

matcher = SequenceMatcher(None, x, y)
blocks = matcher.get_matching_blocks()

# blocks: [Match(a=0, b=0, size=4), Match(a=5, b=5, size=2), Match(a=7, b=7, size=0)]

string = ''.join([x[a:a+n] for a, _, n in blocks])

# string: "abcef"

Edit: It was also pointed out that in a case where you had two strings like such.
t1 = 'WordWordaayaaWordWord'
t2 = 'WordWordbbbybWordWord'

Then the above code would return 'WordWordyWordWord. This is because get_matching_blocks will catch that 'y' that is present in both strings between the expected blocks. A solution around this is to filter the returned blocks by length.
string = ''.join([x[a:a+n] for a, _, n in blocks if n > 1])

If you want more complex analysis of the returned blocks you could also do the following.
def block_filter(substring):
    """Outputs True if the substring is to be merged, False otherwise"""
    ...

string = ''.join([x[a:a+n] for a, _, n in blocks if block_filter(x[a:a+n])])


text:
Q: How do you integrate a Vue.js package (like vodal) into Laravel? I have an empty Laravel project and have been trying to install vodal
(https://github.com/chenjiahan/vodal) into it, with no luck.
I know the basics of vue.js but am still a beginner and have never used a Vue.js package in my Laravel app before.

Note: I was able to download https://github.com/chenjiahan/vodal and get it running as a standalone. The challenge is getting it integrated into a new Laravel 5.8 project.

After running:
npm i -S vodal

Where does this code go in my laravel app? What should go in:

*

*app.js

*a blade.php view file

*a new Vue component

*any other location?

How do I get this Vodal (or for that matter, any vue.js) package to work with Laravel? I've been struggling for hours on end, and ANY help would be appreciated.
<vodal :show="show" animation="rotate" @hide="show = false">

A vue modal with animations.

</vodal>
import Vue from 'vue';
import Vodal from 'vodal';

Vue.component(Vodal.name, Vodal);

export default {
  name: 'app',

  data() {
    return {
      show: false
    }
  }
}
// include animation styles
@import "vodal/common.css";
@import "vodal/rotate.css";

A: In laravel first open terminal and install npm with the command npm install after that you can see a new folder in your project named as node_modules. all your packages code is inside this folder.
Now simply run your command for vodal like npm i -S vodal
now you can simply import this package into your app.js file as you did.
Run npm run watch for development mode which will import all vodal code from node_modules folder into your app.js file which is inside your public directory.
Update
I saw your repository and I downloaded it and edit some of your files. you were doing totally wrong.
I suggest you to learn vuejs first rather than getting deep into it.
the problem was you calling it in vue, not in the vue component so why you give the following code.
export default {
    components: {
        Vodal
    },
    data() {
        return {
            show: false
        }
    }
}

we do this in vue component, not in vue.
in data, we return only in vue component and the official documentation of vodal, they also give an example of using it in vue component.
and you not using it in vue component so simply did this in vue like below
const app = new Vue({
    el: '#app',
    data:{
        show: false
    }
});

So Now Your CSS.
so for including css. i simply import this in app.scss file like below.
@import "~vodal/common.css";
@import "~vodal/rotate.css";

now the final part and your biggest mistake is.
why you don't include app.js file in welcome.blade file. All your code is written in app.js file and you are not including it. so i simply include it in welcome.blade file like below

<link rel="stylesheet" href="{{ asset('css/app.css') }}">

after all, just run npm run watch
so now the main part you need to show:true for show modal. by default is false so it will not show you.
am making a click event for the show , so you understand how it's all going to work. and ill share files with the link in the comment.


text:
Q: Matrix-like printing of 2D arrays in Python Say I have a matrix in a numpy array in Python
In [3]: my_matrix
Out[3]:
array([[ 2.,  2.,  2.,  2.,  2.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  2.,  2.,  2.,  2.,  0.,  0.,  0.,
         0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  2.,  2.,  2.,
         2.,  2.,  2.,  2.,  2.]])

Is there a way to have Python/IPython print my array as:
[ 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2;
  0 0 0 0 0 0 2 2 2 2 0 0 0 0 0 0 0 0;
  0 0 0 0 0 0 0 0 0 0 2 2 2 2 2 2 2 2 ]

? (~ similar to the way MATLAB does it)
Also, I have noticed that IPython does not use the full width of my terminal when printing numpy arrays. Other functions do (e.g. pprint.pprint). How can I change that?

A: Use numpy.set_printoptions. For increasing the line width:
np.set_printoptions(linewidth=150)

Replace 150 by whatever you need. Now, to print as you asked (I guess it means without the decimal point):
print my_matrix.astype('i')

If you have floating point values you can also control the precision for printouts with the option precision:
np.set_printoptions(precision=3)


text:
Q: How to center a Navbar that is 90% of the screen I want to center the navbar as a whole, not the contents of the nav bar.
This is the CSS and HTML for my navbar.

.navbar {
  border-radius: 10px 10px 30px 30px;
  background: #3CE18F;
  overflow: visible;
  position: fixed;
  bottom: 3%;
  width: 90%;
}

    Fixed bottom

I've tried centering using css & using class names to center but it always seems to left align. I want it perfectly centered.
See attached image for what's going wrong.

As you can see the nav bar is forced left.
I don't want to use padding as that can vary for different screen sizes.
Any help will be appreciated.

A: Wrap you nav inside a div and add property justify-content to align it horizonatally:

    Fixed bottom

.wrapper {
    display: flex;
    justify-content: center;
}

A: Add display: block and margin: auto to the navbar. Add display: flex to the parent element of the navbar. Should work.


text:
Q: Setting a member variable to an object outside the class I want to track a variable in my class that was created outside the scope. In C++ i'd just pass a pointer like this.
class Camera
{
    Player* player;
    Position pos;

    void setFollow(Player* pl) { pl = player; }
    void update() { pos = pl->getPos(); }
}

int Main()
{
    Camera* camera = new Camera();

    Player* player = new Player();

    camera->setFollow(player);
}

In C# I tried to pass by reference but it didnt seem to work.
public class Game1 : Microsoft.Xna.Framework.Game
{
    Camera cam = new Camera();
    Player player = new Player();

    cam.setFollow(ref player);  // <-- by reference
}

This is just a shortened version of my actual code.
Thanks for any help.
EDIT: Thanks to all for the information.

A: In C#, object (class) variables are implicitly pointers.  So, if your class Camera has a field p of type Player, setting cam.p = player in your code would leave both references pointing to the same instance.  There's generally no need to use ref unless you're passing value types (int, float, structs, etc) by reference.

A: There should be no need to use the ref keyword here as objects are always passed by reference in C#.  The ref keyword in C# is typically used more like a pointer-to-a-pointer (**) would be used in C/C++

A: Player itself is a reference type why are you using ref.
You can read more about ref here
http://msdn.microsoft.com/en-us/library/14akc2c7.aspx

A: Classes are always passed by reference so you don't need the ref bit that you are trying to do
simply
cam.setFollow(player);

A: ref keyword in C# has a really bad name. It doesn't mean you pass by reference! It should have been named alias, because this is the good word that describes the semantic of ref.
// here I assign a reference(another bad name :) )
// you can also call it Garbage Collector Handler
// of type Player with a new object
Player player = new Player();
// ref means that player is the same thing that parameter pl of setFollow
cam.setFollow(ref player);

More details


text:
Q: Real Analysis - Manipulating an inequality I am trying to get the following into a nice expression in terms of $n$ by using inequalities.
$$\sup_{x \in [-1,1]}\left| \sqrt{x^2+\frac1n \cos^2(nx)} - |x| \right| \leq \sup_{x \in [-1,1]}\left| \sqrt{x^2+\frac1n} - |x| \right|$$
and now I am stuck as to what to do next!

A: By symmetry the last expression equals $$\sup_{x \in [0,1]} \left( \sqrt{ x^2 + \frac 1n} - x\right).$$
Let $\phi(x) = \sqrt{x^2 + 1/n} - x$. Then $$\phi'(x) = \frac{x}{\sqrt{x^2 + \frac 1n}}- 1 < 0$$
because $\sqrt{x^2 + \frac 1n} > x$ for all $x$.  Thus $\phi$ is decreasing on $[0,1]$ so its supremum on this interval is attained at $x=0$. It follows that$$\sup_{x \in [0,1]} \left( \sqrt{ x^2 + \frac 1n} - x\right) = \frac{1}{\sqrt n}.$$

Alternatively, for all $x \ge 0$ you have
$$\sqrt{x^2 + \frac 1n} - x = \frac{x^2 + \frac 1n - x^2}{\sqrt{x^2 + \frac 1n} + x} = \frac{\frac 1n}{\sqrt{x^2 + \frac 1n} + x} \le \frac{\frac 1n}{\frac 1{\sqrt n}} = \frac{1}{\sqrt n}.$$


text:
Q: How to construct Cayley Table when only few entries are known? Let $A$ be a set consisting of 25 elements, that is, $a$, $b$, $c$, $d$ and so on..., and $*$ be a binary operation defined on $A$.
If I know the value of only a few compositions, like for instance $a*b = f$ and $c*d = k$, then how can I construct a composition table for all 25 elements using a For loop and such that Mathematica compute the rest of the compositions using the known compositions?

A: If all you're looking for is to display the Cayley table and do some of those replacements, this is straightforward. We will use Outer as suggested by J.M.. It is the natural way to construct Cayley tables.
As an example, let's take as our group (I'm assuming a group, of course, but I guess you might not be dealing with a group; perhaps a monoid or even some weaker structure; anyway),
group = g /@ Range[0, 4];

Then, we construct the table as follows:
cayleyTable[group_] := Outer[NonCommutativeMultiply, group, group]

We are using the built-in function NonCommutativeMultiply, which can be written using Infix notation with **. Finally, we display the table nicely as follows:
TableForm[cayleyTable[group], TableHeadings -> {group, group}]

Now, if we have some known compositions, let's combine them into a list of composition rules:
compositionRules = {g[0] ** g[0] -> g[0], g[0]**g[1] -> g[1], g[2]**g[4] :> g[1]};

Then,
TableForm[cayleyTable[group] /. compositionRules, TableHeadings -> {group, group}]

We can also make replacements more general. Recognizing that the only group of order 5 is the cyclic group of order 5, let's make the following rule:
cyclicGroupRule = {g[a_] ** g[b_] :> g[Mod[a + b, 5]]};

Then,
TableForm[cayleyTable[group] /. compositionRules, TableHeadings -> {group, group}]


text:
Q: How to make 2 dl's go side by side? I'm trying to get my stats class dl's to go side by side, but they just won't.
I've tried display: inline-block but it didn't seem to work either.
The issue: http://prntscr.com/7pdusz
.stats {
    display: inline-block;
    float: right;
    top: 50%;
    margin-top: -20px;
}
.stats dl {
    display: inline-block;
    float: left;
    min-width: 80px;
    padding: 0 6px;
    text-align: center;
    text-transform: uppercase;
    font-size: 11px;
    margin: 0;
}
.stats dd {
    display: block;
    color: rgb(184,184,184);
    font-size: 18px;
}
.stats dt {
    display: block;
    color: rgb(144,144,144);
}

and html is here:

2

Topics

2

Replies

A: Use float:left;

.stats {
    display: inline-block;
    float: right;
    top: 50%;
    margin-top: -20px;
}
.stats dl {
    display: inline-block;
    float: left;
    min-width: 80px;
    padding: 0 6px;
    text-align: center;
    text-transform: uppercase;
    font-size: 11px;
    margin: 0;
}
.stats dd {
    display: block;
    color: rgb(184,184,184);
    font-size: 18px;
}
.stats dt {
    display: block;
    color: rgb(144,144,144);
}

dl {
  float:left;
  margin: 4px;
}

2

Topics

2

Replies

A: Wrap your code inside a
 and remove margin-top from the dl class.

.stats {
  display: inline-block;
  float: right;
  top: 50%;
}
.stats dl {
  display: inline-block;
  float: left;
  min-width: 80px;
  padding: 0 6px;
  text-align: center;
  text-transform: uppercase;
  font-size: 11px;
  margin: 0;
}
.stats dd {
  display: block;
  color: rgb(184, 184, 184);
  font-size: 18px;
}
.stats dt {
  display: block;
  color: rgb(144, 144, 144);
}

2

Topics

2

Replies


text:
Q: Hibernate Multiple Row Set Differing In only one column? How do I represent similar multiple row data in one hibernate pojo?
For example lets have a table say
PKEY  | REFS | UNIQUEID

Now I envision a scenario in which I expect multiple REFS for same set of {PKEY, UNIQUEID} values. This will cause multiple rows in the database with same PKEY and UNIQUEID but differing REFS.
In such scenario how do I map that table to my hibernate pojo. Will the following work?
@Entity
@Table(name = "MYTABLE")
public class TablePojo
{
    @Id
    @Column(name = "PKEY")
    int pkey;

    @Column(name = "REFS")
    List<String> refsList;

    @Column(name = "USERID")
    Long userId;

       ..........
       ..........
       ..........
};


text:
Q: Joining multiple resultsets I have four Select queries for four different tables, each extracting only one record. For example:
Select * from table where col1 = 'something'

gives one row having 3 columns.
The second select query also gives one record having two columns(fields). Same for third and fourth select query.
I want to combine all four ResultSets into one having one row. How is it possible?
I will write the queries for you
1st one
Select Top 1 column1,column2 from table 1 where column 1 = 'something'
and col1 = (Select max(col1) where column 1 = 'something')

2nd query
Select Top 1 column1 , column3 from table 2 where column 1 = 'something'
and column3 = (Select max(column3) where column 1 = 'something')

3rd query use result obtained from query 2
Select column4 ,column3 from table 3
where column3 = (obtained from 2nd query) (there is only one row)

4th
Select column5 from table 4
where column3 = (obtained from 2nd query) (there is only one row)

this means I have to join 2nd ,3rd ,4th query then resultant set int 1st
I can't use union since column are different
so only problem is with joining the result set
I hope it explains
Result set
Sql query1
column1 column2
aaa              bbb
Sql query 2
column1  column3
aaa              cccc
Sql query 3
column3 column4
cccc           dddd
sql query 4
column3  column5
cccc           eeee
The resultant set
coulumn1 column2 column3 column4 column5
aaa      bbb     cccc    dddd    eeee
hope the reultset explains everything

A: Make the column number and types the same for all queries by adding columns (even if you don't need them):
Select column4, column3 from table 3
where column3 = ...

Select column5, column3 from table 4
where column3 = ...

As an aside, it looks likely that your query can be simplified considerably. It's quite messy at the moment.
Perhaps you should re-phrase your question to explain in English what you are trying to do and what your table schema is, and let us suggest the whole query.

A: create table table1(c1 varchar(10), c2 varchar(10), c3 varchar(10), c4 varchar(10), c5 varchar(10));

create table table2(c1 varchar(10), c2 varchar(10), c3 varchar(10), c4 varchar(10), c5 varchar(10));

create table table3(c1 varchar(10), c2 varchar(10), c3 varchar(10), c4 varchar(10), c5 varchar(10));

create table table4(c1 varchar(10), c2 varchar(10), c3 varchar(10), c4 varchar(10), c5 varchar(10));

insert into table1 values (1,2,3,4,5);

insert into table2 values (1,5,3,7,8);

insert into table3 values (1,15,3,17,18);

insert into table4 values (1,22,3,24,25);

  with max3 as
  (select c1, max(c3) c3 from table2 where table2.c1 = 1 group by c1)
  select table1.c1, table1.c2, max3.c3, table3.c4, table4.c5
    from table1
    join max3
      on max3.c1 = table1.c1
    join table3
      on table3.c3 = max3.c3
    join table4
      on table4.c3 = max3.c3
   where table1.c1 = 1;

output
c1 c2 c3 c4 c5
 1  2  3 17 25


text:
Q: Number of Extra Samples is 0 for 32 bits/pixel image Following is the status of an image that I have:
ExifTool Version Number         : 12.42
File Type                       : TIFF
MIME Type                       : image/tiff
Exif Byte Order                 : Little-endian (Intel, II)
Subfile Type                    : Full-resolution image
Bits Per Sample                 : 8 8 8 8
Compression                     : LZW
Photometric Interpretation      : RGB
Samples Per Pixel               : 4
Rows Per Strip                  : 1
Planar Configuration            : Chunky
Predictor                       : Horizontal differencing

The extra samples count is 0. What does this mean? What is the extra 8 bits present in the data?


text:
Q: Use of Infinitive vs. Gerund I framed two sentences, one using infinitive and another using gerund. Which of the two sounds more correct?

Although the app will continue to occupy the storage space, it will,
  at least, not run in the background.
Although the app will continue occupying the storage space, it will,
  at least, not run in the background.

Are both the sentences correct?

A: Both are correct and have the same meaning, though using the gerund form is considered more eloquent. I find that Practical English Usage (Swan ch.296) is excellent at explaining the rules for using infinitive or gerund.

A:
Although the app will continue to occupy the storage space, it will,
  at least, not run in the background.
Although the app will continue occupying the storage space, it will,
  at least, not run in the background.

When I read your first sentence, I understand;
The app was disrupted (stopped working). However the situation is fixed and the app will continue to occupy.
When I read your second sentence, I understand;
The app was not disrupted (continues working). There is nothing to fix but only a change in how the app is running.


text:
Q: Htaccess rewrite issue when redirecting from one dynamic url to another I am looking to rewrite a URL from current dynamic structure..
www.domain.com/news/news.php?news=id
to this new
www.domain.com/?p=id
the id is a dynamically number-based id.
I have tried multiple solutions for this, but it seems like I am not good enough at htaccess, because I can't get it to work.
Anyone with a good solution?

A: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On

RewriteCond %{QUERY_STRING} (?:^|&)news=([^&]+) [NC]
RewriteRule ^news/news\.php$ /?p=%1 [L,NC]


text:
Q: how to play video from my youtube account in android I want want to play video from my personal account in you tube.
  Intent videoClient = new Intent(Intent.ACTION_VIEW);
  videoClient.setData(Uri.parse("http://www.youtube.com"));
  videoClient.setClassName("com.google.android.youtube","com.google.android.youtube.PlayerActivity");
   startActivity(videoClient);

this code use for only play video in youtube. I want to play video into MY personal account in youtube..
I'm also log in in youtube.I have created my account in youtube and add video in my youtube account... question is this "how to play video on my youtube account"

A: For playing video from your youtube channel(account) you want to get rtsp URL of your video. And for complete example click here.


text:
Q: How to add scroll into listItem of list on search I have a List which contains ListItem and a search bar. Search functionality is working well as per the requirement and its highlighting the ListItem. Now i am trying to add the scroll so that the List gets scroll to first occurrence of the 'includes' if the search item is not available on visible window but not able to implement it. Tried  const ref = React.createRef();
How to get it working?
Here is the codesandbox link

A: You can easily achieve this one using vanilla js.
First just store the index of all matching ListItem in a state:
  const getMatchingListItems = React.useCallback(() => {
    return [...messages]
      .map(({ id, primary, secondary, person }, i) => {
        if (secondary.includes(searchTranscript) && searchTranscript !== "") {
          return i;
        }
      })
      .filter((elmt) => elmt !== undefined);
  }, [searchTranscript]);

  const [matchingListItems, setMatchingListItems] = useState(getMatchingListItems());

Use it to define which className to use:
<div
  className={
    matchingListItems.includes(i) ? classes.searchHighLight : ""
  }

And finally use the useEffect hook to scroll to the first matching LisItem when matchingListItems is updated:
   React.useEffect(() => {
    setMatchingListItems(getMatchingListItems());
  }, [getMatchingListItems, setMatchingListItems]);

  React.useEffect(() => {
    const firstListMatch = matchingListItems[0];

    if (firstListMatch) {
      const firstLi = document.querySelector(
        `ul div:nth-child(${firstListMatch})`
      );
      firstLi.scrollIntoView();
    } else {
      document.querySelector("ul").scrollIntoView();
    }
  }, [matchingListItems]);

You can try it using this codesandbox.


text:
Q: Citrix XenServer, networking how I am new to virtual servers, vlans. I am a programmer and have been assigned the task to make a stable storage server, i threw XenServer Free 5.6SP2 on an old box (HP ProLiant ML350 G5) set my raid(5), installed the footprint, all went well. very simple using the gui.
I installed my image of windows server 2003, all worked well.
Now from xencenter, i set my networks up, created a vlan. But how do i connect my VLAN to the network? Do i need a compatible switch? Do i do something with this switch? Its all new, confusing.
Do i need 1 physical NIC per VM? i was under the impression i can use my only physical NIC for as many server as i wanted (obviously with consequences)
Basically, i have a server with xenserver. windows server 2003 installed and working. just cant get it onto MY network.
I am appreciative of your time reading this.

A: What you need to do is have at least one Layer 3 Switch or Router which you connect at least one of the NIC's of the Xen Server too. This NIC needs to be set up as a trunk to carry all VLAN traffic. In XenCenter when you created your VLAN's you assigned them all to a specific NIC, make sure the connection between the switch and the NIC on the XenServer is set as a trunk on the switch.
On the switch, you will then need to create the same VLAN's as you have on your XenServer with the same ID's. Then, if you need to pass traffic elsewhere you can assign a port a specific VLAN ID and connect an ethernet from that port to wherever it needs to go.


text:
Q: Datepicker and FullCalender.io cannot run together datepicker is not a function I am trying to run instances of both fullcalendar and datepicker in one html file. I can get full calendar working as expected but I cannot get datepicker working along side.
When I run datepicker in its own separate html file it works fine.
The error that I get in the console is the below:

jQuery.Deferred exception: $(...).datepicker is not a function TypeError: $(...).datepicker is not a function

and

Uncaught TypeError: $(...).datepicker is not a function
      at HTMLDocument.

I am running this through Django but I don't think that is relevant.
Below is my code to make this happen, the idea is to open the modal and have a datepicker in there:

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ"
  crossorigin="anonymous">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
  crossorigin="anonymous">

  <link href="{%  static 'css/fullcalendar.min.css' %}" rel='stylesheet' />
  <link href="{%  static 'css/fullcalendar.print.min.css' %}" rel='stylesheet' media='print' />

  <link href="{%  static 'css/datepicker.css' %}" rel='stylesheet' />

</script>

<title>{% block title %}ProSquad | Scheduler{% endblock %}</title>

    <button type="button" class="btn btn-primary" data-target="#modal" data-toggle="modal">
      Launch the demo
    </button>

Datepicker

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              ×
            </button>

            <input type="text" class="form-control" data-toggle="datepicker">

            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

LoopLab

Copyright ©

This has been driving me mad for days and hoping it's just something stupid, any help would be seriously appreciated!


text:
Q: Change pixels between similar pixels on image I want to average pixel color between two similar pixels. White pixels between black pixels should become black and vice versa. This rule must apply in all directions. This is the complete example of what should happen:
Horizontal:
□■□ -> □□□

Vertical:
□   ->  □
■   ->  □
□   ->  □

■□■ -> ■■■

■   ->  ■
□   ->  ■
■   ->  ■

□■□  ->   □□□   ->   □□□
■■■  ->   ■■■   ->   ■□■
■□■  ->   ■□■   ->   ■□■

Can OpenCV do this? Can anyone make algorighm like this? This is what I tried:
while(i<image->width){
    while(j<image->height){
        if(pixel[i,j-1] == pixel[i,j+1]){
            pixel[i,j] = pixel[i,j-1];
        }else if(pixel[i-1,j] == pixel[i+1,j]){
            pixel[i,j] = pixel[i-1,j];
        }
        j++;
    }
    i++;
}

A: You didn't access the image pixels correctly.
For gray-scale image (in your example, Mat pixel), to access its pixel, you should use:
pixel.at<uchar>(j, i) = ...;


text:
Q: How to slide a div with p tag to right with css animation usin max-width? I have an info box but I want it to slide in from left to right. But the css animation begins with a very high div because of the p tag inside it. Is there a way to fix this ?
JsFiddle : https://jsfiddle.net/scj5vc3b/
Html :

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore ipsam fugit vero, autem asperiores accusamus ea unde magni distinctio excepturi minus amet repudiandae, debitis nulla voluptatem earum deleniti error reiciendis!

SCSS :
.info-box {
   margin: 10px 0;
   border-left: 3px solid black;
   overflow: hidden;
   display: inline-block;
   -webkit-animation: slideIn 1s linear;
   position: relative;

   p {
    display: block;
    padding: 10px 20px 10px 10px;
    margin-bottom: 0;
   }
}

@keyframes slideIn {
  0%   {max-width: 0px;}
  100% {max-width: 1000px;}
}

.info-box.info {
 background-color: lighten(blue, 24);
}

A: Use a transform on the paragraph instead:

.info-box {
  margin: 10px 0;
  border-left: 3px solid black;
  -webkit-animation: slideIn 1s linear;
  position: relative;
  display: inline-block;
  overflow: hidden;
}
p {
  padding: 10px 20px 10px 10px;
  margin-bottom: 0;
  transform: translateX(-100%);
  -webkit-animation: slideIn 1s linear forwards;
}
i {
  padding-right: 15px;
}
@keyframes slideIn {
  to {
    transform: translateX(0%);
  }
}
.info-box {
  background-color: lightblue;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore ipsam fugit vero, autem asperiores accusamus ea unde magni distinctio excepturi minus amet repudiandae, debitis nulla voluptatem earum deleniti error reiciendis!


text: Q: Can I hook into wp_update_core outside of the admin? I'm trying to bring some of the admin functionality to a custom front end in WordPress. Questions of security and pragmatism of this aside, is there an available hook to trigger wp_update_core outside of the admin?


text:
Q: Instantiate and call a method in one line Is there a way to instantiate a class and call one of its methods in one line? I hoped the following would work but it doesn't:
(new User())->get_name();

A: This is not possible. You could, however, create a static method returning a new instance. Something like:
class User {
    public static function create() {
        return new self();
    }
}

User::create()->get_name();

A: Nope, sorry, this unfortunately doesn't work in PHP. You could work around it by using a static factory method or something like that though.

A: I know this question is old but the replies can be misleading.
Since version 5.4 you can instantiate and call methods inline:
(new Foo())->bar();

http://docs.php.net/manual/en/migration54.new-features.php

A: Try if this works for you. It calls the function from the class not an object.
User::get_name();


text:
Q: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '05/20/2020' I'm making an app with laravel, this features a calendar. I'm using "fullcalendar" which is very restricting on date format and AFAIK only accepts 'yyyy/mm/dd'. I'm using the jQuery datepicker and have edited the formatting to make it work. That all works fine and on the insert for a long time I would never get this error, however suddenly it's started giving me this error after days of not having it. I really don't understand. Unless there's a way to change fullcalendar formatting to match the accepted formatting for SQL, which has not affected my app since now, then I'd love to hear it.
(error: QLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '05/14/2020' for column)
Thanks.

A: fixed it, my formatter was broken


text:
Q: Proving a theorem in classical propositional logic In van Fraasen and Beall's book Possibilities and Paradox, there is the following line (on pg 7):

"In classical propositional logic we can prove that $$(A \iff B) \lor (A
 \iff C) \lor (B \iff C)$$ is valid."

$A, B$ and $C$ have not been previously defined.
Can someone point me to the proof of this theorem?

A: The letters $A,B$, and $C$ stand for propositions, each of which may be either true of false. The point of the quoted statement is that it doesn't matter exactly what propositions they are or which of them (if any) are true: the displayed statement is true no matter what.
You can prove it with a truth table. However, you don't actually need one. $$(A\iff B)\lor(A\iff C)\lor(B\iff C)$$ is true if and only if at least one of the disjuncts $A\iff B$, $A \iff C$, and $B\iff C$ is true. $A\iff B$ is true exactly when $A$ and $B$ have the same truth value: both are TRUE, or both are FALSE. Similarly, $A\iff C$ is true exactly when $A$ and $C$ have the same truth value, and $B\iff C$ is true exactly when $B$ and $C$ have the same truth value.
Since there are only two truth values in classical propositional logic, no matter how you assign truth values to $A,B$, and $C$, two of them have to get the same truth value. This means that under any assignment of truth values to $A,B$, and $C$, at least one of the three disjuncts has to be true, and hence the whole proposition must be true as well.

A: Here is a natural deduction proof using a Fitch-style proof checker.
The first part starts the proof using the law of the excluded middle on $(A\leftrightarrow B)\lor \neg A\leftrightarrow B)$. The left disjunct derives the desired goal in lines 1-2. The rest of the proof will show how the right disjunct does the same.

The law of the excluded middle will be used on $(B\leftrightarrow C)\lor \neg (B \leftrightarrow C)$ to derive the goal from the left disjunct of line 20:

The law of the excluded middle will be used on $(A\leftrightarrow C)\lor \neg (A \leftrightarrow C)$ to derive the goal from the right disjunct of line 20:

Kevin Klement's JavaScript/PHP Fitch-style natural deduction proof editor and checker http://proofs.openlogicproject.org/


text:
Q: not able to import ddt in python 2.7 import unittest

from ddt import  data, unpack
from selenium import webdriver
import ddt

@ddt

class searchddt(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.implicitly_wait(30)
        self.driver.maximize_window()

        self.driver.get('https://magento.com/products/magento-commerce')

        @data(("phones",2))
        @unpack
        def test_search(self,search_val,expected_count):
            self.searchfield=self.driver.find_element_by_xpath("//I[@aria-hidden='true']/self::I")
            self.searchfield.clear()
            self.searchfield.send_keys(search_val)
            self.searchfield.submit()

        def tearDown(self):
            self.driver.quit()
    if __name__=='__main__':
        unittest.main(verbosity=2)

FAILED (errors=1)

getting error in importing ddt and code is not executing

Error
          Traceback (most recent call last):
            File "C:\Python27\lib\unittest\case.py", line 329, in run
              testMethod()
            File "C:\Python27\lib\unittest\loader.py", line 32, in testFailure
              raise exception
          ImportError: Failed to import test module: ddt

              class searchddt(unittest.TestCase):
          TypeError: 'module' object is not callable
Process finished with exit code 1

A: I believe that the issue lies in the way that you are importing needed decorators
from ddt import  data, unpack
from selenium import webdriver
import ddt

If you look at the last statement, you are importing ddt which is a module, and this is causing the error when decorating the class. You need a decorator - callable that is located inside the ddt module.
I think that the solution would be to import it in the first line like this
from ddt import ddt, data, unpack
from selenium import webdriver

A: There are two issues here.
The first is covered by the other answer: you need to from ddt import ddt rather than import ddt.
The second is that your test function is decorated with @unpack, so the tuple you pass to @data will be unpacked by ddt, creating two function calls: test_search_1("phones") and test_search_2(2). This isn't what you want.
You probably want something like:
@data([
    {"search_val": "phones", "expected_count": 2},
    {"search_val": "things", "expected_count": 3},
    {"search_val": "stuff", "expected_count": 4},
])
@unpack
def test_search(self, search_val, expected_count):

There's a bonus third issue, which is the indentation of your test and tearDown functions, which should not be within setUp.


text:
Q: How to retrieve image from SharePoint list column using react js? I have given the code as:

It is retrieving the specific image which i give in the url.
For example: I have 3 items in pages list,in which each item have images.I would like to retrieve all the items with values and display it in a table.I am able to display Title,Modified field in table but not the image.
I tried to get the image property by doing F12 and tried implementing that but getting the error as:
Error - typescript - src\webparts\newsAppPart\components\NewsAppPart.
tsx(76,82): error TS2339: Property 'Url' does not exist on type '""'.
Any pointers would be helpful.
Thanks.


text:
Q: Can we use history file for auditing purpose We have a common testing environment on AIX for all 15-20 persons. There might be chances that somebody deleted the files mistakenly. In such scenarios,  it is very difficult to know who deleted files from a specific location.
I would like to generate a report for that same so that we can trace it. In fact, I am looking for following information :
< ExecutedCmd>
How can we do that by using shell script ?
Please suggest.

A: Accountability can not exist in an environment with only one user account. For this reason and for many others (granular access control, reliable privilege revocation, account termination upon dismissal, etc.), you should really set up a separate account for each person.
Further, finding out who deleted a file is not going to solve your problem; the file is gone anyway. If the data is mission-critical, it should be backed up regularly and incrementally. There are many ways to do this. rsync with --link-dest is appropriate for large-scale system backups whereas some kind of source control would work better for something like a directory full of text files.


text:
Q: Kaniko do not use cache options I am trying to use the --cache-repo option of the kaniko executor but I see that it does not use the cache that I saved in ECR/AWS and the gitlab log returns this;
Checking for cached layer [MASKED]/dev-cache:627d56ef7c151b98c02c0de3d3d0d9a5bc8d538b1b1d58632ef977f4501b48f4...
INFO[0521] No cached layer found for cmd COPY --from=build /../../../../..............

I have rebuilt the image with the same tag and the code has not changed and it is still taking the same time...
The version of kaniko I am using is the following gcr.io/kaniko-project/executor:v1.9.1
These are the flags I use in kaniko:
  /kaniko/executor --cache=true \
    --cache-repo "${URL_ECR}/dev-cache" \
    --cache-copy-layers \
    --single-snapshot \
    --context "${CI_PROJECT_DIR}" ${BUILD_IMAGE_EXTRA_ARGS} \
    --dockerfile "${CI_PROJECT_DIR}/Dockerfile" \
    --destination "${IMAGE_NAME}:${IMAGE_TAG}" \
    --destination "${IMAGE_NAME}:latest" \
    --skip-unused-stages \
    --snapshotMode=redo \
    --use-new-run

Do you have any ideas?

A: Successfully resolved issue by removing the flags: --cache-copy-layers and --single-snapshot, and adding the flag: --cleanup


text:
Q: Combine tables with values other tables with column names in SQL I have 5 tables. One with individual details, two with column names for the latter two and two with values.
T1: people
-----------------
|name|age|gender|
-----------------
|Alice|22 | f   |
|Bob  |33 | m   |
-----------------

T2: skillgroup names
--------------
|id | name    |
---------------
| 1 | sgn1    |
| 2 | sgn2    |
|.. |  ...    |
| 63| sgn63   |
---------------

T3: skill names
--------------
|id | name    |
---------------
|101 | sk101  |
|102 | sk102  |
|..  |  ...   |
|180 | sk180  |
---------------

T4: skillgroup person
--------------------------------
|name  | skillgroupID | value  |
--------------------------------
|Alice | 1            | 40     |
|Alice | 2            | 38     |
|...   | ..           | ..     |
|Bob   | 63           | 25     |
--------------------------------

T5: skill person
---------------------------
|name  | skillID | value  |
---------------------------
|Alice | 101     | 80     |
|Alice | 102     | 70     |
|...   | ..      | ..     |
|Bob   | 180     | 90     |
---------------------------

However, I would like to get a table like this:
    ------------------------------------------------------------
    |name |age|gender|sgn1|sgn2|...|sgn63|sk101|sk102|...|sk180|
    ------------------------------------------------------------
    |Alice| 22| f    | 40 | 38 |...| ... | 80  |  70 |...| ... |
    |Bob  | 33| m    | ...| ...|...|  25 | ... | ... |...| 90  |
    ------------------------------------------------------------

How can I do this? As far as I can see, the skillgroup and skills are the same for each person, meaning that each person has the same amount of skillgroups and skills.

A: The following mysql query solves your particular problem:
SELECT
  p.name,
  p.age,
  p.gender,
  MAX(IF(skgn.name = 'sgn1', skgp.value, NULL)) AS sgn1,
  MAX(IF(skgn.name = 'sgn2', skgp.value, NULL)) AS sgn2,
  MAX(IF(skgn.name = 'sgn63', skgp.value, NULL)) AS sgn63,
  MAX(IF(skn.name = 'sk101', skp.value, NULL)) AS sk101,
  MAX(IF(skn.name = 'sk102', skp.value, NULL)) AS sk102,
  MAX(IF(skn.name = 'sk180', skp.value, NULL)) AS sk180
FROM people AS p
INNER JOIN skillgroup_person AS skgp ON p.name = skgp.name
INNER JOIN skill_person AS skp ON p.name = skp.name
INNER JOIN skillgroup_names AS skgn ON skgp.skillgroupID = skgn.id
INNER JOIN skill_names AS skn ON skp.skillID = skn.id
GROUP BY p.name, p.age, p.gender;

See DEMO
Since this solution is not dynamic, in case you have lot of columns to turn into row data it is better to go with a dynamic pivot table solution at this SO answer.


text:
Q: Setting Core Data attribute depending on other attributes I'm trying to understand how Core Data works. For this I've tried to implement a simple entity named "Color" with these attributes :

*

*value -> an NSColor to handle the color itself, bound to an NSColorWell

*red -> a float value to handle the red component of the color, bound to an NSSlider

*green -> same as red but for green component, bound to an NSSlider

*blue -> blue component, bound to an NSSlider

For this I'm using a class named Color and I've overwritten - (id)value to get the color depending on components :
 @implementation Color

@dynamic blue;
@dynamic green;
@dynamic name;
@dynamic red;
@dynamic value;

- (id)value
{
    return [NSColor colorWithCalibratedRed:self.red.floatValue green:self.green.floatValue blue:self.blue.floatValue alpha:1.0];
}

+ (NSSet *)keyPathsForValuesAffectingValue
{
    return [NSSet setWithArray:@[@"red", @"green", @"blue"]];
}

Every time I change a slider value the color adapts itself to components.
What I'd like to do is the inverse operation, when I set the color (drag'n drop or NSColorWell's color picker) the component adapt themselves.
I've tried to implement this but it never works. I've tried too much things to paste them here (it would be irrelevant because it didn't work).
How can I do this ? Understanding this could help me a lot to understand how Core Data works.

A: So here is the piece of code that made it work :
@implementation Color

@dynamic blue;
@dynamic green;
@dynamic name;
@dynamic red;
@dynamic value;

- (id)value
{
    return [NSColor colorWithCalibratedRed:self.red.floatValue green:self.green.floatValue blue:self.blue.floatValue alpha:1.0];
}

- (void)setValue:(id)value
{
    [self willChangeValueForKey:@"value"];
    [self setPrimitiveValue:value forKey:@"value"];
    [self didChangeValueForKey:@"value"];
    [self setRed:@([(NSColor *)value redComponent])];
    [self setGreen:@([(NSColor *)value greenComponent])];
    [self setBlue:@([(NSColor *)value blueComponent])];
}

+ (NSSet *)keyPathsForValuesAffectingValue
{
    return [NSSet setWithArray:@[@"red", @"green", @"blue"]];
}

Now I can work on HSB sliders.


text:
Q: Docker: multiple PHP7-FPM containers on different ports I am playing around with Docker for my local development environment. My setup for now is 5 containers (1 HaProxy + 2 NGINX + 2 PHP7-FPM).
The proxy container is used to direct the request based on the url, so if I enter http://project1.dev it will proxy the request to the project1-nginx that uses project1-php for evaluating php. The setup is similar for http://project2.dev.
Now, I am trying to wrap my head around the ports of the two php containers. The default fpm port is 9000, so both php containers cannot run on this. I am assuming the way to go here is to let both containers export port 9000 but make them 9000 and 9001 on the host?
Something along these lines in my compose file.
project_1_php:
  ports:
    - "9000:9000"
project_2_php:
  ports:
    - "9001:9000"

So, everything boots up fine, and project 1 is working, but project 2 gives me a 502. Nginx error log says
2016/01/26 14:37:05 [error] 6#6: *1 connect() failed (111: Connection refused)
while connecting to upstream, client: 172.17.0.9, server: code.dev,
request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.4:9001"

A: For those looking like I did for a way to run multiple NGINX and PHP-FPM containers for different projects at the same time and found this SO thread, ran across this:
https://github.com/docker-library/php/issues/479
Inside the php-fpm Dockerfile:
FROM php:7.2-fpm
RUN sed -i 's/9000/3001/' /usr/local/etc/php-fpm.d/zz-docker.conf

Then in your docker-compose.yaml file you can point your Nginx to that specific port for that PHP-FPM instance.

A: Had similar issue with php-fpm7,
as @Mjh mentioned in the comments, by default fpm listening to 127.0.0.1:9000,
so you should replace it with a 0.0.0.0:9000,
I found a solution there: githib:matriphe/docker-alpine-nginx
So you can add to your fpm container Dockerfile :
RUN sed -i "s|;*listen\s*=\s*127.0.0.1:9000|listen = 9000|g" /etc/php7/php-fpm.conf

A: Just thought I would mention that Traefik Proxy is a fantastic way to handle this scenario


text:
Q: Applying And to lists of Booleans I'd like to take {True,True,False} and {True,False,False} and apply And to get {True,False,False}. Right now I'm using
And @@ # & /@ Transpose[{{True, True, False}, {True, False, False}}]

Is that really the best way? I would like And[{True, True, False}, {True, False, False}] to work but it does not.

A: Late to the party
BitAnd @@ Boole@l /. {1 -> True, 0 -> False}

A: A silly one (convert both lists to numbers, multiply, convert back) and some timings:
(l1 /. {True -> 1, False -> 0}) (l2 /. {True -> 1, False -> 0}) /. {0 -> False, 1 -> True})

n = 1000000;
res = Table[
   l1 = RandomChoice[{True, False}, n];
   l2 = RandomChoice[{True, False}, n];
   {
    (r1 = And[l1, l2] // Thread) // AbsoluteTiming // First,
    (r2 = And @@@ Transpose[{l1, l2}]) // AbsoluteTiming // First,
    (r3 = MapThread[And, {l1, l2}]) // AbsoluteTiming // First,
    (r4 = Inner[And, l1, l2, List]) // AbsoluteTiming // First,
    (r5 = (l1 /. {True -> 1, False -> 0}) (l2 /. {True -> 1,
             False -> 0}) /. {0 -> False, 1 -> True}) // AbsoluteTiming // First
   }, {10}];

Mean /@ (res\[Transpose])

{0.3687211, 0.6879394, 0.5338305, 0.3507201, 0.7428425}

Inner wins.

A: I want in on this fun.  Doesn't seem to be the fastest, but here it is:
l1={{True,True,False},{True,False,False}};
(# != 0) & /@ Times @@ Boole[l1];

(*{True,False,False}*)

A: I like more :
MapThread[ And, {{True, True, False}, {True, False, False}}]

{True, False, False}

Edit
We should test efficiency of various methods for a few different lists.
Definitions
Argento[l_] := (And @@ # & /@ Transpose[l]; // AbsoluteTiming // First)
Brett[l_]   := (And @@@ Transpose[l]; // AbsoluteTiming // First)
Artes[l_]   := (MapThread[And, l]; // AbsoluteTiming // First)
kguler[l_]  := (And[l[[1]], l[[2]]] // Thread; // AbsoluteTiming // First)
RM[l_]      := (Inner[And, l[[1]], l[[2]], List]; // AbsoluteTiming // First)

Test I
l1 = RandomChoice[{True, False}, {2, 10^5}];
Argento[l1]
Brett[l1]
Artes[l1]
kguler[l1]
RM[l1]

0.2710000
0.0820000
0.0530000
0.0520000
0.0390000

Test II
l2 = RandomChoice[{True, False}, {2, 7 10^5}];
Argento[l2]
Brett[l2]
Artes[l2]
kguler[l2]
RM[l2]

1.4690000
0.5820000
0.3840000
0.3700000
0.2890000

Test III
l3 = RandomChoice[{True, False}, {2, 3 10^6}];
Argento[l3]
Brett[l3]
Artes[l3]
kguler[l3]
RM[l3]

6.2320000
2.4750000
1.6530000
1.4150000
1.2150000

A: I prefer using Inner for this, as conceptually, it is a generalized dot of the two Boolean lists with And as the operator.
Inner[And, {True, True, False}, {True, False, False}, List]
(* {True, False, False} *)

A: And in a late bid for the silver medal by subversive means:
Unprotect@And; SetAttributes[And, {Flat, OneIdentity, Protected, Listable}];
l1 = RandomChoice[{True, False}, {2, 10^6}];
Argento[l1]
Brett[l1]
Artes[l1]
kguler[l1]
RM[l1]
And @@ l1 // AbsoluteTiming // First

0.705648
  0.288288
  0.193292
  0.163886
  0.149485
  0.160957

A: I like Artes' and kguler's answers, but I'd like to point out that in general
f @@ # & /@ list

can be more concisely written as
f @@@ list

For example:
And @@@ Transpose[{{True, True, False}, {True, False, False}}]

(* {True, False, False} *)

A: You can use Thread:
Thread[And[{True, True, False}, {True, False, False}]]

or, Thread with Apply (@@) :
Thread[And@@{{True, True, False}, {True, False, False}}]
(* {True, False, False} *)


text:
Q: Relationships in Laravel Models How can I write this without a join for a scope in a Laravel model as the 'id' field becomes ambiguous
 /**
  * Return events that social category name
  */
public function scopeWithSocialEvents($query)
{
    return $query->join('categories', 'events.event_type_id', '=', 'categories.id')
                ->where('categories.name', 'social');
}

A: Use this:
public function eventType()
{
    return $this->belongsTo(Category::class);
}

public function scopeWithSocialEvents($query)
{
    return $query->whereHas('eventType', function($query) {
        $query->where('name', 'social');
    });
}


text:
Q: Label Values and Total in Google Visualization Stacked Bar Chart I am trying to display the value of each bar and then the total value of all bars in a stacked bar chart The problem is, I get the last bar's value and the total both outside the bar.  If I do not show the total, I get the value inside the bar.  Using the code below the the last two annotations are outside the second bar even when the second bar is long enough to show its label.

    <base target="_top">

Registrations

If I removed the last option in the setColumns to make that section read as follows:
  view.setColumns([0,
    1, {
      calc: function (dt, row) {
      return dt.getValue(row, 1);
    },
    type: "number",
    role: "annotation"
    },
    2, {
      calc: function (dt, row) {
      return dt.getValue(row, 2);
    },
    type: "number",
    role: "annotation"
    },
    // series 1
    {
      calc: function (dt, row) {
      return dt.getValue(row, 1) + dt.getValue(row, 2);
    },
    type: "number",
    role: "annotation"
    }
  ]);

I get the labels where I want them without the Total, as shown below

What I am after is to add the Total to the end and the Labels consistently inside as shown below:

I have tried too many methods to remember or list here, but am not getting the Total at the end.  How can I get this last Label to appear and keep the others inside the bar when they will fit there? Note that I have made the red bar longer than the blue one and the numbers still displayed as shown.

A: you could add another series column for the total
then hide it from the chart with the following options...
    enableInteractivity: false,
    tooltip: "none",
    visibleInLegend: false

this will allow the annotations from the other values to perform normally
the total annotation will always show outside,
but need to adjust a few options to keep it from overwriting others...
    annotations: {
      stem: {
        color: "transparent",
        length: 28
      },
      textStyle: {
        color: "#000000",
      }
    },

see following working snippet...

google.charts.load('50', {
  packages:['corechart']
}).then(function () {
  var myHeight = 350;
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Registrations');
  data.addColumn('number', 'Regular');
  data.addColumn('number', 'Work Study');

  data.addRows([
    ['Adult', 20, 12],
    ['Teen', 3, 0]
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0,
    1, {
      calc: function (dt, row) {
        return dt.getValue(row, 1);
      },
      type: "number",
      role: "annotation"
    },
    2, {
      calc: function (dt, row) {
        return dt.getValue(row, 2);
      },
      type: "number",
      role: "annotation"
    },
    {
      calc: function (dt, row) {
        return 0;
      },
      label: "Total",
      type: "number",
    },
    {
      calc: function (dt, row) {
        return dt.getValue(row, 1) + dt.getValue(row, 2);
      },
      type: "number",
      role: "annotation"
    }
  ]);

  var options = {
    animation:{
      duration: 1000,
      easing: 'out',
      startup: true
    },
    title: 'Registrations',
    backgroundColor: 'transparent',
    height: myHeight, width: 500,
    legend: {
      position: 'top',
      maxLines: 3
    },
    bar: { groupWidth: '75%' },
    isStacked: true,
    series: {
      2: {
        annotations: {
          stem: {
            color: "transparent",
            length: 28
          },
          textStyle: {
            color: "#000000",
          }
        },
        enableInteractivity: false,
        tooltip: "none",
        visibleInLegend: false
      }
    }
  };
  var chart = new google.visualization.BarChart(document.getElementById('registrations_chart'));
  chart.draw(view, options);
});

EDIT
there are no standard options for annotation position
but you can move them manually, once the chart's 'ready' event fires
or in this case, the 'animationfinish' event
see following working snippet,
the total annotations are moved down...

google.charts.load('50', {
  packages:['corechart']
}).then(function () {
  var myHeight = 350;
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Registrations');
  data.addColumn('number', 'Regular');
  data.addColumn('number', 'Work Study');

  data.addRows([
    ['Adult', 20, 12],
    ['Teen', 3, 0]
  ]);

  var view = new google.visualization.DataView(data);
  view.setColumns([0,
    1, {
      calc: function (dt, row) {
        return dt.getValue(row, 1);
      },
      type: "number",
      role: "annotation"
    },
    2, {
      calc: function (dt, row) {
        return dt.getValue(row, 2);
      },
      type: "number",
      role: "annotation"
    },
    {
      calc: function (dt, row) {
        return 0;
      },
      label: "Total",
      type: "number",
    },
    {
      calc: function (dt, row) {
        return dt.getValue(row, 1) + dt.getValue(row, 2);
      },
      type: "number",
      role: "annotation"
    }
  ]);

  var options = {
    animation:{
      duration: 1000,
      easing: 'out',
      startup: true
    },
    title: 'Registrations',
    backgroundColor: 'transparent',
    height: myHeight, width: 500,
    legend: {
      position: 'top',
      maxLines: 3
    },
    bar: { groupWidth: '75%' },
    isStacked: true,
    series: {
      2: {
        annotations: {
          stem: {
            color: "transparent",
          },
          textStyle: {
            color: "#000000",
          }
        },
        enableInteractivity: false,
        tooltip: "none",
        visibleInLegend: false
      }
    }
  };
  var chart = new google.visualization.BarChart(document.getElementById('registrations_chart'));

  google.visualization.events.addListener(chart, 'animationfinish', function () {
    $('#registrations_chart text[fill="#000000"]').each(function (index, annotation) {
      if (!isNaN(parseFloat(annotation.textContent))) {
        var yCoord = parseFloat($(annotation).attr('y'));
        $(annotation).attr('y', yCoord + 18);
      }
    });
  });

  chart.draw(view, options);
});


text:
Q: How best to decouple a web service from its publicly-available domain names? I'm trying to design a system that allows for multiple public endpoints that funnel into a single web service.  The web service must be able to determine which endpoint was the intended destination of the request.  Here's a little sample configuration that might fit the bill:

In this system, the "reverse proxies" (for lack of a better term) add an HTTP header to the incoming requests before they hit the web service.  Otherwise, the proxies are entirely transparent to the request and response.
We're a Windows shop using IIS7/WCF.
The goal is 1) to maintain only a single web service, rather than one per domain, and 2) to decouple domain/web site management from the business logic in the web service.  That is, if we know that context will always be specified with a key in the HTTP header, then we don't have to worry about domains changing or the specific content of Request.Headers["HOST"].
My questions are: is this a reasonable approach?  If so, is there an app out there that will do the job of the "reverse proxies"? (Squid?  IIS itself?)
Thank you for the help!

A: It sounds to me as though what you're trying to do is have a single app that does 2 wholly separate things. At a certain point theres going to be overlap in the code base and functionality, but I don't know your app well enough to help you with that. I have 2 possible solutions for you:

*

*I would try to separate the view related code out from your controllers and models if you're going the MVC direction. That would give you a cleaner separation of the business logic. One possible way to do that is to put your views into 2 separate directories, but then include code from a shared 3rd directory. That gives you one shared library that handles the backend logic while cleanly separating the presentation logic.

*I wouldn't be afraid of the HTTP Host header. It's required by HTTP/1.1 and all modern browsers use it. Heck, virtual hosting is entirely dependent on it and you'd be hard pressed to find an IIS or Apache admin who would tell you not to use virtual hosts on production. The big downside of course, if you're doing the header check on the application side, is you can run into some pretty ugly if/case statements. The only thing a reverse proxy setup does is look for a Host and add another header in addition to the Host. So you're really just adding more headers and complexity to your architecture with the reverse proxying.

A: Firstly, your HTTP Host field should be preserved by your reverse proxy as it passes the request through. If it's not, then your proxy is wrongly (and weirdly!) configured.
Secondly, passing extra headers and identifying traffic by that is the standard and accepted way to identify traffic handled by a load balancer. For example, that's how load balancers are usually configured to inform web servers that traffic is coming in over SSL (as SSL can't be proxied at that level).
Finally, I think you may be overcomplicating your problem. Realistically how often do domain names change compared to the content behind them?! That's not really how the web is meant to work... There's nothing wrong with your application serving content based on domain name in the HTTP Host header, it's very common practice.

A: One way to do this would be to have a small array of cloud load-balancers each aimed at your web service.  Rackspace provides LBaas, and possibly others do as well.
http://www.rackspace.com/cloud/cloud_hosting_products/loadbalancers/
Full disclosure: I do work for Rackspace, however not in sales.


text:
Q: How to call method in class throw event? I have an element that need to drag in window, code with function work well, but when i use classes i cant understand why it doesnt.
Can you help me with manipulate_this_element() method in codepen below?
https://codepen.io/igor-sushko/pen/oNNBvQX?editors=1011
class View {
  create_staff() {
    console.log("staff work!");
    this.listener();
  };

  listener() {
    console.log("listener work!");
    let a = document.getElementById("AAA");
    a.addEventListener("mousedown", this.mouse_down)
    // .onmousedown = this.mouse_down();
  };

  mouse_down(e) {
    let that = this;
    console.log("mouse_down work!");
    e.preventDefault();
    document.addEventListener("mousemove",  that.manipulate_this_element)
    // document.onmousemove = this.manipulate_this_element();
  };

  manipulate_this_element() {
    console.log("manipulate_this_element work!");
  };
}

let a = new View();
a.create_staff();

I want to see "manipulate_this_element work!" in console when i moving mouse

A: It is too late for :
    mouse_down(e) {

      let that = this;
      ...

    }

In mouse event callback 'this' is undefined.
Most simply but not the best way is to use global scope access.

listener() {
    var root = this;
    console.log("listener work!");
    let a = document.getElementById("AAA");
    a.addEventListener("mousedown", this.mouse_down)

    // Global access
    document.addEventListener("mousemove",  a.manipulate_this_element, false);

   // simple this
    document.addEventListener("mousemove",  root.manipulate_this_element, false);

  };

 mouse_down(e) {
    let that = this;
    console.log("mouse_down work!");
    e.preventDefault();
    // You can't attach event infinity , just one time.
  };

A: The problem is that with a.addEventListener("mousedown", this.mouse_down) the mouse_down would not be called on the view object when the event occurs, so the this within that mouse_down does not refer to the view instance anymore.
To solve the problem you have various ways to bind the this to the function.
Given that you already use class then you are probably already able to use this syntax:
 mouse_down = (e) => {
 }

Using the arrow function that way will bind the this of that arrow function to the instance of View.
The big advantage of this method is, that this also allows you to remove the event listener easily using a.removeEventListener("mousedown", this.mouse_down)
Here the full code:
class View {
  create_staff() {
    console.log("staff work!");
    this.listener();
  }

  listener() {
    console.log("listener work!");
    let a = document.getElementById("AAA");
    a.addEventListener("mousedown", this.mouse_down)
    // .onmousedown = this.mouse_down();
  }

  mouse_down = (e) => {
    let that = this;
    console.log("mouse_down work!");
    e.preventDefault();
    document.addEventListener("mousemove",  that.manipulate_this_element)
    // document.onmousemove = this.manipulate_this_element();
  }

  manipulate_this_element = () => {
    console.log("manipulate_this_element work!");
  }
}

let a = new View();
a.create_staff();


text:
Q: Register entityFramework with MySql.Data 6.7.2.0 connector I have tried to configure my web project to use MySQL pre release of .net connectors, version 6.7.2.0. However, i keep getting this message, even if I try my best configure my project to use the 6.7.2.0 version of the connectors.
As it is now, I keep getting this errormessage:

No Entity Framework provider found for 'MySql.Data.MySqlClient' ADO.NET provider. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

I have tried different ways to configure my Web.config file, and here is my current settings:
  <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
        <add name="MySQL Data Provider"
             invariant="MySql.Data.MySqlClient"
             description=".Net Framework Data Provider for MySQL"
             type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.7.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
  <entityFramework>
    <defaultConnectionFactory type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />
  </entityFramework>

I have installed EF6 alfa3 from NuGet. Currently my connector has been installed manually from this downloaded file, I tried to install it from NuGet repository, but with the exact same result.

A: In addition to registering the ADO.NET provider, you need to register the Entity Framework provider:
<entityFramework>
  <providers>
    <provider invariantName="MySql.Data.MySqlClient"
              type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity" />
  </providers>
</entityFramework>

You also need to ensure that the provider has been built against Entity Framework 6. See this article for more information on this.

A: I had a similar issue. After rolling back to EF5 and MySql Connector 5.6 and it still not working, I finally found a feed where someone had mentioned that they had to remove the version and culture reference in order to get it to work. No idea why. Here:
 <system.data>
    <DbProviderFactories>
      <remove invariant="MySql.Data.MySqlClient" />
        <add name="MySQL Data Provider"
             invariant="MySql.Data.MySqlClient"
             description=".Net Framework Data Provider for MySQL"
             type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, PublicKeyToken=c5687fc88969c44d" />
    </DbProviderFactories>
  </system.data>
   <entityFramework>
<defaultConnectionFactory type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data" />


text:
Q: How to temporarily change the package name of an Android app? I need to temporarily change the package name of an Android app.
The reason I need to do this is because my customer does not yet have a Google Play account, but wants to test the app I've been developing for him. So I want to put it on an internal testing channel using my Play account, but I want to do so under a different package name.
When I develop iOS apps, there is a mechanism in Xcode by which any app can have multiple targets, and each target can have a separate bundle ID, and other properties, creating a unique app from the same source code. Then I can switch between targets at will to produce either version of the app.
What is the correct way to do this in Android?
The answers I've found online suggest that a wholesale refactoring of all the package names in the actual source code files is necessary -- I don't think this is the right answer in my case. I just want to toggle between two package names the same way you would toggle between build variants.
Thanks,
Frank

A: Use applicationIdSuffix ".demo" to extend the given name (the namespace does not really matter, the package name only has to be unique). One probably cannot completly override the applicationId; the merge output of AndroidManifest.xml would show what is broken.
Better publish to Firebase App Distribution first (can be linked to Play Store).
There the obstacles are generally lower - and one can also see remote crashes.


text:
Q: Returning a message depending on data being deleted in TSQL using a stored procedure I'm working on building a simple card game scoring program and I'm setting up a stored procedure to clear previous players and scores from my table.
I'm attempting to have the stored procedure return "Players cleared. Ready to start!" if there were records deleted from the table. Otherwise, if the table is already empty, I want it to say "Ready to start!".
My latest attempt is below. I've also tried declaring a variable and setting each of the results to that variable and returning the variable at the end.
Whenever I run the stored procedure, it only returns an empty column of "Players". I know this is from the select statement, but I'm struggling to figure out how to return the text above.
Thanks in advance!
CREATE PROCEDURE new_game
AS
BEGIN
    SELECT player
    FROM Score

    IF @@ROWCOUNT > 0
    BEGIN
        DELETE FROM dbo.Score

        PRINT 'Players cleared. Ready to start!';
    END
    ELSE
    BEGIN
        PRINT 'Ready to start!';
    END
END

A: Please try this.
    CREATE PROCEDURE new_game AS
    BEGIN
     IF EXISTS( SELECT TOP 1 player FROM Score)
     BEGIN
       DELETE FROM dbo.Score
       SELECT 'Players cleared. Ready to start!' AS Players;
     END
     ELSE
     BEGIN
       SELECT 'Ready to start!' AS Players;
     END
    END


text:
Q: Retrieving date of birth from Google OAuth API in MVC I have added following scopes to access data from user
#region Google
 var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = ConfigurationManager.AppSettings["Google_AppID"],
            ClientSecret = ConfigurationManager.AppSettings["Google_AppSecret"]
        };
        googleAuthenticationOptions.Scope.Add("profile");
        googleAuthenticationOptions.Scope.Add("email");
googleAuthenticationOptions.Provider = new GoogleOAuth2AuthenticationProvider()
        {
            OnAuthenticated = async context =>
            {
                //context.Identity.AddClaim(new Claim("birthday", context.User.GetValue("birthday").ToString()));
                string claimType;
                bool bAddClaim = false;
                foreach (var claim in context.User)
                {

                    claimType = string.Empty;
                    bAddClaim = false;
                    switch (claim.Key)
                    {
                        case "given_name":
                            claimType = "FirstName";
                            bAddClaim = true;
                            break;
                        case "family_name":
                            claimType = "LastName";
                            bAddClaim = true;
                            break;
                        case "gender":
                            claimType = "gender";
                            bAddClaim = true;
                            break;
                    }

                    if (bAddClaim)
                    {
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                    }
                }
            }
        };

While debugging at context.user in side foreach loop by putting breakpoint
I am getting following information

{
"sub": "101111724115925537597",
"name": "Alok Nath",
"given_name": "Alok",
"family_name": "Nath",
"profile": "https://plus.google.com/101111724115925537597",
"picture":"https://lh3.googleusercontent.com/XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/
          photo.jpg",
"email": "aloknathbabuji786@gmail.com",
"email_verified": true,
"gender": "male",
"locale": "en"
}

So even after adding the "profile" scope, I don't get birthday as part of return value. I have made sure that profile has Birthday visibility set to public i.e. it is visible to all. Is there any specific scope or specific settings I need to do in order to retrieve Birthday from Google?
Or is there any way to resolve this problem please post the solution

A: I think you need to set scope to https://www.googleapis.com/auth/plus.login in order to get date of birth suggested by this stackoverflow user:
Retrieving date of birth and marital status with Google OAuth API
More information can also be found here:
https://developers.google.com/+/api/oauth#plus.login


text:
Q: how to call an interface method in the same class? I created an interface in a class. I want to call a method of this interface in the same class and just passing parameters to it
public class NewArticle extends JFrame {
    interface NewArticleEvent{
        public void addarticle(String name ,String category,String B);
    }
   .
   .
   .
    JButton add= new JButton("add");
    add.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            /* I want to call 'addarticle' method here * /

        }
    });
   .
   .
   .
}

I want to call my method addarticle here using my 3 defined parameters:

*

*l1.gettext().tostring()

*l2.gettext().tostring()

*l3.gettext().tostring()
because I want to use this method with those parameters in another class.

A: You need to pass an instance of NewArticleEvent in order to use it's methods.
A solution could be to pass to NewArticle class an object that implements NewArticleEvent and call the method where you need to. Further code would be appreciated.


text:
Q: Let $X,Y$ be banach spaces $T,T_n: X\to Y$ and let $T_n \to T$ pointwise, show $T_n \to T$ uniformly on all compact sets Let $X,Y$ be banach spaces $T,T_n: X\to Y$ and let $T_n \to T$ pointwise (weak*), show $T_n \to T$ uniformly on all compact sets.
I reason like this:
I claim that $T_n$ are equicontinuous. That is true as by uniform boundedness principle $\|T_n\|\leq M$ for all $n$. Thus $T_n$ are all lipshitz of constant less than $M$, which means they are equicontinuous. Now Pointwise+equicontinuity imply uniform on a compact sets, and so the result follows. Is this correct? IS there another solution to this problem?

A: Let us assume that $T_n$ does not converge uniformly on every compact set. Then there exists a compact set $K$, an $ε_0 >0$ and a subsequence $(T_n)_{n \in M \subset \mathbb N}$ of the original sequence, as well as  a sequence $(x_n)_{n \in M} \subset K$ such that
$|| T_n (x_n) -L(x_n)|| \geq ε_0$, for all $n \in M$. Since $K$ is compact, we may assume without loss of generality that there exists a $x \in K$ s.t $x_n \to x$. Notice that
\begin{align}
 ε_0& \leq ||(T_n-T) (x_n) || \leq || (T_n-T) (x) || + || (T_n-T)(x_n-x) || \\
 &\leq || (T_n-T)(x)|| + ||T_n-T||_{op} || x_n-x||. ~~~~~~~~~(1)
\end{align}
But, $||x_n -x ||\to 0$ and $|| (T_n-T)(x) || \to 0$. Furthermore, since the sequence of operators $(T_n)$ converges pointwise, it must be pointwise bounded. Applying Banach-Steinhaus thm, we get that $\sup_n ||T_n||_{op}< \infty$. Taking the   $ \limsup_{n \to \infty} $ in (1) we end up with $ε_0 \leq 0$  which is absurd.


text:
Q: Add to Realm List only if doesn't exist I am trying to create a TV Series schema with a list of available Seasons (using RealmJS), I would like to not add duplicate season numbers to the Seasons[] list.
This is what I have:
TvSeries.schema = {
  name: 'TvSeries',
  primaryKey: 'mediaId',
  properties: {
    mediaId: 'string',
    seasons: 'Seasons[]'
  }
}

Seasons.schema = {
  name: 'Seasons',
  primaryKey: 'seasonNumber',
  properties: {
    seasonNumber: 'int'
  }
}

realm.write(() => {
  let season = realm.create('Seasons', { seasonNumber: seasonNumber }, true)
  let tvShow = realm.create('TvSeries', mediaObject, true)
  let seasonsList = tvShow.seasons
  seasonsList.push(season)
})

When I add a new episode (not shown here), it will add the TV Series data and Season again and as there are multiple episodes in a season, it will add to the Seasons[] list multiple times.
My thoughts would be to go through the Seasons[] list and check if it exists, if not then push a new season to it.
Is there a better way of doing this?

A: I would just do a quick check to see if the list already contains the season before inserting:
realm.write(() => {
    let season = realm.create('Seasons', { seasonNumber: seasonNumber }, true)
    let tvShow = realm.create('TvSeries', mediaObject, true)
    let seasonsList = tvShow.seasons
    if (seasonsList.filtered("seasonNumber == $0", season.seasonNumber).length == 0) {
        seasonsList.push(season)
    }
})


text:
Q: Why is "in" operation in Python faster than iterating a list? For example, I want to determine if a certain number a is in a list A. If I use return a in A, this would be much faster than writing an iteration function like
for number in A:
    if a == number:
        return True

What's under the hood? Is Python using a different way as mine to determine the membership? I skimmed the Python documentation but didn't find the answer.

A: 6.10.2. Membership test operations
For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y).
For the string and bytes types, x in y is True if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.
For user-defined classes which define the __contains__() method, x in y returns True if y.__contains__(x) returns a true value, and False otherwise.
For user-defined classes which do not define __contains__() but do define __iter__(), x in y is True if some value z with x == z is produced while iterating over y. If an exception is raised during the iteration, it is as if in raised that exception.
Lastly, the old-style iteration protocol is tried: if a class defines __getitem__(), x in y is True if and only if there is a non-negative integer index i such that x == y[i], and all lower integer indices do not raise IndexError exception. (If any other exception is raised, it is as if in raised that exception).
Information extracted from the Python official page: https://docs.python.org/3/reference/expressions.html


text:
Q: Show that $R^{-1}=R=R \circ R$ implies $R$ is an equivalence relation I was leafing through the "Introduction to Classical Real Analysis" (Stromberg), and while reading the paragraph "Equivalence Relations" in the "Preliminaries" section, I saw:

One checks that any such $R$ [i.e. which is reflexive, symmetric and transitive] satisfies $R^{-1}=R=R \circ R$ and that, conversely, any relation $R$ satisfying these two equalities is an equivalence relation on its domain.

I am not able to prove that $R^{-1}=R=R \circ R$ implies $R$ being reflexive, that is, why if  $R^{-1}=R=R \circ R$ then $$\newcommand{\dom}{\operatorname{dom }} x \in \dom R \implies (x,x) \in R \;?$$
Here the domain of the binary relation $R$ over a set $X$ is defined as $$\dom R = \{x \in X : (x,y) \in R \textrm{ for some } y \in X\}.$$

A: Because it is not true. Suppose that $R=\emptyset$. Then $R^{-1}=R=R\circ R(=\emptyset)$. But, unless the domain itself is the empty set, this is not a reflexive relation.

A: As correctly pointed out by José Carlos Santos, the fact that $R^{-1} = R = R \circ R$ does not imply that $R$ is an equivalence relation over a set $X \neq \emptyset$ in the case of $R = \emptyset$. But it does imply that $R$ is an equivalence relation over the domain of $R$ defined as $\mathrm{dom}(R) = \{x \in X \mid \exists \, y \in X : x \,R\, y\}$ (which is actually what the book you cited claims on p. 3). Let us prove it.

*

*Reflexivity over $\mathrm{dom}(R)$: Let $x \in \mathrm{dom}(R)$. By definition of domain of $R$, there is $y \in X$ such that $x \, R \, y$. Since $R^{-1} = R$, then $y \, R \, x$. Since $R = R \circ R$, from $x \,R\, y$ and $y \,R\, x$ it follows that $x \,R\, x$.

*Symmetry: Let $x \,R\, y$. Since $R^{-1} = R$, then $y \,R\, $.

*Transitivity: Let $x \,R\, y$ and $y \,R\, z$. Then, $x \,R\, z$ because $R = R \circ R$.
Clearly, if to the hypothesis $R^{-1} = R = R \circ R$ we add the further hypothesis $\mathrm{dom}(R) = X$, then $R$ is an equivalence relation over $X$.
Note that the fact that $R^{-1} = R = R \circ R$ with the further hypothesis $R \neq \emptyset$ does not imply the reflexivity of $R$ over $X$ if $X$ has at least two elements. For instance, take $X = \{0,1\}$ and $R = \{(1,1)\}$.

A: Suppose $x$ is in the domain of $R$. Then there exists $y$ with $(x,y)\in R$. Owing to $R=R^{-1}$, we have $(y,x)\in R$. Apply $R\circ R=R$.


text:
Q: how to properly deal with bigdecimal values in ormlite? Is it possible to use sum() function for bigdecimal column in sqlite, since they are stored as varchar? I'm using ormlite for that.

A: If the "bigdecimal" is stored as string (SQLite3 TEXT type), then you cannot use the sum() function.  You have to either (1) extract the fields, convert them to some numeric type, and perform the sum() in your program, or (2) create a custom function in SQLite3 that would do the same, and call that.


text:
Q: jQuery submit event handler only works once I'm validating a simple form with jQuery 1.6 using a .submit() event handler that returns false when the form is not valid:
$(function() {
  $('#my-form').submit(function(event) {
    if (true) {  // for testing, always go through the failure path
      alert("Invalid entry");
      return false;
    } else {
      return true;
    }
  });
});

If the user has made a selection, the form's submitted properly. If the user hasn't made a selection, the alert is shown and the form isn't submitted (again, properly). The problem is that in this case, the submit button no longer works.  In other words, once the failure case occurs, the user stays in the form but clicking on the submit button does nothing.
I've validated the HTML (no duplicate IDs, no names/IDs of "submit", "length", etc.). The form is loaded dynamically so testing with Firebug is a problem. Other event handlers on the form are working fine (e.g., I see alerts when a field value changes). Another oddity: I replaced "return false" with "event.preventDefault(); return true" but the form is still submitted. (I thought .preventDefault() would stop that.)
Any ideas?
EDIT: This approach works:
$(function() {
  $('#my-form :submit').click(function(event) {
    if (...validation stuff goes here...) {
      alert("Invalid entry");
      return false;
    } else {
      $('#my-form').submit();
    }
  });
});

I'd still like to find out what's wrong with my original.submit() event handler approach.

A: Please read this documentation to "$().on" method (this replaces .live())
http://api.jquery.com/on/
Check if your form is not recreated by some ajax method - if it is handler will be discarded.

A: Your form is most probably reloaded with some ajax.
Since ajax reload only part of the page, the $(function() { yourCodeHere }); is not run again. So your onSubmit event handler is not re-attached to your form.
Use this technic to re-attach your onSubmit event handler to your form
$('body').on('submit','#my-form', function() {
    if (true) {  // for testing, always go through the failure path
      alert("Invalid entry");
      return false;
    } else {
      return true;
    }
}

We could translate to human language as "for any change in the body, re-attach the onsubmit event to element with id 'my-form'.

A: if the form is loaded dynamically, you might try binding the event with .live() instead.
like this...
  $('#my-form').live('submit', function(event) {
    if (true) {  // for testing, always go through the failure path
      alert("Invalid entry");
      return false;
    } else {
      return true;
    }
  });

A: There is most likely another event handler being binded elsewhere. Get the chrome extension Visual Event to see, in detail, all handlers attached to the element to see what is blocking it.

A: Also, check to make sure there is no other Javascript interfering.  For example,  Web Forms (.NET) will often have callbacks or some related code to handle postbacks.  Being new to .NET, it was not until I disabled the included scripts/libraries (to test and see) that the problem was resolved.