text:
Q: Expression: vector subscript out of range (Visual C++) I have a problem with my code. While building I am not getting any errors. But while debugging there is an information: "Expression: vector subscript out of range".
I am going to put the whole code (which is about representing the graph using Adjacency List) in here.
I'd be grateful for each answer.
Thanks.
Graph.h
#include <stdio.h>
#include <iostream>
#include <list>
#include <exception>

using namespace std;

class Graph
{
public:
    /*
    Adds an edge between given vertices. Third argument is a weight of an edge (1 by default).
    If the edge already exists or we try to add a loop, no edge is added.

    Error handling:
    throw std::invalid_argument with appropriate message if:
    - we try to create a loop
    - there are no such vertices
    - if the edge already exists
    */
     virtual void addEdge(int u,int v,int weight=1) =0;

     /*
     Removes an edge between given vertices.
     If the edge does not exist, nothing is changed.

     Error handling:
     throw std::invalid_argument with appropriate message if:
     - an edge does not exist
     - vertices do not exist
     */
     virtual void removeEdge(int, int) =0;

    /*
    Returns:
    1 if given vertices are connected by an egde
    0 if the vertices are not connected

    Error handling:
    throw std::invalid_argument with appropriate message if:
    - vertices do not exist
    */
     virtual int areConnected(int,int) =0;

     /*
    Returns:
    the weight of an edge between given vertices.

    Error handling:
    throw std::invalid_argument with appropriate message if:
    - an edge does not exist
    - vertices do not exist
    */
     virtual int getWeight(int,int) =0;

     /*
     Prints the representation of a graph.
     */
    virtual void show() =0;

    /*
    Returns the number of vertices in a graph.
    */
     virtual int getVerticesCount() =0;

     /*
    Returns the number of edges in a graph.
    */
     virtual int getEdgesCount() =0;

     /*
     Returns:
     degree of the given vertex

     Error handling:
     throw std::invalid_argument with appropriate message if:
    - vertex does not exist
     */
    virtual int getDegree(int) =0;

    /* Return a pointer to the clone of the graph (with the same representation) */
    virtual Graph* clone() =0;

    /* Return a pointer to the empty graph with n vertices and the same representation */
    virtual Graph* empty(int) =0;

};

AdjacencyListGraph.h
#include "Graph.h"
#include <vector>

using namespace std;

class AdjacencyListGraph:
    public Graph
{
public:
     /*
     creates a graph with given number of vertices and no edges
     */
     AdjacencyListGraph(int n=0);
     /*
     creates a copy of a given graph
     */
     AdjacencyListGraph(const AdjacencyListGraph&);
     ~AdjacencyListGraph();

     void show() override;
     int getVerticesCount() override;

     void addEdge(int,int,int) override;
     void removeEdge(int, int) override;
     int getEdgesCount() override;
     int getDegree(int) override;
     int areConnected(int,int) override;
     int getWeight(int,int) override;

     Graph* clone() override;
     Graph* empty(int) override;

private:
    /*
        adjacency list
        add whatever is necessary here
    */
    int n;
    vector<vector<int>> neighbors;
    vector<vector<int>> weights;

};

AdjacencyListGraph.cpp
#include "AdjacencyListGraph.h"

/*
 creates a graph with given number of vertices and no edges
*/
AdjacencyListGraph::AdjacencyListGraph(int n) : neighbors(0), weights(0), n(n){}

/*
 creates a copy of a given graph
*/
AdjacencyListGraph::AdjacencyListGraph(const AdjacencyListGraph& other)
{
    this->n = other.n;
    this->neighbors = other.neighbors;
    this->weights = other.weights;
}

/* destructor */
AdjacencyListGraph::~AdjacencyListGraph()
{
    neighbors.clear();
    weights.clear();
}

////////////////////////////////////////////////////////

/*
 Prints the representation of a graph. Make sure that weight are visible.
 Exemplary representation:

0: 1(2) 4(5)
1: 0(2)
2:
3:
4: 0(5)

 Complexity O(n^2)
*/
void AdjacencyListGraph::show()
{
    int i=0;
    while(i < this->n)
    {
        cout << i << ": ";
        size_t j=0;
        while(j < neighbors[i].size())
        {
            cout << neighbors[i][j] << "(" << weights[i][j] << ") ";
            j++;
        }
        cout << endl;
        i++;
    }
}

/*
Returns the number of vertices in a graph.

Complexity O(1)
*/
int AdjacencyListGraph::getVerticesCount()
{
    return n;
}

///////////////////////////////////////////////////////

    /*
    Adds an edge between given vertices. Third argument is a weight of an edge (1 by default).
    If the edge already exists or we try to add a loop, no edge is added.
    Assume that weights are positive integers.

    Error handling:
    throw std::invalid_argument with appropriate message if:
    - we try to create a loop
    - there are no such vertices
    - if the edge already exists

    Complexity O(n)
    */
void AdjacencyListGraph::addEdge(int u,int v, int weight)
{
    //throw invalid_argument("this is the way you throw exception with a given message");
    if(u==v)
        throw invalid_argument("creating a loop is not allowed");

    int a=1;
    for(int g=0; g<n; ++g)
    {
        if(g!=u)
            continue;
        else if(g==u)
        {
            a=2;
            break;
        }
    }
    if(a==1)
        throw invalid_argument("the vertex does not exist");

    int b=1;
    for(int h=0; h<n; ++h)
    {
        if(h!=v)
            continue;
        else if(h==v)
        {
            b=2;
            break;
        }
    }
    if(b==1)
        throw invalid_argument("the vertex does not exist");

    if(weights[u][v]>0)
        throw invalid_argument("the edge already exists");
    else
    {
        neighbors[u].push_back(v);
        weights[u][v]=weight;
    }
}

     /*
     Removes an edge between given vertices.
     If the edge does not exist, nothing is changed.

     Error handling:
     throw std::invalid_argument with appropriate message if:
     - an edge does not exist
     - vertices do not exist

     Complexity O(n)
     */
void AdjacencyListGraph::removeEdge(int u, int v)
{
    if(weights[u][v]==0)
        throw invalid_argument("the edge does not exist");

    int a=1;
    for(int g=0; g<n; ++g)
    {
        if(g!=u)
            continue;
        else if(g==u)
        {
            a=2;
            break;
        }
    }
    if(a==1)
        throw invalid_argument("the vertex does not exist");

    int b=1;
    for(int h=0; h<n; ++h)
    {
        if(h!=v)
            continue;
        else if(h==v)
        {
            b=2;
            break;
        }
    }
    if(b==1)
        throw invalid_argument("the vertex does not exist");

    for(int j=0; j<n; ++j)
    {
        if(j==u)
        {
            for(size_t i=0; i<neighbors[j].size(); ++i)
            {
                if(neighbors[j][i]==v)
                {
                    weights[u][v] = 0;
                    cout << "the edge is removed";
                    return;
                }
            }
        }
    }
}

/*
    Returns the number of edges in a graph.

    Complexity O(n^2)
*/
int AdjacencyListGraph::getEdgesCount()
{
    int count=0;
    for(int i=0; i<n; ++i)
        for(size_t j=0; j<neighbors[i].size(); ++j)
        {
            if(weights[i][j]>0)
                count++;
            else
                continue;
        }
    return count/2;
}

     /*
     Returns:
     degree of the given vertex

     Error handling:
     throw std::invalid_argument with appropriate message if:
    - vertex does not exist

    Complexity O(n)
     */
int AdjacencyListGraph::getDegree(int v)
{
    int b=1;
    for(int h=0; h<n; ++h)
    {
        if(h!=v)
            continue;
        else if(h==v)
        {
            b=2;
            break;
        }
    }
    if(b==1)
        throw invalid_argument("the vertex does not exist");

    int degree=0;
    for(int i=0; i<n; ++i)
    {
        if(i==v)
        {
            for(size_t j=0; j<neighbors[i].size(); ++j)
            {
                    if(weights[i][j]>0)
                        degree++;
            }
            return degree;
        }
    }
}

    /*
    Returns:
    1 if given vertices are connected by an egde
    0 if the vertices are not connected

    Error handling:
    throw std::invalid_argument with appropriate message if:
    - vertices do not exist

    Complexity O(n)
    */
int AdjacencyListGraph::areConnected(int v,int w)
{
    int a=1;
    for(int h=0; h<n; ++h)
    {
        if(h!=v)
            continue;
        else if(h==v)
        {
            a=2;
            break;
        }
    }
    if(a==1)
        throw invalid_argument("the vertex does not exist");

    int b=1;
    for(int h=0; h<n; ++h)
    {
        if(h!=w)
            continue;
        else if(h==w)
        {
            b=2;
            break;
        }
    }
    if(b==1)
        throw invalid_argument("the vertex does not exist");

    for(int j=0; j<n; ++j)
    {
        if(j==v)
        {
            for(size_t i=0; i<neighbors[j].size(); ++i)
            {
                if(neighbors[j][i]==w)
                    if(weights[v][w]>0)
                        return 1;
            }
            return 0;
        }
    }
}

     /*
    Returns:
    the weight of an edge between given vertices.

    Error handling:
    throw std::invalid_argument with appropriate message if:
    - an edge does not exist
    - vertices do not exist

    Complexity O(n)
    */
int AdjacencyListGraph::getWeight(int u, int v)
{
    int a=1;
    for(int g=0; g<n; ++g)
    {
        if(g!=u)
            continue;
        else if(g==u)
        {
            a=2;
            break;
        }
    }
    if(a==1)
        throw invalid_argument("the vertex does not exist");

    int b=1;
    for(int h=0; h<n; ++h)
    {
        if(h!=v)
            continue;
        else if(h==v)
        {
            b=2;
            break;
        }
    }
    if(b==1)
        throw invalid_argument("the vertex does not exist");

    if(weights[u][v]==0)
        throw invalid_argument("the edge does not exist");

    int weight=0;
    for(int i=0; i<n; ++i)
    {
        if(i==u)
        {
            for(size_t j=0; j<neighbors[i].size(); ++j)
            {
                    if(neighbors[i][j]==v)
                    {
                        weight=weights[i][j];
                        return weight;
                    }
            }
        }
    }
}

Graph* AdjacencyListGraph::clone()
{
    Graph *c = new AdjacencyListGraph(*this);
    return c;
}

Graph* AdjacencyListGraph::empty(int n=0)
{
    Graph *c = new AdjacencyListGraph(n);
    return c;
}

main.cpp
#include "AdjacencyListGraph.h"

void main()
{
    Graph &g = AdjacencyListGraph(4);
    try
    {
        cout << "add loop (0,0): ";
        g.addEdge(0,0);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }

    try
    {
        cout << "add edge with non-existing end (0,7): ";
        g.addEdge(0,7);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }

    g.show();

    cout << "add edge (0,1,3)"<<endl;
    g.addEdge(0,1,3);

    cout << "add edge (0,2)"<<endl;;
    g.addEdge(0,2);

    cout << "get weight (0,1): " << g.getWeight(0,1) <<" should be 3"  << endl;
    cout << "get weight (0,2): " << g.getWeight(0,2) <<" should be 1"  << endl;

    Graph* g1 = g.clone();
    g1->show();
    try
    {
        cout << "add loop (1,1): ";
        g1->addEdge(1,1);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }
    cout<<endl;
    cout << "add edge (1,2)"<<endl;
    g.addEdge(1,2);
    cout << "add edge (2,3)"<<endl;
    g.addEdge(2,3);
    try
    {
        cout << "add duplicate edge (2,3,7): ";
        g.addEdge(2,3);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }
    cout << "get weight (2,3): " << g.getWeight(2,3) << " should be 1"  <<endl;
    g.show();
    cout<<endl;
    g1->show();

    cout << "remove edge (1,2)"<<endl;
    g.removeEdge(1,2);

    try
    {
        cout << "remove non-existing edge (1,2): ";
        g.removeEdge(1,2);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }
    try
    {
        cout << "remove edge with non-existing end (1,7): ";
        g.removeEdge(1,7);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }

    cout << "check edge (0,1): " << g.areConnected(0,1) <<" should be 1"     << endl;
    cout << "check edge (0,3): " << g.areConnected(0,3) <<" should be 0"     << endl;

    try
    {
        cout << "check edge with wrong end (0,7): "<< g.areConnected(0,7);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }
    try
    {
        cout << "check edge with wrong end (-1,7): "<< g.areConnected(0,7);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }

    cout << "vertices: " << g.getVerticesCount() <<" should be 4" << endl;
    cout << "edges: " << g.getEdgesCount() <<" should be 3" << endl;

    cout << "deg(0): " << g.getDegree(0) <<" should be 2" << endl;

    try
    {
        cout << "check degree of non-existing vertex deg(7): " << g.getDegree(7);
        cout<<" - should throw invalid_argument exception"<<endl;
    }
    catch (invalid_argument& e)
    {
        cout<<"Exception: "<<e.what()<<" - OK"<<endl;
    }

    delete g1;
    system("pause");
}


text:
Q: Geting XML in specific format c# I am working on MVC web API, where at one function I need to convert SQL DB result into XML file.
private string DbToXml(int fileID)
        {
            DataSet ds = new DataSet("Requirements");
            string connetionString = ConfigurationManager.ConnectionStrings["DemoConnectionString"].ConnectionString;
            string XML;
            using (SqlConnection connection = new SqlConnection(connetionString))
            {
                string sql = "SELECT RequirementLabel as ID, VagueWord, Suggestion, Explanation, VaguePhrase, ContentText, VagueTypeText FROM [Test].[dbo].[Vague_Terms_View] where FileID=" + fileID;
                string XML_Output_Path = System.Configuration.ConfigurationManager.AppSettings.Get("XML_Output_Path");
                connection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
                adapter.Fill(ds, "Requirement");
                var sb = new StringBuilder();
                XmlWriter xmlWrite = XmlWriter.Create(sb);
                ds.WriteXml(xmlWrite);
                XML = ds.GetXml();
            }

I am getting XML from this code like below which is correct.
<?xml version="1.0" encoding="utf-8"?>
<Requirements>
  <Requirement>
    <ID>Req97</ID>
    <VagueWord>or</VagueWord>
    <Suggestion>Keep each requirement in a single sentence.</Suggestion>
    <Explanation>Suggests that you are combining requirements. Requirements that contain conjunctions/disjunctions (AND/OR) are dangerous and can lead to downstream problems in defining scope of the requirement.</Explanation>
    <VaguePhrase>Marketing or Servicing</VaguePhrase>
    <ContentText>If a user is identified as Marketing or Servicing, then the Campaign Management (CM) hyperlink should be displayed.</ContentText>
    <VagueTypeText>Not Standard</VagueTypeText>
  </Requirement>
  <Requirement>
    <ID>Req97</ID>
    <VagueWord>should</VagueWord>
    <Suggestion>Use 'shall/must/will' for requirements,</Suggestion>
    <Explanation>Is often ambiguous, or inappropriate. Some readers will interpret these as optional or advisory, others as required.</Explanation>
    <ContentText>If a user is identified as Marketing or Servicing, then the Campaign Management (CM) hyperlink should be displayed.</ContentText>
    <VagueTypeText>Not Standard</VagueTypeText>
  </Requirement>
  <Requirement>
    <ID>Req98</ID>
    <VagueWord>Unless</VagueWord>
    <Suggestion>Specify each conditions explicitly. One condition per requirement.</Suggestion>
    <Explanation>Is an escape clause. Requirements with escape clauses are not testable. The word implies additional condition to the requirement.</Explanation>
    <ContentText>Unless Sleep, Latency, Noise, or apply conditions are present, the data transmissions will contain the code for Normal Operation.</ContentText>
    <VagueTypeText>Not Standard</VagueTypeText>
  </Requirement>
</Requirements>

But Now I need XML to be converted like, check for ID element inside Requirement node. If it is repeating in below Requirement nodes then rename it and all other elements inside Requirement node to append id=1 and number goes so on.
Expected output for above XML is like below.
<?xml version="1.0" encoding="utf-8"?>
<Requirements>
  <Requirement>
    <ID "id=1">Req97</ID>
    <VagueWord "id=1">or</VagueWord>
    <Suggestion "id=1">Keep each requirement in a single sentence.</Suggestion>
    <Explanation "id=1">Suggests that you are combining requirements. Requirements that contain conjunctions/disjunctions (AND/OR) are dangerous and can lead to downstream problems in defining scope of the requirement.</Explanation>
    <VaguePhrase "id=1">Marketing or Servicing</VaguePhrase>
    <ContentText "id=1">If a user is identified as Marketing or Servicing, then the Campaign Management (CM) hyperlink should be displayed.</ContentText>
    <VagueTypeText "id=1">Not Standard</VagueTypeText>
  </Requirement>
  <Requirement>
    <ID "id=2">Req97</ID>
    <VagueWord "id=2">should</VagueWord>
    <Suggestion "id=2">Use 'shall/must/will' for requirements,</Suggestion>
    <Explanation "id=2">Is often ambiguous, or inappropriate. Some readers will interpret these as optional or advisory, others as required.</Explanation>
    <ContentText "id=2">If a user is identified as Marketing or Servicing, then the Campaign Management (CM) hyperlink should be displayed.</ContentText>
    <VagueTypeText "id=2">Not Standard</VagueTypeText>
  </Requirement>
  <Requirement>
    <ID>Req98</ID>
    <VagueWord>Unless</VagueWord>
    <Suggestion>Specify each conditions explicitly. One condition per requirement.</Suggestion>
    <Explanation>Is an escape clause. Requirements with escape clauses are not testable. The word implies additional condition to the requirement.</Explanation>
    <ContentText>Unless Sleep, Latency, Noise, or apply conditions are present, the data transmissions will contain the code for Normal Operation.</ContentText>
    <VagueTypeText>Not Standard</VagueTypeText>
  </Requirement>
</Requirements>

A: var doc = XElement.Load("test.xml");

var dict = doc.Elements("Requirement")
    .Elements("ID")
    .GroupBy(id => id.Value)
    .ToDictionary(id => id.Key, id => id.Count() > 1 ? 1 : 0);

foreach (var req in doc.Elements("Requirement"))
{
    var id = req.Element("ID").Value;

    if (dict[id] > 0)
    {
        foreach (var elem in req.Elements())
        {
            elem.Add(new XAttribute("id", dict[id]));
        }
        dict[id]++;
    }
}

Now doc contains xml with added id attribute where needed.

A: You can either deserialize it (create objects from XML), modify your IDs as objects and then serialize the objects back to XML or you can edit the XML directly.
This is a good example how to edit an XML directly: How to modify existing XML file with XmlDocument and XmlNode in C#.

A: I have used below solution , not sure if its optimized
 XmlElement root = returnXmlFile.DocumentElement;
         XmlNodeList nodes = root.ChildNodes;
         for (int i = 0; i < nodes.Count; i++)
         {
             string OuterIDvalue = nodes[i].ChildNodes[0].InnerText.ToString();
             const int idVal = 1;
             int counter = 1;
             if (nodes[i].FirstChild.Attributes.Count == 0)
             {
                 for (int ctrInner = 0; ctrInner < nodes[i].ChildNodes.Count; ctrInner++)
                 {
                     XmlAttribute xKey = returnXmlFile.CreateAttribute("id");
                     xKey.Value = idVal.ToString();
                     nodes[i].ChildNodes[ctrInner].Attributes.Append(xKey);
                 }
             }
                 for (int j = i + 1; j < nodes.Count; j++)
                 {
                     string innerIDvalue = nodes[j].ChildNodes[0].InnerText.ToString();
                     if (OuterIDvalue == innerIDvalue && nodes[j].FirstChild.Attributes.Count == 0)
                     {
                         counter++;
                         for (int ctr = 0; ctr < nodes[j].ChildNodes.Count; ctr++)
                         {
                             XmlAttribute xKey = returnXmlFile.CreateAttribute("id");
                             xKey.Value = counter.ToString();
                             nodes[j].ChildNodes[ctr].Attributes.Append(xKey);
                         }
                     }
                 }
         }
         string xmlnew = returnXmlFile.InnerXml;
         returnXmlFile.Save(FileName);
        return xmlnew;
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: i can't modify the css of integrated WordPress code I have a static web page which I use as my main homepage. I am designing the page with HTML and CSS code with some PHP code integrated from My WordPress.
The last integrated code is the code to display the recent 3 posts. It displays the posts, but I can't modify the result with CSS. Here is the PHP code:
<?php
    $args=array('numberposts'=>3,'post_status'=>"publish",'post_type'=>"post",'orderby'=>"post_date");
    $postslist = get_posts( $args );
    echo '
';
    foreach ($postslist as $post) :  setup_postdata($post);
?>

    <?php the_post_thumbnail('medium'); ?>

    <a href="<?php the_permalink(); ?>" title="<?php the_title();?>"> <?php the_title(); ?>

<?php endforeach; ?>

I have tried everything in CSS, naming div, naming span, even using ul in CSS and nothing happens. It keeps it the same as it is.

A: important wouldn't be needed if your css rules are coded properly. The last rules should overwrite any previous ones. Make sure you're targeting the correct elements and put the rules you want to apply in the very end of your css code.

A: use this on your custom css file
   ul.latest_posts{
    list-style: none !important;
    }


text:
Q: Traverse elements that aren't children between two elements with Nokogiri Using Nokogiri, I'm trying to figure out the best way to select div elements that match a css class between two other div elements. Here's some sample HTML of what I'm working with:

  Today

  Tomorrow

What I want is to basically return the divs whose class is "preferred" between the divs with "date" class.
I can grab my starting point with something like:
doc.at("span:contains('Today')").parent

However, I'm not sure the best way to get its next_elements based on class up until the next div.date.

A: I'm applying the Kaysian method for obtaining the intersection of a set (as described in the duplicate link of this question) in the context of your specific scenario (and not considering any other external context which you didn't include in your question).
You need to define two sets:

*

*A: //div[preceding-sibling::div[@class='date']] (all div elements which have a preceding sibling div of the date class.)

*B: //div[following-sibling::div[@class='date']] (all div elements which have a following sibling div of the date class.)

The intersection of those two sets is the solution to your problem. The formula of the Kaysian method is: A [ count(. | B) = count(B) ]. Applying that to your problem, the result you need is:
//div[preceding-sibling::div[@class='date']][count( . | //div[following-sibling::div[@class='date']] ) = count(//div[following-sibling::div[@class='date']] ) ]

This will select the following elements:

If you apply this expression in a global context where there are other
 elements, you will have to adapt it and change your sets so that they uniquely identify the bordering elements.


text:
Q: How to make easy to share offline django projects I have completed a Django project. It runs well on the development server on my machine. However, it can't be shared and run on other devices easily. How can I package it so that it can easily be shared and run on local server, offline on individual machines?
What I do: I use xampp to serve it from Apache then manually copy the necessary files. However this has too many setting up steps, copy paste files and not user friendly at all. Is there a better way?


text:
Q: Collecting all the tests implemented in pytest along with markers I am looking forward to list all the (pytest) test cases in the form of CSV.
Use case scenario:
We already have test cases defined for multiple platforms and databases. These test cases are organized/grouped based on different markers (Ex : platform_linux, platform_centos, db_maria, db_mongo, db_redis etc).
I want to create a CSV file, that contains all the markers and test cases that belong the marker.
Sample of CSV file:
> Marker, Test Cases
> platform_linux, [test_linux1, test_linux2...]
> db_mariadb, [test_mariadb1, test_mariadb2...]

Goal here is to process the CSV file and derive all the tests running on Linux platform with mariadb.
I did get get some answers on collecting test cases (--collect-only) can it be used to create desired CSV?, Do we have existing plugins to achieve the same?

A: I'm not aware of a suitable plugin (though there are hundreds of them, so it may still exist), but you can implement this yourself by implementing pytest_collection_modifyitems. You get there in the collection phase after all items are collected. The collected test items are passed there as a list, which you may use to write out the csv.
You would probably make this dependent on some option with the file name as value. Here is an example:
top-level conftest.py
import csv

def pytest_addoption(parser):
    parser.addoption("--output-tests-csv", action="store", default=None)

def pytest_collection_modifyitems(config, items):
    csv_out = config.getoption("--output-tests-csv")
    if csv_out:
        tests = {}
        # collect all tests with matching markers
        for item in items:
            for mark in item.iter_markers():
                if mark.name.startswith(("platform_", "db_")):
                    tests.setdefault(mark.name, []).append(item.name)
        # write tests in csv (one line per marker)
        with open(csv_out, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile, delimiter=',')
            for marker, tests in tests.items():
                writer.writerow([marker, tests])

This assumes that the markers to consider start with platform_ or db_, you may have to adapt this, also the wanted csv format, but this should give you an idea.

A: There is pytest-csv plugin that provides option to generate required CSV with markers, markers_as_parameters etc.
https://github.com/nicoulaj/pytest-csv
Sample usage (customizing the columns in the CSV):
py.test --csv tests.csv --csv-columns host,function,status,duration,parameters_as_columns

Note: requirement pytest >= 6.0


text:
Q: Dynamic Database Stored Procedure on SQL Server 2016 I'm trying to build a stored procedure that will query multiple database depending on the databases required.
For example:
SP_Users takes a list of @DATABASES as parameters.
For each database it needs to run the same query and union the results together.
I believe a CTE could be my best bet so I have something like this at the moment.
SET @DATABASES = 'DB_1, DB_2'  -- Two databases in a string listed

-- I have a split string function that will extract each database
SET @CURRENT_DB = 'DB_1'

WITH UsersCTE (Name, Email)
AS (SELECT Name, Email
    FROM [@CURRENT_DB].[dbo].Users),

    SELECT @DATABASE as DB, Name, Email
    FROM UsersCTE

What I don't want to do is hard code the databases in the query. The steps I image are:

*

*Split the parameter @DATABASES to extract and set the @CURRENT_DB Variable

*Iterate through the query with a Recursive CTE until all the @DATABASES have been processed

*Union all results together and return the data.

Not sure if this is the right approach to tackling this problem.

A: Using @databases:
As mentioned in the comments to your question, variables cant be used to dynamically select a database.  Dynamic sql is indicated.  You can start by building your template sql statement:
declare @sql nvarchar(max) =
    'union all ' +
    'select ''@db'' as db, name, email ' +
    'from [@db].dbo.users ';

Since you have sql server 2016, you can split using the string_split function, with your @databases variable as input.  This will result in a table with 'value' as the column name, which holds the database names.
Use the replace function to replace @db in the template with value.  This will result in one sql statement for each database you passed into @databases.  Then, concatenate the statements back together.  Unfortunately, in version 2016, there's no built in function to do that.  So we have to use the famous for xml trick to join the statements, then we use .value to convert it to a string, and finally we use stuff to get rid of the leading union all statement.
Take the results of the concatenated output, and overwrite the @sql variable.  It is ready to go at this point, so execute it.
I do all that is described in this code:
declare @databases nvarchar(max) = 'db_1,db_2';

set @sql = stuff(
    (

        select      replace(@sql, '@db', value)
        from        string_split(@databases, ',')
        for xml     path(''), type

    ).value('.[1]', 'nvarchar(max)')
    , 1, 9, '');

exec(@sql);

Untested, of course, but if you print instead of execute, it seems to give the proper sql statement for your needs.
Using msForEachDB:
Now, if you didn't want to have to know which databases had 'users', such as if you're in an environment where you have a different database for every client, you can use sp_msForEachDb and check the structure first to make sure it has a 'users' table with 'name' and 'email' columns.  If so, execute the appropriate statement.  If not, execute a dummy statement.  I won't describe this one, I'll just give the code:
declare @aggregator table (
    db sysname,
    name int,
    email nvarchar(255)
);

insert @aggregator
exec sp_msforeachdb '

    declare @sql nvarchar(max) = ''select db = '''''''', name = '''''''', email = '''''''' where 1 = 2'';

    select      @sql = ''select db = ''''?'''', name, email from ['' + table_catalog + ''].dbo.users''
    from        [?].information_schema.columns
    where       table_schema = ''dbo''
    and         table_name = ''users''
    and         column_name in (''name'', ''email'')
    group by    table_catalog
    having      count(*) = 2

    exec (@sql);

';

select      *
from        @aggregator

A: I took the valid advice from others here and went with this which works great for what I need:
I decided to use a loop to build the query up. Hope this helps someone else looking to do something similar.
CREATE PROCEDURE [dbo].[SP_Users](
    @DATABASES VARCHAR(MAX) = NULL,
    @PARAM1 VARCHAR(250),
    @PARAM2 VARCHAR(250)
)

BEGIN
    SET NOCOUNT ON;

    --Local variables
    DECLARE
     @COUNTER INT = 0,
     @SQL NVARCHAR(MAX) = '',
     @CURRENTDB VARCHAR(50) = NULL,
     @MAX INT = 0,
     @ERRORMSG VARCHAR(MAX)

    --Check we have databases entered
    IF @DATABASES IS NULL
    BEGIN
        RAISERROR('ERROR: No Databases Provided,
        Please Provide a list of databases to execute procedure. See stored procedure:
        [SP_Users]', 16, 1)
        RETURN
    END

    -- SET Number of iterations based on number of returned databases
    SET @MAX = (SELECT COUNT(*) FROM
               (SELECT ROW_NUMBER() OVER (ORDER BY i.value) AS RowNumber,  i.value
               FROM dbo.udf_SplitVariable(@DATABASES, ',') AS i)X)

    -- Build SQL Statement
    WHILE @COUNTER < @MAX
        BEGIN

        --Set the current database
        SET @CURRENTDB = (SELECT X.Value FROM
            (SELECT ROW_NUMBER() OVER (ORDER BY i.value) AS RowNumber,  i.value
            FROM dbo.udf_SplitVariable(@DATABASES, ',') AS i
            ORDER BY RowNumber OFFSET @COUNTER
            ROWS FETCH NEXT 1 ROWS ONLY) X);

        SET @SQL = @SQL + N'
                          (
                          SELECT Name, Email
                          FROM [' + @CURRENTDB + '].[dbo].Users
                          WHERE
                              (Name = @PARAM1 OR @PARAM1 IS NULL)
                              (Email = @PARAM2 OR @PARAM2 IS NULL)
                          ) '
                          + N' UNION ALL '

            END
            PRINT @CURRENTDB
            PRINT @SQL

            SET @COUNTER = @COUNTER + 1
        END

        -- remove last N' UNION ALL '
        IF LEN(@SQL) > 11
            SET @SQL = LEFT(@SQL, LEN(@SQL) - 11)

        EXEC sp_executesql @SQL, N'@CURRENTDB VARCHAR(50),
                                   @PARAM1 VARCHAR(250),
                                   @PARAM2 VARCHAR(250)',
                                   @CURRENTDB,
                                   @PARAM1 ,
                                   @PARAM2

END

Split Variable Function
CREATE FUNCTION [dbo].[udf_SplitVariable]
(
    @List varchar(8000),
    @SplitOn varchar(5) = ','
)

RETURNS @RtnValue TABLE
(
    Id INT IDENTITY(1,1),
    Value VARCHAR(8000)
)

AS
BEGIN

--Account for ticks
SET @List = (REPLACE(@List, '''', ''))

--Account for 'emptynull'
IF LTRIM(RTRIM(@List)) = 'emptynull'
BEGIN
    SET @List = ''
END

--Loop through all of the items in the string and add records for each item
WHILE (CHARINDEX(@SplitOn,@List)>0)
BEGIN

    INSERT INTO @RtnValue (value)
    SELECT Value = LTRIM(RTRIM(SUBSTRING(@List, 1, CHARINDEX(@SplitOn, @List)-1)))

    SET @List = SUBSTRING(@List, CHARINDEX(@SplitOn,@List) + LEN(@SplitOn), LEN(@List))

END

INSERT INTO @RtnValue (Value)
SELECT Value = LTRIM(RTRIM(@List))

RETURN

END


text:
Q: Is it true that $\textrm{Rad}(R)=\bigcap I$ where $I$'s are both two-sided ideals in $R$ and maximal left ideals in $R$? Define Jacobson radical $\textrm{Rad}(M)$ of a module $M$ as the intersection of all it's maximal submodules.
Let $R$ be an associative ring with unity. It's clear thar $\textrm{Rad}(_RR)$ coincides with the intersection of annihilators of all simple left $R$-modules. Hence, $$\textrm{Rad}(_RR)=\bigcap\limits_{I\textrm{ is a maximal left ideal of }R}\textrm{Ann}_R(R/I)=\bigcap\limits_I\,(I:R)$$ where $(I:R)=\{x\in R\,|\,xR\subseteq I\}$ is the largest (two-sided) ideal of $R$ which lies in $I$. In particular, $\textrm{Rad}(_RR)$ is an ideal of $R$.
Moreover, $\textrm{Rad}(_RR)=\{s\in R\,|\,\forall r\in R: 1+rs\textrm{ has the left inverse in } R\}.$
In fact, this definition is symmetric: $\textrm{Rad}(_RR)=\textrm{Rad}(R_R),$ so, we can talk about Jacobson radical of $R$ which we denote $\textrm{Rad}(R).$
My question is:

Is it true that $\textrm{Rad}(R)=\bigcap I$ where $I$'s are both two-sided ideals in $R$ and maximal left ideals in $R$?

Clearly, $\textrm{Rad}(R)\subseteq\bigcap I.$ I suppose that the inverse inclusion does not hold in general but cannot find a counterexample. Do you know a one? Any help is appreciate!

A:
Is it true that $\textrm{Rad}(R)=\bigcap I$ where $I$'s are both two-sided ideals in $R$ and maximal left ideals in $R$?

No: consider a field $F$ and $R=F\times M_2(F)$.  It has four ideals: $\{0\}\times \{0\}$, $F\times \{0\}$, $\{0\}\times M_2(F)$ and $R$.
The only one which is maximal as a left ideal is $\{0\}\times M_2(F)$, but the Jacobson radical is $\{0\}\times \{0\}$.
But the containment you said is of course correct: a two-sided ideal that is maximal as a left ideal is certainly a maximal two-sided ideal, and the Jacobson radical is contained in such ideals.


text:
Q: multiple threads injecting data into the subsequent process I have a project made using Java.
I have a complex processing, something like from one single process i create 10 different threads, then the process waits for the other threads to complete processing. Now the threads that were created do some database processsing, and then finally generates the output. But the problem here is, the process that have been waiting, again needs to process all the data that was created in the threads that were created, sort of aggregated result.
I am almost clueless what needs to be done.
Regards

A: You could use a java.util.concurrent.ConcurrentLinkedQueue.  Have each thread put their results on the queue when they're done.  The main thread just watches the queue and processes the results as they come in.
Another alternative is to use Futures.  Instead of threads just use Futures for each of the processes.  The main thread will block while waiting for each future to finish it's processing.

A: You might consider using a BlockingQueue to aggregate all your data in one data structure.
This queue can then be used by your main process (even before all your threads actually finished their work).

A: You'll need to start 10 threads in your main thread, and wait for them to finish. This can be done calling Thread.join() on each of the 10 started threads (after they are all started).
For more information about threads, read the Java tutorial about concurrency.

A: If your difficulty is how to wait in the main thread until child threads complete their work , then you can use childThread.join() on child threads from the main thread.  If you are troubled by how to make the results brought by the child threads from db availble to the main thread for processing , then use some shared data structure which is populated by the child threads and which is then accessed by the main thread. ( Make sure you synchronize properly )
For all such tasks however , it is best to use Executor framework in Java 1.6.

A: You could just use a shared object to add data to it.
If I understand right then:
Create a class that will hold all data in the end (for example MyData). This class could have "getData" method that will return data and "add" method which will add data to some collection of your choice (array, list, ...).
Then when a thread is done with processing the data it calls:
MyData.add(partialDataFromThread)

And in the end your main class will do:
MainClass.process(MyData.getDatA());

Hope it helps...

A: You can use java.util.concurrent.CompletionService to submit and poll for the task completion.
Alternatively look into CountdownLatch or the CyclicBarrier classes.
Let me know if you need examples because I assume internet would already be flooded with such examples; also the javadocs are pretty good and it is always a good learning curve to do it first hand.


text:
Q: Mock Repository but the Repository didn't found [NestJS] my unit testing

describe('AssetService', ()=>{
    let assetService: AssetService;
    let assetRepository: AssetRepository;

    beforeEach(async () =>{
        const module = await Test.createTestingModule({
            providers: [AssetService, TenantProfileService, ProfileUserService,
                TenantsService, UsersService,
                {provide: AssetRepository, useFactory: ()=>({
                    find: jest.fn(()=>[])
                })},
            ],

        }).compile();

        assetService = await module.get(AssetService);
        assetRepository = await module.get(AssetRepository);

    });

    describe('getAssets',()=>{
        it('call assetRepository.find and should return all assets', async ()=>{
            const result = await assetService.findAll(null, null);
            expect(assetRepository.find).toHaveBeenCalled();
        });
    })
})

Hi, I am just trying to mock my repository but I got error. It like my repository never exists. I use jest.fn but it still didn't work.
my code
  async findAll(limit:number=50, keyword:string): Promise<Asset[]> {
    let options: FilterQuery<AssetDocument>;
    if (keyword){
      options = {assetName: {$regex: keyword, $options: 'i'}}
    }else{
      options = {}
    }
    return this.assetRepository.find(options, limit);
  }

I used mongoose and build own repository


text:
Q: Creating new matrix from output values of a function in r? Hi I have made a function Get to calculate the mean and SD from a data set, I have seven data sets of the same format and want to put the output  applying the Get function to these data sets in one matrix to compare. I know I need one more step in my function but cannot figure it out? Also id there away to loop this over each data set automatically if the names are CA1, CA2, ...? I am new to R
This is the function
 Get <- function (x) {
  x <- as.matrix(x)
  m <- mean(x[,3:4])
  SD <- sd(x[,3:4])
  return(list(mean=m, SD=SD))
}

A: Try:
 set.seed(42) #creating some datasets
 CA1 <- as.data.frame(matrix(sample(1:20, 5*20, replace=TRUE), ncol=5))
 CA2 <- as.data.frame(matrix(sample(1:20, 5*20, replace=TRUE), ncol=5))
 CA3 <- as.data.frame(matrix(sample(1:20, 5*20, replace=TRUE), ncol=5))

 nm1 <- ls(pattern="^CA\\d")
 res <- sapply(mget(nm1), Get)
 res #here you get a list of `6`
 #     CA1      CA2      CA3
 #mean 10.1     9.9      9.275
 #SD   6.058687 5.490318 5.579208

To convert to matrix
 m1 <- matrix(unlist(res), ncol=3, dimnames=dimnames(res))
 m1
 #         CA1      CA2      CA3
 #mean 10.100000 9.900000 9.275000
 #SD    6.058687 5.490318 5.579208


text:
Q: Spinner with JQuery or Javascript or HTML? I want to write a spinner code at javascript/jQuery to get minute and hour from user.
I want to implement this with Jquery or Javascript or HTML:

I have implemented the calendar part (at left at screenshot) with JQuery datepicker. There are two spinners over there and hour range is from 00 to 23. Minute range is 00 to 59.
How can I do it?

A: What's in the screenshot isn't exactly a spinner - it's just a <select> with the values from 00 to 59 filled in.
With jQuery:
var select = $('#minute');
for (var i = 0; i < 60; i++) {
    $('<option>', {
        value: i,
        text: (i < 10 ? '0' + i : i)
    }).appendTo(select);
}

You'll also need this HTML in your form:
<select id="minute"></select>

Here is a demo: http://jsfiddle.net/yhmAT/

A: I've really liked Keith Wood's take on date and time entry:
http://keith-wood.name/timeEntry.html


text:
Q: Cannot store file content in hashicorp vault using Vault kv put I am trying to add file content in vault using vault kv put but I am unable to add data in vault
vault kv put -format=json -address ${VAULT_ADDR} key=@abc.json
Here the error says "Must supply data"
I also tried various other options like -
vault kv put -format=json -address ${VAULT_ADDR} key @abc.json
Here key is being added into vault address url e.g vault-address/key
&
vault kv put -format=json -address ${VAULT_ADDR} @abc.json
Here error says "Must supply data"
My Json file is sample test file and has following content in it
{
  "key": "value",
  "foo": "bar",
  "bar": "baz"
}

Can someone please help me solving this issue?

A: You can directly create secret without -format=json. The below command worked for me.
vault kv put app/dev/test @test.json


text:
Q: What CMS to use? We are currently building a deal aggregator site. It collect deals from deal sites and present them in categories. Each deal presented in our website contains a photo, description, location, price and the url of the deal shop. Payments is done directly to the deal website so, our site is just a deal viewer without inner pages.
We decided to build it on an existing cms engine, to have all features such as management, searching, etc.
What cms you will suggest for it? Wordpress, Joomla or what? Any other information is appreciated.

A: Drupal is my choice. It has been working great for my case. I use the module from commerce guys. For my case the following were the basics:

*

*Views

*View mode (different from views)

*Commerce I have been used it for 3 months now with no problem. They release also an expiration cart recently so you don't have to program it, just customize it. Also they have a simple module commerce stock if you don't need something very complicated.

*Take a look for display suite in case you want to use the minimum templates.

The good thing about Drupal is how easy is to customize things. I worked in Joomla also. But I feel Drupal is in some ways more flexible. One feature I love about Drupal (not sure if others has it) is that when there is a security update or any update it display the notifications in your site.
You can find more information about those modules and see how they work. Here are my favorite links:
Commerce module

*

*demo

*videos of commerce module
Views

*

*views simple introduction
Views Mode

*

*view mode drupalconf
display suite

*

*display suite conf in London

A: Drupal.  This is what it is designed for and there are more online resources devoted to this CMS than any other.

A: Drupal is your best open source option. Lots of support and [relatively] painless deployment. Look at something like Refinery (Ruby on Rails) if you want more customization.


text:
Q: Run terrform in azure functions powershell We are developing an azure function which should run terraform cmdlets like init, plan and apply.
when we run above commands in powershell, we are getting below error.
Error checking configuration: <nil>: Failed to read module directory; Module directory C:\home\site\wwwroot\databricks-user-sync-modules does not exist or cannot be read

My run.ps1 file includes below sinppet
write-output (terraform --version)
Write-Output ((Get-ChildItem).Name)
Get-Content -Path main.tf
write-output (terraform init)
terraform plan -var-file dev.tfvars

How to run terraform in azure functions.

A: The error message you are receiving may or may not be related to your attempt to use terraform in Azure Functions.
I'd initially ask whether Azure Functions is the ideal solution to the problem you're trying to solve?
Based on the fact that the functions runtime doesn't include the terraform binary in order to run tf cli commands. You may have more success using Azure Devops pipelines or Github Actions to deploy your terraform code.
Both AzDo and Github can trigger CI/CD operations via a webhook.
https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#repository_dispatch
and
https://learn.microsoft.com/en-us/azure/devops/release-notes/2020/pipelines/sprint-172-update
Unless I am missing something obvious, you may have to provide more context around why you're using Azure Functions for this scenario


text:
Q: Dispersing results from grid onto multiple pages with MCV I currently have view with a grid displaying some data ( I would prefer a table but this is what was wanted). The query that returns the data can have the possibility to return 100+ records.
I would like to be able to only display 10 records at a time, and then put the rest of the results on another page, where user can click button 2,3,4 ect.
Normally I would just do this using Data-Tables, but since this is a grid, I am not quite sure how to handle this. Below is my code. If anyone could give me an idea or point me in the right direction I would greatly appreciate it.
View:
@using (Html.BeginForm("SearchGenericLogs", "Tools", FormMethod.Post)){

    <form class="form-inline row">

            @Html.DropDownListFor(m => m.LogLevelId, new SelectList(Model.LogLevels, "pkLogLevelId", "LogLevel", Model.LogLevelId), new { @class = "form-control", data_toggle = "tooltip", title = Html.DisplayNameFor(m => m.LogLevelId) })

            @Html.DropDownListFor(m => m.LogSource, new SelectList(Model.LogSourceCodes, "pkLogSourceCode", "LogSource", Model.LogSource), new { @class = "form-control", data_toggle = "tooltip", title = Html.DisplayNameFor(m => m.LogSource) })

            @Html.TextBoxFor(m => m.EntityId, new { @class = "form-control", type = "number", placeholder = Html.DisplayNameFor(m => m.EntityId), data_toggle = "tooltip", title = Html.DisplayNameFor(m => m.EntityId) })

            @Html.TextBoxFor(m => m.FromLogDate, new { @class = "form-control", type = "DateTime", placeholder = Html.DisplayNameFor(m => m.FromLogDate), data_toggle = "tooltip", title = Html.DisplayNameFor(m => m.FromLogDate) })

            @Html.TextBoxFor(m => m.ToLogDate, new { @class = "form-control", type = "DateTime", placeholder = Html.DisplayNameFor(m => m.ToLogDate), data_toggle = "tooltip", title = Html.DisplayNameFor(m => m.ToLogDate) })

            <button type="submit" class="btn btn-primary">Submit</button>

    </form>

 ID

 Source

 Level

 Entity ID

 Log Date

 Message

    @foreach (var item in Model.Logs)
    {

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

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

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

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

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

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

    }

}

I would post the controller action as well, except this app is a bit more complex than your typical Model, View, Controller. If anyone needs more info let me know. I can update OP.


text:
Q: Virasoro Algebra vs Witt Algebra I'm reading some notes on CFT, and there's a strange topic that I find quite confusing. We define the Witt algebra to be the generators of conformal transformations on the complex plane.
$l_n = -z^{n+1}\partial_z$
$[l_n,l_m] = (m-n)l_{m+n}$
But then we perform something called the central extension which changes our algebra to the Virasoro algebra.
I'm okay with that. But then we go on to define the generators of conformal symmetry as contour integrals of the stress-energy tensor, and these satisfy not the Witt algebra but the Virasoro algebra. Is there a good reason for this?

A: Basically the reason is that the classical conformal symmetry no longer holds at the quantum level due to the presence of the trace anomaly. More precisely, the tracelessness of the quantum stress-energy tensor is incompatible with the normal ordering needed to define it. By cohomological reasons, the trace of the stress-energy tensor, although non-vanishing, must be a central element of the "quantized Witt algebra", i.e. it must commute with all its generators. This implies that the "quantized Witt algebra" must be a non-trivial central extension of the Witt algebra, which in this particular case must be unique up to isomorphism (thanks to user106422 for recalling this point below) - that is, a Virasoro algebra.
An exposition I particularly like on such matters is the little book of Martin Schottenloher, "A Mathematical Introduction to Conformal Field Theory" (2nd. edition),  Lecture Notes in Physics 759 (Springer--Verlag, 2008).
Edit (June 15th 2022): this comes more than six years late, but only now have I managed to get time to think about Peter Kravchuk's two (correct) points in his comments. I apologize to all.

*

*Indeed the trace anomaly only appears in curved space-time. More precisely, if your reference state has a short-distance behavior similar to that of the Minkowski vacuum state (in the case of Lagrangian free fields, this reduces to the Hadamard property for the two-point function in that state), the expectation value of the trace of the normal-ordered stress-energy tensor (w.r.t. the aforementioned reference state by e.g. point splitting and exploiting the operator product expansion) is state-independent and proportional to both the central charge and the scalar curvature (even if e.g. in the case of Lagrangian free fields you conformally couple the field to the curvature so as to keep the conformal symmetry of the model at the classical level). In other words, the trace anomaly is always there; we just do not see it where the scalar curvature vanishes. The role of the latter is to introduce a scale into the model through the coupling of the field dynamics with the background metric. Curvature, however, is not the only way to do this; another one is to impose boundary conditions on the conformal field theory - the Casimir energy is then also seen to be proportional to the central charge. As a rule, the central charge manifests itself physically as a way the conformal field model reacts to the introduction of an external macroscopic scale by means of a partial (anomalous, not spontaneous) breakdown of that symmetry. A more detailed discussion on this may be found e.g. in pp. 138-146 of the book by P. Di Francesco, P. Mathieu and D. Sénéchal, Conformal Field Theory (Springer-Verlag, 1997).

*In four dimensions the conformal Lie algebra is (semi)simple and therefore has no nontrivial central extensions, but both the trace anomaly in the presence of curvature and the Casimir energy in the presence of boundary conditions persist, so what changes? Well, recall that in four dimensions conformal transformations (in Lorentz signature) are composites of Poincaré transformations, (rigid) scale transformations and the so-called special conformal transformations, whereas the group of conformal transformations in two dimensions is much larger than that (in fact, infinite dimensional!). In Euclidean signature, (one of the two chiral components of) the conformal subgroup generated in the same way as in higher dimensions consists of Möbius transformations on the complex plane and therefore equals the semisimple Lie group $SL(2,\mathbb{R})$. The corresponding "rigid" (Möbius) part of the Witt Lie algebra (generated by $l_0$, $l_1$ and $l_{-1}$), which generates all Möbius transformations, sees no change in the commutation relations among their generators when we perform the central extension to obtain the Virasoro algebra, since the central part of $[l_n,l_m]$ is then given by $\frac{c}{12}(n^3-n)\delta_{m+n,0}$, where $c$ is the central charge. In other words, the Möbius Lie subalgebra does not "see" $c$, just like in higher dimensions. Nonetheless, the appearance of the scalar curvature in the trace anomaly formula shows that this anomaly really only affects "local" (i.e. non-"rigid") conformal transformations. In the case of boundary conditions, they affect the field algebra itself (e.g. in the case of free fields the causal commutator Green function must respect the boundary conditions) and hence also the normal ordering of the stress-energy tensor through shifting by central elements of the field algebra. Needless to say, usually global (resp. "rigid" = Möbius) conformal transformations (resp. in two dimensions) do not survive either the introduction of curvature or boundary conditions, so the role of the ("rigid") conformal Lie (sub)algebra in the present matter becomes moot since they no longer generate symmetries of the field theory anyway.


text:
Q: Android Cloud Firestore document fields query How to query all timestamps for a certain date (20210205) and certain user (ala) from Cloud Firestore in the below example? For now, I can download the entire document and filter it on the device. But it's not effective.
FirebaseFirestore db = FirebaseFirestore.getInstance();
    db.collection("companies").document("softnet").collection("users")
            .document("ala").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            Log.d(TAG, "result: " + task.getResult().getData());
        }
    });

A: You can filter for FieldPath.documentId() as shown here to get the ala document in a query. But as you commented yourself, there's no way to then filter with a wildcard of fields.
The best I can quickly think of is to store an array of dates:
dates: ["20210203", "20210205", "20210207"]

If you use the arrayUnion operator to add values to this array, you'll never end up with duplicates, and then you can use array-contains to check if the array contains a specific date.
So in total that'd be something like (syntax errors definitely possible):
CollectionRefefence users = db.collection("companies").document("softnet").collection("users");
users
  .whereEqualTo(FieldPath.documentId(), "ala")
  .whereArrayContains("date", "20210207");

Honestly though, you'll have to consider if the complexity is worth it, as it's probably simpler to just read the single document that this query returns, and check for the date field in application code.


text:
Q: jekyll assign concat in a loop? I would like to organize a page based on the number of pages that pass a filter.
I have tried to append truthy pages to a collection but it doesn't work.
{% assign homepage_posts = [] %}
{% for my_page in site.pages %}
  {% if my_page.homepage %}
    {% assign homepage_posts = homepage_posts | concat: [my_page] %}
  {% endif %}
{% endfor %}

size{{homepage_posts.size}}

{{homepage_posts}}

This is not working. Does concat only work with strings?

A: Jekyll will use Liquid 4 soon. But, for now, no concat.
In your case you can :
Create an empty array (bracket notation doesn't work in liquid) : {% assign homepage_posts = "" | split:"/" %}
{{ homepage_posts | inspect }} --> output : []
And push elements in it :
{% for my_page in site.pages %}
  {% if my_page.homepage %}
    {% assign homepage_posts = homepage_posts | push: mypage %}
  {% endif %}
{% endfor %}

{{ homepage_posts | inspect }}

A: concat filter only works with arrays and will be available in Jekyll when it upgrades to Liquid 4.*:

concat
Concatenates (combines) an array with another array. The resulting
  array contains all the elements of the original arrays. concat will
  not remove duplicate entries from the concatenated array unless you
  also use the uniq filter.

To filter pages containing a specific attribute (in this case homepage: true) you can use a where filter.
Having a page with front matter:
---
homepage: true
---

Then you can have the pages with the homepage: true attribute like:
{% assign homepages = site.pages | where:"homepage","true" %}


text:
Q: android - Navigation graph Flow Preview in landscape The navigation graph preview of Android jetpack components always shows a portrait view of screens for the screens in the layout editor. Can we customize this to view the screens on an emulator of our choice?

A: In Android Studio 4.1.1 it is possible to switch between screen orientations in the navigation graph preview screen by tapping o key (the letter 'O', not the number 0).


text:
Q: Fetch jsonArray without loop in Android {
"jsonArray": [
    {
        "id": "1",
        "person": "Jason",
        "thur": "F",
        "grade": "17",
        "round": "2"
    },
    {
        "id": "2",
        "person": "Joe",
        "grade": "F",
        "score": "16",
       "round": "3"
    }

    ]
}

I want to fetch "person" and to store it in to string[], But without any loop.
In iOS I'll do it like this.
 NSArray *personArray = [jsonArray valueForKey:@"person"];

A: In android you can use Google library called Gson
for example You can create a class like this
    private class ClassObj {
        @SerializedName("personA")
        private final String personA;
    }

And then parse it
ClassObj object = gson.fromJson(jsonString, ClassObj.class);

ClassObj can contain other sub classes too ;)


text:
Q: Listbox or Listview or Gridview? I am trying to achieve this.

I have a list of records (filenames) which I want to show in a list.
Anybody has any idea as to which control to use.
Regards,
Deepak

A: The information is right at your fingertips. You should learn to use Snoop.  Aside from that, you should choose whatever control works best for you, which requires you to learn the difference between each.  We can't really provide a good answer because there are many different ways this control could be implemented, and that's why WPF is so powerful.
Basically, you'll want to use a mixture of a Grid and ItemsControl.  You can see the layout of the controls that are being used in this screenshot:


text:
Q: How would one go about testing an interpreter or a compiler? I've been experimenting with creating an interpreter for Brainfuck, and while quite simple to make and get up and running, part of me wants to be able to run tests against it.  I can't seem to fathom how many tests one might have to write to test all the possible instruction combinations to ensure that the implementation is proper.
Obviously, with Brainfuck, the instruction set is small, but I can't help but think that as more instructions are added, your test code would grow exponentially.  More so than your typical tests at any rate.
Now, I'm about as newbie as you can get in terms of writing compilers and interpreters, so my assumptions could very well be way off base.
Basically, where do you even begin with testing on something like this?

A: I don't think there's anything 'special' about testing a compiler; in a sense it's almost easier than testing some programs, since a compiler has such a basic high-level summary - you hand in source, it gives you back (possibly) compiled code and (possibly) a set of diagnostic messages.
Like any complex software entity, there will be many code paths, but since it's all very data-oriented (text in, text and bytes out) it's straightforward to author tests.

A: I've written an article on compiler testing, the original conclusion of which (slightly toned down for publication) was:  It's morally wrong to reinvent the wheel.  Unless you already know all about the preexisting solutions and have a very good reason for ignoring them, you should start by looking at the tools that already exist.  The easiest place to start is Gnu C Torture, but bear in mind that it's based on Deja Gnu, which has, shall we say, issues.  (It took me six attempts even to get the maintainer to allow a critical bug report about the Hello World example onto the mailing list.)
I'll immodestly suggest that you look at the following as a starting place for tools to investigate:

*

*Software: Practice and Experience April 2007. (Payware, not available to the general public---free preprint at http://pobox.com/~flash/Practical_Testing_of_C99.pdf.

*http://en.wikipedia.org/wiki/Compiler_correctness#Testing (Largely written by me.)

*Compiler testing bibliography (Please let me know of any updates I've missed.)

A: Testing a compiler is a little different from testing some other kinds of apps, because it's OK for the compiler to produce different assembly-code versions of a program as long as they all do the right thing.  However, if you're just testing an interpreter, it's pretty much the same as any other text-based application.  Here is a Unix-centric view:

*

*You will want to build up a regression test suite.  Each test should have

*

*Source code you will interpret, say test001.bf

*Standard input to the program you will interpret, say test001.0

*What you expect the interpreter to produce on standard output, say test001.1

*What you expect the interpreter to produce on standard error, say test001.2  (you care about standard error because you want to test your interpreter's error messages)

*You will need a "run test" script that does something like the following
function fail {
  echo "Unexpected differences on $1:"
  diff $2 $3
  exit 1
}

for testname
do
  tmp1=$(tempfile)
  tmp2=$(tempfile)
  brainfuck $testname.bf < $testname.0 > $tmp1 2> $tmp2
  [ cmp -s $testname.1 $tmp1 ] || fail "stdout" $testname.1 $tmp1
  [ cmp -s $testname.2 $tmp2 ] || fail "stderr" $testname.2 $tmp2
done

*You will find it helpful to have a "create test" script that does something like
brainfuck $testname.bf < $testname.0 > $testname.1 2> $testname.2

You run this only when you're totally confident that the interpreter works for that case.

*You keep your test suite under source control.

*It's convenient to embellish your test script so you can leave out files that are expected to be empty.

*Any time anything changes, you re-run all the tests.  You probably also re-run them all nightly via a cron job.

*Finally, you want to add enough tests to get good test coverage of your compiler's source code.  The quality of coverage tools varies widely, but GNU Gcov is an adequate coverage tool.
Good luck with your interpreter!  If you want to see a lovingly crafted but not very well documented testing infrastructure, go look at the test2 directory for the Quick C-- compiler.

A: In the case of brainfuck, I think testing it should be done with brainfuck scripts. I would test the following, though:
1: Are all the cells initialized to 0
2: What happens when you decrement the data pointer when it's currently pointing to the first cell? Does it wrap? Does it point to invalid memory?
3: What happens when you increment the data pointer when it's pointing at the last cell? Does it wrap? Does it point to invalid memory
4: Does output function correctly
5: Does input function correctly
6: Does the [ ] stuff work correctly
7: What happens when you increment a byte more than 255 times, does it wrap to 0 properly, or is it incorrectly treated as an integer or other value.
More tests are possible too, but this is probably where i'd start. I wrote a BF compiler a few years ago, and that had a few extra tests. Particularly I tested the [ ] stuff heavily, by having a lot of code inside the block, since an early version of my code generator had issues there (on x86 using a jxx I had issues when the block produced more than 128 bytes or so of code, resulting in invalid x86 asm).

A: The secret is to:

*

*Separate the concerns

*Observe the law of Demeter

*Inject your dependencies

Well, software that is hard to test is a sign that the developer wrote it like it's 1985. Sorry to say that, but utilizing the three principles I presented here, even line numbered BASIC would be unit testable (it IS possible to inject dependencies into BASIC, because you can do "goto variable".

A: You can test with some already written apps.


text:
Q: rsyslog update on Amazon Linux suddenly treats INFO level messages as EMERG I'm having strange issue with rsyslog on some of my EC2 instances running Amazon Linux 2012.3.
Upon yum upgrading rsyslog 4.6 to 5.8.10, it seems like every INFO level log message is suddenly treated as an EMERG level issue and they are getting broadcast everywhere. Commenting out *.emerg    * from /etc/rsyslog.conf squelches the messages, but obviously that's not much of a solution.
The messages look like this:
Message from syslogd@hostname at Jul 13 19:35:07 ...
¿<14>processname[1696]: INFO <yadayadayada>

Most of my logging is coming from a Python 2.6 logger with a logging.handler.SysLogHandler, the configuration of which I've posted below. I've had no luck finding any other information about this specific problem online, and the only thing that seems to solve the problem for me is rolling back to rsyslog 4.6, which instantly solves the problem.  It's not a tragedy if I'm stuck with 4.6, but this problem is very disconcerting and makes me wonder if I've misconfigured something that just took until I updated to rear its head.
Here's my rsyslog.conf:
#### MODULES ####
$ModLoad imuxsock # provides support for local system logging (e.g. via logger command)
$ModLoad imklog   # provides kernel logging support (previously done by rklogd)

#### GLOBAL DIRECTIVES ####
$ActionFileDefaultTemplate RSYSLOG_TraditionalFileFormat
$IncludeConfig /etc/rsyslog.d/*.conf # this directory is empty

#### RULES ####
kern.*                                                 /dev/console

# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none;cron.none                /var/log/messages

# The authpriv file has restricted access.
authpriv.*                                              /var/log/secure
# Log all the mail messages in one place.
mail.*                                                  -/var/log/maillog
# Log cron stuff
cron.*                                                  /var/log/cron
# Everybody gets emergency messages
*.emerg                                                 *
# Save news errors of level crit and higher in a special file.
uucp,news.crit                                          /var/log/spooler
# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log

And this is the configuration for the Python logger:
[handler_syslog]
formatter = syslog
class = handlers.SysLogHandler
args = ('/dev/log',handlers.SysLogHandler.LOG_USER)
level = INFO

[formatter_syslog]
format = %(name)s[%(process)d]: %(levelname)s %(message)s

I'm not sure if I've provided enough information about my question, and this is the first time I've posted on serverfault, so my apologies for any breaches of etiquette.
Thanks a lot.

A: Most likely you are running into a bug/limitation of SysLogHandler that leads to a BOM inserted in the wrong place. This confuses the rsyslog parser, and leads to the message being attributed the EMERG priority.
This has been "fixed" in Python 2.7 by removing the BOM insertion altogether.
You have two options:

*

*Upgrade to Python 2.7

*Encode the message into a str during formatting to workaround the BOM insertion code. One way of doing that is to implement a small custom formatter like this:
class BOMLessFormatter(logging.Formatter):
    def format(self, record):
      return logging.Formatter.format(self, record).encode('utf-8')


text:
Q: c++ operator string and char* causing ambiguous error I'm trying to make a class with conversion operators to string and char*, this makes ambiguous call error when trying to create a string.
assume i have the following class:
class A
{
public:
A(){};
operator const char*() const { return "a" };
operator const string() const { return "b" };
}

and the following main programs:
int main()
{
A a;
string b = string(a);
return 0;
}

this causing ambiguous call error to basic_string(A&)
also tried the following:
class A
{
public:
A(){};
operator const char*() const { return "a" };
explicit operator const string() const { return "b" };
}

int main()
{
A a;
string b = static_cast<string>(a);
return 0;
}

this causing the same error. I need to have both operators in my code, how can i
make this work?
note: using string b = a works but I need the string(a) format to work aswell
note 2: not using explicit keywork makes operator= ambiguous

A: You need to make them both explicit and use static_cast:
class A
{
public:
    A(){};
    explicit operator const char*() const { return "a"; };
    explicit operator const string() const { return "b"; };
};

int main()
{
    A a;
    string b = static_cast<string>(a); // works, b now has "b" as value
    const char * c = static_cast< const char *>(a); // works too, c now has "a" as value
    return 0;
}


text:
Q: Laravel Eloquent - Query with multiples parameters I'm new to the Laravel framework and I could need a little help from you.
Could someone help me to convert this request into Eloquent ?
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")

For the moment I have managed to find a solution but I am running as many queries as the number of parameters.
foreach ($calendar as $code) {
  array_push(
    $data,
    Model::query()
      ->whereYear('date', '=', $year)
      ->where('country', $code)
      ->get()
  );
}

So it comes down to doing :
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Paris"
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND country = "Madrid"

So I don't think it's very efficient knowing that potentially I would have many more parameters.
Thanks

A: You can use the whereIn method:
$countries = ['Paris', 'Madrid']; // or use $calendar instead if it's an array
$data = Model::query()
    ->whereYear('date', '=', $year)
    ->whereIn('country', $countries)
    ->get();

This should give you a query like this:
SELECT * FROM `non_working_days` WHERE YEAR(`date`) = "2021" AND `country` IN ("Paris", "Madrid");

A: You can do it, by
Model::query()
       ->whereYear('date', '=', $year)
       ->where( function( $whereQry ) use( $country_1, $country_2 ) {
            $whereQry->orWhere( 'country', $country_1 );
            $whereQry->orWhere( 'country', $country_2 );
       })
       ->get();

its convert into exactly what you need,
SELECT * FROM `non_working_days` WHERE YEAR(date) = "2021" AND (country = "Paris" OR country = "Madrid")

A: you can do this by using where in and you dont need to make loop for this,like this :-
Model::query()
  ->whereYear('date', '=', $year)
  ->whereIn('country', $calendar)
  ->get()


text:
Q: Autocomplete - Fails randomly after a few uses (how do i debug?) All-
So I'm using qjote2 to render some templates, and using simple modal to display a window.  This window has a simple text box which leverages autocomplete.
For some strange reason, autocomplete will stop working after I open and close the modal about 8 or so times.  It's quite strange.  I DO have 2 of the exact same named (class) text boxes but I bend them both regardless which modal is displayed.
No errors are thrown, does anyone know how I can debug this further? I know for a fact that it is bound as the below prints to log (I call the below whenever the modal is shown):
$(document).find('.object_search').each(function() {

    console.log("FOUND! " + $(this));
    $(this).val('');

    // bind our object search
    $(this).autocomplete({

Does anyone have any ideas on how I can debug this further? I'm pretty new to using jquery this much, so am just used to seeing errors vs. knowing how to debug when something doesn't operate properly.
Edit: I attempted to put this on fiddle, but it jqote won't render. You can view the EXACT same thing here: http://quests.ceilingfansoftware.com/test.php


text:
Q: Vagrant Multibox - my network adapter is not being recognised I have a problem where I am trying to assign a public_network interface for my Vagrantfile I have the right adapter selected, yet every time I run vagrant up it asks me to select the adapter.
The adapter I have set in the file is in the list
web.vm.network "public_network", bridge: "en4: Display Ethernet"
I am not sure why it is asking me to choose an adapter when I have set it like this.
This is my Vagrantfile and an image of the terminal output is below that:
Vagrant.configure("2") do |config|

config.vm.box = "bento/ubuntu-16.04"

config.vm.define "web01" do |web|
    web.vm.network "private_network", ip: "192.168.50.3"
    web.vm.network "forwarded_port", guest: 80, host: 8093
    web.vm.network "public_network", bridge: "en4: Display Ethernet"
    web.vm.network "public_network", ip: "192.168.2.230"
    #web.vm.provision :shell, path: "bootstrap.sh"

    web.vm.provider "virtualbox" do |vb|
        vb.gui = false
        vb.name = "16.04-web01"
        vb.memory = "512"
    end
end

config.vm.define :sql01 do |sql|
    sql.vm.network "private_network", ip: "192.168.50.2"
    sql.vm.network "forwarded_port", guest: 80, host: 8094
    sql.vm.network "public_network", bridge: "en4: Display Ethernet"
    sql.vm.network "public_network", ip: "192.168.2.231"
    #sql.vm.provision :shell, path: "bootstrap.sh"
    sql.vm.provision :shell, path: "installsql.sh"

    sql.vm.provider "virtualbox" do |vb|
        vb.gui = false
        vb.name = "16.04-sqlserver"
        vb.memory = "4096"
    end
end

#Options for Me specific
#config.vm.synced_folder "/Applications/MAMP/htdocs/", "/htdocs_home"

end

A: You are calling the config.vm.network method twice with the same type :public_network but with different arguments. The second call seems to overwrite the settings performed by the first, even though the code suggests the settings should be merged.
Replace:
web.vm.network "public_network", bridge: "en4: Display Ethernet"
web.vm.network "public_network", ip: "192.168.2.230"

With a single line:
web.vm.network "public_network", ip: "192.168.2.230",  bridge: "en4: Display Ethernet"


text:
Q: Pullback of hyperplane under morphism associated with divisor is linearly equivalent to divisor? Let $X$ be a normal projective variety and $D$ a divisor on $X$. Take the complete linear system $|D|$ and a basis of it $\{s_0,...,s_n\}$. The morphism associated with $D$ is defined as $\Phi(P)=[s_0(P):...:s_n(P)]$ from $X$ to $\mathbb{P}^n$.
Our course notes says the pullback under $f$ of a Cartier divisor $\{(U_i,d_i)\}$ is defined as $f^*(div(d_i))=div(f^*(d_i))$ on an affine open cover $\{V_{ij}\}$ of $f^{-1}(U_i)$.
Take the hyperplane $V(X_i)$, which is locally $div(\frac{X_i}{X_0})$ on $U_0$ one of the affine open. Then $\Phi^*(div(\frac{X_i}{X_0}))$ is locally $div(\frac{f^*X_i}{f^*X_0})=div(\frac{s_i}{s_0})$. Now I am confused about a few things.

*Is the definition of pullback correct? How to come up with $\{V_{ij}\}$?

*The notion of linear equivalence, is it global?

*Having answered 1, how to continue to show $D\sim \Phi^*(V(X_0))?$


text:
Q: How to update temp table data during run time AX 2012 I'm new to X++ development. I'm trying to add a field in Vendor aging report. It was done as excepted.
my problem is updating the field value during run time.
Scenario,
We have a Invoice field contain "AA_BBBBBB". What I need to do is I need to split the value as AA, BBBBBB and update BBBBBB to invoice field and AA to new field (Invoice type).
Issue,
Once i got the values to temptable VendAgingReportTmp in the method VendAgingReportDP\insertVendAgingReportTmp, I'm tried to update the above scenario but code is not selecting the records from VendAgingReportTmp. Can someone help me to get this thing done.

A: In VendAgingReportDP class insertVendAgingReportTmp the last line of standard code is vendAgingReportTmp.insert();
If your code is before vendAgingReportTmp.insert(); You do not need to perform the update. If you put vendAgingReportTmp.update(); before vendAgingReportTmp.insert(); you get that error.
Put your code inside //YourCode and //YourCode END withhout vendAgingReportTmp.update();
Example:
/// <summary>
///    Inserts records into the temporary <c>VendAgingReportTmp</c> table.
/// </summary>
/// <param name="_reverseAmountsAndHeadings">
///    A boolean value which indicates whether the column values should be     reversed.
/// </param>
private void insertVendAgingReportTmp(boolean _reverseAmountsAndHeadings)
{
    vendAgingReportTmp.AsOfDate = strFmt("@SYS84682",     date2StrUsr(contract.parmZeroDate(), DateFlags::FormatAll),     contract.parmDateTransactionDuedate());
    vendAgingReportTmp.HeadingAccount = strFmt("@SYS24500");
    vendAgingReportTmp.HeadingName = strFmt("@SYS7399");

    switch (contract.parmDateTransactionDuedate())
    {
        case DateTransactionDuedate::DocumentDate : vendAgingReportTmp.HeadingDate = "@SYS2587";
                                                break;
        case DateTransactionDuedate::TransactionDate : vendAgingReportTmp.HeadingDate = "@SYS67";
                                                break;
        case DateTransactionDuedate::DueDate : vendAgingReportTmp.HeadingDate =     "@SYS14588";
                                                    break;
        default : vendAgingReportTmp.HeadingDate = "@SYS14588";
                                                    break;
    }

    if (_reverseAmountsAndHeadings)
    {
        this.setVendAgingReportTmpInReverse();
    }
    else
    {
        this.setVendAgingReportTmp();
    }

    vendAgingReportTmp.TransDate = tmpAccountSum.TransDate;
    vendAgingReportTmp.InvoiceId = tmpAccountSum.InvoiceId;
    vendAgingReportTmp.Voucher = tmpAccountSum.Voucher;
    vendAgingReportTmp.AccountNum = tmpAccountSum.AccountNum;
    vendAgingReportTmp.Name = vendTable.name();
    vendAgingReportTmp.VendAccount = tmpAccountSum.AccountNum;
    vendAgingReportTmp.Txt = tmpAccountSum.Txt;
    vendAgingReportTmp.Balance = 100;
    vendAgingReportTmp.CurrencyCode = tmpAccountSum.CurrencyCode;
    vendAgingReportTmp.VendGroup = vendTable.VendGroup;

    //YourCode
    //...
    //...
    //...
    //YourCode END

    vendAgingReportTmp.insert();
}

A: I got a solution by adding below,

*

*Added InvoiceType field to temptable VendTmpAccountSum Since this is declared as global variable.

*Updated our custom Invoice type to InvoiceType field in VendTmpAccountSum.

*Then insert the whole data to VendAgingReportTmp from VendTmpAccountSum table by using insert_recordset to increase the performance.

Thanks,


text:
Q: MVC5 and Entity Migrations with Asp.Net Identity I have an issue that I have been struggling with. I would appreciate any help
So, I have an application that uses Code first. For authentication, I use Asp.Net Identity 2.0.1. So I have a User class that derives from Identity User like this:
public class User: IdentityUser
{
    public virtual UserInfo UserInfo { get; set; }
    public virtual Organization Organization { get; set; }
}

Then i define my Context as:
public class IdentityContext: IdentityDbContext<User>
{
    public IdentityContext(): base("Name=IdentityContext")
    {
    }

    static IdentityContext()
    {
        Database.SetInitializer<IdentityContext>(new CreateDatabaseIfNotExists<IdentityContext>());
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Configurations.Add(new UserMap());
        modelBuilder.Configurations.Add(new UserInfoMap());
    }
}

Then i enable migrations using this context. And since Organization class is linked to User it also is added to the migration. But I dont want that, since its different from the Identity classes. My Organization class is as follows:
public partial class Organization: EntityBase
{
    public Organization()
    {
        this.Users = new List<User>();
    }
    public int OrganizationId { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

This derives from EntityBase and not from IdentityUser class and is handled differently.
What I would be able to do is to handle all my non-identity classes through a different context, lets say AppContext that could be defined as:
public class AppContext: DbContextBase
{
    public AppContext(): base("Name=IdentityContext")
    {
    }

    static AppContext()
    {
        Database.SetInitializer<AppContext>(new CreateDatabaseIfNotExists<AppContext>());
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

    protected override void OnModelCreating(DbModelBuilder builder)
    {
        builder.Configurations.Add(new OrganizationMap());
    }
}

And then enable a second migration for this context.
But when I enable a second migration it fails with the exception that "Migrations have already been enabled in project 'Datastore'. To overwrite the existing migrations configuration, use the -Force parameter.". Although it still creates the Configuration file for the second migration.
So when i try to add a migration for this configuration it complains the following:

One or more validation errors were detected during model generation:
Datastore.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no
key defined. Define the key for this EntityType.
Datastore.IdentityUserRole: : EntityType 'IdentityUserRole' has no key
defined. Define the key for this EntityType.
Datastore.UserInfo: : EntityType 'UserInfo' has no key defined. Define the key for this
EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type >'IdentityUserLogin' that has no> keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type >'IdentityUserRole' that has no
keys defined.
UserInfoes: EntityType: EntitySet 'UserInfoes' is based on type 'UserInfo' that has no >keys defined.

I am not sure how to get around this? Any help is really appreciated

A: The idea was to inherit the AppContext with IdentityDbContext. IdentityDbContext itself inherits from DbContext so it has all the functionality available for DbContext plus extra configuration requirements for the Asp.Net Identity framework


text:
Q: Typescript: narrowing types with destructuring The following code errors:
type Foo = {
  a: true,
  b: null,
  c: null
} | {
  a: false,
  b: Error,
  c: null
} | {
  a: false,
  b: null,
  c: { prop: number}
}

function getFoo(): Foo {

  return { a: false, b: null, c: { prop: 5 } };

}

const { a, b, c } = getFoo();

if (!a && !b) {
  console.log(c.prop)
}

The error given is:
Object is possibly 'null'.(2531)

This makes somewhat sense, because when the result from getFoo() was destructured, the types from the larger Foo object was lost.
However, I'm trying to replicate what the Apollo React client is doing:
const { loading, error, data } = useQuery('...');

if (loading) {
  return '..';
}
if (error) {
  return '..';
}
return data.foo;

I'm having a hard time figuring out from their source how they make this work.
Is this doable in Typescript at all? My best guess is that their types might not be 100% accurate, and they say they always return data even when they don't.

A: It is not possible to have type guard between 2 variables. You can make a link between variable a and b to tell that: if a condition of a is met ==> b is something else. For Apollo React client, I think that strictNullChecks is disabled


text:
Q: PHP: get content from first file in folder and then delete it Using PHP, I want to get the content from the first file in a folder and when the content is loaded, delete the file. Here is what I have:
$a = opendir('./');
while (false !== ($entry = readdir($a))) {
    if($entry != '.' && $entry != '..') {
        echo $entry = file_get_contents('./'.$entry.'', FILE_USE_INCLUDE_PATH);
        break; // only need the first file
        }
    }

The code above loads the first file in the folder and I can delete it successfully using something like
unlink("temp.txt");

So there are no permission denied errors. BUT what I need to do is delete the file by its variable name (because every filename is different). Surprisingly for me, unlink("$entry"); or something similar does not let me delete it, instead showing a warning along with the first few lines of the content of that file. If I echo $entry It shows temp.txt correctly. Can someone enlighten me? What am I missing here?
(Optional (un)related question: If I have numeric files like 1.txt, 2.txt, 3.txt, 10.txt... . Is there a way I could modify the code above in a way, that it does not load files like 1,10,2,3 ..., instead load it like 1,2,3,10...?)
UPDATE:
The updated code that works (for future reference):
$a = opendir('./');
while (false !== ($entry = readdir($a))) {
    if($entry != '.' && $entry != '..') {
        echo $b = file_get_contents('./'.$entry.'', FILE_USE_INCLUDE_PATH);
        break; // only need the first file
        }
    }
unlink("./$entry");

A: The first problem is that you're overwriting $entry with the file contents, as such the filename is no longer valid when trying to delete it (explaining the error with the file contents).
Secondly, because you're using FILE_USE_INCLUDE_PATH you don't know exactly where the file is located, and unlink resolves related to the current working directory, which is most probably not $a.
Use unlink($a.'/'.$entry) and you'll be fine.
As for the unrelated question - use scandir to get all the files in the folder, then apply natsort to the resulting array to sort by a 'natural sorting algorithm'. Keep in mind that a directory listing always also lists the folders . and .. which you'll have to detect and skip or remove manually.


text:
Q: Apply css ease transitions on hover I have created box using css and on hover it will show overflow content(text),
Is there any way to apply smooth transaction effect to this hover effect?
I have tried using css-transition but its not working!

I don't want to change the method of doing it! Need only css/Javascript solution.

html {
   height: 100%;
   width: 100%;
   font-size: 14px;
   color: #000;
   font-family: sans-serif;
   text-align: justify;
 }
 .box {
   margin: 100px auto;
   position: relative;
   width: 500px;
   cursor: pointer;
   transition: all 0.4s ease;
   background: #eee;
   padding: 5px;
   color: #222;
   white-space: nowrap;
   text-overflow: ellipsis;
   -webkit-text-overflow: ellipsis;
   transition: all 1s ease;
 }
 .box:hover {
   white-space: normal;
 }
 .box:after {
   content: '';
   width: 75%;
   height: 10px;
   bottom: 0;
   box-shadow: 0px 9px 20px #ccc;
   position: absolute;
   left: 12%;
   z-index: -1;
 }
 .box > div {
   overflow: hidden;
   transition: all 1s ease;
 }

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id nisl eu tortor accumsan hendrerit. Nulla dui quam, mattis iaculis pharetra ut, cursus ut tortor. Donec velit nisl, pellentesque eu tellus ac, tempus efficitur elit. Sed et enim tincidunt,
    iaculis tortor eget, sodales nulla. In facilisis tincidunt aliquet. Mauris scelerisque leo eu lectus facilisis vulputate. Proin interdum sed nibh at luctus. In turpis nunc, gravida vel arcu eget, fringilla dapibus lacus. Duis sagittis nisl sed sem
    vulputate commodo. Morbi nisl neque, fermentum in mollis gravida, aliquam quis felis. Etiam et placerat mauris. Integer ut nulla in sem sagittis varius at et mi. Maecenas in rutrum orci. Sed vel mi vel erat vulputate sodales. Sed velit velit, ullamcorper
    eget finibus ut, pharetra ac enim. Morbi eu placerat orci. Mauris augue enim, semper quis convallis id, dapibus eget sem. Aenean lacus leo, fermentum luctus erat vitae, ultrices tempus libero. Curabitur ultrices tellus a mauris interdum, commodo consectetur
    magna sollicitudin.

A: You'd need to use some css property that can be animated...
In you case, instead of dealing with overflow, you would have to deal with the height, though it's not easy to make a transition from height fixed to auto.
A possible hack, as answered here, is to use max-height, though it's not pretty, as it requires you to use hard coded values...

html {
   height: 100%;
   width: 100%;
   font-size: 14px;
   color: #000;
   font-family: sans-serif;
   text-align: justify;
 }
 .box {
   margin: 100px auto;
   position: relative;
   width: 500px;
   cursor: pointer;
   background: #eee;
   padding: 5px;
   color: #222;
   text-overflow: ellipsis;
   -webkit-text-overflow: ellipsis;
 }

 .box:after {
   content: '';
   width: 75%;
   height: 10px;
   bottom: 0;
   box-shadow: 0px 9px 20px #ccc;
   position: absolute;
   left: 12%;
   z-index: -1;
 }
 .first {
   transition: all 0.4s ease;
   max-height: 13px;
   overflow: hidden;
 }

.box:hover .first {
   max-height: 250px;
 }

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse id nisl eu tortor accumsan hendrerit. Nulla dui quam, mattis iaculis pharetra ut, cursus ut tortor. Donec velit nisl, pellentesque eu tellus ac, tempus efficitur elit. Sed et enim tincidunt,
    iaculis tortor eget, sodales nulla. In facilisis tincidunt aliquet. Mauris scelerisque leo eu lectus facilisis vulputate. Proin interdum sed nibh at luctus. In turpis nunc, gravida vel arcu eget, fringilla dapibus lacus. Duis sagittis nisl sed sem
    vulputate commodo. Morbi nisl neque, fermentum in mollis gravida, aliquam quis felis. Etiam et placerat mauris. Integer ut nulla in sem sagittis varius at et mi. Maecenas in rutrum orci. Sed vel mi vel erat vulputate sodales. Sed velit velit, ullamcorper
    eget finibus ut, pharetra ac enim. Morbi eu placerat orci. Mauris augue enim, semper quis convallis id, dapibus eget sem. Aenean lacus leo, fermentum luctus erat vitae, ultrices tempus libero. Curabitur ultrices tellus a mauris interdum, commodo consectetur
    magna sollicitudin.


text:
Q: Linkback just can't work in LaTeXiT! I'm new to OS X and LaTeXiT for a week.
I can use the 'Detect and typeset equations' successfully in the 'Service' menu of Pages, then it produces the right things which should be.
However, I can't double-click the picture to edit the LaTeX code.
The linkback  just can't work! How can I do?
Is there something should be set in the preferences in the LaTeXiT?
Here is my screen:


text:
Q: Android: file permissions on external storage folder I would like to know if it is possible to set the permissions of the files that my Android app writes on behalf of the user in the external storage folder (that is the common user folders that are accessible to my app like "Documents") so that those files are not writable by other applications that know where they are or explore the external storage folders to find them.
I mean, if my application has many installations and it becomes the target of malware apps, and it has a known user files folder, the malware could change or delete those files (json and other types like txt, doc). I would like that it is not possible by means of file permissions setting.
But note that the user has to be able to manage those files and also edit them.
Even my app sends intents so other apps edit them.
Is it possible?

A: That is not possible. If you do not want other apps to have access to the files, put them on internal storage, not external storage.

A: You can create encrypted storage with consistency checking instead of using permissions, what is not possible.


text:
Q: Jquery dynamically added and remove multiple textbox? I am able to add 1 textbox when user click add and c# read the user input data when click on submit button,but i have no idea on how to add 4 textbox vertically when user click on add button please guide me,thank you.
my c#
protected void Post(object sender, EventArgs e)
{
    string[] textboxValues = Request.Form.GetValues("DynamicTextBox");
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    this.Values = serializer.Serialize(textboxValues);
    string message = "";
    foreach (string textboxValue in textboxValues)
    {
        message += textboxValue + "\\n";
    }
    ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('" + message + "');", true);
}

my jquery to add and remove textbox

my html
<input class="btn btn-primary" id="btnAdd" type="button" value="Input" onclick="AddTextBox()">

<asp:Button ID="btnPost" Text="Submit" CssClass="btn btn-success" runat="server" OnClick="Post" />

A: You can add a "for" clause on AddTextBox function...
function AddTextBox() {
    for (i = 0; i <=4; i++) {
        var div = document.createElement('DIV');
        div.innerHTML = GetDynamicTextBox("");
        document.getElementById("TextBoxContainer").appendChild(div);
    }
}


text:
Q: Cómo captar fechas desde una barra de búsqueda Buenas, tengo una barra de búsqueda en la parte superior de mi navbar para buscar coincidencias en mi base de datos. Concretamente, coincidencias con el titulo, la fecha y el país de las fotos que se hayan subido.
La SELECT que hago es la siguiente (la gestiono de forma dinámica, de ahí que la concatene):
 $sql .= " titulo LIKE '%$infoBusqueda%' OR fecha LIKE '%$infoBusqueda%' OR pais LIKE '%$infoBusqueda%'";

PROBLEMA:
Me encuentra coincidencias cuando hago búsquedas por título y país, pero no encuentra cuando introduzco una fecha, sea el formato que sea (Ej: 01/11/2017, 2017/11/01... etc).
¿Alguien me podría ayudar? Muchas gracias de antemano.

A: Las bases de datos suelen manejar las fechas del tipo aaaa-mm-dd por lo que en el formato que lo estás utilizando no te va a servir. Podrías hacer uso del siguiente código:
try {
    DateTime::createFromFormat('d/m/Y', $infoBusqueda);
    $fecha = $date->format('Y-m-d');
} catch(Exception $e) {
    $fecha = $infoBusqueda;
}
$sql .= " titulo LIKE '%$infoBusqueda%' OR fecha LIKE '%$fecha%' OR pais LIKE '%$infoBusqueda%'";

Y por cierto es altamente recomendable que parametrices las sentencias, sino podrías ser víctima de un ataque de inyección SQL, podrías hacer lo siguiente:
$sql .= " titulo LIKE ? OR fecha LIKE ? OR pais LIKE ?";
$q = $dbc->prepare($sql);
$q->execute(array('%$infoBusqueda%', '%$fecha%', '%$infoBusqueda%'));

Espero haber sido de ayuda!
Saludos!

A: Para tu respuesta hay dos posibles casos.
Si el campo fecha es de tipo DATETIME, en este caso tu consulta no será valida, ya que estas comparando una cadena con una fecha. El formato de la fecha, ademas debe ser YYYY/MM/DD, con lo que de alguna manera debes convertir la entrada del usuario a este formato.
Para usar las fechas la comparación debe realizarse con el operado = y en caso de querer filtrar por un rango de fechas, te aconsejo que uses la sentencia con un BETWEEN fecha1 AND fecha2
Si tu campo fecha es de tipo VARCHAR, si sería posible que uses la clausula LIKE, pero debes tener en cuenta que el formato es el de YYYY/MM/DD
Y por último como consejo, encierra cada una de las condiciones entre los simbolos '(' y ')', para que tengas mas claro como usar el operador AND y OR

A: He encontrado una solución (dejo aquí la fuente: https://stackoverflow.com/questions/22506930/how-to-query-datetime-field-using-only-date-in-sql-server)
Puedes usar un rango:
select * from test
where date between '03/19/2014' and '03/19/2014 23:59:59'

o usa la función datediff():
select * from test
where datediff(day, date, '03/19/2014') = 0

Espero que te funcione, un saludo!


text:
Q: Testing update, version 1.0/1.1 refers to bundle version or bundle version string,short? I've seen many posts regards to testing an update version.

*

*install version 1 ipa

*do something with version 1

*install version 2 ipa (with itunes or testflight)

*do something with version 2

When they say version1/2, are they talking about "bundle version" or "bundle version string, short"?