text:
Q: Getting stuck while trying to upload images to a specific user account in Imgur I've created an Angular application which uploads images to Imgur. I've found ways to anonymously upload images to Imgur. I'm getting stuck when I'm trying to upload images to a specific user account.
Looking at the Imgur API and following the steps, I'm able to get the access token inside POSTMAN
and then use the access token inside the header and send requests. I want to get the access token inside my application itself rather than posting requests inside POSTMAN. From what I've understood, for using it inside my application I need to make a call to:
https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=REQUESTED_RESPONSE_TYPE&state=APPLICATION_STATE
How do I make the call to the above URL, get the response and then store the access_token from the response URL inside an Angular application. Because I've already tried sending GET request to the above URL inside Angular application and the above URL returns a HTML document and I didn't understand where to display this returned HTML document so I tried rendering it inside a DIV element which I think is a wrong choice. Now the HTML document is properly rendered inside the div element but the problem occurs when I'm trying to enter username and password inside the rendered HTML document, I get an error saying you cannot POST from 'https://localhost:4200/'.
I'm clearly doing something wrong and I don't understand how to make it work.

A: You should display/appeend returned html by following url in Modal dialog box instead of <div> tag.  On Modal dialog box should POST to server.
\https://api.imgur.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=REQUESTED_RESPONSE_TYPE&state=APPLICATION_STATE


text:
Q: Where should a new XTemplate be defined using Sencha Touch 2? I am building my first app with ST2 and began by building the app outlined in Getting Started with Sencha Touch 2 and then taking that and trying to modify it so it met my own needs. The demo app has a DataView List where each element can be tapped to reveal a corresponding detail page.
In that app the content on the detail pages is being pulled in dynamically and does not need to be styled or arranged much. However, for my own detail pages I need to use a Template or XTemplate to style and position my data.
I can't seem to figure out where I should define the template (ie, var myTpl = new Ext.XTemplate(...)) —In the controller, in the model?
Any guidance on this front would be much appreciated.

A: This depends on where you want to use the XTemplate.  If it is only ever going to be used in one view, then just define the xtemplate when you defined the view.
{
   xtype : 'view',
   tpl : new XTemplate('

...')
}

If you are going to use it in multiple views, then you can create a class that has a sole purpose of sharing templates.
Ext.define('MyApp.util.SharedTemplates', {
    statics : {
         sharedTemplate1 : new XTemplate('

')
    }

});

This way the template only gets compiled once and is re-useable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flash videos choppy after computer has been ON for a day or so I find that flash videos are extremely choppy (in firefox) or are really sped up as if on fast forward (on chrome) when my Ubuntu 11.10 has been ON for more than a day or so. Usually restarting the computer helps.
My flash version is: 11,2,202,238
Is there any process that I can turn off and then turn on instead of rebooting my computer?
I tried this to no avail: YouTube movies are playing too fast with chrome

A: The issue is with pulseaudio.
killall pulseaudio and then restarting it made the problem disappear.


text:
Q: Determine MySQL Database used by Magento Installation This question is probably fairly stupid but I installed a couple instances of Magento (for various reasons) and I made the MySQL database names very similar. In fact they only vary by some arbitrary numbering system I made up (and have since forgotten). All the installations have very few accounts, items, etc that were setup.
I'm wanting to do some house cleaning and get rid of the databases associated with installations I no longer use. Is there an easy way to figure out which is which or should I just back them all up and play roulette with the delete button?

A: You will find the database name in the file app/etc/local.xml of each magento instance you have.
Figure out which instances you are not using and look in the file mentioned above at the tag <dbname>.

A: Just for posterity, in newer versions of Magento this is kept in app/etc/env.php


text:
Q: Communication between Windows Universal App and Desktop application (Win 10) Is there any way to realize communication between a Windows Universal App and a standard Desktop application running at the same computer? I read that UAs don't support IPC. Instead they use those so called background agents. But is it possible to use those background agents not to communicate with a UA but rather a desktop application or is this completely suppressed?
The reason is, that I already have a desktop application and I would like to add Cortana support to it, without too much effort. So I would like to avoid converting the desktop app to a universal app. Cortana is only available in Universal Apps at the moment.


text:
Q: Strange result with Pandas.equals I have an initial dataframe df.
I use it to create an sql database.
Then, I create a new dataframe dfsql from my sql database with pandas.read_sql.
Using variable explorer, I can see my two dataframe are exactly the sames. Moreover, same columns and rows number.
However, when i use pd.equals to compare the two same columns "IdUnique" of the two dataframe, I have a false out :
In[4] : df['IdUnique'].equals(dfsql['IdUnique'])
Out[4] : False

What is missing to have "True" out ?


text:
Q: I'm a god. I'm not the God In 'Groundhog Day' Bill Murray's character said "I'm a god. I'm not the God."
What does "I'm a god" mean?

A: The Oxford Living Dictionaries has these definitions for the word god:

God
NOUN

*

*(in Christianity and other monotheistic religions) the creator and ruler of the universe and source of all moral authority; the supreme being.

*(in certain other religions) a superhuman being or spirit worshipped as having power over nature or human fortunes; a deity.
'a moon god'
'the Hindu god Vishnu'

Groundhog Day was set in the US where christianity dominates.  That is, a lot of Americans believe in the "one true god".  In the movie, Murray is saying that although he believes himself to be a god (definition #2), he is not the (christian) god (definition #1).

A: He is clearly referring to supernatural powers that he has somehow obtained, making him way higher over mere humans.
However, he qualifies himself, and warns that he is not G-d as the audience knows him. Not the one that people pray to, or that is responsible for creating the universe. Rather, he just has superhuman capabilities and powers.


text:
Q: How to perform XSL Transformation using XMLTABLE in pl sql? 1.For the following code I am not getting any output. DBMS output window showing nothing after executing this code. What could be the problem?
2.Here I have tried to get only one name by referring an attribute [@id="1"] , is it possible to get all the names?
    declare
    x varchar(100);
    c1 sys_refcursor;
    xml clob:=
   '<?xml version="1.0"?>
    <Com>
      <Employee id="1">
        <Name>John</Name>
        <Age>21</Age>
        <Phone>111111111</Phone>
      </Employee>
      <Employee id="2">
        <Name>Adam</Name>
        <Age>22</Age>
        <Phone>22222222</Phone>
      </Employee>
      <Employee id="3">
        <Name>David</Name>
        <Age>22</Age>
        <Phone>333333333</Phone>
      </Employee>
      <Employee id="4">
        <Name>Roy</Name>
        <Age>22</Age>
        <Phone>44444444</Phone>
      </Employee>
    </Com>';

    xsl clob:=
    '<?xml version="1.0"?>
     <xsl:transform version="1.0"                                                              xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
     <xsl:template match="/">
     <xsl:for-each select="Com/Employee[@id=''1'']">
     <![CDATA[<Com>]]>
     <xsl:value-of select="Name"/>
     <![CDATA[</Com>]]>
     </xsl:for-each>
     </xsl:template>
     </xsl:transform>';

    function fun1 return sys_refcursor
    as
    c2 sys_refcursor;
    begin
    open c2 for select Names_List from XMLTABLE('/Com/Employee'
    PASSING XMLTYPE(XMLTRANSFORM(xmltype(xml),xmltype(xsl)).GetClobVal())
    columns Names_List varchar(100) path 'Name');
    return c2;
    end;
    begin
    c1:=fun1;
    loop
    fetch c1 into x;
    exit when c1%notfound;
    dbms_output.put_line('Names : '|| x);
    end loop;
    end;

A: Change the OPEN C2 ... with this:
  OPEN c2 FOR SELECT Names_List FROM XMLTABLE('/Com'  PASSING XMLTRANSFORM(xmltype(xml),xmltype(xsl)) columns Names_List varchar(100) path '/Com');

When you get errors, make it step by step. After XMLTRANSFORM you have:
<Com>John</Com>

There is no Employee tag. Than XMLTRANSFORM returns XMLType. You are getting from XMLType a CLOB and convert it in XMLType. Why?


text:
Q: Euler Characteristic of a blowing up I'm trying to compute the Euler Characteristic of the blowing up of  $\mathbb{C}\mathbb{P}^2$ at $n$ points. Does anyone know how could I do this?

A: I thought I'd write down a couple of thoughts about how we can obtain the result $\chi_{\rm top}(Bl_n(\mathbb P^2)) = 3 + n$ explained in Nicolas' answer.
Method 1:
Noether's formula for surfaces states that
$$\chi(\mathcal O_X)= \tfrac 1 {12}\left( K_X.K_X + \chi_{\rm top}(X)\right)$$
where $\chi(\mathcal O_X)$ denotes the holomorphic Euler characteristic of the structure sheaf, $K_X . K_X$ denotes the self-intersection of the canonical divisor, and $\chi_{\rm top}(X)$ denotes the topological Euler characteristic of the space (with the analytic topology).
We also have the following two facts (both of which are proved in Beauville's Complex Algebraic Surfaces):

*

*As Mohan pointed out, $\chi(\mathcal O_X)$ is a birational invariant, so if $\pi : \widetilde X \to X$ is a blow-up, then $\chi(\mathcal O_{\widetilde X}) = \chi(\mathcal O_X)$.

*The self-intersection of the canonical class of the blow-up is related to the self-intersection of the original space by $K_{\widetilde X}.K_{\widetilde X}=\pi^\star K_X . \pi^\star K_X - 1$.
Combining all of these observations, we see that blowing up a surface at a point increases the topological Euler characteristic $\chi_{\rm top}(X)$ by one.
Method 2:
I think this method is really equivalent to  Nicolas' answer...
I believe that complex quasi-projective varieties obey an inclusion-exclusion principle (see also here): if $X$ is a complex projective variety and $Y \subset X$ is a closed subvariety, then
$$ \chi_{\rm top}(X) = \chi_{\rm top}(X \setminus Y) + \chi_{\rm top} (Y)$$
So if you think of the blow-up operation as removing a point ($Y = \{ \rm pt \}$), then adding a two-sphere ($Y = \mathbb {CP}^1$), this formula tells you that the Euler characteristic increases by one after the blow-up.
I must admit I've never studied a proof of this result, but I believe it is based on triangulation.

A: It is easy to see that for a complex surface $S$ and $p$ a smooth point, we have $\chi(Bl_{p}S) = \chi(S) +1 $, say using triangulations. This gives $\chi(Bl_{n}(\Bbb{P}^2)) = 3 + n$.
For example, $n=6$ is a cubic hypersurface and you can easily check that you get $9$.


text:
Q: count unique values in a group, and exclude already counted rows in mysql I would like to count all unique visitors group by day.But i want to exclude the visitor if he has already visited any previous day.My sample table is as below
mysql> select * from visitor;
+-------+------------+--------------+
| user  | visit_date | No Of Visits |
+-------+------------+--------------+
| user1 | 20150101   | 10           |
| user2 | 20150102   | 1            |
| user3 | 20150101   | 1            |
| user1 | 20150102   | 2            |
+-------+------------+--------------+

My requirement is to get a distinct count of user group by visit date but to exclude already visited user.
20150101 --> User1 and user 3 visited
20150102 --> User 2 visited (Exclude user1 as he has already visited)
+----------------------+------------+
| count(distinct user) | visit_date |
+----------------------+------------+
|                    2 | 20150101   |
|                    1 | 20150102   |
+----------------------+------------+

A: select visit_date, count(distinct user)
from visitors as v1
where not exists (
    select 1
    from visitors as v2
    where
            v2.user = v1.user
        and v2.visit_date = date_sub(v1.visit_date, interval 1 day)
)
group by visit_date

or
select v1.visit_date, count(distinct v1.user)
from
    visitors as v1
    left outer join visitors as v2
        on      v2.user = v1.user
            and v2.visit_date = date_sub(v1.visit_date, interval 1 day)
where v2.user is null
group by v1.visit_date

Not really sure if DISTINCT is actually necessary in the aggregate.

A: Solved
select count(*),hr from (select user, min(visit_date)as hr
      from visitor v
      group by user) as data group by hr


text:
Q: Create all combination of 11 names out of 22 where sum of credit is 100 I have two columns one has 22 Names and another column with respective credit against each name. I need to know all the combination of 11 names which sums up to 100.
i am attaching image of data for example.
I searched and returned with itertool which gets you all the combination. But I was not sure of how this can be used to get all the combination.
import pandas as pd
import itertools
from itertools import combinations
from itertools import permutations
data=pd.read_excel(r'C:\Users\anup.kumar.dutta\Documents\Test\Test.xlsx',index=False)
def f(length,total_sum):
    if length == 1:
        yield (total_sum,)
    else:
        for value in range(total_sum + 1):
            for permutation in sum(length - 1,total_sum - value):
                yield (value,) + permutation

L = list(f(5,100))
print('total permutations:',len(L))

It should return all combination of names which sums up to credit 100.

A: Doing combinations calculations of this sort is not quick. I'm timing it using time.time.
starttime = time.time()

We will use combintations from itertools.
from itertools import combinations

First I will recreate your data (please include next time for responders so we don't have to recreate). I'm using letters for names. I will use pd.Series as this fits your data and this will be quickest next to using numpy directly.
s = pd.Series(np.random.randint(8,11,22), index = list('ABCDEFGHIJKLMNOPQRSTUV'))

Next set the combination parameters.
# set combination parameters
r =  11
n = len(s)

Create a list for tracking the names whose scores == 100.
name_list = []

Finally, loop through the combinations storing all combinations summing to 100.
for p in combinations(s.index, r):
    if s.loc[list(p)].sum() == 100:
        name_list.append(p)

endtime = time.time()

print('Time to run', endtime - starttime)
Time to run 350.4899344444275

name_list (fist ten rows)

[('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'M'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'T'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'V'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'M', 'T'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'M', 'V'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'T', 'V'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'L', 'M'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'L', 'T'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'L', 'V'),
 ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'M', 'O'),...

How many combinations are there?
print(len(name_list))
86724


text:
Q: Writing a website with VB.NET back-end, no ASP.NET I've been asked to make a website with VB.NET server-side code, and I cannot use ASP.NET or any client-side scripting. The pages need to interact with a Microsoft SQL Server database hosted on a Windows 2003 server (which has IIS and the .NET framework installed). I've been googling for examples, but all the ones I find seem to be about ASP.
I have some basic PHP experience, and can program in VB.NET, but I've never had to do anything like this before. Can anyone give me a reference or basic example that I could play with that will help me connect an html webpage to the SQL database with VB.NET as my server-side code, without using ASP.NET?
Edit and clarification: I know ASP.NET is server-side - what I have been specifically banned from using is any tag starting <asp: or containing runat=server. If there are other features of ASP.NET that I can/need to use, then that's fine.

A:
More specifically, I've been told I can't use any tags starting "<asp:" or containing "runat=server"

You can at least use IIS, and the .Net tools within IIS, right? You're not completely re-implementing a web server?
Just make a handler (*.ashx), and use Response.Write() ,<%=, and <%: for everything.
You should also look into whether you can use ASP.Net MVC (it doesn't need server controls at all). Otherwise you're essentially back in the dark days of classic asp.

A: ASP.NET is not client side.
ASP.NET is a web development framework which uses a server side language like C#/ Vb.NET. So what you are going to create is going to be an ASP.NET app with VB.NET as your codebehind language.
If you still do not want to use ASP.NET webforms framework to create a website but still like to use Vb.NET as the language, you may think about creating a WCF Service using VB.NET and Let your client non-asp.net web app consume it.
EDIT: After seeing your comment

I have been specifically banned from using is any tag starting

Consider ASP.NET MVC. There is no Server controls like what you have in webforms which has runat=server. You will be writing PURE HTML code and bind with some data as needed.

A: Well I suppose you could write a web server in VB.net that doesn't use ASP.net, but why?
Given you haven't had a specific restriction against using MVC, I'd look into that.

A: You don't necessarily have to use  controls to make the website with ASP.NET.   Use plain HTML and have your server side code just output text.  Something like this:
<table>
<%= tableRow.toString() %>
</table>

You'll use a lot of string builders but it should accomplish what you're looking for.
MVC might be another alternative if you can persuade them that it's not actually doing any client side code.  You're separating the HTML View (and any javascript if they're letting you use that) from the business logic and database logic.
Hope that helps some.


text:
Q: Using a function to generate on object on a background thread using RxJava Observables I'm playing around with RxJava and trying to figure out how run a method on a background thread and deal with the results on the foreground thread.  I stumbled across a solution but wanted to get a sanity check and see if there was a better way, since there seem to be a lot of different ways to compose Observables to do similar things.
Here's what I have:
    Observable.defer(
        () -> Observable.just(
            // A. Should run on Scheduler.newThread
            db.query(
                false, DATABASE_TABLE, null,
                null, null, null, null, null,
                null)))
    .subscribeOn(Schedulers.newThread())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(
        Subscribers.create(
            // B. Should run on AndroidSchedulers.mainThread
            cursor -> adapter.swapCursor(cursor)
        ));

The code works as expected.  A runs on the background thread and B runs on the main thread.
My question is, this seems reasonable enough but is there a more elegant way to do this?

A: defer is a decent enough way to do it, but with the optional RxAsyncUtil lib, you can use the slightly nicer fromFunc0, like this:
Observable.fromFunc0(() -> db.query(...))
    .subscribeOn(... etc.

also, you don't have to use Subscribers.create, since one of the main overloads of subscribe takes a single action for onNext.
So, your subscribe could become:
    .subscribe(cursor -> { adapter.swapCursor(cursor) })

(not 100% sure if the {}s are necessary with the java8 lambdas. they may not be if swapCursor is void... try both?)
so, all together:
Observable.fromFunc0(() -> db.query(
    false, DATABASE_TABLE, null, null, null, null, null, null, null))
    .scheduleOn(Schedulers.newThread())
    .observeOn(Schedulers.mainThread())
    .subscribe(cursor -> { adapter.swapCursor(cursor) })

seems like a pretty tight implementation. :)


text:
Q: A circular reference was detected EF 6 Ok, I am getting this error:

A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Asset_AED71699FAD007BF6F823A5F022DB9888F62EBBD9E422BBB11D7A191CD784288'.

I get what it means. My code was generated from VisualStudioTools and it generated all my POCOs with virtual navigation properties and mapped the relationships.
I am happy with that and I want the lazy loading.
Here is an example of my user class:
public partial class User : IdentityUser
{
    public User()
    {
        this.Assets = new List<Asset>();
        this.Categories = new List<Category>();
        this.Collections = new List<Collection>();
        this.Comments = new List<Comment>();
        this.LocalIntegrations = new List<LocalIntegration>();
        this.Pages = new List<Page>();
        this.Ratings = new List<Rating>();
        this.Themes = new List<Theme>();
        this.ForbiddenCategories = new List<Category>();
        this.ForbiddenPages = new List<Page>();
    }

    public string CompanyId { get; set; }
    public string CreatedById { get; set; }
    public string ModifiedById { get; set; }
    public System.DateTime DateCreated { get; set; }
    public Nullable<System.DateTime> DateModified { get; set; }
    public System.DateTime LastLoginDate { get; set; }
    public string Title { get; set; }
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string JobTitle { get; set; }
    public string Telephone { get; set; }
    public string Mobile { get; set; }
    public string Photo { get; set; }
    public string LinkedIn { get; set; }
    public string Twitter { get; set; }
    public string Facebook { get; set; }
    public string Google { get; set; }
    public string Bio { get; set; }
    public string CompanyName { get; set; }
    public string CredentialId { get; set; }
    public bool IsLockedOut { get; set; }
    public bool IsApproved { get; set; }
    public bool CanEditOwn { get; set; }
    public bool CanEdit { get; set; }
    public bool CanDownload { get; set; }
    public bool RequiresApproval { get; set; }
    public bool CanApprove { get; set; }
    public bool CanSync { get; set; }
    public bool AgreedTerms { get; set; }
    public bool Deleted { get; set; }

    public virtual Company Company { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual User ModifiedBy { get; set; }
    public virtual ICollection<Asset> Assets { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<Collection> Collections { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<LocalIntegration> LocalIntegrations { get; set; }
    public virtual ICollection<Page> Pages { get; set; }
    public virtual ICollection<Rating> Ratings { get; set; }
    public virtual ICollection<Theme> Themes { get; set; }
    public virtual ICollection<Group> MemberOf { get; set; }
    public virtual ICollection<Category> ForbiddenCategories { get; set; }
    public virtual ICollection<Page> ForbiddenPages { get; set; }
}

and my group class looks like this:
public partial class Group
{
    public Group()
    {
        this.ForbiddenCategories = new List<Category>();
        this.ForbiddenPages = new List<Page>();
        this.Members = new List<User>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string CompanyId { get; set; }
    public bool Preset { get; set; }
    public Nullable<bool> CanEdit { get; set; }
    public Nullable<bool> CanEditOwn { get; set; }
    public Nullable<bool> CanDownload { get; set; }
    public Nullable<bool> RequiresApproval { get; set; }
    public Nullable<bool> CanApprove { get; set; }
    public System.DateTime DateCreated { get; set; }
    public bool CanSync { get; set; }
    public Nullable<System.DateTime> DateModified { get; set; }
    public string CreatedById { get; set; }
    public string ModifiedById { get; set; }
    public bool Deleted { get; set; }

    public virtual Company Company { get; set; }
    public virtual User CreatedBy { get; set; }
    public virtual User ModifiedBy { get; set; }
    public virtual ICollection<Category> ForbiddenCategories { get; set; }
    public virtual ICollection<Page> ForbiddenPages { get; set; }
    public virtual ICollection<User> Members { get; set; }
}

I read that in order to stop circular references, you could do something like this:
public async Task<JsonResult> Get()
{
    try
    {
        using (var service = new UserService(new CompanyService()))
        {
            var u = from user in await service.GetAll()
                    select new
                    {
                        Id = user.Id,
                        UserName = user.UserName,
                        Email = user.Email,
                        IsApproved = user.IsApproved,
                        IsLockedOut = user.IsLockedOut,
                        MemberOf = user.MemberOf
                    };

            return new JsonResult { Data = new { success = true, users = u } }; // Return our users
        }
    }
    catch (Exception ex)
    {
        return new JsonResult { Data = new { success = false, error = ex.Message } };
    }
}

but it fails when returning the users because of MemberOf.
The circular reference is with the User, which has a Collection and each Asset has a User who created it.
Is there a way to get it to only do lazy loading on the first POCO (in this case the User class) so that it only loads the MemberOf, Assets, etc. but not the rest (i.e. not User > Assets > User)??
Update 1
evanmcdonnal suggested that it might be an issue with the JsonResult rather than my POCO classes, so I decided to have a look if there was a way to verify that.
Basically I created a JsonNetResult class that inherited from JsonResult and I overrode ExecuteResult. This is what it looks like:
public class JsonNetResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        var response = context.HttpContext.Response;

        response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        if (Data == null)
            return;

        // If you need special handling, you can call another form of SerializeObject below
        var serializedObject = JsonConvert.SerializeObject(Data, Formatting.Indented);
        response.Write(serializedObject);
    }
}

so my method looks like this now:
    public async Task<JsonNetResult> Get()
    {
        try
        {
            using (var service = new UserService(new CompanyService()))
            {
                var u = from user in await service.GetAll()
                        select new
                        {
                            Id = user.Id,
                            UserName = user.UserName,
                            Email = user.Email,
                            IsApproved = user.IsApproved,
                            IsLockedOut = user.IsLockedOut,
                            MemberOf = user.MemberOf
                        };

                return new JsonNetResult { Data = new { success = true, users = u } }; // Return our users
            }
        }
        catch (Exception ex)
        {
            return new JsonNetResult { Data = new { success = false, error = ex.Message } };
        }
    }

and when I run this, I get the same error as before but it shows in more details. It actually states this:

An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Self referencing loop detected with type 'System.Data.Entity.DynamicProxies.Asset_AED71699FAD007BF6F823A5F022DB9888F62EBBD9E422BBB11D7A191CD784288'. Path 'users[0].MemberOf[0].Company.Assets[0].Categories[0].Assets'.

Now I am going to check to see if I can change the recursion limit :(

A: You can try adding [DataContract(IsReference = true)] to your class. This will serialise your objects using reference ids and should solve circular reference problems.

A: Based on your update I'm going to assume the current value for RecursionLimit is the problem. The docs for that property are relatively sparse but that's okay they can be found here http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult.recursionlimit(v=vs.118).aspx
I believe you can resolve the issue by replacing your current return line with the following lines of code;
JsonResult retVal = new JsonResult();
retVal.RecursionLimit = 1000; //maybe parameteraize this?
reVal.Data = = new { success = true, users = u };
return retVal;

EDIT: After your update I know how easily solve the problem as your exception is now thrown by JsonConvert.SerializeObject and I've solved this before :)
Based on your update you could easily fix this by changing some code in ExecuteResult (this option I'm more confident in as I actually have it implemented in my current project, I personally have not used the JsonResult class and my previous suggestion is just me leveraging my general knowledge of json.NET). You can call an overload of SerializeObject like sample below and it will now throw when you have circular references;
string json = JsonConvert.SerializeObject(YourInstanceToSerialize, Formatting.Indented,
 new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize });

The available values for ReferenceLoopHandling can be found here; http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_ReferenceLoopHandling.htm I believe the default is 0 which is why your code is throwing. Since you already updated with those changes I think I'd advise going with the second method (I at least know it will work) but feel free to try the first one too.

A: Ive found turning OFF lazy loading for these queries works. Simply ensure your query selects all it needs to via "include" if needed.
Then before the query:
efContext.Configuration.LazyLoadingEnabled = false;


text:
Q: Accessing XML attributes data I have two lines of XML data that are attributes but also contain data inside then and they are repeating fields. They are being stored in a SimpleXML variable.
<inputField Type="Name">John Doe</inputField>
<inputField Type="DateOfHire">Tomorrow</inputField>

(Clearly this isnt real data but the syntax is actually in my data and I'm just using string data in them)
Everything that I've seen says to access the data like this, ,which I have tried and it worked perfectly. But my data is dynamic so the data isn't always going to be in the same place, so it doesn't fit my needs.
$xmlFile->inputField[0];
$xmlFile->inputField[1];

This works fine until one of the lines is missing, and I can have anywhere from 0 to 5  lines. So what I was wondering was is there any way that I can access the data by attribute name? So potentially like this.
$xmlFile->inputField['Name'];

or
$xmlFile->inputField->Name;

I use these as examples strictly to illustrate what I'm trying to do, I am aware that neither of the above lines of code are syntactically correct.
Just a note this information is being generated externally so I cannot change the format.
If anyone needs clarification feel free to let me know and would be happy to elaborate.

A: Maybe like this?
echo $xmlFile->inputField->attributest()->Name;

And what you're using? DOMDocument or simplexml?

A: You don't say, but I assume you're using SimpleXMLElement?
If you want to access every item, just iterate:
foreach ($xmlFile->inputField as $inputField) { ... }

If you want to access an attribute use array notation:
$inputField['Type']

If you want to access only one specific element, use xpath:
$xmlFile->xpath('inputField[@Type="Name"]');

Perhaps you should read through the basic examples of usage in the SimpleXMLElement documentation?

A: For example you can a grab a data:
$xmlFile = simplexml_load_file($file);

foreach($xmlFile->inputField as $res) {

    echo $res["Name"];

}


text:
Q: How do i find parent class name with Selenium - ChromeDriver im trying to find the parent class name on a element, but i don't know how i find it.
Here is a picture of what im trying to find the parent class name of.

What do i need to press to find the parent class name?
I can send the link to the website and show which element I am trying to get parent class name on

A: To find the parent classname of the WebElement you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following Locator Strategy:

*

*Code Block:
driver.get("https://www.zalando.dk/cart")
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Fortsæt med at shoppe']//parent::button[1]"))).get_attribute("class"))

*Console Output:
z-1-button z-coast-base-primary-accessible undefined z-1-button--primary z-1-button--button

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


text:
Q: Solr error - Stream Body is disabled I'm deleting documents from browser URL.
I'm using Solr-7.4.0
I'm using this query for delete document
http://localhost:8983/solr/test/update?stream.body=<delete><query>*:*</query></delete>&commit=true

This is return below error message.
{
  "error":{
    "metadata":[
      "error-class","org.apache.solr.common.SolrException",
      "root-error-class","org.apache.solr.common.SolrException"],
    "msg":"Stream Body is disabled. See http://lucene.apache.org/solr/guide/requestdispatcher-in-solrconfig.html for help",
    "code":400}}

I also tried with
http://localhost:8983/solr/test/update?commit=true -H "Content-Type: text/xml" --data-binary '<delete><query>*:*</query></delete>'

but not get any luck.
This return below message:
{
  "responseHeader":{
    "status":0,
    "QTime":1}}

but documents not deleting.
I'm using DIH for import data.
my data-config.xml file is
<dataConfig>
<dataSource type="JdbcDataSource" driver="com.microsoft.sqlserver.jdbc.SQLServerDriver" url="jdbc:sqlserver://127.0.0.1\SQL2017;databaseName=mydatabase"   user="sa" password="mypassword"/>

    <document>
      <entity name="Product"
        pk="Id"
        query="select Id, [Name] from Product"
        deltaImportQuery="SELECT Id, [Name] from Product WHERE Id='${dih.delta.id}'"
        deltaQuery="SELECT Id FROM Product  WHERE updated_at > '${dih.last_index_time}'"
        >
         <field column="Id" name="Id"/>
         <field column="Name" name="Name"/>
      </entity>
    </document>
</dataConfig>

A: Another way is to open the solrconfig.xml file and edit it directly.
The default value should look like this:
<requestParsers enableRemoteStreaming="true"
                multipartUploadLimitInKB="2048000"
                formdataUploadLimitInKB="2048"
                addHttpRequestToContext="false"/>

We need to add the enableStreamBody attribute:
<requestParsers enableRemoteStreaming="true"
                enableStreamBody="true"
                multipartUploadLimitInKB="2048000"
                formdataUploadLimitInKB="2048"
                addHttpRequestToContext="false"/>

Just remember to reload the collection in Solr so the changes will be applied.

A: I fixed it by postman
Method: POST
Content-Type: application/json
Body:
{
    "set-property": [{
            "requestDispatcher.requestParsers.enableRemoteStreaming": true
        },
        {
            "requestDispatcher.requestParsers.enableStreamBody": true
        }
    ]
}

URL: http://localhost:8983/api/cores/test5/config
after that run below URL:
http://localhost:8983/solr/test5/update?stream.body=%3Cdelete%3E%3Cquery%3E*:*%3C/query%3E%3C/delete%3E&commit=true

and it's working fine.


text:
Q: Ellipsis(...) is not working for single word I have set the following style sheet as value template for column of the grid in general interface (TIBCO GI) for text ellipsis
white-space:nowrap;text-overflow:ellipsis;

It is working for sentences / more than one word. it is not working for single word.
Please help me to fix this out.
-Sridhar

A: jsfiddle
I was able to get the ellipsis to show with only one word.  Try setting the overflow:hidden;.
I do want to add that I don't have TIBCO, so I couldn't test it in there, but this is a proof that it does work outside of it.


text:
Q: Facebook application unavailable for some users I'm having a weird problem in my Facebook apps. It shows a "Application is unavailable" error but only for some users (actually, for the most part). I'm the only administrator of the page and I assume I can see it working for that reason. However, two of my friends who are testing can see it and everyone else can't.
I used Facebook's Debug Tool to check if anything was wrong but it seems to be ok.
The app page is: http://apps.facebook.com/taggeoapp/
Thanks in advance for any hint... I really don't know what is going on...


text:
Q: Label that wraps an input - how to make focus style visible only when focused using the keyboard, not mouse click? In the following example, the button's focus style is visible only when the button is focused using a keyboard (not mouse click).
How could I achieve the same effect on a label that wraps a hidden input?
In the code below, the label's focus style is visible when the label is focused using a keyboard or using a mouse click. I'd like it to be visible only when focused using a keyboard.

.visually-hidden {
  position: absolute;
  border: 0;
  width: 1;
  height: 1;
  padding: 0;
  margin: -1;
  overflow: hidden;
  clip: rect(0, 0, 0, 0);
  white-space: nowrap;
  word-wrap: normal;
}

body {
  margin: 40px;
}

div {
  display: flex;
  gap: 20px;
}

input:focus {
  outline: 4px solid red;
}

button:focus-visible {
  outline: 4px solid red;
}

label:focus-within {
  outline: 4px solid red;
}

  <input type="text" />
  <button>Submit</button>

    <input class="visually-hidden" type="checkbox" />
    Label

A: Update the styles of the input inside it so it can style get the focus while being visually hidden:

label {
  position:relative;
}
.visually-hidden {
  position: absolute;
  inset: 0;
  margin: 0;
  padding: 0;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  overflow: hidden;
}

button:focus-visible,
input:focus-visible{
  outline: 4px solid red;
}

body {
  margin: 40px;
}

div {
  display: flex;
  gap: 20px;
}

  <input type="text" />
  <button>Submit</button>

    <input class="visually-hidden" type="checkbox" />
    Label


text:
Q: How to Implement auto-scrolling for recyclerView when items are clicked like instagram? Instagram have an auto-scrolling effect on their listviews when users clicks on a filter: See a video of it here: https://www.youtube.com/watch?v=R3VsKt5Ktao
So when the user clicks on an item, it helps the user to scroll one item to the left or right. How can this be archived with a recyclerView?


text:
Q: Как сделать автоматическое сложение или вычитание Подскажите пожалуйста как можно сделать так, что если я добавляю новую строку с данными в БД, вставленную в datagridview, эта строка сама инициализировалась по типу (доход или расход) и соответственно автоматически добавлялась к итоговой сумме "Дохода" или автоматически вычиталась от итоговой суммы "Расхода". чтобы не вводить на каждую добавленную строку отдельный код. если можно объяснить подробно, потому что я пока разбираюсь в этом и могу чего то не понять, буду признателен
Код добавления новой строки:
private void AddButton_Click(object sender, EventArgs e) {
    Form1 main = this.Owner as Form1;
    if (main != null) {
        DataRow nRow = main.база_данныхDataSet.Tables[0].NewRow();
        int rc = main.dataGridView1.RowCount + 1;
        nRow[0] = rc;
        nRow[1] = tbType.Text;
        nRow[2] = tbCategory.Text;
        nRow[3] = tbDate.Text;
        nRow[4] = tbSum.Text;
        // nRow[5] = tbTotal.Text;
        nRow[6] = tbComments.Text;

        main.база_данныхDataSet.Tables[0].Rows.Add(nRow);
        main.accountingTableAdapter.Update(main.база_данныхDataSet.Accounting);
        main.база_данныхDataSet.Tables[0].AcceptChanges();
        main.dataGridView1.Refresh();
        tbType.Text = " ";
        tbCategory.Text = " ";
        tbDate.Text = " ";
        tbSum.Text = " ";
        // tbTotal.Text = " ";
        tbComments.Text = " ";
    }
}

Код, который вычисляет сумму и разность, прописанный вручную, действующий только на имеющиеся строки.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) {
    dataGridView1.Rows[0].Cells[5].Value = Convert.ToString(Double.Parse(dataGridView1.Rows[0].Cells[4].Value.ToString()));
    dataGridView1.Rows[1].Cells[5].Value = Convert.ToString(Double.Parse(dataGridView1.Rows[0].Cells[5].Value.ToString()) + Double.Parse(dataGridView1.Rows[1].Cells[4].Value.ToString()));
    dataGridView1.Rows[2].Cells[5].Value = Convert.ToString(Double.Parse(dataGridView1.Rows[1].Cells[5].Value.ToString()) + Double.Parse(dataGridView1.Rows[2].Cells[4].Value.ToString()));
    dataGridView1.Rows[3].Cells[5].Value = Convert.ToString(Double.Parse(dataGridView1.Rows[2].Cells[5].Value.ToString()) - Double.Parse(dataGridView1.Rows[3].Cells[4].Value.ToString()));
    dataGridView1.Rows[4].Cells[5].Value = Convert.ToString(Double.Parse(dataGridView1.Rows[3].Cells[5].Value.ToString()) - Double.Parse(dataGridView1.Rows[4].Cells[4].Value.ToString()));
    dataGridView1.Rows[5].Cells[5].Value = Convert.ToString(Double.Parse(dataGridView1.Rows[4].Cells[5].Value.ToString()) - Double.Parse(dataGridView1.Rows[5].Cells[4].Value.ToString()));
}

A: private void ButtonAdd_Click(object sender, EventArgs e)
    {
        //если это не первая запись в таблице
        if (_dataSet.Tables[0].Rows.Count > 0)
        {
            //сначала находим максимальный Id
            var lastId = _dataSet.Tables[0].AsEnumerable().Max(r => r.Field<int>("Id"));
            //находим последнюю запись
            var lastRow = _dataSet.Tables[0].AsEnumerable()
                                       .First(r => r.Field<int>("Id") == lastId);

            //вычисляем значение Итого
            decimal lastTotal = lastRow.Field<decimal>("Total");
            string type = _comboBoxType.Text;
            decimal current = 0;
            if (decimal.TryParse(_textBoxSum.Text, out decimal sum))
            {
                current = (type.Equals("Доход") ? 1 : -1) * sum;
            }
            //создаем новую строку
            var row = _dataSet.Tables[0].NewRow();
            row["Type"] = type;
            row["Category"] = _comboBoxCategory.Text;
            row["Date"] = _dateTimePicker.Value;
            row["Sum"] = sum;
            row["Total"] = lastTotal + current;
            _dataSet.Tables[0].Rows.Add(row);
        }
        else
        {
            // в случае первой записи в таблицу...
        }

        //пишем в БД
        try
        {
            using (var adp = new SqlDataAdapter(_selectString, _conString))
            using (var cmb = new SqlCommandBuilder(adp))
            {
                var added = adp.Update(_dataSet.Tables[0]);
                Trace.WriteLine($"Добавлено {added}");
            }
            _dataSet.Tables[0].AcceptChanges();
            _dataGridView.Refresh();
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.Message);
        }
    }


text:
Q: How to avoid DB2 driver Classloader Memory leak on Tomcat application .war file redeployment IBM's well supported JDBC driver creates a memory leak in combination with Tomcat's well supported connection pool.
Please refer to Classloader memory leak on Tomcat application .war file redeployment.
java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [DB2JccConfiguration.properties]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
    at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1327)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1023)
    at com.ibm.db2.jcc.am.ud.run(Unknown Source)
    at java.security.AccessController.doPrivileged(AccessController.java:285)
    at com.ibm.db2.jcc.am.GlobalProperties.a(Unknown Source)
    at com.ibm.db2.jcc.am.GlobalProperties.d(Unknown Source)
    at com.ibm.db2.jcc.am.mq.run(Unknown Source)
    at java.util.TimerThread.mainLoop(Timer.java:567)
    at java.util.TimerThread.run(Timer.java:517)

I do not understand the suggested solution as it is in conflict with the most recommended practice of including the driver jar in the Tomcat lib directory.
We need shared deployment and re-deployment without Tomcat re-start. Please share your solution here if you have experience with this software combination and the described issue.

A: For driver version 4.22.29, I'm currently using this code in a ServletContextListener:
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    // This fixes the JDBC driver not unloading corectly on a context reload  for DB2 JDBC 4.22.29
    try {
        logger.debug("Trying to stop the timer");
        new com.ibm.db2.jcc.am.iq() {
            // instance initializer to execute the fix when the anonymous class is instantiated, i.e. now
            {
                if (a != null) {
                    a.cancel();
                } else {
                    logger.debug("Timer is null, skipped");
                }
            }
        };
        logger.debug("Stopped the timer");
    } catch (Exception e) {
        logger.error("Could not stop the DB2 timer thread", e);
    }
}

Note: Since the DB2 driver JAR appears to be obfuscated, the timer storage (com.ibm.db2.jcc.am.iq.a) will probably be different for other driver versions. Also, the constructor of the class you're subclassing might have side effects, in my case there are none.
How I got to this solution
Get the exception
java.lang.NullPointerException
    at org.apache.catalina.loader.WebappClassLoaderBase.getResource(WebappClassLoaderBase.java:1600)
    at com.ibm.db2.jcc.am.wd.run(wd.java:49)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.ibm.db2.jcc.am.GlobalProperties.a(GlobalProperties.java:146)
    at com.ibm.db2.jcc.am.GlobalProperties.d(GlobalProperties.java:100)
    at com.ibm.db2.jcc.am.dr.run(dr.java:124)  <------- point of interest <----------
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

The main class for the timer is com.ibm.db2.jcc.am.dr.
Using IntelliJ, I set a breakpoint in its constructor. Wait for the breakpoint to hit:

Go to where it's instantiated, in my case in GlobalProperties. Look on what timer it is scheduled.

Find a way to access iq.a: Since this is a static protected field, we can inherit from iq and from inside that class, access the static field of the parent class to call cancel() on a.

A: This is a confirmed bug in the IBM JDBC driver version 4.19 (timer task that cannot be disabled). The workaround is to downgrade to version 4.18.

A: Fix for version 4.19.66:
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    // This fixes the JDBC driver not unloading corectly on a context reload  for DB2 JDBC 4.19.66
    try {
        System.out.println("Trying to stop the DB2 timer thread");
        new com.ibm.db2.jcc.am.tp() {
            {
                if (a != null) {
                    a.cancel();
                } else {
                    System.out.println("Timer is null, skipped");
                }
            }
        };
        System.out.println("Stopped the timer");
    } catch (Exception e) {
        System.out.println("Could not stop the DB2 timer thread " + e.getMessage());
    }
}


text:
Q: Using vpath and wild card in Makefile 1) I am having directory called dir, and the subdirectories are sub1, sub2, sub3.
2) I want to create a Makefile which will compile all the sources in the subdirectory. These are some lines of my makefile.
CFLAGS = -I/usr/include/ -I./ -ansi -g
GPROF_CFLAGS = -I/usr/include/ -I./
VPATH = ./sub1 ./sub2 ./sub3
SRCS := $(wildcard *.c)
OBJS=$(SRCS:.c=.o)
exe:    $(OBJS)
        $(CC) $(LFLAG) -o exe $(CFLAGS) $(OBJS) -lm

exe_gprof:
        gcc $(LFLAG) -o exe $(GPROF_SUFFIX) $(GPROF_CFLAGS) $(SRCS)

clean:
        rm -f *.o

clean_all: clean
        rm -f exe exe$(GPROF_SUFFIX) gmon.out Simfir000.stat rm -f *.o.

3) This make file works fine, if i have only sub folder called sub(this directory contains all source files) and no other sub folder. (i.e) in the make file vpath=./sub.
4) If there are sub folders as I mentioned in point 1, the main file is in the subfolder of sub1/src/main.c(i.e sub folder inside the sub folder). If I try to compile. It's giving undefined ref to main.
5) what change I have to do, to compile this successfully. Can we give more than one directory path in vpath?.
Overall map is:

Having directory called dir
sub directory dir/sub1
dir/sub2
dir/sub3
main file is in dir/sub1/src/main.c

My second question is
If I want to execute directory by directory and create different exe's

compiling sub1 only and create sub1exe
copiling sub2 only and create sub2exe.

The make file will be
CFLAGS = -I/usr/include/ -I./ -ansi -g
GPROF_CFLAGS = -I/usr/include/ -I./
VPATH = ./sub1 ./sub2 ./sub3
SRCS1 := $(wildcard *.c)
SRCS2 := $(wildcard *.c)
OBJS=$(SRCS:.c=.o)
exe1:    $(OBJS)
        $(CC) $(LFLAG) -o exe1 $(CFLAGS) $(OBJS) -lm
exe2:    $(OBJS)
        $(CC) $(LFLAG) -o exe2 $(CFLAGS) $(OBJS) -lm

exe1_gprof:
        gcc $(LFLAG) -o exe1 $(GPROF_SUFFIX) $(GPROF_CFLAGS) $(SRCS1)
exe2_gprof:
        gcc $(LFLAG) -o exe2 $(GPROF_SUFFIX) $(GPROF_CFLAGS) $(SRCS2)

clean:
        rm -f *.o

clean_all: clean

What changes I have to make instead of $(wildcard *.c).

A: This post seems to answer your question: Sources from subdirectories in Makefile
Try SRCS = $(wildcard *.c) $(wildcard **/*.c)
I think VPATH and wildcard are not working together, so that your SRCS doesn't have all source files.
By the way, have you already tried CMake?


text:
Q: PVCS service getting down once the server CPU physical memory usage become high. Whats the issue and How to resolve it? Our PVCS service getting down once the physical memory usage of the server goes high. Once the server restarts(Not recommended) again the service will be up. Is there any permenant fix for this?

A: I resolved this issue by increasing the heapsize parameters...:-)

1.On the server system, open the following file in a text editor:

Windows as of VM 8.4.6: VM_Install\vm\common\bin\pvcsrunner.bat
Windows prior to VM 8.4.6: VM_Install\vm\common\bin\pvcsstart.bat
UNIX/Linux: VM_Install/vm/common/bin/pvcsstart.sh

2.Find the following line:

set JAVA_OPTS=

And set the value of the following parameters as needed:

-Xmsvaluem -Xmxvaluem

3.If you are running a VM release prior to 8.4.3, make sure -Dpvcs.mx= is followed by  the same value shown after -Xmx.

4.Save the file and restart the server.

The following is a rule of thumb when increasing the values for -Xmx:

•256m -> 512m
•512m -> 1024m
•1024m -> 1280m

A: As Riant points out above, adjusting the HEAP size is your best course of action here. I actually supported PVCS for nine years until this time in 2014 when I jumped ship.  Riant's numbers are exactly what I would recommend.
I would actually counsel a lot of customers to set -Xms and -Xmx to the same value (basically start it at 1024) because if your PDBs and/or your user community are large you're going to hit the ceiling quicker than you might realize.


text:
Q: GraphQL: How to query for all available types? In the LearnGraphQL.com sandbox if you click the < DOCS button in the upper right hand corner it reveals a "Documentation Explorer" which lists the following:
ROOT TYPES
-----------------------
query: BlogSchema
mutation: BlogMutations

What is the raw query that can be sent to a graphql server that will return this information?

A: Every GraphQL server, according to the spec, must support a set of queries for "introspection": http://graphql.org/docs/introspection/
This means you can use GraphQL queries to get information about that server's available types, fields, queries, mutations, directives, etc.
So if you want some specific information, you can use that documentation to construct a query that will get it.
If you want all of the information available, you can use the built-in introspection query from GraphQL-JS, listed here: https://github.com/graphql/graphql-js/blob/master/src/utilities/introspectionQuery.js
You can use this information for many different purposes:

*

*Plug it into tools like eslint-plugin-graphql to validate your queries at development time

*Build custom documentation browsers

*Generate typed code stubs to integrate query results into your Java/Swift apps


text:
Q: Emulate Run Command? I'm attempting to create a basic Run command emulator using VBScript, or .bat if that would be easier.
I have had no formal education on these languages, but can do very basic functions from looking at forums and web help. I need this code to be able to request user input for the program they want to open (input box function) and actually open the program.
The server I work at has both Run and CMD blocked, but not written scripts.
Any help would be appreciated.
~Jester

A: This runs CMD and captures it's output.
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
Set cmd = CreateObject("Wscript.Shell").Exec("cmd")
cmd.stdin.writeline "dir"
wscript.sleep 20000
cmd.stdin.writeline "dir"
cmd.stdin.writeline "exit"
Do While Not cmd.stdout.AtEndOfStream

    results = cmd.stdout.readall
    If err.number <> 0 then Exit Do
        wscript.echo results
Loop
'wscript.sleep 5000

This shows making your own console program. Most menu options don't do anything.
Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout

Showmenu

Sub ShowHelpMenu
    outp.writeline " -----------------------------------------------------------------------------"
    outp.writeblanklines(1)
    outp.writeline " Menu"
    outp.writeline " ----"
    outp.writeblanklines(1)
    outp.writeline "  1 Help              2 HTML Help          3 Version           4 History"
    outp.writeblanklines(1)
    outp.writeline "  5 Exit"
    outp.writeblanklines(1)
    outp.write "Filter>"
End Sub

'=============================================
Sub ShowMenu
    Do
        ShowHelpMenu
        Answ=Inp.read(1)
Outp.write Answ
'       Answ=Inp.readline
        If Answ = "1" Then
            ShowGeneralHelp "TEXT"
        Elseif Answ = "2" Then
            ShowGeneralHelp "HTML"
        Elseif Answ = "3" Then
            Version
        Elseif Answ = "4" Then
            History
        Elseif Answ = "5" Then
            Exit Do
        End If
    Loop
End Sub

'=============================================
Sub History
    On Error Resume Next
    WshShell.Run """" & FilterPath & "FilterHistory.txt""" , 1, False
    err.clear
End Sub

'=============================================
Sub Version
    outp.writeblanklines(1)
    outp.writeline " Version"
    outp.writeline " -------"
    outp.writeblanklines(1)
    outp.writeline "   Filter Ver 0.6  -  2015  (Public Domain)"
    outp.writeblanklines(1)
    outp.writeline "   by David Candy"
    outp.writeblanklines(1)
End Sub

This shows a basic batch.
:start
set /p CMDToExec=Enter Command
%CMDToExec%
Goto Start


text:
Q: Javascript Tag cloud font size rolling over after 10 occurrances I have a JSON string from my DB that gets fed into the script below, your basic tag cloud with font size being increased based on frequency.  My problem is that once a frequency hits ten (10), the font size goes back to the same as if it were one.  I've had similar problems where I was passing a string in PHP instead of INT, but that is not the case here.
{"tags":[{"tag":"programming","freq":11}]}
$(function() {

  $.getJSON("tagcloud.php", function(data) {

    $("<ul>").attr("id", "tagList").appendTo("#tagCloud");

    //create tags
    $.each(data.tags, function(i, val) {

      //create item
      var li = $("<li class=\"tagInfo\">");

      //create link
      $("<a>").text(val.tag).attr({class:"a",href:"index.php?page=tagdata&tagName=" + val.tag }).appendTo(li);

      /*If I set the first equation to more than what my frequency is (10000 here for caution), it works fine.
      But the equation in the line commented out where `(val.freq / 10 < 1) is not
      giving me the correct output.  Am I missing ensuring this variable is an
      INT in my JS after it's retrieved in JSON? */
      li.children("a").css("fontSize", (val.freq / 10000 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");
      //li.children("a").css("fontSize", (val.freq / 10 < 1) ? val.freq / 10 + 1 + "em": (val.freq / 10 > 2) ? "2em" : val.freq / 10 + "em");

      //add to list
      li.appendTo("#tagList");
    });
  });
});

A: Try this (never mind the syntax changes -- it's just for readability):
li.children("a").css("fontSize",
    ((val.freq / 20) <= 1 ? (val.freq / 20) + 1 :
     (val.freq / 10) >= 2 ? 2 : (val.freq / 10)) + "em");

Why...
Due to the initial use of less than < expression, rather than <=, your algorithm negates 10 / 10 as true and ends up in the "else" segment of your ternary statement (returning 1em).
Another issue your going to run into is that you've limited yourself to a very small range of values -- in this case, font sizes. Currently, your equation results in the following:
 divisor | frequency | product | size (em)
-------------------------------------------
    10        1          0.1       1.1
    10        2          0.2       1.2
    10        3          0.3       1.3
    10        4          0.4       1.4
    10        5          0.5       1.5
    10        6          0.6       1.6
    10        7          0.7       1.7
    10        8          0.8       1.8
    10        9          0.9       1.9
    10        10         1.0       1.0
    10        11         0.1       1.1
    10        12         0.2       1.2
    ...       ...        ...       ...

You can resolve the issue so that it will scale up, from 1.05em to 2em (with increments of .05em), by simply changing the divisor from 10, to 20. This will help to make sure that the size keeps scaling until it hits your threshold, 2em.
I would suggest marking up some of your variables as currently the size scales up for every 1 hit, and stops scaling at 20 hits. You know, 20 -> 200, 10 -> 100. Either way...


text:
Q: Is there a way to cast _io.TextIOWrapper to an integer in Python f = open("example.txt", "r")
print(f.read())

f = int(f)

i am trying to compare what is the document with a number e.g. in the document there is 4 and I want to compare it like this
if 5 < f

A: _io.TextIOWrapper is a file object, created by open. You actually want to read its contents into a string and then convert that to an int.
with open("example.txt") as f:
    n = int(f.read())

print(n, 5 < n)  # example

By the way, it's good practice to open files with a with statement. See Reading and Writing Files in the Python Tutorial for the basics.


text:
Q: In a commutative Koszul algebra, does every ideal generated by a subset of variables have linear resolution? Let $A = k[x_1 , \dots , x_n] / I$ be a commutative Koszul algebra; that is, the ideal $(x_1 , \dots , x_n)$ has linear minimal free resolution. Does it follow that the ideal generated by any subset of variables $(x_{i_1} , \dots , x_{i_\ell})$ also has a linear minimal free resolution?
The answer seems to be yes. Indeed, it seems like the resolution of the subset of variables is obtained as a direct summand of the Priddy (generalized Koszul) complex, which is acyclic by the Koszul assumption on $A$. Probably this subcomplex is realized as a Tate construction, and I was looking for a reference (or a quick proof/counterexample) of the question in the title.
Edit: As provided by Hailong, there is indeed a counterexample to the above claim. I would like to mention that there is a notion of "strongly Koszul" introduced by Herzog, Hibi, and Restuccia. This imposes the additional assumption that all colon ideals of the form $(x_{i_1} , \dots , x_{i_k} ) : x_{i_{k+1}}$ (for $i_1 < \cdots < i_{k+1}$) are generated by a subset of the variables. It turns out that being strongly Koszul does imply that the ideal generated by any subset of the variables has linear resolution.

A: The ring $R= K[a,b,c,d]/(ac,ad,ab-bd,a^2+bc,b^2)$ is Koszul but the ideal $I=(b)$ is not Koszul as $bc^2=0$, and indeed $c^2$ appears in the presentation matrix of $I$.


text:
Q: Export command not found in su - user Starting with root, I want execute a sql script with another $USER. But I have to set the right $ORACLE_HOME and $PATH for $USER.
With this command I receive error export: command not found
su - $USER -c "export ORACLE_HOME=$ORA_HOME;export PATH=$ORA_HOME/bin:$PATH;sqlplus / as sysdba"

My question is: starting executing a script in root, how can I export a environment variable for another user and execute a command using that environment variable?

A: As steeldriver commented, it's likely that your target user is using csh or tcsh.
If you want to be sure of the shell that you're using, invoke it explicitly:
su - "$USER" -c \
  "/bin/ksh -c 'export ORACLE_HOME=$ORA_HOME;export PATH=$ORA_HOME/bin:$PATH;sqlplus / as sysdba'"

While the (sub)shell will contain any (exported) environment variables from the main shell, it will not contain any (unexported) shell variables from the user's main shell.

A: You don't need to export anyway. Just run:
su - $USER -c "ORACLE_HOME=$ORA_HOME;PATH=$ORA_HOME/bin:$PATH;sqlplus / as sysdba"

The export is only needed if you need the variables to be inherited by any child shells launched by your shell. Here, you're launching the command from the same shell, so there's no need to export.
But, as pointed out in the comments, that won't help if sqlplus needs to see those variables, only if they need to be set in order to find sqlplus correctly. If that fails, try:
su - $USER -c "ORACLE_HOME='$ORA_HOME' PATH='$ORA_HOME/bin:$PATH' sqlplus / as sysdba"


text:
Q: Using dplyr to check values of multiple rows that meet a condition (ex- all rows where the date column falls in a specified period) I have a dataset of event ids, the event type, and the time of the event. The events consist of "start" and "pause". I would like to identify "pause" events that are not followed by a "start" event within 7 days and classify these as "stops".
Here is the code for the test dataset:
test <- data.frame("id" = 1:5,
               "event" = c("pause",
                           "pause",
                           "start",
                           "pause",
                           "start"),
               "time" = dmy("03-11-2012",
                            "05-11-2012",
                            "06-11-2012",
                            "21-11-2012",
                            "30-11-2012"))

So far, I used lead() to check if the following event was a "start" event AND happened within 7 days. However, I realized that sometimes a "pause" event was followed by another "pause" event and then a "start" event, all within 7 days. Both "pause" events in this case should not be considered to be a stop. This means that I need to check all events/rows that occurred within 7 days of the "pause" event and look for a "start" event.
I am looking for a function I can use within dplyr (I'll use non-dplyr solutions if I have to) where I can check the value of multiple rows.
My solution so far using lead(), which checks the immediate next row only.
test2 <- test %>%
mutate(stop = ifelse(event == "pause" &
                     !((time + days(7) > lead(time)) &
                          lead(event) == "start"),
                   "yes",
                   "no"))

This gives
|id|event|time      |stop|
|------------------------|
|1 |pause|2012-11-03|yes |
|2 |pause|2012-11-05|no  |
|3 |start|2012-11-06|no  |
|4 |pause|2012-11-21|yes |
|5 |start|2012-11-30|no  |

I would like the stop column value for the first "pause" to also be a "no" because it has a "start" event within 7 days of it.

A: If you want to do this inside a dplyr function, you can sapply inside a mutate:
test %>%
  mutate(stop = sapply(seq_along(time),
          function(i) {
              if(event[i] != "pause") return(FALSE)
              ind <- which(time > time[i] & event == "start")
              if(length(ind) == 0) return(FALSE)
              as.numeric(difftime(time[ind[1]], time[i], units = "day")) > 7
            }))

#>   id event       time  stop
#> 1  1 pause 2012-11-03 FALSE
#> 2  2 pause 2012-11-05 FALSE
#> 3  3 start 2012-11-06 FALSE
#> 4  4 pause 2012-11-21  TRUE
#> 5  5 start 2012-11-30 FALSE

A: Although it might get slow with large dataset, this might do the work:
library(dplyr)
library(purrr)
test %>%
  mutate(
    stop = ifelse(event=="pause" & !((time + days(7) > lead(time)) & lead(event) == "start"),
                  "yes", "no"),
    stop2 = ifelse(map_lgl(row_number(),
                           ~any(event=="start" & time>=time[.x] & time<=time[.x] + days(7))),
                   "no", "yes")
  )

#   id event       time stop stop2
# 1  1 pause 2012-11-03  yes    no
# 2  2 pause 2012-11-05   no    no
# 3  3 start 2012-11-06   no    no
# 4  4 pause 2012-11-21  yes   yes
# 5  5 start 2012-11-30   no    no

Using row_number() and time[.x], this allows to consider every row independently. Then, we just check if there is any "start" between "now" and "in 7 days" and put the right value accordingly. purrr::map_lgl allows to loop over every row and return a logical vector.
The slowness comes from the fact that you have to check for all the rows each time you want to compute the value for one row.


text:
Q: pgbench for postgresql 9.3 for centos where to find it? How can I install pgbench for postgresql 9.3?
I have basically set up my postgresql9.3 on centos 64 bit, and it runs fine. No problem at all.
I then installed postgresql93-contrib on my centos machine. But i dont seem to have pgbench? I get command not found?
I execute the following under bash:
pgbench -i -U test test

any ideas?

A: It is in contrib.  The exact spelling depends on which repo you use, something like postgresql93-contrib
It is possible that pgbench will not be in your default path. Then you can run it by executing: /usr/pgsql-10/bin/pgbench --help

A: in Centos6
install pgbench
yum install postgresql93-contrib

then pgbench will appear in /usr/pgsql-9.3/bin
add this path to system
vi /etc/profile

add /usr/pgsql-9.3/bin to Path
source /etc/profile

now can run pgbench now


text:
Q: Jasmine $HTTP requests with mock data Im trying to test $http requests and no matter what I do I cant seem to get it to work. I have a factory that holds the 4 request type GET, POST, PUT, DELETE.
Im trying to test the response from a get request but my scope variable that is assigned the response in the controller is giving an error or undefined = the response from the get request.
The factory code is as follows:
app.factory('requestService', ['$http', function ($http) {
// reusable requests
return {
    //reuable get request
    getRequest: function (url) {
        return $http({
            method: 'GET',
            dataType: "json",
            url: url
        });
    },
    //reuable post request
    postRequest: function (url, data) {
        return $http({
            method: 'POST',
            data: data,
            url: url
        });
    },
    //reuable put request
    putRequest: function (url, data) {
        return $http({
            method: 'PUT',
            data: data,
            url: url
        });
    },
    //reuable delete request
    deleteRequest: function (url) {
        return $http({
            method: 'DELETE',
            url: url
        });
    }
}
}]);

The following is in the controller.
    //get the teams
    $scope.getTeams = function(){
    requestService.getRequest('https:.../teams').then(function (response) {
        $scope.teams = response;
    });
}
$scope.getTeams();

Jasmine code:
describe('Controller Test', function() {
var $rootScope, controller;

//Tell the $httpBackend to respond with our mock object
var teamsResponse = {// Teams Data //};

beforeEach(function() {
    module('myApp')
});
beforeEach(inject(function($rootScope, $controller, _$httpBackend_, $http) {
    $scope = $rootScope.$new();
    controller = $controller;
    controller('Controller', {$scope: $scope});

    $httpBackend = _$httpBackend_;

    $httpBackend.whenGET('https:...../teams').respond(200, teamsResponse);

}));

it('should load a list of teams', function() {
    $scope.getTeams();
    $httpBackend.flush();

    expect($scope.teams).toBe(teamsResponse);
});
});

The error I get is:
Expected undefined to be {// Teams Data //}

A: describe("Testing Common Get JSON Service", function () {

    var service, $httpBackend;

    beforeEach(inject(function($injector,$rootScope) {
        service = $injector.get('CommonService');
        $httpBackend = $injector.get('$httpBackend');
        scope = $rootScope.$new();
        successCallback = jasmine.createSpy();
        errorCallback = jasmine.createSpy();

        $httpBackend.when('GET', getFlightIncidentLookupUrl).respond(getFlightIncidentLookup);
        successCallback();
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('test getServiceJSON works fine and calls a GET method', function () {
        service.getServiceJSON(getFlightIncidentLookupUrl).then(function(response) {
            expect(response.data.incidentLookup.length).toEqual(1);
        });
        $httpBackend.flush();
    });

});

This worked for me . here CommonService is a service in Angular js which calls a get method. I got the response correctly.


text:
Q: Extending the Token class in JavaCC I'm working on a JavaCC project and I'm having some trouble extending the Token class. I want to create a subclass classed IDToken and override its getValue() method. Below is my subclass code
public class IDToken extends Token implements java.io.Serializable {
  private static final long serialVersionUID = 1L;
  public int kind;
  public int beginLine;
  public int beginColumn;
  public int endLine;
  public int endColumn;
  public String image;
  public Token next;
  public Token specialToken;
  public IDToken(){}
  public IDToken(int kind)
  {
    this(kind,null);
  }
  public IDToken(int kind, String image){
    this.kind=kind;
    this.image=image;

  }
  public String toString(){
    return this.image;
  }
  public static Token newToken(int ofKind, String image){
    switch (ofKind)
    {
      default: return new Token(ofKind, image);
    }
  }
  public static Token newToken(int ofKind){
    return newToken(ofKind, null);
  }
  @Override
  public Object getValue(){
    return "abcdefg";
  }
}

However the override doesn't seem to work, getValue() returns null. I think I'm supposed to use newToken() in Token.java to create my IDToken but I haven't been able to figure out how to do that just yet.

A: In order to be able to extend the Token class and re-define the getValue() method you need to set the TOKEN_FACTORY option to a custom class that has static method newToken(int, String) returning an instance of Token:
// Parser.jj
options {
    STATIC = false;
    JAVA_UNICODE_ESCAPE = true;
    UNICODE_INPUT = true;
    JDK_VERSION = "1.8";

    TOKEN_FACTORY = "FooBar";
}

// FooBar.java
class MyCustomToken extends Token {
    @Override
    public Object getValue() {
        return 42;
    }
}

public class FooBar {
    public static Token newToken(int kind, String image) {
        switch (kind) {
            case 42:
                return new MyCustomToken();
            default:
                return new Token(kind, image);
        }
    }
}


text:
Q: ¿Cómo puedo comunicar un fragment con un activity que se encuentran en diferentes rutas? Quiero comunicar un fragment (llamado ecdsa, que se encuentra en com.emhg.mylibrary con un Activity (llamado SecondActivity, que se encuentra en com.emhg.transmissiondevice).
Mi intención es mandar datos desde ese fragment al Activity. Para ello, quiero que se realice la comunicación cuando haga click en un botón.

Había probado a escribir la siguiente parte de código:

Pero me da error... Haciendo alt + enter para encontrar posibles soluciones, me da la opción de añadir una dependencia, PERO si lo hago, me advierte de que no va a funcionar bien, y efectivamente, eso sucede, pues ya lo he probado:

¿Alguien me podría ayudar? Gracias :)


text:
Q: Duplicates in Database, Help Edit My Query to Filter Them Out? I have just finished my latest task of creating an RSS Feed using PHP to fetch data from a database.
I've only just noticed that a lot (if not all) of these items have duplicates and I was trying to work out how to only fetch one of each.
I had a thought that in my PHP loop I could only print out every second row to only have one of each set of duplicates but in some cases there are 3 or 4 of each article so somehow it must be achieved by the query.
Query:
SELECT *
FROM uk_newsreach_article t1
    INNER JOIN uk_newsreach_article_photo t2
        ON t1.id = t2.newsArticleID
    INNER JOIN uk_newsreach_photo t3
        ON t2.newsPhotoID = t3.id
ORDER BY t1.publishDate DESC;

Table Structures:
uk_newsreach_article
--------------------
id | headline | extract | text | publishDate | ...

uk_newsreach_article_photo
--------------------------
id | newsArticleID | newsPhotoID

uk_newsreach_photo
------------------
id | htmlAlt | URL | height | width | ...

For some reason or another there are lots of duplicates and the only thing truely unique amongst each set of data is the uk_newsreach_article_photo.id because even though uk_newsreach_article_photo.newsArticleID and uk_newsreach_article_photo.newsPhotoID are identical in a set of duplicates, all I need is one from each set, e.g.
Sample Data
id | newsArticleID | newsPhotoID
--------------------------------
 2 |     800482746 |     7044521
10 |     800482746 |     7044521
19 |     800482746 |     7044521
29 |     800482746 |     7044521
39 |     800482746 |     7044521
53 |     800482746 |     7044521
67 |     800482746 |     7044521

I tried sticking a DISTINCT into the query along with specifying the actual columns I wanted but this didn't work.

A: group by all your selected columns with HAVING  COUNT(*) > 1 will eleminate all duplicates like this:
SELECT *
FROM uk_newsreach_article t1
    INNER JOIN uk_newsreach_article_photo t2
      ON t1.id = t2.newsArticleID
    INNER JOIN uk_newsreach_photo t3
      ON t2.newsPhotoID = t3.id
GROUP BY  t1.id, t1.headline, t1.extract, t1.text, t1.publishDate,
          t2.id, t2.newsArticleID, t2.newsPhotoID,
          t3.id, t3.htmlAlt, t3.URL, t3.height, t3.width
HAVING  COUNT(*) > 1
ORDER BY t1.publishDate DESC;

A: As you have noticed, the DISTINCT operator will return every id. You could use a GROUP BYinstead.
You will have to make a decision about wich id you want to retain. In the example, I have used MINbut any aggregate function would do.
SQL Statement
SELECT MIN(t1.id), t2.newsArticleID, t2.newsPhotoID
FROM uk_newsreach_article t1
    INNER JOIN uk_newsreach_article_photo t2
        ON t1.id = t2.newsArticleID
    INNER JOIN uk_newsreach_photo t3
        ON t2.newsPhotoID = t3.id
GROUP BY t2.newsArticleID, t2.newsPhotoID
ORDER BY t1.publishDate DESC;

Disclaimer
Now while this would be an easy solution to your immediate problem, if you decide that duplicates should not happen, you really should consider redesigning your tables to prevent duplicates getting into your tables in the first place.


text:
Q: Using Excel (Or Calc) as a web-app frontend or embedded widget Problem: When dealing with web-applications that require grid-based input (but is not a fullblown spreadsheet like Google's) there is a common problem. Either the web-GUI sucks, or it is tied behind some heavily-specialized API that takes way too much training and time to use effectively (not to mention the price tag tends to be high for these kinds of things).
Question: Assuming all the target users have Excel or OpenOffice (or can be told to get a copy) has anyone out there tried using a spreadsheet as an input form for a live web application?
Scenario: User X comes to your website, she gets to a page where she downloads a spreadsheet to continue some complex number crunching in the midst of using your webapp. When she is done, she presses a button on your specially constructed spreadsheet, and the spreadsheet itself submits its payload via POST to your website, then the website does whatever with the recently-crunched numbers.
Motivation: The motivation for this question stems from huge frustration with all the various "grid control" widgets out there for use in web pages. They either are not enough, or not sufficiently capable of being "embedded" as a control in a web page.

A: This is common practice for data-heavy intranet applications. In the past, you would have used VB for Applications. Today, the Open XML SDK offers a very elegant way of hooking into the open and close events of the document. Excel will execute your managed code upon open (to populate the spreadsheet) and upon close/save (to extract the data from the spreadsheet and write it back to the database).
The Excel document can be served from a Web server that does not need to have Office installed.


text:
Q: gRPC Node Js client: "Method not found" I have a gRPC server implemented in python and I am calling an RPC from NodeJS but it gives an error "Method not found". When I call using the python client, the request is successful.
stream_csv.proto
syntax = "proto3";

package csv;

service Stream {
  rpc csvToObject(CSVDataRequest) returns (stream CSVDataResponse) {};
  rpc sayHello(HelloRequest) returns (HelloReply);
}

message CSVDataRequest{
  string url = 1;
  enum Protocol {
    HTTP = 0;
    HTTPS = 1;
    FTP = 2;
    SFTP = 3;

}

  Protocol protocol = 2;
}

message CSVDataResponse{
  repeated string row = 1;
}

message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

client.js
var PROTO_PATH = '../stream_csv.proto';

var grpc = require('grpc');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
    PROTO_PATH,
    {keepCase: true,
     longs: String,
     enums: String,
     defaults: true,
     oneofs: true
    });
var proto = grpc.loadPackageDefinition(packageDefinition).csv;

function main() {
  var client = new proto.Stream('localhost:5000',
                                       grpc.credentials.createInsecure());
  var user;
  if (process.argv.length >= 3) {
    user = process.argv[2];
  } else {
    user = 'world';
  }
  console.log(user);
  client.sayHello({name: user}, function(err, response) {
    console.log(err);
  });
}

main();

server.py
import grpc
import stream_csv_pb2
import urllib.request
from urllib.error import HTTPError, URLError
from concurrent import futures
class DataService:

    def csv_to_object(self, request, context):
        url = request.url
        protocol = stream_csv_pb2.CSVDataRequest.Protocol.Name(
            request.protocol)
        fetch_url = protocol.lower() + "://"+url

        try:
            with urllib.request.urlopen(fetch_url) as data:
                for line in data:
                    decoded_line = line.decode()
                    val = decoded_line.split(',')
                    print(val)
                    print("Data send")
                    yield stream_csv_pb2.CSVDataResponse(row=val)

            print("Sending finished!")

        except URLError as e:
            context.abort(grpc.StatusCode.UNKNOWN,
                        'Randomly injected failure.')
            # return stream_csv_pb2.CSVDataResponse(row=[], error=e.reason)

    def SayHello(self, request, context):
        name = request.name
        print(name)
        return stream_csv_pb2.HelloReply(message='Hello %s' % (name))

def add_DataServicer_to_server(servicer, server):
    rpc_method_handlers = {
        'CSVToObject': grpc.unary_stream_rpc_method_handler(
            servicer.csv_to_object,
            request_deserializer=stream_csv_pb2.CSVDataRequest.FromString,
            response_serializer=stream_csv_pb2.CSVDataResponse.SerializeToString,
        ),
        'SayHello': grpc.unary_unary_rpc_method_handler(
            servicer.SayHello,
            request_deserializer=stream_csv_pb2.HelloRequest.FromString,
            response_serializer=stream_csv_pb2.HelloReply.SerializeToString,
        )
    }
    generic_handler = grpc.method_handlers_generic_handler(
        'stream_csv.Stream', rpc_method_handlers)
    server.add_generic_rpc_handlers((generic_handler,))

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    add_DataServicer_to_server(DataService(), server)
    server.add_insecure_port('[::]:5000')
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    serve()

Error
Error: 12 UNIMPLEMENTED: Method not found!
    at Object.exports.createStatusError (/home/shantam/Documents/grepsr/client/node_modules/grpc/src/common.js:91:15)
    at Object.onReceiveStatus (/home/shantam/Documents/grepsr/client/node_modules/grpc/src/client_interceptors.js:1209:28)
    at InterceptingListener._callNext (/home/shantam/Documents/grepsr/client/node_modules/grpc/src/client_interceptors.js:568:42)
    at InterceptingListener.onReceiveStatus (/home/shantam/Documents/grepsr/client/node_modules/grpc/src/client_interceptors.js:618:8)
    at callback (/home/shantam/Documents/grepsr/client/node_modules/grpc/src/client_interceptors.js:847:24) {
  code: 12,
  metadata: Metadata { _internal_repr: {}, flags: 0 },
  details: 'Method not found!'
}

A: I wrote a simpler variant of your Python (and Golang) server implementations.
Both work with your Node.JS client as-is.
I think perhaps your issue is as simple as needing to name the rpc sayHello (rather than SayHello).
from concurrent import futures
import logging

import grpc

import stream_csv_pb2
import stream_csv_pb2_grpc

class Stream(stream_csv_pb2_grpc.StreamServicer):

    def sayHello(self, request, context):
        logging.info("[sayHello]")
        return stream_csv_pb2.HelloReply(message='Hello, %s!' % request.name)

def serve():
    logging.info("[serve]")
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    stream_csv_pb2_grpc.add_StreamServicer_to_server(Stream(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    logging.basicConfig()
    serve()

And:
node client.js
Greeting: Hello, Freddie!
null

Conventionally (!) gRPC follows Protobufs style guide of CamelCasing service, rpc and message names and using underscores elsewhere see Style Guide. When protoc compiles, the results don't always match perfectly (e.g. Python's CamelCased functions rather than lowercased with underscores).
Conventionally, your proto would be:
service Stream {
  rpc CsvToObject(CSVDataRequest) returns (stream CSVDataResponse) {};
  rpc SayHello(HelloRequest) returns (HelloReply);
}

...and then the Python generated function would be (!) SayHello too.


text:
Q: html: construct link through multiple buttons I have a form which I want to link through to some pre constructed html pages that are constructed in a hierarchy such as:
           |Data1(DIR) -> file1,file2,file3
/var/www/  |
           |Data2(DIR) -> file1,file2,file3

I want to be able to choose which directories files to view via a radio button (or equivalent) but I cant find how to do this. I have the form set up as follows with a radio button choice followed by a dropdown of the 7 files, where the ##option## is what I want to have replaced with the directory to open. I think I am going after this in a perl manner and not at all html-y. Any advice would be appreciated.
<form action="../cgi-bin/redirect.pl" method="post" onsubmit="return dropdown(this.gourl)">

<big>
    <input name="project" value="data1" type="radio"> Dataset1
    <input name="project" value="data2" type="radio"> Dataset2</big>

<select name="gourl"><option value="">Choose Taxonomy level...
    </option><option value="##option##/superkingdom.html">Superkingdom
    </option><option value="##option##/phylum.html">Phylum
    </option><option value="##option##/class.html">Class
    </option><option value="##option##/order.html">Order
    </option><option value="##option##/family.html">Family
    </option><option value="##option##/genus.html">Genus
    </option><option value="##option##/species.html">Species
    </option></select>
<input value="Go" type="submit">

A: I've sorted it through php. Adding it here for any future people!
<?php
echo "<form>";
echo "Select a Site:
";
$sites = glob("*");
foreach ($sites as $site) {
    print "<input name=\"$site\" type=\"radio\" value=\"$site\" onclick=\"submit()\">$site
";
}
echo "</form>";

foreach($_GET as $key=>$value) {
    $$key = $value;
    $return = $value;
    print "site: $return";

    print "
<select id=\"setit\" name=\"url\">
           <option value=\"\">Choose Taxonomy level...</option>
           <option value=\"$return/superkingdom.html\">Superkingdom</option>
           <option value=\"$return/phylum.html\">Phylum</option>
           <option value=\"$return/class.html\">Class</option>
           <option value=\"$return/order.html\">Order</option>
           <option value=\"$return/family.html\">Family</option>
           <option value=\"$return/genus.html\">Genus</option>
           <option value=\"$return/species.html\">Species</option>
           </select>
           <input type=\"button\" value=\"go\"
    onclick=\"window.open(setit.options[setit.selectedIndex].value)\">";
}
?>


text:
Q: Rails form called from a another controller's action I have models User, Event, Rsvp.  I want to have a Rsvp form appear in the show page of my Event model.  A User can create many Events but I don't need to know which User create which Event (at least I don't think).  A User can also rsvp to an Event. My models looks like so:
user.rb
has_many :rsvps

event.rb
has_many :rsvps

rsvp.rb
belongs_to :user
belongs_to :event

I think my RsvpsController should look like this:
class RsvpsController < ApplicationController
  def new
    @user = current_user
    @event = Event.find(params[:id])
    @rsvp = Rsvp.new
  end
end

Now in my show page of an Event I want a form in the sidebar which lets Users rsvp to the Event.  I have something like this but it's not quite right.  I'm especially not sure what is the first argument that goes into form_for:
form_for [@user, @event, @rsvp], url: {controller: 'rsvps_controller', action: 'create' } do |f|

in my events/show.html.haml I try to render the Rsvp new action like this:
=render template: 'rsvps/new'

but this instead renders an event/new partial
EDIT
I think I know why this render is rendering an Event new partial.  Inside Rsvps/new.html.haml I have render 'form'.  I also have a _form.html.haml in my Events folder.
EDIT2
rsvps_controller.rb
def create
  @rsvp = current_user.rsvps.build(params[:rsvp])
  if @rsvp.save
    flash[:success] = "You have RSVPed."
    redirect_to Event.find(params[:event_id])
  else

  end
end

A: since you want to create the reservation for the current user, you should only pass the event to the rsvp create action. for the form, use
<%= form_for Rsvp.new do |f| %>
  <%= f.hidden_field :event_id, value: @event.id %>

This should give you access to the event that the current user wants to rsvp.  So in your create action of the Rsvp controller, you can build the reservation by using the following code
def create
  @rsvp = current_user.rsvps.build params[:rsvp]

  if @rsvp.save
    ...
end


text:
Q: Alternative to "FOR JSON" in SQL Server 2012? In SQL Server 2016 I can output query results as JSON as described in the documentation Format Query Results as JSON with FOR JSON (SQL Server)
SELECT *
FROM x
FOR JSON PATH

But I'm finding that this is not supported in SQL Server 2012.
Is there a built-in way to convert tabular data to JSON data in SQL Server 2012?
To make this cross compatible I would ideally like to be able to use for json path in SQL Server 2012.

A: No. JSON support was new in SQL Server 2016.
If you want to convert data to JSON, you have a few options:

*

*Fetch the rows as you would any other query result, and convert it in the application tier (like C#, Java, etc)

*Build T-SQL logic in a stored procedure or function to convert it to JSON yourself (but keep in mind that you won't be able to use "FOR JSON PATH" the exact same way 2016 does)

*Build CLR logic to do it (again, won't be compatible with "FOR JSON PATH")

A: In SQL Server 2012, you can use FOR XML. For my case, this was a viable alternative to JSON, since I was just passing the string to a browser.

A: Community wiki answer:
You can play with this but change the formatting for your JSON. This stores all the results as one item:
$server = 'Test'
$mainquery = sqlcmd -E -S $server -Q "set nocount on; select name,database_id,compatibility_level from sys.databases" -m 10 -h-1
$mainquery | convertto-json #-Depth 3

Alternatively, you can build your own functions as described in Producing JSON Documents from SQL Server queries via TSQL by Phil Factor.

A: Working solution to build JSON data out of SQL Server 2012
    DECLARE @TableName NVARCHAR(50)
    DECLARE @TempTableColumns TABLE (
        [Object_Id] NVARCHAR(100),
        [TableName] NVARCHAR(100),
        [ColumnName] NVARCHAR(100),
        [ColumnSequence] INT,
        [Type] NVARCHAR(100)
    )

    INSERT INTO @TempTableColumns ([Object_Id],[TableName],[ColumnName],[ColumnSequence],[Type])
    SELECT
        [T].[OBJECT_ID] [Object_Id]
        , [T].[Name]
        , [C].[Name] [ColumnName]
        , [C].[column_id] AS [ColumnSequence]
        , UPPER(CASE
            WHEN
                UPPER([ST].[Name]) = 'VARCHAR' OR UPPER([ST].[Name]) = 'NVARCHAR' THEN [ST].[Name] + '(' +  CASE WHEN CONVERT(VARCHAR,[C].[Max_Length]) = -1 THEN 'MAX' ELSE CONVERT(VARCHAR,[C].[Max_Length]) END + ')'
            ELSE [ST].[Name] END) [Type]
        FROM SYS.COLUMNS [C]
        INNER JOIN SYS.TYPES [ST] ON [C].[System_Type_Id] = [St].[System_Type_Id]
        INNER JOIN SYS.TABLES [T] ON [C].[OBJECT_ID] = [T].[OBJECT_ID]
        WHERE [ST].[Name] <> 'sysname'
    ORDER BY [T].[Name], [C].[column_id]

    SELECT
        [T1].[TableName],
        REPLACE('SELECT ROW_NUMBER() OVER (ORDER BY ' + (SELECT T3.ColumnName FROM @TempTableColumns T3 WHERE T3.TableName = T1.TableName AND T3.ColumnSequence = 1) + ' ASC) SequenceNumber, ''{' +
        STUFF((
            SELECT '"' + T2.ColumnName + '": '' + CASE WHEN ' + T2.ColumnName + ' IS NULL THEN ''NULL'' ELSE ''"'' + CONVERT(NVARCHAR(MAX), ' + T2.ColumnName + ') + ''"'' END  + '','
                FROM @TempTableColumns AS T2 WHERE T1.TableName = T2.TableName
                FOR XML PATH('')
        ),1, 0,'')  + '}'' DataResults FROM ['+ T1.TableName +'] WITH (NOLOCK)', ',}','}') AS [Query]

    FROM @TempTableColumns [T1]
    WHERE T1.TableName >= @TableName OR @TableName = ''
    GROUP BY [T1].[TableName]

The Output of queries would return Select statement as follows :
SELECT ROW_NUMBER() OVER (ORDER BY ID ASC) SequenceNumber, '{"ID": ' + CASE WHEN ID IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), ID) + '"' END  + ',"DatabaseName": ' + CASE WHEN DatabaseName IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), DatabaseName) + '"' END  + ',"SchemaName": ' + CASE WHEN SchemaName IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), SchemaName) + '"' END  + ',"ObjectName": ' + CASE WHEN ObjectName IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), ObjectName) + '"' END  + ',"ObjectType": ' + CASE WHEN ObjectType IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), ObjectType) + '"' END  + ',"IndexName": ' + CASE WHEN IndexName IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), IndexName) + '"' END  + ',"IndexType": ' + CASE WHEN IndexType IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), IndexType) + '"' END  + ',"StatisticsName": ' + CASE WHEN StatisticsName IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), StatisticsName) + '"' END  + ',"PartitionNumber": ' + CASE WHEN PartitionNumber IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), PartitionNumber) + '"' END  + ',"ExtendedInfo": ' + CASE WHEN ExtendedInfo IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), ExtendedInfo) + '"' END  + ',"Command": ' + CASE WHEN Command IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), Command) + '"' END  + ',"CommandType": ' + CASE WHEN CommandType IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), CommandType) + '"' END  + ',"StartTime": ' + CASE WHEN StartTime IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), StartTime) + '"' END  + ',"EndTime": ' + CASE WHEN EndTime IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), EndTime) + '"' END  + ',"ErrorNumber": ' + CASE WHEN ErrorNumber IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), ErrorNumber) + '"' END  + ',"ErrorMessage": ' + CASE WHEN ErrorMessage IS NULL THEN 'NULL' ELSE '"' + CONVERT(NVARCHAR(MAX), ErrorMessage) + '"' END  + '}' DataResults FROM [CommandLog] WITH (NOLOCK)

and when you run individual queries returned from above. Would give you the output as follows :

{"ID": "79143","DatabaseName": "msdb","SchemaName": NULL,"ObjectName": NULL,"ObjectType": NULL,"IndexName": NULL,"IndexType": NULL,"StatisticsName": NULL,"PartitionNumber": NULL,"ExtendedInfo": NULL,"Command": "DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N'G:\Backup\AWS19WVSQL072\msdb\FULL' IF @ReturnCode <> 0 RAISERROR('Error creating directory.', 16, 1)","CommandType": "xp_create_subdir","StartTime": "Jul 18 2020  1:00AM","EndTime": "Jul 18 2020  1:00AM","ErrorNumber": "0","ErrorMessage": NULL}

{"ID": "79144","DatabaseName": "msdb","SchemaName": NULL,"ObjectName": NULL,"ObjectType": NULL,"IndexName": NULL,"IndexType": NULL,"StatisticsName": NULL,"PartitionNumber": NULL,"ExtendedInfo": NULL,"Command": "BACKUP DATABASE [msdb] TO DISK = N'G:\Backup\AWS19WVSQL072\msdb\FULL\AWS19WVSQL072_msdb_FULL_20200718_010056.bak' WITH CHECKSUM, NO_COMPRESSION","CommandType": "BACKUP_DATABASE","StartTime": "Jul 18 2020  1:00AM","EndTime": "Jul 18 2020  1:01AM","ErrorNumber": "0","ErrorMessage": NULL}


text:
Q: Possible implications of points, planes, and planes having no actual "size". Even though we depict points, lines, and planes with some sort of thickness when drawn, they are said to have no thickness whatsoever.
Is there any paradoxical or interesting implications of this property of these three geometric objects?
Moreover, all geometric objects are said to consist of points. How do we prove or demonstrate/ justify that lines and planes have infinitely many points. Or do we simply use our intuition/axiom to justify these claims?