text:
Q: Batch script failing at 7z command for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set year=%%c
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set month=%%a
for /f "tokens=2-4 delims=/ " %%a in ('date /T') do set day=%%b
set TODAY=%year%
echo %TODAY%
7z a D:\Catalog_Bkp\BKP_%TODAY%.7z D:\Catalog_Backup
pause
exit

When i run this script it is failing at 7z telling that 7z is not recognized as internal or external command but same command wrote in command prompt it is working fine.
7z a D:\Catalog_Bkp\Backup_%DATE:~7,2%.7z D:\Catalog_Backup

A: It seems likely you've placed your 7z.exe in the same folder as your script; if so, try this:
%~dp07z a filename.7z

The %~dp0 tells the script to look for 7z.exe in the same folder as the script, as opposed to in the current working directory.


text:
Q: "Protected Apps" setting on Android phones We can ask the user to protect our app, by using (e.g. Huawei phones):
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
startActivity(intent);

Is there a way of knowing if the app got protected or not? I'm trying to avoid asking the user to protect the app e.g. every time the app is created.
For other intents, I can use:
List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(
                    new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, Uri.parse("package:" + getPackageName()))
                    ,
                    PackageManager.MATCH_DEFAULT_ONLY);

System.out.println("MY_intent_TEST_1(looks always true): "+( list.size() > 0 ) );

PowerManager pwm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

System.out.println("MY_intent_TEST_2(true when whitelisted): "+ pwm.isIgnoringBatteryOptimizations(context.getPackageName()) );

P.S. I'm learning from: "Protected Apps" setting on Huawei phones, and how to handle it

A: Because related interfaces are not exposed, currently you cannot get to know whether the app got protected or not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Running a script at startup that uses xrandr to set display options I've tried numerous methods of getting the following commands to run at startup
xrandr --output DFP10 --rotate left
xrandr --output DFP11 --right-of DFP10

This is necessary because my left monitor is portrait. When I launch Ubuntu Gnome 14.04.2,it sets DFP10 (the portait monitor which is on the left) to be on the right, and does not rotate it to portait).
I have tried putting a script in /etc/rc.local & usr/share/applications, adding the command to startup applications in the form: xrandr --output DFP10 --rotate left && xrandr --output DFP11 --right-of DFP10.
None of these work. Yet, I know that the commands work, if I run them myself in terminal.
Here's some background the situation, that i think might be relevant:
I'm definitely not an expert on this. I know that there a bunch of different config files for editing display options. xorg.conf, xorg.conf~ (a backup), xorg.conf.fglrx-0 and xorg.conf.fglxr-0~ (backup) all exist within /etc/X11 but editing them does not solve my problem.
The situation involving the display driver is fairly complex. I'm running the latest fglrx-updates on my AMD R9 280X, which took some work... I have used a workaround for installing the driver on 14.04.2 (necessary due to bug with LTS Enablement Stacks)
TLDR; how do I make this: xrandr --output DFP10 --rotate left and this xrandr --output DFP11 --right-of DFP10 run at startup?
thanks in advance

A: What you usually need to do in these situations is adding a small break in the command after login. Add this to your Startup Applications:
/bin/bash -c "sleep 15&&xrandr --output DFP10 --rotate left && xrandr --output DFP11 --right-of DFP10"

(If that is the normally working command)
The reason is that most likely the command is performed too early, while the desktop is still loading. It will break then.
You can experiment a little with the sleep 15 duration to see what is needed or possible.


text:
Q: doReturn doesn't act as proxy but calls my method I'm implementing some Unit testing in my app and I have a dependency that relies in the Application context. That dependency returns a list of Item but I want to mock that logic to return whatever I want.
I already know the difference between:
a) when(foo.method1()).return(bar)
b)  doReturn(bar).when(foo).method1()
(b) shouldn't invoke the method.
Now I have a method called in ItemHelper.kt :
fun retrieveItems(): MutableList<Item> {
    val boxStore = BoxStore.getInstance().getBoxFor(Item::class.java)
    return boxStore.all
}

and that .getInstance() relies on the Application.
Since I want to mock it, this is my test:
class ItemHelperTests {

    @JvmField
    @Rule
    var mockitoRule = MockitoJUnit.rule()!!

    @Mock
    private lateinit var itemHelper: ItemHelper

    @Test
    fun itemsNumber_Test() {
        Mockito.doReturn(ArrayList<Item>()).`when`(itemHelper).retrieveItems()

        System.out.println("this line is unreachable")
    }
}

but that ends calling my code:
java.lang.Exception: Please init BoxStore.boxStore in the MainApplication

    at com.example.dependencies.coreData.BoxStore$Companion.throwBoxStoreNotInitialized(BoxStore.kt:33)
    at com.example.dependencies.coreData.BoxStore$Companion.getInstance(BoxStore.kt:26)
    at com.example.helpers.coreData.Item.ItemHelper.retrieveItems(ItemHelper.kt:20)
    at com.example.helpers.ItemHelperTests.itemsNumber_Test(ItemHelperTests.kt:27)

so that method is called, I just want to retrieve an empty ArrayList() when that method is called from JVM.

EDIT
When using @RunWith(MockitoJUnitRunner::class)
I get the same error, but I get one more line of Mockito error:
java.lang.Exception: Please init BoxStore.boxStore in the MainApplication

    at com.example.dependencies.coreData.BoxStore$Companion.throwBoxStoreNotInitialized(BoxStore.kt:33)
    at com.example.dependencies.coreData.BoxStore$Companion.getInstance(BoxStore.kt:26)
    at com.example.helpers.coreData.Item.ItemHelper.retrieveItems(ItemHelper.kt:20)
    at com.example.helpers.ItemHelperTests.itemsNumber_Test(ItemHelperTests.kt:27)

org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.example.helpers.ItemHelperTests.itemsNumber_Test(ItemHelperTests.kt:27)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

    at org.mockito.internal.runners.DefaultInternalRunner$1$1.testFinished(DefaultInternalRunner.java:69)
    at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
    at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
    at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
    at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
    at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:78)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:84)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

A: In Kotlin every class and method is closed.
I had to define open before retrieveItems(), remaining:
open fun retrieveItems(): MutableList<Item> {
    val boxStore = BoxStore.getInstance().getBoxFor(Item::class.java)
    return boxStore.all
}


text:
Q: Phabricator and Mercurial: arc amend not working because of "immutable local history" I'm trying to setup Phabricator with Mercurial for my team for Code Review. At this point I'm testing different scenarios, and I'm having problems with staked diffs.
Let's say I have rev 1 sent to review, and rev 2 stacked on rev 1. Now change requests come for rev 1. I did the changes and tried to run arc amend. It didn't work.
I got this message:

Usage Exception: This project is marked as adhering to a conservative
  history mutability doctrine (having an immutable local history), which
  precludes amending commit messages.

How can I make Mercurial allow me to amend unpublished revisions?
Thank you!


text:
Q: Validate request using API key from div on external website Hi dear StackOverflow friends.
I'm trying to solve a quite complex solution I have to develop for the company for which I'm working. I have developed an electrical energy calculator in JavaScript and it is located on our own web server as a webpage with a complete DOM (html, head, body and lots of ".css" and ".js" files included).
The problem is that the calculator has to be a part of our customers web page (in a div) where it loads the calculator from our web server. When the company website requests the calculator it has to take a secret API key with the request to our domain that validates the customer and sends the calculator back to the customer with the right view that the customer has payed for.
I have tried an "IFRAME" and it works great but there is no way to send a "SECRET" api key with the request (the company web page needs to be a .html file):
<iframe src="http://localhost/calc/energycalc.php"
        width="815"
        height="572"
        frameborder="0"
        scrolling="no"
        style="border-radius: 7px;">
</iframe>

Also, I have read that iframes are to be avoided so I'm looking for something else.
Now I'm working on a solution where the request order looks like this:

Company website -> company website api folder with secret key in a
  .php script -> our webserver -> return calculator to company .php
  script -> return calculator to company website.

I have tried a couple of jQuery solutions. This ajax call comes from the companies website where the div has an id called 'siteloader' the makes a ajax call to the api folder (which is also located on the companies website) which has an .php script:
$.ajax({
    url: 'http://localhost/customer/api/key.php',
    dataType: 'html',
success: function(data) {
    $('#siteloader').html($(data));
    }});

The key.php script does a cURL request with the secret key as a POST parameter:
$api_key = "9chuPsWJBSpbiphxgxF3ld9pSWQQIEj5dPEkbstj0YReumqQ06"
$url = 'http://localhost/calc/energycalc.php' // our web server
$post_params['key'] = $api_key

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$reply = curl_exec($ch);
curl_close($ch);

echo $reply;

This is not working properly - it does not return any styling.
Please ask if there is something that needs clarification (which there probably is)!
Anyone that has any input on how to solve this problem or improve my solution?
Any help would be greatly appreciated.
Thanks,
David

A: I'm not quite sure I'm following your logic, but let me try to re-state things. You're shooting off an AJAX request to a key.php page on the client's server? And then that key.php page is shooting off a curl request to your remote web server?
Could your jQuery AJAX call just send a request to your remote server? it would pass the secret API key over to the server and receive back the template that you want to drop in place on the clients page? Your server would then validate the API key and act accordingly. If the API key is invalid, then you would send back a 401 (Unauthorized) to the jQuery request and just display a message or do nothing (your choice).
There are a lot of applications that handle things this way (Google Analytics, Disqus, Stackoverflow, etc).
Update: You should look at the "data" option of the jQuery.ajax() method. It allows you to send, obviously, data (your API key) over to the server. You could also embed that in to the URL of the request.
Examples
$.ajax({
  type: "GET",
  url: "/server.php",
  data: { key: "yoursecretkey" }
})
  .done(function( response ) {
    alert( "response back: " + response );
  });

or something using the URL:
$.ajax({ type: "GET", url: "/server.php?key=yoursecretkey" });


text:
Q: How can I check whether a struct has been instantiated? I have a struct that (for the purposes of this question) pretty much mimics the built in Point type.
I need to check that it has been instantiated before using it. When it was Point, I could do this:
if (this.p == null)

But that now generates the following error:

Operator '==' cannot be applied to operands of type 'ProportionPoint' and '<null>'

How can I compare my struct against null? Is there another way to check for instantiation?

A: A struct is a value type - it's never null.
You can check against default(ProportionPoint), which is the default value of the struct (e.g. zero). However, for a point, it may be that the default value - the origin - is also a "valid" value.
Instead you could use a Nullable<ProportionPoint>.

A: A struct can't be null. Its a value type, not a reference type. You need to check against the properties with the default values.  Something like:
if(p.X == 0 && p.Y == 0)

A: because p is struct it never be null so you should compare it to it's default value. In order to check equivalence between your value and dafault value.
 If you use == you will get
cannot be applied to operands of type 'ProportionPoint' and 'ProportionPoint' error

because structs do not get an implementation of  == by default. so you need to  overload the == and != operators in your struct like this:
public static bool operator ==(firstOperand op1,  secondOperand2 op2)
{
    return op1.Equals(op2);
}

public static bool operator !=(firstOperand op1,  secondOperand2 op2)
{
   return !op1.Equals(op2);
}

and then :
if (this.p == default(ProportionPoint))

another option is to use Equals directly:
f (this.p.Equals.default(ProportionPoint))

A: structs are value types and they can never be null contrary to reference types. You could check against the default value:
if (this.p.Equals(default(ProportionPoint)))

A: A struct can never be null, so you can't compare it to null. And a struct is always initialized - if not by you, then by the compiler with default values.

A: Use a nullable:
ProportionPoint? p1 = null;
if (p1 == null) ...

or
if (!p1.HasValue) ...

A: Structs can't be null, but the workaround of checking a struct against its default can give a false negative if you actually want to store values equivalent to the defaults in it at any point.
(For example, a struct with the value (0,0,0) could be an untouched default, or it could be storing the origin point in 3D space.)
Another approach that avoids this false negative issue would be to just add another property to the struct - e.g. a bool or int - to track whether data has actually been stored in it. Then have any constructor that initializes the struct with actual data set this value to true/1. In the default struct, this value will still be false/0, so checking against default(MyStruct) should never give you a false negative even if all other data stored in it matches the default values.
public Struct MyStruct {
    public float x { get; private set; }
    public bool initialized { get; private set; }

    public MyStruct(float _x){
        x=_x;
        initialized = true;
    }
}

A: I made an extension method that only works with structs:
public static bool IsNull<T>(this T source) where T:struct
{
  return source.Equals(default(T));
}

Calling convention:
if(myStruct.IsNull())
  DoSomething();

I understand that it isn't really checking if it's null. However, if I gave it a more precise name, like IsEmpty or IsDefault, in six months I would forget it's there and upon seeing the list of methods available not pick it. It's not technically a null check; but conceptually it is.

A: Unlike a variable or value of a reference type, which is a reference to either zero or one instances of that type, a struct variable or value is a struct instance.  If one has a block of code which starts with {Point myPoint; ...}, and nothing in the block closes over MyPoint (closure occurs when there is a yield return within a block, or when a lambda or anonymous method uses a variable from an enclosing block), then an instance of Point will come into existence sometime before execution enters the block, and may cease to exist at any time after execution leaves the block.  In any context where one can make use of a struct-type variable, the structure exists.
The reason one all structure types are regarded as having a do-nothing default constructor is that structure types come into existence implicitly.  When one performs a statement like Point[] myPoints = new Point[100];, it creates a zero-filled array of 100 Point structures; in the process, 100 zero-filled Point instances instantly come into existence.  In C++, if a type has a constructor, creating an array of that type will call the constructor on every element of the array in sequence before any code is given access to the array as a while.  If an exception is thrown while constructing any element, compiler-generated code will run the deterministic destructor on every element which had been successfully created before the array itself evaporates.  While this is a very powerful feature, including it within .net would have substantially complicated the Framework.

A: You can't check struct on null but you can check on default unitialized value like this:
if (instanceOfYourStruct == default)


text:
Q: Playing video in Gtk in a window with a menubar I have created a video player in Gtk3 using Gstreamer in Python3. It works except when I add a GtkMenuBar (place 2). It will then either show a black screen, or fail with an exception. The exception references the XInitThreads, which I am calling (Place 1) (I took this from the pitivi project) but this does not seem to make a diffrence.
Question: How do I make this work?
Other things I would like to know:

*

*Why would the menubar break this?

*This will clearly break on anything not X, is there some prebuilt component the abstracts this logic and is crossplatform that I am missing?

System:

*

*python3

*Gtk3

*Ubuntu 16.04

The exception:
[xcb] Unknown request in queue while dequeuing
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python3: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.

The code (in as small a form as possible to demonstrate the concept):
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
gi.require_version('GstVideo', '1.0')

from gi.repository import Gtk, xlib
from gi.repository import Gst, Gdk, GdkX11, GstVideo
Gst.init(None)
Gst.init_check(None)

# Place 1
from ctypes import cdll
x11 = cdll.LoadLibrary('libX11.so')
x11.XInitThreads()

# [xcb] Unknown request in queue while dequeuing
# [xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
# [xcb] Aborting, sorry about that.
# python3: ../../src/xcb_io.c:179: dequeue_pending_request: Assertion `!xcb_xlib_unknown_req_in_deq' failed.

# (foo.py:31933): Gdk-WARNING **: foo.py: Fatal IO error 11 (Resource temporarily unavailable) on X server :1.

class PipelineManager(object):
    def __init__(self, window, pipeline):
        self.window = window
        if isinstance(pipeline, str):
            pipeline = Gst.parse_launch(pipeline)

        self.pipeline = pipeline

        bus = pipeline.get_bus()
        bus.set_sync_handler(self.bus_callback)
        pipeline.set_state(Gst.State.PLAYING)

    def bus_callback(self, bus, message):
        if message.type is Gst.MessageType.ELEMENT:
            if GstVideo.is_video_overlay_prepare_window_handle_message(message):
                Gdk.threads_enter()
                Gdk.Display.get_default().sync()
                win = self.window.get_property('window')

                if isinstance(win, GdkX11.X11Window):
                    message.src.set_window_handle(win.get_xid())
                else:
                    print('Nope')

                Gdk.threads_leave()
        return Gst.BusSyncReply.PASS

pipeline = Gst.parse_launch('videotestsrc ! xvimagesink sync=false')

window = Gtk.ApplicationWindow()

header_bar = Gtk.HeaderBar()
header_bar.set_show_close_button(True)
# window.set_titlebar(header_bar)  # Place 2

drawing_area = Gtk.DrawingArea()
drawing_area.connect('realize', lambda widget: PipelineManager(widget, pipeline))
window.add(drawing_area)

window.show_all()

def on_destroy(win):
    try:
        Gtk.main_quit()
    except KeyboardInterrupt:
        pass

window.connect('destroy', on_destroy)

Gtk.main()

A: When searching through documentation on a separate issue, I came across a reference to the gtksink widget. This seems to be the correct way to put video in a gtk window, but unfortunately none of the tutorials on this use it.
Using the gtksink widget fixes all the problems and greatly reduces code complexity.
The revised code:
from pprint import pprint

import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
gi.require_version('GstVideo', '1.0')

from gi.repository import Gtk, Gst
Gst.init(None)
Gst.init_check(None)

class GstWidget(Gtk.Box):
    def __init__(self, pipeline):
        super().__init__()
        self.connect('realize', self._on_realize)
        self._bin = Gst.parse_bin_from_description('videotestsrc', True)

    def _on_realize(self, widget):
        pipeline = Gst.Pipeline()
        factory = pipeline.get_factory()
        gtksink = factory.make('gtksink')
        pipeline.add(gtksink)
        pipeline.add(self._bin)
        self._bin.link(gtksink)
        self.pack_start(gtksink.props.widget, True, True, 0)
        gtksink.props.widget.show()
        pipeline.set_state(Gst.State.PLAYING)

window = Gtk.ApplicationWindow()

header_bar = Gtk.HeaderBar()
header_bar.set_show_close_button(True)
window.set_titlebar(header_bar)  # Place 2

widget = GstWidget('videotestsrc')
widget.set_size_request(200, 200)

window.add(widget)

window.show_all()

def on_destroy(win):
    try:
        Gtk.main_quit()
    except KeyboardInterrupt:
        pass

window.connect('destroy', on_destroy)

Gtk.main()


text:
Q: A question of strict inequality and Riemann integral Question:
Let $f : [a, b] \to \mathbb{R}$ be a continuous function such that $f(x)\ge0$ for all
$x \in [a, b]$ and such that $f(c) \gt 0$ for some $c \in [a, b]$. Prove that
$ \int^a_b  f > 0$.
What I have determined so far is that since $f$ is continuous on $[a,b]$, it follows that $f\in \mathbb{R}_{[a,b]}$ (Riemann Integrable). It also follows that since $\forall x \in [a,b]$, $f(x)\ge0$, then $\int^a_bf\ge0$.
Now I need to show that this is a strict inequality. I suspect I have to use the fact that $f(c) \gt 0$ for some $c \in [a, b]$
My thought was that since $f(c) > 0$, $f(b)\ge0$, and $f(a) \ge 0$, then $\int^b _a f = (\int^c_a f + \int^b_cf) \gt 0$ by virtue of the fact that $a \neq b$ and since $c \in [a,b]$, possibly $c=a$ or $c=b$ but not both. So either $\int^c_a f\gt0$ or $\int^b_cf\gt0$. So it must be that $\int^b _a f = (\int^c_a f + \int^b_cf) \gt 0$.
This is probably wrong so any corrections and help would be appreciated.

A: Since $f(c) > 0$, show that by continuity of $f$, $f(x) > \frac{f(c)}{2}$ for all $x$ in a closed interval $[\alpha,\beta]$ containing $c$. Then as $f \ge 0$, $$\int_a^b f \ge \int_\alpha^\beta f \ge \frac{f(c)}{2}(\beta - \alpha) > 0.$$

A: Due to continuity, since $f(c)>0$,  you must have an entire neighborhood of $c$ that is bounded away from 0 (neighborhood within the domain $[a,b]$).
We can express that neighborhood as for some $\epsilon>0$,  $(c-\epsilon ,c+\epsilon )\cap [a,b]$.  You may want to take some cases on whether $c=a,c=b$ just for the one sided $[a,b]$,  but the important part of the argument is that we have an entire open, positive length interval that's a subset of $[a,b]$ where $f>0$.  Pick two points inside that open interval, so that the function is strictly positive inside the closed interval.   Now, divide your integral from $[a,b]$  into integrals inside the closed interval where it's strictly positive and the other 1 or 2 regions. (depending on whether you're in the middle, left, or right).
Since f is strictly positive on the little one, the integral is strictly positive. Add to that numbers that are at least 0, and you are still strictly positive.


text:
Q: how to use svg:defs to create rect with same height in d3.js? I am working on a d3.js project where I am displaying a number of rectangles to be the same height. The rectangles are connected to a input[type=number] that adjust the height of each group of rectangles. To make animation easier (so I only have to manipulate the svg:defs onchange of the number input), I would like to be able to specify the height of a group of rectangles with a svg:def tag like this:
var svg = d3.select("body").append("svg")
    .attr("width", 960)
    .attr("height", 500);
svg.append("defs").selectAll(".rectdef")
  .data(data).enter()
  .append("rect")
  .attr("class", "rectdef")
  .attr("id", function (d, i){return "rect" + d.name;})
  .attr("x", 0)      // overridden below
  .attr("width", 0)  // overridden below
  .attr("y", 0)      // overridden below
  .attr("height", function (d, i){return d.height});

and then to be able to just refine placement x, y and width of the rectangles with something like this:
svg.selectAll(".bar")
  .data(data).enter()
  .append("use")
  .attr("class", "bar")
  .attr("xlink:href",function (d){return "#rect"+d.type;})
  .attr("x", function(d) { return d.x })
  .attr("width", function (d) {return d.w;})  // this does NOT adjust width!
  .attr("y", function (d) {return 0;});

This snippet correctly changes the x and y coordinates but it does not properly change the width! Any ideas what's wrong here? Is this a browser issue (I'm using Chrome 24.0.1312.52)? Is width not editable like this on an svg:use tag?
There aren't any problems with the data (I've checked that) and I have been able to confirm that the animation does work correctly.

A: If you point a <use> element at a <rect> the width/height of the <use> are ignored according to the SVG specification
I recomment you put the <rect> in a <symbol>, and then have the use reference the symbol. That way the width/height of the use will apply to the rect. You probably want to make the rect's width/height 100% within the symbol.
In other words, something like this should work:
svg.append("defs").selectAll(".rectdef")
  .data(data).enter()
  .append("symbol")
  .attr("class", "rectdef")
  .attr("id", function (d, i){return "rect" + d.name;})
  .append("rect")
  .attr("x", 0)           // overridden below
  .attr("width", "100%")  // overridden below
  .attr("y", 0)           // overridden below
  .attr("height", function (d, i){return d.height});

svg.selectAll(".bar")
  .data(data).enter()
  .append("use")
  .attr("class", "bar")
  .attr("xlink:href",function (d){return "#rect"+d.type;})
  .attr("x", function(d) { return d.x })
  .attr("width", function (d) {return d.w;})  // this correctly adjusts width!
  .attr("y", function (d) {return 0;});


text:
Q: Не получается сортировать по дате используя distinct У меня таблица из ссылок. Многие повторяются.
| id | url | camp_send_date |

Я обрезаю не нужные части ссылок и выбираю одинаковые части как distinct и их вывожу. Но почему то используя distinct не сортирует по дате
SELECT DISTINCT TRIM( TRIM(LEADING SUBSTRING_INDEX(url, '/', 3) FROM TRIM(TRAILING SUBSTRING_INDEX(url, '/', -1)  FROM url))) AS url
FROM stats
WHERE  url NOT LIKE '%wp-content%' AND camp_name NOT LIKE '%test%' AND DATE(camp_send_date) > DATE_SUB(CURDATE(), INTERVAL 90 DAY)
GROUP BY camp_send_date DESC
ORDER BY camp_send_date DESC

A: Пробуй
SELECT TRIM( TRIM(LEADING SUBSTRING_INDEX(url, '/', 3) FROM TRIM(TRAILING SUBSTRING_INDEX(url, '/', -1)  FROM url))) AS domain
FROM stats
WHERE url NOT LIKE '%wp-content%'
  AND camp_name NOT LIKE '%test%'
  AND camp_send_date > CURDATE() - INTERVAL 90 DAY
GROUP BY domain
ORDER BY MAX(camp_send_date) DESC


text:
Q: Hadoop stream sorting Could anyone help on this hadoop streaming sort problem? Thanks for any suggestions in advance.
I am newbie on Hadoop and need to implement a sort function on a 500GB tab delimited text file. The following is an example input, there are 3 fields in one line like READA14 chr14   50989. Here I need to numeric sort by the 2nd and 3rd column, unless I set number of reducers to 1, I will never get the correct ordering result.
Example Input:

READA14 chr14   50989
READB18 chr18   517043
READC22 chr22   88345
READD10 chr10   994183
READE19 chr19   232453
READF20 chr20   42912
READF9  chr9    767396
READG22 chr22   783469
READG16 chr16   522257
READH9  chr9    826357
READH16 chr16   555098
READH21 chr21   128309
READH4  chr4    719890
READH18 chr18   944551
READH22 chr22   530068
READH9  chr9    212247
READH11 chr11   574930
READH22 chr22   664833
READH2  chr2    908178
READH22 chr22   486178
READH7  chr7    533343
READH6  chr6    109022
READH15 chr15   316353
READH20 chr20   439938
READH21 chr21   731912
READH11 chr11   81162
READH2  chr2    670838
READH15 chr15   729549
READH3  chr3    196626
READH14 chr14   841104

My code of streaming sort:

hadoop jar \
/home/hadoop-0.20.2-cdh3u5/contrib/streaming/hadoop-streaming-0.20.2-cdh3u5.jar \
-input /user/luoqin/projects/samsort/number \
-output /user/luoqin/projects/samsort/number_sort \
-mapper "cat" \
-reducer "sort -k 2.5 -n -k 3" \
-partitioner org.apache.hadoop.mapred.lib.KeyFieldBasedPartitioner \
-jobconf map.output.key.field.separa="\t" \
-jobconf num.key.fields.for.partition=1 \
-jobconf mapred.data.field.separator="\t" \
-jobconf map.output.key.value.fields.spec="2:0-" \
-jobconf reduce.output.key.value.fields.spec="2:0-" \
-jobconf mapred.reduce.tasks=50

Results were partitioned into 50 parts cause reduce.task is set to 50. Viewing the results as, however it was not correct unless reduce.task is set to 1:

   hadoop fs -cat /user/projects/samsort/number_sort/*

A: BY default hadoop uses a hash partitioner - in that the key output from your mapper 'hashed' to determine which reducer that key should be sent to. This hashing is what's causing your 'incorrect' results when you use more than a single reducer.
You should note that each output part is sorted, and now you just need to interleave the different parts to get your single sorted output.
You can solve this problem by implementing your own partitioner and sending key,value pairs to a reducer depending on the chrx value in your second field. You will however need couple your partitioner implementation and the number of reducers, otherwise you'll still similar to results to what you have at the moment.
So if you know the domain or range of values of your second column (lets say chr0 to chr255) then you could run a 256 reducer job with a custom partitioner based upon the int value after the chr string


text:
Q: executing command through popen in linux I am executing commands through popen(), system() in my c++ application. Every command is executing successfully and getting results as expected. But whenever I am trying any command with lpstat (displays information of printers and jobs), getting no results.
Note : I take same code in my test app, and it runs fine. lpstat gives results as expected.
So is there anything, which is blocking to execute lpstat command ?
Thanks in advance !!!
I am calling this method in main, passing command "lpstat -W all" or any lpstat command with diffrent options not executing. Wherever other commands are working fine.
here is my code Sample :
**
std::string ExecQueryRun(std::string lcCommand)
{
    std::string Result;
    FILE * stream;
    if (lcCommand.empty())
        return "Bash Command is empty ";

    char ReadBuffer[MAX_BUFFER + 1] = {0};
    lcCommand.append(" 2>&1");
    stream = popen(lcCommand.c_str(), "r");
    if (stream)
    {
        while (!feof(stream))
        {
            if (fgets(ReadBuffer, MAX_BUFFER, stream) != NULL)
            {
                Result.append(ReadBuffer);
            }
        }
        pclose(stream);
    }
    else
    {
        cout << "popen fails in ExecQueryRun " << endl;
    }

    return Result;
}

void main()
{
   cout << "Result :: " << ExecQueryRun("lpstat -W all") << endl;

   /* some other code here */

  getchar();
  return;
}

**


text:
Q: Segmentation fault disappears when debugging with GDB I am having a segmentation fault while running this code: http://ideone.com/yU80Bd
The problem is when I run it in GDB, the code runs fine and excellent. Why is this running in gdb with no segfault but running every other place with a segmentation fault?
Here is the problem I am trying to solve: http://www.codechef.com/DEC13/problems/CHODE

A: The problem is that your input includes characters that are not in the range [a-Z]. For example: ! That causes the vector to be accesed at invalid indexes.
You can check these things running your program with valgrind.
valgrind ./ideone < stdin
...
==2830== Invalid read of size 4
==2830==    at 0x40111A: main (ideone.cpp:53)
...
==2830== Invalid write of size 4
==2830==    at 0x401120: main (ideone.cpp:53)

The problem is in these lines:
    for(int i=0;i<cipherText.size();++i)
    {
        char c = tolower(cipherText[i]);
        ++(cipherF[c-97].frequency);
    }

c - 97 may be lower than 0.
You can check, for example:
    for(int i=0;i<cipherText.size();++i)
    {
        char c = tolower(cipherText[i]);
        if (c < 'a' || c > 'z') continue;
        ++(cipherF[c-97].frequency);
    }


text:
Q: wpf How to set xctk:ColorPicker default color EDIT: I actually managed to fix the problem, I was doing Binding Value.Color instead of Binding Color, which was previously set. Thanks for the help anyway!
I'm making a GUI that has a xctk:ColorPicker in xaml:
<GridViewColumn.CellTemplate>
    <DataTemplate>
        <xctk:ColorPicker SelectedColor="{Binding Value.Color}"  Width="40"/>
    </DataTemplate>
</GridViewColumn.CellTemplate>

Currently, the default color of the selector is Blue, I would like to change it to black. How do i accomplish this?

A: The color picker shows the default color from your binded property value
so in this case if your property Value.Color return blue then it will be blue
So by changing the property color to black would change it to black
but in case if you do not want to change the property value then you could make use of a placeholder property with default value of black and update the source when it changes
example for placeholder approach
<Grid Background="{Binding Value}">
    <xctk:ColorPicker SelectedColor="{Binding PlaceHolder}"  Width="40" VerticalAlignment="Center"/>
</Grid>

view model
bool isDefault = true;
public Color PlaceHolder
{
    get
    {
        if (isDefault)
            return Colors.Black;

        return Value.Color;
    }
    set
    {
        Value.Color = value;
        isDefault = false;
    }
}

public SolidColorBrush Value { get; set; }

in above example I assumed Value of type SolidColorBrush, and I initialized it as Value = new SolidColorBrush(Colors.Green);

A: If you're using .NET 4, then you can change the Background colour of the selected row in the GridView by simply defining a few Resources... just add these to your GridView.Resources collection:
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Blue" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Blue" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" />


text:
Q: How do you actually install ndiswrappers without internet connection? How do you install ndiswrappers without internet connection because the link for that in the following link doesn't work:
https://help.ubuntu.com/community/WifiDocs/Driver/Ndiswrapper
and I need to be able to install the driver for a Linksys AE3000 wireless network adapter to practice the lab for my wireless networking class in the class room during my instructors office hours. I tried to do this on my own, but I hit a dead end when I realized the link that explains how to do this doesn't work when I was in the class room practicing.


text:
Q: Determining the convex hull of the union of two polyhedra I'm doing an introductory course to linear programming and I'm working through some exercises to prepare for the final exam, I'm stuck on an exercise and I would really appreciate a hint:

Let $a\in \mathbb{R}^n $ where $\Vert a\Vert = \sqrt{a^T a}=1\,$ and let$\,\,b_1 , b_2 \in \mathbb{R}$ with $b_1 < b_2$. Define $H_1=\{ x\in \mathbb{R}^n : a^Tx=b_1\}$ and $H_2=\{ x\in \mathbb{R}^n : a^Tx=b_2\}$
Determine the convex hull of $H_1 \cup H_2$

The first thing I would do here is to define $C=\{ x\in \mathbb{R}^n : b_1 \leq a^Tx \leq b_2\}$, which is a polyhedron and therefore convex, and so $conv( H_1 \cup H_2) \subset C$.
$conv(S)$ here means the intersection of all convex sets that contain $S$.
I just need to show that $C \subset conv( H_1 \cup H_2)$, but I don't really know where to start.
Thanks in advance!

A: Hint: $H_1$ and $H_2$ are hyperplanes, so what happens if you take any old halfspace $H'= \{x \mid (a')^T x \leq c \}$ for $a\neq a'$? Does $H'$ contain $H_1$ or $H_2$? Why or why not?


text:
Q: How to set git client certificate for client authentication? I have my own git repository running under jetty-9.
I want to know how can i set the git client certificate so my git server (jetty server) would be able to receive the certificate in servlet request and be able to get the git client certificate ad in order to do client authentication.
Following command i am trying to run,
git -c http.sslcainfo=D:\jetty\punws-sohanba.sigmasys.net.crt \
    -c http.sslCert=D:\jetty\curl-ca-bundle.crt \
    clone "https://punws-sohanba.sigmasys.net:8443/git.ctr-0.0.1-SNAPSHOT/dashboard-portal/.git"

Where "punws-sohanba.sigmasys.net.crt" is my server cert in order to git-client should accept the self signed certs.
curl-ca-bundle.crt is the git cert set in global config of git and also i am explicitly trying to set it via command line as well. (i am not sure i am doing it this right way). This curl-ca-bundle.crt file is also imported to my server.jks file as truststore.
On server i am not able to get the certificates when i do:
X509Certificate[] certs = (X509Certificate[])req.getAttribute(
    "javax.servlet.request.X509Certificate");
System.out.println(
    "cert name from git client =========>> " + certs[0].getSubjectDN().getName()
); //returns null-pointer here

I gives following error on commandline :
fatal: unable to access 'https://punws-sohanba.sigmasys.net:8443/git.ctr-0.0.1-SNAPSHOT/dashboard-portal/.git/': unable to set private key file: 'D:\jetty\curl-ca-bundle.crt' type PEM

Please suggest.

A: It's quite difficult to read unbroken lines in this way, and it's not very clear how you are trying to achieve authentication with a CA bundle as a private key (which won't work - CA's a certificates, don't have a private component), can you clarify how many certificates and private keys you have got?
You'll need to read some materials on how TLS authentication is working.
In case you just need some rough direction, for a peer (client or server) to be authenticated, it needs a public key within a certificate, and a private key, and for the other side to trust it, the other side will need the issuer CA (or the self signed cert) as a trusted one.
The usual configuration is then a certificate PLUS the private key for the certificate for the server, and a CA bundle, or at least the single issuer CA configured on the CLIENT as a trusted curtificate.
With client authentication, in addition to that, you'll need a similar configuration on the client side: a certificate for the client PLUS the private key for it, and a configuration on the server (or at least the single issuer certificate on the SERVER as a trusted certificate).
It won't work if you have only a single self-signed certificate, you'll need one (self-signed, or CA issued) for the server and the client as well.
You can't just copy the certificate part from the server to authenticate the client.  This part is sufficient for the client to trust the server, but without a private key, it cannot be used for cryptographic authentication.
The above command line is just showing you try to use a list of public certificates (the CA bundle) as a private key - have you got an actual certificate with a private key?


text:
Q: Proving path length, transitive closure Set A is finite with n elements. Suppose a and b are elements of a set A with a != b. Let R be a relation on the set A so that there is a path from a to b of length at least 1. Show there is a path from a to b of length not exceeding n − 1.
I understand the proof for when a does equal b. And though I understand conceptually how this proof works, I am unable to put it in words.

A: I will try to explain using less formal language.
Assume there is a path at least one in relation $R$ on Set $A$ from $a$ to $b$. Let $m$ be the shortest length of such path, so $x_0,x_1,x_2,...,x_{m-1},x_m$ is the path where $x_0 = a$ and $x_m = b$.
In the case when $a = b$, suppose $m > n$, we have $n$ vertices in total in the set $A$, so among the $m$ vertices $x_0,x_1,x_2,...,x_{m-1}$, there will be at least two vertices that are equal, according to the pigeonhole principle.
If two vertices are equal, then there will be a loop in the path and we can get rid of the loop to obtain the shortest path, so there will be at least $n$ path (i.e., $m = n$).
In the case when $a \not = b$, among the $m$ vertices $x_0,x_1,x_2,...,x_{m-1}$, no vertices can be equivalent to $b$, otherwise $m$ will not be the shortest path from $a$ to $b$. So there will be $n-1$ choices of vertices for the $m$ vertices. If $m > n - 1$, then by the pigeonhole principle, at least two vertices will be the same. Then if two vertices are equal, we can again get rid of the loop and obtain the shortest path, so there will be at least $n-1$ path.

A: Let $P_0 = \{a\}$, and let $P_{k+1} = P_k \cup \{x | \, yRx \text{ for some } y \in P_k \}$. $P_k$ is the set of elements reachable in $k$ or fewer steps
starting from $a$.
Note that $P_k \subset P_{k+1}$ and $P_k \subset A$ for all $k$, hence
$|P_0| \le |P_k| \le |P_{k+1}| \le |A|$.
Hence there is some $m$ such that $|P_0| < |P_2| < \cdots < |P_m|$ are strictly nested, and $P_{k+1} = P_k$ for all $k \ge m$. It follows from
this that $m \le n-1$.
Since there is a path from $a$ to $b$, we must have $b \in P_l$ for some $l$.
If $l \le n-1$ then we have the desired result. If $l > n-1$, we note that
$P_l = P_m$, and hence there is a path from $a$ to $b$ of length $\le m \le n-1$.


text:
Q: Calculating the complexity of the function I have writing a function for calculating the length of longest increasing sequence. Here arr[] is array of length n. And lisarr is of length of n to store the length of element i.
I am having difficulty to calculate recurrence expression which is a input for master theorem.
int findLIS(int n){
        if(n==0)
            return 1 ;
        int res;
        for(int i=0;i<n;i++){
            res=findLIS(i);
            if(arr[n]>arr[i] && res+1>lisarr[n])
                lisarr[n]=res+1;
        }
        return lisarr[n];
    }

Please give the way to calculate the recurrence relation.
Should it be
T(n)=O(n)+T(1)?

A: It is O(2^n). Let's calculate exact number of iterations and denote it with f(n). Recurrence relation is f(n) = 1 + f(n-1) + f(n-2) + .. + f(1) + f(0), with f(1)=2 and f(0)=1, which gives f(n)=2*f(n-1), and finally f(n)=2^n.
Proof by induction:
Base n=0 -> Only one iteration of the function.
Let us assume that f(n)=2^n. Then for input n+1 we have f(n+1) = 1 + f(n) + f(n-1) + .. + f(1) + f(0) = 1 + (2^n + 2^(n-1) + .. + 2 + 1) = 1 + (2^(n+1) - 1)=2^(n+1).. Number one at the beginning comes from the part outside of the for loop, and the sum is the consequence of the for loop - you always have one recursive call for each i in {0,1,2,..,n}.


text:
Q: What is the best way to integrate a CMake project into Buck? I am using Buck for my own C++ project, but I depend on a third-party library that is built using CMake. The CMake file is complex, so I do not think it is practical to recreate their CMake file in Buck. Instead, I would like to call CMake from Buck.
What is the best way to call CMake from Buck?
How should I structure my project to minimise headaches?

A: My suggestion is using genrule and prebuilt_cxx_library.
This is my Buck study project using Google Test:
https://github.com/ar90n/lab/tree/master/sandbox/buck-study/gtest
This project contains two Buck files. The one (./gtest/BUCK) is for fetching and building Google Test. The another (./BUCK) is for building and running test programs.
If you want to build and run this project, please execute the following commands,
$ buck fetch //gtest:googletest-src
$ buck build :sample1
$ buck run :sample1

A: Calling CMake will break reproducibility, so it isn't the best approach. Instead, try the following:

*

*Fork the project that builds with CMake.

*Call CMake to generate any header files.

*Save the header files somewhere in the project (e.g. /cmake-generated).

*Create a header-only library of the header files generated by CMake.

*Build the rest of the project with Buck, depending on the CMake library.

*Commit everything to Git.

*Repeat step 2 for every target that you require.

This is not as good as a true port to Buck, but you get most of the benefits for a one-time manual step.


text:
Q: Sorting MySQL with several fields to choose from I have a portfolio which I would like to have listed in ASC sort order, according to several fields to choose from on top of the list. Without sorting the printout is perfect, but when activating the sort statement (line 35) I get the following error message:

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
  result resource in /home/domain/public_html/db_name/portfolio.php on
  line 47

Can somebody please help and tell me what to do with this code? Many thanks for any advice:

<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Portfolio</title>
<link rel="stylesheet" type="text/css" href="../scripts/css/formate.css" />

<?php
 // Connects to Database
 mysql_connect("localhost","user","passw") or die(mysql_error());
 mysql_select_db("db_name") or die(mysql_error());
 ?>

        Order by Villa name   |
        Order by no. of Beds   |
        Order by Sleeps

<?php
// sort table as selected
$orderBy = array('ref_id', 'bedrooms', 'max_occupants');
$order = 'ref_id';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
    $order = $_GET['orderBy'];
}

// Read table ---> and sort it:

// $data = mysql_query("SELECT * FROM res_properties");

 $data = mysql_query("SELECT * FROM db_row ORDER BY '.$order");

 Print "
";
 Print "

Portfolio

";
 echo 'Listings as per: -       ';
 print date('r');
 print "\\n";
 Print "

";

 Print "
";
 Print "
Villa Name	Beds	Baths	Sleeps	Property Website 	Prop.ID
";

   while($info = mysql_fetch_array( $data ))

{

 Print "
";
 Print "".$info['ref_id'] . "	 ";
 Print "".$info['bedrooms'] . " 	";
 Print "".$info['bathrooms'] . " 	";
 Print "".$info['max_occupants'] . " 	";
 Print "Open website here	";
 Print "".$info['id'] . "
 ";

 }
 Print "
";
 ?>

A: I think its simply how your building your query.
 $data = mysql_query("SELECT * FROM db_row ORDER BY '.$order");

to
 $data = mysql_query("SELECT * FROM db_row ORDER BY " . $order);

If that doesn't work add mysql_error after execution of that statement and see what the error is.

A: try
$data = mysql_query("SELECT * FROM db_row ORDER BY '$order'");

or
 $data = mysql_query("SELECT * FROM db_row ORDER BY " . $order."'");

NOTE 2 : Use of mysql_* function are deprecated even it will generate E_DEPRECATED warning in php5.5 so use PDO or MySQLi instead if you want to learn pdo here is good tutorial

A: Maybe you are looking for something like this?:
$data = mysql_query('SELECT * FROM db_row ORDER BY ' . $order . ' ASC');

In order to do ascending and descending sorting, you need to add another parameter to your link. Should it be asc or desc by default is your call, whatever makes more sense. In this case I made 0 for ascending and 1 for descending.

The next thing you want to do is to add logic for sort handling:
$sortBy = array('asc', 'desc');
$sort = 0;
if (isset($_GET['sort']) && in_array($_GET['sort'], array_keys($sortBy))) {
    $sort = $_GET['sort'];
}

And the last thing to do is the change of asc to desc and vice versa when you click the link second time. If you put the code I provided (logic for sort handling) and the code for the $order handling above your navigation table (to make the variables accessible within the table), you can add a condition into the link:
<a href="?orderBy=ref_id&sort=<?php echo ($order == 'ref_id' ? !$sort : 0); ?>">

And you MySQL query will look something like this:
$data = mysql_query('SELECT * FROM db_row ORDER BY ' . $order . ' ' . $sortBy[$sort]);


text:
Q: Get string response How to get 'ssl_result_message' from this string (it a curl response):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- process-transaction-response -->

<html>
<head>
    <meta content=
    "1;url=http://www.xxx.com/perfect-process-status.php?ssl_email=&ssl_status=TEST+MODE&ssl_cvv2_response=P&ssl_ship_to_phone=&ssl_last_name=&ssl_ship_to_country=&ssl_ship_to_state=&ssl_eci_ind=&ssl_account_balance=0.00&ssl_ship_to_zip=&ssl_get_token=&ssl_token=&ssl_result_message=APPROVED&ssl_token_response=&ssl_country=&ssl_city=&ssl_phone=&ssl_invoice_number=1876&ssl_ship_to_address2=&ssl_ship_to_address1=&ssl_txn_id=00000000-0000-0000-0000-00000000000&ssl_result=0&ssl_customer_code=14&ssl_ship_to_company=&ssl_avs_response=X&ssl_approval_code=123456&ssl_ship_to_last_name=&ssl_avs_zip=&ssl_exp_date=0415&ssl_ship_to_city=&ssl_ship_to_first_name=&ssl_avs_address=&ssl_address2=&ssl_first_name=&ssl_amount=30.00&ssl_state=&ssl_card_number=37**********0005&ssl_txn_time=10%2F29%2F2013+02%3A28%3A11+AM"
    http-equiv="refresh">
    <style type="text/css">
         BODY, TD, INPUT, SELECT, TEXTAREA, BUTTON, .normal {font-family:arial,helvetica,sans-serif; font-size:10pt; font-weight:normal; } .small {font-size: 10pt} .medium {font-size: 14pt} .large {font-size: 18pt}
    </style>

    <title></title>
</head>

<body>
    <form action="#" id="frmMenu" method="post" name="frmMenu">
        <input name="dispatchMethod" type="hidden"> <input name=
        "permissionDesc" type="hidden"> <input name="menuAction" type="hidden">
        <input name="thClientID" type="hidden" value="">
    </form>
</body>
</html>

this is response from:
print_r(htmlspecialchars($post_response));

A: try preg_match:
if (preg_match('/ssl_result_message\=([^&]+)/m', $response, $match)) {
    var_dump($match);
}

and the result is:
array(2) {
  [0]=>
  string(27) "ssl_result_message=APPROVED"
  [1]=>
  string(8) "APPROVED"
}


text:
Q: Module overriding in Joomla 1.6 I am new to Joomla, started learning it just a day ago and didn't manage to find an answer to my question in the docs (which suck real bad compared to Drupal).
So what I want to do is override the whole module in a template. The documentation only suggests I can override the markup of a module by placing corresponding files in the html folder, but I have to make some corrections to the actual logic. Is copying the module, changing and then installing it as a separate entity the only way to go? I mean it makes sense that "template" folder is for "views" but with the kind of application I have to develop it is gonna be annoying...

A: Yeah, you can only override views.
If you want to override logic, you have 2 options:

*

*Change the actual logic in-place, which leads to problems on updating etc

*Duplicate the module and change the logic, as you suggested

A: One other way to consider is to replicate or fix the logic in the template. While this is not a very slick way of doing it, it is faster, especially than duplicating a whole component.
Note that you can also add your own libraries to the Joomla libraries folder to centralize your own code.
Further, if you manage your code with (for example) svn, you should not have any problems on upgrades with creating new views that may include their own logic.


text:
Q: Jquery ui tooltip doesn't displayon button tag I have this simple button tag:
<button class="toolb">this is a button</button>

This is my code:
$(".toolb").tooltip({ content: "example tooltip!" });

I hover the mouse on the button, but no tooltip is displayed. How come?

A: Your button needs a title attribute to work, even if it's empty:
<button class="toolb" title="">this is a button</button>

jsFiddle example

A: Try:
<button class="toolb" title="example tooltip!">this is a button</button>
<script>
$(document).tooltip();
</script>


text:
Q: view become unresponsive after using KGModal and DTAlertView I have an app where I am using DTAlertView & KGModal.
All is working perfectly. The only problem comes when I show DTAlertView over KGModal.
Let me explain working scenario.

*

*Click button and show modal

*Modal comes

*Tap outside of modal to dismiss

*Click again button to show modal.

*Modal comes

Below is the scenario which is not working

*

*Click button and show modal

*Modal comes

*Click button that in inside modal to show alertview.

*alertview comes

*click dismiss button to dismiss alertview

*alertview get dismissed

*Tap outside of modal to dismiss

*Click again button to show modal.

*Nothing comes (Here is the problem. Now the whole view is un-responsive)

Any idea what is going on?
Below is the link for sample download of project.
Sample Project
Code I have is as below.
- (IBAction)showModal:(id)sender {
    UIView *contentView  = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 300, 280)];
    contentView.backgroundColor = [UIColor blackColor];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button addTarget:self
               action:@selector(bringAlertBox)
     forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Show Alert" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 200, 300, 40.0);
    button.backgroundColor = [UIColor whiteColor];
    button.titleLabel.textColor = [UIColor blackColor];
    [contentView addSubview:button];

    [[KGModal sharedInstance] showWithContentView:contentView andAnimated:YES];
}

-(void) bringAlertBox {
    NSLog(@"bringAlertBox");
    DTAlertView *myAl = [DTAlertView alertViewWithTitle:@"WOW Alert" message:@"I like this alertview...." delegate:nil cancelButtonTitle:@"Dismiss" positiveButtonTitle:nil];
    [myAl setDismissAnimationWhenButtonClicked:DTAlertViewAnimationSlideTop];
    [myAl showWithAnimation:DTAlertViewAnimationSlideBottom];
}

A: Not sure what was the problem, however when I hide below line in DTAlertView.m, problem is solved.
previousKeyWindow = DTRetain([[UIApplication sharedApplication] keyWindow]);


text:
Q: Django: to pass data JSON from view to javascript I have my model
class Calendar(models.Model):
name = models.CharField(_('name'), max_length=50)

class Event(models.Model):
....
calendar = models.ForeignKey(Calendar, verbose_name=_('categorie'))

and my view:
event_list = []
events = Event.objects.all()

for event in events:
    event_list.append({
            'categorie': event.calendar
            })

return http.HttpResponse(json.dumps(event_list),
                             content_type='application/json')

I try to return event.categorie in a javascript file but It's not working
alert(event.categorie) display undefined....
if I print event_list, I have
{'categorie': <Calendar: thermique>}

The problem comes from  models.ForeignKey ?

A: You can't dumps Calendar instance to json. You should get error TypeError <Calendar: thermique> is not JSON serializable.
You need convert Calendar instance to dict of simple types. For example add method as_dict to Calendar:
class Calendar(models.Model):
    name = models.CharField(_('name'), max_length=50)

    def as_dict(self):
        return {
            'id': self.id,
            'name': self.name,
        }

and use it in you code:
for event in events:
    event_list.append({
        'categorie': event.calendar.as_dict(),
    })

A:
it just the calendar names

Since all you need is the calendar names you can modify your query a little bit to use values but the real problem is probably called by needing to resolve the queryset
events = Event.objects.values('calendar__name')
return http.JsonResponse(status=200,
                         {'categories': json.dumps(list(events))})


text:
Q: Retrofit2 and streaming serialized objects I am using Retrofit2. So far I tried it to send and receive java.util.List<MyCustomClass> and it is working really well. I am however wondering what would happen with really big lists. Is there way to make more "streaming" interface?
For example I could parse to api Iterator<MyCustomClass> instead of List and create each next instance on fly to save memory when sending data to API. Same Iterator<MyCustomClass> be used for the opposite direction.
Is there a way to achieve that?
I can see that Gson is able to do streaming serialization and deserialization. Can Retrofit utilize that?
Edit: Clarified question a bit.

A: An interesting question. First of all, you have to take into account that List and Iterable differ semantically, especially in the scope of I/O. If you look at it from the I/O perspective, lists are used to collect elements into an in-memory object and then close the underlying resource immediately. Iterables are not introduced to Gson, I think, because of being too lazy and deferring the elements evaluation from input streams: iterables should be able to return new iterators by design. It's not possible to create a new iterator unless another I/O resource reading is requested. This is where the confusion comes. I recently solved a very similar problem for Spring Framework (the MVC module) and Java 8 streams, and I seem to have a solution for Retrofit too. However, Retrofit needs to be used very carefully in order to be used properly and protect from resource leaks. Note that you can't use iterables here, but you can use iterators (Iterator): they are semantically very similar to Java 8 streams (Stream), and Java I/O streams (InputStream and OutputStream), because they cannot be reused. However, knowing the difference you still can work with Iterator instances.
Let's create a simple static HTTP web server in Python if you want to experiment more:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 8080

class myHandler(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/json')
        self.end_headers()
        # Send the html message
        self.wfile.write('["foo","bar","baz"]')
        return

try:
    server = HTTPServer(('', PORT_NUMBER), myHandler)
    print 'Started httpserver on port ' , PORT_NUMBER
    server.serve_forever()
except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    server.socket.close()

This web service always returns ["foo","bar","baz"] no taking requests into account. Now create a sample service to work with it:
interface IService {

    @GET("/")
    Call<Iterator<String>> get();

}

Second, Gson does not work with iterables or iterators by default, so a custom (de)serialization module needs to be implemented. The type adapter factory below either creates a special type adapter for iterators, or lets Gson to choose another previously strategy if any exists:
final class IteratorTypeAdapterFactory
        implements TypeAdapterFactory {

    private static final TypeAdapterFactory iteratorTypeAdapterFactory = new IteratorTypeAdapterFactory();

    private IteratorTypeAdapterFactory() {
    }

    static TypeAdapterFactory getIteratorTypeAdapterFactory() {
        return iteratorTypeAdapterFactory;
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
        if ( Iterator.class.isAssignableFrom(type.getRawType()) ) {
            @SuppressWarnings("unchecked")
            final TypeAdapter<T> castTypeAdapter = (TypeAdapter<T>) getIteratorTypeAdapter(getIteratorParameterType(type.getType()), gson);
            return castTypeAdapter;
        }
        return null;
    }

}

Next, the iterator type adapter implementation is as follows. Note that it's very easy to write iterator to a stream, but reading is much more complex:
final class IteratorTypeAdapter<T>
        extends TypeAdapter<Iterator<T>> {

    private final Type elementType;
    private final Gson gson;

    private IteratorTypeAdapter(final Type elementType, final Gson gson) {
        this.elementType = elementType;
        this.gson = gson;
    }

    static <T> IteratorTypeAdapter<Iterator<T>> getIteratorTypeAdapter(final Type elementType, final Gson gson) {
        return new IteratorTypeAdapter<>(elementType, gson);
    }

    @Override
    @SuppressWarnings("resource")
    public void write(final JsonWriter out, final Iterator<T> iterator)
            throws IOException {
        out.beginArray();
        while ( iterator.hasNext() ) {
            final T next = iterator.next();
            gson.toJson(next, elementType, out);
        }
        out.endArray();
    }

    @Override
    public Iterator<T> read(final JsonReader in) {
        return getJsonReaderIterator(elementType, gson, in);
    }

}

And the reading iterator:
final class JsonReaderIterator<T>
        implements Iterator<T>, Closeable {

    private final Type elementType;
    private final Gson gson;
    private final JsonReader in;

    private ReadingIteratorState state = ReadingIteratorState.BEFORE_ARRAY;

    private JsonReaderIterator(final Type elementType, final Gson gson, final JsonReader in) {
        this.elementType = elementType;
        this.gson = gson;
        this.in = in;
    }

    static <T> Iterator<T> getJsonReaderIterator(final Type elementType, final Gson gson, final JsonReader in) {
        return new JsonReaderIterator<>(elementType, gson, in);
    }

    @Override
    public boolean hasNext() {
        try {
            if ( state == ReadingIteratorState.END_OF_STREAM ) {
                return false;
            }
            final boolean hasNext;
            loop:
            for ( ; ; ) {
                switch ( state ) {
                case BEFORE_ARRAY:
                    if ( in.peek() == BEGIN_ARRAY ) {
                        in.beginArray();
                        state = ReadingIteratorState.WITHIN_ARRAY;
                    }
                    continue;
                case WITHIN_ARRAY:
                    if ( in.peek() == END_ARRAY ) {
                        in.endArray();
                        state = ReadingIteratorState.END_OF_STREAM;
                        continue;
                    }
                    hasNext = true;
                    break loop;
                case AFTER_ARRAY:
                    hasNext = false;
                    state = ReadingIteratorState.END_OF_STREAM;
                    break loop;
                case END_OF_STREAM:
                    hasNext = false;
                    break loop;
                default:
                    throw new AssertionError(state);
                }
            }
            return hasNext;
        } catch ( final IOException ex ) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public T next() {
        try {
            if ( !in.hasNext() || state == ReadingIteratorState.END_OF_STREAM ) {
                throw new NoSuchElementException();
            }
            final T element;
            loop:
            for ( ; ; ) {
                switch ( state ) {
                case BEFORE_ARRAY:
                    in.beginArray();
                    state = ReadingIteratorState.WITHIN_ARRAY;
                    if ( in.peek() == END_ARRAY ) {
                        state = ReadingIteratorState.END_OF_STREAM;
                    }
                    break;
                case WITHIN_ARRAY:
                    element = gson.fromJson(in, elementType);
                    if ( in.peek() == END_ARRAY ) {
                        state = ReadingIteratorState.AFTER_ARRAY;
                    }
                    break loop;
                case AFTER_ARRAY:
                    in.endArray();
                    state = ReadingIteratorState.END_OF_STREAM;
                    break;
                case END_OF_STREAM:
                    throw new NoSuchElementException(String.valueOf(state));
                default:
                    throw new AssertionError(state);
                }
            }
            return element;
        } catch ( final IOException ex ) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void close()
            throws IOException {
        in.close();
    }

    private enum ReadingIteratorState {

        BEFORE_ARRAY,
        WITHIN_ARRAY,
        AFTER_ARRAY,
        END_OF_STREAM

    }

}

Note that the iterator must be closeable in order to close underlying resources. To be honest, I don't like the contract of the close method in Java that requires the method to close underlying resources, and I believe that closing resources is a responsibility of an object that opened the resources. For example, such an iterator does not need to be closed in Spring MVC because the framework listens to HTTP requests itself, lets your handlers process the requests, and then closes the requests itself. In Retrofit resource leaks can happen if exposing iterators, so this is why this implementation has the close method implementation.
Next thing: configuring Retrofit to work with Iterator-aware Gson instances. There is a converter factory below that can work with lazy iterators. Note that the default GsonConverterFactory implementation does not let to work with iterators since it closes input streams before one can process them and convert to iterators. The rest two methods can be re-used from the default implementation, but it's not necessary to pass it from outside and can be instantiated privately. Also note that the response converters of the factory work for top-most objects only and there is no need to close iterators that can be fields of another objects.
final class CustomGsonConverterFactory
        extends Factory {

    private final Gson gson;
    private final GsonConverterFactory gsonConverterFactory;

    private CustomGsonConverterFactory(final Gson gson, final GsonConverterFactory gsonConverterFactory) {
        this.gson = gson;
        this.gsonConverterFactory = gsonConverterFactory;
    }

    static Factory getCustomGsonConverterFactory(final Gson gson, final GsonConverterFactory gsonConverterFactory) {
        return new CustomGsonConverterFactory(gson, gsonConverterFactory);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(final Type type, final Annotation[] annotations, final Retrofit retrofit) {
        final TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        final boolean isClosedElsewhere = isIterator(type);
        return (Converter<ResponseBody, Object>) responseBody -> {
            try {
                return adapter.read(gson.newJsonReader(responseBody.charStream()));
            } finally {
                if ( !isClosedElsewhere ) {
                    responseBody.close();
                }
            }
        };
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(final Type type, final Annotation[] parameterAnnotations, final Annotation[] methodAnnotations,
            final Retrofit retrofit) {
        return gsonConverterFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
    }

    @Override
    public Converter<?, String> stringConverter(final Type type, final Annotation[] annotations, final Retrofit retrofit) {
        return gsonConverterFactory.stringConverter(type, annotations, retrofit);
    }

}

The code above uses some reflection utilities:
final class Reflection {

    private Reflection() {
    }

    static Type getIteratorParameterType(final Type type)
            throws IllegalArgumentException {
        return getTParameterType(type, Iterator.class);
    }

    static boolean isIterator(final Type type) {
        return Iterator.class.equals(type)
                || type instanceof ParameterizedType && Iterator.class.equals(((ParameterizedType) type).getRawType());
    }

    private static Type getTParameterType(final Type type, final Type expectedParameterizedType)
            throws IllegalArgumentException {
        if ( expectedParameterizedType.equals(type) ) {
            return expectedParameterizedType;
        }
        if ( type instanceof ParameterizedType ) {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            if ( expectedParameterizedType.equals(parameterizedType.getRawType()) ) {
                final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                if ( actualTypeArguments.length == 1 ) {
                    return actualTypeArguments[0];
                }
            }
        }
        throw new IllegalArgumentException(String.valueOf(type));
    }

}

And code below will use the following closeable iterator utilities in order to close I/O resources (remember the converter factory that creates a converter that does not close resources for iterators?).
final class CloseableIterators {

    private CloseableIterators() {
    }

    static <T> void forEachAndClose(final Iterator<? extends T> iterator, final Consumer<? super T> consumer)
            throws Exception {
        try {
            while ( iterator.hasNext() ) {
                consumer.accept(iterator.next());
            }
        } finally {
            tryClose(iterator);
        }
    }

    static <T> List<T> collectToListAndClose(final Iterator<? extends T> iterator)
            throws Exception {
        final List<T> list = new ArrayList<>();
        forEachAndClose(iterator, list::add);
        return unmodifiableList(list);
    }

    static void tryClose(final Object object)
            throws Exception {
        if ( object instanceof AutoCloseable ) {
            ((AutoCloseable) object).close();
        }
    }

}

As you can see, all of the methods above close try to close given iterators to free I/O resources. And here is how all of that works:
final Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(getIteratorTypeAdapterFactory())
        .create();
final Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://localhost")
        .addConverterFactory(getCustomGsonConverterFactory(gson))
        .build();
final IService service = retrofit.create(IService.class);
final Call<Iterator<String>> getCall = service.get();
getCall.enqueue(new Callback<Iterator<String>>() {
    @Override
    public void onResponse(final Call<Iterator<String>> call, final Response<Iterator<String>> response) {
        try {
            final Iterator<String> iterator = response.body();
            if ( ... ) {
                forEachAndClose(iterator, out::println);
            } else if ( ... ) {
                out.println(collectToListAndClose(iterator));
            } else {
                tryClose(iterator);
            }
        } catch ( final Exception ex ) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public void onFailure(final Call<Iterator<String>> call, final Throwable throwable) {
        throwable.printStackTrace(err);
    }
});

Note that onResponse must close the top-most iterator objects itself, or a particular request resource will be leaked: even if there is no interaction expected, tryClose must be invoked in order to close a JsonReaderIterator instance. But, according to how iterators work, you can use them once.
Edit: closeable iterators enhancement
Here you have I think at least 2 ways to make them more robust. Consider an iterator that can be closed
interface IAutoCloseableIterator<E>
        implements Iterator<E>, AutoCloseable {
}

This interface can be used for the JsonReaderIterator above. And then you can:

*

*either return its instances an via callbacks like Call<IAutoCloseableIterator<E>>;

*or wrap any iterator in order to detect if it's AutoCloseable:

static <E, I extends Iterator<E> & AutoCloseable> I asAutoCloseable(final Iterator<E> iterator) {
    final Iterator<E> resultIterator;
    if ( iterator instanceof AutoCloseable ) {
        resultIterator = iterator;
    } else {
        resultIterator = new IAutoCloseableIterator<E>() {
            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public E next() {
                return iterator.next();
            }

            @Override
            public void close() {
                // do nothing or whatever elsewhere if there is no way to implement the method
            }

        };
    }
    @SuppressWarnings("unchecked")
    final I castIterator = (I) resultIterator;
    return castIterator;
}

And then (for the first option):
try ( final IAutoCloseableIterator<String> iterator = response.body() ) {
    while ( iterator.hasNext() ) {
        out.println(iterator.next());
    }
}

Or (for the 2nd option; may be not that robust...):
try ( final IAutoCloseableIterator<String> iterator = asAutoCloseable(response.body()) ) {
    while ( iterator.hasNext() ) {
        out.println(iterator.next());
    }
}

try-with-resources is your friend here.


text:
Q: While running PHP in XAMPP server in Windows 7, I am getting the error "undefined variable _SESSION" I am running an php website in xaamp server and while running i am getting this error, what does it means?  and how do i solve this?

Undefined variable: _SESSION in C:\xampp\htdocs\web\Movie\admin.php on line 56

A: It most likely means you need to add session_start(); to the very top of your php page.

A: It means you are referencing the _SESSION variable without declaring it anywhere. Go to line 56 in your admin.php file to locate the reference. Once you find the reference you can then decide where to place the session_start() function call in your code to initialize _SESSION
For more info on session variables and _SESSION visit the PHP documentation page here.


text:
Q: how to merge collections into a specific column in laravel I have 3 collections of different objects. I need to aggregate these 3 collections into 1 according to the shared value (here shared value is id).
I mean:
$names = {"id":1, "name":"John"};
$ages = {"id":1, "age":20};
$address = "{"id":1, "address":"222"};
  .......
 .........

if I return return $names->merge($ages)->merge($address), it will show me like this:
[
  {"id":1, "name":"John"},
  {"id":1, "age":20},
  {"id":1, "address":"222"},
  {"id":2, "name":"Jim"},
  {"id":2, "age":30},
  {"id":2, "address":"333"},
]

I want to return me like this:
[
   {"id":1, "name":"John", "age":20 , "address":"222"},
   {"id":2, "name":"Jim", "age":30 , "address":"333"}
 ]

A: This is my solution:
$items = [
  {"id":1, "name":"John"},
  {"id":1, "age":20},
  {"id":1, "address":"222"},
  {"id":2, "name":"Jim"},
  {"id":2, "age":30},
  {"id":2, "address":"333"},
];

$items = collect($items)->groupBy('id');
$result = [];
foreach ($items as $values) {
  $temp = [];
  foreach ($values as $value) {
    $temp = array_merge($temp, $value);
  }
  $result[] = $temp;
}

dd($result);


text:
Q: how to increase the precision and recall value hi am trying to create a staff promotion aloghritim which will have a high recall and precision value,trying to fit my model but get this error
pls help below is my collab link to my works so far
https://colab.research.google.com/drive/1ugKUswSjwnrfActsu2E-1gSg94ylwUJK
import catboost as ctb
from sklearn import metrics
    # fit a CART model to the data
parameters = {'depth'         : [6,8,10],
                  'learning_rate' : [0.01, 0.05, 0.1],
                  'iterations'    : [30, 50, 100]
                 }
model = ctb.CatBoostClassifier(silent=True)
model.fit(X_train, y_train)
print(); print(model)

     # make predictions
expected_y  = y_train
predicted_y = model.predict(X_test)

    # summarize the fit of the model
print(); print(metrics.classification_report(expected_y, predicted_y))
print(); print(metrics.confusion_matrix(expected_y, predicted_y))
ValueError                                Traceback (most recent call last)
<ipython-input-26-abdfdbe585e3> in <module>()
     16
     17     # summarize the fit of the model
---> 18 print(); print(metrics.classification_report(expected_y, predicted_y))
     19 print(); print(metrics.confusion_matrix(expected_y, predicted_y))

2 frames
/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
    203     if len(uniques) > 1:
    204         raise ValueError("Found input variables with inconsistent numbers of"
--> 205                          " samples: %r" % [int(l) for l in lengths])
    206
    207

ValueError: Found input variables with inconsistent numbers of samples: [30649, 7663]

A: From your abbreviations, I think it should be
expected_y = y_test

instead of
expected_y  = y_train


text:
Q: How to mirror a replicated database Forgive me if this question has already been asked - I've hunted around, but can't find something that matches my situation.
Say I have my Principle server (DB1), with a database Mir1.  I set up mirroring with my Mirror server (DB2).  Everything is fine.  I can failover, and see the Principle move from DB1 to DB2, and I can see it go back again.
Now, imagine we need a new database called Mir1DW, which is a replicated database off Mir1.  The distributor is on another machine altogether (DB3).
I need this Mir1DW database to be available, and to be continually updated (via replication) after the mirroring has done a failover.
I'm struggling to work out what's required.  I can find plenty of examples of mirroring with replication where the agents (using PublisherFailoverPartner) change where the data is coming from, but (from what I gather), the Mir1DW database itself is not included in the mirroring.
I've got a few limitations that I need to work within -

*

*Must be in SQL 2012 Standard (Enterprise not an option)

*Both the Mir1 and Mir1DW databases must be available and functioning correctly after a failover

*The Mir1 and Mir1DW databases must be on the same server (i.e., both on DB1 when running normally)

Now, I assume I would need a publisher on DB1 and DB2 (and probably DB3), and a subscription on either/both DB1 and DB2.  But I can't get my head around how to get subscriptions to play ball with mirroring.
Any pointers would be greatly appreciated!


text:
Q: How to get response from API after POST I am interacting with an API that sometimes will return a reference number for certain functions. How would i go about displaying this reference number. At present the API returns for example this string (some code taken out for security reasons).
if (AppSettings.GetLandingPageReceipts())
{
   long returnValue = loanLP.AddWithdrawalToBankID(CustomerID, SavingsAccountID, BankAccID, Amount);
   return string.Concat("Requested Withdrawal Ref No: ", returnValue);
}

ReceiptWithdrawal withdraw = new ReceiptWithdrawal(CustomerID, SavingsAccountID, Amount, session, pp, BankAccID);

ReceiptTRN TRN = new ReceiptTRN();

TRN.Post(withdraw);

return JsonConvert.SerializeObject(withdraw.ReceiptNo);

In the Ruby code I use this for Post calls
def post_call(routePath, params)
  started_at = Time.now
  logger.bench 'SERVICE - POST', started_at, routePath
  uri = URI.parse("#{settings.abacus_service_endpoint}#{routePath}")
  http = Net::HTTP.new(uri.host, uri.port)
  http.set_debug_output $stderr
  req = Net::HTTP::Post.new(uri.request_uri,get_header_for_abacus_service)
  req.form_data = params
  resp = http.request(req)
  if response_ok?(resp)
    if @errors
      puts '======= post request form_data ======='
      puts params
      puts '==================='
    end
    return resp
  end
end

I can see the following in my console when working locally so I know its being passed. Its just accessing it is the problem.
opening connection to 10.10.10.27...
opened
<- "POST /Accounts/WithdrawalToBank HTTP/1.1\r\nAuthorization: Token 433\r\nX-Customer-Id: 433\r\nX-Customer-Pin: 8EFD155E7C829421E16F14D367568C4179C4548320CD7E1B6AD6E9A485F2AF092FA42D0F645085F3DBBA5AEC2434720FC76E407E41443C3F5EDAFB958793254A\r\nX-Ip-Address: 10.0.2.2\r\nAccept: */*\r\nUser-Agent: Ruby\r\nContent-Type: application/x-www-form-urlencoded\r\nConnection: close\r\nHost: 10.10.10.27:3579\r\nContent-Length: 81\r\n\r\n"
<- "CustomerID=433&SavingsAccountID=10922&BankAccountID=2450&Amount=10.00&Reference=a"
-> "HTTP/1.1 200 OK\r\n"
-> "Transfer-Encoding: chunked\r\n"
-> "Content-Type: text/html\r\n"
-> "Server: Microsoft-HTTPAPI/2.0\r\n"
-> "Date: Mon, 23 Nov 2015 11:03:02 GMT\r\n"
-> "Connection: close\r\n"
-> "\r\n"
-> "22\r\n"
reading 34 bytes...
-> "Requested Withdrawal Ref No: 10059"
read 34 bytes
reading 2 bytes...
-> "\r\n"
read 2 bytes
-> "0\r\n"
-> "\r\n"
Conn close

If any further information is needed please let me know.

A: If the API is returning a body you should be able to get this from your response with resp.body


text:
Q: Git force push with IntelliJ IDE I've searched the documentation and online also, but I can seem to find a way to do Git force push aka git push --force with IntelliJ, it is easy to do with the command line but how can you do it within the IDE itself?

A: From the Push window (Ctrl/cmd-shift-K), the Push button has a down arrow to reveal a dropdown option 'Force Push'. This will perform at first a --force-with-lease, which if fails, will prompt a --force push.

If your branch is trying to push to master, 'Force Push' is grey. To enable force push to master, remove it from the list of protected branches in Preferences → Git:


text:
Q: SOAP output processing i am calling a soap based web service in php.
when i echo the output nothing can be seen on the page, but i can see a xml in viewsouce.
Can anyone guide me in processing the output so that i can appropriate data from it. I have never dealt with xml before so finding it a bit confusing.
Here's my code
$a = new SoapClient('http://abc.com?wsdl');
$login = $a ->TestConnectStr(array('UserName' => 'Test', 'Password' => '1234'));
echo $login->TestConnectStrResult;

the output link view-source:http://www.toolbrands.co.uk/rialto.php
Thanks in advance

A: The reason is that your  given web service method $a ->TestConnectStr(); returns a XML string . if you print the resulted string using echo  the browser will render the xml tags . if want the see xml out put for testing purpose you can print those values to a textarea like this

$xml= $login->TestConnectStrResult;
echo "< textarea cols=50 rows=10> $xml < /textarea> ";

if you need do any operations on resulted xml string you need to parse that xml


text:
Q: Jquery check element exists by data attribute matching only the start of a specific value I want to be able to check to see if a specific data attribute exists that starts with a specific value.
for example lets say i have the following HTML code:

and then i want to find any use of the data tag of data-attr that starts with 123
 if ($('[data-attr="123"]').length > 0) {
     //do something
 }

This appears to always return 0 as i have no data-attr="123" How would i make it so i can check for only that specific data attribute that starts with 123 and has anything after that?

A: here is how
if ($('[data-attr^="123"]').length > 0) {
 //do something
}


text:
Q: Sites list link in recent Overflow blog post should have the view set to list In the Check out the Stack Exchange sites that turned 10 years old in Q4 blog post, there is a link to the Stack Exchange sites list with the sort set to total "Question Per Day" (https://stackexchange.com/sites#questionsperday).
This link will navigate properly only when your last view selection on that page was a list view (eg. https://stackexchange.com/sites?view=list).
If your last selection was grid view instead, (https://stackexchange.com/sites?view=grid) the link from the blog post won't navigate to the intended "Sort by" filter.
If the URL has the ?view=list bit appended to the end, then the view will be set correctly when the user clicks the link, ensuring that the page matches what's mentioned in the blog. It should be:
https://stackexchange.com/sites?view=list#questionsperday

instead of
https://stackexchange.com/sites#questionsperday

Blog spot screenshot with URL:

A: Thank you for reporting. The link has been fixed on the blog post.


text:
Q: How to get all values from a list? Sorry in advance, dev code and web access are on two seperate platforms so I could not copy and paste.
In my jsp if have a list define as such:
<form:form id=""fm-form commandname="command" action="$actionURL" onsubmit="return false;">
// what does this commandName="command" do?  I see it in several places in the code
// and it all has to do with dropdown lists.
.
.
.
.
.
<form:select id="fm-explosives2" path="fm-explosives2" items="${command.explosiveList}"       onchange="populateDensity(); populatetntEquiv()";/>

Then I make a call to the makeCaluculations() in .js file...
function makeCalculations(){
...
var explosiveNames = new array();
.
.
.
var explosiveList = DWRUtil.getValue("fm-explosive2");
// this should have all the names from the dropdown list - or am I wrong?

// then I try to populate the array to be used later...
for (var i=0; i < explosiveList.length; i++){
      var explosive = explosiveList[i];

      alert("explosive name is: " + explosive.explosives);  // all NULL values!!! Why? Help!
      explosiveNames.push(explosive.explosives);
      more code .....

}

}
Question:  what does this commandName="command" (in the .jsp source) do?  I see it in several places in the code
           and it all has to do with dropdown lists. Anyone?

A: Based on your comment clarification. Your function should look something like...
function makeCalculations(){
var explosiveNames = [];
var explosives = DWRUtil.getValue("fm-explosive2");
// this should have all the names from the dropdown list - or am I wrong?

// then I try to populate the array to be used later...
for (var i=0; i < explosives.length; i++){
      var explosivenames = explosiveList[i];

      alert("explosive name is: " + explosives[i].explosives);
      explosiveNames.push(explosives[i].explosives);
}

A: *

*explosive  is not defined in your entire code.

*in the loop, it shouln't be explosive.explosives, it should be explosiveList[i].explosives, where explosives can be your entity of the explosiveList[i]

So, basically replace all explosive.explosives with
  explosiveList[i].explosives in your code, then it should work.


text:
Q: Hazelcast Queue ItemListener for Pending Item (Producer-Consumer Concept) I have 2 nodes that use Hazelcast.
Node A is a Producer, it puts items into a Queue
Node B is a Consumer, it consume or pool items from the Queue.
I add ItemListener into Node B
so when an item added to the queue, the consumer will notice and start to consume.
There's nothing wrong if everything work fine, but..
Sometimes the consumer is shutdown, and the producer still working and put item to the queue.
When I start the consumer again, it just consume when the producer add an item.
So.. how about the pending item.
I'm using Hazelcast 3.3.
Is there any solution for this problem..?
Thanks.

A: It not a bug, the ItemListener is a listener so it is fired when add/remove items so you have to add a new functionality when your consumer starts to check if there are any pending element in the queue.
In my case I just create a heartbeat to ask the queue if there are any element, in that case the consumer method is executed.


text:
Q: Adding quotes to a string in VBScript I have this code:
a = "xyz"
g = "abcd " & a

After running it, the value of g is abcd xyz.
However, I want quotes around the value of a in g. After running the code, g should be abcd "xyz" instead.
How can I accomplish this?

A: You can escape by doubling the quotes
g="abcd """ & a & """"

or write an explicit chr() call
g="abcd " & chr(34) & a & chr(34)

A: I usually do this:
Const Q = """"

Dim a, g
a = "xyz"
g = "abcd " & Q & a & Q

If you need to wrap strings in quotes more often in your code and find the above approach noisy or unreadable, you can also wrap it in a function:
a = "xyz"
g = "abcd " & Q(a)

Function Q(s)
  Q = """" & s & """"
End Function

A: The traditional way to specify quotes is to use Chr(34). This is error resistant and is not an abomination.
Chr(34) & "string" & Chr(34)

A: You have to use double double quotes to escape the double quotes (lol):
g = "abcd """ & a & """"

A: You can do like:
a="""xyz"""
g="abcd " & a

Or:
a=chr(34) & "xyz" & chr(34)
g="abcd " & a

A: I don't think I can improve on these answers as I've used them all, but my preference is declaring a constant and using that as it can be a real pain if you have a long string and try to accommodate with the correct number of quotes and make a mistake.  ;)

A: I designed a simple approach using single quotes when forming the strings and then calling a function that replaces single quotes with double quotes.
Of course this approach works as long as you don't need to include actual single quotes inside your string.
Function Q(s)

    Q = Replace(s,"'","""")

End Function

...
user="myself"
code ="70234"
level ="C"

r="{'User':'" & user & "','Code':'" & code & "','Level':'" & level & "'}"
r = Q(r)
response.write r

...
Hope this helps.

A: I found the answer to use double and triple quotation marks unsatisfactory. I used a nested DO...LOOP to write an ASP segment of code. There are repeated quotation marks within the string.  When I ran the code:
thestring = "<asp:RectangleHotSpot Bottom=""" & bottom & """ HotSpotMode=""PostBack"" Left="""& left & """    PostBackValue=""" &xx & "." & yy & """ Right=""" & right & """ Top=""" & top & """/>"

the output was:
<`asp:RectangleHotSpot Bottom="28
 'Changing the code to the explicit chr() call worked:

thestring = "<asp:RectangleHotSpot Bottom=""" & bottom & chr(34) & " HotSpotMode=""PostBack"" Left="""& left & chr(34) & " PostBackValue=""" &xx & "." & yy & chr(34) & " Right=""" & right & chr(34) & " Top=""" & top & chr(34) &"/>"

The output:
<asp:RectangleHotSpot Bottom="28" HotSpotMode="PostBack" Left="0" PostBackValue="0.0" Right="29" Top="0"/>