text:
Q: Azure Functions C# CloudTable Table Query doesn't return any matching results I have a C# Azure durable function that needs to read data from some tables and put data in other tables, in response to some inbound JSON it receives via an HTTP trigger.  Everything has been coming along nicely.  Now, the exact same syntax and methods that I've used to make earlier queries in my code suddenly don't return any results.  I'm sure that I must be overlooking something obvious.
Here, I bind the CloudTable, exactly as I do for the other queries that work:
[Table ("ProductFeatures")] CloudTable ProductFeatures,
I define the table entity:
public class FeatureEntity : TableEntity
    {
        public string productcode {get;set;}
        public string featurecode {get;set;}
        public string featurefriendlyname {get;set;}
    }

Unless I've missed something, this matches what's in the Table, and, as you can see, there are actual entries that ought to be returned if I try to match productcode "test" which I've verified through logging is the value of prodcode which is used in the query (below) in trying to perform the match.

And here I query against it:
var ProdFeatures = new List<FeatureEntity>();
TableQuery<FeatureEntity> featureQuery = new TableQuery<FeatureEntity>()
    .Where(TableQuery.GenerateFilterCondition("productcode", QueryComparisons.Equal, prodcode));

// TableContinuationToken ct = null;  <== declared in previous query, so we reset it
ct = null;

try
{
    do
    {
        var page = await ProductFeatures.ExecuteQuerySegmentedAsync(featureQuery, ct);
        ct = page.ContinuationToken;
        ProdFeatures.AddRange(page.Results);
    }
    while (ct != null);
}

Next, we do a check against ProdFeatures:
if (ProdFeatures.Count == 0)
{
    log.LogInformation($"[{Product}]: No features found - Processing Terminated");
    return false;
}

I use this exact same approach for 2 queries before I get to this one so I'm really confused why it's not returning any results.  I feel like this is probably something really stupid that I'm missing, but I've been over it multiple times and can't figure out why it isn't returning the matching data that you can see in image of the table.
This is occurring in an async task function called by the durable functions orchestrator:
Boolean success = await context.CallActivityAsync<Boolean>("DoQueueItem",data);
Where the task is defined like so:
[FunctionName("DoQueueItem")]
public static async Task<Boolean> DoQueueItem([ActivityTrigger] MySpecialItem Item,
[Table ("ProductFeatures")] CloudTable ProductFeatures,
ILogger log)

The total runtime is < 5 seconds, so I don't think I'd be running afoul of any processing limitation, but I'm very new to Azure and wondering if there could be something of an environmental or contextual nature with durable functions in general that could affect this.

A: In your Function annotation, I don't see you passing the Connection parameter in Table input binding:
[FunctionName("DoQueueItem")]
public static async Task<Boolean> DoQueueItem([ActivityTrigger] MySpecialItem Item,
[Table ("ProductFeatures", Connection = "StorageConnectionAppSetting")] CloudTable ProductFeatures,
ILogger log)

I suspect because of that it is not connecting to your desired storage account (by default, it uses the same function host storage if you do not specify connection). Refer this for details.
Connection: The name of an app setting that contains the Storage connection string to use for this binding. For example, if you set connection to "MyStorage", the Functions runtime looks for an app setting that is named "MyStorage". If you leave connection empty, the Functions runtime uses the default Storage connection string in the app setting that is named AzureWebJobsStorage.


text:
Q: System.TypeLoadException : Could not load type System.Net.HttpStatusCode, netstandard, while decoding custom attribute: (null) The problem occurs between a Xamarin.IOS type project and a .NetStandard2.0 library. I have created a small solution (link here) demonstrating the problem. To achieve this, the Xamarin project uses the Newtonsoft nuget.
Situation:
In the .NetStandard project, I have a single object containing a single property (in my case, a property of type HttpStatusCode) with a custom attribute defining the default value of this property.
public class TestObject
{
    [DefaultValue(HttpStatusCode.OK)]
    public HttpStatusCode Code { get; set; }
}

In the Xamarin project, I created a single test which instantiated an object of the type created in the .NetStandard project and which tried to serialize it.
[Test]
public void Test()
{
    TestObject obj = new TestObject(code: HttpStatusCode.Accepted);
    JsonConvert.SerializeObject(obj);
}

When running the test, the error returned is as follows: System.TypeLoadException: Could not load type System.Net.HttpStatusCode, netstandard, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = cc7b13ffcd2ddd51 while decoding custom attribute: (null )
In my situation, it is required that the architecture defined in the csproj is of type * ARMv7 + ARM64 * for the sake of compatibility with the old Ipads that we have to support.
I mention this because I know that choosing Linker behavior to Link All and Supported architechtures to ARM64 makes the test pass without problems.
Edit
Answer to the question Why the need to use 2 projects:
In fact, the solution provided in this post is just a tiny excerpt from a much larger project.
In this project, we provide a Windows version (.NetCore 3.1) and an IOS version (Xamarin.IOS) of the application.
To share our models between these 2 different projects, we would like to use a .NetStandard type library, instead of separating this library into Windows and IOS projects.
We are open to other architectural solution proposals if that can solve our problem, but for now that's all we have.
If you have any further questions about the problem and its context, don't hesitate to ask.
Thanks in advance for your help

redpajama_set_name: RedPajamaStackExchange


text:
Q: Writing two breadth first in method in two classes, stuck right now, advices? So pretty much in this assignment I have to add a routine to the EdgeList and AdjMatrix objects class to return a breadth first spanning tree. The signature(s) would be:
In EdgelList: EdgeList BFSpanning();
In AdjMatrix: EdgeList BFSpanning();
But I'm really confused,do I just write the BFSpanning method inside both those classes? can anyone give me a hard structure for me? I can't seem to come up writing the correct method.
Here are my adjmatrix class:
public class AdjMatrix extends Object implements Cloneable{
  private int size;
  private long[][] m;

  public Object clone(){
    int i, j;
    AdjMatrix ret;
    ret = new AdjMatrix();
    ret.setSize(this.getSize());
    for (i=0; (i < this.getSize()); i=i+1){
      for (j=0; (j < this.getSize()); j=j+1){
        ret.setUndirected(i, j, this.getEdge(i, j));
      }
    }
    return (ret);
  }

  public void setSize(int size) throws BadSizeException{
    int i, j;
    if (this.sizeOK(size)) {
      this.size = size;
      m = new long [size][];
      for (i=0; (i < size); i=i+1){
        m[i] = new long[size];
        for (j=0; (j < size); j=j+1){
          m[i][j] = -1;
        }
      }
    } else {
      throw new BadSizeException();
    }
  }

  public int getSize(){
    return(this.size);
  }

  public void setUndirected(int x, int y, long val) throws BadIndexException {
    if (this.OK(x, y)) {
      m[x][y] = val;
      m[y][x] = val;
    } else {
      throw new BadIndexException();
    }
  }

  public void setDirected(int x, int y, long val) throws BadIndexException {
    if (this.OK(x, y)) {
      m[x][y] = val;
    } else {
      throw new BadIndexException();
    }
  }
  public long getEdge(int x, int y) throws BadIndexException {
    long ret = -1;
    if (this.OK(x, y)) {
      ret = m[x][y];
    } else {
      throw new BadIndexException();
    }
    return (ret);
  }

  public boolean sizeOK(int size) {
    return (size > 0);
  }
  public boolean OK(int x, int y) {
    return (((x >=0) && (x < this.size)) &&
            ((y >=0) && (y < this.size)));
  }
}

Here is my edglist class:
public class EdgeList extends Object implements Cloneable{
  private int nodeNumber;
  private Edges[] nodes;

  public Object clone(){
    int i, j;
    EdgeList ret;
    ret = new EdgeList();
    ret.setNodeNumber(this.nodeNumber);
    for (i=0; (i < this.getNodeNumber()); i=i+1){
      ret.nodes[i] = (Edges) (this.nodes[i].clone());
    }
    return (ret);
  }

  public void setNodeNumber(int nodes) throws BadNodeNumberException{
    int i;
    if (nodes > 0) {
      this.nodeNumber = nodes;
      this.nodes = new Edges[nodes];
      for (i=0; (i < nodes); i = i + 1){
        this.nodes[i] = new Edges();
        this.nodes[i].setSize(nodes);
      }
    } else {
      throw new BadNodeNumberException();
    }
  }

  public int getNodeNumber(){
    return(this.nodeNumber);
  }

  public void addEdge(int x, int y, long val) throws BadIndexException, DuplicateEdgeException {
    int i;
    if (this.OK(x, y)) {
      this.nodes[x].add(y, val);
    } else {
      throw new BadIndexException();
    }
  }

  public Edges getEdges(int i) throws BadIndexException {
    Edges ret = null;
    if ((i >= 0) && (i < this.nodeNumber)) {
      ret = (Edges)(nodes[i].clone());
    } else {
      throw new BadIndexException();
    }
    return (ret);
  }

  public boolean OK(int x, int y) {
    return (((x >=0) && (x < this.nodeNumber)) &&
            ((y >=0) && (y < this.nodeNumber)));
  }
}

Also don't know if you need to see this class edges:
public class Edges extends Object implements Cloneable{
  private int size;
  private int place;
  private Edge[] edges;
  public Object clone(){
    Edges ret;
    int i;
    ret = new Edges();
    ret.setSize(this.size);
    for (i=0; (i < this.getSize()); i=i+1){
      ret.add(this.edges[i].getNode(), this.edges[i].getValue());
    }
    return (ret);
  }

  public void setSize(int size){
    edges = new Edge[size];
    this.size = 0;
    this.place = 0;
  }
  public void add(int node, long value) throws DuplicateEdgeException{
    int i;
    boolean ok;
    Edge e;
    ok = ((node  > 0) && (node < edges.length)) && (size < edges.length);
    for (i=0; (i < this.size); i = i + 1) {
      ok = ok && (this.edges[i].getNode() != node);
    }
    if (ok) {
      e = new Edge();
      e.setNode(node);
      e.setValue(value);
      this.edges[this.size] = e;
      this.size = this.size + 1;
    } else {
      throw new DuplicateEdgeException();
    }
  }

  public Edge getCurrent(){
    Edge ret = null;
    if (size != 0) {
      ret =(Edge) (this.edges[place].clone());
    } else {}
    return (ret);
  }

  public void next(){
    this.place = (this.place + 1) % this.size;
  }

  public int getSize(){
    return (this.edges.length);
  }
}

A: Ask your instructor for clarification if you don't understand.  That being said I can offer a guess:
Yes, you are to write a method on each class.  They both return a tree, which is a subset of the graph and has all of the vertices.  How they actually do this will be vastly different.  The goal of the assignment is likely to show that storing the same data in different ways requires different solutions to the same question.  Also you may find that one method is easier to write than the other, this will show that certain data formats make answering certain questions easier or harder.


text:
Q: TextView not zooming out I have an activity in my app where i have two textviews and two buttons for zooming in and zooming out respectively.
Zoom in seems to work just fine but zoom out works opposite, it zooms in instead of zooming out.
Here is the code
 ibzoomout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float s1 = tv1.getTextSize();
                float s2 = tv2.getTextSize();
                s1 = s1-5;
                s2 = s2-5;
                tv1.setTextSize(s1);
                tv2.setTextSize(s2);
            }
        });

ibzoomin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float s1 = tv1.getTextSize();
                float s2 = tv2.getTextSize();
                s1 = s1+5;
                s2 = s2+5;
                tv1.setTextSize(s1);
                tv2.setTextSize(s2);
            }
        });

tv1 and tv2 are textviews and ibzoomin and ibzoomout are buttons.

A: As I can see, you want to zoom in/out the both of TextView, I've created the below code, might be helpful for you :
   ibzoomout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            float s1 = tv1.getTextSize();
            float sp1 = s1 / getResources().getDisplayMetrics().scaledDensity;

            float s2 = tv2.getTextSize();
            float sp2 = s2 / getResources().getDisplayMetrics().scaledDensity;

            tv1.setTextSize(decreaseSize(sp1));
            tv2.setTextSize(decreaseSize(sp2));
        }
    });
    ibzoomin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            float s1 = tv1.getTextSize();
            float sp1 = s1 / getResources().getDisplayMetrics().scaledDensity;

            float s2 = tv2.getTextSize();
            float sp2 = s2 / getResources().getDisplayMetrics().scaledDensity;

            tv1.setTextSize(increaseSize(sp1));
            tv2.setTextSize(increaseSize(sp2));
        }
    });

    public Float increaseSize(float diff) {
        size = diff + 5;
        return size;
    }

    public Float decreaseSize(float diff) {
        size = diff - 5;
        return size;
    }


text:
Q: Can't resolve git conflicts due to policy using Azure DevOps So I have a master branch and a development branch; both of them are locked such that changes to the branches can only be made via pull request. I want to merge some changes from development into master on the server, and I created a pull request to do so. However there were conflicts, so I did the merge manually locally and tried to push the changes to the server. I can't do this due to the policy of requiring a pull request! Is there any other way I can get the conflicts resolved without violating the policy? All I can think of now is to abandon the pull request and create a new one, but I'm not sure if that would even do what I need - there's no way to actually resolve the conflicts that I'm aware of without a local merge, and there's no way to get the resolved changes into the master branch that I'm aware of without pushing to master, which is forbidden by policy - help?

A: If I understand your setup, you are supposed to get changes into develop from feature/somefeature branches via PR, correct? And you get changes from develop into master using another PR (by convention as branch policies do not define relationships between specific branches).
Consider your Conflict Resolution to be a "Feature"
Abandon your current PR as it's busted w/o a force push. Creating a new feature/ConflictResolution branch based on current develop. Then pull latest master on localhost and them merge master => feature/ConflictResolution. This should give you the same conflicts seen in the PR between develop and master. Resolve those conflicts and push to the remote feature/ConflictResolution to initiate a new PR into develop, and then into master.
OR: Put your conflictResolution directly into master via PR
This is basically the same as the previous option, except you are creating a PR between the conflictResolution branch and master. I think this would remove any changes you need to PR between develop and master, so the existing PR might "go away" after you tell it to re-merge.
ULTIMATE OR: Stop using merge hell branch strategies
You still want to use a trunk based strategy, and that's fine, but do away with the locked develop branch convention. Keep the policy on master, make sure it is required, add a build validation on it, and call it good. This forces any changes going into master to use a PR and get a Restore >> Build >> Test gate build executed. If you have a rigid deployment authoring process, use tags to mark those ceremonial milestones in history.
This is a good video about some of the strategies and how they have matured and gained trust over time.

A: The conflict is raised when creating the PR against develop, right? I guess the best you can do is transform that merge into a single revision (if possible for you) on top of development... and then you can create the PR from that.
So..... you have already merged with develop, right?
git reset --soft develop # put all changes related to your PR into the index, ready to commit
git commit -m "My PR changes"

Now, all your changes after solving all conflicts are in a single revision after develop (develop hasn't moved). Push that branch (and that should update the PR on its own and allow you to merge).

A: I talked with my boss about this last night and he figured out how to do it:
1) pulled both master and development
2) merged from master into development locally
3) resolved conflicts
4) created and completed pull request
5) pulled development

A: The correct process is that you should merge master branch to your development branch, then commit and push changes to development branch, then create Pull Request to merge changes to Master.
There is extension that can resolve conflict online without needing to do it locally.
Pull Request Merge Conflict Extension


text:
Q: How can I simplify these CSS selectors? I have some code that I think may be bulky and could be simplified. I haven't found anything that helps in my situation. I am trying to make it so that when I hover over a div, an h2 and p get underlined. It works fine like this:
.test:hover h2, .test:hover p {
  text-decoration: underline;
}

But I was wondering if I could simplify it in some way, not having to repeat .test:hover twice.

A: If you don't need to support Internet Explorer this can be accomplished with the :is pseudo-class:

.test:hover :is(h2, p) {
  text-decoration: underline;
}

An H1

An H2

A paragraph

An alternative would be to leverage a CSS preprocessor like Sass or Less, both of which support nesting which can make for DRY-er, more expressive style source code. This may be overkill in your case, though.  Here's an example in Sass' SCSS format:
.test:hover {
  h2, p {
    text-decoration: underline;
  }
}

A: There is a new pseudo-class :is which will allow this..

The :is() CSS pseudo-class function takes a selector list as its argument, and selects any element that can be selected by one of the selectors in that list.

.test:hover :is(h2, p) {
  color: red;
  text-decoration: underline;
}

Heading

Lorem ipsum dolor sit amet.

A: You can use it:

:is(h1, p) .test:hover {
  text-decoration: underline;
}


text:
Q: image swipe gesture in one activity okay I am learning more about swipe gesture, I have this signleviewactivity.java
its perfeclty displaying image , but how to make slide image without using fragments?
I read and I tested the dev.android but they are using fragments, Can i work it without fragments?
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.singleview);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // list = (ListView) findViewById(R.id.ListView);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
   //     setSupportActionBar(toolbar);

     //   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        imageView = (ImageView) findViewById(R.id.funnyimage);
        Bundle bundle = getIntent().getExtras();

        ArrayList<Listitem> personArrayList = bundle.getParcelableArrayList("Person_List");

        if (personArrayList != null && !personArrayList.isEmpty()) {
            for (Listitem person : personArrayList) {
                Picasso.
                        with(this).
                        load(person.url)
                        .placeholder(R.drawable.logo)
                        .fit()
                        .noFade()
                        .into(imageView);
                Log.i("PersonsActivity",String.valueOf(person.url));
            }
        }
       // GridViewAdaptersingle adapter = new GridViewAdaptersingle (getApplicationContext(), R.layout.singleviewadapter, personArrayList);

    }


text:
Q: How Unzip a Folder At Jelatics? i'm new here. I would like to know how can i unzip a uploaded folder at apache / jelastic / Wordpress, like a folder with all my plugins or images.

A: You can deploy a project from an archive directly from the Jelastic dashboard - see Upload and Deploy your PHP Application in the official docs - but in this case the archive should contain your entire site (e.g. WordPress and all desired plugins, themes etc.).
Alternatively you can upload your archive (via the dashboard, FTP/S, or SFTP) and then connect to your node via SSH.
Then you can use a command like this to extract the archive in the desired location:

tar -xzvf archive.tar.gz

EDIT: Since you mentioned zip archive, the command to use would be:

unzip archive.zip


text: Q: Generalized quantors, how? Is there a "standard" form for a) a generalized existence quantor, assuring that there are at least n objects existing, b) a generalized forall quantor, allowing that n objects violate its assurance? Of course any such statement can be written with $\forall,\exists$. In any case I never saw a (say) $\forall^N$ in math literature yet, and googling didn't brought up anything (as usual, I probably just used the wrong search terms...)


text:
Q: AWS DocumentDB with C# MongoDB driver, unsupported efficient pagination I am developing some queries and indexing against a MongoDB 4.0 using the C# MongoDB.Driver 2.12.4
All is great with MongoDB. Unfortunately, I must use AWS DocumentDB as the production database, which claims to be compatible with MongoDB, but I've been discovering several issues:

*

*Indexes are limited https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html#mongo-apis-index

*It does not support collation indexes or queries (already removed, managed to do case insensitive search by other means)

*It does not support facet (and I use it for efficient pagination)
"message": "Command aggregate failed: Aggregation stage not supported: '$facet'.",
The question is: What's the best way to paginate results with AWS DocumentDB? Is there any option to do so with a single query? or I must hit the database twice?
This was my original implementation using Facet and aggregating facet results.
public async Task<PagedResult<TDocument>> GetAll<TDocument>(
    Expression<Func<TDocument, bool>> filter,
    Sort<TDocument> sort,
    Pagination pagination,
    CancellationToken cancellationToken = new())
    where TDocument : class, IDocument
{
    filter ??= doc => true;
    sort ??= Sort<TDocument>.Default;
    if (pagination == null) throw new ArgumentNullException(nameof(pagination));

    var collection = _collectionRetrieverService.GetCollection<TDocument>();

    var sortDefinition = GetSortDefinition(sort);

    var pageNumber = pagination.PageNumber;
    var pageSize = pagination.PageSize;

    var countPipelineDefinition =
        PipelineDefinition<TDocument, AggregateCountResult>
            .Create(new[]
            {
                PipelineStageDefinitionBuilder.Count<TDocument>()
            });

    var dataPipelineDefinition =
        PipelineDefinition<TDocument, TDocument>
            .Create(new[]
            {
                PipelineStageDefinitionBuilder.Sort(sortDefinition),
                PipelineStageDefinitionBuilder.Skip<TDocument>((pageNumber -1) * pageSize),
                PipelineStageDefinitionBuilder.Limit<TDocument>(pageSize)
            });

    const string countFacetName = "count";
    const string dataFacetName = "data";

    var countFacet = AggregateFacet.Create(countFacetName, countPipelineDefinition);
    var dataFacet = AggregateFacet.Create(dataFacetName, dataPipelineDefinition);

    var aggregateOptions =
        new AggregateOptions
        {
            // Collation is not currently supported in AWS DocumentDB. See https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html#mongo-apis-index
            //Collation = CollationOptions.CaseInsensitiveCollation
        };

    var aggregation =
        await collection
            .Aggregate(aggregateOptions)
            .Match(filter)
            .Facet(countFacet, dataFacet)
            .ToListAsync(cancellationToken);

    var count =
        aggregation
            .First()
            .Facets
            .First(x => x.Name == countFacetName)
            .Output<AggregateCountResult>()
            ?.FirstOrDefault()
            ?.Count;

    if (count is null)
    {
        var emptyResult =
            new PagedResult<TDocument>()
            {
                Items = Enumerable.Empty<TDocument>(),
                PageNumber = pageNumber,
                PageSize = pageSize,
                TotalPages = pageNumber,
                TotalCount = 0
            };
        return emptyResult;
    }

    var totalPages = (int)Math.Ceiling((double)count/ pageSize);

    var data =
        aggregation
            .First()
            .Facets
            .First(x => x.Name == dataFacetName)
            .Output<TDocument>();

    var result =
        new PagedResult<TDocument>
        {
            Items = data,
            PageNumber = pageNumber,
            PageSize = pageSize,
            TotalPages = totalPages,
            TotalCount = count.Value
        };

    return result;
}

UPDATE 2021-07-06
This is my workaround, which queries twice the database because I need the total count of items matching the filter criteria.
public async Task<PagedResult<TDocument>> GetAll<TDocument>(
    Expression<Func<TDocument, bool>> filter,
    Sort<TDocument> sort,
    Pagination pagination,
    CancellationToken cancellationToken = new())
    where TDocument : class, IDocument
{
    filter ??= doc => true;
    sort ??= Sort<TDocument>.Default;
    if (pagination == null) throw new ArgumentNullException(nameof(pagination));

    var collection = _collectionRetrieverService.GetCollection<TDocument>();

    var sortDefinition = GetSortDefinition(sort);

    var pageNumber = pagination.PageNumber;
    var pageSize = pagination.PageSize;

    var skipCount = pageSize * (pageNumber - 1);

    var count = await collection.CountDocumentsAsync(filter, cancellationToken: cancellationToken);

    if (count == 0)
    {
        var emptyResult =
            new PagedResult<TDocument>()
            {
                Items = Enumerable.Empty<TDocument>(),
                PageNumber = pageNumber,
                PageSize = pageSize,
                TotalPages = pageNumber,
                TotalCount = count
            };
        return emptyResult;
    }

    var totalPages = (int)Math.Ceiling((double)count/ pageSize);

    var findOptions =
        new FindOptions<TDocument,TDocument>
        {
            AllowPartialResults = false,
            Sort = sortDefinition,
            Limit = pageSize,
            Skip = skipCount
            // Collation is not currently supported in AWS DocumentDB. See https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html#mongo-apis-index
            //Collation = CollationOptions.CaseInsensitiveCollation
        };
    var queryResult = await collection.FindAsync(filter, findOptions, cancellationToken);
    var results = await queryResult.ToListAsync(cancellationToken: cancellationToken);

    var result =
        new PagedResult<TDocument>
        {
            Items = results,
            PageNumber = pageNumber,
            PageSize = pageSize,
            TotalPages = totalPages,
            TotalCount = count
        };

    return result;
}


text:
Q: Hide iframe but somehow disengage it I am creating a website which hosts 360 panaramic photography. I am creating basically a slideshow of 360's using an iframe with tiled thumbnails. When the user clicks on a tile it loads that 360 into the iframe through JS by changing the src value of the iframe.
My issue is bandwidth, If I use the method of loading the src value into the iframe then every time this occurs, it seems to reload the content - looking at my network tab in my browser this does seem to be the case, I can see the image files being reloaded for a second time if the user re-views a tile/iframe.
My other option would be to have multiple iframes and just hide or show them based on which tile was clicked. Maybe using 'display:none'?
However would this then create the issue of multiple 360 panoramic photos running at the same time and being taxing on the users computer/ graphics card? Or would display:none then disengage the iframe from creating work for the graphics card?
Is there anyway to tell whether the iframe has been disengaged when hidden and is no longer taxing the users computer?
And if it is, then is there a way around this somehow? Can an iframe be disengaged so that it isn't running so to speak but it can still be made visible to the user again without reloading the content again.
Thanks, I hope this makes sense.

A: I think your problem can be solved using two things: Lazy Loading and Visibility.
You can achieve the lazy loading either the native way
<iframe src="your-360-image" loading="lazy"></iframe>

or using one of the libraries that does it for you, Iframely and lazyframe are good ones.
You can set the all the iframes to start loading in the background when the user is near them, so by the time the user clicks the tile, it's already loaded.
Regarding that the browser reloads the images, that might be because you set display to none, or even remove the element completely from the DOM. You might just want to hide it by setting the visibility to hidden, this should not re-load it again.


text:
Q: Existence of $E[X]$ and $E[X^2]$ We know that $\operatorname{Var}(X)=E[X^2]-E[X]^2$. I want to know that if $E[X^2]$ exists,  does it guarantees then $E[X]$ will also exist?

A: $0\le |X| \le \max(1,X^2) \le 1+X^2$ so $0 \le E[|X|] \le 1+ E[X^2]$,
meaning that if $E[X^2]$ is finite then so too are $E[|X|]$ and $E[X]$


text:
Q: Determining the Problematic CSS File in Firebug I have this displayed in my Firebug console

"NetworkError: 404 Not Found - http://********.com/images/slider-img/ajax-loader.gif"

So it's telling me it can't find a background image. But can it pinpoint which CSS file this image has been declared as a background-image property?
I have about 4-5 CSS files being referenced in the document and the manual way of finding it out would to open each of the files and find for this image. So I was wondering if this could be avoided and have Firebug tell me which CSS file is the culprit...

A: Firebug currently (as of version 2.0.x) doesn't directly show you the initiator of a network request. This requires platform support, which is requested in bug 563623.
So, as a workaround you can do this:

*

*Switch to the CSS panel.

*Click into the search field at the right side of Firebug.

*Ensure that the option Multiple Files is checked.

*Enter ajax-loader.gif
=> The CSS panel will switch to the CSS source containing the rule containing the image value.
Notes:
There may be several properties referring to different images named ajax-loader.gif. So you should also check whether the path to the image corresponds to the one shown in the error message. (Within the search field you can hit Enter to get to the next match.)
It's not sure that the request comes from CSS. It may also come from JavaScript, e.g. through an AJAX request or by appending an <img> tag dynamically.


text:
Q: Create objects dynamically according to class files in specified project folder We have a folder with many classes that inherit from the same base class. Their names are formatted like this:

*

*firsttypesubclass_1.cls

*firsttypesubclass_2.cls

*firsttypesubclass_3.cls

*secondtypesubclass_1.cls

*secondtypesubclass_2.cls

The program should scan this class folder and create a temp-table with the class-name prefix and count (f.ex "firsttypesubclass" and count=3):
DEFINE PUBLIC TEMP-TABLE TT_AllSubClasses NO-UNDO
   FIELD Name AS INT /* f.ex "firsttypesubclass" */
   FIELD Name AS INT /* f.ex "firsttypesubclass" */
.

Then we need to create new instances dynamically according to the found classes in a loop like this:
DEF VAR newInstance AS CLASS myBaseClass NO-UNDO.
newInstance = DYNAMIC-NEW TT_AllSubClasses.Name + "_" + STRING(1)(123123) NO-ERROR.

Is there any convenient way to list the class names in the folder? Or is it possibly to get all classes that inherit from the baseclass? I'm thinking about using the file system for checking up the files.

A: You will have to reach out to the file system and list all class files in the relevant folder. If at runtime the source code is not available, you should base your code on R-code. INPUT FROM OS-DIR is your friend there.
If you are mixing procedural and class based R-code in those relevant folders, you'll also have to verify if the R-code is from a procedure or a class:
RCODE-INFO:FILE-NAME = cFileName .

IF RCODE-INFO:IS-CLASS THEN ...
OpenEdge 11.6 has more reflection features. But there is no functionality that lists all child classes of a given base class. As the ABL does not have a fixed library scheme for classes (like C#), that would probably also be difficult for Progress to implement.


text:
Q: When i add carousel in modal , close button is not working in angular 6 I want to add a carousel in a modal popup, so i have add carousel it is working fine.
But when tried to to close the model using close button , it is not working.
Link to stackblitz demo

Any suggestions on how to make work of close button?
Thanks in advance!

A: Please try to change css for prev/next arrows:
.carousel-control-next, .carousel-control-prev {
    height: 30px;
    top: 50%;
    transform: translateY(-50%);
}

top and transform will set arrow icon vertically centered. You can change these values easly depending on your needs. And now prev/next controls will have only 30px height. Hope it helps.


text:
Q: Trying to extract a subimage using python and openimageIO fails I just getting into writing stuff using OpenImageIO. I my experiment, I'm trying to extract a few select sub images from an exr file and write them into another one. But when I try the following examples from the documentation and I keep getting an error.
#!/usr/bin/env python

import OpenImageIO as oiio

filename = "a.exr"
final = "b.exr"

input = oiio.ImageInput.open (filename)
spec = input.spec ()
pixels = input.read_image ()
input.close ()

output = oiio.ImageOutput.create (final)
if output.supports("multiimage") :
    output.open(final, spec)
    output.write_image(pixels)
    output.close ()

When I try this, I get the following error :
ArgumentError: Python argument types in
    ImageOutput.open(ImageOutput, str, ImageSpec)
did not match C++ signature:
    open(PyOpenImageIO::ImageOutputWrap {lvalue}, std::string, boost::python::tuple {lvalue})
    open(PyOpenImageIO::ImageOutputWrap {lvalue}, std::string, OpenImageIO::v1_6::ImageSpec, OpenImageIO::v1_6::ImageOutput::OpenMode)

I was wondering if anyone can please point out what I'm doing wrong here? Any help is very much appreciated.
Thanks a lot

A: Do you know which version specifically you are using?
It's some flavor of 1.6. That's from years ago. The current supported release is 2.0. Is it at all possible for you to use a modern version? Whatever trouble you're running into may be a long-ago-solved problem.


text:
Q: Highlight the list-view selected item programatically in xamarin.forms I'm trying to develop a wpf chat application.I've been looking everywhere for a way to select an item in a ListView and change the color of the row to let the user know which row is selected programatically.
What my requirement exactly is:
On login to the application the user is able to see list of channels and contacts and the logged-in user gets a notification when a user sends him a message.If the user clicked on that notification then the message sender contact should be highlighted to let the user know which chat is opened.
I've tried to set the selected item of listview as the sender based on id but still no use.
var index = _myViewModel.Users.IndexOf(selectedUser);

MyListView.SelectedItem = _myViewModel.Users[index];

I've googled about this and found some links which provide solutions for same case in xamarin/xamarin.android/winforms. but nothing solves my problem as the properties they've used are not available in xamarin.forms listview.
Here are the links:
Xamarin Android ListView select item and change row color
How to select an item in a ListView programmatically?.
Is it possible to do like this.If yes,Is there any workaround to achieve this.Can anyone please help me with this.
Thanks.

A: You can refer my answer given in one of the previous post:
ListView not unselecting
You can create Custom view cell of your List view and add background color to selected view cell.
Hope this may solve your issue.

A: Solution:
You can bind your Cell's background color with the property in your model. When  the user clicked on that notification, change the background color of the specific cell in model and then it will change in listview:
    private void ClickNotification(object sender, EventArgs e)
    {
        var index = _myViewModel.Users.IndexOf(selectedUser);

        //change the background color of the specific cell in model
        myModel model = _myModelList[index];
        model.myBackColor = Color.Blue;
    }

In the model:
class myModel : INotifyPropertyChanged
{
    Color backColor;

    public event PropertyChangedEventHandler PropertyChanged;

    public myModel( Color myColor)
    {
        backColor = myColor;
    }

    public Color myBackColor
    {
        set
        {
            if (backColor != value)
            {
                backColor = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("myBackColor"));
                }
            }
        }
        get
        {
            return backColor;
        }
    }
}

And in the xaml:
<ListView x:Name="myListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" BackgroundColor="{Binding myBackColor}">

                </StackLayout>

            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>


text:
Q: Moving files from one directory to another directory in HDFS using Pyspark I am trying to read data all the JSON files from one directory and storing them in Spark Dataframe using the code below. (it works fine)
spark = SparkSession.builder.getOrCreate()

df = spark.read.json("hdfs:///user/temp/backup_data/st_in_*/*/*.json",multiLine=True)

but when I try to save the DataFrame with multiple files, using the code below
df.write.json("hdfs:///user/another_dir/to_save_dir/")

It doesn't store the files as expected and throws error like to_save_dir already exists
I just want to save the files just like I read it from source dir to destination dir.
edit:
The problem is that, when i read multiple files and want to write it in a directory, what is the procedure in Pyspark? The reason i am asking this is because once the spark load all the files it creates a single dataframe, and each file is a row in this dataframe, how should i proceed to create new file for each of the rows in dataframe

A: The error you get is quite clear, it seems the location you're trying to write into already exists. You can choose to overwrite it by specifying the mode :
df.write.mode("overwrite").json("hdfs:///user/another_dir/to_save_dir/")

However, if your intent is to only move files from one location to another in HDFS, you don't need to read the files in Spark and then write them. Instead, try using Hadoop FS API:
conf = sc._jsc.hadoopConfiguration()
Path = sc._gateway.jvm.org.apache.hadoop.fs.Path
FileUtil = sc._gateway.jvm.org.apache.hadoop.fs.FileUtil

src_path = Path(src_folder)
dest_path = Path(dest_folder)

FileUtil.copy(src_path.getFileSystem(conf),
              src_path,
              dest_path.getFileSystem(conf),
              dest_path,
              True,
              conf)


text:
Q: How to turn radio button into string and store it into the database? EDIT: This post is now solved. However, there are new errors..when I select "Female", it shows me "Male" is selected when I go to the ViewRecord page.
Adding Records (gender)
Viewing Records (gender)
I am trying to make an app with Android Studio which takes student's information and stores them in the database. Part of that information is the student's gender.
When the student selects a radio button (either male or female), that selection gets added to the database.
I have attempted the coding for it but my app crashes whenever I open it...
This is the layout code (xml).
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="40dp"
android:background="#F0F8FF"
>

<TableLayout
    android:id="@+id/add_table"
    android:layout_width="match_parent"
    android:layout_height="606dp"
    android:paddingTop="40dp">

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Student ID:" />

        <EditText
            android:id="@+id/sid"
            android:layout_width="190dp"
            android:layout_height="wrap_content" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="First Name:" />

        <EditText
            android:id="@+id/fn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Last Name:" />

        <EditText
            android:id="@+id/ln"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:layout_marginTop="5dp"
            android:text="Gender:" />

        <RadioGroup
            android:id="@+id/ge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:orientation="horizontal">

            <RadioButton
                android:id="@+id/male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scaleX="0.9"
                android:scaleY="0.9"
                android:checked="true"
                android:text="Male" />

            <RadioButton
                android:id="@+id/female"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:scaleX="0.9"
                android:scaleY="0.9"
                android:text="Female" />

        </RadioGroup>

    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Course Study:" />

        <EditText
            android:id="@+id/cs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:digits="0123456789"
            android:inputType="number"
            android:padding="3dip"
            android:text="Age:" />

        <EditText
            android:id="@+id/ag"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />
    </TableRow>

    <TableRow>

        <TextView
            android:layout_marginLeft="25dp"
            android:padding="3dip"
            android:text="Address:" />

        <EditText
            android:id="@+id/ad"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minWidth="150dip" />

    </TableRow>

    <Button
        android:id="@+id/add_button"
        android:layout_width="207dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="118dp"
        android:layout_marginRight="52dp"
        android:layout_marginTop="14dp"
        android:padding="6dip"
        android:text="Add Student" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        app:srcCompat="@mipmap/man" />

</TableLayout>

 </LinearLayout>

This is the main activity (java code)
public class Addrecord extends AppCompatActivity {

DatabaseManager myDb;
EditText sid, fn, ln, cs, ag, ad;
RadioGroup radioGenderGroup;
RadioButton radioGenderButton;

Button btnAddStudent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle(null);
    myDb = new DatabaseManager(this);

    sid = (EditText)findViewById(R.id.sid);
    fn = (EditText)findViewById(R.id.fn);
    ln = (EditText)findViewById(R.id.ln);

    radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
    int selectedid = radioGenderGroup.getCheckedRadioButtonId();
    radioGenderButton = (RadioButton) findViewById(selectedid);

    cs = (EditText)findViewById(R.id.cs);
    ag = (EditText)findViewById(R.id.ag);
    ad = (EditText)findViewById(R.id.ad);
    btnAddStudent = (Button)findViewById(R.id.add_button);

    AddStudentRecord();

}

public  void AddStudentRecord() {
    btnAddStudent.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isInserted = myDb.insertDataStudent(
                            Integer.parseInt(sid.getText().toString()),
                            fn.getText().toString(),
                            ln.getText().toString(),
                            radioGenderButton.getText().toString(),
                            cs.getText().toString(),
                            Integer.parseInt(ag.getText().toString()),
                            ad.getText().toString()

                    );

                    if(isInserted == true)
                        Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show();
                    else
                        Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show();
                }
            }
    );
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.screen2_menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement

    if (id == R.id.home2) {
        Intent intent = new Intent(Addrecord.this, Home.class);
        startActivity(intent);
        return true;

    }
    return super.onOptionsItemSelected(item);
}
 }

This is the database (java)
public class DatabaseManager extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "student";
public static final String TABLE_NAME1 = "studentinfo";
public static final String TABLE_NAME2 = "taskinfo";
public static final String TABLE_NAME3 = "examinfo";

//student information
public static final String COL_0student = "IDstudent";
public static final String COL_1student = "studentId";
public static final String COL_2student = "firstname";
public static final String COL_3student = "lastname";
public static final String COL_4student = "gender";
public static final String COL_5student = "coursestudy";
public static final String COL_6student = "age";
public static final String COL_7student = "address";

//task information

public static final String COL_0task = "IDtask";
public static final String COL_1task = "taskname";
public static final String COL_2task = "location";
//public static final String COL_3task = "status";

//exam information (no need for Id since no selection happening)

public static final String COL_1exam = "unitname";
public static final String COL_2exam = "date";
public static final String COL_3exam = "time";
public static final String COL_4exam = "location3";

public DatabaseManager(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table if not exists " + TABLE_NAME1 + " (IDstudent INTEGER PRIMARY KEY AUTOINCREMENT,studentId INTEGER,firstname TEXT,lastname TEXT, gender TEXT, coursestudy TEXT, age INTEGER, address TEXT)");
    db.execSQL("create table if not exists " + TABLE_NAME2 + " (IDtask INTEGER PRIMARY KEY AUTOINCREMENT, taskname TEXT,location TEXT,status TEXT)");
    db.execSQL("create table if not exists " + TABLE_NAME3 + " (unitname TEXT,date TEXT,time TEXT, location TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME1);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME3);
    onCreate(db);
}

//INSERT, UPDATE, SELECT, DELETE student record

public boolean insertDataStudent(Integer studentId, String firstname, String lastname, String gender, String coursestudy, Integer age, String address) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues newStudent = new ContentValues();
    newStudent.put(COL_1student, studentId);
    newStudent.put(COL_2student, firstname);
    newStudent.put(COL_3student, lastname);
    newStudent.put(COL_4student, gender);
    newStudent.put(COL_5student, coursestudy);
    newStudent.put(COL_6student, age);
    newStudent.put(COL_7student, address);

    long result = db.insert(TABLE_NAME1, null, newStudent);
    if (result == -1)
        return false;
    else
        return true;
}

public Cursor getAllDataStudent() {
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from " + TABLE_NAME1, null);
    return res;
}

public boolean updateDataStudent(String idstudent, String studentId, String firstname, String lastname, String gender, String coursestudy, String age, String address) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues newStudent = new ContentValues();
    newStudent.put(COL_0student, idstudent);
    newStudent.put(COL_1student, studentId);
    newStudent.put(COL_2student, firstname);
    newStudent.put(COL_3student, lastname);
    newStudent.put(COL_4student, gender);
    newStudent.put(COL_5student, coursestudy);
    newStudent.put(COL_6student, age);
    newStudent.put(COL_7student, address);

    db.update(TABLE_NAME1, newStudent, "IDstudent = ?", new String[]{idstudent});
    return true;
}

public Integer deleteDataStudent(String idstudent) {
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME1, "IDstudent = ?", new String[]{idstudent});
}

  }

This is the error log
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.supriya.project3, PID: 5517
              java.lang.RuntimeException: Unable to start activity   ComponentInfo{com.supriya.project3/com.supriya.project3.Addrecord}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference
                  at com.supriya.project3.Addrecord.onCreate(Addrecord.java:42)
                  at android.app.Activity.performCreate(Activity.java:7009)
                  at android.app.Activity.performCreate(Activity.java:7000)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
    I/zygote: Do full code cache collection, code=98KB, data=54KB
      After code cache collection, code=93KB, data=45KB
    Application terminated.

A: If you are looking for how you can catch the input from radio group. Here is a little hint for you. You also need to get RadioButton id and implement a listener. That's all.
radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
//Get also male and Female (RadioButton) id from the layout.

radioGenderGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
                // checkedId is the RadioButton selected
                if (rdoMale.getId() == checkedId) {
                    //Get the value for male R.Button.rdoMale

                } else if (rdoFemale.getId() == checkedId) {
                  //Get the value for Female R.Button.rdoFemale
                }
        }
    });

A: In onCreate method
radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
radioGenderGroup .setOnCheckedChangeListener(this);

Then override onCheckedChanged method
@Override
public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
    switch (group.getId()) {
        case R.id.male:
            gender = "Male";
            break;

        case R.id.female:
            gender = "Female";
            break;

    }
}

A: Solution:
Firstly, set any one of the RadioButton as:
android:checked="true"

So it should look like:
<RadioButton
    android:id="@+id/male"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleX="0.9"
    android:scaleY="0.9"
    android:text="Male"
    android:checked="true" />

This will give you by default as Male text in String gender.
Secondly, remove this line: String gender = String.valueOf(radioGenderButton.getText()); from this part.
radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
int selectedid = radioGenderGroup.getCheckedRadioButtonId();
radioGenderButton = (RadioButton) findViewById(selectedid);
String gender = String.valueOf(radioGenderButton.getText()); // REVOME THIS

then,
Write this:
radioGenderGroup = (RadioGroup) findViewById(R.id.ge);
int selectedid = radioGenderGroup.getCheckedRadioButtonId();
radioGenderButton = (RadioButton) findViewById(selectedid);

Inside onClick() as shown:
btnAddStudent.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                .... (Write those 3 lines here)

                boolean isInserted = myDb.insertDataStudent(
                        Integer.parseInt(sid.getText().toString()),
                        fn.getText().toString(),
                        ln.getText().toString(),
                        radioGenderButton.getText().toString(),
                        cs.getText().toString(),
                        Integer.parseInt(ag.getText().toString()),
                        ad.getText().toString()

                );

                if(isInserted == true)
                    Toast.makeText(Addrecord.this,"Data Inserted",Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(Addrecord.this,"Data not Inserted",Toast.LENGTH_LONG).show();
            }
        }
);

With the above steps, you will get whatever gender you select and then pass it to database for inserting.
Hope it helps.


text:
Q: WMI : MSVM_Imagemanagmentservice mount method does not assign drive letter I m trying to mount a vhd on windows 2012 hyperV core datacenter edition. For mounting the vhd I m using the MSVM_Imagemanagementservice class and mount method inside that. The disk is mounted but the problem is no drive letter is getting assigned. I have tried it on other 2012 datacenter edition and 2012 core as well it works fine. i.e after mount the drive letter gets assigned.
Any thoughts on this will help.

A: You can query for the drive letters list and then assign the drive letter as per your requirement. Given below is the function to get the drive letters list.
Function GetDriveLetterList(path)

    'Where path is path of VHD

    Dim mountedImage, diskDevice, diskPartition, diskPartitions, logicalPartition, timeout, query
    Dim logicalPartitionList

    timeout = 0
    driveLetterList = ""

    path = Replace(path,"\","\\")

    Set wmiServiceCIM = GetObject("winmgmts:\\.\root\cimv2")

    Do
        WScript.Sleep(3000)
        timeout = timeout + 3

        Set mountedImage = (wmiService.ExecQuery("SELECT * FROM Msvm_MountedStorageImage WHERE Name='" & path & "'")).ItemIndex(0)

        query = "SELECT * From Win32_DiskDrive WHERE Model='Msft Virtual Disk SCSI Disk Device' and SCSITargetId='" & mountedImage.TargetId & "' and SCSILogicalUnit='" & mountedImage.Lun & "' and SCSIPort='" & mountedImage.PortNumber & "'"
        Set diskDevice = wmiServiceCIM.ExecQuery(query).ItemIndex(0)

        query = "ASSOCIATORS OF {" & diskDevice.Path_.Path & "} where AssocClass=Win32_DiskDriveToDiskPartition"

        Set diskPartitions = wmiServiceCIM.ExecQuery(query)

        For Each diskPartition In diskPartitions

            query = "ASSOCIATORS OF {" & diskPartition.Path_.Path & "} WHERE AssocClass=Win32_LogicalDiskToPartition"
            Set logicalPartitionList = wmiServiceCIM.ExecQuery(query)
            If logicalPartitionList.count > 0 Then
                Set logicalPartition = logicalPartitionList.ItemIndex(0)
                'WScript.Echo logicalPartition.DeviceID
                driveLetterList = driveLetterList + logicalPartition.DeviceID
            End If

        Next
End Function

If you want to check for systems drive . Then you can do this ...
folderPath = driveLetter + ":\Windows\System32"

Set fileSys = CreateObject("Scripting.FileSystemObject")
If filesys.FolderExists(folderPath) Then
    //doStuff
End If


text:
Q: How to run "script -a xxx.txt" properly in a shell script? I have a shell script and I want the session text to be saved automatically every time the script runs, so I included the command "script -a output.txt" at the beginning of my script. However, the script stops running after this line of code, which only displays a "bash-3.2$" on the screen and won't go on. Any ideas?
Thanks in advance!

A: The problem is script starts a separate sub-shell than the one that is running the actual script, to club them together. Use the -c flag in script
-c, --command command
       Run the command rather than an interactive shell.  This makes
       it easy for a script to capture the output of a program that
       behaves differently when its stdout is not a tty.

Just do,
script -c 'bash yourScript.sh' -a output.txt


text:
Q: Adding Column to pandas DataFrame in Vectorized way conditioning on other column values I have a pandas dataframe df
>>> df
           a  b  c
0          1  1  0
1          1 -1  1
2          1  0  0

Now I want to add a new column df['e'] conditioning on column a and b. I would like to create the new column in vectorized manner.
For now, I am doing like the following:
df["e"] = [-1 if (df['a'] == 1 and df['b'] == 1) else 1]

which should output:
>>> df
               a  b  c  e
    0          1  1  0 -1
    1          1 -1  1  1
    2          1  0  0  1

But I am getting the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/hmishfaq/anaconda/lib/python2.7/site-packages/pandas/core/generic.py", line 917, in __nonzero__
    .format(self.__class__.__name__))
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

What am I doing wrong and what's the correct way of vectorizing here?
PS: The original dataframe I need to use is really big and thus for-loop takes forever to do this.

A: You can use very fast numpy.where:
df['e'] = np.where((df['a'] == 1) & (df['b'] == 1), -1, 1)
print (df)
   a  b  c  e
0  1  1  0 -1
1  1 -1  1  1
2  1  0  0  1

A: Your error stems from the fact that you're using and, instead of &. Switch to the latter and your error will go away.
Solution:
df["e"] = [-1 if (df['a'] == 1 & df['b'] == 1) else 1]


text:
Q: How to resize height of the Dijit TimeTextBox I tried using the following in changing the height of TimeTextBox:

*

*data-dojo-props="style: { height : 16px } "
=> The arrow button does not change but the box gets smaller.

*data-dojo-props="height: '16px' "
=> Does not work

A: To resize it you have to do it programatically according to the docs
require(["dojo/parser", "dijit/form/TextBox"]);
<label for="dtb">A default textbox:</label>
 <input id="ltb" style="height: 10em;" data-dojo-type="dijit/form/TextBox" />


text:
Q: Cant get a working jsfiddle to work when I copy over to my computer When I click on this fiddle: http://jsfiddle.net/RQL5V/ everything is working properly.
However, when I attempt to copy the code over to Dreamweaver(html file) via http://jsfiddle.net/RQL5V/show/ and deploy, the page seems to freeze up and when the links are clicked and drop down is supposed to be displayed nothing happens...
I cant get this to work not matter what I try!
any help would be greatly appreciated.

Thanks!

A: The problem is that you can't simply copy the code, since there are some relative URLs. Specifically //code.jquery.com/jquery-1.9.1.js is the problem, it's a relative URL made to be short and work both in HTTP or HTTPS. If you use the absolute URL http://code.jquery.com/jquery-1.9.1.js it should work.
When working on a document loaded by a file: URL, the above relative path would be resolved into file://code.jquery.com/jquery-1.9.1.js.


text:
Q: Contract period: Automatically extended for three year periods I confused this sentence so much.
This general agreement shall remain in effect for three years. It will be automatically extended for three year periods.
Is it mean that the agreement will be renewed every three year period? or valid only 6 years?

A: The plural "periods" tells you that at the end of each period, it will be extended for another period, and so on indefinitely.
If they meant only one additional period, they would have used the singular "period".
In both cases, you would expect to see some additional language about how one or both parties can prevent the automatic extension; usually in such contracts neither party can cancel a period that has already started—at least without cause—so this is the only way to keep it from becoming permanent.


text:
Q: How to add custom Play/ pause buttons, volume bar etc in MPMoviePlayerController? I am trying to create a player like in a image below, starting from play and pause button. but it's not showing up on a player. how can i create customize panel for my player, custom bar, volume bar etc?
- (IBAction)playMovie:(UIButton *)sender {

NSURL *url = [[NSURL alloc] initWithString:urlStr.text];
self.movie = [[MPMoviePlayerController alloc]initWithContentURL:url];
self.movie.controlStyle = MPMovieControlStyleNone;

self.movie.shouldAutoplay = YES;
[self.view addSubview:self.movie.view];
[self.movie setFullscreen:YES animated:YES];

playButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];
[playButton setImage:[UIImage imageNamed:@"apple.png"] forState:UIControlStateNormal];
[playButton addTarget:self action:@selector(playButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:playButton];
}

A: add player on a view with button like your image describes
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:urlVideo];
    [moviePlayerController.view setFrame:CGRectMake(0, 170, 320, 270)];
    [self.view addSubview:moviePlayerController.view];
    moviePlayerController.fullscreen = YES;
    [moviePlayerController play];// put it in action


text:
Q: Data Type Mismatch Gridview UPDATE cannot figure out what the data mismatch is referring too, AutoNum is Int32 and UID is String or Int32, neither works?
<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="True"
    BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3"
    DataKeyNames="AutoNum" DataSourceID="AccessDataSource1" ForeColor="Black" GridLines="Vertical"
    AutoGenerateEditButton="true" AutoGenerateDeleteButton="true">
    <FooterStyle BackColor="#CCCCCC" />
    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#6699CC" />
</asp:GridView>

<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="<%$ ConnectionStrings:AccessSubSiteString %>"
    DeleteCommand="DELETE FROM [UsersDataCareerTbl] WHERE [AutoNum] = ?"
    SelectCommand="SELECT * FROM UsersDataCareerTbl"
    UpdateCommand="UPDATE [UsersDataCareerTbl] SET UID = ?  WHERE [AutoNum] = ?">
    <DeleteParameters>
        <asp:Parameter Name="AutoNum" Type="Int32" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="UID" Type="String" />
        <asp:Parameter Name="AutoNum" Type="Int32" />
    </UpdateParameters>
</asp:AccessDataSource>

error message is:
 Data type mismatch in criteria expression.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Data type mismatch in criteria expression.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:


text:
Q: Docker npm errno -13 I'm running a very simple Node.js Koa "hello world" application on Docker 2.4.0 on Windows.  If the base image is node:10-alpine, it works well:
FROM node:10-alpine
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
WORKDIR /home/node/app
COPY package*.json ./
USER node
RUN npm install
COPY --chown=node:node . .
EXPOSE 8080
CMD [ "node", "index.js" ]

But if I change the version to FROM node:15.0.1-alpine3.10
Step 6/9 : RUN npm install
 Removing intermediate container 6ff212db1484
 ---> bfde467f103d
Step 6/9 : RUN npm install
 ---> Running in 37ef90ef4039
npm ERR! code EACCES
npm ERR! syscall open
npm ERR! path /home/node/app/package-lock.json
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, open '/home/node/app/package-lock.json'
npm ERR!  [Error: EACCES: permission denied, open '/home/node/app/package-lock.json'] {
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'open',
npm ERR!   path: '/home/node/app/package-lock.json'
npm ERR! }
........

A: npm install will try to update the package-lock.json file with the current actual versions of the packages it's installed.  For installation in a Docker image, you don't really want this; use npm ci instead to avoid this.
The other problem you're encountering is that COPY by default makes files owned by the root user, but you've switched to an alternate "node" user.  You probably want the application code in your image to be owned by root, and then run as an alternate user: if there's some sort of security issue, this gives you an extra layer of protection against the code in the container getting modified.
If you do both of these things, the corrected Dockerfile would roughly look like:
FROM node:15.0.1-alpine3.10

# WORKDIR also creates the directory.  It will be owned by root,
# which is probably what you want.  (So no `RUN mkdir ...`.)
WORKDIR /home/node/app

# Stay as the root user for now.

# Install packages:
COPY package*.json ./
RUN npm ci             # not `npm install`

# Copy in the rest of the application (still owned by root):
COPY . .

# Declare runtime metadata.  Only now switch to the "node" user.
# This will not be able to modify the source code (good).
USER node
EXPOSE 8080
CMD ["node", "index.js"]


text:
Q: XML processing in distributed system I'm working on Big data from last couple of months.
1
I'm curious to know how XML processing works in multi nodes network. Lets say I have one xml and that's having repetitive tags and in every those tags there are more similar tags.
To process XML, Whole XML needs to be in memory first. So, the moment I submit my hadoop mapreduce task to process 100 GB of XML in the cluster (Lets say 5 node cluster) to process, then how loading of XML in different nodes happens ?
In case of flat files, I can imagine that keep reading the records( one by one) from HDFS and distributing among nodes. But not able to understand in XML. How hadoops know, on what basis of tags splits or distribution needs to happen ?
<employees>
    <employee id="be129">
        <firstname>Jane</firstname>
        <lastname>Doe</lastname>
        <title>Engineer</title>
        <division>Materials</division>
        <building>327</building>
        <room>19</room>
        <supervisor>be131</supervisor>
    </employee>
    <employee id="be130">
        <firstname>William</firstname>
        <lastname>Defoe</lastname>
        <title>Accountant</title>
        <division>Accts Payable</division>
        <building>326</building>
        <room>14a</room>
    </employee>
    <employee id="be131">
        <firstname>Jack</firstname>
        <lastname>Dee</lastname>
        <title>Engineering Manager</title>
        <division>Materials</division>
        <building>327</building>
        <room>21</room>
    </employee>
    <employee id="be132">
        <firstname>Sandra</firstname>
        <lastname>Rogers</lastname>
        <title>Engineering</title>
        <division>Materials</division>
        <building>327</building>
        <room>22</room>
    </employee>
    <employee id="be133">
        <firstname>Steve</firstname>
        <lastname>Casey</lastname>
        <title>Engineering</title>
        <division>Materials</division>
        <building>327</building>
        <room>24</room>
    </employee>
    <employee id="be135">
        <firstname>Michelle</firstname>
        <lastname>Michaels</lastname>
        <title>COO</title>
        <division>Management</division>
        <building>216</building>
        <room>264</room>
    </employee>
</employees>

Lets consider above XML as an example, and imagine there are 10 million of employee tags, Then how hadoop mapper splitting mechanism works to distribute xml among 5 nodes and process and coordinate upon distributed XML to process ?
I hope my question is clear to all.

A: So, first of all, don't use MapReduce. At least, not default options because it only reads line delimited files, not XML formatting
If you want to process xml in parallel, opt for something like spark-xml or pre-process the XML documents before they even enter HDFS into a more Hadoop friendly format, for example, using something like Apache Nifi XML/XPath processors

A: The XML parsing pretty well has to be a sequential process, but it doesn't have to build the whole document in memory.
Everything that happens after parsing can be distributed and parallel.
You could do the initial processing of the XML using a SAX parser or using XSLT 3.0 streaming to split it up into smaller chunks, and then send the smaller chunks to multiple parallel processes. I don't know if any frameworks like NiFi will do this for you, or if you have to code it yourself "by hand".


text:
Q: grpc_out: protoc-gen-grpc: Plugin failed with status code 1 I have cross compiled gRPC (v1.27.3) for QNX 7 (ARM) platform. I am using the protobuf which was already available for our system (QNX ARM v3.11.4).
I used following cmake command to build gRPC for compilation process
cmake -DCMAKE_CROSSCOMPILING=1 -DgRPC_BUILD_TESTS=OFF -DgRPC_PROTOBUF_PROVIDER=package -DgRPC_SSL_PROVIDER=package -DgRPC_ZLIB_PROVIDER=package -DOPENSSL_CRYPTO_LIBRARY=$QNX_TARGET/aarch64le/usr/lib/libcrypto.a -DOPENSSL_SSL_LIBRARY=$TARGET/aarch64le/usr/lib/libssl.a -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=/tmp/qnxarm/toolchain.cmake -DCMAKE_INSTALL_PREFIX=/tmp/qnxarm/inst ../..

make plugins

make -j4

sudo make install

After compiling, I am able to see the binaries in /tmp/qnxarm/inst  folder.
I copied those binaries in our code to compile the application for QNX.
While compiling I am getting this issue:
<local_directory>/grpc/aarch64/qnx/bin/grpc_cpp_plugin: program not found or is not executable
Please specify a program using absolute path or make sure the program is available in your PATH system variable
--grpc_out: protoc-gen-grpc: Plugin failed with status code 1.
lib/qmonitor/proto/CMakeFiles/QMonitorProto.dir/build.make:105: recipe for target 'lib/qmonitor/proto/QAicMonitorInternal.grpc.pb.cc' failed
make[2]: *** [lib/qmonitor/proto/QAicMonitorInternal.grpc.pb.cc] Error 1

Please help me to know what is wrong? or what should be done to solve this.
Do we need to add the PATH in gRPCTargets.cmake file which is generated in lib folder?

A: You've compiled the gRPC tools for your QNX ARM system -- so the version of grpc_cpp_plugin you made is expecting to be run on your QNX system, not your build host.
The usual approach for this sort of thing is to make a second copy of gRPC compiled for your build host, and then instruct your application build to link the libraries from the cross build, but call the grpc_cpp_plugin compiled for the build host.


text:
Q: Make same changes to multiple git repositories We have a Dll with multiple versions. Each one needs to be supported separately as it is sold as a separate product. In some cases, bug fixes apply to multiple versions of the Dll. Previously, TFS was used. A changeset made to TB_2020 and TB_2021 would be created in TB_2020, merged up to TB_Mainline, and merged down to TB_2021.
...,
TB_2019,
TB_2020,
TB_2021,
TB_Mainline
We are transitioning over to git. We would like to use separate, forked repositories. Pushing a commit from TB_2020 to the remote TB_Mainline using force pushes all changes, not just that specific commit. Is what we want possible? If so, how could it be done?


text:
Q: Swipe to slide in new image I am looking for a script or tutorial in which I can display an image wrapped in an anchor tag and when I swipe to the left or right it displays a new image. This script should work with json and jquery mobile and indicates how many images are within the slideshow. Any such tutorial?

A: Awesome Mobile Image Gallery
Can be used as a static image gallery or load images dynamically via $.ajax.

A: I myself wrong the simplest form of image slider using jQuery for jQuery Mobile.
You can find the Tutorial here and the demo here.
Following is the core
$("#myImagePage").swiperight(function () {
        if (i < (imgURL.length - 1)) {
            i++
        } else {
            i = 0;
        }
        var imgStr = "";
        $('#ImageDiv').html(imgStr);
    });
    $("#myImagePage").swipeleft(function () {
        if (i > 0) {
            i--
        } else {
            i = (imgURL.length - 1);
        }
        var imgStr = "";
        $('#ImageDiv').html(imgStr);
    });


text:
Q: What's wrong with this simple SSL Vhost declaration? Any reason why the middle vhost setting is causing an issue w/ Apache? Maybe it's because I don't have the SSL details in there?
<VirtualHost *:80>
  ServerName www.windfarmstudios.com
  ServerAlias windfarmstudios.com
  Redirect permanent / https://windfarmstudios.com
</VirtualHost>

#<VirtualHost *:443>
#  ServerName www.windfarmstudios.com
#  Redirect permanent / https://windfarmstudios.com
#</VirtualHost>

<VirtualHost *:443>
  ServerName windfarmstudios.com
  DocumentRoot /var/www/windfarmstudios.com/public_html

  SSLEngine on
  SSLCertificateFile /etc/apache2/ssl/windfarm.crt
  SSLCertificateKeyFile /etc/apache2/ssl/windfarm.key
  SSLCACertificateFile /etc/apache2/ssl/windfarm.ca-bundle
</VirtualHost>


text:
Q: foreach not reached the first time but the second yes My foreach is not reached the first time I launch the code, but the second time I do (refresh or launch again code), the foreach works for the new DB entry + the olds one . I'm using CodeIgniter.
Code:
$visa = $this->db->get('visa');

            echo 'blop2';

            foreach ($visa->result() as $row_card_accept){

            echo 'blop3';

            $cardaccept = $row_card_accept->CARD_ACCEPT;
            $first = substr($cardaccept,6,1);
            $second = substr($cardaccept,7,1);

            if($first == '1' && $second == '1'){
                $this->db->query('UPDATE `visa` SET `CARD_ACCEPT`="B"');
            }elseif($first == '1' && $second == '0'){
                $this->db->query('UPDATE `visa` SET `CARD_ACCEPT`="V"');
            }elseif($second == '1' && $first == '0'){
                $this->db->query('UPDATE `visa` SET `CARD_ACCEPT`="P"');
            }
        }

So, blop2 is printed the first time I launch the code, blop3 not. The second time blop3 is printed too and my DB is updated correctly. Why this doesn't work the first time?


text:
Q: Is there a way to edit .scss files in Bootstrap's precompiled library? I'm working on the front-end of a project that had already progressed a decent amount before I joined. The project uses Bootstrap's precompiled library, so I don't have any access to the scss files. This means I can't find them at all in my folder.
bootstrap directory
The bootstrap directory is pretty much the one above. I've tried making changes in the css files such as bootstrap.css, but it doesn't work. The changes appear to be saved in the file, but when I run the project and inspect element, I see it referencing back to the scss files with the original code.
inspect element edited bootstrap.css
I'm currently using Visual Studio to edit my files. I've tried putting my own stylesheet after the bootstrap ones in the  to overwrite the boostrap stylesheet, but no luck.
Is there any way I can:

*

*access the scss files to edit them

*have my own stylesheet overwrite the boostrap one

*or just make changes to the bootstrap.css file

Is it plausible to install the version of bootstrap with the scss and replace the precompiled version mid-project?

A: Overwriting the boostrap with your own stylesheet is probably the safest way to go and totally doable you just need to add your own classes and then get super nested into them to override bootstrap. It can take alot of trial and error.

Is it plausible to install the version of bootstrap with the scss and replace the precompiled version mid-project?

I have done this before without too much trouble but it could cause issues if you change the bootstrap version or if someone previous had already customized it. In the later case you'd have to make sure to reflect those changes.
If you decide to go this route here is an awesome bootstrap customizer a co-worker made. https://github.com/rachaelshaw/bootstrap-4-customizer


text:
Q: Jndi bind Java null pointer exception I am learning JNDI from video tutorial. And i try bind my context but i get Java NullPointerException.
There is error.

Exception in thread "main" java.lang.NullPointerException
at com.sun.jndi.fscontext.FSContext.generateNamingException(FSContext.java:809)
at com.sun.jndi.fscontext.FSContext.generateNamingException(FSContext.java:783)
at com.sun.jndi.fscontext.RefFSContext.setBindings(RefFSContext.java:602)
at com.sun.jndi.fscontext.RefFSContext.bindObject(RefFSContext.java:338)
at com.sun.jndi.fscontext.RefFSContext.bind(RefFSContext.java:169)
at com.sun.jndi.fscontext.FSContext.bind(FSContext.java:167)
at javax.naming.InitialContext.bind(InitialContext.java:425)
at jndi.CustomerJndi.main(CustomerJndi.java:23)

and there is my code
  public static void main(String[] args) throws NamingException {

    Hashtable<String,String> environment= new Hashtable<String,String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
    environment.put(Context.PROVIDER_URL,"file:D:/Users");
    Context context=new InitialContext(environment);

    context.bind("Jea",new Boss("Boss","Boosovic"));

}

A: Hi I'm no expert but just created something like that.
Have you tried changing the URL
    environment.put(Context.PROVIDER_URL,"file:D:/Users");

TO
    environment.put(Context.PROVIDER_URL,"file:///D:/Users");


text:
Q: TcpClient - receive multiple messages from client on callback I am trying to create a TCP Listener, who receives the clients, keeps them open and when they send a data call a Callback Method.
I can't seem to find out how to add the callback and how to keep the client open.
My current Code looks like this:
 protected void Listener()
    {
        TcpListener __Listener = new TcpListener(System.Net.IPAddress.Any, Port);
        __Listener.Start();
        long _TicketNo = 0;

        while (IsRunning)
        {
            client = __Listener.AcceptTcpClient();

            _TicketNo++;

            RFIDReaderCommunication work = new RFIDReaderCommunication(client);
            Trigger(work.process());

            System.Threading.Thread.Sleep(100);
        }
    }

The work.process() simply reads the bytes from the network stream.
but this only receives data once from the Client.
Can anybody give me a hint how to receive data multiple times from this single connection?

A: You have client = __Listener.AcceptTcpClient(); inside your loop. This means as soon as the loop comes back around to the top, you're blocking to wait for the next incoming connection, and then overwriting your client variable.
For a start, move this line above the loop.


text:
Q: Creating a search box for quick entry in the spinner The idea is what. Available:
Spiner, adapter and array from where the spinner receives data.
I would like to add a window to the spinner so that you can enter the first letters and the spinner, in addition to the entire list, would give out matches
An example of such a window:

Array and Spinner:
<Spinner
    android:id="@+id/spinner4"
    android:layout_width="271dp"
    android:layout_height="37dp"
    android:layout_marginTop="8dp"
    android:spinnerMode="dialog"
    app:layout_constraintStart_toStartOf="@+id/textView19"
    app:layout_constraintTop_toBottomOf="@+id/textView19"/>

Adapter:
public synchronized void fillNameStocks() {
        String[] tempArr = new String[arrayListMols.size() + 1];
        tempArr[0] = "Nothing";
        for (int i = 0; i < arrayListMols.size(); i++) {
            tempArr[i + 1] = arrayListMols.get(i).Name;
        }
        MyArrayAdapter<String> adapter = new MyArrayAdapter<String>(this, R.layout.spinner_item, tempArr);
        spinnerNamesOfMols.setAdapter(adapter);
        spinnerNamesOfMols.setSelection(0);
        spinnerNamesOfMols.setOnItemSelectedListener(new SpinnerActivity());
    }

A: Found on Google a library called, which allows just changing one line (write "com.toptoche.searchablespinnerlibrary.SearchableSpinner" instead of "Spinner") and that's it, the problem is solved.
https://github.com/miteshpithadiya/SearchableSpinner


text:
Q: mysql How To join 2 column value into 2 column value I have two tables with columns as follows:

*

*khs (id, year, program, codemk)

*subjects (id, year, program, codemk,namemk, tm, pr, lp)

I want to have a result containing:
codemk, namemk, tm, pr, lp

Note: Fields year, program and codemk in khs table each is not unique also in subjects table. But combine the 3 value of those fields make a unique value.
I tried this:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON khs.year + khs.program +khs.codemk = subjects.year + subjects.program + subjects.codemk;

but the result for tm, pr and lp is not what I expected. What am I missing? Sorry I am new to MySQL and how do i create it to new table view.
Thanks in advance.

A: Why use a join? Why not try something like this:
SELECT codemk,namemk,tm,pr,lp
FROM khs,subjects
WHERE khs.year = subjects.year

A: Maybe this:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON khs.year=subjects.year, khs.program =subjects.program, khs.codemk = subjects.codemk;

But not sure if that is what you asked, otherwise:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON CONCAT(khs.year,khs.program, khs.codemk) = CONCAT(subjects.year, subjects.program, subjects.codemk);

A: I am not sure what is your result expectetions (could you provide it please? as well as samples of data tables) but you can try for now:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
INNER JOIN subjects
ON khs.year = subjects.year
 AND khs.program = subjects.program
 AND khs.codemk =  subjects.codemk;


text:
Q: Edit list of Favorite apps in Applications menu in Gnome Classic Centos7? I'm running a CentOS 7 + GNOME Classic (Gnome 3 for some unknown reason, crashes) and I'm trying to customize the "Favorites" sub-menu, under the main "Applications" menu.
Apparently I should use dconf or alternatively gsettings. I've tried the following but no response from the system.
$ dconf read /org/gnome/shell/favorite-apps
$

Here's the content of ~/.config/dconf/user file, which I have edited to suit my needs:
$ cat .config/dconf/user
# Set gedit, terminal and nautilus as default favorites
[org/gnome/shell]
favorite-apps = ['gedit.desktop', 'terminator.desktop', 'chromium-browser.desktop']
$

...and the /etc/dconf/profile/user file:
$ cat /etc/dconf/profile/user
user-db:user
system-db:local
system-db:site
system-db:distro
$

What am I missing here? Can someone please point me in the right direction?


text:
Q: logic behind implementation of ModelBinding in MVC3 I was having a problem with binding using the HTML extension to create text and hidden fields.  The value was being changed after I returned the view and I didn't know why.  After some reading, I learned that this is by design, and it's supposed to use whatever is inside the model state.
Can anyone explain the logic behind this? I don't see a good reason why you would want a supplied parameter to be replaced with what's in the model state.
Code
        @Html.Hidden("UpdateMode", "Update")

Result
       <input id="UpdateMode" name="UpdateMode" type="hidden" value="Add" />


text:
Q: Is there have way to add more than 10 phonenumbers in a contact on Windows Phone 8.1? I want to create a StoredContact with more than 10 phonenumbers, but I found this API doesn't have too much properties allow me do that, is there any other methods can implement this?

A: You can reference my last post at here:Can I link multiple contacts to one by programming on WP8.1?
Then you can create a linked contacts which it can have as many phonenumber as you want.


text:
Q: 2-dimensional array of chars returns SEGFAULT I'm beginner with C and I'm trying to create an array of strings saved like this:
[1][firststring]
[2][secondstring]
[2][thirdstring]
.
.
.
My implementation looks like:
int counter = 0;
char for_pole[50][50];
strcpy(for_pole[counter][50],"hello");
counter++;
//then i want to print it:
printf("my string: %s", for_pole[0][50]); //prints out first string
printf("my string: %s", for_pole[1][50]); //...and second one

but returns segmentation fault.
Should i use some dynamic allocation of memory?
As I've told I'm novice, so sorry for bad question.

A: I do not see where in your code there is the second string. I see only one string `"hello".
You can write for example the following way
int counter = 0;
char for_pole[50][50];
strcpy(for_pole[counter],"hello");
counter++;
strcpy(for_pole[counter],"world");

//then i want to print it:
printf("my string: %s\n", for_pole[0]); //prints out first string
printf("my string: %s\n", for_pole[1]); //...and second one

As for this expression
for_pole[counter][50]

then 1) index 50 is outside the array because the valid range of indices is 0 - 49 and 2) it has type char instead of to be an array or a pointer to char that is required by function strcpy or by the format specifier %s. of function printf.

A: When you write
strcpy(for_pole[counter][50],"hello");

You're writing the string "hello" to a char. Moreover, it is on the position 50 of an array that goes from 0 to 49.
you should change it to
strcpy(for_pole[counter],"hello");

because "for_pole[i]" is the i-th string and "for_pole[i][j]" is the j-th character of that string.
Similarly that printf should be
printf("my string: %s", for_pole[0]);

I would add a '\n' to get things a little bit more organized
Finally, the code would be like this
int counter = 0;
char for_pole[50][50];
strcpy(for_pole[counter],"hello");
counter++;

printf("my string: %s\n", for_pole[0]); //prints out first string
printf("my string: %s\n", for_pole[1]); //prints out second string

A: initialize for_pole variable with zero.
char for_pole[50][50] = {0,};

A: Jon.e, there are some reasons for SEGFAULT.
Even when there is no bug at all, but rather there are a lack of memory.
Some guys tell you, to pay attention to compiler message and warning, yes, but that's just a part of story.
Related to SEGFAULT there are the following most notable kinds of SEGFAULTS, that I can tell you by my own experience:
1.   You are trying to access to indices which do not exist.
Array has the size, exactly same size which you have specified while declaring an array.
Review this code:
/* "Array out of bounds" error
       valid indices for array foo
       are 0, 1, ... 999 */
  int foo[1000];
  for (int i = 0; i <= 1000 ; i++)
    foo[i] = i;

Here we have one illegal access to an index which does not exist.
2.  You are trying to access to the value which does not exist.
In this case memory exists but the value...
/* Illegal memory access if value of n is
       not in the range 0, 1, ... 999 */
  int n;
  int foo[1000];
  for (int i = 0; i < n ; i++)
    foo[i] = i;

This is also one of the most common pitfalls.
This pitfall is so fundamental, even experienced developers sometime make such mistake. The problem is in uninitialized memory for variable n.
Initialization is process of putting value of the variable its first value, If you want, we can say that it's process of losing virginity of the variable.
There are very chaotic rule of when variable is initialized and when - not. To complex for remembering. Just always initialize variables.
3. You are trying to access to the memory via pointers.
And that pointer does not point anywhere. You are trying to read something from NOWHERE? It does not make sense, does it?
/* Illegal memory access because no memory
       is allocated for foo2 */
  float  *foo, *foo2;
  foo = (float*)malloc(1000);
  foo2[0] = 1.0;

What happens, if you forget to initialize variable( 2-nd ) or pointer (3-rd case). The answer is broad: from nothing to catastrophe.
Why so? Because memory is the something which has been used by a lot of applications, and it's shared between hundreds of thousands applications running on a computer. So when you create a variable it creates the segment in the memory for that variables, but does not clean that memory (to be precise, in some cases it has been nulled, in others - not) Just assume that is never cleared. So in such situations, no matter the problem caused by variable or by pointer (which is actually is a variable too, but that's another story), we say that, variable stores 'garbage'.
Note, it's not obvious, to find those kind of SEGFAULTS, sometimes it's almost impossible, so you must be ready for such situations, and should use debugger for example gdb, to eliminate the bug.
Also avoid such dummy errors, like. The practice with my students show that it's very very common error.
int n = 100;
int foo[n];

use instead
int foo[100]

or
const int n = 100;
int foo[n];

or
enum N { N = 100 };
int is[N];

Additional references:
Can a const variable be used to declare the size of an array in C?
https://kb.iu.edu/d/aqsj

A: You misunderstand...
...how strings and array indexing work together. A string is an array of characters. For example this is a string:
char some_string[20] = "Hello";

And this is how you print it:
printf("%s\n", some_string);

And this is how you use strcpy() with it:
strcpy(some_string, "Goodbye");

And this is how you access the i-th character in the string:
/* Not compilable by itself; just an example. */
some_string[i]

Notice how the only time you used [...] was in declaring it and accessing a specific character in the array of characters. However, that is for a single string.
For an array of strings, you declare it as a 2-dimensional array of characters, just as you've done with for_pole:
/* An array of 50 strings, all of which can store a maximum of 49
 * characters, plus a null termination character for each string.
 */
char for_pole[50][50];

To use strcpy() with the counter-th string:
strcpy(for_pole[counter], "hello");

And to print the first (0-th) string:
printf("my string: %s", for_pole[0]);

And to print the i-th character of the first string:
printf("string[%d]: %c", i, for_pole[0][i]);

Again, notice how I didn't use [50] every time here. If you have a string, you access it using its name and each character using string[i]. If you have an array of strings, you access the array using its name and each string using array[i] notation. To access the j-th character of the i-th string in the array:
/* Not compilable by itself; just an example. */
array[i][j]

Why your version segfaults
You don't need to use [50] in every expression the way you do. Notice the last expression array[i][j] to access a single character. Since a character is represented by an integer value, the compiler will then convert that integer to a pointer where necessary.
This means that doing something like strcpy(for_pole[counter][50],"hello"); will try to copy the string "hello" to whatever memory address the compiler thinks the character for_pole[counter][50] holds. For example, if the character is the letter A, represented by the integer 65 on my system, then the program would try to copy all 6 bytes of the string "hello" to memory address 65. My program doesn't have permission to write to that memory address, so it segfaults. And that's the problem you are experiencing.


text:
Q: Copy value of cell to another cell to record vehicle mileage I'm working on a spreadsheet to record vehicle mileage.  I'd like to manually enter starting mileage in F6 and ending Mileage in G6.  I'd like the value of G6 to then automatically be copied to F7 and I'd enter the ending mileage in G7- and so on.  The problem I have is dealing with weekends and holidays when 2 or 3 blank cells may occur. I've tried using something like =if(D9=""," ", G6), but this doesn't work.
I've also tried this function in VBA:  =IF(D9=""," ",LastNonBlankCell(G8:G39)) [D9 is a datefield] and only ended up with 0's.
Function LastNonBlankCell(Range As Excel.Range) As Variant

    Application.Volatile

    LastNonBlankCell = Range.End(xlDown).Value

End Function

A: Do you really need the blank rows for weekends or holidays? If not, set D8 to the formula =workday.intl(D7,1) then copy it down as far as needed. If you need to allow for holidays, see the Excel documentation for WORKDAY.INTL. The list of dates will now contain only workdays, so the ending mileage for one row can be copied down to the next with no special handling.
This makes weekends and holidays harder to see at a glance. That can be addressed using conditional formatting. Setup formatting for the range D8:D<whatever>, use the formula =D8>(D7+1), and set the formatting to whatever stands out for you.

A: The following VBA macro will achieve your end goal in a slightly different way than what you asked about.
After you have installed the macro, when you double-click on a cell in column G, the macro will copy the last entered ending mileage to the cell to the left in column F.
For example, if the last ending mileage entry was in cell G6 and you double-click in cell G9, that entry will be copied to cell F9. You can then enter the new ending mileage in cell G9.
  Private Sub WorkSheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

     If Not Application.Intersect(Target, Range("G:G")) Is Nothing Then
        Selection.Offset(0, -1).Value = Selection.End(xlUp).Value
     Else
        Exit Sub
     End If

  End Sub

To install the macro, right-click on the worksheet's name tab, select "View Code", and paste in the macro code. It won't work if you put the code into a regular module.