text:
Q: Why can I override the operators for - (negation) and ! (not) but not ~ (bitwise not)? Why does the following define the ! and - operators, but fail to define the ~ operator?
#include <type_traits>
#include <cstdint>
#include <typeinfo>
#include <cstdio>

template <typename T, T v>
struct integral_constant
    : std::integral_constant<T, v>
{
};

#define DECL_UNARY_OP(op) \
    template <typename T, T t> \
    constexpr integral_constant<decltype(op t), (op t)> \
    operator op(integral_constant<T, t>) \
    { return {}; } \

DECL_UNARY_OP(~);
DECL_UNARY_OP(-);
DECL_UNARY_OP(!);

int main() {
    constexpr auto x = integral_constant<uint8_t, 1>{};
    constexpr auto y = integral_constant<uint8_t, 10>{};
    constexpr auto z = integral_constant<uint8_t, 100>{};
    puts(typeid(-x).name());  // integral_constant<...>
    puts(typeid(~y).name());  // int!
    puts(typeid(!z).name());  // integral_constant<...>
}

Compiling this on GCC-4.8.2 gives the following on godbolt, where you can clearly see that the middle operation has decayed away from an integral_constant type.
Why is this happening?

A: A simpler reproduction can be obtained by eliminating std::integral_constant:
#include <cstdint>
#include <typeinfo>
#include <cstdio>

template <typename T, T v>
struct integral_constant { };

template <typename T, T t>
constexpr integral_constant<decltype(~t), (~t)>
operator ~(integral_constant<T, t>) { return {}; }

int main() {
    constexpr auto y = integral_constant<uint8_t, 10>{};
    puts(typeid(~y).name());
}

Which now fails to compile with:
<source>: In function 'int main()':
<source>:17:17: error: no match for 'operator~' (operand type is 'const integral_constant<unsigned char, 10u>')
     puts(typeid(~y).name());
                 ^
<source>:17:17: note: candidate is:
<source>:11:1: note: template<class T, T t> constexpr integral_constant<decltype (~ t), (~ t)> operator~(integral_constant<T, t>)
 operator ~(integral_constant<T, t>)
 ^
<source>:11:1: note:   template argument deduction/substitution failed:
<source>: In substitution of 'template<class T, T t> constexpr integral_constant<decltype (~ t), (~ t)> operator~(integral_constant<T, t>) [with T = unsigned char; T t = 10u]':
<source>:17:18:   required from here
<source>:11:1: error: 't' was not declared in this scope
Compiler returned: 1

It seems this can be fixed by adding extra parentheses,
-integral_constant<decltype(~t), (~t)>
+integral_constant<decltype((~t)), (~t)>


text:
Q: Validate Whether Row is Selected MVC 3 In my MVC 3 project, I am using quite a strange bit of code to select a row in a table and perform some updates. My problem is that I am unsure how to validate whether the row has been selected.
Here is the code in my view:

Select an invoice from the grid below:

@if (!string.IsNullOrEmpty(TempData["PaymentError"] as string))
{

@(TempData["PaymentError"] as string)

}

        Invoice Number

        Invoice Amount

        Invoice Month

        Invoice Status

        Client

@using (Html.BeginForm("Confirm", "Invoice"))
{

foreach (var item in Model)
{
    string selectedRow = "";
    if (item.InvoiceNumberID == ViewBag.InvoiceNumberID)
    {
        selectedRow = "selectedRow";
    }

           Select

        @Html.DisplayFor(modelItem => item.InvoiceNumberID)

        @Html.DisplayFor(modelItem => item.InvoiceAmount)

        @Html.DisplayFor(modelItem => item.InvoiceMonth)

        @Html.DisplayFor(modelItem => item.InvoiceStatus)

        @Html.DisplayFor(modelItem => item.Client.FullName)

        @Html.ActionLink("Edit", "Edit", new { id = item.InvoiceNumberID }) |
        @Html.ActionLink("Details", "Details", new { id = item.InvoiceNumberID }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.InvoiceNumberID })

}
<input type='hidden' id='id' name='id' value='0' />

Generate Invoices

Select an amount below to confirm as paid:

Monthly Amounts:	Weekly Amounts:

Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "640", true) R640.00
	Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "140", true) R160.00

Private Lesson (1/2 Hour) @Html.RadioButton("InvoiceAmount", "350", true) R350.00
	Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "87.50", true) R87.50

Group Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "460", true) R460.00	  Private Lesson (1 Hour) @Html.RadioButton("InvoiceAmount", "115", true) R115.00

Custom Amount @Html.RadioButton("InvoiceAmount", "115", true)    @Html.TextBox("InvoiceCustomAmount")

Select a payment type:

@Html.RadioButton("PaymentType", "EFT", true) EFT

@Html.RadioButton("PaymentType", "Credit Card", true) Credit Card

@Html.RadioButton("PaymentType", "Cheque", true) Cheque

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

}

And the code in my controller is:
public ActionResult Confirm(int id, long InvoiceAmount, string PaymentType, float? InvoiceCustomAmount)
    {
        var invoice = db.Invoice.Find(id);

        //now validate that if the logged in user is authorized to select and confirm this invoice or not.
        var clientPayment = new ClientPayments();

        clientPayment.InvoiceNumberID = id;

        if (InvoiceAmount == 115)
        {
            InvoiceAmount = (long)InvoiceCustomAmount;
        }

        var TotalPayments = invoice.ClientPayments.Sum(payment => payment.PaymentAmount) + InvoiceAmount;

        if (TotalPayments > invoice.InvoiceAmount)
        {
            TempData["PaymentError"] = "You cannot pay more than the invoice amount";
            return RedirectToAction("Index");
        }

        clientPayment.PaymentAmount = InvoiceAmount;

        clientPayment.PaymentType = PaymentType;
        clientPayment.PaymentDate = DateTime.Now;
        db.ClientPayments.Add(clientPayment);

        if (TotalPayments != invoice.InvoiceAmount)
        {
            invoice.InvoiceStatus = "Partly Paid";
        }
        else
        {
            invoice.InvoiceStatus = "Confirmed";
        }

        // You don´t need this, since "invoice" was retrieved earlier in the method the database context
        // knows that changes have been made to this object when you call "SaveChanges".
        // db.Entry(invoices).State = EntityState.Modified;

        db.SaveChanges();

        return View();
    }

Is there an easy way to validate if the row has been selected when the form is submitted?
Thanks,
Amy

A: So, what about not enabling the submit button unless you've actually selected something?  You could initially set your submit button to be disabled.  Something like this:
<input type="submit" value="Confirm" class="mysubmit" />

$(document).ready(function () {
   $('.mysubmit').attr('disabled', 'disabled');

   // whatever else...
});

Re-enabling can be done by removing that attribute:
$('.mysubmit').removeAttr('disabled');

Would think you could modify your click to do this:

Didn't test it but seems like that would ensure that the user clicked a select class link before clicking the submit button.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SPARQL query on Pizza ontology I am a beginner in SPARQL. I have the pizza ontology and i'm trying to write a query that lists all hot toppings. So far I've come up with this:
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX pizza: <http://www.co-ode.org/ontologies/pizza/pizza.owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>

SELECT ?targetPizza
WHERE {
?topping rdfs:subClassOf pizza:PizzaTopping .
?topping rdfs:subClassOf ?restriction .
?restriction owl:onProperty pizza:hasSpiciness .
?restriction owl:someValuesFrom pizza:Hot .

}

However, it returns an empty result. Why is my query wrong?
Thanks in advance for your help.

A: Short answer: There is nothing that matches your query. You can see everything that would match your query structure without the given spiciness value by running
PREFIX pizza: <http://www.co-ode.org/ontologies/pizza/pizza.owl#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>

SELECT * WHERE {
  ?topping rdfs:subClassOf pizza:PizzaTopping .
  ?topping rdfs:subClassOf ?restriction .
  ?restriction rdf:type owl:Restriction .
  ?restriction ?p ?o .
}

Result:
+--------------------+---------------------+---------------------+
|      topping       |          p          |          o          |
+--------------------+---------------------+---------------------+
|  pizza:FishTopping |  rdf:type           |  owl:Restriction    |
|  pizza:FishTopping |  owl:onProperty     |  pizza:hasSpiciness |
|  pizza:FishTopping |  owl:someValuesFrom |  pizza:Mild         |
|  pizza:NutTopping  |  rdf:type           |  owl:Restriction    |
|  pizza:NutTopping  |  owl:onProperty     |  pizza:hasSpiciness |
|  pizza:NutTopping  |  owl:someValuesFrom |  pizza:Mild         |
+--------------------+---------------------+---------------------+

So what's the problem here? Next step would be to go the other way around, i.e. we check for everything that is related to hot spiciness:
PREFIX pizza: <http://www.co-ode.org/ontologies/pizza/pizza.owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>

SELECT DISTINCT ?s WHERE {
  ?s rdfs:subClassOf ?restriction .
  ?restriction owl:onProperty pizza:hasSpiciness .
  ?restriction owl:someValuesFrom pizza:Hot .
}

Result:
+------------------------------+
|              s               |
+------------------------------+
|  pizza:HotGreenPepperTopping |
|  pizza:JalapenoPepperTopping |
|  pizza:TobascoPepperSauce    |
|  pizza:CajunSpiceTopping     |
|  pizza:HotSpicedBeefTopping  |
+------------------------------+

So, how can this be? Well, the short answer is, none of the spicy toppings is defined as instance of the class pizza:PizzaTopping, you can validate this with an additional OPTIONAL triple pattern
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX pizza: <http://www.co-ode.org/ontologies/pizza/pizza.owl#>
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX owl: <http://www.w3.org/2002/07/owl#>

SELECT distinct ?s ?type WHERE {
  ?s rdfs:subClassOf ?restriction .
  ?restriction owl:onProperty pizza:hasSpiciness .
  ?restriction owl:someValuesFrom pizza:Hot .
  OPTIONAL {?s rdf:type ?type }
}

Result:
+------------------------------+------------+
|              s               |    type    |
+------------------------------+------------+
|  pizza:HotGreenPepperTopping |  owl:Class |
|  pizza:JalapenoPepperTopping |  owl:Class |
|  pizza:TobascoPepperSauce    |  owl:Class |
|  pizza:CajunSpiceTopping     |  owl:Class |
|  pizza:HotSpicedBeefTopping  |  owl:Class |
+------------------------------+------------+

A: I think you just have to select ALL subclasses of Pizza Topping, then you're query should work properly :
SELECT ?targetPizza
WHERE {
?targetPizza rdfs:subClassOf* pizza:PizzaTopping .
?targetPizza rdfs:subClassOf ?restriction .
?restriction owl:onProperty pizza:hasSpiciness .
?restriction owl:someValuesFrom pizza:Hot .

}

A: SELECT ?targetPizza
WHERE {
?targetPizza rdfs:subClassOf pizza:PizzaTopping .
?targetPizza rdfs:subClassOf ?restriction .
?restriction owl:onProperty pizza:hasSpiciness .
?restriction owl:someValuesFrom pizza:Hot .

}


text:
Q: Why isn't Powershell clearing? So, I'm having an issue getting my function to produce it's own data after the second time I run it. The first time I produce the GetUsers command, provided my username and password is right, it'll return an arraylist with my users. If I run it again, no matter what username or password I use, it'll return the same users. I'm sure my code is quite the mess, but I've been messing with it trying to get it to clear.
As for a little background, I consider myself a novice programmer so the problem very well could be something really basic.
Thanks!
 public ArrayList GetUsers(string user, string pass)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();

            iss.ImportPSModule(new[] { "MSOnline" });
            using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss))
            {
              myRunSpace.Open();
              using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
              {
                  ArrayList available_users = new ArrayList();

                  //create Powershell runspace

                  powershell.Runspace = myRunSpace;

                  Command connect = new Command("Connect-MsolService");
                  System.Security.SecureString secureString = new System.Security.SecureString();
                  string myPassword = pass;
                  foreach (char c in myPassword)
                      secureString.AppendChar(c);

                  connect.Parameters.Add("Credential", new PSCredential(user, secureString));
                  powershell.Commands.AddCommand(connect);

                  Collection<PSObject> results = null;
                  results = powershell.Invoke();
                  powershell.Commands.Clear();

                  Command getuser = new Command("Get-MsolUser");
                  powershell.Commands.AddCommand(getuser);
                  results = null;

                  powershell.Stop();

                  results = powershell.Invoke();

                  foreach (PSObject item in results)
                  {
                      string userprincipalname = item.Properties["UserPrincipalName"].Value as string;
                      available_users.Add(userprincipalname);
                  }

                  powershell.Dispose();
                  myRunSpace.Dispose();

                  powershell.Runspace.Dispose();
                  powershell.Runspace.Close();
                  myRunSpace.Close();
                  return available_users;
              }
            }
        }

A: have you tried explicitly deleting or nulling the available_users type? I don't think it would be necessary, but...


text:
Q: improper text alignment from pytesseract Trying to extract data from pdf using pytesseract with below code. But text alignment is improper when printing/Writing data to doc.
from PIL import Image
import pytesseract
import sys
from pdf2image import convert_from_path
import os
PDF_file = "d.pdf"
pages = convert_from_path(PDF_file, 500)

image_counter = 1

for page in pages:
    filename = "page_"+str(image_counter)+".jpg"
    page.save(filename, 'JPEG')
    image_counter = image_counter + 1

files = os.listdir("JPEG_PATH")
for i in files:
  text = str(((pytesseract.image_to_string(Image.open(i),lang='eng'))))
  print(text)

Sample.PDF
Category A       2015
A1              45,908
A2              67,876
A3              9,888
                ------
Total A count    123,672

Expected:
 Category A  2015\n
 A1 45,908\n
 A2 67,876\n
 A3 9,888\n
 Total A count 123,672\n

Actual Result is something like this
Category A\n
A1\n
A2\n
A3\n
Total A count\n
2015\n
45,908\n
67,876\n
9,888\n


text:
Q: OpenLayers 6 & RollupJS recipe I am trying to create a production build of OpenLayers 6 using RollupJS.
I want to produce a minimised ES6 module from which I can import classes in my code...I don't want to mix my code with the core OL classes. From what I've seen the default OpenLayers bundler, Parcel, & other options, cannot manage this.
All worked fine with OpenLayers-5 using ol-rollup (https://github.com/openlayers/ol-rollup).
However if I update to OpenLayers-6 & RollupJS <= 1.26.0
(https://github.com/flavour/ol-rollup), then I get the following error:
(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en#error-this-is-undefined
node_modules\ol\layer\Tile.js
1: var __extends = (this && this.__extends) || (function () {
                    ^
2:     var extendStatics = function (d, b) {
3:         extendStatics = Object.setPrototypeOf ||
...and 1 other occurrence
node_modules\ol\source\XYZ.js
2:  * @module ol/source/XYZ
3:  */
4: var __extends = (this && this.__extends) || (function () {
                    ^
5:     var extendStatics = function (d, b) {
6:         extendStatics = Object.setPrototypeOf ||
...and 1 other occurrence
node_modules\ol\AssertionError.js
1: var __extends = (this && this.__extends) || (function () {
                    ^
2:     var extendStatics = function (d, b) {
3:         extendStatics = Object.setPrototypeOf ||
...and 1 other occurrence
...and 98 other files

The RollupJS website has these to say about this:
https://rollupjs.org/guide/en/#error-this-is-undefined
https://rollupjs.org/guide/en/#danger-zone
I have no idea how to use options.context or options.moduleContext to fix this.

A: The issue is caused by the class inheritance code of the TypeScript compiler, which is used to transpile OpenLayers to ES5. One option is to configure rollup with
onwarn: function(warning, superOnWarn) {
  if (warning.code === 'THIS_IS_UNDEFINED') {
    return;
  }
  superOnWarn(warning);
}

The official OpenLayers+Rollup recipe (https://github.com/openlayers/ol-rollup) has been updated with this change recently.
Another option is to import the source modules instead of the transpiled ones in your application. So e.g. instead of
import Map from 'ol/Map'

you could
import Map from 'ol/src/Map'

For more information about this issue, you can refer to https://github.com/openlayers/openlayers/issues/10245.


text:
Q: Targeting specific Micronaut WebSocket connections I'm trying to create a Kotlin service which is able to pass data from Kafka on to (specific) WebSocket connections.
For instance if data from a user passes by on Kafka, the program receives it and I want to pass it on to the right WebSocket connection if this same user is currently connected.
The basics I have are:
@KafkaListener()
@Controller
@Secured(SecurityRule.IS_ANONYMOUS)
@ServerWebSocket("/ws/{id}")
class WebSocket() {

    @OnOpen
    fun onOpen(session: WebSocketSession, id: String): Publisher<String> {
        return session.send("connection opened")
    }
}

However if in the same class I receive a Kafka message, which holds the user id I'm looking for, how can I pass this to the right WebSocket connection?
I figured maybe if I use the "/ws/{id}" from the url I could easily send it to the right id, but I can't figure out how.
The only way I know to send data to a connection is from inside the websocket annotated functions like OnOpen and OnMessage etc.
Furthermore, I've found the Micronaut WebSocketBroadcaster to be useful, but only for broadcasting of course.
And something else I'm trying to figure out is where to ensure that the id that's being connected to is also the user's actual id and not someone else's, should I implement that in the @Secured annotation?

A: For anyone interested, i did find a solution to this.
Using the Micronaut WebSocketBroadcaster you can broadcast messages, and by using the second parameter, which takes a Predicate<WebSocketSession> which defines to which WebSocketSessions it sends the message.
If you do know the specific WebSocketSession ID, you can simply use { it.id == "id" } for a predicate, as is done in example 1.
If you do need to send it to a specific user, based on some other attribute, you can assign attributes to the WebSocketSession itself by using session.attributes.put("id", id) for example in the onOpen function. The predicate you can use for this is in example 2, only thing about this is that I couldn't find a way to retreive the attributes without casting it to a map, which isn't very pretty.
class ExampleClass(val broadcaster: WebSocketBroadcaster) {
    val userId = "user_001"
    val webSocketId = "asdasdasd"

    // [1] Send message to a specific socket ID
    broadcaster.broadcast("message", { it.id == webSocketId)

    // [2] Send message to a user with specific ID or any other identifying attribute of choice
    broadcaster.broadcast("message", { it.attributes.asMap()["id"]?.equals(id) ?: false})
}


text:
Q: how to split a column into comma seperated string? Here  is sample dataframe and a is my column name.

    a   b   x
0   1   3   a
1   2   4   a
2   1   3   b
3   2   5   b
4   2   4   c

need a column unique values to be seperated in this way
required output: '1','2'

below is my code i'm getting like this
x=x1['id'].unique()
x2=','.join("\'"+str(i)+"\'" for i in x)

for this way of code
i'm getting output some thing like this
output:"'1','2'"

**2nd approach:**
x2=','.join("\'"+x1['id']+"\'"):

if i'm do this i'm getting the count of id has been increasing

i need to pass output into sql query like select * from abc where a in (x2) for that reason need output something like this
x2 -->'1','2'

i'm getting
x2--->" '1','2'"

A: Try using your first approach with f-strings to make things easier.
x2 =' ,'.join(f"'{str(i)}'" for i in x)

query = rf"""
SELECT
    *
FROM
    abc
WHERE
    a in ({x2})
"""

If you try print(query), it gives
SELECT
    *
FROM
    abc
WHERE
    a in ('1' ,'2')


text:
Q: C# Corrupt Memory Error I cant post the code (proprietary issues) but does anyone know what types of things would cause the following error in C#. It is being thrown by a VOIP client that I wrote (using counterpath api) when the call is ended by the other client. The error is:
System.AccessViolationException was unhandled
  Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
  Source="System.Windows.Forms"
  StackTrace:
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CollabAnalysisSF.Edge.GUI.Forms.Program.Main() in d:\data\beyerss\Desktop\client\GUI\ARGui\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
UPDATE:
Turns out one of the libraries we were using was sending off an event that we didnt know about, and the problem was in there somewhere. Fixed now.

A: List of some possibilities:

*

*An object is being used after it has been disposed. This can happen a lot if you are disposing managed object in a finalizer (you should not do that).

*An unmannaged implementation of one of the object you are using is bugged and it corrupted the process memory heap. Happens a lot with DirectX, GDI and others.

*Mashaling on managed-unmanaged boundary is flawed. Make sure you pin a managed pointer before you use it on an unmanaged part of code.

*You are using unsafe block and doing funny stuff with it.

In you case it could be a problem with Windows Forms. But the problem is not that it is happening, but rather that it is not being reported correctly; you possibly still have done something wrong.
Are you able to determine what control is causing the error using the HWND? Is it always the same? Is this control doing something funny just before the application crashes? Is the unmannaged part of the control a custom window or a standard control?

A: This kind of prolem can occur if you are calling unmanaged code e.g. a dll. It can occur when Marshalling goes horribly wrong.
Can you tell us if you are calling unmanaged code? If so are you using default Marshalling or more specific stuff? From the looks of the stack trace are you using unsafe code e.g. Pointers and the like? This could be your problem.

A: Here is a more detailed stacktrace. It looks to me like it has something to do with the System.Windows.Form.dll
the TargetSite is listed as {IntPtr DispatchMessageW(MSG ByRef)}
and under module it has System.windows.forms.dll


text:
Q: counterexample for a DC critical point that is not a limiting-stationary point? Let $f$ be a DC function defined by $f = g - h$ where $g$ and $h$ are proper, lower semicontinuous and convex functions from $\mathbb{R}^n$ to $\mathbb{R}\cup\{+\infty\}$. A point $x^*$ is called a DC (Difference-of-convex) critical point if $0\in \partial g(x^*)- \partial h(x^*)$, where $\partial$ stands for the classical subdifferential of convex functions defined by
$$\partial g(x^*) := \left\{ y\in \mathbb{R}^n: g(z) \geq g(x^*) + \langle y, z-x^* \rangle, \forall z\in \mathbb{R}^n \right\}.$$ A point $x^*$ is called a limiting-stationary point if $0\in \partial^{\text{lim}} f(x^*)$ where the limiting-subdifferential is defined by
$$\partial^{\text{lim}} f (x^*) : = \left\{ y\in \mathbb{R}^n: \liminf_{z\to x^*, z\neq x^*} \frac{f(z) - f(x^*) - \langle y, z-x^* \rangle}{\|z-x^*\|}\geq 0 \right\}.$$
I wondered is there any counterexample such that a DC critical point is not a limiting-stationary point?

A: I think there is a simple but convincing example:
Consider $$g(x)=\max\{0,x\} + \chi_{\{x\geq -1\}}(x), \quad h(x)=\max\{0,-x\} $$
where $\chi_{\{x\geq -1\}}$ is the indicator function of the convex set $\{x\in \mathbb{R}: x\geq -1\}$. Hence, both $g$ and $h$ are proper, lower semicontinuous and convex functions from $\mathbb{R}$ to $\mathbb{R}\cup \{+\infty\}$.
Now, consider the point $x^*=0$. We can show that $x^*$ is a DC critical point but not a limiting-stationary point.
$$\partial g(0)=[0,1], \quad \partial h(0) = [-1,0], \quad \partial^{\text{lim}}f(0) = \{1\}.$$
Hence,
$$0\in \partial g(0) - \partial h(0) = [0,2]$$
but
$$0\notin \partial^{\text{lim}}f(0).$$


text:
Q: How to child a Plane? I have a plane:
 let = new THREE.Plane(new THREE.Vector3(0, 1, 0));

I want to rotate the plane based on a parent object's movement. It doesn't seem like I can do:
parentObj.add(plane);

so what's the next simplest method of achieving this? Would be great if I didn't have to manually set its position. I need to use Plane specifically for its clippingPlanes feature.
I guess I could create an Object3d mesh as a "plane", make it a child of parentObj, then set the Plane to the Object3d's position every update? Is there a less convoluted method I'm missing?

A:
It doesn't seem like I can do: parentObj.add(plane);

No, that's not possible. An instance of THREE.Plane is a pure mathematical representation of a plane. Hence, it is not derived from THREE.Object3D and thus can't be part of the scene graph.
That means you have to compute the plane per animation step (considering it is not static but moves around in 3D space).
three.js R110


text:
Q: Missing bottom and right edge on text fields I am using tkinter to build a very simple UI and I am using some text fields but they seem to miss the bottom and the right hand edging\bevel (unsure of the correct term).
There does appear to be ample space for the widget to render, I am posting here to see if this expected behaviour or a common\easily addressable issue.
I am using a grid layout and placing the widgets into the page like so:
runway_data_label.grid(row=3, column=0, sticky="w")
runway_data_text = tk.Text(load_frame, height=1, width=50, bg="light grey")
runway_data_text.grid(row=3, column=1, sticky="w")
runway_data_text.config(state=tk.DISABLED)

Here is a screen shot which shows what I am talking about. Some widgets have a grey background and some white, but the effect is apparent with both, regardless of the size I give the widget, I have underlined in blue where the effect is most obvious.

Here is a minimal reproducible example, where you can see there is a missing bottom and right edge to the text field:
root = tk.Tk()
root.resizable(False,False)
root.title("Test")
root.geometry("600x600")

tab_control = ttk.Notebook(root)
tab_control.pack(expand = 1, fill ="both")

style = ttk.Style()
style.theme_use("default")
style.configure("TFrame", background="white")
style.configure("TLabel", background="white", font=("URW Gothic L", "10", "bold"))
style.configure("TButton", font=("URW Gothic L", "10", "bold"))
style.configure("TNotebook.Tab", background="grey", font=("URW Gothic L","10"))
style.map("TNotebook.Tab", background=[("selected", "white")], font=[("selected", "bold")])

load_tab = ttk.Frame(tab_control)
load_frame = ttk.Frame(load_tab, padding=(8,8,12,12))
airport_data_label = ttk.Label(load_frame, text="Data", width=15, anchor="w")
airport_data_label.grid(row=1, column=0, sticky="w")
airport_data_text = tk.Text(load_frame, height=1, width=50, bg="light grey")
airport_data_text.grid(row=1, column=1, sticky="w")
airport_data_text.config(state=tk.DISABLED)
airport_data_btn = tk.Button(load_frame, text="Open", command=lambda: print("Hello")).grid(row=1, column=2, sticky="w")
load_frame.pack()

tab_control.add(load_tab, text="Load Data")

root.mainloop()

Here is a screen shot from the MRE:

A: After observing all the reliefs carefully, I realised that some of them (raised, sunken, ridge, groove) give a 3D appearance to the border by adding shadows to some edges. This gives the illusion that some edges are missing.
On the other hand, solid adds a uniform 2D border and flat adds a flat border that has the same colour as the background colour of the widget.

Solution:
If you want all the edges to be visible, you can use the solid relief. Also, you can change the border thickness by changing the value of bd.
airport_data_text = tk.Text(load_frame, height=1, width=50, bg="light grey", relief = "solid", bd = 1)


text:
Q: Как в базе aspnet_Users сбросить пароль? Как в базе где есть таблицы aspnet_Users , aspnet_Application сбросить пароль? Или как получить значение пароля? В процедуре сброса aspnet_Membership_ResetPassword есть параметры пароль (не знаю шифрованый или нет), соль, поэтому не очевидно как её задействовать. Если есть доступ к этой базе - как оживить авторизацию?
И последнее, как эта система называется (если можно)?
Из имен вижу слова SqlMembershipProvider и SqlProfileProvider.


text:
Q: I cannot run pyinstaller on my computer even though I have installed it This is the problem right here, do you have any advice for that?

installed pip and pyinstaller, but still got this error message when I tried to convert my project into an .exe.

A: From Pyinstaller installation guide:

If you cannot use the pyinstaller command due to the scripts directory not being in PATH, you can instead invoke the PyInstaller module, by running python -m PyInstaller (pay attention to the module name, which is case sensitive). This form of invocation is also useful when you have PyInstaller installed in multiple python environments, and you cannot be sure from which installation the pyinstaller command will be ran.

So you may run it as e.g.:
python -m PyInstaller some_system.py

Or, as the issue seems that PATH Windows environment variable doesn't include Python's Script folder, it'd better to fix it. From the same guide:

If the command is not found, make sure the execution path includes the proper directory:
Windows: C:\PythonXY\Scripts where XY stands for the major and minor Python version number, for example C:\Python38\Scripts for Python 3.8)

To fix you may run where python to get exact location of Python on your machine (let's say it shows C:\Python38\). Then add to PATH env variable Scripts folder inside it (in this example it'd be C:\Python38\Scripts\)


text:
Q: SQL: Get list of non-coupled items using MySQL 4 I'm not that good in SQL and I've come across a problem I don't know how to solve. I've read and re-read parts of a book about SQL (O'Reilly's Learning SQL) which I hoped would contain the information I needed but I haven't found it.
My problem is the following. I'll use a simplified example to make it easier to discuss.
I've got three tables, car, rim and the combination of the two: carRim.
car
    carId
    description

rim
    rimId
    description

carRim
    carRimId
    carId
    rimId
    price

In the table carRim I have an extra attribute of price, because the price of a rim is potentially different for every type of car. A constraint I have is that every type of rim should only be coupled once to every type of car. So all combinations of car-rim should be unique.
If I want to add a rim to a car I need a list of rims that are not yet coupled to that car. For this I think I need the rim table and the carRim table respectively for the total list of rims and the list of carRims that are already coupled to the car I want to add a rim to.
I've written the (simple) query to make the list of rims that are coupled to a specific car, in the following example the car with carId 9.
SELECT
    *
FROM
    rims
INNER JOIN
    carRims
ON
    carRims.rimId = rim.rimId
WHERE
    carRims.carId = 9

But now I need the list of rims that are not yet coupled to a specific car. The problem is that if I do a LEFT OUTER JOIN the list I get is "tainted" with couplings of rims to other cars, so the filter condition of "WHERE carRims.carId IS NULL" does not work.
SELECT
    *
FROM
    rims
LEFT OUTER JOIN
    carRims
ON
    carRims.rimId = rim.rimId
WHERE
    carRims.carId IS NULL

Another challenge is that I can't use any syntax new to MySQL 5, like subqueries, because my client is using MySQL 4 and can't upgrade at this time.
Can a query for this problem be written in MySQL 4, I suspect it can.
Thanks!

A: SELECT  *
FROM    rims r
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    carRims cr
        WHERE   cr.rimId = r.RimId
                AND cr.carID = 9
        )

Update:
To rewrite the NOT EXISTS into a LEFT JOIN / IS NULL, you'll need to put all conditions into the ON clause of the join:
SELECT  r.*
FROM    rims r
LEFT OUTER JOIN
        carRims cr
ON      cr.rimId = r.rimId
        AND cr.crID = 9
WHERE   cr.carId IS NULL

A: You can put extra conditions in a left outer join ON expression.  What you want is a row from carRims that matches your rims row, and belongs to car number 9, right?
SELECT
    *
FROM
    rims
LEFT OUTER JOIN
    carRims
ON
    carRims.rimId = rim.rimId
    AND carRims.carId = 9
WHERE
    carRims.carId IS NULL

If there are other carRims for other cars, they'll be filtered out by the extra condition in the ON clause.

Re your questions about where to put a condition, in the JOIN or in the WHERE clause:
For outer joins, it matters where you put the comparison.  The condition in a JOIN clause is for testing whether rows in one table match rows in the other table.  What we do with the rows from the respective tables after we test the match depends on the type of join.
For an outer join, we want rows from rims even if there's no matching row in carRims.  What if we were to put the carID=9 condition in the WHERE clause?
FROM rims r LEFT OUTER JOIN carRims c ON r.rimId = c.rimID
WHERE c.carID = 9

Here's what happens: the outer join returns all rows from rims, with rows from carRims that match the rimID and includes the rows with spurious carID values.  Only if none of the cars match a given rim does it use NULL for the c.* columns.
But then the WHERE clause eliminates all the rows resulting from the join, unless carID is the value 9.  That means it also eliminates where carID is NULL, that is it eliminates rows for any rim matches none of the cars.  Therefore the result becomes equivalent to the result of an INNER JOIN.
So we need to exclude rows from carRims with the wrong carID before the rows are joined to rims.
FROM rims r LEFT OUTER JOIN carRims c ON r.rimId = c.rimID AND c.carID = 9

It's a condition on what rows from that individual table can match rows in the other joined table.
Many books say you can freely mix conditions between the ON clause and the WHERE clause.  But this isn't true in all cases.  It works for INNER JOIN, because the end result is the same either way.  It also works for a condition that applies only to the left table in a left join, for example:
FROM rims r LEFT OUTER JOIN carRims c ON r.rimId = c.rimID AND r.make = 'ABC Rims'

FROM rims r LEFT OUTER JOIN carRims c ON r.rimId = c.rimID
WHERE r.make = 'ABC Rims'

For a condition on the right table in a left outer join, it does matter where you put the condition.

One more comment on something you said:

A constraint I have is that every type of rim should only be coupled once to every type of car. So all combinations of car-rim should be unique.

So have you declared a UNIQUE constraint on carRims(carId,rimId)?

A: (I needed some more room to elaborate, a comment did not have enough characters)
@Bill Karwin
The query you've provided is the correct answer to my problem. Thanks!
What I wanted was a list of rows (rims) that are not connected to a specific car.
In the "Learning SQL" book I read that the location of filter and join conditions in the query did not matter. They gave an example of an inner join where there was 1 join condition (after the ON clause) and 1 filter condition (after the WHERE clause). They demonstrated that whether you put those two conditions after the ON clause or after the WHERE clause effectively did not matter.
With that in mind I don't understand a part of your solution. If the condition
carRims.carId = 9

and the condition
carRims.carId IS NULL

are both present, doesn't that result in an empty resultset? Because no field can be 9 and NULL simultaneously right?
My suspicion then is: the conditions in the JOIN clause are location-bound, and you can't just put them in the WHERE clause.
Is this correct?


text:
Q: Pandas : Merge in loop does not work, but works on each table separately? I had to slice the table I'm working on in pieces, because it was to heavy for Pandas and I'm using a loop to apply my treatments on each piece, using a dictionnary. It's been working fine, until I had to apply a merge on each piece, using the same DataFrame for the left :
for piece, df in d.iteritems():
   df = pd.merge(df,table_left, on='column', how='inner')

It doesn't raise any error, but the columns of my left table are not added.
Weird thing is, when I use the same code on one of my tables, out of the loop, it works fine...
Any idea of what I'm missing there anyone?

A: Currently, you are only changing the iterated value in your for loop as df is a local object in loop. By re-assigning that iterated value, the merge only remains in that state during the current iteration. You do not re-assign the value's source, namely the dictionary, d.
Consider updating the dictionary element inside for loop by explicitly referring the dictionary:
for piece, df in d.iteritems():
   d[piece] = pd.merge(df, table_left, on='column', how='inner')

Alternatively, try a dictionary comprehension:
new_dict = {piece: pd.merge(df, table_left, on='column', how='inner') for piece, df in d.iteritems()}


text:
Q: Python 3: how to filter list of packages? How do I filter this list to show only items that match a substring? The following code shows an ordered list of Python packages installed for a Jupyter notebook.
import pkg_resources

dists = [d for d in pkg_resources.working_set]
# Filter out distributions you don't care about and use.
dists.reverse()
dists

I tried:
list(filter(lambda k: "fsspec" in k, dists))

but get the error:
TypeError: argument of type 'Distribution' is not iterable

I tried copying the pattern of the solution here: Filtering a list of strings based on contents

A: You are trying to filter a class object with filter. Either you want to convert it to string or change the filter method accordingly. For this usecase, the below code should work fine.
import pkg_resources

dists = [d.project_name for d in pkg_resources.working_set]
# Filter out distributions you don't care about and use.
dists.reverse()
lst = list(filter(lambda k: "fsspec" in k, dists))
print(lst)

Generally to debug type errors, try to get the type of the variable you're working with using type() and if it is a class you can use the __dict__ attribute to print out its properties for a better perspective on what you need to do.


text:
Q: Email Formular in Wordpress footer i allready serched but didnt find an answer to my problem. I have to make a wordpress site. I usually just write my sites with html, php, js,... but for that project i need wordpress so i started learning how it works and how to make my own theme. Everything worked perfectly out but now i want to intigrate a Contact formular in my footer. I usually would do that with PHP sending an Email to the admin adress whe somebody fills out a form. But taht just doesnt seem to work out.
Does somebody has an idee how to code it in a wordpress theme?
Best regard
Paul
BTW im not a nativ english speaker please dont criticise it too hard;)

A: You must first make sure that sending email is allowed on your server.
Then you can use wp_mail() function in order to send messages.
Example:
$to = 'sendto@example.com';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');

wp_mail( $to, $subject, $body, $headers );


text:
Q: IRepository vs ISession I have some Repository. Work with them is realized through an interface IRepository.
In sample project HomeController constructor realized with ISession. When I wrote this:
public class TestingController : Controller
{
    private ISession session;

    public TestingController(ISession session)
    {
        this.session = session;
    }
//Some code here with this.session
}

It working well. When I decided to use IRepository:
public class TestingController : Controller
{
    private IRepository repository;

    public TestingController(IRepository repository)
    {
        this.repository = repository;
    }
//Some code here with this.repository
}

It doesn't work in this method of other class WindsorControllerFactory:
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null)
        {
            throw new HttpException(404, string.Format("The controller for path {0} culd not found!", requestContext.HttpContext.Request.Path));
        }

        return (IController)this.kernel.Resolve(controllerType);
    }

I have exception

Can't create component 'MvcApplication1.Controllers.ResultsController' as it has dependencies to be satisfied.
'MvcApplication1.Controllers.ResultsController' is waiting for the
  following dependencies:
  - Service 'dal.Repository.IRepository' which was not registered.

How to solve it?
P.S. Assembly dal.Repository is working. If I write everywhere new dal.Repository.Repository() instead of this.repository - it working.

A: It looks like you missing the binding for IRepository.
You have to have concrete class that would implement IRepository interface, say MyRepository. Then you should configure Windsor, to understand what the IRepository is about.
Something like,
container.Register(Component.For<IRepository>().ImplementedBy<MyRepository>());

A: I able to resolve the same issue by following this Documentation
and another thing is if we download new version for this project from github we will not see this expcetion Link


text:
Q: Task is running on only one executor in spark I am running below code in spark using Java.
Code
Test.java
package com.sample;

import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.functions;
import org.apache.spark.storage.StorageLevel;

import com.addition.AddTwoNumbers;

public class Test{

    private static final String APP_NAME = "Test";
    private static final String LOCAL = "local";
    private static final String MASTER_IP = "spark://10.180.181.26:7077";

    public static void main(String[] args) {

        SparkConf conf = new SparkConf().setAppName(APP_NAME).setMaster(MASTER_IP);
        String connection = "jdbc:oracle:thin:test/test@//xyz00aie.in.oracle.com:1521/PDX2600N";
        // Create Spark Context
        SparkContext context = new SparkContext(conf);
        // Create Spark Session

        SparkSession sparkSession = new SparkSession(context);
        long startTime = System.currentTimeMillis();
        System.out.println("Start time is : " + startTime);
        Dataset<Row> txnDf = sparkSession.read().format("jdbc").option("url", connection)
                .option("dbtable", "CI_TXN_DETAIL_STG_100M").load();

        System.out.println(txnDf.filter((txnDf.col("TXN_DETAIL_ID").gt(new Integer(1286001510)))
                .and(txnDf.col("TXN_DETAIL_ID").lt(new Integer(1303001510)))).count());

        sparkSession.stop();
    }

}

I am simply trying to find count of range of rows. Range is 20 Million.
Below is snapshot of spark dashboard

Here I can see  Active task only on one Executor.
I have total of 10 Executors running.
My question
Why my application is showing active task on one Executor instead of distributing it across all 10 executors?
Below is my spark-submit command :
./spark-submit --class com.sample.Test--conf spark.sql.shuffle.partitions=5001 --conf spark.yarn.executor.memoryOverhead=11264 --executor-memory=91GB --conf spark.yarn.driver.memoryOverhead=11264 --driver-memory=91G --executor-cores=17  --driver-cores=17 --conf spark.default.parallelism=306 --jars /scratch/rmbbuild/spark_ormb/drools-jars/ojdbc6.jar,/scratch/rmbbuild/spark_ormb/drools-jars/Addition-1.0.jar --driver-class-path /scratch/rmbbuild/spark_ormb/drools-jars/ojdbc6.jar --master spark://10.180.181.26:7077 "/scratch/rmbbuild/spark_ormb/POC-jar/Test-0.0.1-SNAPSHOT.jar" > /scratch/rmbbuild/spark_ormb/POC-jar/logs/log18.txt

A: Looks like all data are read in one partition, and goes to one executor.
For use more executors, more partitions have to be created.
Parameter "numPartitions" can be used, along with partition column, as specified here:
https://docs.databricks.com/spark/latest/data-sources/sql-databases.html#jdbc-reads
Also this link can be useful:
Spark: Difference between numPartitions in read.jdbc(..numPartitions..) and repartition(..numPartitions..)


text:
Q: How to get 1 row from every group sql My current query from a table is giving me something like this
C1 | C2 | C3 | C4
xx | cc | ff | i1
xx | dd | kk | i2
yy | oo | tt | i3
zz | uu | ll | i4
zz | jj | ee | i5

All the 'i's are integers
I am grouping by C1, C2, C3
I want to to get only one row for every distinct C1 value corresponding to highest C4 value
Whats the best way to do this?

A: For this, you want analytic functions.  The function row_number() does what you want:
select c1, c2, c3, c4
from (select t.*, row_number() over (partition by c1 order by c4 desc) as seqnum
      from t
     ) t
where seqnum = 1

A: Quite simple with co-related subqs:
select C1,C2,C3,C4 from table tb where c4 in
(select max(C4) from table where C1=tb.C1 )

Edit:
After Conrad's comment, for the following set of data:
c1      c2      c3      c4
 1      2        3       4
 1      3        4       4

This query will return both rows.
I am still not sure if it is required or not, for me it looks like we should return 2 rows for this data, as we are not able to distinguish between two and both rows are fulfilling the requirements.
It's something like we want to know in which subject a student got highest marks. If he got 92 both in Maths and English, we should return both rows.


text:
Q: How to display data value according to dropdown in laravel? I have a table in my database which has a field lis_type and the field has 2 values: sale and rent, and I am calling data on my view page. Let's suppose I click on the Sale page, there only sale similar listing should be displayed. If I click on Rent then similar listing should be shown for rent. However, right now both listings are coming together, Please let me guide where I am making a mistake.
Controller
public function listingshownow(Request $r, $slug)
{
    $listview = Listing::where('slug', $slug)->first();
    $products = Listing::where('propId', $listview->propId)
        ->where(function ($query) {
            $query->where('lis_type', '=', 'sale')->orWhere('lis_type', '=', 'rent');
        })->get();

    return view('listings-view', compact('products'));
}

View for Similar Listings...
@foreach($products as $prod)
    @if($prod->lis_type === 'sale')

                        {{$prod->ls_fs}}

                        {{$prod->bathroom}} Bathroom

    @endif
@endforeach

A: You need to pass a variable to your controller to indicate what kind of page you are viewing, so you can use that in your query/filter.
For example, let's say your sales page URL looks like http://example.com/listings/sales.  Then you could set up a route like:
Route::get('listings/{type}', 'ListingsController@show');

Now your ListingsController could have a method like:
// The $type parameter will be what was matched in the route
public function show($type) {
    $listings = Listings::where('lis_type', $type)->get();
    return view('listings-view', ['listings' => $listings]);
}

You might want to check that $type only matches the values you expect.  You could either do that in the controller, eg:
// At the top of show()
if ($type !== 'sales' && $type !== 'rent') {
    abort(404);
}

Or you could restrict it in your route, by specifying that the {type} there has to match some pattern:
Route::get('listings/{type}', 'ListingsController@show')->where('type', 'sales|rent');

All of this is covered in the Laravel routing docs, I suggest reading them, and better yet, take some minutes and browse all the docs! 30min skimming will give you a broad idea of how things work, and the knowledge of where to look and read more when you need a question answered.


text:
Q: Why is this function not returning the correct value? I've made a function that converts an integer input into another integer, which it returns. Specifically, it takes in a console color, and returns a corresponding color which has the same background as the input, but with a white character.
This function always returns 255. What's going wrong?
int convertColorToPlayerColor(int color)
{
    int playerColor = 0;

    if (color <= 15)
        playerColor = 15;

    else if ((color > 15) && (color <= 31))
        playerColor = 31;

    else if ((color > 31) && (color <= 47))
        playerColor = 47;

    else if ((color > 47) && (color <= 63))
        playerColor = 63;

    else if ((color > 63) && (color <= 79))
        playerColor = 79;

    else if ((color > 79) && (color <= 95))
        playerColor = 95;

    else if ((color > 95) && (color <= 111))
        playerColor = 111;

    else if ((color > 111) && (color <= 127))
        playerColor = 127;

    else if ((color > 127) && (color <= 143))
        playerColor = 159;

    else if ((color > 159) && (color <= 175))
        playerColor = 175;

    else if ((color > 175) && (color <= 191))
        playerColor = 191;

    else if ((color > 191) && (color <= 207))
        playerColor = 207;

    else if ((color > 207) && (color <= 223))
        playerColor = 223;

    else if ((color > 223) && (color <= 239))
        playerColor = 239;

    else if (color > 239);
        playerColor = 255;

    return playerColor;
}

A: You have an extra semicolon:
else if (color > 239);    // <--- the semicolon

The extra semicolon gets parsed as the "then" part of an empty if statement. This effectively turns your function into
[ a long-winded if-else statement ]

playerColor = 255;

return playerColor;

A: Aside that you have extra semicolon, you can make your function way simpler using return inside if and removing redundant checks:
   if (color <= 15)
      return 15;

   if (color <= 31) // no need to check color > 15
      return 31;

   if (color <= 47) // no need to check color > 31
      return 47;
   ...
   return 255; // no need for if (color > 239)

Also you can do binary lookup instead of linear check:
int convertColorToPlayerColor(int color)
{
     static std::vector<int> v { 15, 31, 47, 63, 79, 95, 111, 127, 143, 175, 191, 207, 223, 239 };
     auto it = std::lower_bound( v.begin(), v.end(), color );
     return it == v.end() ? 255 : *it;
}

this will not only make it more effective and shorter, but make it less error prone (as you do not have to repeat numbers more than once). Just keep in mind that values in vector have to be in sorted order.


text:
Q: Getting average of distinct list values I have 4k values in list created from first col of this dataset (link):
11 1
19 1
42 2
16 1
63 3
14 1
11 1
83 4
63 3
11 1
13 1
17 1
92 4
11 2
86 2

and so on
I want to convert first column in distinct list along with average value of it's corresonding 2nd value.
Approach 1: looping through last line and checking condition if similar value then increment count and add value in 2nd col. At the end divide by count
Apprach 2: convert col1 into list
col1 = list(set(col1)) which will give distinct values for col1 but how do I get average of 2nd col for each distinct value in first col?

A: Alternatively, supposed you have Pandas installed, it will be a straight forward groupby with mean, like this:
import pandas as pd
import io

s = '''11 1
19 1
42 2
16 1
63 3
14 1
11 1
83 4
63 3
11 1
13 1
17 1
92 4
11 2
86 2 '''
# using your sample data
df = pd.read_table(io.StringIO(s), header=None, sep=' ')

df
Out[5]:
     0  1
0   11  1
1   19  1
2   42  2
3   16  1
4   63  3
5   14  1
6   11  1
7   83  4
8   63  3
9   11  1
10  13  1
11  17  1
12  92  4
13  11  2
14  86  2

Using groupby to group the column 0 which is the first-column values, and they will be distinct, then mean will apply to column 1 to calculate their relative average values:
df.groupby(0).mean()
Out[6]:
       1
0
11  1.25
13  1.00
14  1.00
16  1.00
17  1.00
19  1.00
42  2.00
63  3.00
83  4.00
86  2.00
92  4.00

As a side note: Pandas read_table(), read_csv() etc etc. can read from both file path and file buffer. My sample above is merely using an in-memory buffer.

A: I suggest building a defaultdict() using the first-column value as the key, and a list of values from the second column.  Then loop over your defaultdict and compute the average values.
Like this:
from collections import defaultdict

d = defaultdict(list)

with open('data.txt') as f:
    for line in f:
        key, value = (int(x) for x in line.split())
        d[key].append(value)

def mean(lst):
    if not lst: return 0
    return float(sum(lst)) / len(lst)

mean_values = {key: mean(lst) for key, lst in d.iteritems()}


text:
Q: How to reference multiple values in a Python dict? From this question:
>>> t_list = [('a', 10, 98), ('b', 234, 65), ('c', 459, 5)]
>>> t_dict = {a:{b:c} for a,b,c in t_list}
>>> t_dict
{'a': {10: 98}, 'c': {459: 5}, 'b': {234: 65}}

And I can call values based on the first element such as:
>>> t_dict['a']
{10: 98}

But how would I access individual values based on the key? Such as 10 or 98. I am expecting something like this: t_dict['a'][0]. I have tried using split() and slicing it but no luck.

A: Use this instead:
t_dict = {a:[b,c] for a,b,c in t_list}

Since you wanted to save b and c as a list.

A: The generic solution would be this one:
t_dict = {t[0]: t[1:] for t in t_list}

And if you consider the particular case you'd have:
t_dict = {t[0]:t[1:3] for t in t_list}


text:
Q: Kendo-Ui angular 2 grid control with check boxes for first column how to add check box for first column of kendo UI angular2 grid? and how to retrive if the data is checked or not for each row?

A: finally found answer to this quesion.
add following code to grid template.
<kendo-grid-column field="Select" width="50">
                            <template kendoCellTemplate kendoHeaderTemplate let-dataItem>
                                <input type="checkbox" />
                            </template>
                        </kendo-grid-column>


text:
Q: Disallow ec2 ssh key-pair login but allow a special ssh key to login I have a use case that my product image only allow a specific ssh keypair (not distribute to customer, only support team has the keypair) to ssh to a VM.
The AMI image is built by packer. Is it possible to ignore the ssh keypair specific during the EC2 creation page but only allow a specific ssh keypair to login?
The reason is that we don't want user to login to the VM and change the configuration; Only support team can ssh into the VM during troubleshooting.

A: Set ssh_redirect_user to true in cloud-init and build in your authized key. This should disable the loading of authorized keys from EC2 meta data.
See https://cloudinit.readthedocs.io/en/latest/topics/modules.html#users-and-groups


text:
Q: Does an EF6 DbContext rollback open transactions when it is disposed? If I dispose an EF6 DbContext and there is a transaction on it that is still open (i.e. not committed, not rolled back), what happens to the transaction? Is it rolled back immediately or does it remain open until the transaction object eventually gets disposed?
EDIT: Or is the behaviour provider-dependent?
Sample code:
  using (var dbContext = MagicallyCreateDbContext())
  {
    DbContextTransaction dbTransaction = dbContext.Database.BeginTransaction();

    // do stuff ...

    // What happens if we don't invoke this?
    // dbTransaction.Commit();
  }


text:
Q: Facebook Deep Linking not working on Android I am trying to implement Facebook deep linking feature according to https://developers.facebook.com/docs/app-ads/deep-linking.
I have followed step by step instructions:

*

*Created FB app

*Added FB sdk (4.13.2) to Android app

When I run the app, it is detected by Facebook, verified on the https://developers.facebook.com/tools/app-ads-helper/

I also created an Activity to handle deep links. AndroidManifest configuration:
    <activity android:name=".DeeplinkActivity">
        <intent-filter>
            <data
                android:host="deeplink.com"
                android:pathPrefix="/openapp"
                android:scheme="deep" />
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
    </activity>

DeeplinkActivity opens if started from adb via:
adb shell am start -W -a android.intent.action.VIEW -d "deep://deeplink.com/openapp" com.example.rps

This is Android configuration under Facebook app settings:

Please note that fully qualified Class Name (com.example.rps.DeeplinkActivity) is also not working.
I tried testing deep links via Deeplink Tester, on the App Ads Helper page (link above)

I receive notification on my phone from Facebook app, saying "Tap to launch your deep link", but nothing happens, my app is never started.
What am I missing?

A: When you receive notification on your phone from Facebook app, saying "Tap to launch your deep link" you have to open Facebook app on the "notifications" tab and click on the received notification THERE, that will start your app (if it's installed, that is).
If you just click on the notification in the action bar nothing will happen. Confusing I know, since it blatantly states "Tap to launch your deep link".


text:
Q: Is it possible to start the various iot-edge modules one by one sequentially? If so, how to do it? Is it possible to start the various iot-edge modules one by one sequentially? If so, how to do it?

A: Currently, there is no support for starting various modules sequentially in Iot Edge due to various module dependencies and seems to be intentionally done to bring in resiliency. The sequencing may not be of help if any other module your module depends on crashes or is updated. In such cases The IoT Hub SDK will retry operations for you, and you should be able to adjust it's timeouts.
Here is one good reference https://github.com/Azure/iotedge/issues/1105


text:
Q: Passing extra arguments with Tkinter Bindings I'm trying to bind an extra argument opt to the following radiobuttons below. I'm trying to make it so that when WSRB_UD is triggered I can know which radiobutton triggered it. How do I go about this?
Snippet:
        self.WS.SW.SearchFrame = []
        self.WS.SW.SearchRB = []

        self.WS.RBvar  = Tkinter.IntVar()

        i = 0
        while i < 6 :

            Frame = Tkinter.Frame(self.WS.SW.OptFrame, width=125, height=22, bd=1,
                                             bg=self.WSbg)
            Frame.grid(column=0, row=4 + i)
            Frame.grid_propagate(0)

            self.WS.SW.SearchFrame.append(Frame)

            RB = Tkinter.Radiobutton(self.WS.SW.SearchFrame[i], value=i,
                               variable=self.WS.RBvar, indicatoron=0, font=self.WSfo,
                               fg=self.WSfg, activeforeground=self.WSfg, bg=self.WSbg, activebackground=self.WSbg,
                               selectcolor=self.WSbg, bd=self.WSbw)
            RB.grid()
            RB.bind( "<Enter>", self.WSRB_UD, i)
            print i

            self.WS.SW.SearchRB.append(RB)

            i = i + 1

        self.QuickLinkList= []
        self.WS_timer_count = 0

    def WSRB_UD(self, event, opt):
        print self.WS.RBvar.get()

A: You can use lambda to define an anonymous partial function:
RB.bind( "<Enter>", lambda event: self.WSRB_UD(event, i) )

You could also use functools.partial if you don't like the lambda syntax.


text:
Q: T-SQL Query performance We are using SSIS package to execute the following statement.
SQL statement
delete from ABC
            OUTPUT DELETED.[ABC_Id], 5
                           into XYZ (OId, OCode)
where ([ABC_Id] = ?)

Column Types
ABC_Id: uniqueidentifier
OCode:  int
OId:    uniqueidentifier

Currently the above query is taking 2 min for 100'000 records. Can anybody provide me with any hints on how to speed up the above statement?

A: I'm assuming you have a Data Flow with 100,000 records and an OLEDB Command transform which executes that update statement. That results in 100,000 individual update statements running.
Instead use an OLEDB destination with fast load enabled to write to a stage table (some table which you have previously truncated in an Execute SQL task) to insert the 100,000 rows. Then do an Execute SQL task which does:
delete a
from ABC a
join StageTable s on s.ABC_Id = a.ABC_Id
            OUTPUT DELETED.[ABC_Id], 5
                           into XYZ (OId, OCode)

A: First advice: you can speed up query by applying index to columns in where clause, i.e. ABC_Id.
Second advice: indexes slow down deletion and insertion of rows in a table, so if you abused indexes (and defined many on one table), deletion also may be slowed down by these.
Generally, there is no obvious answer: delete ... where can be thought as steps:

*

*Find rows to delete - it can benefit from indexes

*Delete found rows - this suffer from indexes
So you can benchamrk, which step is more important to your query.
For reference: More indexes, slower DELETE, there you can read:

In theory, we would expect the best delete performance for a table without any indexes—as it is for insert. If there is no index, however, the database must read the full table to find the rows to be deleted.


text:
Q: Matlab plotyy and semilogx I need to plot two curves which share the same x axis but not the y. This can be achieved with plotyy.
However, the common x axis is to use the log scale, hence i would need to use semilogx.
I have tried the hold on, did not work.
My problem is that one can not combine plotyy with semilogx. Is there a solution to this vexing problem?

A: You can use the axes property XScale
set(gca,'XScale','log')

to change the axis scale to from 'linear' (default) to 'log'.  (The other axes work the same way).
With multiple sets of axes, you can find the handles of the children of the figure, and set this property on all of them.

A: Here's an example of how to do it:
t = 0:900; A = 1000; a = 0.005; b = 0.005;
z1 = A*exp(-a*t);
z2 = 2*A*exp(-a*t/2);
plotyy(t,z1,t,z2,'semilogx','semilogx');


text:
Q: Nuxt: Import a js depending on i18n I am currently importing a js file and processing it right with the folowwing asyncdata
async asyncData({ route, error }) {
    try {
      const entry = await import(
        `~/assets/data/portafolio/${route.params.work}.js`)
      return { entry: entry.default || entry }
    } catch (error_) {
      error({
        message: 'Not Found',
        statusCode: 404,
      })
    }
    return {}
  },

But when I try to add a language identifier to load the right file, that doesnt work.
async asyncData({ route, error }) {
    try {
      const entry = await import(
        `~/assets/data/${this.i18n.locale}/portafolio/${route.params.work}.js`)
      return { entry: entry.default || entry }
    } catch (error_) {
      error({
        message: 'Not Found',
        statusCode: 404,
      })
    }
    return {}
  },

Of course the path and files exists but I am getting an error with:
http://localhost:3000/[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object],[object%20Object] 404 (Not Found)
Any ideas on whats going wrong?
Thank you in advance!

A: I have found a solutiond and it is simple.
I was missing to add the app and then using it inside asuncData (on that context this. doesnt do anything)
async asyncData({ route, app, error }) {
    try {
      const entry = await import(
        `~/assets/data/${app.i18n.locale}/portafolio/${route.params.work}.js`)
      return { entry: entry.default || entry }
    } catch (error_) {
      error({
        message: 'Not Found',
        statusCode: 404,
      })
    }
    return {}
  },


text:
Q: How can I store different async functions in a struct? I'm trying to store different async functions in a Vec within a struct.
I've tried different things like using Box<Fn -> Future<Output = ...>>, to fall into dynamic dispatch and also wrap Output into Box<dyn>. But I get this error all the time: expected opaque type, found a different opaque type.
Here's my last tentative solution to the problem:
use futures::Future;
//use futures::prelude::TryFuture;

struct Failure<A> {
    data: A,
}

async fn add(data: u8) -> Result<u8, Failure<u8>> {
    Ok(data + 1)
}

async fn add2(data: u8) -> Result<u8, Failure<u8>> {
    Ok(data + 2)
}

struct Transaction<A, T>
where
    T: Future<Output = Result<A, Failure<A>>>,
{
    steps: Vec<Step<A, T>>,
}
struct Step<A, T>
where
    T: Future<Output = Result<A, Failure<A>>>,
{
    c: fn(A) -> T,
}

fn main() {
    Transaction {
        steps: vec![
            Step { c: add },
            Step { c: add2 }
        ],
    };
}

playground
This code fails to compile:
  --> src/main.rs:34:23
   |
34 |             Step { c: add2 }
   |                       ^^^^ expected opaque type, found a different opaque type
   |
   = note: expected fn pointer `fn(_) -> impl core::future::future::Future`
                 found fn item `fn(_) -> impl core::future::future::Future {add2}`
   = note: distinct uses of `impl Trait` result in different opaque types

How do I make it compile?


text:
Q: Using tikz-cd the labels are not centered and arrows done not come together Using tikz with tikzcd the:

*

*label on the arrow are not centered, see those that sloped.

*When arrow split ans come back together the distance between the end points are not equal.

How do you solve these?
\documentclass[preview]{standalone}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{cd}
\begin{document}

\begin{tikzcd}[column sep=large, row sep=large]
    &&\arrow[rr,"decrement"]&&
    \arrow[rd,sloped, midway,"return"]&&\\

    \text{Start}\arrow[r,"f(x)"]&
    \ \arrow[ur,"x > 0",sloped,description]\arrow[rd,"x\leq0",sloped,above]
    &&&\    &\arrow[r]&\text{End}\\

    &&\arrow[rr,"increment"]    && \arrow[sloped]{ru}{return}&&
\end{tikzcd}
\end{document}

The output is:

A: I'm not sure why, but labels on sloped arrows seem to be anchored at the arrow's center with one of their borders.
You can manually move the label along the arrow, but for this particular case there si s slicker trick, that also allows to easily avoid the wrong typesetting of labels with math italic.
\documentclass{standalone}
\usepackage{amsmath,mathtools}
\usepackage{tikz-cd}

\newcommand{\ctext}[1]{\text{\makebox[0pt]{#1}}}

\begin{document}

\begin{tikzcd}[column sep=large, row sep=large]
  && \arrow[rr,"\ctext{decrement}"]
  && \arrow[rd,sloped, midway,"\ctext{return}"]
  &&
\\
  \text{Start}\arrow[r,"f(x)"]
  & \arrow[ur,"\ctext{$x > 0$}",sloped,description]
    \arrow[rd,"\ctext{$x\leq0$}",sloped,above]
  &&&&
  \arrow[r]
  &\text{End}
\\
  && \arrow[rr,"\ctext{increment}"]
  && \arrow[ru,sloped,"\ctext{return}"]
  &&
\end{tikzcd}
\end{document}

A: \documentclass[preview]{standalone}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{cd}
\begin{document}

\begin{tikzcd}[column sep=large, row sep=large]
&&\arrow[rr,"decrement"]&& \arrow[rd,sloped, midway,"return"]&&\\
\text{Start}\arrow[r,"f(x)"]&\ \arrow[ur,sloped,description,"x > 0"near end]\arrow[rd,"x\leq0"near start,sloped,above]&&&\    &\arrow[r]&\text{End}\\
&&\arrow[rr,"increment"]    && \arrow[sloped]{ru}{return}&&
\end{tikzcd}
\end{document}

Here is the code with the modification.
    \documentclass[preview]{standalone}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{arrows}
\usetikzlibrary{cd}
\begin{document}

\begin{tikzcd}[column sep=large, row sep=large]
&&\arrow[rr,"decrement"]&& \arrow[rd,sloped, midway,"return"near start]&&\\
\text{Start}\arrow[r,"f(x)"]&\ \arrow[ur,sloped,description,"x > 0 "near end]\arrow[rd,"x\leq0"near start,sloped,above]&&&\    &\arrow[r]&\text{End}\\
&&\arrow[rr,"increment"]    && \arrow[ru,sloped, midway,"return"near end]&&
\end{tikzcd}
\end{document}


text:
Q: Typescript: Inject custom service in controller in I'm trying to create a custom service and $inject it into my controller. It seems to be a fairly basic problem, but I havn't been able to find a working solution.
HTML:
<!DOCTYPE html>
 <html lang="en" ng-app="myApp">
  <head>
<title></title>
<meta charset="utf-8" />
  </head>
   <body ng-controller="MyController as vm">
    <script src="Scripts/angular.min.js"></script>
    <link href="Content/bootstrap.min.css" rel="stylesheet" />
    <script src="app/AnimalService.js"></script>
    <script src="app/app.js"></script>
   </body>
</html>

I use the following code to create the service, i'm trying to call from the controller.
AnimalService.ts:
    module services {
    "use strict";

    export interface IAnimal {
        sound: string;
        hearMySound(): void;
    }

    class Animal implements IAnimal {
        sound: string;

        constructor() {
            this.sound = "RAWR";
        }

        hearMySound(): void {
            console.log(this.sound);
        }
    }
    angular.module("myApp")
        .service("Animal", Animal);
}

In the controller, am I trying to call the function hearMySound(), which has the string initilized by the service constructor.
app.ts
module controllers{
    class MyController {
        "use strict";

        static $inject = ["Animal"];
        constructor(animalService: services.IAnimal) {
            animalService.hearMySound();
        }

    }
    angular.module('myApp', [])
        .controller('MyController', ["Animal", MyController]);
}

Google chrome console error:
        Uncaught Error: [$injector:nomod] http://errors.angularjs.org/1.4.8/$injector/nomod?p0=myApp(anonymous function)
    @ angular.js:38(anonymous function)
    @ angular.js:2005b @ angular.js:1929(anonymous function)
    @ angular.js:2003services @ AnimalService.ts:20(anonymous function)
    @ AnimalService.ts:22
        angular.js:12520 Error: [$injector:unpr] http://errors.angularjs.org/1.4.8/$injector/unpr?p0=AnimalProvider%20%3C-%20Animal%20%3C-%20MyController
            at Error (native)
            at http://localhost:51139/Scripts/angular.min.js:6:416
            at http://localhost:51139/Scripts/angular.min.js:41:121
            at Object.d [as get] (http://localhost:51139/Scripts/angular.min.js:39:92)
            at http://localhost:51139/Scripts/angular.min.js:41:195
            at d (http://localhost:51139/Scripts/angular.min.js:39:92)
            at Object.e [as invoke] (http://localhost:51139/Scripts/angular.min.js:39:362)
            at M.instance (http://localhost:51139/Scripts/angular.min.js:80:336)
            at D (http://localhost:51139/Scripts/angular.min.js:61:362)
            at g (http://localhost:51139/Scripts/angular.min.js:55:105)(anonymous function) @ angular.js:12520(anonymous function)
@ angular.js:9292r.$apply @ angular.js:16157(anonymous function)
@ angular.js:1679e
@ angular.js:4523c
@ angular.js:1677yc
@ angular.js:1697Zd
@ angular.js:1591(anonymous function)
@ angular.js:29013b
@ angular.js:3057If
@ angular.js:3346Hf.d
@ angular.js:3334

I suspect I might not be registering the service correctly, or registering the modules. Any input is appreciated.
Updated
Added full console error msg
Result
Thank to @hansmaad, i ended up with up with the following in order to make it work:
<script src="app/moduleReg.js"></script>     // Registrere the module
<script src="app/app.js"></script>           // Controller logic
<script src="app/AnimalService.js"></script> // Service logic

A: Your module registration should be the first thing that happens. The first file you include should contain
angular.module('myApp', []);

In your case, you've included AnimalService.js before app.js.
When you register services and controllers later, use
    angular.module('myApp').controller(/*...*/);

By the way, if you define the injections as static $inject = ["Animal"]; you don't have to pass them again in the registration. Just do
angular.module('myApp', [])
    .controller('MyController', MyController);


text:
Q: mysql GROUP BY if this row table.filed > 0 how i can GROUP BY entry_category if entry_category > 0
| entry_id | entry_title | entry_category |
-------------------------------
| 1        | xxx         | 6       |
| 2        | xxx         | 4       |
| 3        | xxx         | 6       |
| 4        | xxx         | 0       |
| 5        | xxx         | 0       |
| 6        | xxx         | 6       |
| 7        | xxx         | 4       |
| 8        | xxx         | 7       |

I want  entrys  category is set , not show duplicate :
| 1        | xxx         | 6       |
| 2        | xxx         | 4       |
| 4        | xxx         | 0       |
| 5        | xxx         | 0       |
| 8        | xxx         | 7       |

A: Here is a way to do it, but there may be better way to do it. I took table name as test
select
entry_id,
entry_title,
entry_category
from
(
  (
    select
    t1.entry_id,
    t1.entry_title,
    t1.entry_category
    from test t1
    left join test t2
    on t1.entry_category = t2.entry_category
    AND t1.entry_id < t2.entry_id
    where t1.entry_category <> 0
    group by t1.entry_category
  )
  union all
  (
    select entry_id,entry_title,entry_category from test
    where entry_category = 0
  )
)x
order by entry_id

DEMO

A: this is  very good worked for me :
    SELECT * FROM entrys
    WHERE entry_category> 0
    GROUP BY  entry_category
  UNION
    SELECT * FROM entrys
    WHERE entry_category= 0

good worked.


text:
Q: Twitter Spark Streaming using Apache Spark 2.2.1 - Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/Logging Just started working on twitter spark streaming on eclipse IDE. I updated my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
    http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>please.help</groupId>
    <artifactId>please</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.10</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming_2.10</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming-twitter_2.10</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-examples_2.10</artifactId>
            <version>1.0.2</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
</project>

And I created a java class named TweetStream.java with the following codes:
public static void main(String[] args) {
    final String consumerKey = "****";
    final String consumerSecret = "****";
    final String accessToken = "****";
    final String accessTokenSecret = "****";

    SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("SparkTwitterHelloWorldExample");
    JavaStreamingContext jssc = new JavaStreamingContext(conf, new Duration(30000));

    System.setProperty("twitter4j.oauth.consumerKey", consumerKey);
    System.setProperty("twitter4j.oauth.consumerSecret", consumerSecret);
    System.setProperty("twitter4j.oauth.accessToken", accessToken);
    System.setProperty("twitter4j.oauth.accessTokenSecret", accessTokenSecret);

    JavaReceiverInputDStream<Status> twitterStream = TwitterUtils.createStream(jssc);

    // Without filter: Output text of all tweets
    JavaDStream<String> statuses = twitterStream.map(
            new Function<Status, String>() {
                public String call(Status status) { return status.getText(); }
            }
    );
    statuses.print();
    jssc.start();
}

Follwoing that, I did Run as > Maven install which built successfully. Then Run as > Run as Java application which gave the error:
    Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
18/03/04 10:39:02 INFO SparkContext: Running Spark version 2.2.1
18/03/04 10:39:02 WARN SparkContext: Support for Scala 2.10 is deprecated as of Spark 2.1.0
18/03/04 10:39:02 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
18/03/04 10:39:03 INFO SparkContext: Submitted application: SparkTwitterHelloWorldExample
18/03/04 10:39:03 INFO SecurityManager: Changing view acls to: Xian
18/03/04 10:39:03 INFO SecurityManager: Changing modify acls to: Xian
18/03/04 10:39:03 INFO SecurityManager: Changing view acls groups to:
18/03/04 10:39:03 INFO SecurityManager: Changing modify acls groups to:
18/03/04 10:39:03 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(Xian); groups with view permissions: Set(); users  with modify permissions: Set(Xian); groups with modify permissions: Set()
18/03/04 10:39:04 INFO Utils: Successfully started service 'sparkDriver' on port 60829.
18/03/04 10:39:04 INFO SparkEnv: Registering MapOutputTracker
18/03/04 10:39:04 INFO SparkEnv: Registering BlockManagerMaster
18/03/04 10:39:04 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
18/03/04 10:39:04 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
18/03/04 10:39:04 INFO DiskBlockManager: Created local directory at C:\Users\User\AppData\Local\Temp\blockmgr-72db40d5-23de-4b88-98c1-30114f48828c
18/03/04 10:39:04 INFO MemoryStore: MemoryStore started with capacity 901.8 MB
18/03/04 10:39:04 INFO SparkEnv: Registering OutputCommitCoordinator
18/03/04 10:39:04 INFO Utils: Successfully started service 'SparkUI' on port 4040.
18/03/04 10:39:04 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://192.168.100.4:4040
18/03/04 10:39:04 INFO Executor: Starting executor ID driver on host localhost
18/03/04 10:39:04 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 60842.
18/03/04 10:39:04 INFO NettyBlockTransferService: Server created on 192.168.100.4:60842
18/03/04 10:39:04 INFO BlockManager: Using     org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
18/03/04 10:39:04 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, 192.168.100.4, 60842, None)
18/03/04 10:39:04 INFO BlockManagerMasterEndpoint: Registering block manager 192.168.100.4:60842 with 901.8 MB RAM, BlockManagerId(driver, 192.168.100.4, 60842, None)
18/03/04 10:39:04 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, 192.168.100.4, 60842, None)
18/03/04 10:39:04 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, 192.168.100.4, 60842, None)
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/Logging
        at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at org.apache.spark.streaming.twitter.TwitterUtils$.createStream(TwitterUtils.scala:44)
    at org.apache.spark.streaming.twitter.TwitterUtils$.createStream(TwitterUtils.scala:56)
    at org.apache.spark.streaming.twitter.TwitterUtils.createStream(TwitterUtils.scala)
    at please.TweetStream.main(TweetStream.java:27)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.Logging
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 16 more
18/03/04 10:39:05 INFO SparkContext: Invoking stop() from shutdown hook
18/03/04 10:39:05 INFO SparkUI: Stopped Spark web UI at http://192.168.100.4:4040
18/03/04 10:39:05 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped!
18/03/04 10:39:05 INFO MemoryStore: MemoryStore cleared
18/03/04 10:39:05 INFO BlockManager: BlockManager stopped
18/03/04 10:39:05 INFO BlockManagerMaster: BlockManagerMaster stopped
18/03/04 10:39:05 INFO     OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped!
18/03/04 10:39:05 INFO SparkContext: Successfully stopped SparkContext
18/03/04 10:39:05 INFO ShutdownHookManager: Shutdown hook called
18/03/04 10:39:05 INFO ShutdownHookManager: Deleting directory C:\Users\User\AppData\Local\Temp\spark-b93e2698-f4fb-4d1a-b690-6f1128f4759c

The application started successfully, but a logging problem occurred and the application just skipped the codes and closed the connection.


text:
Q: Does polymorphism apply on value objects? Consider a scenario when a parent class only has attributes and "no method" and several child classes are extending the parent class for code re-usability.
These objects are essentially value objects and if a child value object is passed in a method accepting the parent variable as input, will you still call it a polymorphic behavior when child has no behavior to override? For example:
class Parent { int value = 100; /* doesn't have any method to be overriden */ }

class Child1 extends Parent {};

class Child2 extends Parent {};

public class Test {

    public static void main(String[] args) {
        Parent obj1 = new Child1();
        doSomething(obj1);

        Parent obj2 = new Child2();
        doSomething(obj2);

        Child1 obj3 = new Child1();
        doSomething(obj3);

        Child2 obj4 = new Child2();
        doSomething(obj4);
    }

    static void doSomething(Parent p) {
        // some code
    }
}

Will you still call above a polymorphic behavior even though there is no behavior at all?

A: Do you mean something like this?
class A { int foobar = 42; }
class B extends A {}

public class Test3 {
    public static void printAsFoobarValue(A a) { System.out.println(a.foobar); }
    public static void printBsFoobarValue(B b) { System.out.println(b.foobar); }

    public static void main(String[ ] args) throws Exception {
        A a = new A();
        B b = new B();
        A c = new B();
        printAsFoobarValue(a);
        printAsFoobarValue(b);
        printAsFoobarValue(c);
        printBsFoobarValue(b);
    }
}

I'll call this polymorph.

A: Since Parentclass in your post does not have methods to be overriden by subclasses then dosomething method in Test does something which does not invoke any overriden methods - if this is the case then it is not polymorphism


text:
Q: Display custom option in cart page magento 2? I am adding custom option using this code
$product->addCustomOption('custom', $id, $product);

Its save in database but how to display that custom option in cart item in magento 2?

A: You can display item option by overriding Magento_Checkout/templates/cart/item/default.phtml and get the custom option from quote item:
<?php
$_item = $block->getItem();
...
?>
...
<!-- Custome code -->
<?php echo $_item->getOptionByCode('custom')->getValue(); ?>
<!-- Custome code -->


text:
Q: Display "created by" field using jslink without "object Object" error Created by field is formatted as "name". Field ref used in jslink ctx override is:
 ...Submitted by: " + ctx.CurrentItem.Author + "...

Field is present in view but all I get is "object Object". It does work when list body only is formatted, so seems to be related to formatting the header element.
Update:
(function () {

var overrideCtx = {};
overrideCtx.Templates = {};

overrideCtx.Templates.Header = "
";
overrideCtx.Templates.Footer = "
";

//       Register the template overrides.

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);

})();

function CustomItem(ctx) {

var ret = "
"
 + ctx.CurrentItem.Image_x0020_upload + "
" + ctx.CurrentItem.Title + "
Submitted by: "
 + ctx.CurrentItem.Author + "
" + ctx.CurrentItem.Body + "
";
return ret;
}

A: I just did a quick test, and it seems like ctx.CurrentItem.Author is actually an array:

So you might want to try this:
...Submitted by: " + ctx.CurrentItem.Author[0].title + "...


text:
Q: How do I stop this for loop at n? Trying to get the summing to stop at 100. When I run the program as it is, it sums all the way to 5050.
public class IntSum {

    public static void main(String[] args) {
        int sum = 0;
        int n = 100;

        for (int i=1;i<=n;i++) {
            sum = sum+i;
            System.out.println("Sum = " +sum);
        }
    }
}

A: The for loop can use any boolean expression as the check, it doesn't always have to be the format of i < x. For example:
for (int i = 1; sum < 100; i++) {
    sum = sum + i;
}

A: Use an if-statement inside your loop. If the sum exceeds 100, break to for-loop


text:
Q: Cannot read property '[function]' of undefined I'm writing in Typescript with Ionic 2.2.1 in my home.ts class.
I get the error: TypeError: this.GetLocalInformation is not a function
on execution.
Here are how the two functions interact:
  ngOnInit() {
this.GetLocalInformation(); //sets this.school to the school
this.fullSchedule = this.schedProvider.GetCorrespondingSchool(this.school);
this.fullSchoolName = this.schedProvider.GetFullSchoolName(this.school);

this.timerFunc(); //Timer Function -- This method is in a loop with itself
}

timerFunc() { //Self Updating Timer Method
this.GetLocalInformation();
this.periods = this.schedProvider.GetPeriod(this.school);
this.timeInSeconds = ((this.periods[0].h * 3600) + (this.periods[0].m * 60)) - (new Date().getHours() * 3600 + new Date().getMinutes() * 60) - new Date().getSeconds(); //Calculate time difference
this.currentP = this.periods[0].title;
this.nextP = this.periods[1].title;

var dt = Date.now() - this.expected; // the drift (positive for overshooting)
if (dt > this.interval) {
  // something really bad happened. Maybe the browser (tab) was inactive?
  // possibly special handling to avoid futile "catch up" run
}
//Set Variables

//Update Timer
//this.timer.timer.secondsRemaining = +this.timeInSeconds;
this.timer.updateTimer(this.timeInSeconds);
this.expected += this.interval;
setTimeout(this.timerFunc, Math.max(0, this.interval - dt)); // take into account drift
}

I receive the error on the first line of timerFunc(), which makes no sense because I called that same function perfectly fine in ngOnInit()

A: You're losing your this context when you pass in this.timerFunc into the setTimeout function. To properly bind your scope you can use .bind(this):
setTimeout(this.timerFunc.bind(this), Math.max(0, this.interval - dt)

Or use an arrow function to auto-bind this:
setTimeout(() => this.timerFunc(), Math.max(0, this.interval - dt))


text:
Q: What's a good book on experimental methods for physics? I have read many books which can guide one in becoming a better theoretician but I haven't come across many books that help one become a better experimental physicist. For some reason the history of science favours the theoreticians and while I admire Lev Landau, Henri Poincaré and Albert Einstein, I would also like to become a better experimentalist.
In this context, I would like to know whether there are books(autobiographies even) which can guide one in becoming a good experimentalist.

A: There is a very good book on experimental methods of physics in German by Friedrich Kohlrausch with the title "Praktische Physik"(i.e. "Practical Physics"). I used this impressive compilation during my studies and later in research. Its first edition appeared more than 100 years ago. Its modern 24th edition has three sizable volumes covering all fields of experimental physics.
It seems that there also exist English editions of this book with the title "An Introduction to Physical Measurements", vol. 1; vol. 2; vol.3. It is not clear whether all three volumes are still available. "https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Dstripbooks&field-keywords=Kohlrausch+Physics

A: I do agree with physicopath that it is hard to contain experimental physics in one book and still capture an appropriate depth. But if you are looking to become a good experimentalist, here is a great book with specifics about varied experiments:
Experiments in Modern Physics by Melissinos and Napolitano. I used this book as a guide for a 3rd year undergraduate lab course in experimental modern physics. This book contains an array of topics ranging from classic quantization experiments (e.g. Milikan oil drop experiment) to basic electronics to spectroscopy (e.g. Zeeman effect). Check out the table of contents to get a better idea of the topics covered (as this book is not all-encompassing). This book repeatedly covers the underlying physics, the experimental apparatus, and the results of each experiment.
As a supplemental text, I also recommend: Data Reduction and Error Analysis for the Physical Sciences by Bevington and Robinson. This book covers the typical statistical and math tools that all experimentalists are familiar with (such as error analysis, Monte Carlo methods, and least-squares fitting to name a few).
Additionally, maybe you can clarify as to the type of experimental physics book you are looking for. Are you looking for stories about experimentalist's life or a rigorous textbook?...
Edit: here is a related question.


text:
Q: knitr kable formatting cell text as ordered list I'm creating a table in a rmarkdown/html document and it's inadvertently changing cell values to an ordered list when in the format of for example (123). An example is below. Any help would be most welcomed.

---
output: html_document
---

df <-
  data.frame(
    col1 = c("a", "b"),
    col2 = c("(123)", "(61)"),
    stringsAsFactors = FALSE
    )

knitr::kable(
  df,
  format = "html",
  align = c('lr')
)

A: The values are recognized as markdown and pandoc thinks that (123) and (61) are list items. Try
df <- data.frame(col1 = c("a", "b"),
                 col2 = c("(123)", "(61)"),
                 stringsAsFactors = F)

df$col2 <- gsub("\\(", "(", df$col2)
df$col2 <- gsub("\\)", ")", df$col2)

to replace the parenthesis by their HTML entity code.
Note: stringsAsFactors = F is the new default in R > 4.0

A: Another approach is to disable the fancy_lists extension.  This will apply globally to the document, so you might prefer @MartinSchmelzer's solution.
Just put this in your YAML:
output:
  html_document:
    md_extensions: "-fancy_lists"

After you've done this, you'll only get ordered lists with numbers (no letters or Roman numerals), and they have to be in the format 1., not (1) or 1), etc.


text:
Q: How to integrate pandas script to tkinter I want to integrate pandas script to my GUI app but I got the following error message when I click on button.
File "pandas\_libs\parsers.pyx", line 756, in pandas._libs.parsers.TextReader.read
  File "pandas\_libs\parsers.pyx", line 771, in pandas._libs.parsers.TextReader._read_low_memory
  File "pandas\_libs\parsers.pyx", line 827, in pandas._libs.parsers.TextReader._read_rows
  File "pandas\_libs\parsers.pyx", line 814, in pandas._libs.parsers.TextReader._tokenize_rows
  File "pandas\_libs\parsers.pyx", line 1951, in pandas._libs.parsers.raise_parser_error
pandas.errors.ParserError: Error tokenizing data. C error: Expected 2 fields in line 10, saw 4

Here is my code:
def open_data():
    #This import Excel file and reads it
    data= filedialog.askopenfilename(initialdir = "/", title = "Select a File",
                                          filetypes = (('Excel file', '*.xlsx'), ('all files', '*.*')))

    df = pd.read_excel(data)
def select_country():
    selected = df.loc[df['country'] == values]

window = Tk()
#Set title
window.title ('Report Generator')
# Set window size
window.geometry("800x500")
#Create a button
Button(window, text = 'Import data', command = open_data, bg = 'red', fg = 'white',
       height = 2, font = 'none 14 bold') .grid(sticky = E, padx = 6, pady = 8 )
country_selected = Label(window, text = 'Select Country')
country_list = Combobox(window, values = ['Russian Federation', 'United Arab Emirates', 'Germany',
                                          'Italy', 'United States', 'Ukraine', 'Sweden', 'Norway',
                                          'Netherlands', 'Canada', 'Chile', 'Denmark', 'Brazil',
                                          'United Kingdom', 'Finland', 'France', 'Greece', 'Israel',
                                          'Hungary', 'Portugal', 'Mexico', 'Estonia', 'Peru', 'Slovakia',
                                          'Slovenia', 'Turkey', 'South Africa', 'Switzerland', 'Austria',
                                          'Spain', 'Poland', 'Czech Republic', 'Morocco', 'Belgium', 'Romania',
                                          'Latvia', 'Saudi Arabia', 'Lithuania'] )
Button(window, text = 'Generate Report', command = select_country, bg = 'red', fg = 'white',
       height = 2, font = 'none 14 bold') .grid(sticky = E, padx = 6, pady = 8 )
window.mainloop()

I want the Import data button to import excel file, the Combo box to select the country, Generate report button to filter out selected country, and download automatically.


text:
Q: How to judge the covariance matrix? As for a numeric matrix, how to judge that it is a covariance matrix?
For example, the following $3\times3$ symmetric positive matrix is not a covariance matrix.
$$
        \begin{pmatrix}
        2 & 4 & 8 \\
        4 & 2 & 7 \\
        8 & 7 & 12 \\
        \end{pmatrix}
$$

A: Innuo, Jan 6 at 14:01:
A covariance matrix $C$ is always symmetric and positive semi-definite (i.e. all eigenvalues are $\ge 0$). You can check if that is true. Or you can conclude that it is not a covariance matrix if you are able to find a vector $x$ such that the $x' C x < 0$. Try $x = (1, -1, 0)$ for your matrix.


text:
Q: Parsing functions from BASHRC I'm using BASHRC to store alot of my daily routines, and overtime its gotten cluttered, and now there are some duplicate.
Was wondering if there's a way with SED\AWK\grep to parse all of the functions into array and then remove duplicate.
sample of bashrc with duplicate:
  function action1(){
    /usr/bin/operate $1
    }
   function action2(){
    /usr/bin/perform $1 $2
    }
   function action1(){
    /usr/bin/operate $1
    }

Thanks,
Roy

A: If that's REALLY what your input file looks like then all you need is:
$ awk '$1=="function"{unq=!seen[$2]++} unq' file
  function action1(){
    /usr/bin/operate $1
    }
   function action2(){
    /usr/bin/perform $1 $2
    }

If it's not then edit your question to provide some truly representative sample input and expected output.