text:
Q: How lack of information changes state? Suppose two orthonormal states $|\psi_0\rangle$ and $|\psi_1\rangle$ are kept in two separate boxes. If we know which box shares which state, the state of the composite system is $|\psi_0\rangle |\psi_1\rangle$. But if this information is not available what is the state of the composite system ?

A: If you have incomplete information about your system, then you can no longer consider the system to be in a pure state, and you need to describe the resulting mixed state as a density matrix that's a convex combination of the full-information states
$$
\rho_{01}=|\psi_0\rangle\langle\psi_0|\otimes|\psi_1\rangle\langle\psi_1|
$$
and
$$
\rho_{10}=|\psi_1\rangle\langle\psi_1|\otimes|\psi_0\rangle\langle\psi_0|.
$$
How you mix them will depend on how much information you have about where each state went, and if you really have no information at all then you should use the even-weights mixture
$$
\rho=\frac12\bigg(
|\psi_0\rangle\langle\psi_0|\otimes|\psi_1\rangle\langle\psi_1|
+
|\psi_1\rangle\langle\psi_1|\otimes|\psi_0\rangle\langle\psi_0|
\bigg).
$$
It's important to note, on the other hand, that this is rather different to coherent superpositions of the form $|\psi\rangle = \frac{1}{\sqrt{2}}\bigg( |\psi_0\rangle|\psi_1\rangle + |\psi_1\rangle |\psi_0\rangle \bigg)$, where the information isn't just unavailable - it just doesn't exist.


text:
Q: Roslyn: Reconstruct code from BasicBlocks in a CFG In Roslyn, a control flow graph has the list of BasicBlocks which constitute the program. Is it possible to get code statements from each block to reconstruct the entire code?

A: This is not possible using Roslyn's in-built methods in my knowledge.
I achieved a similar result by constructing a dictionary of blocks and sets of line numbers corresponding to those blocks using string matching. Additional filtering done to the same in order to improve accuracy in case of blocks that include locks etc.
The result is not 100 percent accurate, but it comes pretty close in most cases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Orthogonal Vectors in $\Bbb R^n$ where $n>3$ While studying orthogonality and orthonormal bases, I found it hard to conceptualize orthogonal vectors in a Vector Space over $\Bbb R^n$ with $n>3$. In $\Bbb R^3$, we get the set of orthogonal vectors similar to the x,y,z axes.
In $\Bbb R^3$, vectors are orthogonal to planes, computed by looking at the vector's projection onto a plane(s). However, in $\Bbb R^4$, we are no longer looking at the projection onto a plane but rather the projection onto a vector space in $\Bbb R^3$?
So to find orthongonal vectors you would need to find the projection onto the span of three vectors in $\Bbb R^4$?

A: Rule is that the sum of dimensions of orthogonal subspaces is the dimension of the ambient space.
So since in $\mathbb{R}^3$ you have 3 dimensions, the orthogonal space of a vector (which is a 1 dimensional object) is a plane, because 3-1 = 2 and the plane is 2 dimensional  . So any object inside the plane orthogonal to that vector is orthogonal to the vector. Vectors in $\mathbb{R}^3$ can be orthogonal to other vectors, to lines, and ultimately to planes.
(Example: if I consider the vector $a = (0,0,1)$ his orthogonal plane is $\pi = \{z = 0\}$ which consists of the vectors $(x,y,0)$ with random $x$ and $y$. Hence the plane $\pi$ is orthogonal to $a$, and any vector inside $\pi$ is also orthogonal to $a$.)
Hence in $\mathbb{R}^4$, since you have 4 dimensions, the space orthogonal to a vector is a 3 dimensional space. (Ex:vector $(0,0,0,1)$ and space $(x,y,z,0)$ are orthogonal.
Yes, in $\mathbb{R}^4$ to find a vector orthogonal to a 3 dimensional space, you have to see if the projection of that vector on the span of 3 vectors generating your space is 0.


text:
Q: Filling a page with figures I have a text and then a bunch of figures. I would like to fill A page with all the figures so the text would continue AFTER this page. In other words I would need something like this :
Page 1 : text
Page 2 : Figures (don't want any text)
Pages 3 : following of text of Page 1
Thank you in advance !

A: Try using the placeins package.
\usepackage{placeins}
\begin{document}
page 1, text

\pagebreak
\FloatBarrier % This command was enabled by placeins. The floating figure will not pass it.
\begin{figure}
...
\end{figure}
\pagebreak
\FloatBarrier

page 3, text
\end{document}

The placeins package enables the use of \FloatBarrier (must use capital F and B). Floating figures will not pass over \FloatBarrier.


text:
Q: C# checking if more files have one of more of these strings it's me again , your boi...
Stuck with another problem I didn't find anywhere else strangely...
This is the code I possess in order to check if files in a directory and subdirectiories have a certain string. If they do, I'll add a string at the bottom of the file...
I followed for most part the documentation on Microsoft Docs.
public class OFiles
{
    public string PathProgetto
    {
        get;
        set;
    }

    public void Change()
    {

        try
        {
            string docPath = PathProject;

            var files = from file in Directory.EnumerateFiles(docPath, "*.h", SearchOption.AllDirectories)
                        from line in File.ReadLines(file)
                        where line.Contains("String I want")
                       // where line.Contains("Other String I want")
                       // where line.Contains("Another String I want")

                        select new
                        {
                            File = file,
                            Line = line
                        };

            System.Collections.ArrayList arr = new System.Collections.ArrayList();
            foreach (var f in files)
            {
                arr.Add(f.File.ToString());

            }
            string sNuovaRiga = "This One";
            foreach (var s in arr)
            {
                File.AppendAllText(s.ToString(), "\r\n" + sNuovaRiga);
            }
            Console.WriteLine($"{files.Count().ToString()} files found and modified.");
        }

        catch (UnauthorizedAccessException uAEx)
        {
            Console.WriteLine(uAEx.Message);
        }
        catch (PathTooLongException pathEx)
        {
            Console.WriteLine(pathEx.Message);
        }

    }
}

You'll notice that there are other strings I want my program to check. The problem is that I have no idea how to do it, I only know that the way I did it I cannot do it with another WHERE so I'm asking here. Ask me anything unclear and thanks in advance

A: I want to close this question, so I'll just answer it.
As @elgonzo suggested, in this particular all I had to do was putting || when I had to choose between the strings.


text:
Q: Why does Gmail API fail with a 403 error, using code that works properly for Google Calendar API? I'm following these guides: https://developers.google.com/google-apps/calendar/quickstart/python, https://developers.google.com/gmail/api/quickstart/python.
I've completed all the setup steps for both, and the calendar API code works fine, while the Gmail API code fails with a 403 error. What's causing this? What's different between these two APIs?
I've combined the code from these two different examples, so they are sharing as much of the API setup code as possible, to rule out a mistake there.
I've disabled and re-enabled Gmail API in Google Dev Console.
As mentioned here, I've enabled the Contacts and Google+ APIs.
As mentioned here, I've tried all three combinations for Gmail scopes - just the scope from the example, just 'https://mail.google.com/', or both.
This answer, as well as several other sources, suggest 'setting the "Referers" to "Any referer allowed"', but there is no page in Dev Console I can find that contains this option. I can add a domain through the "domain verification" tab, but this does not seem to affect anything.
Code:
import httplib2
import os
from pprint import pprint

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

import datetime

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

class GoogleApi(object):
    client_secret_file = 'client_secret.json'
    application_name = 'test_app'

    def __init__(self):
        self.credentials = self.get_credentials()
        self.http = self.credentials.authorize(httplib2.Http())
        self.service = discovery.build(self.api_name, self.api_version, http=self.http)

    def get_credentials(self):
        """Gets valid user credentials from storage.

        If nothing has been stored, or if the stored credentials are invalid,
        the OAuth2 flow is completed to obtain the new credentials.

        Returns:
            Credentials, the obtained credential.
        """
        home_dir = os.path.expanduser('~')
        credential_dir = os.path.join(home_dir, '.credentials')
        if not os.path.exists(credential_dir):
            os.makedirs(credential_dir)
        credential_path = os.path.join(credential_dir,
                                       'test-app.json')

        store = oauth2client.file.Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self.client_secret_file, self.scopes)
            flow.user_agent = self.application_name
            if flags:
                credentials = tools.run_flow(flow, store, flags)
            else:  # Needed only for compatability with Python 2.6
                credentials = tools.run(flow, store)
            print 'Storing credentials to ' + credential_path
        return credentials

class CalendarApi(GoogleApi):
    scopes = 'https://www.googleapis.com/auth/calendar.readonly'
    api_name = 'calendar'
    api_version = 'v3'

    def get_calendar_ids(self):
        cl = self.service.calendarList().list().execute()
        ids = [x['id'] for x in cl['items']]
        return ids

class GmailApi(GoogleApi):

    scopes = 'https://mail.google.com/'
    #scopes = 'https://www.googleapis.com/auth/gmail.readonly'
    api_name = 'gmail'
    api_version = 'v1'

    def get_labels(self):
        ml = self.service.users().labels().list(userId='me').execute()
        labels = results.get('labels', [])
        return labels

def main():
    cc = CalendarApi()
    ids = cc.get_calendar_ids()
    print(ids)

    m = GmailApi()
    labels = m.get_labels()
    print(labels)

if __name__ == '__main__':
    main()

Current error ("Insufficient Permission"):
Traceback (most recent call last):
  File "gmail_api_test.py", line 92, in <module>
    main()
  File "gmail_api_test.py", line 87, in main
    labels = m.get_labels()
  File "gmail_api_test.py", line 76, in get_labels
    ml = self.service.users().labels().list(userId='me').execute()
  File "/usr/local/lib/python2.7/site-packages/oauth2client/util.py", line 140, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/googleapiclient/http.py", line 729, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Insufficient Permission">

Error from a previous version of the code ("Access Not Configured. The API (Gmail API) is not enabled for your project. Please use the Google Developers Console to update your configuration."):
Traceback (most recent call last):
  File "gmail_demo.py", line 71, in <module>
    main()
  File "gmail_demo.py", line 59, in main
    results = service.users().labels().list(userId='me').execute()
  File "/usr/local/lib/python2.7/site-packages/oauth2client/util.py", line 142, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/googleapiclient/http.py", line 729, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/gmail/v1/users/me/labels?alt=json returned "Access Not Configured. The API (Gmail API) is not enabled for your project. Please use the Google Developers Console to update your configuration.">

A: The reason why the permission is still insufficient is because the refresh_token in your file is still valid. The access_token and refresh_token you get when authenticating your users only have the scopes you specify at that time.
Just imagine if that was not the case. You could then ask your users for readonly and later add the all encompassing https://mail.google.com/-scope and do a lot of additional stuff without the user's consent.

A: This has been answered more thoroughly here:
How do I get around HttpError 403 Insufficient Permission? (gmail api, python)
Even though your question deals with the google calendar API, the 403 error is similar to many of the google API apps.


text:
Q: Property 'byName' does not exist on type '{}' error So, I was trying out typescript, in the mongoose website i could see guide for typescript, to analyize the code, I copied a snippet from the official documentation.
import { Document, Model, Query, Schema, connect, model } from 'mongoose';

interface Project {
  name: string;
  stars: number;
}

const schema = new Schema<Project>({
  name: { type: String, required: true },
  stars: { type: Number, required: true }
});
// Query helpers should return `Query<any, Document<DocType>> & ProjectQueryHelpers`
// to enable chaining.
interface ProjectQueryHelpers {
  byName(name: string): Query<any, Document<Project>> & ProjectQueryHelpers;
}

// The error is on the below line, it says Property 'byName' does not exist on type '{}'

schema.query.byName = function(name): Query<any, Document<Project>> & ProjectQueryHelpers {
  return this.find({ name: name });
};

// 2nd param to `model()` is the Model class to return.
const ProjectModel = model<Project, Model<Project, ProjectQueryHelpers>>('Project', schema);

run().catch(err => console.log(err));

async function run(): Promise<void> {
  await connect('mongodb://localhost:27017/test');

  // Equivalent to `ProjectModel.find({ stars: { $gt: 1000 }, name: 'mongoose' })`
  await ProjectModel.find().where('stars').gt(1000).byName('mongoose');
}

I am not sure why this error has occured, can someone help me out? When inspecting the schema object I could see the query was { }. But why so?

A: I think that your problem is a typescript version, I am using v4.5.4 and everthing ok.
try this, please:

(schema as Schema<Project> & { query: ProjectQueryHelpers }).query.byName = function (
  name: string
): Query<any, Document<Project>> & ProjectQueryHelpers {
  return this.find({ name: name });
};


text:
Q: How to get a D3.js pie chart to render data dynamically from the DOM I'm trying to make a pie chart using D3.js that changes once the submit button has been clicked on in the HTML form (asking for total count of females and males).
This is what I have so far for the JavaScript file:
// Data
function getTotalFemales() {
    let total = document.getElementById('totalFemales').value;
    totals.push(parseFloat(total));
}

function getTotalMales() {
    let total = document.getElementById('totalMales').value;
    totals.push(parseFloat(total));
}

let totals = [];

// Dataset
var dataset = [
    {label: 'Female Count', count: 1},
    {label: 'Male Count', count: 1}
];

function updateChart() {
    dataset.count.forEach(function(num)
        dataset.count = totals[num]
    });

    console.log(totals);
}

and this is the d3 part:
var path = pieChart.selectAll('path')
        .data(pie(dataset))
        .enter()
        .append('path')
        .attr('d', arc)
        .attr('fill', function(d, i) {
        return color(d.data.label);
    });

Any idea on how I can get the count property in the dataset array to change depending on the user's form values?

A: Take the input values and directly put them into the dataset. I don't see the need for the totals array.
And set the properties of the dataset array of objects,
  var dataset = [
    {label: 'Female Count', count: 1},
    {label: 'Male Count', count: 1}
];

    function getTotals() {
        dataset[0].count = document.getElementById('totalFemales').value;
        dataset[1].count = document.getElementById('totalMales').value;
    }


text:
Q: prove or disprove invertible matrix with given equations Given a non-scalar matrix $A$ in size $n\times n$ over $\mathbb{R}$ that maintains the following equation
$$A^2 + 2A = 3I$$
given matrix $B$ in size $n\times n$ too $$B = A^2 + A- 6I$$
Is $B$ an invertible matrix?

A: An alternative version to the other excellent answers by Quark and user1551.
Note first, as the others did, that $(A + 3 I) (A - I) = 0$, and $B = (A - 2 I)(A + 3 I)$.
Then
$$
B (A - I) = 0.
$$
So if $A \ne I$, then $B$ is definitely not invertible.
If $A = I$, as noted by Quark, then $B = -4 I$ is invertible.
But Tharsis (thanks!) made me notice that $A$ is non-scalar by assumption, so the case $A = I$ is excluded (although easy to deal with).

A: It depends, If you factorize the first equation you get,
$$(A-I)*(A+3I)=0$$
This implies$\; \det(A-I)\;\; or\;\; \det(A-3I)\;$ must be zero.
Now factorizing B gives you (A-2I)*(A+3I)
So $\det(B) = \det(A-2I)*\det(A+3I)$
If $\det(A-3I)$ is zero from the first condition, then $\det(B)$ is also zero, so B is not invertible.
But, if $\det(A-I)$ is zero and not $\det(A-3I)$, I don't think anything can be said
(not very sure, but I can give a example: If you take A=I, the first equation is satisfied, and B comes out to be -4I which is invertible...)

A: Hint: The first equation implies that $A^2+2A-3I=(A-I)(A+3I)=0$. Hence the minimal polynomial $m_A(x)$ of $A$ divides $(x-1)(x+3)$. What happens if $x+3$ is not a factor of $m_A(x)$?


text:
Q: Headings don't collapse in MS Word I am using Office 365. I have styled a document with body text, Heading One, Heading Two etc.
I want to be able just to see the Heading Ones. I click right click the Heading One and then Expand/Collapse and then collapse all headings.
I should just be able to see the Headings 1s. However, nothing happens. I see all the formatting.
Am I doing something wrong?
Thank you.


text:
Q: Recording event data problem in google analytics ecommerce I'm implementing enhanced ecommerce in Google Analytics and I have a problem.
When the purchase of a product is made, it's redirected to a thanks page and that's where the Purchase event is sent to Analytics.
ga('require', 'ec');
ga('set', 'currencyCode', 'EUR');
ga('ec:addProduct', {
    'id': 'prueba-001',
    'name': 'Prueba',
    'brand': 'Prueba',
    'category': 'Prueba',
    'variant': 'Prueba',
    'price': 10.50
});
ga('ec:setAction', 'purchase', {
    'id': 't-prueba-01',
    'revenue': 5.50
});
ga('send', 'pageview');

The 'purchase' event is recorded perfectly, but the addProduct event is not quite right, the unique purchases of each product are registered but nothing else.

I don't know what else to do, I have followed the steps in the documentation and the problem persists.
Edit:
Sales report

A: Try to use quote for price and revenue (for consistency with the documentation) and above all add the quantity parameter to the product.


text:
Q: Configure gatsby-source-filestystem to query a single json file I'm trying to follow the readme from https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-transformer-json
I have a links.json that contains a list of (external) Links that I want to query. For each of these links, I want to create a page. Now I'm trying to query the links with
{
  allLinksJson {
    edges {
      node {
        value
      }
    }
  }
}

which fails. According to this post on github, apparently my gatsby-source-filesystem isn't configured correctly. I tried with
{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/src/data/links.json`,
    name: "links",
  },
},

but it didn't work. Unfortunately I cannot find any articles or documentation about how to make this work. Any help would be appreciated.

A: You don't need the full path to the json file. You also need to include gatsby-transformer-json plugin.
  plugins: [
    'gatsby-plugin-react-helmet',
    `gatsby-transformer-json`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `./src/data/`,
      },
    }
  ]


text:
Q: Changing label (wrong reverse) direction using QGIS I use QGIS 3.22.2 and I want to have nice curved labels (along lines): Llyn Brenig Reservoir (currently there are two different labels: Llyn Brenig and Reservoir). Problem is that label Reservoir is displayed in wrong (reverse) direction, as the picture shows.
How I can change reverse direction of label Reservoir to same direction as label Llyn Brenig (as the picture shows)?

A: From the label toolbar you can move and rotate labels.
If the label toolbar is not visible it can be activated via:
View > Toolbars > Label Toolbar


text:
Q: Custom config section with recursive ConfigurationElement I am trying to create a custom configuration section that represents the following xml structure:
<observerSettings>
   <jobSettings>
      <filter key="location" value="de">
        <filter key="type" value="MyType1">
          <filter key="status" value="failed">
            <actions>
              <notify timespan="12.00:00:00">
                <mailSettings>
                  <mailAddress to="mail1@something.com" />
                  <mailAddress to="mail2@something.com" />
                </mailSettings>
              </notify>
              <remove timespan="14.00:00:00">
                <mailSettings>
                  <mailAddress to="mail1@something.com" />
                  <mailAddress to="mail2@something.com" />
                </mailSettings>
              </remove>
            </actions>
          </filter>
        </filter>
      </filter>
   </jobSettings>
</observerSettings>

The FilterConfigElement is defined like this:
internal class FilterConfigElement : ConfigurationElement, IFilterConfigElement
{
        [ConfigurationProperty("filter", IsRequired = false)]
        public FilterConfigElement ChildFilter => base["filter"] as FilterConfigElement;

        [ConfigurationProperty("actions", IsRequired = false)]
        public ActionsConfigElement Actions => base["actions"] as ActionsConfigElement;

        [ConfigurationProperty("key", IsRequired = true)]
        public string Key => base["key"] as string;

        [ConfigurationProperty("value", IsRequired = false)]
        public string Value => base["value"] as string;
}

When accessing the config section like below, the application is crashing with a StackOverflow exception:
internal class ObserverSettings : ConfigurationSection, IObserverSettings
{
   public static IObserverSettings Instance { get; private set; } = ConfigurationManager.GetSection("observerSettings") as ObserverSettings;

   [ConfigurationProperty("jobSettings")]
   protected JobSettingsCollection JobSettingsCollection => base["jobSettings"] as JobSettingsCollection;

   public virtual IJobSettingsCollection JobSettings => JobSettingsCollection;
}

So I assume ConfigurationManager is creating this structure with infinite depth and not stopping when the last filter element is reached. Can this be limited somehow? Is such structure even supported?

A: Ok, after digging through the implementation of ConfigurationElement it seems to be not possible at all to create recursive structures the way I tried.
Cause of the problem is the implementation of PropertiesFromType where assignment of the properties to s_propertyBags is done after the call to CreatePropertyBagFromType and thus creating an endless recursion where properties is always null.
private static bool PropertiesFromType(Type type, out ConfigurationPropertyCollection result)
{
   ConfigurationPropertyCollection properties = (ConfigurationPropertyCollection)s_propertyBags[type];
   result = null;
   bool firstTimeInit = false;
   if (properties == null) /*code omitted*/
   {
      properties = CreatePropertyBagFromType(type);
      s_propertyBags[type] = properties;
      firstTimeInit = true;
   }
   result = properties;
   return firstTimeInit;
}

Source: https://referencesource.microsoft.com/#System.Configuration/System/Configuration/ConfigurationElement.cs
Edit:
Only workaround to keep some kind of "recursive" structure was to wrap all child FilterConfigElements into a ConfigurationElementCollection with element name childFilter. This leads to following not so nice but acceptable config structure:
<jobSettings>
  <filter key="location" value="de">
    <childFilter>
      <filter key="type" value="MyType1">
        <childFilter>
          <filter key="status" value="failed">
            <actions>
              <!-- ... -->
            </actions>
          </filter>
        </childFilter>
      </filter>
    </childFilter>
  </filter>
</jobSettings>

Source: Recursive Custom Configuration in c#


text:
Q: Angular Schematics confusion Not sure to fully understand a concept with Angular Schematics. More precisly how to execute a schematic.
Reading from some articles, I saw that we have to use ng g my-schematics-collection:simple-schematic --name="some name".
In other articles I saw schematics  my-schematics-collection:simple-schematic --name="Angular Community".
And again using NX, they simple use ng g component, exactly like the base Angular Schematics to create a component. How can they overwrite the existing Angular Schematics? The fact that they doesn't point to their own schematics collection confuses me.
Can someone explain what to use for what use cases?
Thanks!

A: Angular schematics is just a library. There are different tools that use the library. You can read more about what is expected from the tooling in the docs.
When using ng g my-schematics-collection:simple-schematic --name="some name" you are using the tooling provided by angular-cli.
When using schematics  my-schematics-collection:simple-schematic --name="Angular Community" you are using the reference cli tooling.
Both tools leverage nodejs module resolution to find schematic files. So my-schematics-collection is actually a name of a node_module. For example the default angular schematics are defined in this module. Notice that in the package.json there's a key called schematics. It will point to a json configuration file.
So in general if you are using Angular, stick with the angular-cli tooling. If you are developing custom schematics, the reference CLI is useful for testing. If you don't mind writing some custom tooling, then you can just import the library directly.

A: It's very easy to understand, when you are development the schematics you would like to test your schematic using the schematics word and you need to specify these stuff:
schematics [schematic-path-of-your-project]:[schematic-name] --[flags]
For example:

*

*schematics .:add-custom-component --debug=false --> this if you are creating a project like library and you would like to test inside the project.

*schematics ./projects/schematics:add-custom-component --debug=false --> this if you are creating the schematics inside your angular project.
However, when you already finished your schematics you need to do different things depends on if you are creating a library or creating schematics inside the project:

*

*If you are creating a Schematics like a library you need to create an schematic named: ng-add, when you are in the project that you want to add it, you need to execute: ng add @hyperxq/schematics;

*If you are creating a schematic inside your project you need to compile the schematic and in your angular project execute: npm link ./projects/schematics/dist. After that you need only to execute: ng g @hyperxq/schematics:add-custom-component.

:) I hope that help you to understand schematics.


text:
Q: DQL for selecting a row in a x-to-x relationship I have 3 different entities that are mapped to each other. To give a very simplified example.
ProductList:
class ProductList
{
    /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="productlist") */
    protected $products;
}

Product:
class Product
{
    /**
     * @ORM\ManyToOne(targetEntity="Edition")
     * @ORM\JoinColumn(name="edition_id", referencedColumnName="id")
     */
    protected $edition;

    /**
     * @ORM\ManyToOne(targetEntity="ProductList")
     * @ORM\JoinColumn(name="productlist_id", referencedColumnName="id")
     */
    protected $productlist;
}

Edition
class Edition
{
    protected $id;
}

How can I get all the productLists in my productListRepository that contain only 1 product with an specific edition id using DQL?
I know how to do it the 'lazy' way by retrieving all the items from the productList and check whether the related product entity contains an specific edition id but this seems highly ineffective if there is a large dataset to iterate through.
I know I have to use a join but I am stuck at the idea that I need to iterate through the products in productLists. ProductLists can contain more then one products but I only need the ones with only a single product and check wether they have an edition with the specific id.

A: Try this for extract all the productlist for a specified version that have only one edition:
SELECT pl
FROM ProductList pl
-- LEFT JOIN pl.products p
LEFT JOIN p.edition e
WHERE (sum (p1) from Product p1 where  p1.productlist = pl.id) = 1

Hope this help


text:
Q: How to read consecutive .plt files and store them I have 1000 files that I want to read with python. Before, I had 74 and I just read them one by one, but now there are too much to do so.
data_1 = np.genfromtxt('test4-1.000001.plt', delimiter=' ', skip_header=3)
data_2 = np.genfromtxt('test4-1.000002.plt', delimiter=' ', skip_header=3)
data_3 = np.genfromtxt('test4-1.000003.plt', delimiter=' ', skip_header=3)
data_4 = np.genfromtxt('test4-1.000004.plt', delimiter=' ', skip_header=3)
data_5 = np.genfromtxt('test4-1.000005.plt', delimiter=' ', skip_header=3)
data_6 = np.genfromtxt('test4-1.000006.plt', delimiter=' ', skip_header=3)
data_7 = np.genfromtxt('test4-1.000007.plt', delimiter=' ', skip_header=3)
.
.
.
.
.
data_73 = np.genfromtxt('test4-1.000073.plt', delimiter=' ', skip_header=3)
data_74 = np.genfromtxt('test4-1.000074.plt', delimiter=' ', skip_header=3)

I have tried to use a loop for, but it doesn't work. I tried to make i be a string, but still didn't work
for i in range(1:1000):
     data_'i' = np.genfromtxt('test4-1.00000'i'.plt', delimiter=' ',skip_header=3)

Thank you very much for the help

A: You kinda have the right idea but you made a few syntax mistakes, and it looks like you need to learn about lists.
What you should do is make a list of all your data. Lets call it data.
We define an empty like like this: data = []
To add to a list we use the append command like this:
data.append(np.genfromtxt('test4-1.000001.plt', delimiter=' ',skip_header=3))

The last thing is you were trying to concatenate your strings wrong. In python you concatenate strings with a + so this line: 'test4-1.00000'i'.plt' should be 'test4-1.'+str(i).zfill(6)+'.plt'. Note I had to turn it into a string first and I also used the zfill function to pad it with zeros.
Putting all this together we have the code
data = []
for i in range(1:1000):
    data.append(np.genfromtxt('test4-1.'+str(i).zfill(6)+'.plt', delimiter=' ',skip_header=3))

This will leave you with a list of data that you can call from using the syntax data[23] to get the 24th data set (list indexing starts at 0).
Hope this helped!

A: data = []
for i in range(1, 1000):
     data.append(np.genfromtxt('test4-1.%06d.plt' % i, delimiter=' ',skip_header=3))

Edit
Loocid's answer explains how each part of this works.


text:
Q: How to skip word in YASM (8086) I've been working on the project. The main goal is to calculate how many words do not contain letters 'B' nor 'C'. Given file has [0;1000] lines. Every line contains 6 columns.
he first two columns contain string with [1; 20] characters. Characters could be letters, numbers, and whitespaces.
3-5 columns contain integers in the range [-100; 100]. 6th column contain real numbers in range [-9.99; 9.99] with only two digits after decimal point.
Each section I separated by a semicolon ';'.
FILE EXAMPLE:
helloA;lB;lC;lD;lE;lF
A11;bas morning;0;0;5;1.15
B12; Hello WoRlD;-100;11;78;1.33
B11;table;10;0;55;-2.44
C1;OakWood;0;8;17;3.77

TASK: calculate how many words (word is one or more symbols without ' '(space)) in the first two columns do not contain letters 'B' or 'C'. And print that integer number.
I have dealt with the most part of the task. I already did File's name reading from command line, reading the file, priting the integer out. But I have stuck on one thing. I don't really get it how to check every word one by one. I almost every time get a wrong answer.
Input: ( a A a a aba aca;BA A C BA a;1;1;1;1.00) - without brackets.
Output: 6

MY CODE SO FAR
org 100h

%include 'yasmmac.inc'

section .text

    startas:
        macPutString 'Write outpu file name', crlf, '$'

        ; Reading file from command line
        .commandLine:
            mov bx, 82h
            mov si, 0h
            jmp .checkInputFile

        ; Turns it into ASCIIZ
        .checkInputFile:
            mov cl, [bx+si]
            cmp cl, 20h
            jl .addZero
            inc si
            jmp .checkInputFile

        .addZero:
            mov byte [bx+si], 0h
            xor si, si

            ; Saving writing file
        mov al, 128
        mov dx, writingFile
        call procGetStr
        macNewLine

        ; Open reading file
        mov dx, bx
        call procFOpenForReading
        jnc .writingFileIsOpened
        macPutString 'Error while opening reading file', '$'
        exit

        ; Atidarome rasymo faila
        .writingFileIsOpened:
            mov [readingDescriptor], bx
            mov dx, writingFile
            call procFCreateOrTruncate
            jnc .openWritingFile
            macPutString 'Error while opening writing file', '$'
            jmp .writingError

        ; Save writing descriptor
        .openWritingFile:
            mov [writingDescriptor], bx

        ; Reads first line
        call procReadLine

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

        ; Main loop
        .whileNotEndOfFile:
            xor di, di
            xor si, si
            call procReadLine

            ; Check first two columns
            ;mov al, ';'

        mov di, line
        mov al, [di]
        cmp al, ' '
        je .nextWord
        cmp al, ';'
        je .nextWord

            ; Checking words
            .checkWord:
                mov al, [di]
                inc di

                cmp al, byte 'B'
                je .nextWord
                cmp al, byte 'b'
                je .nextWord
                cmp al, byte 'C'
                je .nextWord
                cmp al, byte 'c'
                je .nextWord

                cmp al, byte ' '
                je .addNumber
                cmp al, byte ';'
                je .semicolon
                jmp .checkWord

            .nextWord:
                call procNextWord
                jmp .checkWord

            .semicolon:
                call procAddNumber
                inc si
                cmp si, 0x2
                je .skipLine
                jmp .nextWord

            .addNumber:
                call procAddNumber
                jmp .nextWord

            ; If this is not the end of file, repeat loop
            .skipLine:
            cmp [readLastLine], byte 0
            je .whileNotEndOfFile

            ; Hexadecimal convertion to decimal
           mov dx, lineCount
           mov ax, [lineCount]
           call procUInt16ToStr
           call procPutStr
           macNewLine
           mov si, dx

           .writingToFile:
           lodsb
           cmp al, 0
           jne .writingToFile
           sub si, dx
           lea cx, [si-1]
           mov bx, [writingDescriptor]
           mov ah, 40h
           int 21h

        ; Closing Files
        .end:
            mov bx, [writingDescriptor]
            call procFClose

        .writingError:
            mov bx, [readingDescriptor]
            call procFClose

        macPutString 'Program ends', crlf, '$'

        exit

%include 'yasmlib.asm'

; void procReadLine()
; Read line to buffer 'eilute'
procReadLine:
    push ax
    push bx
    push cx
    push si

    mov bx, [readingDescriptor]
    mov si, 0

    .loop:
        call procFGetChar

        ; End if the end of file or error
        cmp ax, 0
        je .endOfFile
        jc .endOfFile

        ; Putting symbol to buffer
        mov [line+si], cl
        inc si

        ; Check if there is \n?
        cmp cl, 0x0A
        je .endOfLine

        jmp .loop

    .endOfFile:
        mov [readLastLine], byte 1
    .endOfLine:

    mov [line+si], byte '$'
    mov [lineLenght], si

    pop si
    pop cx
    pop bx
    pop ax
    ret

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

procAddNumber:
    push si
    push ax
    push bx
    push cx
    push dx

    ;lineCount++
    mov ax, word [lineCount]
    inc ax
    mov [lineCount], ax

    pop dx
    pop cx
    pop bx
    pop ax
    pop si
    ret

procNextWord:

    .loop:
        inc di
        mov al, [di]
        cmp al, byte ' '
        je .loop
        jmp .t

    .t:
        cmp al, byte ';'
        je .t2
        jmp .return

    .t2:
        inc di
        mov al, [di]
        cmp al, byte ' '
        je .t2
        jmp .return

    .return:
        ret

section .data

    readingDescriptor:
        dw 0000

    writingFile:
        times 128 db 00

    writingDescriptor:
        dw 0000

    readLastLine:
        db 00

    line:
        db 64
        times 66 db '$'

    lineLenght:
        dw 0000

    lineCount:
        times 128 db 00

GITHUB: yasmmac.inc/yasmlib.asm
Any help will be appreaciated.

A: Completely starting over on the thinking process that is needed to solve the main task, I came up with the following:

*

*Before checking the character in a word, I skip all the leading whitespace (if present at all)

*If the leading whitespace ends with a semicolon, it is rather the trailing whitespace from the last word in the current column

*A word ends when finding a space or a semicolon

*.checkWord does not early-out on finding an invalid character {BbCc}, but sets a flag to 0

; Main loop
.whileNotEndOfFile:
  call procReadLine
  mov  si, 2       ; Do 2 columns
  mov  di, line
.skipSpaces:
  mov  al, [di]
  inc  di
  cmp  al, ' '
  je   .skipSpaces
  cmp  al, ';'
  je   .q3         ; It's trailing whitespace
  dec  di
.checkWord:
  mov  bx, 1       ; Assuming it will be a 'good' word
.q1:
  mov  al, [di]
  inc  di
  cmp  al, ' '
  je   .q2
  cmp  al, ';'
  je   .q2
  or   al, 32      ; LCase
  cmp  al, 'b'
  jb   .q1
  cmp  al, 'c'
  ja   .q1
  xor  bx, bx      ; One or more invalid chars in current word
  jmp  .q1

.q2:
  add  [lineCount], bx  ; BX=[0,1] Counting the 'good' words
  cmp  al, ';'
  jne  .skipSpaces
.q3:
  dec  si          ; Next column ?
  jnz  .skipSpaces
.skipLine:
  cmp  [readLastLine], byte 0
  je   .whileNotEndOfFile

The label lineCount is no longer particularly good for counting valid words, wouldn't you say?

A:
    mov al, [di]
    cmp al, ' '         *
    je .nextWord        *
    cmp al, ';'         *
    je .nextWord        *
.checkWord:
    mov al, [di]
    inc di

You are losing characters from the string!
Consider eg. "mouse bat" where .checkWord will fetch the space character and leave DI pointing at the "b", but then procNextWord starts by incrementing DI, effectively erasing that "b" from inspection. The rest of the program only sees "at" and thinks it's a 'good' word.
procNextWord:
        dec  di         ; Correcting DEC
    .t1:
        inc  di
        mov  al, [di]
        cmp  al, ' '
        je   .t1
        cmp  al, ';'
        jne  .return
    .t2:
        inc  di
        mov  al, [di]
        cmp  al, ' '
        je   .t2
    .return:
        ret

If you apply the proposed correction, then also change the lines that I marked with asterisks and write:
    cmp  al, ' '
    je   .nextWordEx
    cmp  al, ';'
    je   .nextWordEx

    ...

.nextWordEx:
    inc  di
.nextWord:
    call procNextWord
    jmp  .checkWord

[edit]
When you found an unsuitable character in a word, you need to skip the remainder of that word and that is not something the procNextWord was build for! You need another code:
  cmp  al, 'B'
  je   .skipRemaining
  cmp  al, 'b'
  je   .skipRemaining
  cmp  al, 'C'
  je   .skipRemaining
  cmp  al, 'c'
  je   .skipRemaining

  cmp  al, ' '
  je   .addNumber
  cmp  al, ';'
  je   .semicolon
  jmp  .checkWord

.skipRemaining:
  call procSkipRemaining
  jmp  .checkWord

  ...

procSkipRemaining:
  mov  al, [di]
  cmp  al, " "
  je   .return
  cmp  al, ";"
  je   .return
  inc  di
  jmp  procSkipRemaining
.return:
  ret


text:
Q: Show/Hide LineGraph/BarGraph on checkbox listener, BarGraph not working. MPAndroidChart Android I am using MPANDROIDCHART library to show a chart,
in combine chart, I am showing Line chart and Bar Chart. My requirement is when  Line checkbox true it should show line and when Bar checkbox is true it should show barchart.
When I uncheck line checkbox Line chart should hide.
and when uncheck bar checkbox bar chart should hide.
My code is working in case of Line but in case of Bar chart, it is not working I am getting the Nullpointer exception.
Below is my code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:orientation="vertical"
   android:layout_height="match_parent"
   tools:context="com.swytch.chartdemo.MainActivity">

   <LinearLayout
      android:layout_width="wrap_content"
      android:layout_height="wrap_content">

    <CheckBox
        android:id="@+id/chechbToken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="line" />

    <CheckBox
        android:id="@+id/chechbEnergy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bar" />

</LinearLayout>

  <com.github.mikephil.charting.charts.CombinedChart
      android:id="@+id/chart1"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

</LinearLayout>

MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private CombinedChart mChart;
    private final int itemcount = 12;
    private CheckBox chechmnb,chechabc;

    protected String[] mMonths = new String[] {
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"
};

    private XAxis xAxis;

    private BarData barData;
    private LineData lineData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        mChart = (CombinedChart) findViewById(R.id.chart1);

        checkBoxInitialiozation();
        chartInitialization();
        setChartDataBasic();
     }

     private void checkBoxInitialiozation() {

         chechabc = findViewById(R.id.chechbEnergy);
         chechmnb = findViewById(R.id.chechbToken);

         chechabc.setChecked(true);
         chechmnb.setChecked(true);

         chechabc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                 if (!b) {
                    if (!chechmnb.isChecked()) {
                        chechabc.setChecked(true);

                    } else {
                         chechabc.setChecked(false);
                      }

                 }
                 setChartData();

             }
           });
           chechmnb.setOnCheckedChangeListener(new
  CompoundButton.OnCheckedChangeListener() {
             @Override
             public void onCheckedChanged(CompoundButton compoundButton,
 boolean b) {
                 if (!b) {
                     if (!chechabc.isChecked()) {
                       chechmnb.setChecked(true);
                   } else {
                        chechmnb.setChecked(false);
                    }
                }
                setChartData();
            }
        });
    }
     protected float getRandom(float range, float startsfrom) {
         return (float) (Math.random() * range) + startsfrom;
     }

     private void chartInitialization() {

         mChart.getDescription().setEnabled(false);
         mChart.setBackgroundColor(Color.WHITE);
         mChart.setDrawGridBackground(false);
         mChart.setDrawBarShadow(false);
         mChart.setHighlightFullBarEnabled(false);

         // draw bars behind lines
         mChart.setDrawOrder(new CombinedChart.DrawOrder[]{
                 CombinedChart.DrawOrder.BAR,CombinedChart.DrawOrder.LINE
         });

         Legend l = mChart.getLegend();
         l.setWordWrapEnabled(true);
         l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
         l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.CENTER);
         l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
         l.setDrawInside(false);

         YAxis rightAxis = mChart.getAxisRight();
         rightAxis.setDrawGridLines(false);
         rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
         rightAxis.setEnabled(false);

         YAxis leftAxis = mChart.getAxisLeft();
         leftAxis.setDrawGridLines(false);
         leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

         xAxis = mChart.getXAxis();
         xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
         xAxis.setAxisMinimum(0f);
         xAxis.setGranularity(1f);

     }

     private LineData generateLineData(ArrayList<Entry> entries) {

         LineData d = new LineData();
         LineDataSet set = new LineDataSet(entries, "Token");

         set.setLineWidth(2.5f);

         set.setCircleRadius(3f);
         set.setCircleColor(getResources().getColor(R.color.colorAccent));
         set.setColors(getResources().getColor(R.color.colorAccent));
         set.setFillColor(getResources().getColor(R.color.colorPrimary));
       set.setValueTextColor(getResources().getColor(R.color.colorPrimary));
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setValueTextSize(10f);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
         //to draw value in side graph
        set.setDrawValues(false);
        d.addDataSet(set);

       return d;
    }

   private BarData generateBarData(ArrayList<BarEntry> entries) {

        BarDataSet set1 = new BarDataSet(entries, "Energy");
        set1.setColor(getResources().getColor(R.color.colorPrimary));

    set1.setValueTextColor(getResources().getColor(R.color.colorAccent));
    set1.setValueTextSize(10f);
    set1.setAxisDependency(YAxis.AxisDependency.LEFT);
    //to draw value inside graph
    set1.setDrawValues(false);

    float barWidth = 0.45f; // x2 dataset

    BarData d = new BarData(set1);
    d.setBarWidth(barWidth);

    return d;
   }
   private void setChartDataBasic() {

        ArrayList<BarEntry> entriesBarEntry = new ArrayList<BarEntry>();
        ArrayList<Entry> entriesLineEntry = new ArrayList<Entry>();

        entriesBarEntry.clear();
        entriesLineEntry.clear();

        for (int index = 0; index < itemcount; index++)
            entriesLineEntry.add(new Entry(index + 0.5f, getRandom(15, 5)));

         entriesBarEntry = getBarEnteries(entriesBarEntry);

         try {
             if (mMonths.length > 0) {
               xAxis.setValueFormatter(new IAxisValueFormatter() {
                   @Override
                    public String getFormattedValue(float value, AxisBase axis) {
                    return mMonths[(int) value % mMonths.length];
                }
            });

            barData = generateBarData(entriesBarEntry);
            lineData = generateLineData(entriesLineEntry);
            setChartData();
        } else {

            mChart.setData(null);
            mChart.notifyDataSetChanged();
            mChart.invalidate();
        }
    } catch (ArithmeticException e) {
        Log.d("MainActivity", "setChartData: " + e.getMessage());
    }
}

  public void setChartData() {

    CombinedData chartData = new CombinedData();
    if (chechabc.isChecked())
        chartData.setData(barData);
    if (chechmnb.isChecked())
        chartData.setData(lineData);
    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.setData(chartData);
    mChart.notifyDataSetChanged();
    mChart.invalidate();

  }

   private ArrayList<BarEntry> getBarEnteries(ArrayList<BarEntry> entries) {
    entries.add(new BarEntry(1, 20));
    entries.add(new BarEntry(2, 10));
    entries.add(new BarEntry(3, 80));
    entries.add(new BarEntry(4, 40));
    entries.add(new BarEntry(5, 20));
    entries.add(new BarEntry(6, 60));
    entries.add(new BarEntry(7, 22));
    entries.add(new BarEntry(8, 15));
    entries.add(new BarEntry(9, 45));
    return entries;
  }
 }

Facing Exception
 FATAL EXCEPTION: main
                                                                  Process:
com.swytch.chartdemo, PID: 10510

java.lang.NullPointerException: Attempt to invoke virtual method 'int
com.github.mikephil.charting.data.BarData.getDataSetCount()' on a null
object reference
                                                                      at
 com.github.mikephil.charting.renderer.BarChartRenderer
 .initBuffers(BarChartRenderer.java:61)
                                                                      at
 com.github.mikephil.charting.renderer.CombinedChartRenderer
.initBuffers(CombinedChartRenderer.java:82)
                                                                      at
 com.github.mikephil.charting.charts.BarLineChartBase
 .notifyDataSetChanged(BarLineChartBase.java:326)
                                                                      at
  com.github.mikephil.charting.charts.Chart.setData(Chart.java:304)
                                                                      at
  com.github.mikephil.charting.charts.CombinedChart
 .setData(CombinedChart.java:94)
                                                                      at
   com.swytch.chartdemo.MainActivity
  .setChartData(MainActivity.java:240)
                                                                      at
  com.swytch.chartdemo.MainActivity$1
  .onCheckedChanged(MainActivity.java:93)
                                                                      at
  android.widget.CompoundButton.setChecked(CompoundButton.java:154)
                                                                      at
  android.widget.CompoundButton.toggle(CompoundButton.java:113)
                                                                      at
  android.widget.CompoundButton.performClick(CompoundButton.java:118)
                                                                      at
  android.view.View$PerformClick.run(View.java:19884)
                                                                      at
  android.os.Handler.handleCallback(Handler.java:739)
                                                                      at
  android.os.Handler.dispatchMessage(Handler.java:95)
                                                                      at
  android.os.Looper.loop(Looper.java:135)
                                                                      at
  android.app.ActivityThread.main(ActivityThread.java:5343)
                                                                      at
  java.lang.reflect.Method.invoke(Native Method)
                                                                      at
  java.lang.reflect.Method.invoke(Method.java:372)
                                                                      at

  com.android.internal.os.ZygoteInit$MethodAndArgsCaller
  .run(ZygoteInit.java:905)
                                                                      at
   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

OutputImage :-

A: Replace your setChartData method with:
public void setChartData()
{
    CombinedData chartData = new CombinedData();
    if(chechabc.isChecked() && chechmnb.isChecked())
    {
        chartData.setData(barData);
        chartData.setData(lineData);
    }
    else if (chechabc.isChecked())
    {
        LineData ld = new LineData();
        ld.clearValues();
        chartData.setData(ld);
        chartData.setData(barData);
    }

    else if (chechmnb.isChecked())
    {
        BarData bd = new BarData();
        bd.clearValues();
        chartData.setData(bd);
        chartData.setData(lineData);
    }

    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.setData(chartData);

    mChart.notifyDataSetChanged();
    mChart.invalidate();
}

A: Try changing your code as follows.
public void setChartData() {

    CombinedData chartData = new CombinedData();
    boolean dataAvailable = false;
    if (chechabc.isChecked()) {
        chartData.setData(barData);
        dataAvailable = true;
    }
    if (chechmnb.isChecked()) {
        chartData.setData(lineData);
        dataAvailable = true;
    }
    if (dataAvailable) {
        mChart.setData(chartData);
    } else {
        mChart.setData(null);
    }
    xAxis.setAxisMaximum(chartData.getXMax() + 0.25f);
    mChart.notifyDataSetChanged();
    mChart.invalidate();
}


text:
Q: While loop around switch cases in C I recently came across the code snippet shown below, I was expecting it to be a syntax error but to my surprise, the code produces valid output.
#include <stdio.h>

int main(void) {
    int x = 2;

    switch(x) {
    case 1: printf("1"); break;

        do {
            case 2: printf("2 "); break;
            case 3: printf("3 "); break;
        } while(++x < 4);

        case 4: printf("4"); break;
    }
    return 0;
}

output: 2 4

Compiler: GCC 6.3
I found a similar problem but it is not justifying above condition completely,
Mixed 'switch' and 'while' in C
Can anyone explain,

*

*What exactly happening here?

*Why isn't it a syntax error?

*Why case '3' is skipped?

A: case X: some_statement; is a labeled statement (6.8.1)  just like goto_label: some_statement; with the only caveat that case/default labels may only appear inside the body of a switch (possibly in an arbitrarily nested compound statement). That makes case statements only very loosely coupled with switches, syntactically.
Semantically, switches are implementable as computed gotos and like regular gotos, they may jump pretty much anywhere (in C11, you can't jump past a VLA declaration) including inside of a loop (see https://en.wikipedia.org/wiki/Duff%27s_device#Mechanism for another description).
In your example, case 3: is skipped because of the break, but case 4: does follow because the break after case 3: is a loop-breaking break, not a switch-breaking break (break/continue always apply to the nearest construct they can apply to).

A: The official C grammar for a switch statement is:

switch ( expression ) statement

Any statement can be a labeled-statement, for which the grammar includes:

case constant-expression : statement

This means you can put pretty much whatever you want inside the body of the switch: It can be a compound statement which includes multiple statements and a do-while statement that includes multiple statements, and case labels can be prefixed to any of those statements.
The compiler merely implements the switch using jump instructions (inside its abstract machine; they may end up as other instructions after optimization). Loops statements such as do-while are implement with code that tests the controlling expression and jumps conditionally. So, in spite of the nice structure you think of in structured languages, it boils down to jump instructions, and those can be interwoven as desired.
The jumps are not the most disconcerting part of this. Object initialization and lifetime is more of a concern. Switch statements can unintentionally skip the initialization of objects if care is not taken.
The printf of "3 " is never executed because control jumps from the switch to case 2, then breaks, which exits the do-while. This leaves code at the case 4 statement, which prints "4 " and then breaks out of the switch statement.


text:
Q: PowerShell: Update/Refresh the TOC of a Word-Document I am working on a PowerShell-Script to update / refresh automatically the table of contents in a Word Document (which earlier was exported from an application that doesn't do that automatically)
The TOC in an exported document arrives like that:

On click (Inhaltsverzeichnis aktualisieren) it generates the Table of Contents properly.
However, I want this to happen automatically using PowerShell and came up with the following script (mind, that I am a beginner in PowerShell):
$latestFile = Get-ChildItem -Path C:\ExportedDocuments -File -Filter "*.docx" | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$word = New-Object -ComObject Word.Application
$word.Visible=$true
$doc=$word.Documents.Open($latestFile.FullName)
$toc = $latestFile.TablesOfContents
$toc.Update()
$latestFile.save()
$latestFile.close()

Following errors I receive - but I don't completely understand and I also don't know how to fix them:
You cannot call a method on a null-valued expression. At line:6 char:1
+ $toc.Update()
+ ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull   Method invocation failed because [System.IO.FileInfo] does not contain a method named 'save'. At line:7 char:1
+ $latestFile.save()
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound   Method invocation failed because [System.IO.FileInfo] does not contain a method named 'close'. At line:8 char:1
+ $latestFile.close()
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

A: Please see your script amended below:
$latestFile = Get-ChildItem -Path C:\ExportedDocuments -File -Filter "*.docx" | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$word = New-Object -ComObject Word.Application
$word.Visible = $true
$doc = $word.Documents.Open($latestFile.FullName)
$toc = $doc.TablesOfContents
$toc.item(1).update()
$doc.save()
$doc.close()

The 1st issue you were having is that you assigned the document to the object $doc and then on the next line tried to call the document directly again instead of referencing the object $doc:
$doc = $word.Documents.Open($latestFile.FullName)
$toc = $latestFile.TablesOfContents

The 2nd issue is as mentioned by the other user, you need to reference which ToC you want to update:
$toc.item(1).update()

A: One can have multiple Tables Of Contents, which is why this is called
TablesOfContents.
You should use TablesOfContents(1).Update().


text:
Q: Argo Workflows: `workflow-role` seems to be missing from Argo install I am new to Argo Workflows and following along with this tutorial.
Following along with it, we are to create a service account and then attach the pre-existing workflow-role to the service account, like this:
> kubectl create serviceaccount mike
serviceaccount/mike created # Response from my terminal

> kubectl create rolebinding mike --serviceaccount=argo:mike --role=workflow-role
rolebinding.rbac.authorization.k8s.io/mike created # Response from my terminal

But then when I tried to submit a job using that service account, it said that there is no such role workflow-role:
Message:  Error (exit code 1): pods "mike-cli-hello-svlmn" is forbidden: User
"system:serviceaccount:argo:mike" cannot patch resource "pods" in API group "" in the namespace
"argo": RBAC: role.rbac.authorization.k8s.io "workflow-role" not found

(I also do not understand why my default API group is null, but I'm assuming that is unrelated.)
I then checked, and indeed there is no such role:
❯ kubectl get role
NAME                       CREATED AT
agent                      2022-02-28T21:38:31Z
argo-role                  2022-02-28T21:38:31Z
argo-server-role           2022-02-28T21:38:32Z
executor                   2022-02-28T21:38:32Z
pod-manager                2022-02-28T21:38:32Z
submit-workflow-template   2022-02-28T21:38:32Z
workflow-manager           2022-02-28T21:38:32Z

Could it be that the role is workflow-manager? That sounds more like an automated service to manage the pipeline / DAG or something similar.
I am obviously quite new to Argo.  I have successfully launched jobs, but not when trying to use that newly created service account.
Should Argo have a default role of workflow-role?  How do I create it?

A: Actually, I think I got it, but if someone sees this, a confirmation would be nice.
I created a role file as follows:
role.yaml:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: workflow
rules:
- apiGroups:
  - ""
  resources:
  - pods
  verbs:
  - get
  - watch
  - patch
- apiGroups:
  - ""
  resources:
  - pods/log
  verbs:
  - get
  - watch

I then created the role via the standard
kubectl apply -f role.yaml

Then created the role-binding same as above:
kubectl create rolebinding mike --serviceaccount=argo:mike --role=workflow

Then I could submit jobs with the new service account without a problem:
argo submit --serviceaccount mike --watch argo_tutorial.yaml


text:
Q: Questions list does not show new questions (iOS app) Right now the top question I see in the app is this one, while obviously there are newer questions.
The time difference appears to be two hours, and I'm in GMT+2 timezone so maybe it's related?

A: This is related to some filtering we are doing (temporarily) on closed "on hold" questions, but because of a simple oversight, the first page of questions in the questions list was getting lost.  This will be fixed in the next build.


text:
Q: Syntax coloring my DSL in Xtext I'm doing a small academic assignment, in which I'm supposed to implement an eclipse plugin for the NuSMV language (a model checking language) using Xtext. The xtext grammar was provided (with some minor bugs).
I've created an Xtext project and called it "smv.project" with language name of "NuSMV" and extension of "*.smv". I've coppied the provided Xtext grammar into smv.project/src/NuSMV.xtext, generated artifacts, and created runtime eclipse. Seems to work fine except those minor bugs (which are originated in the grammar in my opinion).
Now, my next step is to change the default colors in my DSL. Obviously, every user can do that for himself in the eclipse menus when using my plugin, but I wand the DEFAULT color to change. I've read the Xtext documentation for syntax coloring. It was short and had many terms I didn't understand. What I did understand is that there are 2 kinds of syntax coloring in Xtext, Lexical and Semantic. I didn't understand the meaning of each but it seemed to me that Lexical coloring is simpler, so I went for it.
The documentation said that I should implement the interface IHighlightingConfiguration. It showed an example of implementation called DefaultHighlightingConfiguration (full source can be seen here https://github.com/eclipse/xtext/blob/master/plugins/org.eclipse.xtext.ui/src/org/eclipse/xtext/ui/editor/syntaxcoloring/DefaultHighlightingConfiguration.java). I've coppied this implementation into my project, to smv.project.ui/src/smv.project.ui.editor.syntaxcoloring. Of course, I changed the "package" line in the beginning of the file.
I've changed all red values to 255 to see difference.
I've generated the artifacts again, created runtime eclipse, created a *.smv file but the colors were the same.
My guess was that I need to set my new class in some variable or configuration class... I tried searching for "DefaultHighlightingConfiguration" in the example's repository and found out that it's used in the file XtextProposalProvider.java (full source https://github.com/eclipse/xtext/blob/87a6c7dc25074ca4ff28429c059e728ef420b926/plugins/org.eclipse.xtext.xtext.ui/src/org/eclipse/xtext/ui/contentassist/XtextProposalProvider.java) in line 235 - We're overriding getKeywordDisplayString(). So I've went to the already existing NuSMVProposalProvider.java in my repository and tried to add the same lines:
@Override
 protected StyledString getKeywordDisplayString(Keyword keyword) {
    return stylerFactory.createFromXtextStyle(keyword.getValue(),
            defaultLexicalHighlightingConfiguration.keywordTextStyle());
}

Here is my full NuSMVProposalProvider.xtend:
/*
 * generated by Xtext
 */
package smv.project.ui.contentassist

import smv.project.ui.contentassist.AbstractNuSMVProposalProvider
import javax.inject.Inject
import org.eclipse.xtext.ui.editor.syntaxcoloring.DefaultHighlightingConfiguration
import org.eclipse.jface.viewers.StyledString
import org.eclipse.xtext.Keyword

/**
 * see http://www.eclipse.org/Xtext/documentation.html#contentAssist on how to customize content assistant
 */
class NuSMVProposalProvider extends AbstractNuSMVProposalProvider {

    @Inject
    private DefaultHighlightingConfiguration defaultLexicalHighlightingConfiguration;

    @Override
     protected StyledString getKeywordDisplayString(Keyword keyword) {
        return stylerFactory.createFromXtextStyle(keyword.getValue(),
                defaultLexicalHighlightingConfiguration.keywordTextStyle());
    }

}

However, the next errors appeared:

*

*"The annotation @Override is disallowed for this location."

*"extraneous input 'keyword' expecting ')'"

*"mismatched input '{' expecting '=>'"
in the first 3 lines, respectively.

My questions are:

*

*What exactly should I do with my class that implements
IHighlightingConfiguration?

*What is Lexical and Semantic highlighing?

*Is there something else I need to know for my syntax coloring to work?

Thanks a lot!! :)
Chai

A: NuSMVProposalProvider wasn't the way to go.
I didn't have to add any code there at all.
What I was looking for was adding the next lines in NuSMVUiModule.java:
public Class<? extends IHighlightingConfiguration> bindIHighlightingConfiguration () {
     return DefaultHighlightingConfiguration.class;
}

Thanks everyone for their comments!
Chai


text:
Q: Call a method in child of child class I have three classes. First of them is abstract, and it is inherited by child class, which is again inherited. How to call method from the third class in abstract one?
Example code:
public abstract class DoSth
{
    public void DoSomething()
    {
        Console.WriteLine("I'm doing something");
        this.DoSomethingBigger();
    }
    protected abstract void DoSomethingBigger();
}

public class Writer : DoSth
{
    protected override void DoSomethingBigger()
    {
        Console.WriteLine("I'm writting");
    }
}

public class BookWriter : Writer
{
    protected new void DoSomethingBigger()
    {
        Console.WriteLine("I'm writting a book");
    }
}

How to call DoSomethingBigger() from a BookWriter class?
When I make an instance of a BookWriter and I call DoSomething() my output is
I'm doing something
I'm writting

but I want
I'm doing something
I'm writting a book

A: By marking your DoSomethingBigger method with new keyword you hide the initial DoSomethingBigger method instead of overriding it.
You should rewrite your code this way for it to work
public abstract class DoSth
{
    public void DoSomething()
    {
        Console.WriteLine("I'm doing something");
        this.DoSomethingBigger();
    }
    protected abstract void DoSomethingBigger();
}

public class Writer : DoSth
{
    protected override void DoSomethingBigger()
    {
        Console.WriteLine("I'm writting");
    }
}

public class BookWriter : Writer
{
    protected override void DoSomethingBigger()
    {
        Console.WriteLine("I'm writting a book");
    }
}

A: You are not overriding the method in the 3rd class, you are basically creating an entirely new method that the base knows nothing about. see here for more info. It's no different than changing the name of the method in BookWriter to something completely different like DoSomethingElseAltogether(), now it's much more obvious that you cannot call it from the base class.
Instead, you should override in the third class:
public class BookWriter : Writer
{
    protected override void DoSomethingBigger()
    {
        Console.WriteLine("I'm writting a book");
    }
}


text:
Q: In an AJAX update, how can I access code from an external javascript file? I'm learning Ruby on Rails and I'd like to use some unobtrusive javascript to display a modal. When the user clicks on a remote link, it calls an action in one of my controllers that returns the following javascript...
var SM = new SimpleModal({"width":600});
SM.addButton("Action button", "btn primary", function(){
  this.hide();
});

SM.addButton("Cancel", "btn");
SM.show({
    "model":"modal-ajax",
    "title":"Title",
    "param":{
      "url":"/ajax/url",
      "onRequestComplete": function(){ /* Action on request complete */ }
    }
});

...but the problem is the code doesn't know what SimpleModal is since that's defined in a separate javascript file. How can I import or reference that SimpleModal code so that my AJAX update can create the SimpleModal object and show it?
Thanks in advance for your wisdom!

A: Require Simple Modal in your application.js for application wide use
//= require simple_modal


text:
Q: Solution in terms of Lambert $W$ function or infinite series I've tried to solve $x\log x = 2(x-1)(1-ax)$ for $a\ge 0$. If $a=0$, I obtained
$$x \log x = 2x-2\\ \to  x(\log x-2)= -2 \\ \to x\log(xe^{-2}) = -2
\\ \to
xe^{-2}\log(xe^{-2}) = -2e^{-2}\\ \to x =e^{W(-2e^{-2})+2}.$$
Similarly as in the above solution, can I express the solution for $a>0$ in terms of Lambert $W$ function?

A: Of course $x=1$ is a solution, but that's presumably not the one you want.
As far as I can tell, there is no closed-form expression for the solution when $a > 0$, whether in terms of $W$ or anything else.
As a series in powers of $a$: with $w = W(-2 e^{-2})$,
$$ x = e^{2+w} \left( 1+2\,{\frac {w+2}{w \left( w+1 \right) }}a+2\,{\frac { \left( w+2
 \right)  \left( 2\,{w}^{2}+9\,w+6 \right) }{{w}^{2} \left( w+1
 \right) ^{3}}}{a}^{2}+\ldots\right)$$
It appears that the coefficient of $a^n$ in the series is
$(w+2)/(w^n (w+1)^{2n-1})$ times a polynomial in $w$ of degree $2n-2$.


text:
Q: Is there any PHP or JavaScript math expression formatters (which adds brackets)? Google Calculator formats math expressions this way:
2+2/2 ---> 2 + (2 / 2)
2+2/2*PI ---> 2 + ((2 / 2) * PI)

In others words - it adds brackets.
Are there any similar PHP or JavaScript solutions to do the same thing?

A: Yes; quickest and easiest way to not code it yourself (like how Google did) is to use MathML.
Hope this helps!

A: surely you could just query the calendar via curl + ajax / postback?
the result is a json array with left, right, error etc.
query example: http://www.google.com/ig/calculator?q=5*9%2B%28sqrt+10%29^3%3D
php / curl sample: http://www.dynamicguru.com/php/currency-conversion-using-php-and-google-calculator-api/#more-285


text:
Q: upload image on twitpic using as3 how I can upload image on twitpic using as3 and flash professorial cs6
and i try the code below and nothing happened
Thank's in advance
import flash.net.FileReference;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;

var urlVars:URLVariables = new URLVariables();
urlVars.username = "xxxx";
urlVars.password = "xxxxx";

var urlRequest:URLRequest = new URLRequest("http://twitpic.com/api/upload");
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = urlVars;

var file:File = File.desktopDirectory.resolvePath("test.png");
file.upload(urlRequest, 'media');


text:
Q: Ajax request vs kendoUI Datasource I am new to Kendo ui, Can any one help in understaning what is the deifference between ajax and kendo UI datasource

A: A Kendo UI datasource is an object in JavaScript that abstracts AJAX communication in your web application.
AJAX is a client-side technique used to communicate with a server in web applications.


text:
Q: JBOSS SQL Logging Using JBOSS
I would like to see the query being executed in the logs - and I need to see it in a plain SQL, (if possible).
For example, I have a DO class with the named query
@NamedQuery(name="MyElementDO.findByAllStuff",
  query="SELECT o FROM MyElementDO o WHERE <here goes some list of
   conditions>")
@Table(name = "tblElement")
public class MyElementDO implements Serializable
{
  //all mapped fields
}

In my EJB class, I am calling this by
Query qry =manager.createNamedQuery("MyElementDO.findByAllStuff").
            setParameter("param1", value1).<some more setParameters()
             >...setParameter("param_n", vaue_n);
    list =  qry.getResultList() ;

The problem is that when I designed this query and am running it in SQL Server management studio, I get 3 records back (which is OK)
When the Java EJB class executes it, I get 1 record back.
The actual query is very large, with a lot of parameters, some of which are set based on conditions.  I would like to see the actual query being executed by JBOSS Jvm.  So, my question is:
How can I enable the log?
I did this - set loging categories in jBoss console, like found here
HERE, on this page
However, I get a very unclear to me output, like this
\-[QUERY] Node: 'query'
+-[SELECT_FROM] Node: 'SELECT_FROM'
|  +-[FROM] Node: 'FROM'
|  |  \-[RANGE] Node: 'RANGE'
|  |     +-[DOT] Node: '.'
|  |     |  +-[DOT] Node: '.'
|  |     |  |  +-[DOT] Node: '.'
|  |     |  |  |  +-[DOT] Node: '.'
|  |     |  |  |  |  +-[IDENT] Node: 'com'
|  |     |  |  |  |  \-[IDENT] Node: 'package'
|  |     |  |  |  \-[IDENT] Node: 'subpackage'
|  |     |  |  \-[IDENT] Node: 'entity'
|  |     |  \-[IDENT] Node: 'MyElementDO'
|  |     \-[ALIAS] Node: 'o'
|  \-[SELECT] Node: 'SELECT'
|     \-[IDENT] Node: 'o'
\-[WHERE] Node: 'WHERE'
   \-[EQ] Node: '='
      +-[DOT] Node: '.'
      |  +-[DOT] Node: '.'
      |  |  +-[IDENT] Node: 'o'
      |  |  \-[IDENT] Node: 'RelatedTableDO'
      |  \-[IDENT] Node: 'someId'
      \-[COLON] Node: ':'
         \-[IDENT] Node: 'strPlanId'

and, I guess, I can sit and translate it into a regular syntax, but can I get a normal translated SQL output?


text:
Q: GInputStream and tracking the total downloaded bytes I'm learning C with the GLib stack and I have a sample code that opens a connection to a host and downloads the file by reading a number of bytes in the GInputStream. I'm trying to track the total number of bytes per second by breaking the while loop after a second had elapse then printing it to the screen. But there are times that the loop breaks after more than a second (sometimes 2-4 seconds) and I dont understand why is this. Here's my code:
#define _POSIX_C_SOURCE 199309L

#include <stdio.h>
#include <libsoup/soup.h>
#include <time.h>

#define DOWNLOAD_SIZE 4096
#define DOWNLOAD_SPEED_LIMIT 819200L // bytes, 800kb

int main(void)
{

    SoupSession *session;
    SoupLogger *logger;

    session = soup_session_new_with_options (
        SOUP_SESSION_ADD_FEATURE_BY_TYPE, SOUP_TYPE_CONTENT_SNIFFER,
        NULL
    );

    logger = soup_logger_new(SOUP_LOGGER_LOG_HEADERS, -1);
    soup_session_add_feature(session, (SoupSessionFeature *) logger);

    g_object_unref(logger);

    SoupMessage *message;
    GInputStream *stream;
    GError *error = NULL;
    char *url = "https://releases.ubuntu.com/20.04/ubuntu-20.04-desktop-amd64.iso";
    message = soup_message_new("GET", url);
    stream = soup_session_send(session, message, NULL, &error);

    const gchar *content_length = soup_message_headers_get_one(message->response_headers, "content-length");
    const gchar *content_type = soup_message_headers_get_one(message->response_headers, "content-type");
    gssize content_size = 0;
    if(content_length)
    {
        content_size = atol(content_length);
    }

    g_print("content-length: %u\n", content_size);
    g_print("content-type: %s\n", soup_message_headers_get_content_type(message->response_headers, NULL));

    GBytes *download_bytes;
    gssize downloaded_size = 0;
    gssize downloaded_size_per_iter = 0;

    guchar buff[DOWNLOAD_SIZE];

    if(content_length)
    {

        struct timespec start, current, end;

        // if content-length is known
        while(downloaded_size < content_size)
        {
            timespec_get(&start, TIME_UTC);
            end.tv_sec = start.tv_sec + 1;
            end.tv_nsec = start.tv_nsec;

            downloaded_size_per_iter = 0;
            while(1)
            {

                // download_bytes = g_input_stream_read_bytes(stream, DOWNLOAD_SIZE, NULL, NULL);
                // downloaded_size_per_iter +=  g_bytes_get_size(download_bytes);

                downloaded_size_per_iter += g_input_stream_read(
                    stream, &buff, DOWNLOAD_SIZE, NULL, NULL
                );
                timespec_get(&current, TIME_UTC);

                if(current.tv_sec == end.tv_sec && current.tv_nsec >= end.tv_nsec)
                    break;
                if(current.tv_sec > end.tv_sec)
                    break;
            }
            downloaded_size += downloaded_size_per_iter;
            printf("%ld %ld \n", start.tv_sec, start.tv_nsec);
            printf("%ld \n", (downloaded_size_per_iter/1024));
            printf("%ld %ld\n", current.tv_sec, current.tv_nsec);
            printf("\n\n");
        }
    }else
    {
        // content-length not known
    }
    return 0;
}

Here's the printed result: https://imgur.com/Nb3QVXD
So is it a problem on my code? Is reading a stream without a sleep bad? Or is it a network issue like ping and etc? Im just connecting to a wifi and ping is not that good when playing games
Thanks!


text:
Q: Binding isn't working for ListBox while using MVVM I have a simple UserControl with a DropDown showing versions like V14, V15 etc.
I have another ListBox whose ItemSource is binded to a property in the ViewModel which depend upon the SelectedValue of the Version DropDown.
ViewModel Looks like this:
 class MultiSelectEnvironmentContextControlViewModel: ViewModelBase
    {
        private string selectedVersion;
        private DomainFacade domainFacade;
        private ObservableCollection<string> environments= new ObservableCollection<string>();

        public MultiSelectEnvironmentContextControlViewModel()
        {
            domainFacade = ((App) Application.Current).DomainFacade;

        }
        public IEnumerable<string> EnvironmentVersions
        {
            get
            {
                return (domainFacade.GetEnvironmentVersions().Select(v => "Version " + v));
            }
        }

        public string SelectedVersion
        {
            get { return selectedVersion; }
            set
            {
                selectedVersion = value;
                RaisePropertyChanged("Environments");
            }
        }

                 public ObservableCollection<string> Environments
    {
        get
        {
            environments = (ObservableCollection<string>)(domainFacade.GetEnvironments(SelectedVersion));
            return environments;
        }
    }

    }

I am keeping track of the SelectedVersion in a property which raises PropertyChanged on Environments so that whenever SeelectedVersion changes, the Environments should update the UI.
Issue I am facing is, ehn I run the application, I see the versions being populated, but there is nothing in the ListBox.
I am setting the DataContext of the UserControl to the ViewModel in the constructor of the UserControl.
Here is how my Control.cs file looks like:
 public partial class MultiSelectEnvironmentContextControl : UserControl
    {
        private static MultiSelectEnvironmentContextControlViewModel dataContext = new MultiSelectEnvironmentContextControlViewModel();

        public MultiSelectEnvironmentContextControl()
        {
            InitializeComponent();
            this.DataContext = dataContext;
           dataContext.SelectedVersion = (string)this.ComboBoxVersions.SelectedItem;

        }

        private void ComboBoxVersions_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
          dataContext.SelectedVersion = ((ComboBox) sender).SelectedValue.ToString();
        }
}

Here is the XAML:

    <ComboBox Grid.Column="0" Grid.Row="0" x:Name="ComboBoxVersions" SelectedIndex="0" Margin="10" SelectionChanged="ComboBoxVersions_OnSelectionChanged" ItemsSource="{Binding EnvironmentVersions}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}" />
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

    <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="0" Margin="10">
        <TextBlock VerticalAlignment="Center" Margin="0,0,10,0">Tests to be run for:</TextBlock>
        <ComboBox  Name="ComboBoxFileTypeSelector" ItemsSource="{Binding AvailableValidationTypes}" DisplayMemberPath="Key" SelectedValuePath="Value" SelectedIndex="0">
        </ComboBox>
    </StackPanel>

    <ListBox x:Name="ListBoxEnvironments" Grid.Column="0" Grid.Row="1" Height="300" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" Margin="10" SelectionMode="Multiple" ItemsSource="{Binding Environments}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel Orientation="Horizontal" HorizontalAlignment="Left" Width="800" >
                </WrapPanel>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox x:Name="CheckBoxEnvironment" Content="{Binding}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" Margin="5">
                </CheckBox>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

A: I believe this is because SelectedVersion has values like "Version 1", "Version 2", etc, but your method DomainFacade.GetEnvironments(string version) expects values like "1", "2" etc.
I would write your viewmodel like this:
public class MultiSelectEnvironmentContextControlViewModel : ViewModelBase
{
    private string selectedVersion;
    private DomainFacade domainFacade;
    private IEnumerable<string> environments;

    public MultiSelectEnvironmentContextControlViewModel()
    {
        domainFacade = ((App)Application.Current).DomainFacade;
        EnvironmentVersions = domainFacade.GetEnvironmentVersions();
    }

    public IEnumerable<string> EnvironmentVersions { get; private set; }

    public string SelectedVersion
    {
        get { return selectedVersion; }
        set
        {
            selectedVersion = value;
            RaisePropertyChanged("SelectedVersion");
            Environments = domainFacade.GetEnvironments(SelectedVersion);
        }
    }

    public IEnumerable<string> Environments
    {
        get { return environments; }
        set
        {
            environments = value;
            RaisePropertyChanged("Environments");
        }
    }
}

}
and applied to formatting of environment versions in view:
<ComboBox SelectedItem="{Binding SelectedVersion}"
          ItemsSource="{Binding EnvironmentVersions}"
          ItemStringFormat="Version: {0}" />


text:
Q: C - Can not use strcpy with strtok I am working with a function that accept full name as input and print them out in order: first name, middle name, last name.
The problem is my while loop seem to go infinite and i haven't figured out how to fix it.
Here is my function:
void order(char ar[])
{
    int i, count=0, a=1;
    char* token;
    char last[20], middle[20], first[20],c;
    char s[]=" ";
    for(i=0;i<strlen(ar)-1;i++)
        if(ar[i]==' ') count++;

    token=strtok(ar,s);
    strcpy(last,token);

    while(token!=NULL)
    {
        token=strtok(NULL,s);
        if(a<count) strcpy(middle,token);
        else strcpy(first,token);
        a++;
    }
    printf("%s %s %s",first,middle,last);
}

A: When first is copied (i.e. all tokens identified), while loop will be entered once again(note that token is not NULL, but points to first in this case). Now strtok() will be called and it will return NULL. Code will go to the else part and try to strcpy(), which is causing the problem.
Check for NULL before strcpy(). I have done this like this and it works fine.
while(token!=NULL)
{
    token=strtok(NULL,s);
    if (token == NULL)
      break;
    if(a<count) strcpy(middle,token);
    else strcpy(first,token);
    a++;
}

A: This is more like how I'd present the code in the question — before I passed it through a compiler:
void order(char ar[])
{
    int count = 0, a = 1;
    char *token;
    char last[20], middle[20], first[20];
    char s[] = " ";

    for (int i = 0; i < strlen(ar) - 1; i++)
    {
        if (ar[i] == ' ')
            count++;
    }

    token = strtok(ar, s);
    strcpy(last, token);

    while (token != NULL)
    {
        token = strtok(NULL, s);
        if (a < count)
            strcpy(middle, token);
        else
            strcpy(first, token);
        a++;
    }
    printf("%s %s %s", first, middle, last);
}

You can argue about brace placement — I use Allman but 1TBS is a widely used alternative style.  I recommend choosing one of those two.  I put braces around the body of a loop if it is more than one line; YMMV.
Use more white space around operators.  Don't define unused variables (c vanished).  I placed int i in the for loop.  I would probably define one variable per line, and I probably wouldn't use the count or a.
The call to strlen() should not be in the condition of the loop.  I'm not sure how you'd cope with my name — I don't have a middle name.  I think you could avoid the while loop altogether.  I'm not convinced you need the for loop either.  Those are a separate discussion.
I'm not attempting to fix the algorithmic problem — this is not an answer to the question in the question (so it shouldn't be accepted), but is an answer to the question in the comment, and since code cannot be formatted in comments, I can't answer it sanely in a comment; hence, this 'not an answer' but 'intended to be helpful to an auxilliary question from the OP'.


text:
Q: Buscando o próximo registro e o registro anterior usando duas colunas para ordenação de tabelas diferentes Tenho a seguinte estrutura de banco de dados:
___ Table: modules___
id int(10)
name varchar(50)
position int(10)

___ Table: lessons ___
id int(10)
module_id int(10) FK
position int(10)
name varchar(50)

Considerando que tenhos os seguintes dados para a tabela modules:
1 - 1 - Módulo 1
2 - 2 - Módulo 2
3 - 3 - Módulo 3

E para a tabela lessons tenho os seguintes dados:
1 - 1 - 1 - Aula 1
2 - 1 - 2 - Aula 2
3 - 1 - 3 - Aula 3
4 - 1 - 4 - Aula 4

5 - 2 - 1 - Aula 1
6 - 2 - 2 - Aula 2
7 - 2 - 3 - Aula 3
8 - 2 - 4 - Aula 4

9  - 3 - 1 - Aula 1
10 - 3 - 2 - Aula 2
11 - 3 - 3 - Aula 3
12 - 3 - 4 - Aula 4

Então, eu tenho a seguinte query buscando uma aula:
SELECT * FROM lessons WHERE id = 8

Na query acima a próxima aula seria a lesson com id 9 e a aula anterior seria a lesson com id 7.
Como fazer as querys acima, sendo que a paginação dependerá da position tanto da tabela modules como da tabela lessons?
Eu já tentei baseado na position da tabela lessons pegar a próxima aula assim:
SELECT * FROM lessons WHERE position > 4 ORDER BY position ASC LIMIT 1;

No caso o número 4 é a position da da lesson com id 8. Só que claro que não pegou já que não tem nenhuma position maior que 4.
Tentei também na coluna position da tabela lessons guardar os valores assim:
0000000001.0000000001
0000000001.0000000002
0000000001.0000000003
0000000001.0000000004

0000000002.0000000001
0000000002.0000000002
0000000002.0000000003
0000000002.0000000004

0000000003.0000000001
0000000003.0000000002
0000000003.0000000003
0000000003.0000000004

Seguindo o padrão MODULE_ID.LESSON_ID mas acredito que não seria uma boa opção já que a ordenação de modules e lessons podem ser mudadas.
Gostaria de saber como fazer da melhor forma. Se tenho que pensar em outra estrutura de banco de dados ou como fazer as querys para pegar a lesson anterior e a próxima lesson.
Obrigado.

A: Você precisa primeiro fazer a junção das duas tabelas, e então estabelecer a condição desejada (mesmo módulo e posição superior/inferior, ou módulo superior/inferior):
SELECT *
FROM lessons l
  JOIN modules m on l.module_id = m.id
WHERE (m.position = 2 AND l.position > 4) OR m.position > 2
ORDER BY m.position ASC, l.position ASC
LIMIT 1;

SELECT *
FROM lessons l
  JOIN modules m on l.module_id = m.id
WHERE (m.position = 2 AND l.position < 4) OR m.position < 2
ORDER BY m.position DESC, l.position DESC
LIMIT 1;

Exemplo no SQLFiddle. Na hora de ordenar, ele considera primeiro o módulo depois a posição dentro do módulo.


text:
Q: Z-index does not work between 2 react functional components Here is my example where I need to put the first component in front of the second.
Currently the second component is in front of the first despite z-index. I tried also to put style on the component tag but it does not work. Where is my mistake ?
First component:
import styled from "styled-components";

const Container = styled.div`
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 500px;
z-index: 100;
`;

function Aaa() {

    return (
        <Container>asd</Container>
    )
}

export default Aaa;

Second component
import styled from "styled-components";

const Container = styled.div`
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 500px;
margin-top: -200px;
background: pink;
z-index: 1;
`;

function Bbb() {

    return (
        <Container>qwe</Container>
    )
}

export default Bbb;

App:
function App() {
  return (
    <>
    <Aaa />
    <Bbb />
    </>
  );
}

export default App;

A: You need position: relative.

Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).

https://www.w3schools.com/cssref/pr_pos_z-index.asp
E.g.
import styled from "styled-components";

const Container = styled.div`
position: relative;
display: flex;
justify-content: center;
align-items: center;
height: 500px;
margin-top: -200px;
background: pink;
z-index: 1;
`;

function Bbb() {

    return (
        <Container>qwe</Container>
    )
}

export default Bbb;

A: Try adding a container for the components instead of fragment and apply display: flex and flex-direction: column on that container and see if it works. Edit: Code sandbox with fix: https://codesandbox.io/s/floral-frog-fie10?file=/src/Aaa.js

A: I dont know why it not work,this seems no reason.But what ever, maybe you could use this instead:
import styled from "styled-components";
const Container = styled.div`
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 500px;
    transform: translateY(0px);
    `;

    function Aaa() {

    return (
        <Container>asd</Container>
    )
    }

    export default Aaa;


text:
Q: Multiple integration with constraints on variables I have a function $(x_1, x_2)\mapsto g(x_1, x_2)$ where $x_1$ and $x_2$ are both 3D vectors.
I would like to integrate function $g$ over the whole space but with some constraints on $x_1$ and $x_2$ which are represented by following functions :
$$x_1 = f_1(x)~,~~x_2 = f_2(x)~,~~x\in\mathbb{R}^3$$
Then integration could be written as follows :
$$ I= \iint_{x_1 = f_1(x)~,~x_2 = f_2(x)~,~x\in\mathbb{R}^3} g(x_1, x_2)\,dx_1\,dx_2 $$
Variables $x_1$ and $x_2$ are linked by  $x$, so I would like to replace this double integral over space by a single one over $x$ :
 $$ J= \int_{x\in\mathbb{R}^3} g[f_1(x), f_2(x)]\,dx $$
But I am really not sure about $J = I$.
If there was only one variable, say $x_1$, then to integrate over $x$ instead over $x_1$ comes to a change of variable :
 $$ I= \int_{x_1 = f_1(x)~,~x\in\mathbb{R}^3} g(x_1)\,dx_1 = \int_{x\in\mathbb{R}^3} g[f_1(x)]|\det(J_1)|\,dx$$
where $J_1$ is the jacobian matrix of function $f_1$.
How this applies to my case ?
Thanks for your attention.
Regards

A: I answeer to my own question because I think I have understood what was wrong in my first post.
===================
First, I take a very close example to my qestion borrowed from line integration.
Consider a surface function $(x, y)\mapsto f(x, y)$ with both $x,~y\in\mathbb{R}$.
Then, you want to compute the integral of this function on a given contour $\mathcal{C}$ parametrically defined by $x = h(t)~,~~y = g(t)$.
Integration over this contour is defined by :
$$\int_{\mathcal{C}} f(x,y)\,ds \triangleq \int_a^b f[h(t), g(t)]~~||r'(t)||\,dt$$
where $||r'(t)||$ is the norm of vector $r'(t) = (h'(t), g'(t))^T$
So one gets :
$$\int_{\mathcal{C}} f(x,y)\,ds \triangleq \int_a^b f[h(t), g(t)] \sqrt{h'(t)^2 + g'(t)^2}\,dt$$
====================
Coming back to my earlier question and trying to apply this above development, the "I" integral in previous post should be defined as follows :
$$ I = \int_{\mathcal{C}}f(x_1,x_2)\,ds$$
where $\mathcal{C}$ is a "contour" defined by $x_1 = f_1(x)~,~~x_2 =f_2(x)$
Following the analogy, $I$ becomes :
$$ I = \int_{x\in\mathbb{R}}f[f_1(x),f_2(x)]~||r'(x)||\,dx$$
However, the definition of vector $r'(x)$ is not straightforward. For sure, we have :
$$\,dx_1 = J_{f_1}\,dx~~\text{and}~~\,dx_2 = J_{f_2}\,dx$$
Then, I can only infer the norm of this vector is :
$$||r'(x)|| = \sqrt{\det(J_{f_1})^2 + \det(J_{f_2})^2} $$
so that, when you keep only variable, say $x_1$, you fall back on the former formula for changing of variables.
So, the formula I was looking for is :
$$I = \int_{x\in\mathbb{R}}f[f_1(x),f_2(x)]~\sqrt{\det(J_{f_1})^2 + \det(J_{f_2})^2} \,dx$$
Do you agree with this reasoning ?
Regards


text:
Q: Does db_ddladmin have reader and writer permission in sql server? DDLadmin has privilege's to alter the objects like schema, permissions. But my question is, does db_dlladmin has permission to read (db_datareader) and write (db_datawriter) in database.
Does db_datareader and db_datawriter are subsets of DDLadmin role?

A: By security reason, the Microsoft SQL Server db_ddladmin only can ALTER, CREATE and DROP. It cannot SELECT, UPDATE, INSERT, DELETE nor MERGE or TRUNCATE.
Demo...
CREATE USER USR_DDL WITHOUT LOGIN;
GO

ALTER ROLE db_ddladmin ADD MEMBER USR_DDL
GO

EXECUTE AS USER = 'USR_DDL'

SELECT *
FROM   anytable

Error wil result !


text:
Q: How to create 3 image full size boxes responsive my question is how to create 3 image full size linkable boxes responsive

Please advise, what framework to use?

A: We normally don't do your work here but I made an exception and hope this is your solution:

html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: stretch;
  align-content: stretch;
}

body>div {
  flex-grow: 1;
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  text-align: center;
  display: table;
}

body>div>h1 {
  vertical-align: middle;
  display: table-cell;
}

@media (max-device-width: 20cm) {
  body {
    flex-direction: column;
  }
  body>div {
    height: 33%;
  }
}

Text

Text

Text

A: For a setup as straightforward as this, you can give each image a percentage width of 33.33%.

div {
color: rgb(255, 255, 255);
font-weight: bold;
text-align: center;
line-height: 180px;
}

img {
float: left;
width: 33.33%;
height: 180px;
}

img:nth-of-type(1) {
background-color: rgb(127, 0, 0);
}

img:nth-of-type(2) {
background-color: rgb(127, 127, 0);
}

img:nth-of-type(3) {
background-color: rgb(0, 63, 0);
}

A: You Can Use col-md-4 property of bootstrap for responsive part and insert the desired link in the link tag.
I hope it will help you.


text:
Q: Is it possible to disable sorting in hadoop? My job dosn't require sorting, just aggregation information per key. So I think if it possible to disable sorting of all information in order of increasing performance.

Note: I can't set reducers count to zero because I need to aggregate data between many mappers. I just not interested in sorted result withing one reducer.

A: One of the main purpose to sort the map output is, when the  tuples reaches reducer, reducer has to make ) to invoke reducer task, with the sorted map output list it can make the list just by sequential scan (when it sees different key then just make new list), if the map output is not sorted then it has to scan the whole list to form the list with same key.

A: No, Sorting in MapReduce is essentially performed for internal purposes and not for the end results to be sorted.
Sorted input ensures good performance when creating list of values for unique keys, which are fed as Values> arguments when calling the reduce() function.

A: Shuffling and sorting in Hadoop MapReduce are not performed at all if you specify zero reducers (setNumReduceTasks(0)).
and
The number of reducer can be set to 0 in driver class by job.setNumreduceTasks(0).This shows that there is no reducer phase and has only map phase.It is called as a map-only job.