text:
Q: C# - sort List by using custom CompareTo method I have the following classes hierarchy:
abstract class Product : IComparable
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Barcode { get; set; }

    public int CompareTo(object obj)
    {
        int ret = -1;
        if (String.Compare(this.GetType().Name, obj.GetType().Name,StringComparison.Ordinal) == 0)
            ret = 0;

        return ret;
    }
}

abstract class Book : Product
{
    public int PagesCount { get; set; }
}

class ProgrammingBook : Book
{
    public string ProgrammingLanguage { get; set; }
}

class CulinaryBook : Book
{
    public string MainIngridient { get; set; }
}

class EsotericBook : Book
{
    public int MininumAge { get; set; }
}
   abstract class Disc : Product
{
    internal enum Content
    {
        Music,
        Video,
        Software
    }

    public Content DiscContent { get; set; }
}

class CdDisc : Disc
{

}

class DvdDisc : Disc
{

}

And I trying to sort following collection by using IComparable interface method CompareTo:
 List<Product> products = new List<Product>
        {
            new DvdDisc {Name = "The lord of the rings 2",DiscContent = Disc.Content.Video,Price = 200M,Barcode = "5435443-2"},
            new CdDisc {Name = "Antonio Vivaldi: best picks",Price = 700M, DiscContent = Disc.Content.Music,Barcode = "4543765-565"},
            new CulinaryBook{Name = "Midterranian foods",MainIngridient = "Salmon",PagesCount = 436,Price = 350M,Barcode = "41457561-897"},
            new CdDisc{Name = "Windows XP", DiscContent = Disc.Content.Software, Price = 950M, Barcode = "5433668-4"},
            new EsotericBook{Name = "Russian Freemasonry 1731-2000",MininumAge = 21,PagesCount = 2100,Price = 3000M,Barcode = "6464632-876"},
            new CdDisc {Name = "The best of Mussorgsky",Price = 300M, DiscContent = Disc.Content.Music,Barcode = "5435436-567"},
            new ProgrammingBook{Name = "CLR via C#",PagesCount = 900, Price = 1110M,ProgrammingLanguage = "C#",Barcode = "5546533-2446"},
            new DvdDisc {Name = "The lord of the rings 1",DiscContent = Disc.Content.Video,Price = 200M,Barcode = "54354423-2"},
            new ProgrammingBook{Name = "ASP.NET MVC 4",PagesCount = 800,Price = 1200M,ProgrammingLanguage = "C#",Barcode = "46476573-65"},
            new EsotericBook{Name = "Russian Freemasonry in it's future and past",MininumAge =19, PagesCount = 900, Price = 2342M,Barcode = "3656353-24"},
            new CulinaryBook{Name = "Traditional Polish dishes",MainIngridient = "Red meat",PagesCount = 630,Price = 840,Barcode = "54634234-5"}
        }; products.Sort();

Output list should look like this:
1.1 Programming books
   1.2 Culinary books
   1.3 Esoteric books
2.1 Cd discs sorted by content
   2.2 DVD discs sorted by content
My current CompareTo method does only part of the job - comparing classes by name.

A: You need to work with equals option
rtn = Primary Sort;
if(rtn =0)
    rtn =secondary Sort;
if(rtn =0)
    rtn =tertiary Sort;

as your primary sort seems to be on the type of book
you would do
rtn = this.GetType().Name.CompareTo(obj.GetType().Name);
if(rtn ==0)
    rtn =this.Name.CompareTo(obj.Name);
return rtn;

if your problem is that you don't want alphabetic sorting on the type
then add to product
public abstract int SortOrder{get;}

and use that as your primary sort

A: This is a working example that will render the exact same output:
1.1 Programming books
1.2 Culinary books
1.3 Esoteric books

2.1 Cd discs sorted by content
2.2 DVD discs sorted by content

I also added IComparable<Product> to more easily make it comparable with other products.
 abstract class Product : IComparable<Product>
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Barcode { get; set; }
        protected abstract int InternalSortOrder { get; }
        protected virtual string SortBy { get {return Name;} }

        public int CompareTo(Product obj)
        {
            var sameType = string.Compare(GetType().Name, obj.GetType().Name, StringComparison.Ordinal) == 0;

            var sameBaseType = GetType().BaseType != null && obj.GetType().BaseType != null &&
                               string.Compare(GetType().BaseType.ToString(), obj.GetType().BaseType.ToString(),
                                   StringComparison.Ordinal) == 0;

            // They have the same base type, but not the same type. Order by base type first.
            if (!sameType && !sameBaseType && GetType().BaseType != null && obj.GetType().BaseType != null)
            {
                // Order by base type first.
                return string.Compare(GetType().BaseType.ToString(), obj.GetType().BaseType.ToString(),
                    StringComparison.Ordinal);
            }

            // it's the same base type (eg. book or disc)
            if (sameBaseType)
            {
                // Order by sort order.
                if (obj.InternalSortOrder != this.InternalSortOrder)
                {
                    return InternalSortOrder.CompareTo(obj.InternalSortOrder);
                }
            }

            if (sameType)
            {
                // Same sort order. We sort by name.
                return string.Compare(SortBy, obj.SortBy, StringComparison.Ordinal);
            }

            // Order by Type.
            return string.Compare(GetType().Name, obj.GetType().Name, StringComparison.Ordinal);
        }

    }

    abstract class Book : Product
    {
        public int PagesCount { get; set; }
    }

    class ProgrammingBook : Book
    {
        public string ProgrammingLanguage { get; set; }

        protected override int InternalSortOrder
        {
            get { return 1; }
        }
    }

    class CulinaryBook : Book
    {
        public string MainIngridient { get; set; }

        protected override int InternalSortOrder
        {
            get { return 2; }
        }
    }

    class EsotericBook : Book
    {
        public int MininumAge { get; set; }

        protected override int InternalSortOrder
        {
            get { return 3; }
        }
    }
    abstract class Disc : Product
    {
        internal enum Content
        {
            Music,
            Video,
            Software
        }

        protected override string SortBy
        {
            get { return DiscContent.ToString(); }
        }

        public Content DiscContent { get; set; }
    }

    class CdDisc : Disc
    {
        protected override int InternalSortOrder
        {
            get { return 1; }
        }
    }

    class DvdDisc : Disc
    {
        protected override int InternalSortOrder
        {
            get { return 2; }
        }
    }

UPDATE:
I've added virtual SortByin Product. It will go to Name by default, but Disc will return Content.


text:
Q: Building wheel for pyscard (setup.py): finished with status 'error' I have pyscard within requirements.txt. Therefore the build on readthedocs is failing:
Running setup.py install for pyscard: finished with status 'error'
  error: subprocess-exited-with-error

  × Running setup.py install for pyscard did not run successfully.
  │ exit code: 1
  ╰─> [17 lines of output]
      running install
      running build
      running build_py
      running build_ext
      building 'smartcard.scard._scard' extension
      swigging smartcard/scard/scard.i to smartcard/scard/scard_wrap.c
      swig -python -outdir smartcard/scard -DPCSCLITE -o smartcard/scard/scard_wrap.c smartcard/scard/scard.i
      creating build
      creating build/temp.linux-x86_64-3.7
      creating build/temp.linux-x86_64-3.7/smartcard
      creating build/temp.linux-x86_64-3.7/smartcard/scard
      gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -fPIC -DVER_PRODUCTVERSION=2,0,2,0000 -DVER_PRODUCTVERSION_STR=2.0.2 -DPCSCLITE=1 -Ismartcard/scard/ -I/usr/include/PCSC -I/usr/local/include/PCSC -I/home/docs/.pyenv/versions/3.7.9/include/python3.7m -c smartcard/scard/helpers.c -o build/temp.linux-x86_64-3.7/smartcard/scard/helpers.o
      smartcard/scard/helpers.c:28:10: fatal error: winscard.h: No such file or directory
       #include <winscard.h>
                ^~~~~~~~~~~~
      compilation terminated.
      error: command 'gcc' failed with exit status 1
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> pyscard

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.

I have tried to skip pyscard in docs/conf.py:
autodoc_mock_imports = ['pyscard']

and in setup.py:
if os.getenv('READTHEDOCS'):
        requirements = [x for x in requirements if "pyscard" not in x]

but I still get the same error.
Have you encountered something similar? If so, how have you solved the problem?

A:
This header file is provided by pcsc-lite. Install libpcsclite-dev (or similar) package.

https://github.com/LudovicRousseau/pyscard/issues/78
Edit: please follow Manuel Kaufmann's answer for detailed solution

A: If pyscard is not required to build your documentation, you should remove it from your documentation requirements.txt. This is the most common case.
You may need to split your current requirements.txt:

*

*requirements.txt with all the dependencies

*docs/requirements.txt with only the dependencies to build the documentation (without pyscard)

Then, in your readthedocs.yaml file (see https://docs.readthedocs.io/en/stable/config-file/v2.html), you can use:
python:
  install:
    - requirements: docs/requirements.txt

On the other hand, if pyscard is required to build your documentation, you can take a look at the FAQ from the documentation https://docs.readthedocs.io/en/stable/faq.html#i-get-import-errors-on-libraries-that-depend-on-c-modules

A: I added into .readthedocs.yml:
build:
  apt_packages:
    - swig
    - pcscd
    - libpcsclite-dev

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fit a 3-D parametric equation to datapoints Consider that I have $3$ parametric equations as function of time and describe the motion of a body in space:
$x = f(t)$
$y = g(t)$
$z = h(t)$
These curves are pretty simple and can be modeled within a certain interval by a 2nd order polynomial.
Is it as simple as performing individual fitting on each function or that would break the time relationship between the functions?
Any pointers appreciated.

A: It should be appropriate to treat them independently since each is a function of time. The case where you have to worry is if f,g,h involve x,y,z. For example, if y=g(t,z,x) you could not treat them independently. Also if x=f(t,x) y=g(t,y) and z=h(t,z) you could still treat the x,y,z independently.


text:
Q: Tridion 2011 - Engine.GetObject overloads I found the following difference between the old VBScript API and the .Net API:
In the old VBScript API it's possible to invoke "TDSE.getObject" to retrieve a Tridion object passing by the webdav path, an integer to select how to open it (read only, read and write, etc) and the ID of the publication where there is the exact element of the blueprint we want.
In the new .Net API all I found was "Engine.GetObject" but it only receives the TCM ID or the webdav path of an element.
Our scenario is the following; in the old VBScript code, this overload of the getObject method was used to avoid some permission issues detected while using TCM IDs instead of the webdav paths and because it's much more handful when you need to copy the code between different environments (see DEV, PREPROD and PROD for example), avoiding changing TCM IDs.
So my questions are:

*

*Is there and overload like the old one in the new .Net API?

*If not, is there a way of retrieving items by webdav keeping in mind that some of them could be localized and changed from their parent? (the old way works with this, if you send the root webdav path it will retrieve local objects even if their names aren't exactly the same as the parents)

Thank you!

A: Do you want to be able to use the webdav url of the top-level item, and specify the publication id from which to get the item?
I would create an extension method on Engine that does this for you:
public static T GetObject<T>(this Engine engine, string webDavUrl, int publicationId)
    where T : IdentifiableObject
{
    [logic to retreive the item and then if needed
     get the correct tcm uri and get the intended item]

    return item as T;
}

However, this is quite an expensive operation since you get two objects instead of one. So I dont know if I would use this method very often.

A: Here some samples
IdentifiableObject item = engine.GetObject(new TcmUri("tcm:5-677"));
//will give you the latest approved version in the publication 5.

IdentifiableObject item = engine.GetObject(new TcmUri("tcm:5-677-v0"));
//will give you the WF or Editable version.

TcmUri uri = new TcmUri("tcm:5-677");
uri.PublicationId = 6;
IdentifiableObject item = engine.GetObject(uri);
//will give you the latest approved version in the publication 6.

A: Engine.GetObject has 4 overloaded method.
GetObject(Session, string)
GetObject(string)
GetObject(TcmUri)
GetObject(Item)
You can check the Tom.Net Api for more details.

A: Actually, using Engine.GetObject Method (String) should work.
public virtual IdentifiableObject GetObject(
    string itemUriOrWebDavUrl
)

You can do something in this way:-

*

*Get the Object based on WebDav URL

*Get the TCM ID from this object

*Based on your publication, modified your TCM ID accordingly and do your stuff

OR
Try something this way too:-
Repository testRepository = (Repository)session.GetObject("tcm:0-2-1");
Component testComponent = (Component)testRepository.GetObject(webdavURL); //Assuming actual TCM ID is "tcm:1-3"
Console.WriteLine(testComponent.Id); // should show "tcm:2-3"
// Do Your Other Stuff


text:
Q: Example of a normal ring In 'Commutative Ring Theory' by Matsumura the definition of normal ring is as follows:
A ring $R$ is called normal if for every prime ideal $\mathfrak p\subset R$, $R_{\mathfrak p}$ is an integrally closed domain.
I know that a domain is integrally closed if and only if localisation at every prime ideal gives an integrally closed domain, i.e., it is normal.
I want to have an example of a 'non-domain' which is normal. Also is there any equivalent criteria for a ring (not necessarily domain) to be a normal ring like in the domain case?
Thank you in advance.

A: The product of normal rings is normal and never a domain.

A: For example $F\times F$ for a field $F$.
Or any of these at DaRT.


text:
Q: Can't install pyperclip, multiple instances of Python I had to download the Microsoft store version of Python for BS Windows compatibility reasons- I'd been working off of the direct python download before this. Recently, I was messing with PATH stuff and messed up in a weird way. I deleted my C:\ProgramFiles(x86) PATH on accident and launched a system restore to get it back.
Things got worse from there.
When my computer relaunched, my web browsers were deleted. Unrelated, but weird.
I went back to working on PATH stuff, and solved my original WIN + R problems.
However, as soon as I launched a program with pyperclip, the module was no longer present. I've installed pip, and pyperclip using cmd but I can't import the module into IDLE or run it in my programs.
I think it has to do with the multiple versions of Python and some directory issue.
Is there any way to install pyperclip in all versions of Python present? I don't want to deal with more issues by trying to delete just one instance of Python.

A: Some problems solve themselves. I just kept messing with file locations and running pip install pyperclip in cmd. Buffed out.


text:
Q: Accessing the Twitter API via PHP I'm working on making my script mesh with OAuth instead of Basic Auth, and I'm stuck. So far, I'm just working on authenticating at the moment, but I can't get that working. This code:
<?php

  include 'config.php';
  include 'twitteroauth/twitteroauth.php';

  // Use config.php credentials
  $conn = new TwitterOAuth(CONSUMER_KEY,CONSUMER_SECRET);

  // Use application's registered callback URL
  // And get temporary credentials using made connection
  $tempCred = $conn->getRequestToken();

  // Use 'Sign in with Twitter'
  // for Redirect URL
  $rURL = $conn->getAuthorizeURL($tempCred);

  echo '1. Click me first!
';

works just fine. However, when I make it to this step:
  // Build a new TwitterOAuth connection
  // Now that the app has verified credentials
  $conn = new TwitterOAuth(CONSUMER_KEY,
                           CONSUMER_SECRET,
                           $_SESSION['oauth_token'],
                           $_SESSION['oauth_token_secret']);

  // Get non-temporary credentials from Twitter
  $tokenCred = $conn->getAccessToken();

  echo '2. Click me next!
';

?>

I get a Page Not Available, Error 324 (net::ERR_EMPTY_RESPONSE): Unknown error. Is anyone familiar with this issue? I was following the documentation as closely as I could, but as I am a complete rookie I'm sure I made some stupid mistake.
Also, a follow up question: Once I do get my script authorizes via this process, what is my next step in terms of grabbing the friends feed xml? Can I just cURL it like before?
EDIT: The source for getAccessToken(); is as follows:
 function getAccessToken($oauth_verifier = FALSE) {
    $parameters = array();
    if (!empty($oauth_verifier)) {
      $parameters['oauth_verifier'] = $oauth_verifier;
    }
    $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
    $token = OAuthUtil::parse_parameters($request);
    $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
    return $token;
  }

And yes, config.php is correct.

A: I have used this api for pin based oauth authentication for twitter. I used php simple oauth library http://php.net/manual/en/book.oauth.php.
Here is the code if you want to see.

class TwitterPinBasedOauth{
    private static $requestTokenUrl = 'http://twitter.com/oauth/request_token';
    private static $accessTokenUrl = 'http://twitter.com/oauth/access_token';
    private static $authorizeUrl = 'http://twitter.com/oauth/authorize';
    private static $updateUrl = 'http://twitter.com/statuses/update.json';

    private $twitterOauth;
    public function __construct(){
        $this->twitterOauth = new OAuth(ConsumerToken::$CONSUMER_KEY,
                                        ConsumerToken::$CONSUMER_SECRET,
                                        OAUTH_SIG_METHOD_HMACSHA1,
                                        OAUTH_AUTH_TYPE_AUTHORIZATION);
    }

    public function getAndStoreRequestToken(){
        $callbackUrl = "oob";
        $response = $this->twitterOauth->getRequestToken(self::$requestTokenUrl, $callbackUrl);
        print_r("REQUEST TOKEN:\n");
        print_r($response);
        print_r(PHP_EOL);
        file_put_contents(Constants::$oauth_request_file, serialize($response));
        echo "AUTH URL:\n".self::$authorizeUrl."?oauth_token=".$response['oauth_token'].PHP_EOL;
    }
    public function getAcessToken($pin){
        $request_tokens = unserialize(file_get_contents(Constants::$oauth_request_file));
        $this->twitterOauth->setToken($request_tokens["oauth_token"],$request_tokens["oauth_token_secret"]);
        $response = $this->twitterOauth->getAccessToken(self::$accessTokenUrl, NULL, $pin);

        file_put_contents(Constants::$oauth_access_file, serialize($response));

        print_r("ACESS TOKEN:\n");
        print_r($response);
        print_r(PHP_EOL);
    }
    public function updateStatus($status){
        try{
            $access_tokens = unserialize(file_get_contents(Constants::$oauth_access_file));
            $this->twitterOauth->setToken($access_tokens["oauth_token"],$access_tokens["oauth_token_secret"]);
            $this->twitterOauth->fetch(self::$updateUrl,
                                    array('status' => $status),
                                    OAUTH_HTTP_METHOD_POST);
        }
        catch(OAuthException $e){
            error_log($e->getMessage().PHP_EOL);
            return intval($e->getCode());
        }
   }
}

A: Check that CONSUMER_KEY and CONSUMER_SECRET are the same as the values in your application page on twitter.
What is the Authorisation URL returned from the method?

A: I've used this API and it worked fine for me.
Nothing else comes to mind except really checking that CONSUMER_KEY and CONSUMER_SECRET, as Ian Quigley said
Because you say your $_SESSION['oauth_token'] is empty, and it shouldn't be. The reason why its empty could be the wrong values in CONSUMER_KEY and CONSUMER_SECRET
If you are sending wrong keys to Twitter, its not giving you those session variables you need
Just check if those values in https://twitter.com/apps (your application data) and in config.php file are identical. By default, config.php contains wrong values, you need to fill in your own.


text:
Q: CoordinatorLayout layout_anchor does not work I just tried out the new Support Design Library with CoordinatorLayout, but I'm having problems anchoring child views. My layout currently looks like this:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:layout_scrollFlags="enterAlways" />

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_anchor="@id/toolbar"
    app:layout_anchorGravity="bottom"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginRight="16dp"
    android:src="@drawable/ic_fab_add"
    android:onClick="onAddPlayerClick"
    android:layout_gravity="bottom|end"
    app:elevation="4dp"
    app:borderWidth="0dp"/>

When the RecyclerView list is loaded, the first item is being overlapped by the action bar. I assume the app:layout_anchor is not working properly. I already tried anchoring it to appbar to no success.
Does anyone know what I am doing wrong here?

A: Try this code. You need to use app:layout_behavior in your RecyclerView
<android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_marginBottom="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginRight="16dp"
    android:src="@drawable/ic_fab_add"
    android:onClick="onAddPlayerClick"
    app:elevation="4dp"
    app:borderWidth="0dp"
    app:layout_anchor="@id/appbar"
    app:layout_anchorGravity="bottom|right|end"
    android:clickable="true"/>


text:
Q: Change order status after checkout I want to change the status of my order based on current order status. If my current order status is pending I want to change it to completed after paying in pay for order (checkout/order-pay). However, after paying the status is still processing instead of completed.
add_action( 'woocommerce_thankyou', 'my_change_status_function', 10, 1 );
function my_change_status_function( $order_id ) {
    $order = wc_get_order( $order_id );
    if( $order->get_status() == 'pending' ){
        $order->update_status( 'completed' );
    }else{
       $order->update_status( 'processing' );
    }
}


text:
Q: Azure Data Factory - Teams Message Card including variable results I have a teams message card that I post using a web activity.
Currently, I do a lookup to determine whether or not I post the results, those results are stored in a variable, like so;

I want to include the results held in "Set variable" within my teams message, this will output the following as an array;

Using the web body, in expression builder, how can I include the values stored in the variable within my message, here is what I have generated so far;
{
"@type": "MessageCard",
"@context": "https://schema.org/extensions",
"summary": "This is the summary property",
"themeColor": "800000",
"sections": [
    {
        "heroImage": {
            "image": "https://messagecardplayground.azurewebsites.net/assets/FlowLogo.png"
        }
    },
    {
        "startGroup": true,
        "title": "**Checks - Requires Investigation**",
        "facts": [
            {
                "name": "Date submitted:",
                "value": "06/27/2017, 2:44 PM"
            },
            {
                "name": "Details:",
                "value": "The validation checks are hilighted below; "
            },
            {
                "name": "Results:",
                "value": "Include the output here"
            },
            {
                "name": "Support Document:",
                "value": "[Click here](https://dev.azure.com/supportDocument)"
            }
        ]
    }
]

}

A: You can use String interpolation to include the value of your variable (array). Please look at the following demonstration:

*

*I have used a fake API in my web activity where I use PUT method. The following is the request body that is needed to be passed to the API.

{
    "name": "morpheus",
    "job": "leader"
}

*

*Instead of using static data, if I want to use dynamic content (lets say, for 'name') i.e., use the result of my variable in the web body, we can do it in the following way. In the following, the variable req_name has value morpheus.

{
"name": "@{variables('req_name')}",
"job": "leader"
}

*

*Now since you have the required result, which should be used in web body, stored in your variable, you can change your body as follows in the expression builder:

{
"@type": "MessageCard",
"@context": "https://schema.org/extensions",
"summary": "This is the summary property",
"themeColor": "800000",
"sections": [
    {
        "heroImage": {
            "image": "https://messagecardplayground.azurewebsites.net/assets/FlowLogo.png"
        }
    },
    {
        "startGroup": true,
        "title": "**Checks - Requires Investigation**",
        "facts": [
            {
                "name": "Date submitted:",
                "value": "06/27/2017, 2:44 PM"
            },
            {
                "name": "Details:",
                "value": "The validation checks are hilighted below; "
            },
            {
                "name": "Results:",
                "value": "@{variables('<your_variable_name>')}"
            },
            {
                "name": "Support Document:",
                "value": "[Click here](https://dev.azure.com/supportDocument)"
            }
        ]
    }
]
}

NOTE:

*

*You can always check the debug input to check whether the body you are passing is the correct format.

*If it is not, then you can manipulate the variable as required to convert it to required format and then include its value as demonstrated above using String Interpolation (@{......}).


text:
Q: GetCursorPos returning 0 in a Windows Service application I have a Arduino communicating the state of a button through serial port. On the PC I have a Windows Service application that is polling the serial port to get the state of the button. Whenever I receive a message in the serial port about the button state, I write the received message to a file, and also want to log the current mouse position. Following this I would like to raise a left click event at the current mouse position.
For some reason, when I read the current mouse position using GetCursorPos, I always get 0, 0 as the mouse position. I am using user32.dll to do this.
The following is my C# code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Threading;
using System.IO;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace MouseInterface
{
    public class MyMouseClass
    {
        [DllImport("user32.dll")]
        static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);

        [Flags]
        public enum MouseEventFlags
        {
            LEFTDOWN = 0x00000002,
            LEFTUP = 0x00000004
        }

        [DllImport("user32.dll")]
        static extern bool SetCursorPos(int x, int y);

        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(ref Point pt);

        public static void LeftDown(int x, int y)
        {
            SetCursorPos(x, y);
            mouse_event((int)(MouseEventFlags.LEFTDOWN), x, y, 0, 0);
        }

        public static void LeftUp(int x, int y)
        {
            SetCursorPos(x, y);
            mouse_event((int)(MouseEventFlags.LEFTUP), x, y, 0, 0);
        }
    }

    public partial class Service1 : ServiceBase
    {
        private HCIDevice hcidev;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            hcidev = new HCIDevice();
            hcidev.init();
        }

        protected override void OnStop()
        {
            hcidev.terminate();
        }

        private void onElapsedTimer(object source, ElapsedEventArgs e)
        {

        }
    }

    public class HCIDevice
    {
        private SerialPort _sPort;
        private Thread _reader;
        private bool _connected;
        private bool _stop;
        private System.Timers.Timer _contimer = new System.Timers.Timer();

        public HCIDevice()
        {
            // create a new serial port
            _sPort = new SerialPort();
            // update settings
            updateSerialPortSettings();

            // set reader and writer threads.
            _reader = new Thread(this._readerthread);

            // reset flags.
            _connected = false;
            _stop = false;

            // start the thread.
            //init();
        }

        public void connect()
        {
            if (this._sPort.IsOpen == false)
            {
                try
                {
                    this._sPort.Open();
                    _connected = true;
                    AddToFile("Device connected!\n");
                }
                catch
                {
                }
            }
        }

        public void disconnect()
        {
            if (this._sPort.IsOpen)
            {
                this._sPort.Close();
            }
            _connected = false;
            AddToFile("Device disconnected!\n");
        }

        public void init()
        {
            try
            {
                this._stop = false;
                // start thread.
                this._reader.Start();
            }
            catch
            {
                //AddToFile("Service could not be started!\n");
            }
        }

        public void terminate()
        {
            // first stop.
            this._stop = true;
            this._reader.Join();
            //AddToFile("Device stopped!");
        }

        public bool isRunning()
        {
            return (this._stop == false);
        }

        public bool isConnected()
        {
            return this._sPort.IsOpen;
        }

        private void updateSerialPortSettings()
        {
            // Allow the user to set the appropriate properties.
            this._sPort.PortName = System.Configuration.ConfigurationManager.AppSettings["devCOM"];
            this._sPort.BaudRate = int.Parse(System.Configuration.ConfigurationManager.AppSettings["devbaudrate"]);
            this._sPort.Parity = Parity.None;
            this._sPort.DataBits = 8;
            this._sPort.StopBits = StopBits.One;
            this._sPort.Handshake = Handshake.None;

            // Set the read/write timeouts
            this._sPort.ReadTimeout = 500;
            this._sPort.WriteTimeout = 500;
        }

        private void _readerthread()
        {
            byte[] _rxdata = new byte[1024];
            //int n;
            double nanosecPerTick = 1.0 / Stopwatch.Frequency;
            Stopwatch stp_watch = new Stopwatch();
            stp_watch.Start();

            AddToFile("Service started!\n");
            while (_stop == false)
            {
                // make sure the device is still connected.
                if (isConnected())
                {

                    // Do nothing if in pause
                   // Not paused read data and parse
                    try
                    {
                        handle_message();
                    }
                    catch (System.TimeoutException) { }
                }
                else
                {
                    // Just got disconnected?
                    if (_connected)
                    {
                        disconnect();
                        // Reset timer.
                        stp_watch.Reset();
                        stp_watch.Start();
                    }
                    else
                    {
                        // try to connect every one second.
                        if (stp_watch.ElapsedMilliseconds >= 1000)
                        {
                            connect();
                            // Reset timer.
                            stp_watch.Reset();
                            if (_connected == false)
                            {
                                stp_watch.Start();
                            }
                        }
                    }
                }
            }
            disconnect();
            AddToFile("Service stopped!\n");
        }

        private void AddToFile(string line)
        {
            using (FileStream fs = File.Open(System.Configuration.ConfigurationManager.AppSettings["logloc"], FileMode.Append, FileAccess.Write, FileShare.None))
            {
                Byte[] info = new UTF8Encoding(true).GetBytes(string.Format("{0} {1}", DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss"), line));
                // Add some information to the file.
                fs.Write(info, 0, info.Length);
            }
        }

        private void handle_message()
        {
            // read line.
            string msg = _sPort.ReadLine();
            AddToFile(msg);
            Point pt = new Point();
            MyMouseClass.GetCursorPos(ref pt);
            AddToFile(string.Format("{0}, {1}", pt.X, pt.Y));
        }
    }
}

What am I doing wrong? I googled for a couple of hours to find the solution, but could not find anything about this.


text:
Q: Query to delete sql table row based on attribute in xml file c# I currently have 3 different xml elements to "Add", "Update", and "Delete".  Following these elements, I have a few attributes that will either add, update, or delete from my sql table.  I was able to use  "LOAD XML LOCAL INFILE" query for the "add" and "update" elements, but there is no remove/delete options for the "LOAD XML LOCAL INFILE" query.  The following is my get/set method, Class1 class and my main method class.
Main Class
using System;
using System.Collections.Generic;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string conString = "Driver={MySQL ODBC 5.3 ANSI Driver};"
                + "Server=WWW;Port=XXX;"
                + "Database=inventory;"
                + "uid=YYY;pwd=ZZZ";
            OdbcConnection connection = new OdbcConnection(conString);

            {
                XDocument theFile = XDocument.Load("C:\\Users\\Bob\\Documents\\Update.xml");
                foreach (XElement el in theFile.Root.Elements())
                {
                    if (el.Name == "ADD")
                    {
                       Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully added.");
                        Console.ReadLine();

                        OdbcCommand Command1 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' INTO TABLE item ROWS IDENTIFIED BY '<ADD>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command1.ExecuteReader();
                        connection.Close();
                    }
                    else if (el.Name == "UPDATE")
                    {
                        Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully updated.");
                        Console.ReadLine();

                        OdbcCommand Command2 = new OdbcCommand("LOAD XML LOCAL INFILE 'C:/Users/Adam/Documents/Update.xml' REPLACE INTO TABLE item ROWS IDENTIFIED BY '<UPDATE>'", connection);
                        connection.Open();
                        OdbcDataReader reader = Command2.ExecuteReader();
                        connection.Close();
                    }
                    else if (el.Name == "DELETE")
                    {
                        Console.WriteLine("Item {0} ", el.Attribute("invent_id").Value + " was successfully deleted."); ;
                        Console.ReadLine();

                        OdbcCommand Command3 = new OdbcCommand("", connection, connection);
                        connection.Open();
                        OdbcDataReader reader = Command3.ExecuteReader();
                        connection.Close();
                    }
                    else
                    {
                       Console.WriteLine( "Nothing to do");
                    }
                }
            }
        }
    }
}

Class1 Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    public class Class1
    {
        public static object Item_ID { get; set; }
        public static object Invent_id { get; set; }
        public static object Itemsize { get; set; }
        public static object Color { get; set; }
        public static decimal Curr_price { get; set; }
        public static object Qoh { get; set; }
    }
    public class transactions
    {
        [XmlRoot(ElementName = "UPDATE")]
        public class UPDATE
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "ADD")]
        public class ADD
        {
            [XmlAttribute(AttributeName = "qoh")]
            public string Qoh { get; set; }
            [XmlAttribute(AttributeName = "curr_price")]
            public string Curr_price { get; set; }
            [XmlAttribute(AttributeName = "color")]
            public string Color { get; set; }
            [XmlAttribute(AttributeName = "itemsize")]
            public string Itemsize { get; set; }
            [XmlAttribute(AttributeName = "invent_id")]
            public string Invent_id { get; set; }
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "DELETE")]
        public class DELETE
        {
            [XmlAttribute(AttributeName = "item_id")]
            public string Item_id { get; set; }
        }

        [XmlRoot(ElementName = "transactions")]
        public class Transactions
        {
            [XmlElement(ElementName = "UPDATE")]
            public UPDATE UPDATE { get; set; }
            [XmlElement(ElementName = "ADD")]
            public List<ADD> ADD { get; set; }
            [XmlElement(ElementName = "DELETE")]
            public DELETE DELETE { get; set; }
        }
    }
}

A: I was able to solve this by adding my attribute and value to the query like so
OdbcCommand Command3 = new OdbcCommand("DELETE FROM item WHERE item_id = " + el.Attribute("item_id").Value, connection);

Also, since my queries pull the information straight from my xml file, there is no need for my get and set methods.


text:
Q: How to detect a key press in Java My son (aged 11) who is learning Java is going to enter a question and some code. He tells me he has not been able to find the answer to this question on the site. You will be reading my edited version of his question. Many thanks.
How can I detect a keypress in java, My IDE is called eclipse and I have made some classes. I found the code inside keyconfigofplayer of the internet and changed it to extend player class. I want it so when I hold down a key a rectangle or oval will move across the screen, how could I do this? For some reason it wont type the code correctly which is why my imports dont have the asterisk and look wierd. sorry about that. please ignore it. I cant fix that:(.
here is my code:
code for window:
import javax.swing.*;
import java.awt.*;

public class window {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        f.setSize(600, 600);
        player p = new player();
        f.add(p);

        keyconfigofplayer key = new keyconfigofplayer();
        p.add(key);
        f.add(key);

    }
}

//this class is the player graphic

import javax.swing.*;
import java.awt.*;

    public class player extends JPanel {

    int x = 50;
    int y = 50;

    public void paint() {//This is where the graphic is painted to the screen
        repaint();
    }

    public void paintComponent(Graphics g) {
        //This is where the graphic is 'manufactured'
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        int width = 20;
        int height = 20;
        g.fillRect(x, y, width, height);

        int width2 = 10;
        int height2 = 10;
        g.fillOval(x, y, width2, height2);

    }
}

//the keyconfigofplayer class(where i think the problems are):
//this class is the player graphic

import javax.swing.*;
import java.awt.*;

    public class player extends JPanel {

    int x = 50;
    int y = 50;

    public void paint() {//This is where the graphic is painted to the screen
        repaint();
    }

    public void paintComponent(Graphics g) {
        //This is where the graphic is 'manufactured'
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        int width = 20;
        int height = 20;
        g.fillRect(x, y, width, height);

        int width2 = 10;
        int height2 = 10;
        g.fillOval(x, y, width2, height2);
    }
}

The classes I have tried to comment well so you know what it means.
I got keyconfigofplayer's code from the youtube channel macheads101 how to program GUI in java episode 12 or 11 I think. I think my problem isn't about updating the image, but about detecting when the key is pressed and then released. So maybe I should make a while loop stating that:
if this key is pressed down, + 10 to the x coordinates until its done and constantly update the position.
I would also like to ask, when to use public, private and void? I dont understand those :( and if Ive done the extends player implements thing correctly. I tried to alter macheads101's code carefully, when I copied it exactly it didn't work too. So I really dont know what is wrong. I would be thankfull if you answered my question and helped me to alter my code. In the end its gonna be a shooter, like the arcade game 'space invaders' or 'dragon shooter'.

A: So GUI are event driven. Everything that occurs is driven by an event. A key press is an event. A component needs to listen for events, and do something when the event is fired. You can read more about how to write different listeners here. Some of the basic listeners are fairly easy to recognize (by name) like KeyListener or MouseListener. ActionListener is also pretty common for button presses. You'll want to go through the tutorials and learn the different listeners.
Note though that with Swing there are focus issues with using a KeyListener so it is preferred to use key bindings. As stated in the KeyListener tutorial:

To define special reactions to particular keys, use key bindings instead of a key listener

A tutorial for key bindings can be found here and an example can been seen here. Here's the gif from the example, showing the movement of rectangle with a key press using key bindings

UPDATE just notice.

*

*Don't override the paint method of JPanel

*Never call repaint() from inside a paint/paintComponent method
public void paint() {//This is where the graphic is painted to the screen
    repaint();
}

Get completely rid of the above code.

A: There's a great library which works smoothly and it listens to global events. It's the only thing which worked without any issues for me:
https://github.com/kwhat/jnativehook
It grabs every event in the system, pretty cool for any development.
You can use it like this:
package main;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

class MyKeyboard implements NativeKeyListener {

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            System.err.println("There was a problem registering the native hook.");
            System.err.println(ex.getMessage());

            System.exit(1);
        }

        GlobalScreen.addNativeKeyListener(new MyKeyboard());

        // Now press any keys and look at the output
    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent e) {
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nke) {
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent nke) {
    }

}

A: Read about java.awt.event.KeyListener
A code should look like this:
    f.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            System.out.println("Key pressed code=" + e.getKeyCode() + ", char=" + e.getKeyChar());
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
    });

A: I don't see anything in your code which actually listens for key presses or which modifies the position of x and y. The circle will only move if you change x and y and then repaint the screen.
You have set up the panel, etc here but not actually added anything to respond to user action. You will probably need to add a KeyListener somewhere to respond to key presses. This is probably either in the tutorial you are doing or in a previous or later tutorial.

A: KeyListener
You should be putting his KeyListener Event within the class you need it not in the Main Method!
addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) {
        //This is where you want to implement your key!
        if(e.getKeyCode() == KeyEvent.VK_SPACE){
             //Fire Gun!
        }
        ....
    }

    public void keyReleased(KeyEvent e) { //I dont really use these!
    }

    public void keyTyped(KeyEvent e) { //I dont really use these!
    }
});

More on Keys here: KeyListeners

Public and Private:
Now for Public and Private, there is already an answer on StackOVerflow which I think does the job pretty well! Here

Functions/Methods and Void:
As for Void, It is used in functions where you wish to return nothing! I do not know how well you know about functions but let me give you an example:
int sum;
public int addReturn(int x, int y){
    sum = x +y;
    return sum;
}

What this does is it adds the two ints given as x and y and then returns the sum as an integer!
With void what you can do is:
int sum;
public void add(int x, int y){
    sum = x+ y;
}

Here you return nothing but it still stores x+y into sum!
So in your class:
int Summation, x = 10, y = 10;
summation = addReturn(x,y); //<-- This will place summation = 10+10 = 20

For the void function you do not need to make a variable since it doesnt return a value, rather it sets the value within the function. All you need to do is call it
add(x,y);

If you need more help just comment! :)
Also I find it awesome that your son is so interested in Java at such a young age. Great Parenting :D

A: Suppose you need to detect the key f, use this:
//packageStatement
import javax.swing.*;
import java.awt.event.*;
//more imports
public class window {
 //code
 f.addKeyListener(new KeyListener() {
    @Override
    public void KeyTyped(KeyEvent e) {
        if(e.getKeyChar == 'f'){
           //code
        }
    }
    //more code
 });
 //more code
}

Remember to use the string literal, because the getKeyChar() method returns a char.


text:
Q: React useState can't use from another component I Created a node.js server and i can write user info to MongoDb and i can create JWT in postman. so i want to use this on react project.
i created react router with private route which it's checking if there is an any user info in the local storage. example , (i did not create a axios post for login api. i just want to write user info with hardcode for see the code is working)
import { useAuth } from "../Context/AuthContext";
import { Navigate,useLocation } from "react-router-dom";

export default function PrivateRoutes({children}){

const user = JSON.parse(localStorage.getItem('user'))

const location = useLocation();

if(!user){
    return <Navigate to="/login" state={{return_url:location.pathname}} />
}

return children;
}

authcontext
So , when i'm in a login page , i created a button and if i click this button i want to access to my AuthProvider and set user info to the LocalStorage in AuthProvider.
Login page,
LoginPage.js
import { useAuth } from "../../../Context/AuthContext";
import { useNavigate,useLocation } from "react-router-dom";

export default function LoginPage(){

const navigate = useNavigate();
const location = useLocation();

const { setUser } = useAuth();

const loginHandle = () => {
    setUser({
        id : 1,
        username : 'umitcamurcuk'
    })

    navigate(location?.state?.return_url || '/');
}

const logoutHandle = () => {
    setUser(false);
    navigate('/');
}

return (
    <div>
        <button onClick={loginHandle}>Sign In</button>
        <button onClick={logoutHandle}>Cikis yap</button>
    </div>
   )
}

and my AuthContext page,
AuthContext.js
import { createContext, useState , useContext, useEffect } from "react";

const Context = createContext()

export const AuthProvider = ({ children }) => {

const [user , setUser] = useState(JSON.parse(localStorage.getItem('user')) || false);

const data = [ user, setUser ]

useEffect(() => {
    localStorage.setItem('user', JSON.stringify(user))
},[user])

return(
    <Context.Provider value={data}>
        {children}
    </Context.Provider>
)

}

export const useAuth = () => useContext(Context);

But when i click login button , this error show up
error
LoginPage.js:12 Uncaught TypeError: setUser is not a function

and my indexJS
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {BrowserRouter} from 'react-router-dom';
import { AuthProvider  } from './Context/AuthContext.js';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <AuthProvider>
      <App />
    </AuthProvider>
  </BrowserRouter>
);

is anyone for help me ?
Thanks

A: You defined your value as array and not an object
const [user, setUser] = useAuth();

or
const data = { user, setUser }


text:
Q: Convert JSONP to JSON with Spring RestTemplate I have a service which downloads a JSONP file containing JSON and processes it. I am trying to do it in the correct Spring way but I have not found any tutorials for this particular scenario (though there are plenty about converting json to jsonp).
To illustrate the problem, lets say that I am hitting the following url: "https://www.example.com/file.jsonp" which contains the following:
callback(
 {
   "field1": "value1",
   "field2": "value2"
 }
);

In order to process the JSON, I need to remove the callback (which I am currently doing manually with substring). Is there any recommended way in Spring how to get POJO directly from this JSONP file?
Let's assume that I only have the annotated pojo and just want to call:
  RestTemplate restTemplate = new RestTemplate();
  Pojo pojo = restTemplate.getForObject(url, Pojo.class);

At the moment, it gives me the following exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class com.berrycloud.blueberry.monitor.price.model.OnDemandPricePOJO] and content type [application/javascript]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868)
...

Thank you for any tips. I hope this is not a duplicate.

A: It turns out that there is no built in converter for JSONP objects as described in my question. I ended up manually removing the beginning and end of the string and then converting the rest into standard JSON.
Another possibility is to implement a custom MessageConvertor and preprocess the JSONP object there.
A nice tutorial on how to write custom message convertors can be found HERE.


text:
Q: Culture-conversion in C# with DateTime I'm having trouble getting my ASPX-App to work on the productive server. As my local environment is german but the server is english and my whole code didn't provide culture-support, I'm currently implementing that throughout the script.
As you might think, as I'm writing this in here, it doesn't quite work the way I want it to.
The App uses a MSSQL-Database for gathering information that is based on dateranges. So, I use the user-selected daterange for calculation using Date BETWEEN x AND y.
The dates are set by the user and parsed in the script to datetime-values to be able to handle them:
_DateRangeStart = DateTime.Parse(DateStart + " 00:00:00", _Culture);
_DateRangeEnd = DateTime.Parse(DateEnd + " 23:59:59", _Culture);

Where _Culture is defined as following:
public CultureInfo _Culture = CultureInfo.GetCultureInfo("de-DE");

and _DateRangeStart (and End) are the user-input from text-fields.
So, as I look into the skript, it shows me that the user input is transformed from 1.11.2009 (which is a correct german formatted date) to 11/1/2009 00:00:00 AM, which should be 1.11.2009 00:00:00 (for _DateRangeStart).
This value cannot be read by the SQL and it gives me an error that converting a char to a valid datetime was not possible.
Why is the conversion not done correctly?

A: I'm guessing you are calling ToString() on your DateTime variable and it's outputting in the default format. SQL then tries to interpret it in it's default format and fails. I think what you need to do is format the date in an unambiguous format and send it to SQL Server.
E.g.
  string myDate = _DateRangeStart.ToString("yyyy-MM-dd");

A: Is your sql server set to another culture than de-de ?  That would also create this behavior. If your sql server thinks he's an american he wants american formatted dates.


text:
Q: getting ids from 3 tables a team table which containd a team ID and a team name and then 2 further tables that contain data from a quiz and another with data from a questionnaire.
I need to get a list of team IDs that have completed BOTH the quiz (so have some quiz data) AND the questionnaire (so have some questionnaire data) but I can't see how to join the 3 tables to get the list of ids I need.
Any pointers greatly received

A: As you said in upper comment..

I actually want team IDs that are in either of the data tables. How
  would that amend the query? – Dave

Try this, This is what I understood with your words..
select teamID,teamName from team where teamID in (select teamID from quiz) or teamID in (select teamID from questionnaire);

A: Assuming you have some reference of team table inside quiz and questionaire tables, you will need to make a join this way -
SELECT team.id, team.name
from
 team, quiz, questionnaire
where
 team.id=quiz.team_id
 AND team.id=questionnaire.team_id

when you do team.id=quiz.team_id AND team.id=questionnaire.team_id only those team IDs which are present in both quiz and questionnaire tables willbe shown in the result.

If you need team ID which exists in either of the tables quiz or questionaire, then you will to replace AND by OR-
SELECT team.id, team.name
from
 team, quiz, questionnaire
where
 team.id=quiz.team_id
 OR team.id=questionnaire.team_id


text:
Q: Finding no. of working days in a month till sysdate/ today's date is it is current month I am using the following query to find out the number of working days in a month excluding the weekends
select payroll_id as payrollId,
(select count(*)
from ( select rownum rnum
from all_objects
where rownum <= to_date(to_char(last_day(to_date('01-'||'MAY'||'2017','DD-MM-YYYY')),'DD')||'MAY'||'2017','DD-MM-YYYY') - to_date('01-'||'MAY'||'2017','DD-MM-YYYY')+1 )
where to_char( to_date('01-'||'MAY'||'2017','DD-MM-YYYY')+rnum-1, 'DY' )
not in ( 'SAT', 'SUN' )) - (select count(*) from admin_holiday where to_char(holiday_date,'DD-MON-YYYY') like '%-MAY-2017%' and holiday_type_id=1) days
from employee where DEL_FLAG=1 order by payrollId

Here, payrollId is the employee_id in employee table and admin_holiday is a table that contains information about the national holidays in a month
My requirement is that if the month is current month then the working days should be upto today's date. For example the current month is MAY/2017 and till today(i.e 22/05/2017) the working days count excluding weekends is 15 (10/05/2017 is a national holiday according to Hindu calendar.
How do I obtain the required result.
NOTE this action has to be performed in a single select statement and no other pl/sql blocks, etc.

A: Here is how I would approach the equivalent query. By placing the date range calculation into a small cross joined query you can access the result easily throughout the remainder of the query.
SELECT
     e.payroll_id AS payrollId
  ,  cj. working_days
FROM employee e
cross join (
        select
             GREATEST(NEXT_DAY(start_date, 'MON') - start_date - 2, 0)
            + ((NEXT_DAY(end_date, 'MON') - NEXT_DAY(start_date, 'MON'))/7)*5
            - GREATEST(NEXT_DAY(end_date, 'MON') - end_date - 3, 0)
            - (
                  SELECT COUNT(holiday)
                  FROM admin_holiday
                  WHERE holiday_date BETWEEN start_date AND end_date
               )
              as working_days
        FROM (
              select
                 to_date('20170501','yyyymmdd')  as start_date
               , to_date('20170522','yyyymmdd')  as end_date
              from dual
            )
        ) cj
WHERE e.DEL_FLAG = 1
ORDER BY e.payrollId

The working days logic is:
Calculate leading days in first week + (Count the number on mon/fri periods) * 5 - number of trailing days in final week - the additional holidays in a table:
select
      GREATEST(NEXT_DAY(start_date, 'MON') - start_date - 2, 0)
    + ((NEXT_DAY(end_date, 'MON') - NEXT_DAY(start_date, 'MON'))/7)*5
    - GREATEST(NEXT_DAY(end_date, 'MON') - end_date - 3, 0)
    - (
          SELECT COUNT(holiday)
          FROM admin_holiday
          WHERE holiday_date BETWEEN start_date AND end_date
       )
      as working_days
    , start_date
    , end_date
    , holidays
    , end_date - start_date
FROM (
      select
         trunc(sysdate,'MM')  as start_date
       , trunc(sysdate)       as end_date
      from dual
    )

example (not there is zero holidays here):
+--------------+--------------+-------------+------------+-------------------------+
| WORKING_DAYS | START_DATE   | END_DATE    | HOLIDAYS   |   END_DATE-START_DATE   |
+--------------+--------------+-------------+------------+-------------------------+
|           16 |  01.05.2017  | 22.05.2017  |          0 |                      21 |
+--------------+--------------+-------------+------------+-------------------------+

To manually set the dates you can do this:
select
      GREATEST(NEXT_DAY(start_date, 'MON') - start_date - 2, 0)
    + ((NEXT_DAY(end_date, 'MON') - NEXT_DAY(start_date, 'MON'))/7)*5
    - GREATEST(NEXT_DAY(end_date, 'MON') - end_date - 3, 0)
    - (
          SELECT COUNT(holiday)
          FROM admin_holiday
          WHERE holiday_date BETWEEN start_date AND end_date
       )
      as working_days
FROM (
      select
         to_date('20170501','yyyymmdd')  as start_date
       , to_date('20170522','yyyymmdd')  as end_date
      from dual
    )


text:
Q: Getting Fun White Square when Uploading to S3 via Put Friends, Countrymen, Lend me your ears...
I'm signing my url for amazon s3, and then using fileReader and Fetch to put my file in s3.
Though when I do I get a fun white square instead of my image:
https://s3.amazonaws.com/hubbble/Gabe/lX4H0.png
const reader = new FileReader();
reader.onload = ((e) => {

  let s3headers = new Headers();
  s3headers.append("content-type", 'image/png');

  fetch(signedRequest, {
      method: 'PUT',
      headers: s3headers,
      body: e.currentTarget.result
  }).then((response)=>{
    console.log(response);
  });
});

*

*Permissions Issue? Don't really think so as you can definitely view the image

*Corrupted somehow?

*Maybe an incorrect content type?

Thoughts?
Thanks for any guidance, been banging my head against the wall on this!

A: The contents of that appear to be a base64 encoded image. That is, you're uploading a text file and not a binary image (and then saying it is, a image/png) You could just convert it first doing something like this first.

A: If anyone is coming from a Node environment, the solution is to use the following code. I tested this and it works. There is no need for atob or doing some bytearray acrobatics.
      // base64DataString is the base64 string, which I assume you have
      // base64Data is a Buffer that is encoded in base64!
      // STEP 1: we remove the header of the dataUri string
      const base64Data = new Buffer.from(b64DataString.replace(/^data:image\/\w+;base64,/, ""), 'base64');

      // STEP 2: CALL PUT OBJECT
      s3.putObject(
        {
          Bucket: "your bucket name",
          Key: `yourfile.jpg`, // the key for S3 location
          Body: base64Data,
          ContentEncoding: 'base64', // important to tell that the incoming buffer is base64
          ContentType: "image/jpeg", // e.g. "image/jpeg" or "image/png"
          ACL:'public-read'
        },
        (err, data) => {
          if(err) {
            reject(err)
            return;
          }
          console.log("UPLOAD SUCCESSFULLY:") //optional
          console.log(data) //optional
          resolve(data); // if this is in a promise, then include
        }
      )


text:
Q: Aren't pointers supposed to point to nullptr when an array ends? Why does this code not work?, I used the function from "A Tour of C++" and it tells me that pointers point to nullptr when an array ends briefly explained. I tried to implement it and it doesn't show anything. Thanks in advance.
#include <iostream>

int count_x(char* p, char x)
{
    int count = 0;
    while (p)
    {
        if (*p == x){++count;}
        p++;
    }
    return count;
}

int main()
{
    char my_string[] {"hello world"};
    char* my_string_ptr {my_string};

    std::cout << "There are " << count_x(my_string_ptr,'a') << " a in the string\n";

    return 0;

}```

A: No, pointer at the end of an array are not null. You probably want:
while (*p)

which is the same as
while (*p != '\0')

and
while (*p != 0)

which are testing for the null character.

A: p stores an address value in the computer memory which is deferenced by astricks (*) like *p.
In your code,
p++;

is incrementing the current address to which the p is pointing currently. When you reach the end of the string (at the last null character), p will be the address of the null character not the null itself, so
while(p)

will be true and following p++ will increment it to next memory location (which technically does not belong to the allocated string), and hence p will return non-zero address this while loop will keep on running and you will get a segmentation fault.
As the jeffrey has mentioned in his answer too, use *p to test the while condition so when p reaches the null, it can derefer it.

A: Your original code crashed (or caused segmentation fault). The reason is that in the while loop, you did not correctly specify the condition to exit this while loop. Therefore, the while loop will continue to go past the end of the string, which causes segmentation fault (i.e, your app will crash).
One correct way to exit the while loop is to compare each character of  the string to see if that character equals the end of string character that is '\0'.
When you encounter this end of string character that is '\0',  you should exit the while loop.
I have fixed one line of your code, and your function is now working fine as shown below:
int count_x(char* p, char x)
{
    int count = 0;

    while (*p != '\0')   // I fixed your code here
    {
        if (*p == x){++count;}
        p++;

    }
    return count;
}

Again, please note that the code above runs well, and produces the correct result as I have verified it. Please let me know if you run into any issue. Cheers.


text:
Q: configure always_return_data based on param I'm using django tastypie, and would like to configure always_return_data to trigger true or false based on a patch vars specified (specifically a patch list update).
Example: patch to /api/v1/thisresource
data: {objects: {[name="john"]}, return_data: false}

Is there any way to configure this?

A: I actually just made another custom resource for the specific patch's that had a ton of data to sift through, seems to have fixed in...


text:
Q: Receiving Array from client side javascript page I'm trying to send values of a table by arrays to server. On server side php file putting a echo, I can see that the value has passed in a form like - [value1, value2] etc. But on serverside php file, when I'm trying to retrieve the values using Php array it's not working.
Here's my client side JS function -
function saveData(){

var req;
try{
// Opera 8.0+, Firefox, Safari
    req = new XMLHttpRequest();
    //document.write("2");
    }catch (e){
    // Internet Explorer Browsers
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            try{
               req = new ActiveXObject("Microsoft.XMLHTTP");
            }catch (e){
           // Something went wrong
               alert("Your browser broke!");
               return false;
           }
        }
   }

    req.onreadystatechange = function() {
   //Is request finished? Does the requested page exist
   if(req.readyState==4 && req.status==200) {
        alert(req.responseText);
        //document.getElementById('editgamediv').innerHTML = req.responseText;
    }
}

var table = document.getElementById('POITable');
var rowCount = table.rows.length;
var latArray = []
var lngArray = []
var id = []
var id2=[]
var levelname = document.getElementById('leveltext');
//alert(rowCount);

for(var i=1; i< rowCount; i++){
    latArray[i] = table.rows[i].getElementsByTagName('input')[0].value;
    lngArray[i] = table.rows[i].getElementsByTagName('input')[1].value;
    id[i] = levelname+i;
    id2[i] = levelname+i+i;

    //alert(lngArray[i]);
}

var queryString= "?latArray="+latArray;
queryString+="&lngArray="+lngArray+"&id="+id+"&id2="+id2+"&levelname="+levelname;
req.open("GET","http://aiworker2.usask.ca/PasswARGUI1/addLevel_server.php"+queryString,true)  //true indicates ASYNCHRONOUS
req.send(null);
}

Server side Php -
$dbhost = myHost;
$dbuser = my User name;
$dbpass = my Password;
$dbname = "testGame";

    //Connect to MySQL Server
$link= mysql_connect($dbhost, $dbuser, $dbpass);

if (!$link) {
    die('Could not connect: ' . mysql_error());
    echo 'Go n Die';
}
else{
    echo 'Connected successfully';
}
    mysql_select_db($dbname);
    //$latArray = array();
    $latArray=$_GET['latArray'];
    $lngArray[]=$_GET['lngArray'];
    $id[]=$_GET['id'];
    $id2[]=$_GET['id2'];
    $levelname = $_GET['levelname'];

    echo $latArray;
    $printlatArray[0] = $latArray[0];

    echo $printlatArray;
    for($num = 0; $num< count($latArray) ; $num++){

        $sql_zones1 = "INSERT INTO Zones (zone_id, latitude, longitude, tag, relativeAlt, alt, dimension) VALUES
          ('{$id[$num]}', '{$latArray[$num]}', '{$lngArray[$num]}', '{$levelname[$num]}', '0', '10', '3')";

        $sql_zones2 = "INSERT INTO Zones (zone_id, latitude, longitude, tag, relativeAlt, alt,  dimension) VALUES
          ('{$id2[$num]}', '{$latArray[$num]}', '{$lngArray[$num]}', '{$levelname[$num]}', '50', '80','2')";

        $sql_transform1 = "INSERT INTO Transform (poiID, rel, angle, scale) VALUES ('{$id[$num]}', 'true', '0', '3')";
        $sql_transform2 = "INSERT INTO Transform (poiID, rel, angle, scale) VALUES ('{$id2[$num]}', 'true', '0', '4')";

        $sql_object1 = "INSERT INTO Object (poiID, size) VALUES ('{$id[$num]}', '3')";
        $sql_object2 = "INSERT INTO Object (poiID, size) VALUES ('{$id2[$num]}', '3')";

    }

    if (!$result_zones1 || !$result_transform1 || !$result_object1 ||!$result_zones2 || !$result_transform2 || !$result_object2) {
    die('Invalid query: ' . mysql_error());
    }
    else{
        echo "success";
     @mysql_close($link);
     return;
    }

The table on the client size is dynamic. So, I cannot even put the values in a single variable.
Need help badly :(

A: In your javascript, you should join the arrays into a regular comma-delimited string, and then when received by PHP you can explode() them back into an array:
// Javascript
// Join the arrays into comma-delimited strings
var latString = latArray.join(",");
var lngString = lngArray.join(",");

// Later...
// PAss them into the querystring as strings:
var queryString= "?latString="+latString;
queryString+="&lngString="+lngString+"&id="+id+"&id2="+id2+"&levelname="+levelname;

//--------------
// In PHP, explode them back to arrays:
$latArray = explode(",", $_GET['latString');
$lngArray = explode(",", $_GET['lngString');


text:
Q: Picking out a specific column in a table My goal is to import a table of astrophysical data that I have saved to my computer (obtained from matching 2 other tables in TOPCAT, if you know it), and extract certain relevant columns. I hope to then do further manipulations on these columns. I am a complete beginner in python, so I apologise for basic errors. I've done my best to try and solve my problem on my own but I'm a bit lost.
This script I have written so far:
import pandas as pd
input_file = "location\\filename"
dataset = pd.read_csv(input_file,skiprows=12,usecols=[1])

The file that I'm trying to import is listed as having file type "File", in my drive. I've looked at this file in Notepad and it has a lot of descriptive bumf in the first few rows, so to try and get rid of this I've used "skiprows" as you can see. The data in the file is separated column-wise by lines--at least that's how it appears in Notepad.
The problem is when I try to extract the first column using "usecol" it instead returns what appears to be the first row in the command window, as well as a load of vertical bars between each value. I assume it is somehow not interpreting the table correctly? Not understanding what's a column and what's a row.
What I've tried: Modifying the file and saving it in a different filetype. This gives the following error:
FileNotFoundError: \[Errno 2\] No such file or directory: 'location\\filename'

Despite the fact that the new file is saved in exactly the same location.
I've tried using "pd.read_table" instead of csv, but this doesn't seem to change anything (nor does it give me an error).
When I've tried to extract multiple columns (ie "usecol=[1,2]") I get the following error:
ValueError: Usecols do not match columns, columns expected but not found: \[1, 2\]

My hope is that someone with experience can give some insight into what's likely going on to cause these problems.

A: Maybie you can try dataset.iloc[:,0] . With iloc you can extract the column or line you want by index(not only). [:,0] for all the lines of 1st column.

A: The file is incorrectly named.
I expect that you are reading a csv file or an xlsx or txt file. So the (windows) path would look similar to this:
import pandas as pd
input_file = "C:\\python\\tests\\test_csv.csv"
dataset = pd.read_csv(input_file,skiprows=12,usecols=[1])

The error message tell you this:
No such file or directory: 'location\\filename'


text:
Q: Internal server error when running php script to add watermark on images Am developing new photography website in which images are uploaded frequently.... Now I want to add watermark on uploaded images before it goes to client side, I have used the following code for watermark
$SourceFile = "sys\img\image1.jpg";
$DestinationFile = "sys\img\image1-wm.jpg";
$WaterMarkText = 'Copyright sys.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
 list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$font = 'arial.ttf';
$font_size = 10;
imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
   imagejpeg ($image_p, $DestinationFile, 100);
} else {
   header('Content-Type: image/jpeg');
  imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};

But it showing the following error
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your
request.
Please contact the server administrator to inform of the time the error occurred and of anything
you might have done that may have caused the error.

More information about this error may be available in the server error log.

What is the mistake I have done...?

A: Finally I found an another way to add watermark to my images...
Here is the code for watermark....
$filename=$_REQUEST['filename'];
$imgpath="img/"; // Folder of your images in the server
$imgpath = $imgpath.$filename;
header('content-type: image/jpeg'); //HTTP header - assumes your images in the gallery are JPGs
$watermarkfile="img/watermark.png";
$watermark = imagecreatefrompng($watermarkfile);
list($watermark_width,$watermark_height) = getimagesize($watermarkfile);
$image = imagecreatefromjpeg($imgpath);
$size = getimagesize($imgpath);
$dest_x = $size[0] - $watermark_width - 15;
$dest_y = $size[1] - $watermark_height - 15;
imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);

Save this code as watermark.php and then use it in the img tag as follows...
<img src="watermark.php?filename=image1.jpg">

Thats it... Working fine...


text:
Q: Hilbert Spaces and Projections Suppose that $\{Y_{t}: t \in \mathbb{Z} \}$ is a stationary zero mean time series. Consider the Hilbert space $\mathcal{H}$ generated by the random variables $\{Y_t: t \in \mathbb{Z} \}$ with inner product $$ \langle X, Y \rangle = E(XY)$$ and norm $$||X||^2 = E|X|^2$$
Consider the subspace $\mathcal{M}$ generated by the random variables $\{Y_u: u \leq t \}$. Why are future values found by projecting onto the subspace $\mathcal{M}$? For example, why is $Y_{t+1}$ found by $\mathcal{P}_{\mathcal{M}}Y_{t+1}$?


text:
Q: Jquery error in console Am trying to concat
         var id = this.id;
         var repoCopy = repo.filter( "#" + id ).clone();

But when I run my code I have this error in console although I have used this before without facing any errors
Uncaught Error: Syntax error, unrecognized expression: #
    at Function.fa.error (jquery.min.js:2)
    at fa.tokenize (jquery.min.js:2)
    at fa.compile (jquery.min.js:2)
    at fa.select (jquery.min.js:2)
    at fa (jquery.min.js:2)
    at Function.fa.matches (jquery.min.js:2)
    at Function.n.filter (jquery.min.js:2)
    at z (jquery.min.js:2)
    at n.fn.init.filter (jquery.min.js:2)
    at HTMLAnchorElement.<anonymous> (index.html:527)

A: Check the value of this, if it's not what you think it is it might not have an id.

A: Have you tried something like this:
var id = "#" + this.id;
var repoCopy = repo.filter(id).clone();


text:
Q: R - parse XML getElementById and nodeValue Is there a XML library for R that would allow me to simply do this :
desiredValue <- getElementById("myDesiredId").NodeValue()

I'm looking for a library that is short and simple.
Cheers !

A: You mean package, not library, and yes there is.  It's called XML.
CRAN link and Windows binary.


text:
Q: iOS - How does Cordova invoke objective c function? How does cordova trigger objective-c native method. For example- When a user taps on submit button (html button), app needs to invoke native objective c function called 'dataSubmitted'.

*

*Does Cordova monitor webview navigation and based on URL tags call method internally?

*Is there any way JavaScript can interact with Obj-c native methods except monitoring webview navigations?

A: There are two ways to communicate with native language from JS.
1. Go to MainViewController.m -> find a function named webViewDidFinishLoad
and add the follwing code snippet..
- (void)webViewDidFinishLoad:(UIWebView*)theWebView
{
    NSString *pageUrl = [theWebView.request.URL absoluteString];

    if ([pageUrl  containsString:@"xyz"]) {
      //   xyz for xyz.html
    }else if ([pageUrl  containsString:@"abc"]) {
      //  abc for abc.html
    }

    self.webView = theWebView;
    return [super webViewDidFinishLoad:theWebView];
}

*Develop your own native plugin with cordova.exec ;

A: There are a few libraries available to communicate between Javascript and Objective-C it seems:

WebViewJavascriptBridge: https://github.com/marcuswestin/WebViewJavascriptBridge
GAJavaScript: https://github.com/newyankeecodeshop/GAJavaScript

I suggest you to check out this beautiful SO Post which explains Javascript & Objective-C interactions in detail.


text:
Q: What's the difference between a random variable and a measurable function? I've tried to wrap my head around the measure theoretical definition of a random variable for a couple of days now.
In his book Probability and Stochastics, Erhan Çinlar defines a measurable function as follows:

Let (E, ℰ) and (F, Ƒ) be measurable spaces [where ℰ and Ƒ are σ-algebras on the sets E and F respectively]. A mapping f : E ↦ F is
  said to be measurable relative to ℰ and Ƒ if
f⁻¹B ∈ ℰ for every B in Ƒ.

Later, he defines a random variable as follows:

Let (Ω, H, ℙ) be a probability space. The set Ω is called the sample space; its elements are called outcomes. The σ-algebra H may be called the grand history; its elements are called events.
[...]
Let (F, Ƒ) be a measurable space. A mapping X : Ω ↦ F is called a
  random variable taking values in (F, Ƒ) provided that it be measurable relative to H and Ƒ, that is, if
X⁻¹A = {X ∈ A} := {ω ∈ Ω : X(ω) ∈ A} is an event [i.e. ∈ H] for every A in Ƒ

Aside from using (Ω, H) instead of (E, ℰ), these definitions look pretty identical to me. What's the difference? Are all measurable functions on probability spaces random variables? (And why is it called random if it's deterministic?)

A: In the theory of probability as developed by Kolmogorov, random variables just are measurable functions (provided that the underlying space is a probability space, which is just a space with a normalized finite measure).
That's actually the key idea to Kolmogorov's theory. It allows us to rigorously encode everything that one did with elementary probability theory into measure spaces and measurable functions. In this formulation, things like expected value (and other moments) are just linear functionals which allows one to use all of the results of measure theory and functional analysis (such as inequalities, convergence results, etc.) as tools for probabilistic calculations.

A: Formally, they are the same: a random variable is a particular type of measurable function. However, there are important differences which may be more philosophical than mathematical.
There is a (somewhat subjective) difference in the underlying domains. A random variable operates on a set of outcomes of a random experiment or process. A measurable function normally does not (otherwise it's called a random variable). This isn't a mathematical difference, per-se, as the underlying domains are just sets, and the $\sigma$-algebra and measures provide the relevant mathematical structure.
For a probability space though, even if a specific random process isn't mentioned, one might argue that there is an implied assumption that we are to imagine that such a random process 'exists'. Otherwise, there is no need for probabilists to have their own language $-$ probability vs. measure; almost surely or almost always vs. almost everywhere, etc.
A philosophical note:
A random variable can only be evaluated by performing an unpredictable experiment, i.e. you can't truly choose which $\omega$ to plug in. If you did choose a specific $\omega$, then you aren't evaluating a random variable, you're just evaluating a measurable function. A regular measurable function can always be evaluated however you please. This is a subtle, more philosophical point, but mathematicians should be free to discuss such topics. It is an important part of developing a deep understanding, similar to the way that physicists discuss the existence of the objects they study.
The set $\Omega$ is oftentimes not explicitly described. When $\Omega$ is clearly defined, often a note is added to state that we are ignoring certain things in order to define $\Omega$. However, $\Omega$ is usually mapped to another set (via a random variable) $X:\Omega\rightarrow A$ thereby inducing a probability measure on $A$, which is a more tractable space.
An example:
Let $X$ be the random variable representing the outcome of a fair coin flip; $\Omega$ can be thought of as the set of outcomes of that coin flip (actual real physical outcomes, not numbers or letters). Of course, we usually map $\Omega$ to $\{0,1\}$ to do calculations. The random variable $X$ acts on $\Omega$ though, not $\{0,1\}$. So the value of $X$ depends on the actual outcome of a real physical coin flip $-$ which you cannot predict perfectly, i.e. it's random. Once you are working in $\left(\{0,1\},2^{\{0,1\}},\nu\right)$, where $\nu$ is simply a normalized counting measure, we can think of $X$ as being the deterministic identity function: $X(i)=i$. But the probability space is $\left(\Omega,\mathcal{F},\mathbb{P}\right)$, on which $X$ is a random variable. Usually, $X(\omega)=\mathbf{1}_{\{\text{upper face on coin is heads}\}}(\omega)$. So $X:\left(\Omega,\mathcal{F},\mathbb{P}\right)\rightarrow\left(\{0,1\},2^{\{0,1\}},\mu\right)$ thus maps a probability space to a measure space, in a sense.
Even reducing $\Omega$ to $\{\omega_1,\omega_2\}$ is an oversimplification.  With a coin flip, there could be all sorts of variables to include, such as the length and shape of the flight path of the coin, how many times it flipped in the air, the location and angle of rotation after it lands, etc. All of these could result in a large number of $\omega$'s.
But you could partition $\Omega=H\cup T\cup N$. Where $$H=\{\omega| \text{upper face of coin is heads}\},$$ $$T=\{\omega| \text{upper face of coin is tails}\},$$ and $$N=\{\omega| \text{upper face of coin is neither heads nor tails}\}.$$ For a fair coin, $\mathbb{P}(N)=0$ and $\mathbb{P}(H)=\mathbb{P}(T)=1/2$.
Often, $\Omega$ is completely ignored even. In the above example, instead of saying $P(\{\omega|X(\omega)=1\})=1/2$, we write $P(1)=1/2$.


text:
Q: SharePoint Workflow permissions - where is it inheriting permissions from? I used SharePoint Designer 2013 to create an approval workflow which simply modifies the text in the default mails for clarity. It is technically a SharePoint 2010 workflow. I couldn't get the 2013 workflows to work but can't remember the details.
Once the workflow is started, the permissions are set for the appropriate user as it goes through the workflow. However, there are additional permissions that are granted for CERTAIN people with FULL CONTROL, but not all. I can't understand why.
Where are these permissions inherited from? I would like my power users (anyone with FULL CONTROL) to be able to see all tasks no matter where they are in a workflow.

A: In workflow 2010 platform, we can set "Only allow task recipients and process owners to edit workflow tasks" option under settings section when click blue "Approval" in the start approval process action.
If not tick this option, other users with "Contribute" permission level or high level can approve the workflow.
If the users cannot view the tasks, please check if they have permission in the associated task list.


text:
Q: java.lang.IllegalStateException: No data type for node AggregateNode: 'MAX' I'am Trying to get the row with the max date value from mysql table Transfer
Her Is the Dao
    public static Transfer getTransferByID(int id){

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction T = null;
    Query Q = null;
    Transfer Result = null;
    Date D = null;

    try {
        T = session.beginTransaction();
        String query1 = "SELECT MAX(TDate) FROM Transfer WHERE EmpID=:id GROUP BY EmpID";
        Q = session.createQuery(query1);
        Q.setInteger("id", id);
        D = (Date) Q.uniqueResult();
        String query2 = "FROM Transfer WHERE EmpID=:id AND TDate=:dt";
        Q = session.createQuery(query2);
        Q.setInteger("id", id);
        Q.setDate("dt", D);
        Result = (Transfer) Q.uniqueResult();
        T.commit();
        return Result;

    } catch (HibernateException e) {
        if (T != null) T.rollback();
        return null;

    } catch (NullPointerException e) {
        if (T != null) T.rollback();
        return null;

    } finally {
        session.close();
    }
}

I'am using java.sql.date
but when i execute i get this
    Caused by: java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.AggregateNode
 \-[AGGREGATE] AggregateNode: 'MAX'
    \-[IDENT] IdentNode: 'TDate' {originalText=TDate}
    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:174)

what is wrong with my HQL
please help

A: Please try below HQL Query with aliases:
public static Transfer getTransferByID(int id){

    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction T = null;
    Query Q = null;
    Transfer Result = null;
    Date D = null;

    try {
        T = session.beginTransaction();
        String query1 = "SELECT MAX(transfer.TDate) FROM Transfer transfer WHERE transfer.EmpID=:id GROUP BY transfer.EmpID";
        Q = session.createQuery(query1);
        Q.setInteger("id", id);
        D = (Date) Q.uniqueResult();
        String query2 = "FROM Transfer transfer WHERE transfer.EmpID=:id AND transfer.TDate=:dt";
        Q = session.createQuery(query2);
        Q.setInteger("id", id);
        Q.setDate("dt", D);
        Result = (Transfer) Q.uniqueResult();
        T.commit();
        return Result;

    } catch (HibernateException e) {
        if (T != null) T.rollback();
        return null;

    } catch (NullPointerException e) {
        if (T != null) T.rollback();
        return null;

    } finally {
        session.close();
    }
}


text:
Q: Ошибка Exception thrown at 0x008C22A2 in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x000F0000 Помогите разобратся с проблемай, записываю данные в файл через ifstream читаю содержимое также.
Если файл пустой по программа работает, следует записать что то в файл при повторном запуске не запускается в VisualStudio показывает ошибку
Exception thrown: read access violation.
_Pnext was 0x6C438C.
#include
#include
#include
#include

using namespace std;

class Tovar {
public:
string nazvanie = "";
string proizvoditelj = "";
string sotrudnik = "";
double cena = 0;
int id = 0;
short int kolicestvo = 0;
Tovar() {
string nazvanie = "";
string proizvoditelj = "";
string sotrudnik = "";
double cena = 0;
int id = 0;
short int kolicestvo = 0;
}

Tovar(int i, string n, string p, string sot, double c, short int k)
{
id = i;
nazvanie = n;
proizvoditelj = p;
sotrudnik = sot;
cena = c;
kolicestvo = k;
}
bool operator == (const Tovar& s) const { return id == s.id; }
bool operator != (const Tovar& s) const { return! operator==(s); }
};
list tovarlist;

int max_id()
{
if (::tovarlist.size() < 1) {
return 0;
};
::tovarlist.sort([](const Tovar& f, const Tovar& s) { return f.id > s.id; });
return ::tovarlist.front().id;
}

int read()
{
ifstream file_obj;

file_obj.open("tovar.bin", ios::in | ios::binary);

Tovar obj; //

file_obj.read((char*)&obj, sizeof(obj));
if (!file_obj.is_open())
{
cout << "Files is not open!" << endl;
}
else
{
while (!file_obj.eof()) {
::tovarlist.push_back(obj);
file_obj.read((char*)&obj, sizeof(obj));
}
}
file_obj.close();
return 0;
}

int save()
{
ofstream file_obj;
Tovar obj;

file_obj.open("tovar.bin", ios::in | ios::trunc);
for (Tovar t : ::tovarlist) {
obj.id = t.id;
obj.nazvanie = t.nazvanie;
obj.cena = t.cena;
obj.proizvoditelj = t.proizvoditelj;
obj.kolicestvo = t.kolicestvo;
obj.sotrudnik = t.sotrudnik;
file_obj.write((char*)&obj, sizeof(obj));}

file_obj.close();
return 0;
cout << "Saved";
}

void add()
{
string nazvanie, proizvoditelj, sotrudnik,sotrudnik_name, sotrudnik_surname, temp_sotrudnik;
double cena;
short int kolicestvo, temp;
string temp_string;
cin >> nazvanie;
cin >> proizvoditelj;
cin >> cena;
cin >> kolicestvo;
cin >> sotrudnik_name;
cin >> sotrudnik_surname;
temp_sotrudnik = sotrudnik_name + " " + sotrudnik_surname;
Tovar tovar = Tovar(max_id() + 1, nazvanie, proizvoditelj, temp_sotrudnik, cena, kolicestvo);
::tovarlist.push_back(tovar);
save();
}
}

void print() {
    header();
    for (Tovar t : ::tovarlist) // cikl prolistivaet vesj falj i vivodit objekti iz lista
    {
        cout.width(4); cout << internal << t.id << " |" << " ";
        cout.width(12); cout << internal << t.nazvanie << " |" << " ";
        cout.width(7); cout << internal << t.cena << " |" << " ";
        cout.width(21); cout << internal << t.proizvoditelj << " |" << " ";
        cout.width(11); cout << internal << t.kolicestvo << " |" << " ";
        cout.width(25); cout << internal << t.sotrudnik << " |" << " " << endl;
    }
}

A: В коде желательно было указать main() функцию. По обьявлению классов и функций сложно что то сказать. Касательно самой ошибки - исключение вызывается к не инициализированной переменной.


text:
Q: Spark - Mysql connection - Unsupported major.minor version 52.0 error I am trying to extract MySQL data through Spark but unfortunately I am getting below error. Here is my sample RDD :
emp_df = sqlContext.read.format("jdbc").option("url",url).option("dbtable","employee").option("driver", 'com.mysql.jdbc.Driver').load()

Error :
**Py4JJavaError: An error occurred while calling o149.load. : java.lang.UnsupportedClassVersionError: com/mysql/jdbc/Driver : Unsupported major.minor version 52.0**    at java.lang.ClassLoader.defineClass1(Native Method)    at java.lang.ClassLoader.defineClass(ClassLoader.java:803)  at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)  at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)     at java.net.URLClassLoader.access$100(URLClassLoader.java:71)   at java.net.URLClassLoader$1.run(URLClassLoader.java:361)   at java.net.URLClassLoader$1.run(URLClassLoader.java:355)   at java.security.AccessController.doPrivileged(Native Method)   at java.net.URLClassLoader.findClass(URLClassLoader.java:354)   at java.lang.ClassLoader.loadClass(ClassLoader.java:425)    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)    at org.apache.spark.sql.execution.datasources.jdbc.DriverRegistry$.register(DriverRegistry.scala:38)    at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:45)   at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:45)   at scala.Option.foreach(Option.scala:236)   at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$.createConnectionFactory(JdbcUtils.scala:45)   at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:120)     at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:91)   at org.apache.spark.sql.execution.datasources.jdbc.DefaultSource.createRelation(DefaultSource.scala:57)     at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:158)   at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:119)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:606)     at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:231)     at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:381)   at py4j.Gateway.invoke(Gateway.java:259)    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)     at py4j.commands.CallCommand.execute(CallCommand.java:79)   at py4j.GatewayConnection.run(GatewayConnection.java:209)   at java.lang.Thread.run(Thread.java:745)

A: It is a Java version mismatch. The JDK and JRE should not be conflicting. If you are using JDk-1.8, use JRE 8