text:
Q: Distribution-agnostic package search and installation I'm trying to figure out a distribution-agnostic way to install packages providing specific executables or files. I know that it is impossible to get this perfect, but I think I have something that is almost good enough and I was hoping that maybe someone has an idea on how to improve upon it.
Basically I've written a script that provides an abstraction layer around the most common package managers:
commandAvailable() { command -v $1 &> /dev/null; }

if commandAvailable dnf; then
    updatePackageInfo() { dnf check-update; }
    searchPath() { dnf provides $1 2> /dev/null | grep ' : ' | head -1 | cut -d'.' -f1 | rev | cut -d'-' -f 2- | rev; }
    searchBin() { searchPath {/bin,/sbin,/usr/bin/,/usr/sbin}/$1; }
    install() { dnf install -y $@; }
elif commandAvailable yum; then
    updatePackageInfo() { yum check-update; }
    searchPath() { yum provides $1 2> /dev/null | grep ' : ' | head -1 | cut -d'.' -f1 | rev | cut -d'-' -f 2- | rev; }
    searchBin() { searchPath {/bin,/sbin,/usr/bin/,/usr/sbin}/$1; }
    install() { yum install -y $@; }
elif commandAvailable apt-get; then
    updatePackageInfo() { apt-get update && if ! commandAvailable apt-file; then install apt-file; fi && apt-file update; }
    searchPath() { apt-file search $1 | head -1 | cut -d':' -f1; }
    searchBin() { searchPath {/bin,/sbin,/usr/bin/,/usr/sbin}/$1; }
    install() { apt-get install -y $@; }
elif commandAvailable pacman; then
    updatePackageInfo() { pacman -Sy && pacman -Fy; }
    searchPath() { pacman -F $1 | head -1 | rev | cut -d' ' -f2 | rev; }
    searchBin() { pacman -F $1 | grep -B 1 -P "    (usr/bin|usr/sbin|bin|sbin)/$1" | head -1 | cut -d' ' -f1; }
    install() { pacman -S --noconfirm $@; }
elif commandAvailable zypper; then
    updatePackageInfo() { zypper refresh; }
    searchPath() { zypper search -f $1 | grep " | package" | head -1 | tr -d ' ' | cut -d'|' -f2; }
    searchBin() { searchPath {/bin,/sbin,/usr/bin/,/usr/sbin}/$1; }
    install() { zypper --non-interactive install "$@"; }
elif commandAvailable emerge; then
    updatePackageInfo() { emerge-webrsync -v && if ! commandAvailable e-file; then install app-portage/pfl; fi; }
    searchPath() { e-file $1 | grep -P "(\[I\]| \* )" | sed 's/*//g' | sed 's/\[I\]//g' | tr -d ' '; }
    searchBin() { searchPath /usr/bin/$1; searchPath /usr/sbin/$1; searchPath /bin/$1; searchPath /sbin/$1; }
    install() { emerge $@; }
fi

searchBins() { for executable in "$@"; do searchBin $executable; done | tr "\n" " "; echo; }
searchPaths() { for path in "$@"; do searchPath $path; done | tr "\n" " "; echo; }
installPkgWithPath() { install $(searchPath "$1"); }
installPkgsWithPaths() { install $(searchPaths $@); }
installPkgWithExecutable() { install $(searchBin $1); }
installPkgsWithExecutables() { install $(searchBins $@); }

The functions it creates can be used like this:
updatePackageInfo                                  # Equivalent to apt-get update

installPkgWithPath "curl/curl.h"                   # Installs the package containing the header file curl/curl.h

installPkgsWithPaths "curl/curl.h" "/usr/bin/wget" # Installs multiple packages by file paths

installPkgWithExecutable curl                      # Install the package that provides the `curl` executable

installPkgsWithExecutables curl wget make          # Install all packages required to get these 3 executables

This basically works fine on Fedora, RHEL, Debian, Arch, Gentoo, OpenSuse (and many more I would think). But it does not work on Ubuntu for example because Ubuntu doesn't have the required apt-file package (unless you enable the Universe repository that provides it).
Another thing that doesn't work is installing things like vlc in Fedora. On Fedora you would usually enable the RPM Fusion repositories for that.
And I'm sure other distributions have similar situations.
What I have considered is maybe adding a --force flag that, when set, causes these repositories to be searched and added if needed. But I would hate to end up in a situation where I have to maintain lists of repositories. My hope is that most distributions somehow reference these semi-trusted repositories in a way that I don't have to maintain a list of repositories for every distribution.
Any ideas?

A: I guess with Debian's 50,000+ installable packages, I haven't needed to look outside Debian mirrors. The idea you have is kind of cool, but you probably would require repository list updating. Also, you're going to be creating franken distros, and that can really screw things up!
Using various force options is good for getting out of a jam, but not recommended for everday use. You could maybe add a subscript to convert packages using alien. The idea lends itself well to consuming all available spare time, without limit
I once pondered a HTML system to hold all Linux documentation in existence. I didn't have to ponder it for long!

A: I have never looked at this before but it could be a good exercise...
I am an Arch Linux user. I am a GNOME user, too. I know there is a GNOME application store [1] and it must be distro-agnostic because Arch provides it, Ubuntu and Fedora as well, etc...
So, looking into gnome-software [2] dependencies two of them have drawn my attention:

*

*PackageKit [3], described as "A system designed to make installation and updates of packages easier"

*AppStream [4], described as "Provides a standard for creating app stores across distributions"
I think answer to your question is there or at least they will give you a good starting point where to look in

[1] https://wiki.gnome.org/Apps/Software/
[2] https://archlinux.org/packages/extra/x86_64/gnome-software/
[3] https://www.freedesktop.org/software/PackageKit/
[4] https://www.freedesktop.org/wiki/Distributions/AppStream/


text:
Q: Detectar si un elemento html es visible o no con javascript puro espero que puedan ayudarme con esta duda, lo que pasa es que estoy detectando si un elemento es visible en pantalla, para ello estoy utilizando esta función:
    var imagen = document.querySelector(".rast-photo");
    window.onscroll = function () {
        var posTopView = window.scrollY;
        var posButView = posTopView + window.innerHeight;
        var elemTop = imagen.offsetTop;
        var elemBottom = elemTop + imagen.offsetHeight;
        if ((elemBottom < posButView && elemBottom > posTopView) ||(elemTop > posTopView && elemTop < posButView)) {
            console.log("Si es visible")
        } else {
            console.log("No es visible")
        }
    };

El único problema es que esto me manda algo así:
me repite bastantes veces el console log porque la condición se cumple varias veces, de que manera puedo hacer que solo aparezca una vez? me refiero a que si el elemento es visible mande el mensaje que es visible pero solo una vez y cuando deje de ser visible me mande el mensaje de que no es visible pero igual solo una vez, espero puedan ayudarme con esta duda, GRACIAS!

A: Ok, ya lo solucioné jeje... me había bloqueado pero fue bastante sencillo en realidad >.<
        var imagen = document.querySelector(".rast-photo");
        var visible = false;
        window.onscroll = function () {
            var posTopView = window.scrollY;
            var posButView = posTopView + window.innerHeight;
            var elemTop = imagen.offsetTop;
            var elemBottom = elemTop + imagen.offsetHeight;
            if ((elemBottom < posButView && elemBottom > posTopView) ||(elemTop > posTopView && elemTop < posButView)) {
                if(visible === false){
                    console.log("Si es visible")
                }
                visible=true;
            } else {
                if (visible === true){
                    console.log("No es visible")
                }
                visible=false;
            }
        };

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a good comparison of the different Entity Framework 2.0 code generators? Inspired by this post, I'm wondering if anyone has found a good comparison between the POCO Generator and the 1.0esque Entities/Context.  Why should I use one over the other?  Or, what criteria should I be evaluating on my project to make my decision?
I once thought that POCO's were less work for mvc/wcf/databinding.  But it seems a more customized object really suits the needs better. ie viewmodels or dto's.  Or is this point. They were created to shortcut development with less than ideal implementations?
Assume I'm familiar with the adonet blog, which should be mandatory reading.


text:
Q: Any recommendations for a CSS minifier? Any recommendations for a CSS minifier?
I'll be rooting around Google and trying some out, but I suspected that the smart, proficient and curiously handsome StackOverflow community might have already evaluated the pros and cons of the heavyweights.

A: The YUI Compressor is fantastic. It works on JavaScript and CSS. Check it out.

A: If you use Python I would recommend slimmer which is probably not as fast as YUI Compressor but unlike csscompressor.net it doesn't choke on CSS hacks.
I'm biased since I wrote slimmer and I'm currently evaluating YUI Compressor to see how it handles hacks. An example of slimmer in action can be seen if you view the source of crosstips.org

A: If you are looking for an online tool, try this: https://csscompressor.net/

A: Check out CSSTidy: http://csstidy.sourceforge.net/usage.php
And online at: http://cdburnerxp.se/cssparse/css_optimiser.php

A: There's also a .NET port of YUI Compressor which allows you to:-

*

*intergrate the minification/file combining into Visual Studio post-build events

*intergrate into a TFS Build (including CI)

*if you wish to just use the dll's in your own code (eg. on the fly minification).

UPDATE 2011: And it's now available via NuGet also :)

A: I've written an ultra fast CSS minifier in C#. The algorithm does not handle Javascript though. Thy this: http://www.ko-sw.com/Blog/post/An-Ultra-Fast-CSS-Minify-Algorithm.aspx.

A: Try closure-stylesheets.
Beside minification it also supports linting, RTL flipping, and class renaming.
It can also add variables, functions, conditionals, and mixins to CSS.
Also note that some of these features depend on rest of Closure Tools (which are very powerful on their own).

A: If you're looking for something in PHP, here's the link:-
Fat-Free Minify
Although it's part of the PHP Fat-Free Framework, it can also be used stand-alone.

A: I find that isnoop's CSS SuperScrub works very well.  It can only handle direct links to CSS online though :/  You can get around that though by using your preferred pastebin service to hold the css code and just giving SuperScrub the raw link.

A: If your site is in ASP.NET, you can let your site do the CSS minification on the fly (so you don't have to do it manually each time you make a change). For example with this:
http://www.codeproject.com/KB/aspnet/CombineAndMinify.aspx

A: Still "in beta", but should work fairly well. I use the code behind it in every project: http://claudiu.phpfogapp.com/ It's built in PHP and also hosts your *.css file for a fairly large amount of time, surely enough to let you test your code with the minified css. (I would only delete old css files if the space gets crowded on the server).

A: Perl has CSS::Minifier (and an XS version for extra speed).

A: Others have mentioned YUI Compressor, then the .NET port of it, and I'll add another link to the chain. StyleManager is a server control which wraps up the .NET port of YUI Compressor so you can use it just like you're used to using ScriptManager. It adds a bunch of other nice features too, like CSS constants, tilde (~) resolution w/in your background-image definitions, etc etc. It's tight, well documented, and I've used it on all my recent projects w/o an issue. Check it out - gStyleManager.com

A: An online tool (much better than www.csscompressor.net which jacked my css up): http://www.cssdrive.com/compressor/compress.php does an excellent job.

A: There is a codeplex project that will plug in to .net websites that will minify and compress the CSS and the JS files.  There is also a comparison between the Microsoft AJAX Minifier and the YUI Compressor which shows the YUI coming out slightly better.  There is an extra variation which combines the Microsoft Minifier and compression which drastically srunk the file.
Anyway the link is
http://xpedite.codeplex.com/wikipage?title=Minifier%20(CSS%2FJavaScript%20Minification%20Handlers)

A: This is how I did it for MVC3:
http://mkramar.blogspot.com/2011/08/css-and-javascript-minify-and-combine.html
The beauty of this approach is that it does it all on the fly and you don't have to pre-process files manually or configure post-build.

A: I like Minify. In PHP and works with CSS or JavaScript.

A: CSSO is currently best minifier/optimizer.

A: C# example:
css = css.Replace("\n", "");
css = Regex.Replace(css, @"\s+", " ");
css = Regex.Replace(css, @"\s*:\s*", ":");
css = Regex.Replace(css, @"\s*\,\s*", ",");
css = Regex.Replace(css, @"\s*\{\s*", "{");
css = Regex.Replace(css, @"\s*\}\s*", "}");
css = Regex.Replace(css, @"\s*\;\s*", ";");

A: zbugs.com will be a good online tool for you, it will minify your css in a single click

A: Have a peek at the latest HTML5BoilerPlate by Paul Irish - it contains a build script to minify all your assets (including PNG's and JPG's). You can see a demo video here.


text:
Q: Sending mail with PHP and AJAX I am trying to send a customized email with Ajax and PHP. But I the mail is not being delivered to my inbox or say that the script is not working. Please help me guys.
HTML Form:
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="">

            Name *
            <input type="text" id="name" class="form-control" required="required">

            Email *
            <input type="email" id="email" class="form-control" required="required">

            Phone *
            <input type="number" class="form-control" id="phone" required="required">

            Company Name
            <input type="text" class="form-control" id="company">

            Subject *
            <input type="text" name="subject" class="form-control" required="required" id="subject">

            Message *
            <textarea name="message" id="message" required="required" class="form-control" rows="8"></textarea>

            <button type="submit" name="submit" class="btn btn-primary btn-lg" id="submit">Send Mail</button>

      </form>

Ajax:

send-mail.php page:
<?php
$to = 'info@siliguriwebmedia.in';
$subject = "Inquiry form received";

$name    = (!empty($_POST['name']))?$_POST['name']:null;
$email   = (!empty($_POST['email']))?$_POST['email']:null;
$phone   = (!empty($_POST['phone']))?$_POST['phone']:null;
$company = (!empty($_POST['company']))?$_POST['company']:null;
$subject = (!empty($_POST['subject']))?$_POST['subject']:null;
$message = (!empty($_POST['email']))?$_POST['message']:null;

$htmlContent = '

        <title>Inquiry form received</title>

                Name:
                $name

                Email:
                $email

                Phone:
                $phone

                Company:
                $company

                Subject:
                $subject

                Message:
                $message

    ';

// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Send email
mail($to,$subject,$htmlContent,$headers);
?>


text:
Q: How to find current location and make marker on that location .? I want to find current location and make marker on that location.
plz tell me
if any example is there then please tell me..
like this

Thanks in Advance...

A: for find current location use gps. You can get more examples for that and for marker see this links. https://github.com/jgilfelt/android-mapviewballoons

A: Here we have few simple steps
class MapOverlay extends com.google.android.maps.Overlay
    {
        @Override
        public boolean draw(Canvas canvas, MapView mapView,
        boolean shadow, long when)
        {
            super.draw(canvas, mapView, shadow);

            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);

            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.pin);
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
            return true;
        }
    }

after abv code call your marker
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mapView = (MapView) findViewById(R.id.mapView);

    Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;
    try {
        addresses = geocoder.getFromLocationName(getIntent().getStringExtra("address"), 1);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Address address = addresses.get(0);
    double lng  = address.getLongitude();
    double lat  = address.getLatitude();

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

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

  //---Add a location marker---
    MapOverlay mapOverlay = new MapOverlay();
    List<Overlay> listOfOverlays = mapView.getOverlays();
    listOfOverlays.clear();
    listOfOverlays.add(mapOverlay);

    mapView.invalidate();
    mapView.invalidate();
 }

Hope I have cleared you some what. Keep smiling :)


text:
Q: How can I make an AutoHotkey message box dissapear without clicking okay? I need something like a msgbox displaying in my script but without the need for waiting to click okay.
What I need is to display a string for a certain duration of time and then make it disappear. It would be helpful if it can display a live timer string but not mandatory.
Something like:
;//...
msgbox, MyInformationString; display information
sleep, 30000 ; wait 30 seconds
;// close msgbox but HOW ???
;//...

It doesn't have to be the msgbox command. but I can not figure out how to create a new popup or any other way to display information. Format is the least of my concern here.

A: Look at msgbox in the docs. Since you are producing the msgbox via AutoHotkey, you can set a time limit on it that will close the message automatically.  That means that you don't have to push anything - the box appears and then just goes away.
MsgBox [, Options, Title, Text, Timeout]

Timeout is the last parameter:

(optional) Timeout in seconds, which can contain a decimal point but
  is not an expression by default.  In v1.1.06+, this can be a forced
  expression such as % mins*60.
If this value exceeds 2147483 (24.8 days), it will be set to 2147483.
  After the timeout has elapsed the message box will be automatically
  closed and the IfMsgBox command will see the value TIMEOUT.
Known limitation: If the MsgBox contains only an OK button, IfMsgBox
  will think that the OK button was pressed if the MsgBox times out
  while its own thread is interrupted by another.

A: If you would really like your own count down, you can create a GUI that acts as your MsgBox.

In this example, we have 4 parameters.

*

*The Title of the Window

*The Message

*The Number of Seconds

*The name of a label to call when it disappears.

Here's the way your code changes from normal MsgBox, to this one.
MsgBox, Title, Msg
OtherCode
return

to
MsgBoxTimed("Title", "Msg", 10, "Foo")
return
Foo:
OtherCode
return

This function needs to be in the same file, or #Included
MsgBoxTimed(title, msg, seconds, complete="") {
    static init = false, _seconds, _complete
    global Msg92, Seconds92
    if (!init)
    {
        init := true
        Gui, 92:Font, s24
        Gui, 92:Add, Text, vMsg92 Center w360, %msg%
        Gui, 92:Font, s30 cRed
        Gui, 92:Add, Text, vSeconds92 Center w360, %seconds%
    }

    _seconds := seconds
    _complete := complete

    GuiControl, 92:, Msg92, %msg%
    Gui, 92:Show, w400 h150, %title%

    Update92:
    GuiControl, 92:, Seconds92, %_seconds%
    _seconds -= 1
    if (_seconds > 0) {
        SetTimer, Update92, -1000
    }
    else {
        Gui, 92:Hide
        if (_complete)
            SetTimer, %_complete%, -1
    }
    return
}


text:
Q: How to access Express parameters on HTML without using Jade? After Rendering my page to HTML
res.render('myPage', myParameters);

how can I then access myParameterson my HTML+js page ? (without using Jade)

A: I was able to solve this using Consolidate renderer instead of jade:
var cons = require('consolidate');

app.engine('html', cons.swig);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

and then to access it on js it's as simple as using {{ varname }}, ex: :
var myParameters = "{{myParameters}}";


text:
Q: iPhone UIWebView Bug I am getting this error message in the console, while i am trying to load a html page in UIWebView ?
"void SendDelegateMessage(NSInvocation*): delegate failed to return after waiting 10 seconds. main run loop mode: UITrackingRunLoopMode
If you were not using the touch screen for this entire interval (which can prolong this wait), please file a bug."
Any reason for it ?
Thanks

A: I don't know if this is necessarily your problem, but I have received the same message when a piece of Javascript takes too long to execute. Do you know if the webpage you are loading is doing any heavy javascript on load?
In my case I was testing if you could use prompt() in a UIWebView - which worked, but gave the error you mentioned if I took more than 10 seconds to dismiss the popup.

A: If you only see this error when you put a breakpoint in webViewDidFinishLoad: I don't think that this is a problem.
On the other hand, if you see it when your code is running normally then it is a problem. You may need to break out the parsing of the XML file into a separate thread or, at least, decouple it from the web view.


text:
Q: how to place horizontal scroll bar in Ext js Grid how to place horizontal scroll bar in Ext js Grid.
pls help

A: set autoScroll config property to true. As long as grid is wider than container it's in, a scroll bar should be rendered.


text:
Q: Why won't Ubuntu 20.10 Boot on VirtualBox with a Windows 10 Host flashing cursor? I have a Windows 10 Host that I have ensured HyperV is turned off along with Device Guard. I have also ensured virtualization is turned on (I have an Asus Z590).
When I boot I get a black screen with a blinking cursor. If I boot then hit e and replace quiet splash with text I get...

I also tried adding nomodeset still the same issue
When I try with 20.04 I get...

A: I got it, in the Virtual box settings for the image it defaults to 32bit Linux I needed to make it 64bit.


text:
Q: Executing Stored Proc in Pervasive Control Center I am relatively new to Pervasive Control Center and I was wondering if I wanted to test a stored Procedure to see its results, how would I simply select that stored proc? I have:
Select SP_test_getMeasure06

I am sure I am missing something because I know this is legal my syntax must be off slightly.
Thanks in advance!

A: You can execute a stored procedure using either Call or Exec.  For example:
exec SP_test_getMeasure06

You'll need to make sure your stored procedure uses the RETURNS clause to get data back.  For more information check out the Stored Procedure docs.


text:
Q: my .htaccess file rewrite something wrong I have a problem with .htacces file.
Can you tell me please what am I doing wrong here?
I will show you some screenshot:  This image shows my Cpanel my Script files is in home/lulu/public_html/

And another problem is: When i click my friends picture his/her profile it shows me my profile but url is www.ecoshoptr.com/rajesh

last proflem is when i click my friends button page said (Not: I have no friends folder )

<a href="<?php echo $base_url.'friends/'.$session_username; ?>">Friends

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^ecoshoptr.com$
RewriteCond %{REQUEST_URI} !^/
RewriteRule (.*) http://www.ecoshoptr.com/$1
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?id=$1

A: I dont if you left it out but the [L] param prevents it from further rewriting and thus not ending up in your last rules
Maybe you can turn on your RewriteLog if that is available on your apache version
RewriteRule foo bar [L]

A: Change the following two lines:
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?id=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?id=$1

to
RewriteRule ^(.*)/?$ index.php?id=$1

Your rules would only rewrite urls that has characters a-z in lower and upper case, an underscore, a - and digits 0-9. The url friends/Name wouldn't match that rule because it has a / in it. The rule I have will accept that. Also I combined the two rules into the by adding a ? after the / because it will say that it might be there and it might not be there.


text:
Q: Does the azure python sdk support the azure resource manager api? I'm new to azure, I see that a new api/abstraction has been released called Azure Resource Manger, which will superceed older azure service management :
I was trying to spin up an instance using the azure python sdk, but I see the sdk still using the older concepts (afinity groups, virtual networks, hosted services). There is no mention of resource groups. Are this supported? If not when will this be added to the sdk?

A: Per my experience, currently Python SDK doesn't provide packages for new Azure Resource Manager APIs while it provides components, i.e. ServiceManagement, Storage, and ServiceBus. Please feel free to submit your ideas and feedback on https://github.com/Azure/azure-sdk-for-python/issues.

A: You might want to take a look at the azure-mgmt collection of packages, which use the new Resource Manager APIs.


text:
Q: How do I store multipule class objects in the same array in Java? If I create an Array in the class DefaultItems:
DefaultItems[] items = new DefaultItems[20];

I want to use this as a storage array for 5 different class objects.   I want to store a Car object, Person object and Pet object.
 DefaultItems[1] = Car Object;
 DefaultItems[2] = Person Object;

Is this possible?

A: If Car and Person derive from DefaultItems then your code should work (assuming the typos are fixed).
If the classes are not related in any way then you can achieve what you want by using Object[] instead of DefaultItems[]. All classes derive from Object.

A: Make sure all your 5 objects i.e. Car, Person etc. are extended from base class DefaultItems. Once you do that, you can achieve what you want.
i.e.
 public class Person extends DefaultItems {
   //...
 }

 public class Car extends DefaultItems {
   //...
 }

then
 DefaultItems[] items = new DefaultItems[2];
 DefaultItems[0] = new Person();
 DefaultItems[1] = new Car();

One example with Number class and its sub classes as is as below:
    Number[] nums = new Number[3];
    nums[0] = new Integer(0);
    nums[1] = new Double(1.0);
    nums[2] = new Float(0.5);

    for(Number num: nums){
        System.out.println(num);//<--prints the numbers
    }

A: It is possible, in a type safe way, just if all the obejcts you want to store in the array share a common parent class from which they inherit:
class Car extends MyObject {
  ...
}

class Person extends MyObject {
  ...
}

MyObject[] array = new MyObject[2];
array[0] = new Car();
array[1] = new Person();

But after having added them to the array they can be accessed just as MyObject instances (unless you typecast them, which must be avoided), so if MyObject class doesn't provide a common interface then this is pretty pointless. It's better to use composition:
class MyClass {
  Person person;
  Car car;
  ..
}


text:
Q: Ignore HTML characters when searching HTML stored content PHP/MySQL? We are storing blocks of HTML content in MySQL (it is formatted text created in CKeditor. Ckeidor adds inline CSS styles to format the text).  We are storing the database in a column called "page_content"
We want a search feature that allows users to search the text (only). However we don't want the search to return HTML characters which is what is happening right now. For example, if we search "font" we dont want the search results to return pages with the HTML styles <font>
Is there some way to ignore HTML/CSS characters when searching HTML stored content from MySQL?

A: Have you considered setting up a separate table for these searches? MySQL's full text search only works with MyISAM tables so you probably don't want to mix that the full text search with important data (unless, of course, you have some strange distaste for foreign keys and referential integrity).
The approach I've used in the past is basically this:

*

*Set up a separate table with a simple (id, search_text) structure.

*

*The id matches the id of the thing you're searching.

*The search_text is everything (body text, title, author name, ...) that you want to search mashed into one blob of text.

*Add full text indexing on the search table.

*Update your database update process to construct the appropriate search_text string as plain text; this is where you would strip out the HTML and possibly apply some other mappings (such as expanding things like "A+" to something that the full text search will find).

*When searching, you apply the same mappings as you apply to the searchable data and then go look in your search table for matches.

This solves your HTML problem, lets you search more than the HTML content easily, and allows you to tune the search results by weighting different components of the search text through repetition (e.g. if you want tags to be more important than the body text, just add the tags two or three times when building the search_text).
You'll have to process your text to remove or ignore the HTML. This approach lets you do it just once rather than doing it on every search.

A: I am guessing you want to do the searching on the database? (in that case, stripping HTML tags would mean that you would have to store the content twice).
Try looking into using MYSQLs full text search functionality, in natural language mode.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html


text:
Q: Draw a Rect using GUI.DrawTexture on exactly gameobject's position Unity I have to use the "GUI.DrawTexture(new Rect..." function to draw a rectangle on my screen(actually, it's a gradient GUI bar i got from https://www.assetstore.unity3d.com/en/#!/content/19972, but deep inside it's just a rectangle). I want to do it right beside a gameobject i have on my screen.
The problem is: It seems like rectangle's coordinates are not the same as a gameobjects coordinates(i have searched online and i guess it's true). I have tried the function below to convert a gameobject's position to a rectangle's coordinates but still no luck:
 public Vector2 WorldToGuiPoint(Vector2 position)
     {
         var guiPosition = Camera.main.WorldToScreenPoint(position);
         guiPosition.y = Screen.currentResolution.height - guiPosition.y;

         return guiPosition;
     }

My best strike was when i did this:
Vector3 gameObjectsPosition = Camera.main.WorldToScreenPoint(gameObject);

And then when i wanted to draw the rectangle i did:
GUI.DrawTexture(new Rect(gameObjectsPosition.x, Screen.height - gameObjectsPosition.y, Background.width * ScaleSize, Background.height * ScaleSize), Background);

But still, the Rect isn't on the exact gameObject's position. It's x is right but y don't and when i searched the internet, they said I only had to do the "Screen.height - gameObjectsPosition.y" when drawing the Rect. It didn't work for me, the y is still wrong.
What should i do to create a rectangle that's like, right beside a current gameobject on screen (like, if the gameobject's position is x = -401 and y = -80, i want it on y=-80 and x=-300)

A: You need to use Screen.height instead of
Screen.currentResolution.height
using UnityEngine;
using System.Collections;
public class GuiPosition : MonoBehaviour
{

    public Vector2 WorldToGuiPoint(Vector3 GOposition)
    {
        var guiPosition = Camera.main.WorldToScreenPoint(GOposition);
        // Y axis coordinate in screen is reversed relative to world Y coordinate
        guiPosition.y = Screen.height - guiPosition.y;

        return guiPosition;
    }

    void OnGUI()
    {
        var guiPosition = WorldToGuiPoint(gameObject.transform.position);
        var rect = new Rect(guiPosition, new Vector2(200, 70));
        GUI.Label(rect, "TEST");
    }
}

I've just tested attaching that MonoBehaviour to a Cube GameObject and it works


text:
Q: How to configurate my ckeditor for correct display image the picture climbs out of the div
and when i open site on mobile divice pictures show no correct

{{ post.text | safe }}

problem on mobile divice,
big screen problem

A: Edit contents.css in CKEditor's top-level folder. (Same folder as ckeditor.js)
Go to the bottom of the file and add whatever CSS code you like to enforce max widths and responsive behavior. e.g.
p.lead img {
  max-width: 100%;
}

If you need further help on this, I recommend adding the tag css to your question.


text:
Q: How to reset a button/label in Xcode 5 I am creating an app where you press a button and then it gives you a tally in a label. I then have a button to clear out the information.
Example. If I press buttonTwo it will add "1" to the label "labelTwo". A user pressed the button 5 times and the labelTwo will show "5". I click "clearButton" and it clears it out.
My issue is that after clearing, if I press button two, labelTwo will not restart at "1" but continue at "6" as if I never cleared it.
Thank you
 - (IBAction)buttonFour:(id)sender {
    self.four += 1;
    [self.labelFour setText:[NSString stringWithFormat:@"%d", self.four]];
}

- (IBAction)buttonThree:(id)sender {
    self.three += 1;
    [self.labelThree setText:[NSString stringWithFormat:@"%d", self.three]];
}

- (IBAction)buttonTwo:(id)sender {
    self.two += 1;
    [self.labelTwo setText:[NSString stringWithFormat:@"%d", self.two]];
}

- (IBAction)buttonOne:(id)sender {
    self.one += 1;
    [self.labelOne setText:[NSString stringWithFormat:@"%d", self.one]];
}

- (IBAction)clearButton:(id)sender {
    self.clear = 0;
    [self.clearFour setText:[NSString stringWithFormat:@"%d", self.clear]];
    self.clear = 0;
    [self.clearThree setText:[NSString stringWithFormat:@"%d", self.clear]];
    self.clear = 0;
    [self.clearTwo setText:[NSString stringWithFormat:@"%d", self.clear]];
    self.clear = 0;
    [self.clearOne setText:[NSString stringWithFormat:@"%d", self.clear]];
    self.clear = 0;
    [self.clearTotal setText:[NSString stringWithFormat:@"%d", self.clear]];
}

- (IBAction)totalOne:(id)sender {
    self.oneTotal +=1; [self.total setText:[NSString stringWithFormat:@"%d", self.oneTotal]];
}

- (IBAction)totalTwo:(id)sender {
    self.oneTotal +=1; [self.total setText:[NSString stringWithFormat:@"%d", self.oneTotal]];
}

- (IBAction)totalThree:(id)sender {
    self.oneTotal +=1; [self.total setText:[NSString stringWithFormat:@"%d", self.oneTotal]];
}

- (IBAction)totalFour:(id)sender {
    self.oneTotal +=1; [self.total setText:[NSString stringWithFormat:@"%d", self.oneTotal]];
}

A: You need to set the value of self.two back to zero in the clearButton: method. Add this to your clearButton: method:
self.one = 0;
self.two = 0;
self.three = 0;
self.four = 0;
self.five = 0;


text:
Q: How to stop timer event when child form closes in MDI project I'm not a regular when it comes to windows forms but still getting better at C# in general. I'm developing a project for a comp. prog. class and it's an MDI form that allows multiple child forms.
Here's my pickle,
I've got a timer on the parent form that; when ticking, handles two label methods ..one to count characters in a text document and the other to display a zoom level.
I can get the timer to fire and handle my events when a child windows opens but when I close the window, I am trying to figure out how to stop the timer some how.
I've tried the form.closing event and tried disabling the timer when I was done but this didn't help.
The project is a text editor and the object's name id "Document". When the object is Disposed, naturally I get an exception but I want to disable the timer before this happens.
"Cannot Access a Disposed Object"
Here's my New() method to call a an instance of a child form..
        void New()
      {
          // Generate a new form from scratch
          TextEditorChild = new Form();  // Declare a variable containing a new Form method
          TextEditorChild.Text = "Document " + count.ToString();  // Text Property - also gets the forms order number
          TextEditorChild.Icon = Properties.Resources._new_doc_icon;  // Use our own icon
          TextEditorChild.MdiParent = this;  // Ensure we are using the original form as the parent form
          Document = new RichTextBox();  // Call a new RichTextBox object
          Document.Multiline = true;  // Yes, a multiline textbox
          Document.Dock = DockStyle.Fill;  // Ensure that the textbox fills the new window
          TextEditorChild.Controls.Add(Document);  // Apply our controls to the child window
          TextEditorChild.Show();  // Display the window
          count++;  // Add this window to a potnetial list of windows, should multiple be opened all at once
          timer.Enabled = true;
      }

Here's my timer even handler...
       private void timer_Tick(object sender, EventArgs e)
    {
            charCount.Text = "Characters in the current document: " + Document.TextLength.ToString();
            zoom.Text = Document.ZoomFactor.ToString();
    }

A: You could add
TextEditorChild.FormClosing += new FormClosingEventHandler(Close);

In the method new()

private void Close(object sender, FormClosingEventArgs e)
{
    timer.Enabled = false;
}

And add this below, as a new method

This makes it so that when the form closes, it stops the timer, and then quits the form

A: Just prior to the line where you are enabling the timer add this code:
        var tec = TextEditorChild;
        FormClosingEventHandler closing = null;
        closing = (s, e) =>
        {
            tec.FormClosing -= closing;
            if (--count == 0)
            {
                timer.Enabled = false;
            }
        };
        tec.FormClosing += closing;

This should stop the timer when all of your windows are closed. I captured the module level TextEditorChild as tec to make sure the reference doesn't change when you open new child windows.
I assume that you are decrementing the count value elsewhere so you need to adjust your logic to make this work, but this should be a good start.


text:
Q: Check if product with category "A" is in the cart and apply a 10% discount to all products with category "B" in the cart: I'm trying to add a 10% discount to all products that fall into category B when a product from category A is in the cart, this is what i've tried so far and from what I see there's not an obvious reason but the discount is not applied in the cart. It can be a total discount fee or a separate discount for each item.
add_action( 'woocommerce_before_calculate_totals', 'apply_category_discount_in_cart', 10, 1 );

function apply_category_discount_in_cart( $cart ) {

  if ( is_admin() && ! defined( 'DOING_AJAX' ) )
    return;

  if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
    return;

  $discount_amount = 0;
  $category_A_in_cart = false;

  // Loop through each item in the cart
  foreach ( $cart->get_cart() as $cart_item ) {
    $product = $cart_item['data'];

    // Check if the product has category A
    if ( has_term( 'categorya', 'product_cat', $product->get_id() ) ) {
      $category_A_in_cart = true;
      break;
    }
  }

  // If a product with category A is found in the cart
  if ( $category_A_in_cart ) {
    // Loop through each item in the cart again
    foreach ( $cart->get_cart() as $cart_item ) {
      $product = $cart_item['data'];

      // Check if the product has category B
      if ( has_term( 'categoryb', 'product_cat', $product->get_id() ) ) {
        $discount_amount += $cart_item['line_total'] * 0.1;
        $cart_item['data']->set_price( $cart_item['data']->get_price() * 0.9 );
      }
    }

    // Add the discount amount as a fee
    $cart->add_fee( 'Discount', -$discount_amount, true );
  }

}


text:
Q: Supplying string parameters to Sweave document This must be a simple question but I don't figure out how I can do it.
I would like to produce a pdf report using Sweave. And actually, many many reports.
I shortened and simplified the sweave code to get to the point. Here's the code (short.rnw) :
\documentclass[a4paper,11pt]{article}
\usepackage[latin1]{inputenc}
\usepackage[OT1]{fontenc}
\usepackage{graphicx}
\usepackage{Sweave}

\begin{document}
\section*{MySection}

\begin{figure}[htbp]
\caption*{MyCaption}
<<echo=FALSE,results=tex>>=
file=paste(getwd(),"fig","boxp.png",sep="/")
cat("\\includegraphics[width=0.5\\textwidth]{",file,"}",sep="")
@
\end{figure}

\end{document}

As you can see, this code simply includes a graphic named "boxp.png" in the report. I actually don't need sweave to do this but what I really want to do is to generate multiple reports with a varying filename.
So, is there a way to pass a string parameter (or any kind of parameter) to build the report without having to rewrite the sweave template each time ?
I generate the reports from a bash script with the command 'R CMD Sweave short.rnw', the string parameters being defined before this call.
EDIT :
#!/bin/bash

for f in ${files}
do

prog1 f
# prog1 is a program which generates figures in a directory dir
# this directory has a name depending on f name
# for instance if f="foo.txt", then dir="./foo_dir"

###
#And now HERE I have to create my report with the images
#in foo_dir
# And I don't know how I can specify the varying names of dir
# in my template...

done

Thanks.
Tony

A: there are two ways to do what you seek. one is using sweave, the other is using an R package called brew which overcomes sweave's limitations of looping over a global variable. i am providing both code chunks.
The Sweave Code Chunk
\begin{document}
<<echo = F, results = tex>>=

figdir   = paste(getwd(), 'fig', sep = '/')
fignames = read.csv('fignames.csv');
for (i in seq_along(fignames)) {

 filename = file.path(figdir, i)

 cat("\\pagebreak");
 cat("\\section{", i, "}", sep = "");
 cat("\\begin{figure}[htbp]");
 cat("\\caption*{MyCaption", i, "}", sep = "");
 cat("\\includegraphics[width = 0.5\\textwidth]{", filename, "}", sep = "");
 cat("\\end{figure}");
}
@

\end{document}

The Brew Code Chunk
\begin{document}
<% figdir   = paste(getwd(), 'fig', sep = '/') %>
<% fignames = read.csv('fignames.csv');
<% for (i in seq_along(fignames)) { -%>

\pagebreak

<% filename = file.path(figdir, i) %>
<%= cat("\section{", i, "}", sep = "") %>

\begin{figure}[htbp]
\caption*{MyCaption}

<%= cat("\\includegraphics[width = 0.5\\textwidth]{filename}")

\end{figure}
<% } -%>
\end{document}

you can check out the link to brew on how to use it from R
EDIT: this would produce a single file with all the output.

A: I had a similar issue where I wanted to 'push' a variable from my R session into a sweave document (see https://stackoverflow.com/questions/2912270/sweave-cant-see-a-vector-if-run-from-a-function).
Rscript sweavescript.R f

It seems that when Sweave runs, it can see objects in the global environment., so you could call R from your bash script passing the value of 'f' to the script (see https://stackoverflow.com/questions/3433603/parsing-command-line-arguments-in-r-scripts).  The script would then put that value of 'f' into the global environment
f<<-commandArgs(trailingOnly = T)

and then runs sweave, where your sweave template then uses the value of f to generate images.
Hope this gets you started.


text:
Q: Angular Http Client Rest Api Delete Request Currently, i'm learning http request module in Angular.
My problem is why the error didn't occur and still get deleted even the request id delete is out the list of data.
deletePost(x) {
this.s.deleteInfo(33).subscribe(res => {
  console.log(res);
  let index = this.post.indexOf(x);
  this.post.splice(index, 1);
},(error:Response)=>{
  if(error.status ==404){
    alert("Expected Error!");
    console.log("hello")
  }
});

As we can see there is only 6 data displayed on the console, but i can still delete with the id of 33

A: It is because your request was successful.
Here to achieve the functionality you want you need to do something like below:
if(this.post.indexOf(33) == -1){
    alert("Expected Error!");
}
else{
    console.log('Hurray!')
}

Or if you are not doing it, you can catch error in your service like below:
import { catchError } from 'rxjs/operators';

errorHandler(error: HttpErrorResponse) {
   return Observable.throw(error.message || "server error.");
}
this.http.get(this.url).pipe(catchError(this.errorHandler))


text:
Q: Elasticsearch processes memory and cpu load I'm running rails gem Searchkick to access Elasticsearch rpm (centos6) installation and I see several Elasticsearch processes having different names (through NewRelic) such as:
java (elasticsearch) 256MB
freeBSD (elasticsearch) 15MB
99 (elasticsearch) 9 MB
linux64 (elasticsearch) 9MB
ru1 (elasticsearch) 1MB
ru (elasticsearch) 0MB
What are all these processes for? What does those names mean? How can I manage them? What's happening at all?!


text: Q: Excel graph "show empty cells as: Connect data points with line" behavior with formula [excel] How to create the graph "show empty cells as: Connect data points with line" behavior when the cell contains a formula that cannot return "empty" but "" as best.


text:
Q: save_and_open_page and spork, spork is loosing test suite / output When i run my rspec tests with spork, every time i use capybara's save_and_open_page, spork is loosing the test suite.. or maybe doesnt output anything anymore...
See the log
# => without save_and_open_page
09:04:24 - INFO - Spork server for RSpec, Test::Unit successfully started

09:04:24 - INFO - Guard::RSpec is running
09:04:24 - INFO - Running all specs
Running tests with args ["--drb", "-f", "progress", "-r", "/Users/myuser/.rvm/gems/ruby-1.9.3-p392/gems/guard-rspec-2.5.2/lib/guard/rspec/formatter.rb", "-f", "Guard::RSpec::Formatter", "--failure-exit-code", "2", "spec"]...
................

Finished in 4.1 seconds
16 examples, 0 failures

Randomized with seed 50331

Done.

# => with save_and_open_page, no .... are shown anymore
09:04:29 - INFO - Guard is now watching at '/Users/myuser/coding/myproject'
09:04:39 - INFO - Running: spec/features/registration/registration_process_spec.rb
Running tests with args ["--drb", "-f", "progress", "-r", "/Users/myuser/.rvm/gems/ruby-1.9.3-p392/gems/guard-rspec-2.5.2/lib/guard/rspec/formatter.rb", "-f", "Guard::RSpec::Formatter", "--failure-exit-code", "2", "spec/features/registration/registration_process_spec.rb"]...
Done.

# => without save_and_open_page, also no .... anymore (after restart it works again)
[1] guard(main)> Running tests with args ["--drb", "-f", "progress", "-r", "/Users/myuser/.rvm/gems/ruby-1.9.3-p392/gems/guard-rspec-2.5.2/lib/guard/rspec/formatter.rb", "-f", "Guard::RSpec::Formatter", "--failure-exit-code", "2", "spec/features/registration/registration_process_spec.rb"]...
Done.

    # => here i added some errors into my code... still no error message shown...
[1] guard(main)> Running tests with args ["--drb", "-f", "progress", "-r", "/Users/myuser/.rvm/gems/ruby-1.9.3-p392/gems/guard-rspec-2.5.2/lib/guard/rspec/formatter.rb", "-f", "Guard::RSpec::Formatter", "--failure-exit-code", "2", "spec/features/registration/registration_process_spec.rb"]...
Done.

# only works again after restarting spork

Any suggestions?

A: Somehow your STDOUT is getting replaced with some other buffer. So whatever is being written by Capybara to STDOUT is getting ignored or consumed somewhere else.
Try the following:
# Add global before/after blocks
before :each do
  @old_stdout, @old_stderr = STDOUT, STDERR
end

after :each do
  STDOUT,  STDERR  = @old_stdout, @old_stderr

  # Some gems use $stdout and $stderr, instead of STDOUT and STDERR, replace those too
  $stdout, $stderr = @old_stdout, @old_stderr
end

Capybara's save_and_open_page uses Launchy gem. So I believe the STDOUT and STDERR are getting stubbed in one of these gems.

A: I found the real solution for described problem at http://blog.mikecordell.com/2013/08/14/guard-and-capybara's-save_and_open_page.html. Special thanks to the actual author of this solution.
Simply add:
RSpec.configure do |config|
  config.before(:each) do
    @old_stdout, @old_stderr = STDOUT, STDERR
  end

  config.after(:each) do
    $stdout, $stderr = @old_stdout, @old_stderr
  end
end

to the spec_helper.rb


text:
Q: Problem, calculating the conditional Probability I am preparing for my exam and have come across this task that causes me problems.
A disease is genetic, and occurs when both genes have a particular mutation. If the disease occurs, the person dies before it can reproduce, that is, as a child. We use the following model. A child receives a gene from father and mother independently of each other. Parents are equally likely to give each of their two genes on. In the adult population, regardless of gender, the percentage of people who do not carry a mutated gene is $\alpha$. Pair formation takes place
regardless of whether the persons carry a mutated gene or not.
a) Calculate the probability that a child is ill and the probability,
that a child doesn't have a mutated gene.
b) Calculate the proportion of the next generation adult population,
that doesn't carry a mutated gene.
c) We assume that the disease has existed for a very long time, and that
so that the portion $\alpha \in$ [0; 1] is stable, i. e. it does not change in the next Generation changes. Calculate $ \alpha $ .
d) Interpret the result from c).
I've done this assignment and I'm gonna get this:
a): Define the sets:
$$M_f = \textrm{Father has mutated gen}\\
\overline{M_f} = \textrm{Father has no mutated gen}\\
M_m = \textrm{Mother has mutated gen}\\\
\overline{M_m} =  \textrm{Mother has no mutated gen}\\ M_c= \textrm{Children has mutated gen}\\
\overline{M_c} = \textrm{children has no mutated gen}\\ \textrm{Then:}\\ P[M_c] = \frac{1}{2} P[M_m] \times \frac{1}{2} P[M_f] = \frac{1}{4} (1 - \alpha)^2 \\ \textrm{and} \\ P[\overline{M_c}] = \frac{1}{2} P[\overline{M_m}] \times \frac{1}{2} P[\overline{M_f}] = \frac{1}{4} \alpha^2 $$
The first solution is right, but the second is wrong. The solutions say that the result for the second one must be $ \frac{1}{4} (1+\alpha)^2$. That is why i stopped working on this exercise. Can anyone tell me how they got the result and why my result is wrong? Could someone also tell me how to go an on b)?
thank you in advance!
I try to use the formula down in the comment:
$$ P[\overline{M_c}] = P[\overline{M_c} \vert M_v M_f] P[M_v M_f] + P[\overline{M_c} \vert \overline{M_v} M_f] P[ \overline{M_v }M_f] + P[\overline{M_c} \vert \overline{M_f} M_v] P[ \overline{M_f }M_v] +P[\overline{M_c} \vert \overline{M_v} M_f] P[ \overline{M_v } \overline {M_f}] $$
i would say that $$P[M_v M_f] = \frac{1}{2} \alpha * \frac{1}{2} \alpha = \frac{1}{4} \alpha^2 \\
P[ \overline{M_v }M_f] = \frac{1}{2} \alpha * \frac{1}{2} (1 - \alpha) = \frac{1}{4} \alpha *(1- \alpha) = P[ \overline{M_f }M_v] \\
 P[ \overline{M_v } \overline {M_f}] = \frac{1}{4} (1-\alpha)^2$$
Can someone tell me, how to calculate the probability of $$ P[\overline{M_c} \vert M_v M_f] \\
P[\overline{M_c} \vert \overline{M_v} M_f]\\
... $$

A: There are 3 ways
1)both parents do not have mutated genes:probability=(alpha)^2
Probability that no mutated gene transported to child and both parents are normal is (alpha)^2(both genes are normal any case is favourable)
2)both patents have mutated genes :probability (1-alpha)^2
Probability that no mutated gene transported to child and both parents are carriers =1/4(1-alpha)^2(its equally probable from both parents to give normal gene so a factor 1/4)
3)one parent is normal and one parent is carrier:probability = 2*(1-alpha)(alpha)
(Now why the extra factor 2, this can be easily viewed though either mother is carrier or father is carrier. Take a example of deck of 52 cards , now tell me which is more probable , getting 4 aces or 1ace, 1 queen, 1king  and 1 jack .if you have any doubts simply do it by: 1-(alpha)^2 -(1-alpha)^2)
Now probability of no mutated gene transported and one parent carrier and one parent normal=1/2*2*(1-alpha)(alpha).  (An extra factor 1/2 appeared because one parent who is normal can give any of the genes but the other parent have to give one of 2 possibe gene)
Therefore total probability(addition of above three cases)
=(Alpha)^2 + 1/4*(1-alpha)^2 + (alpha)*(1-alpha)
=1/4*(1 + (alpha)^2 + 2*(alpha) ) = 1/4* (1+ alpha)^2
I think u can figure out your mistake


text:
Q: Как избежать повторения кода в наследуемых классах? 2 В этом вопросе, мне посоветовал создать дополнительный abstract class.
Как избежать повторения кода в наследуемых классах?
К сожалению это не решило проблему, прошу Вашей помощи.
Важно то, что все новые сущности внутри наследуемых классов, принимают разные входящие значения.
Код:
//базовый класс
abstract class BaseStrategy
{
    //переменная для примера, она будет использована в наследуемом классе
    protected int VariableForSignal = 77;
    //переменная для примера, она будет использована в наследуемом классе
    protected int VariableForOpen = 5;

    //другой manager
    AnotherManager AnotherManager = new AnotherManager();

    //основная функция в которую поступают данные
    public void GetDecimalUpdate(decimal IncomeValue)
    {
        //опрашиваем первый фильтр
        if(!SignalFilterAnswer(IncomeValue))
            return;

        //опрашиваем второй фильтр
        if(!OpenFilterAnswer(IncomeValue))
            return;

        //опрашиваем третий фильтр
        if(!AnotherManager.ReturnAnswer())
            return;
    }

    //реализацию ответа фильтра оставляем наследуемым классам
    protected abstract bool SignalFilterAnswer(decimal IncomeValue);

    //реализацию ответа фильтра оставляем наследуемым классам
    protected abstract bool OpenFilterAnswer(decimal IncomeValue);
}

//наследуем базовый класс, реализуя только метод OpenFilterAnswer
abstract class StupidPaperImplementation : BaseStrategy
{
    //open filter
    StupidPaper StupidPaper = new StupidPaper();

    //реализуем метод, который выполняет работу "open filter"
    protected override bool OpenFilterAnswer(decimal IncomeValue)
    {
        // этот IF для того чтобы показать, что используются protected переменные базового класса
        if(VariableForOpen > IncomeValue)
            return StupidPaper.ReturnAnswer();
        else
            return StupidPaper.ReturnAnswer();
    }
}

//наследуем StupidPaperImplementation и оставшуюся часть реализуем в этом классе
class StupidPaperStrDiffStrategy : StupidPaperImplementation
{
    //signal filter
    StrDiff StrDiff = new StrDiff();

    //реализуем метод, который выполняет работу "signal filter"
    protected override bool SignalFilterAnswer(decimal IncomeValue)
    {
        //этот IF для того чтобы показать, что используются protected переменные базового класса
        if(VariableForSignal < IncomeValue)
            return StrDiff.ReturnAnswer(true, new int[] { 1, 2 });
        else
            return StrDiff.ReturnAnswer(false, new int[] { 2, 3 });
    }
}

В данном случае все отлично работает, но если я хочу наследовать класс и заменить в нем StupidPaper на TimeFrame код StrDiff реализующий метод SignalFilterAnswer повторяется дважды.
//наследуем базовый класс, реализуя только метод OpenFilterAnswer
abstract class TimeFrameImplementation : BaseStrategy
{
    //open filter
    TimeFrame TimeFrame = new TimeFrame();

    //реализуем метод, который выполняет работу "open filter"
    protected override bool OpenFilterAnswer(decimal IncomeValue)
    {
        // этот IF для того чтобы показать, что используются protected переменные базового класса
        if(VariableForOpen > IncomeValue)
            return TimeFrame.ReturnAnswer(new byte[] { 144, 4 });
        else
            return TimeFrame.ReturnAnswer(new byte[] { 12, 4 });
    }
}

//наследуем TimeFrameImplementation и оставшуюся часть реализуем в этом классе
class TimeFrameStrDiffStrategy : TimeFrameImplementation
{
    //signal filter
    StrDiff StrDiff = new StrDiff();

    //реализуем метод, который выполняет работу "signal filter"
    protected override bool SignalFilterAnswer(decimal IncomeValue)
    {
        //////////////////////////////////////////
        // Проблема находиться тут, этот код уже был написан в классе StupidPaperStrDiffStrategy и повторяется в этом классе
        /////////////////////////////////////////
        if(VariableForSignal < IncomeValue)
            return StrDiff.ReturnAnswer(true, new int[] { 1, 2 });
        else
            return StrDiff.ReturnAnswer(false, new int[] { 2, 3 });
    }
}


text:
Q: Data from some Facebook users not inserting to mysql database I have a strange, but definitely serious problem regarding fetching data from some Facebook users who authorize my App and use it (normally by the way).
Around 3000 users have used the App so far, but only 600 are showing up in the users table. How could that be possible? I cannot find connection between old and new users - for some it works flawlessly, for others it just doesn't work at all.
Here's the complete, but for security reasons censored code:
<?php
 require 'facebook.php';
 include 'config.php';
 session_start();

 $app_id = 'id';
 $app_secret = 'secret';
 $app_namespace = 'namespace';
 $app_url = 'https://apps.facebook.com/' . $app_namespace . '/';
 $scope = 'email,publish_actions';

// Init the Facebook SDK
    $facebook = new Facebook(array(
    'appId'  => $app_id,
    'secret' => $app_secret,
    'cookie' => true
    ));

// Get the current user
 $user = $facebook->getUser();

// If the user has not installed the app, redirect them to the Auth Dialog
 if (!$user) {
    $loginUrl = $facebook->getLoginUrl(array(
    'scope' => $scope,
    'redirect_uri' => $app_url,
    ));

print('<script> top.location.href=\'' . $loginUrl . '\'</script>');
 }

 else if ($user) {
    try {

// Proceed knowing we have a logged in user who's authenticated.
    $fbuid = $facebook->getUser();
    $user_profile = $facebook->api('/me');

} catch (FacebookApiException $e) {
    error_log($e);
    $user = null;
}
 }
else{
header('Location: index.php');

 }
 $queryUserExists = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook'AND oauth_uid = " . $user_profile['id']);
 $num=mysql_numrows($queryUserExists);

//If not, add it to the database
 if ($num == 0) {
$query = mysql_query("INSERT INTO users (oauth_uid, oauth_provider, username, first_name, last_name, email, pic_square ,login_date , dailytokens)
        VALUES ({$user_profile['id']}, 'facebook', '{$user_profile['name']}', '{$user_profile['first_name']}','{$user_profile['last_name']}','{$user_profile['email']}', '".$photolink."',CURDATE(),1)");
$query = mysql_query("SELECT * FROM users WHERE oauth_uid = " . mysql_insert_id());
$result = mysql_fetch_array($query);
 }
     else
     {
    $DateLastLogin=mysql_result($queryUserExists,0,"login_date");
    $myDate = date('Y-m-d');

    $CompLastDate = strtotime($DateLastLogin);
    $CompMyDate = strtotime($myDate);

if($CompLastDate < $CompMyDate){
    $updateDailyToken = "Update users set login_date=CURDATE(), dailytokens = dailytokens + 1 where oauth_uid =" . $user_profile['id'];
    $updateToken= mysql_query($updateDailyToken) or die(mysql_error());
}
 }
 $query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = " . $user_profile['id']);

 $_SESSION['userid']=$user_profile['id'];

// Login or logout url will be needed depending on current user state.
     if ($user) {
    $paramsout = array('next'=>'http://facebook.com');
    $logoutUrl = $facebook->getLogoutUrl($paramsout);
     }
     ?>

A: here is your problem
$query = mysql_query("INSERT INTO users (oauth_uid, oauth_provider, username, first_name, last_name, email, pic_square ,login_date , dailytokens)
        VALUES ({$user_profile['id']}, 'facebook', '{$user_profile['name']}', '{$user_profile['first_name']}','{$user_profile['last_name']}','{$user_profile['email']}', '".$photolink."',CURDATE(),1)");

it should be
$query = mysql_query("INSERT INTO users (oauth_uid, oauth_provider, username, first_name, last_name, email, pic_square ,login_date , dailytokens)
        VALUES ('{$user_profile['id']}', 'facebook', '{$user_profile['name']}', '{$user_profile['first_name']}','{$user_profile['last_name']}','{$user_profile['email']}', '{$photolink}',CURDATE(),1)");

A: Problem was with the object type in the database. Some facebook users have incredebly large id: 0098788563000236 for example, so using BIGINT instead of INT solved it.


text:
Q: Monitoring Graphite fullQueueDrops I need to monitor if Graphite is loosing metrics.
I already use https://github.com/klen/graphite-beacon to send alerts on e-mail everytime when executing the query from the following json and the values are breaking the rule
{
  "interval": "5minute",
  "logging": "debug",
  "host": "servmail01",
  "port": 25,
  "from": "BeaconAlerts@metrics01.local",
  "to": ["myemailaddress@email.com"]
  },

  "alerts": [
      {
      "name": "fullQueueDrops",
      "query": "transformNull(carbon.relays.metrics01-a.destinations.127_0_0_1:2104:a.fullQueueDrops,0)",
      "method": "average",
      "interval": "5minute",
      "rules": [ "critical: > 1" ]
    }
  ]
}

The thing is that I would like to monitor the same with zabbix (that does any other monitoring stuff on our network and I would love zabbix to send e-mails when I have metrics dropped. So I have looked to see if there's any tool available and I got into https://github.com/blacked/graphite-to-zabbix. The only problem with it is that it lacks a better documentation.
Has anyone used it? I understood that I should create a template for metrics in zabbix (which I did), to create an item corresponding to the metrics I want to send, but at some point in the documentation it says Note that g2zproxy will work with zabbix web api specified in -z argument, but it will send metrics to service specified in /etc/zabbix/zabbix_agentd.conf. What and how do I specify in that config the service? I don't get it.
Thank you.
Gabriel

A: So in the end I got to understand what one must do in order to make this work. It wasn't hard.
In zabbix I've created an item
graphite[transformNull(carbon.relays.metrics01-a.destinations.127_0_0_1:2*04:*.fullQueueDrops,0)]

which was exactly taken from graphite graph data.
The cron job works by sending the data to zabbix and the created item picks data and store it. Based on this item you can create a graph.
That's all there is. I hope that will be healpfull to anyone who use it.
I have to thank Alexey Dubkov for the wonderful job.
Alexey's github project
Gabriel


text:
Q: Configuration of the receiver I need create a receiver that process information HTTP/TEXT, for example:
curl -X POST -d Data:HolaMundo\r\Data2:Hello http://192.168.241.99:9763/endpoints/httpReceiverTEXTDSB --header "Content-Type:text/plain"

My STREAM has two attributes (DATA and DATA2), but in my HTTP I dont use (,), I need use (\r).
Is possible that my receiver runs with this configuration.

A: Yes it is possible to do with WSO2 CEP. You can map your string to event stream attributes by using regular expressions as explained in CEP sample 0006[1]. This[2] is the event receiver implemented in above sample with custom mapped fields with regular expressions.
[1] https://docs.wso2.com/display/CEP410/Sample+0006+-+Receiving+Custom+Text+Events+via+HTTP+Transport
[2] https://github.com/wso2/product-cep/blob/master/modules/samples/artifacts/0006/eventreceivers/httpReceiver.xml


text:
Q: Character Encoding in Postgres I have UTF8 data stored in Postgres.  I can query it with a Perl script and display it properly.  When I use the Postgres client, it displays like the encoding is off.  I'll see characters displayed like \u0087\u0081.
From inside the database:
=> \encoding
UTF8

In the shell (I manually set LANGUAGE as I read elsewhere that might be a fix.):
$locale
LANG=en_US.UTF-8
LANGUAGE=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

This is in Ubuntu 16.04.
What setting have I missed?
Edited to add code populating psql:
#!/usr/bin/perl

use strict;
use warnings;
use DBI;

### Source DB setup
my $maria_database="srcdb";
my $maria_user = "";
my $maria_password = "";
my $maria_host= "localhost";

my $mariadbh = DBI->connect("dbi:mysql:database=$maria_database;host=$maria_host","$maria_user","$maria_password",{AutoCommit=>1,RaiseError=>1,PrintError=>0,mysql_enable_utf8=>1});

my $mysrcquery = "SELECT fields from sourcetable limit 2;";
my $src = $mariadbh->prepare($mysrcquery);

### Destination DB setup
my $postgresql_database="desdb";
my $postgresql_user="";
my $postgresql_password="";
my $postgresql_host="localhost";

my $dbh = DBI->connect("DBI:Pg:dbname=$postgresql_database; host=$postgresql_host", "$postgresql_user", "$postgresql_password", {AutoCommit => 0,pg_enable_utf8 => 1});

my $pginsertquery = "insert into desttable (fields) VALUES (?)";
my $pginsert = $dbh->prepare($pginsertquery);

$src->execute();
my ($col0);
$src->bind_columns(undef, \$col0 );

### Loop through results and insert in to psql
while($src->fetch())
{
  print $col0;
  $pginsert->execute($col0);
}

$dbh->commit;
$dbh-> disconnect or warn "Disconnection failed: DBI::errstr\n";
$mariadbh-> disconnect or warn "Disconnection failed: DBI::errstr\n";

Test sqldump:
--
-- PostgreSQL database dump
--

-- Dumped from database version 9.6.1
-- Dumped by pg_dump version 9.6.1

SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

SET search_path = public, pg_catalog;

SET default_tablespace = '';

SET default_with_oids = false;

--
-- Name: test; Type: TABLE; Schema: public; Owner: testuser
--

CREATE TABLE test (
    testdata text
);

ALTER TABLE test OWNER TO testuser;

--
-- Name: test id; Type: DEFAULT; Schema: public; Owner: testuser
--

ALTER TABLE ONLY test ALTER COLUMN id SET DEFAULT nextval('test_id_seq'::regclass);

--
-- Data for Name: test; Type: TABLE DATA; Schema: public; Owner: testuser
--

COPY test (testdata) FROM stdin;
пÑ<80>ивеÑ<82>Ñ<81>Ñ<82>вÑ<83>Ñ<8e>
\.

--
-- PostgreSQL database dump complete
--

A: \u0087 (END OF SELECTED AREA) and \u0081 are control characters in the LATIN-1 block. Displaying them as \u0087\u0081 is in fact the convention, and it seems to be what your terminal is doing.
Can you show us the Perl script to insert the data into the database? My assumption is that Perl is inserting non-utf8 data because working with utf8 in perl is a PITA. That PostgreSQL assumes it's utf8 and that the terminal has no idea of how to display it, becuase it's

*

*not really utf8, just marked up as utf8.

*or, you have legitimate control characters encoded in your utf8.

Be careful if you used utf8::upgrade or the like which sets the flag without decoding from the original format.
Advice
Update DBD::Pg, DBD::mysql
First update both DBD::Pg, and DBD::mysql
cpan DBD::Pg DBD::mysql

Bug in DBD::mysql
Reviewing change logs, DBD::mysql has always had a bug, you may even want to install the development version (DBD-mysql-4.041_01)..
2016-12-12 Patrick Galbraith, Michiel Beijen, DBI/DBD community (4.041_1)
* Unicode fixes: when using mysql_enable_utf8 or mysql_enable_utf8mb4,
  previous versions of DBD::mysql did not properly encode input statements
  to UTF-8 and retrieved columns were always UTF-8 decoded regardless of the
  column charset.
  Fix by Pali Rohár.
  Reported and feedback on fix by Marc Lehmann
  (https://rt.cpan.org/Public/Bug/Display.html?id=87428)
  Also, the UTF-8 flag was not set for decoded data:
  (https://rt.cpan.org/Public/Bug/Display.html?id=53130)

Who knows what the hell they're doing there. Unicode is complex and it's not surprising that MySQL developers and users don't understand it.
Unsetting assumptions
I would unset pg_enable_utf8 and mysql_enable_utf8. Pretend these options exist. You're force-setting a utf8 flag on the internal variable. You probably don't want to do that. You clearly can't ensure everything is utf8, or it'd be working properly. Time to remove assumptions. Not create more assumptions.
We need a sample case. You claim foreign characters are displaying as Unicode escape sequences, but you only present control-characters (which can't be displayed). Perhaps you can simply this whole thing, and dump the table pg_dump -t <Table> or copy the problematic rows into a temp table and dump that. Then we can review that data and see what we've got.


text:
Q: How do I edit a URL's location and use it for my code I am trying to create a simple bot using rasa which runs on Python to extract data from an api.
To make explanations easier let us assume it is a corona tracker bot. So the api URL for the corona data is made so that the final section of it filters the api data to a specific set of data so for example:
https://exampleurl.com/api/corona/country/Germany
This means it only contains the data from Germany, but if i were to change it to Russia for example, then it would display the data from Russia.
What I want is that when someone tells my bot "Please tell me how Russia is doing" the bot will recognize first the correct intent and also that the entity is Russia. With that entity I want it to place it into the correct place of the URL and put that into a custom action which will extract the data from the api.
So to summarize I want that entity <Country> gets inputted into https://exampleurl.com/api/corona/country/<country>

A: *

*Use python string concatenation to join 2 strings like so:

country = "Russia"
url = "https://exampleurl.com/api/corona/country"
new_url = url + '/' + country

*Use formatted string literals, introduced in Python 3.6:

new_url = f"{url}/{country}"


text:
Q: "Which answer in this list is the correct answer to this question?" I received this question from my mathematics professor as a leisure-time logic quiz, and although I thought I answered it right, he denied. Can someone explain the reasoning behind the correct solution?

Which answer in this list is the correct answer to this question?

*

*All of the below.

*None of the below.

*All of the above.

*One of the above.

*None of the above.

*None of the above.

I thought:

*

*$2$ and $3$ contradict so $1$ cannot be true.

*$2$ denies $3$ but $3$ affirms $2,$ so $3$ cannot be true

*$2$ denies $4,$ but as $1$ and $3$ are proven to be false, $4$ cannot be true.

*$6$ denies $5$ but not vice versa, so $5$ cannot be true.

at this point only $2$ and $6$ are left to be considered. I thought choosing $2$ would not deny $1$ (and it can't be all of the below and none of the below) hence I thought the answer is $6.$
I don't know the correct answer to the question. Thanks!

A: First suppose there is only one correct answer, as perhaps implied by the question. $1,3,4,$ if true, imply more than one correct answer, and so cannot be true. If $2$ is true and $1,3$ are not then $4$ is true. So $2$ must be false. If $6$ is true, then $1,2,3,4$ are false and $5$ is true, contradicting $6$. So $5$ is the only possibility.
Now assume open season, and more than one could be true.
If $1$ is true then $2$ is true, but that is impossible for $3$. So $1$ is false. If $2$ is true and $1$ false, $3$ is false and $4$ is true, but that contradicts $2$. $3$ and $4$ are then false because everything above them is false. The same argument about $5$ and $6$ applies as before. So $5$ is true.

A: It is important to distinguish the present question:

Which answer in this list is the correct answer to this question?

from the following:

Which answer in this list is true?

When we are asked:

Which answer in this list is true?

*

*All of the below.

*None of the below.

*All of the above.

*One of the above.

*None of the above.

*None of the above.

The correct answer is option 5, which we can discover by assuming the truth of each statement in turn and ruling out each non-viable option.
See this post for a similar question.
However, the original question—Which answer in this list is the correct answer to this question?—requires another approach.
To see this, let's present the same question with a different answer set.

Which answer in this list is the correct answer to this question?

*

*Some roses are red.

*Some violets are blue.

*All dogs are mammals.

*All of the above.

*None of the above.

On further reflection, we are dealing with a pseudo question.
1–3 are all true, which may tempt us to choose answer 4. However, 4 does not really answer this question.
Once we see that 1-4 do not really answer this question, the new temptation is to choose answer 5. However, 5 does not answer the question either—it merely declares that there is no satisfactory answer listed among the answer choices.
To see this more clearly, let's look at a different question.

Which US President in this list signed the Emancipation Proclamation?

*

*George Washington

*Thomas Jefferson

*Millard Fillmore

*None of the above.

Since I know that Abraham Lincoln—not Washington, Jefferson, or Fillmore—signed the Emancipation Proclamation, I would most certainly choose option 4 on any standard multiple-choice test. However, my choosing option 4 has to do with testing conventions, not giving the correct answer to the question. The Emancipation Proclamation was signed by Lincoln, not by "none of the above."
So, even when we look at a real, rather than pseudo, question selecting "none of the above" is a testing convention by which the test-taker claims that the answer set has no satisfactory answer. Note: declaring that there is no satisfactory answer listed among the answer choices is different from providing the correct answer.
With this in mind, let's go back to the original:

Which answer in this list is the correct answer to this question?

*

*All of the below.

*None of the below.

*All of the above.

*One of the above.

*None of the above.

*None of the above.

Once we stop treating "none of the above" as an answer to the question and start treating it as a statement about the other options, we can see that choices 2, 5, and 6 are all true statements. However, being true will not make 2, 5, or 6 an answer to the question any more than adding other true statements to the list—like "some roses are red" or "all dogs are mammals"—would make those statements an answer to the question. As with my question about the Emancipation Proclamation, to declare that no satisfactory answer is listed among the answer choices is different from providing the correct answer.
So, if we are dealing with a pseudo question, why don't we see this at first glance?
Because the list associated with this particular pseudo question uses the "none of the above" list option as a red herring to draw us off-track. We have grown accustomed to thinking that marking "none of the above" answers a question, but this is false. Again, "none of the above" allows us to declare that no satisfactory answer is listed among the answer choices, which is different from providing a correct answer.
So, there is not a correct answer choice, nor is the question even intelligible. The question's author has exploited a common misunderstanding to trick us into thinking otherwise—which makes for a great puzzle.

A: I am no logician or mathematician. Here's my layman's take on this:
a. If 1 is true, 2 is true, but 2 contradicts the rest of 1. So 1 is
   self-contradictory, so 1 is out. 2 is still in.
b. 3 can't be true because we know 1 is out. So 3 is out.
c. if 2 is true, 4 is false, but 4 in fact supports 2 being true,
   because with 1 and 3 out, the "one of the above" must be 2. 2 is
   therefore self-contradictory.  So 2 is out.
d. Having established that 1, 2 and 3 are out, 4 cannot be true. So 4 is
   out.
e. 5 being true supports the fact that 1,2,3 and 4 are out. It is
   non-committal on 6, allowing 6 to be false, which in turn allows 5 to
   be true. So 5 is still in.
f. if 6 is true, 5 must be false, meaning at least one of 1,2,3,4 are
   true, which we know to be impossible. So 6 is out.
Leaving 5.

A: Let's use predicate calculus (http://www.cs.toronto.edu/~hehner/FMSD/). I'll not explain my answer in great detail, because chapter 1 and lecture segments 1 and 2 of FMSD should suffice to explain it.
Translate the claims of each choice into the calculus:

*

*(all of the below)$1 = 2 \wedge 3 \wedge 4 \wedge 5 \wedge 6 $

*(none of the below)
\begin{align*}
    &2 \\
  = &\neg (3 \vee 4 \vee 5 \vee 6) \\
    &\text{hint: De Morgan's Law} \\
  = &\neg 3 \wedge \neg 4 \wedge \neg 5 \wedge \neg 6
\end{align*}

*(all of the above)
\begin{align*}
   &3 \\
 = & 1 \wedge 2 \\
 = & 2 \wedge (3 \wedge \neg 3) \wedge \dots \wedge (6 \wedge \neg 6) \\
 = & 2 \wedge \bot \wedge \dots \wedge \bot \\
 = &\bot
\end{align*}
Since $3 = \bot$, we can update the statements of $1$ and $2$:

*

*$1 = (2 \wedge 3 \wedge \dots \wedge 6) = 2 \wedge \bot \wedge \dots \wedge 6) = \bot$

*$2 = \neg 3 \wedge 4 \wedge \dots \wedge 6 = \top \wedge 4 \wedge \dots \wedge 6 = 4 \wedge \dots \wedge 6$
Moving on to $4$:

*

*(one of the above) $4 = 1 \vee 2 \vee 3 = \bot \vee 2 \vee \bot = 2$

*$5 = \neg 1 \wedge \neg 2 \wedge \neg 3 \wedge \neg 4 = \top \wedge \neg 2 \wedge \top \wedge \neg 4 = \neg 2 \wedge \neg 4 = \neg 2 \wedge \neg 2 = \neg 2 $

*$6 = \neg 1 \wedge \neg 2 \wedge \neg 3 \wedge \neg 4 \wedge \neg 5 = \top \wedge \neg 2 \wedge \top \wedge \neg 2 \wedge 2 = \bot$ (because $2 \wedge \neg 2 = \bot$)

Going back and examining $2$:

*

*$2 = \neg 4 \wedge \neg 5 \wedge \neg 6 = \neg 2 \wedge \neg \neg 2 \wedge \top = \neg 2 \wedge 2 = \bot $

*$4 = 2 = \bot$

*$5 = \neg 2 = \top$
So, $5$ is a theorem, and thus the only "correct answer".

A: You can use propositional logic to formalize the problem, then satisfying assignments help to find the solutions.
Let $a,b,c,d,e,f$ represent the six sentences, respectively.

*

*$a\leftrightarrow b\land c\land d\land e\land f$

*$b\leftrightarrow \neg c\land \neg d\land \neg e\land \neg f$

*$c\leftrightarrow a\land b$

*$d\leftrightarrow (a\land \neg b\land \neg c)\lor(\neg a\land b\land \neg c)\lor (\neg a\land \neg b\land c)$

*$e\leftrightarrow \neg a\land \neg b\land \neg c\land \neg d$

*$f\leftrightarrow \neg a\land \neg b\land \neg c\land \neg d\land \neg e$

Assuming there is at least one solution: 7. $a\lor b\lor c \lor d\lor e\lor f$
The only satisfying truth assignment is the one which sets $a,b,c,d,f$ to false and set $e$ true. So choice 5 is the solution.

A: // gcc ImpredictivePropositionalLogic1.c -o ImpredictivePropositionalLogic1.exe -std=c99 -Wall -O3

/*
Which answer in this list is the correct answer to this question?

(a) All of the below.
(b) None of the below.
(c) All of the above.
(d) One of the above.
(e) None of the above.
(f) None of the above.
*/

#include <stdio.h>
#define iff(x, y) ((x)==(y))

int main() {
  printf("a b c d e f\n");
  for (int a = 0; a <= 1; a++)
  for (int b = 0; b <= 1; b++)
  for (int c = 0; c <= 1; c++)
  for (int d = 0; d <= 1; d++)
  for (int e = 0; e <= 1; e++)
  for (int f = 0; f <= 1; f++) {
    int Ra = iff(a, b && c && d && e && f);
    int Rb = iff(b, !c && !d && !e && !f);
    int Rc = iff(c, a && b);
    int Rd = iff(d, (a && !b && !c) || (!a && b && !c) || (!a && !b && c));
    int Re = iff(e, !a && !b && !c && !d);
    int Rf = iff(f, !a && !b && !c && !d && !e);

    int R = Ra && Rb && Rc && Rd && Re && Rf;
    if (R) printf("%d %d %d %d %d %d\n", a, b, c, d, e, f);
  }
  return 0;
}

This outputs:
a b c d e f
0 0 0 0 1 0

The main point I'd like to get across is that you cannot assume at the outset that there is only 1 satisfying assignment.  For example consider the question:
Which of the following is true?
    (a) both of these
    (b) both of these

You might be tempted to say that both (a) and (b) are true.  But it is also consistent that both (a) and (b) are false.  The tendency to assume singularity from definitions isn't correct when the definitions are impredictive.

A: Your last point is not correct:
If 6 is true, then 5 is false, which implies that at least one of 1-4 is correct, which is a contradiction. So 6 is false.
On the other hand, 4 is not correct, this implies that 2 is incorrect. Indeed 4 is correct if and only if 2 is correct since 1 and 3 are false. (If 2 is true then 4 is true by the content of 4, but it has been shown that 4 is false.)
Hence the only choice is 5.

A: Since this is a question on mathemetics, I would argue that the correct answer is that this is not a question at all. Of course it is syntactically valid, but not semantically.
I will try to rephrase it in terms of sets:

May A be the set of possible answers. The set of correct answers B is the intersection of A and B.

This definition is clearly self-referential and therefore not covered in ZFC.
(I think I read something by Bertrand Russel once about sentences that were syntactically valid but semantically invalid. Can't remember right now. Russel's Paradox is definitely related.)
All other answers so far really answer a different question:

May A be the set of possible answers. The set of correct answers B is a non-empty subset of A that is free of contradictions. There is exactly one such subset.

A: I think this quiz tires to lead you to the closest answer instead the correct answer. IDK, just saying. So what I did was analyze the question using a matrix and crossing statements each other. Based on the result I imply the answer is statement number 6, since is the closest to a truth statement.
Happy Friday!

A: "6 denies 5 but not vice versa, so 5 cannot be true." This is the incorrect statement. You are right that 5 does not deny 6, but neither does it affirm 6, so this does not rule out 5. Rather, if 6 holds, then 5 holds a fortiori, but this is a contradiction since 6 denies 5. So 6 is ruled out, and 5 is the only possible answer.
Edit: Note that this approach does not assume that only one answer is correct! I argue above that 6 cannot be true. The OP argues quite clearly that 1, 3, and 4 cannot be true. I might revise the OP's discussion of 2 as follows: if 2 holds, then 4 is false. If we take 4 to mean "at least one of the above," this is already a contradiction. If we take 4 to mean "exactly one of the above," then since 3 is false (by 2), 1 must be true, also a contradiction. So we have shown separately that 1, 2, 3, 4, and 6 produce contradictions. Thus, a posteriori there is at most one correct answer, although this was never assumed. In fact, there is exactly one, since if 5 were false, at least one of the contradictory statements above it would hold.

A: It doesn't appear to me that the yet very interesting point brought up by RCT, nor the original post supply a reason for excluding answer number 2. In fact, the original point that it would not deny 1, does not mean it affirms it, still, and therefore, if #3 to #6 are false, #2 is valid. Until we confute #2, we cannot call 5 true either, samewise.
I think an interesting argumentation - while irrelevant after the preceeding answers - is that the answer has to be a not-self-excluding answer (i.e: not #1, #3, #4). In fact, if the answer were to be #4, for instance, it would define the answer to be not #4, excluding the possibility that #4 is indeed the answer (a contradiction).
This, and RCT point leave us with #2 and #5 again.
Answer 4 ("One of the above") would be true if 2 ("None of the below") were, but 2 contradicts 4, therefore 2 cannot be true and 5 is the only possible answer.
It's the same answer, it just appeared to me that I may have missed to see a valid proof in previous statements, but I may be wrong.

A: Just because there is only one proposition that does not contradict the rest (the 5th one) does not mean that it is the answer. We must consider the question first. And the question does not make any sense. It is a non-starter. You might as well write, "42", and leave it at that. Thankfully, this does not count towards your grade!

A: If we simply reverse the list, and swap the above/below, then it's simplicity becomes more obvious, though we may not have notice how we were suckered into considering the problem in a really difficult order.
Isn't it a meta-problem problem?
Which answer in this list is the correct answer to *this* question?
    None of the below.
    None of the below.
    One of the below.
    All of the below.
    None of the above.
    All of the above.

A: I see this question a little differently:
If I take the #5 statement as a denial of the set of items containing 1-4, then I am judging the truth or falsity of the statement on the basis of set 1-4.
If I take the statement of #6 however, I am actually judging a different set than I am with #5. I am including in that set all items with the denial of #5 included. What I would be saying then is that "none of the above items in set 1-5 are true because the set itself is not structured correctly". Since 6 is outside the previous set, it becomes the "best answer". Notice I don't bother evaluating the truth of number 5 against number six, because it generates a contradiction. I consider number 5 to be simply a "liar" and move forward. Why would I not do that with #5? Because #6 is not in the set of items 1-5 and before six arrives, there is no contradiction in the set of items 1-4 and so 5 has a claim to truth. Once 5 becomes part of the set, you cannot deny a denial. He has no real existence or purpose at that point.
An analogy might be to have a group of black cats (1-4). A tall stranger, #5 shows up and says  "These black cats all suck". Okay. So we take number five under advisement and say that is a possibility for all black cats 1-4. Another tall stranger, #6 shows up and says all black cats suck, and so does tall stranger #5 because he is trying to generate problems with me by contradiction. Since my statement includes him, and his statement does not include me, give me priority. He isn't following the rules of set construction. How do you know? Because I am here, last in this set. He, on the other hand, is not last in the set. His position betrays the lie.

A: This question is not answerable.
Because the contract between a Noun and its Pronoun is not fulfilled.
In computer science lingo, it's a Recursion Without Termination, since the base case is not defined.
Bear with me, as I give 4 examples to illustrate.

1

(1): "what color is the sky?"
(2): "What is the answer to above?"

(2) cannot be answered as-it-is without clarifying what the pronoun 'above' refers to.
Step 1 - RESOLVE 'above' : "What is the answer to 'what color is the sky?' ?
Step 2 - RECURSE 'what color is the sky?'
Step 3 - RETURN 'blue'
(1) 'what color is the sky?' - is a Valid & Terminating base case - It is a question (Valid), and it has no pronouns (Terminating).
(2) refers to (1). Hence (2) is also Valid and eventually Terminating.
Questions (1) & (2) are answerable.
Agree?

2

(1): "the sky is blue"
(2): "What is the answer to above?"

Step 1 - RESOLVE 'above' : "What is the answer to 'the sky is blue' ?
Step 2 - RECURSE 'the sky is blue'
Step 3 - RETURN ??
(1) 'the sky is blue' - is a Terminating but Invalid base case - It has no pronouns (Terminating), but it is not even a question (Invalid).
(2) refers to (1). Hence (2) is also eventually Terminating but Invalid.
Question (2) is not answerable.
Agree?

3

(1): "what color is the sky?"
(2): "What is the answer to above?"
(3): "What is the answer to above?"

*

*RESOLVE 'above' in (3): "What is the answer to 'What is the answer to above?' ?"

*RECURSE 'What is the answer to above?'
2.1. RESOLVE 'above' in (2): "What is the answer to 'what color is the sky?' ?"
2.2. RECURSE 'what color is the sky?'
2.2.1. RESOLVE ? Nothing to resolve

2.2.2. RECURSE ? Nothing to recurse

2.2.3. RETURN 'blue'

2.3. RETURN 'blue'

*RETURN 'blue'
(1) 'what color is the sky?' - is a Valid & Terminating base case.
(2) refers to (1) . Hence (2) is also Valid and eventually (1-level deep) Terminating.
(3) refers to (2). Hence (3) is also Valid and eventually (2-levels deep) Terminating.
Questions (1), (2) and (3) are answerable.
Agree?

4 Coming to OP's example.

(Q): "Which answer in this list is the correct answer to this
  question?"

(Q) cannot be answered as-it-is without clarifying what the pronoun 'this' refers to.

*

*RESOLVE 'this' : "Which answer in this list is the correct answer to 'Which answer in this list is the correct answer to this question?' question?"

*RECURSE 'Which answer in this list is the correct answer to this question?'
2.1. RESOLVE 'this' : "Which answer in this list is the correct answer to 'Which answer in this list is the correct answer to this question?' question?"
2.2. RECURSE 'Which answer in this list is the correct answer to this question?'
2.2.1. RESOLVE 'this' : "Which answer in this list is the correct answer to 'Which answer in this list is the correct answer to this question?' question?"

2.2.2. RECURSE : 'Which answer in this list is the correct answer to this question?'

2.2.2.2.2.2.2....... INFINITE RECURSION :

*RETURN ??
(Q) 'Which answer in this list is the correct answer to this question?' - is a Valid but Non-Terminating base case - It is a question (Valid), but has pronouns (Non-Terminating).
(Q) refers to (Q). Hence (Q) is also Valid but never Terminating.
Question (Q) is not answerable.
Agree ?

The question is basically just a chain of pronouns which will never get resolved to a noun.
It's no different from the following conversation :

(OP) : What is the answer to above?
(Me) : You have a responsibility to resolve the pronoun 'above' before I can answer the question. What does 'above' refer to ?
(OP) : to 'oogabooga'
(Me) : You have a responsibility to resolve the pronoun 'oogabooga'. What does 'oogabooga' refer to ?
(OP) : to 'takamaka'
(Me) : You still have a responsibility to resolve 'takamaka'. What does it refer to ?
(OP) : to 'kumpiwumpi'
...

OP's responsibility of pronoun resolution does not end just because he referred to a cyclic self-referencing statement. Remember, it is OP's responsibility for breaking you out of an infinite loop, not yours.
So, the proper response to OP's question is to repeatedly ask infinitely:

'Which question does 'this' refer to?'


text:
Q: How to add logic to my SQL query to include/exclude search parameters? Using SQL Server 2008R2, I have here is a simple query:
SELECT *
FROM ItemData
WHERE FREETEXT(Title, '"' + @OriginalSearchTerm + '"')
AND  ( WebsiteID=@WebsiteID AND GeoCity = @GeoCity  AND GeoState = @GeoState )
ORDER BY ItemListID DESC

This is all fine when there is a valid value for @GeoCity and @GeoState.  However there will be scenarios where @GeoCity = -1 and/or @GeoState = -1.
I would rather not write entire separate queries for these cases, although this would work just fine.
How can I optimize the current query to do just this?
Thanks.

A: I'm not sure what you want the query to do when @GeoCity = -1 and/or @GeoState = -1. Assuming you want to exclude the GeoCity = @GeoCity and/or GeoState = @GeoState conditions in that case, here's the query:
SELECT *
FROM ItemData
WHERE FREETEXT(Title, '"' + @OriginalSearchTerm + '"')
AND  ( WebsiteID=@WebsiteID AND
    (@GeoCity = -1 OR GeoCity = @GeoCity)  AND
    (@GeoState = -1 OR GeoState = @GeoState) )
ORDER BY ItemListID DESC

A: -- This might be more efficient as OR statement executes block for each OR statement.
SELECT *
FROM ItemData
WHERE FREETEXT(Title, '"' + @OriginalSearchTerm + '"')
AND  ( WebsiteID=@WebsiteID AND
    (GeoCity = ISNULL(@GeoCity,-1)) AND
    (GeoState = ISNULL(GeoState,-1))
ORDER BY ItemListID DESC


text:
Q: Rails Devise Omniauth omniauth_openid_connect issue, how to work with endpoints with different hosts I need some help in configuring omniauth_openid_connect gem (https://github.com/omniauth/omniauth_openid_connect). I have two endpoints one for Authorization and another for token:
Authorization endpoint:
https://oauth.provider.com/authorize
Token endpoint:
https://oauth-secured.provider.com/token
as you can see eachone has a different host, but are the same provider, Im not sure how to configure this in the gem as you can only specify one host
config.omniauth :openid_connect,
{
    name: :openid_connect,
    scope: [:openid],
    issuer: "oauth.provider.com"
    response_type: :code,
    discovery: :true,
    client_options:
    {
    port: 443,
    scheme: "https",
    host: "oauth.provider.com",
    authorization_endpoint: "/authorize",
    token_endpoint: "/token", #How to specify here correctly https://oauth-secured.provider.com/token
    identifier: 'CLIENT_ID',
    secret: 'CLIENT_SECRET',
    redirect_uri: "https://myapp.com/users/auth/openid_connect/callback",
    },
  }

A: Doesn't look like that's configurable. The client only takes one host and endpoints are relative to the host. Configuration eventually ends up in Rack::OAuth2::Client:

*

*https://github.com/omniauth/omniauth_openid_connect/blob/v0.4.0/lib/omniauth/strategies/openid_connect.rb#L94

*https://github.com/nov/openid_connect/blob/v1.3.0/lib/openid_connect/client.rb

*https://github.com/nov/rack-oauth2/blob/v1.19.0/lib/rack/oauth2/client.rb#L8
Rack::OAuth2::Client has an absolute_uri_for method and looks like endpoints go through it.
def absolute_uri_for(endpoint)
  _endpoint_ = Util.parse_uri endpoint
  _endpoint_.scheme ||= self.scheme || 'https'

  # NOTE: just one host
  _endpoint_.host ||= self.host

  _endpoint_.port ||= self.port
  raise 'No Host Info' unless _endpoint_.host
  _endpoint_.to_s
end

I'm only guessing here:
Rack::OAuth2::Client.class_eval do
  private

  def absolute_uri_for(endpoint) # endpoint # => /token or /authorize ...
    _endpoint_ = Util.parse_uri endpoint
    _endpoint_.scheme ||= self.scheme || 'https'

    # NOTE: now there are two
    _endpoint_.host = if endpoint == "/token"
                        "oauth-secured.provider.com"
                      else
                        self.host
                      end

    _endpoint_.port ||= self.port
    raise 'No Host Info' unless _endpoint_.host
    _endpoint_.to_s
  end
end

Probably something will explode. I did not test it. There must be a reason for a single host.


text:
Q: how to show another dropdown box depend on dropdown box value please i need help
i need to do specail command
when some value selected then show another dropdown box
my first dropdown box is in php
and he is my code :
 $conn = mysqli_connect("localhost", "root",
    "", "phoneunlock" )
    or die("Cannot connect to database:" .
    mysqli_connect_error($conn));
    echo "<select name='selectedValue' class= 'dropdown' >";
    echo '<option value="">'.'Please Select Service'.'</option>';
    $sql = "SELECT id, manufacter FROM product";
    $result = $conn->query($sql);
      while($row = $result->fetch_assoc())
    {       echo "<option value='" . $row['manufacter']. "'>" . $row['manufacter'] . '</option>';
        }
        echo '</select>';

and know i need some command like this :
if dropdown box selected = value then
do this
end if
sow please can any one help me

A: if you mean like chained combobox. try using jQuery like this :

$('#yourcomboid').on('change', function() {
  var id = $(this).val();
  $('#youranothercombo').empty();
  $.ajax({
    url: 'your-route-to-get-data/' + id,
    success: function(data) {
      $('#youranothercombo').empty();
      for(var i = 0; i < data.length; i++) {
          var item = data[i];
          $('#youranothercombo').append($('<option></option>').val(item.column-name).text(item.column-name));
      }
    }
   });
});

Hope this code works.


text:
Q: Format of xml in nusoap I'm having a problem putting together a XML file with the right format required by the webservice I want to use. I'm using the nusoap class to do it.
The error I'm getting:
Array
(
[Reservation_Data] => Array
(
[Reservation_Value] => 0
[Status] => ERROR_Create_Internacional_Reservation: Object reference not set to an instance of an object. - 0
)
)

POST /Rentway_Internacional_Reservations_WS/Create_Reservation.asmx HTTP/1.0
Host: www.xxxxxxx.pt
User-Agent: NuSOAP/0.9.5 (1.123)
Content-Type: text/xml; charset=UTF-8
POST /Rentway_Internacional_Reservations_WS/Create_Reservation.asmx HTTP/1.0
Host: www.xxxxxxx.pt
User-Agent: NuSOAP/0.9.5 (1.123)
Content-Type: text/xml; charset=UTF-8
SOAPAction: http://www.xxxxxxx.pt/Rentway_Internacional_Reservations_WS/Create_Internacional_Reservation/Create_Internacional_Reservation
Content-Length: 714
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns3785="http://tempuri.org">
<SOAP-ENV:Body><Create_Internacional_Reservation xmlns="http://www.xxxxxxxxx.pt/Rentway_Internacional_Reservations_WS/Create_Internacional_Reservation">
<Reservation_Request>
<MessageType>N</MessageType>
<Group>01</Group>
..........................
</Reservation_Request>
</Create_Internacional_Reservation>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

My code is:
require_once('nu-soap/nusoap.php');
require_once('config.php');
$client = new     nusoap_client('http://www.xxxxxxxxxx.pt/Rentway_Internacional_Reservations_WS/Create_Reservation.asmx?wsdl', true);
$param = array('Username'=>'xxx','Password'=>'xxx','MessageType'=>'N','Group'=>'01');
$result = $client->call('Create_Internacional_Reservation', array('Reservation_Request' => $param));

When getting information about the request on the webservice's manual which I was advised to use, the only difference I can find is:
Where's:
Code (XML):
<Reservation_Request>
<MessageType>N</MessageType>
<Group>01</Group>
...........................
</Reservation_Request>

Should be:
<Reservation_Request xmlns="http://www.xxxxxx.pt/Rentway_Internacional_Reservations_WS/Reservation_Request.xsd" >
<MessageType>N</MessageType>
<Group>01</Group>
...........................
</Reservation_Request>

How can I send (xmlns="http://www.xxxxxx.pt/Rentway_Internacional_Reservations_WS/Reservation_Request.xsd" ) inside Reservation_Request ?