text:
Q: Linked list and pointers I'm trying to pass to a pointer my address of the linked list in main,pass it in a function to allocate memory to it and traverse to the next node while keeping the position of the next node without breaking head node.
typedef struct {
    int data;
    struct node_list *next;
}node_list;

typedef struct {
    struct node_list *head;
}list;

void insert_list(node_list **c, int num);

void main()
{
    int num;
    list *list_odd = (list*)calloc(1, sizeof(list));
    node_list *c = &list_odd->head;

    while (num != -1)
    {
        if (num % 2)
            insert_list(c, num);
    }
}

void insert_list(node_list **c, int num)
{
    if (*c == NULL)
    {
        *c = (node_list*)malloc(sizeof(node_list)); // it allocates the memory in the right place.
        (*c)->data = num;
        (*c) = (*c)->next; // but this step breaks the starting list pointer
    }
    else
    {
        (*c)->next = (node_list*)malloc(sizeof(node_list));
        (*c)->data = num;
        (*c) = (*c)->next;
    }
}

Edit: I may not explained myself, To clarify: If my list points to the start of the linked-list, while I allocate memory to it and then do (*c) = (*c)->next, my head no longer points to the begging. What I'm trying to achieve is having the start of the list and saving the position of the next node.

A: I'd like to suggest a two-sided singly linked list.
Here is a demonstrative program.
#include <stdlib.h>
#include <stdio.h>

typedef struct node
{
    int data;
    struct node *next;
} node;

typedef struct list
{
    node *head;
    node *tail;
} list;

int push_back( list *lst, int data )
{
    node *new_node = malloc( sizeof( node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->data = data;
        new_node->next = NULL;

        if ( lst->tail == NULL )
        {
            lst->tail = lst->head = new_node;
        }
        else
        {
            lst->tail = lst->tail->next = new_node;
        }
    }

     return success;
 }

void display( list *lst )
{
    for ( node *current = lst->head; current != NULL; current = current->next )
    {
        printf( "%d ", current->data );
    }
    printf( "\n" );
}

int main( void )
{
    list lst = { NULL, NULL };

    int data;

    while ( scanf( "%d", &data ) == 1 && data != -1 )
    {
        if ( data % 2 != 0 ) push_back( &lst, data );
    }

    display( &lst );

    return 0;
}

If to enter this sequence of numbers
0 1 2 3 4 5 6 7 8 9 -1

then the output will be
1 3 5 7 9

The complexity of adding a new node to the end of the list is O(1).

A:
What I'm trying to achieve is having the start of the list and saving the position of the next node.

I'm not entirely sure what you're trying to do, so I've made an equivalent program. If you find this way of adding to the list to be too slow, then the program needs to be changed to either keep a {head, tail} pair or add items to the front of the list. From your text it sounds like you're trying to keep the head the same -- so a {head,tail} pair is probably best.
#include <stdlib.h>  //added
#include <stdio.h>  //added
#include <assert.h>

typedef struct node_list_t {   //changed
    int data;
    struct node_list_t *next;   //changed
} node_list;

typedef struct list_t { //gave the struct a tag
    node_list *head;    //use the typedef name, not the struct name
}list;

void insert_list(list *my_list, int num);

void main()
{
    int num = 0; // initialised
    list my_list = {0}; // changed to be on stack. Could be calloc'd if you like
    node_list* printer;

    while (num != 50) //changed limit
    {
        if (num % 2)
        {
            // we're just passing in the list
            insert_list(&my_list, num);
        }

        num += 1;  //actually incrementing number. :)
    }

    for (printer = my_list.head;
            printer;
                printer = printer->next)
    {
        printf("%d\n", printer->data);
    }
}

void insert_list(list *my_list, int num)
{
    node_list *c = (node_list*) calloc(1, sizeof(node_list));
    c->data = num;

    assert(!c->next);

    if (!my_list->head)
    {
        // if the head is not initialised, then make C the head
        my_list->head = c;
    }
    else
    {
        // otherwise stick it on the end of the list.
        node_list *p;
        for (p = my_list->head;
                p->next;
                    p = p->next)
        {
            //do nothing
        }
        p->next = c;
    }
}


text:
Q: Upgrading does not work due to unmet dependancies bash: /home/pjotrs/.rvm/scripts/rvm: No such file or directory
bash: /home/pjotrs/.rvm/scripts/rvm: No such file or directory

E: Could not get lock /var/lib/dpkg/lock - open (11: Resource temporarily unavailable)
E: Unable to lock the administration directory (/var/lib/dpkg/), is another process using it?
pjotrs@pjotrs-desktop:~$ sudo lsof /var/lib/dpkg/lock
lsof: WARNING: can't stat() fuse.gvfs-fuse-daemon file system /home/pjotrs/.gvfs
      Output information may be incomplete.
COMMAND    PID USER   FD   TYPE DEVICE SIZE/OFF     NODE NAME
update-ma 3440 root   56uW  REG    8,1        0 14942841 /var/lib/dpkg/lock
pjotrs@pjotrs-desktop:~$ sudo kill -TERM 3440
pjotrs@pjotrs-desktop:~$ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 libc-l10n : Breaks: locales (< 2.21-1) but 2.13+git20120306-3 is installed
E: Unmet dependencies. Try using -f.

I am trying to install an upgrade. However it keeps coming up with the error above. How can I solve this?

A: Well since I cannot comment, first upload your sources.list file. And for the time do this:

$ sudo apt-get clean
$ sudo apt-get update
$ sudo apt-get upgrade

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL returning full objects (*) from distincted columns I am looking for a solution concerning SQL Query for Oracle DB what returns DISTINCT full objects from many columns e.g:
SELECT DISTINCT mt.column1, mt.column2, mt.column3 FROM MyTable mt;

But I need full objects like SELECT * FROM MyTable
Is there any way to obtain such effect using usual SQL statements?
Thanks in advance! :)

A: I think you are looking for a query like this:
SELECT *
FROM (
    SELECT
        *, ROW_NUMBER() OVER (PARTITION BY mt.column1, mt.column2, mt.column3 ORDER BY mt.column1, mt.column2, mt.column3) As Seq
    FROM
        MyTable mt) AS DT
WHERE
    Seq = 1;


text:
Q: Move Files from Azure Files to ADLS Gen 2 and Back using Databricks I have a Databricks process which currently generate a bunch of text files which gets stored in Azure Files. These files need to be moved to ADLS Gen 2 on a scheduled basis and back to File Share.
How this can be achieved using Databricks?

A: Installing the azure-storage package and using the Azure Files SDK for Python on Azure Databricks is the only way to access files in Azure Files.
Install Library: file-share azure-storage https://pypi.org/project/azure-storage-file-share/
Note : Pip install only instals the package on the driver node, thus pandas must be loaded first. The library must be deployed as a Databricks Library before it can be used by Spark worker nodes.
Python - Load file from Azure Files to Azure Databricks - Stack Overflow
Alternative could be copying the data from Azure File Storage to ADLS2 via Azure DataFactory using Copy activity : Copy data from/to Azure File Storage - Azure Data Factory & Azure Synapse | Microsoft Docs


text:
Q: Heroku imagemagick brightness parameter when I am trying to change brightness of image (paperclip post processing) at heroku via imagemagick with following code:
command = "#{File.expand_path(@file.path)} -resize x300^ -brightness-contrast +50 -gravity Center -crop 300x300+0+0 -colorspace Gray #{File.expand_path(dst.path)}"

I have following error:
convert: unrecognized option `-brightness' @ error/convert.c/ConvertImageCommand/844.

How can I change brightness of image?


text:
Q: Take a hash out of its braces Given bar = {c: 3, d: 4}, how can you use bar to let a code in this format:
foo(a: 1, b: 2, some_code_here)

express the following?
foo(a: 1, b: 2, c: 3, d: 4)

You can splat an array:
a = [1, 2, 3]
[*a, 4] # => [1, 2, 3, 4]

How do you do this with a hash? I tried this:
a = {i: 1, j: 2, k: 3}
{*a, l: 4} # => error

A: Use double splat (**):
a = {i: 1, j: 2, k: 3}
{**a, l: 4} # => {i: 1, j: 2, k: 3, l: 4}

Ruby devs: why not use the unused regular splat?

A: a = {i: 1, j: 2, k: 3}
a.merge(l: 4) #=> {:i=>1, :j=>2, :k=>3, :l=>4}


text:
Q: proof following Bessel's inequality and Fourier series Letting $a_n$ denote the coefficients in the Fourier cosine series of any function $f(x)$ on
$(0,\pi)$ , how can I show that:
$\sum_{n=1}^N c_n^2 \le ||f∥^2$,  where $c_n$ are the Fourier constants of $f(x)$ that:
$ a_0^2   \over 2  $+ $ \sum_{n=1}^Na_n^2 \le $ $ 2\over π $ $\int_{0}^{π}(f(x))^2\,dx $,  $N = 1,2,3,4\dots$
now that looks better :)

A: But...this is only part of Bessel's inequality, isn't it? I mean, we have the (complete) orthonormal trigonometric system (basis) $\;\{u_n\}_{n\in\Bbb N}\;,\;\;u_n=\{1,\sin x,\cos x, \sin 2x,\cos2x,\ldots\}\;$ with which we work in Fourier series, so then denoting by $\;\langle,\rangle\;$ the usual inner product we get
$$\sum_{n=1}^\infty \langle f(x),u_n\rangle^2\le||f||^2$$
But using the usual notation from Fourier series the above is just
$$||f||^2\ge\sum_{n=1}^\infty c_n^2 $$


text:
Q: Rpy2 and --max-ppsize I'm running some recursive code in R through Rpy2 (has to be that way, unfortunately). I've had to increase options(expressions) but haven't found a way to increase the pointer protection stack. I've looked through the rpy2 code, and can't find an obvious place to set the flag for this. Is it even possible?
The errors I'm getting are:
protect(): protection stack overflow.

I have looked at https://stat.ethz.ch/pipermail/r-help/2006-August/111127.html
Thanks for helping!

A: Found it buried in the rst files in the source code, but has to be done as initial import
import rpy2.rinterface as rinterface
rinterface.set_initoptions((...))


text:
Q: asp.net in IronPython, speed execution of code, first time vs second time differences I'm observing this behavior, when I run the same code for the second time with different parameters in webforms with IronPython,
it runs quite faster. I thought first this had to do with asp.net temporary files, but when I restart the server it gets slow for the first time
again. It's quite a code it has to run so it's reasonable, but it would be great if I could get the speed of the second exeucution. Now cPython compiled the files into pycs files for them to run faster, and I was wondering what does IronPython do to run faster
the code for the second time
is there anything I can do for the code to run at the speed execution of the second time, after I restart the server?
Greetings, Pablo

A: I do not do a lot of work with .NET or IronPython, so this might be widely off the mark, but why not just precompile your files using the aspnet_compiler.exe before you redeploy?


text:
Q: Is there a way to pull data from a rest api endpoint with filter parameters in Fluentd I'm trying to retrieve audit log data from a rest api endpoint with filter parameters like created_before and created_after using fluentd http pull plugin. I need to dynamically pass the  current timestamp and last polled timestamp as query parameters in the rest api as value to the "url" key within the source plugin in fluentd.conf file. Is there ways to do this?
<source>
  @type http_pull
  url "https://example.com/api/v4/groups/audit_events?pagination=keyset&per_page=100&order_by=created_at&sort=asc&created_after=2021-05-11T22:18:29Z&created_before=2021-05-21T14:43:00Z&rel=next"
  interval 1s
</source>


text:
Q: Can't call a method from a swift class in Objective C I'm working on an iOS application written in Objective C that has an attached class written in Swift. When I try to call a in my Obj C AppDelegate.m, I don't get any errors, but the reply callback never fires.
My ObjC has the following methods:
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {

    NSString *success =[ApiController handleCall];
    //NSString *success =[self hello]; // This works if you swap it with the above method
    //NSString *success = @"hello";    // when uncommented this also works.

    NSDictionary *dict = @{@"status" : success};

    reply(dict);
}

-(NSString *)hello{
    return @"hello";
}

NSString *success = [SwiftClass swiftMethod];
My swift class looks like this:
@objc class SwiftClass {
    @objc func swiftMethod()->NSString{
        return "it works!"
    }
}

In addition to the above code, I've made sure to include #import "ProjectName-Swift.h", as well as create a bridging header for the swift code.
Am I missing anything?

A: The swiftMethod is an instance method not a class method. You can call it like this:
NSString *success = [[SwiftClass new] swiftMethod];

If you want to call it as class method then you need to declare it with class:
@objc class SwiftClass {
    @objc class func swiftMethod()->NSString{
        return "it works!"
    }
}

A: Also you have to add @objc before class and method
@objc class MyClass: NSObjec {
   @objc func methodName() {
   }
}


text:
Q: Is there any way to map Weka j48 decision tree output to RDF format? I want to create an ontology using Jena based on Weka j48 decision tree output. But this output needs to be mapped to RDF format before inputting it to Jena. Is there any way to do this mapping ?
EDIT1:
Sample part of j48 decision tree output before mapping:

Sample part of RDF corresponding to decision tree output:

These 2 screens are from this research paper (slide 4):
Efficient Spam Email Filtering using Adaptive Ontology

A: There is likely no built-in way to do that.
Disclaimer: I have never worked with Jena and RDF before. So this answer may be incomplete or miss the point of the intended conversion.
But nevertheless, and first of all, a short rant:

<rant>

The snippets that are published in the paper (namely, the output of the Weka classifier and the RDF) are incomplete and obviously inconsistent. The process of the conversion is not described at all. Instead, they only mentioned:

The  challenge  we  faced  was  mainly  to  make  J48  classification  outputs  to  RDF  and  gave  it  to  Jena

(sic!)

Now, they solved it somehow. They could have provided their conversion code on a public, open-source repository. This would allow others to provide improvements, it would increase the visibility and verifiability of their approach. But instead, they wasted their time and the time of the readers with screenshots of various websites that serve as page-fillers in a pitiful attempt to squeeze yet another publication out of their approach.

</rant>

The following is my best-effort approach to provide some of the building blocks that may be necessary for the conversion. It has to be taken with a grain of salt, because I'm not familiar with the underlying methods and libraries. But I hope that it can be considered as "helpful" nevertheless.
The Weka Classifier implementations usually do not provide the structures that they are using for their internal workings. So it is not possible to access the internal tree structure directly. However, there is a method prefix() that returns a string representation of the tree.
The code below contains a very pragmatic (and thus, somewhat brittle...) method that parses this string and builds a tree structure that contains the relevant information. This structure consists of TreeNode objects:
static class TreeNode
{
    String label;
    String attribute;
    String relation;
    String value;
    ...
}

*

*The label is the class label that was used for the classifier. This is only non-null for leaf nodes. For the example from the paper, this would be "0" or "1", indicating whether an email is spam or not.

*The attribute is the attribute that a decision is based on. For the example from the paper, such an attribute may be word_freq_remove

*The relation and value are the strings representing the decision criteria. These may be "<=" and "0.08" for example.
After such a tree structure has been created, it can be converted into an Apache Jena Model instance. The code contains such a conversion method, but due to my lack of familiarity with RDF, I'm not sure whether it makes sense conceptually. Adjustments may be necessary in order to create the "desired" RDF structure out of this tree structure. But naively, the output looks like it could make sense.
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.Statement;

import weka.classifiers.trees.J48;
import weka.core.Instances;
import weka.core.converters.ArffLoader;

public class WekaClassifierToRdf
{
    public static void main(String[] args) throws Exception
    {
        String fileName = "./data/iris.arff";
        ArffLoader arffLoader = new ArffLoader();
        arffLoader.setSource(new FileInputStream(fileName));
        Instances instances = arffLoader.getDataSet();
        instances.setClassIndex(4);
        //System.out.println(instances);

        J48 classifier = new J48();
        classifier.buildClassifier(instances);

        System.out.println(classifier);

        String prefixTreeString = classifier.prefix();
        TreeNode node = processPrefixTreeString(prefixTreeString);

        System.out.println("Tree:");
        System.out.println(node.createString());

        Model model = createModel(node);

        System.out.println("Model:");
        model.write(System.out, "RDF/XML-ABBREV");
    }

    private static TreeNode processPrefixTreeString(String inputString)
    {
        String string = inputString.replaceAll("\\n", "");

        //System.out.println("Input is " + string);

        int open = string.indexOf("[");
        int close = string.lastIndexOf("]");
        String part = string.substring(open + 1, close);

        //System.out.println("Part " + part);

        int colon = part.indexOf(":");
        if (colon == -1)
        {
            TreeNode node = new TreeNode();

            int openAfterLabel = part.lastIndexOf("(");
            String label = part.substring(0, openAfterLabel).trim();
            node.label = label;
            return node;
        }

        String attributeName = part.substring(0, colon);

        //System.out.println("attributeName " + attributeName);

        int comma = part.indexOf(",", colon);

        int leftOpen = part.indexOf("[", comma);

        String leftCondition = part.substring(colon + 1, comma).trim();
        String rightCondition = part.substring(comma + 1, leftOpen).trim();

        int leftSpace = leftCondition.indexOf(" ");
        String leftRelation = leftCondition.substring(0, leftSpace).trim();
        String leftValue = leftCondition.substring(leftSpace + 1).trim();

        int rightSpace = rightCondition.indexOf(" ");
        String rightRelation = rightCondition.substring(0, rightSpace).trim();
        String rightValue = rightCondition.substring(rightSpace + 1).trim();

        //System.out.println("leftCondition " + leftCondition);
        //System.out.println("rightCondition " + rightCondition);

        int leftClose = findClosing(part, leftOpen + 1);
        String left = part.substring(leftOpen, leftClose + 1);

        //System.out.println("left " + left);

        int rightOpen = part.indexOf("[", leftClose);
        int rightClose = findClosing(part, rightOpen + 1);
        String right = part.substring(rightOpen, rightClose + 1);

        //System.out.println("right " + right);

        TreeNode leftNode = processPrefixTreeString(left);
        leftNode.relation = leftRelation;
        leftNode.value = leftValue;

        TreeNode rightNode = processPrefixTreeString(right);
        rightNode.relation = rightRelation;
        rightNode.value = rightValue;

        TreeNode result = new TreeNode();
        result.attribute = attributeName;
        result.children.add(leftNode);
        result.children.add(rightNode);
        return result;

    }

    private static int findClosing(String string, int startIndex)
    {
        int stack = 0;
        for (int i=startIndex; i<string.length(); i++)
        {
            char c = string.charAt(i);
            if (c == '[')
            {
                stack++;
            }
            if (c == ']')
            {
                if (stack == 0)
                {
                    return i;
                }
                stack--;
            }
        }
        return -1;
    }

    static class TreeNode
    {
        String label;
        String attribute;
        String relation;
        String value;
        List<TreeNode> children = new ArrayList<TreeNode>();

        String createString()
        {
            StringBuilder sb = new StringBuilder();
            createString("", sb);
            return sb.toString();
        }

        private void createString(String indent, StringBuilder sb)
        {
            if (children.isEmpty())
            {
                sb.append(indent + label);
            }
            sb.append("\n");
            for (TreeNode child : children)
            {
                sb.append(indent + "if " + attribute + " " + child.relation
                    + " " + child.value + ": ");
                child.createString(indent + "  ", sb);
            }
        }

        @Override
        public String toString()
        {
            return "TreeNode [label=" + label + ", attribute=" + attribute
                + ", relation=" + relation + ", value=" + value + "]";
        }
    }

    private static String createPropertyString(TreeNode node)
    {
        if ("<".equals(node.relation))
        {
            return "lt_" + node.value;
        }
        if ("<=".equals(node.relation))
        {
            return "lte_" + node.value;
        }
        if (">".equals(node.relation))
        {
            return "gt_" + node.value;
        }
        if (">=".equals(node.relation))
        {
            return "gte_" + node.value;
        }
        System.err.println("Unknown relation: " + node.relation);
        return "UNKNOWN";
    }

    static Model createModel(TreeNode node)
    {
        Model model = ModelFactory.createDefaultModel();

        String baseUri = "http://www.example.com/example#";
        model.createResource(baseUri);
        model.setNsPrefix("base", baseUri);
        populateModel(model, baseUri, node, node.attribute);
        return model;
    }

    private static void populateModel(Model model, String baseUri,
        TreeNode node, String resourceName)
    {
        //System.out.println("Populate with " + resourceName);

        for (TreeNode child : node.children)
        {
            if (child.label != null)
            {
                Resource resource =
                    model.createResource(baseUri + resourceName);
                String propertyString = createPropertyString(child);
                Property property =
                    model.createProperty(baseUri, propertyString);
                Statement statement = model.createLiteralStatement(resource,
                    property, child.label);
                model.add(statement);
            }
            else
            {
                Resource resource =
                    model.createResource(baseUri + resourceName);
                String propertyString = createPropertyString(child);
                Property property =
                    model.createProperty(baseUri, propertyString);

                String nextResourceName = resourceName + "_" + child.attribute;
                Resource childResource =
                    model.createResource(baseUri + nextResourceName);
                Statement statement =
                    model.createStatement(resource, property, childResource);
                model.add(statement);
            }
        }
        for (TreeNode child : node.children)
        {
            String nextResourceName = resourceName + "_" + child.attribute;
            populateModel(model, baseUri, child, nextResourceName);
        }
    }

}

The program parses the famous Iris dataset from an ARFF file, runs the J48 classifier, builds the tree structure and generates and prints the RDF model. The output is shown here:
The classifier, as it is printed by Weka:
J48 pruned tree
------------------

petalwidth <= 0.6: Iris-setosa (50.0)
petalwidth > 0.6
|   petalwidth <= 1.7
|   |   petallength <= 4.9: Iris-versicolor (48.0/1.0)
|   |   petallength > 4.9
|   |   |   petalwidth <= 1.5: Iris-virginica (3.0)
|   |   |   petalwidth > 1.5: Iris-versicolor (3.0/1.0)
|   petalwidth > 1.7: Iris-virginica (46.0/1.0)

Number of Leaves  :     5

Size of the tree :     9

A string representation of the tree structure that is built internally:
Tree:

if petalwidth <= 0.6:   Iris-setosa
if petalwidth > 0.6:
  if petalwidth <= 1.7:
    if petallength <= 4.9:       Iris-versicolor
    if petallength > 4.9:
      if petalwidth <= 1.5:         Iris-virginica
      if petalwidth > 1.5:         Iris-versicolor
  if petalwidth > 1.7:     Iris-virginica

The resulting RDF model:
Model:
<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:base="http://www.example.com/example#">
  <rdf:Description rdf:about="http://www.example.com/example#petalwidth">
    <base:gt_0.6>
      <rdf:Description rdf:about="http://www.example.com/example#petalwidth_petalwidth">
        <base:gt_1.7>Iris-virginica</base:gt_1.7>
        <base:lte_1.7>
          <rdf:Description rdf:about="http://www.example.com/example#petalwidth_petalwidth_petallength">
            <base:gt_4.9>
              <rdf:Description rdf:about="http://www.example.com/example#petalwidth_petalwidth_petallength_petalwidth">
                <base:gt_1.5>Iris-versicolor</base:gt_1.5>
                <base:lte_1.5>Iris-virginica</base:lte_1.5>
              </rdf:Description>
            </base:gt_4.9>
            <base:lte_4.9>Iris-versicolor</base:lte_4.9>
          </rdf:Description>
        </base:lte_1.7>
      </rdf:Description>
    </base:gt_0.6>
    <base:lte_0.6>Iris-setosa</base:lte_0.6>
  </rdf:Description>
</rdf:RDF>


text:
Q: Is there any way to fetch the IMEI Number of the Windows Phone device Using C# Is there any way to fetch the IMEI Number of the Windows Phone device Using C#

*

*windows-phone-8.1

*uwp

*xamarin.uwp

*c#

*visual-studio-2015

A: This looks like what you're looking for...
[assembly: Xamarin.Forms.Dependency(typeof(UniqueIdWinPhone))]
namespace UniqueId.WinPhone
{
    public class UniqueIdWinPhone : IDevice
    {
        public string GetIdentifier()
        {
            byte[] myDeviceId = (byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");
            return Convert.ToBase64String(myDeviceId);
        }
    }
}

This requires the permission ID_CAP_IDENTITY_DEVICE.


text:
Q: Find the volume - using substitution Find the volume of $\omega=\{(x,y,z) | x^2+y^2+z^2\leq a^2 , x^2+y^2\leq ax\}$
$x^2+y^2+z^2\leq a^2 \implies x^2+y^2\leq a^2-z^2$.
Therefore , $a^2-z^2 \leq ax \implies a^2-ax\leq z^2$.
Using substitution $x=a\sin\theta \cos\phi, y=a\sin\theta \sin\phi, z=a\cos\theta,  a>0,0\leq \theta\leq \pi ,0\leq \phi\leq 2\pi$.
$a^2-ax\leq z^2 \implies a^2-a(a\sin\theta \cos\phi)\leq a^2\cos^2\theta \implies 1-\sin\theta\cos\phi\leq \cos^2\theta$.
I don't know how to solve this problem and find the limits of the integral , any help please.


text:
Q: Map Size not updating on map.updateSize() I am Using Open layers to publish a Map. But I can't figure out the way to Make the map size dynamic according to Screen Size. As the map remains same on every screen irrespective of the screen size. I also tried map.updatesize(). But that is not working too.
My Code is
        layer = new ol.layer.Tile({
        title: 'Basemap',
        baseLayer: true,
        visible: true,

        source: new ol.source.TileWMS({
            url: 'http://mlinfomaps.in/geoserver/wms',
            params: { 'LAYERS': 'MSSDS_WS:MSSDS_BASEMAP', 'TILED': true },
            serverType: 'geoserver',

            // Countries have transparency, so do not fade tiles:
            transition: 0,
            crossOrigin: "anonymous"
        })
    });

    var mousePositionControl = new ol.control.MousePosition({
        coordinateFormat: ol.coordinate.createStringXY(4),
        projection: 'EPSG:4326',
        // comment the following two lines to have the mouse position
        // be placed within the map.
        //className: 'custom-mouse-position',
        target: document.getElementById('mouse-position'),
        //undefinedHTML: ' '
    });

    var projection = new ol.proj.Projection({
        //code: 'EPSG: 4326', // *code says: 5261 ...try to see if this is right
        //extent: [71.6142, 22.3645, 81.8754, 15.1508],
        extent:[7970828.0670139585, 1681517.1260521673, 9127778.927138386, 2541280.8202038296]
    })
    function scaleControl() {
        control = new ol.control.ScaleLine({
            units: 'metric',
            bar: true,
            steps: 4,
            text: true,

            minWidth: 100
        });
        return control;
    }

    var sourceMeasure = new ol.source.Vector({
        crossOrigin: "anonymous",

    });
    var vectorMeasure = new ol.layer.Vector({

        source: sourceMeasure,
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: 'rgba(255, 255, 255, 0.2)'
            }),
            stroke: new ol.style.Stroke({
                color: '#df1c29',
                width: 2
            }),
            image: new ol.style.Circle({
                radius: 6,
                fill: new ol.style.Fill({
                    color: '#df1c29'
                })
            })
        }),
        title: 'Measure Overlay',
    });

    // The Map
    //var overlay = new ol.Overlay
    //    ({
    //        element: container,
    //        autoPan: true,
    //        autoPanAnimation: {
    //            duration: 250
    //        }
    //    });

    var view = new ol.View
        ({
            center: ol.proj.transform([76.7997, 18.6298], 'EPSG:4326','EPSG:3857'),
            zoom: 7,
            extent: projection.getExtent(),
            //minZoom:7,
            maxZoom: 12

        });

    var map = new ol.Map
        ({
            target: 'map',
            controls: ol.control.defaults().extend([mousePositionControl, scaleControl()]),
            view: view,
            //fit: view.fit(),
            //overlays: [overlay],
            layers: [layer]

        });
    const extent = projection.getExtent()
    map.getView().fit(extent);
    map.updateSize();

    window.onresize = function()
        {
    setTimeout( function() { map.updateSize();}, 200);
        }

    '''

The map on different screen looks like this:
On my screen It looks like
https://i.stack.imgur.com/KIYio.png
On my colleague's screen it looks like
https://i.stack.imgur.com/6c4zk.png
Please Help me get through this.
Thanks In Advance!

A: hello i have the same problem and I solove it by doing that
ts:

html :


text:
Q: Batch operation not following order I've written a function using pnp-js-core to batch checkout, update and checkin selected items.
Problem I'm seeing however is that it seems that by the time the first map is called the next one proceeds but the result from the return hasn't finished so there isn't anything in the fileRefs=[]?
// Update files
function exclude(isTrue) {
  // Get selected files from list
  var selectedItems = SP.ListOperation.Selection.getSelectedItems().map(x => x.id)
  var myFieldValue = isTrue ? "true" : "false";
  var batch = $pnp.sp.createBatch(); // Create batch object
  var fileRefs = []; // Store selected files reference
  var documentLibrary = $pnp.sp.web.lists.getByTitle("Documents"); // Get document library

  // Get fileRef from selected items
  selectedItems.map(function(item) {
    documentLibrary
      .items
      .getById(item)
      .select("FileRef")
      .inBatch(batch)
      .get()
      .then(x => fileRefs.push(x.FileRef))
  })

  // Check out selected files
  fileRefs.map(function(fileRef) {
    $pnp.sp.web.getFileByServerRelativeUrl(fileRef)
    .inBatch(batch)
    .checkout()
      .then(() => {
          console.log("File checked out:", fileRef);
      });
  })

  // Update file property
  selectedItems.map(function(itemID) {
    documentLibrary
      .items
      .getById(itemID)
      .inBatch(batch)
      .update({
        ccaGrantExcludeFromPAC: myFieldValue
      })
  })

  // Check in file
  fileRefs.map(function(fileRef) {
    $pnp.sp.web.getFileByServerRelativeUrl(fileRef)
    .inBatch(batch)
      .checkin()
        .then(() => {
          console.log("File checked in!");
        });
  })

  // Execute batch?
  batch.execute().then(
    () => console.log("Files have been updated successfully") );
}

A: You can manage asynchronous call of jquery using deferred. It manage the asynchronous call to execute in synchronous way.
function wait(ms) {
      var deferred = $.Deferred();
      setTimeout(deferred.resolve, ms);

     // We just need to return the promise not the whole deferred.
     return deferred.promise();
  }

  // Use it
  wait(1500).then(function () {
      // Call you another function
      wait(1000).then(function () {
           // Do something or call your function
      });
  });


text:
Q: Did Not and Would not Difference Which Sentence construction is correct ? Why ?
Also, what is the exact meaning using did not and would not ?
A ) He did not want the young man's future to be spoilt and only wanted to ensure that he didn't repeat his conduct.
B ) He did not want the young man's future to be spoilt and only wanted to ensure that he won't repeat his conduct.
According to me sentences B is correct because it ensure  the stalker' s future action of not to repeat the misconduct . But in actual article it used didn't.
https://timesofindia.indiatimes.com/city/mumbai/stalking-ca-aspirant-spared-jail-over-his-age-future/articleshow/64361157.cms

A: Let's see if I can contribute to this thread. In terms of construction there's no mistake, none of the sentences are incorrect, again, taking about construction. However, if we take into account the function of the sentence or what I want to express, then sentence B is not correct for the suitable tense to use is WOULD. Is that what you want to know? Else, we can express past situations using WOULD except if we talk about states. For instance:
We would go to the movies every now and then. ✓
They would talk for hours. ✓
They would live in Sidney. X

A: B is wrong, as others have commented: backshift says it has to be wouldn't.
But B corrected, and A are both not only grammatical, but idiomatic.
When corrected, they have didn't and wouldn't. If you take out the back-shift from reported speech, they become doesn't and won't. Either will do, because either can be used to express the future.


text:
Q: Direct uploads with active storage mirror service According to: https://github.com/rails/rails/pull/36312, the mirroring service should be delegating the methods required for direct_uploads to the primary, however, I looked in the master branch for rails (I'm running 6.0.1) and could not find that commit. Did it get removed in favor of something else? The error I get is when active_storage tries to invoke the url_for_direct_upload method on the mirror service and it is undefined.

A: You can see the last commit date for that file for version 6.0.1 is 2019/02/14. https://github.com/rails/rails/blob/v6.0.1/activestorage/lib/active_storage/service/mirror_service.rb
That pull request you linked is from May 22, I guess that file is freezed and maybe it will be included on later rails versions. (It's still not updated for tags 6.0.2rc nor branch 6.0.2).
So, I don't think it was removed, it looks like it's not part of the code of any release yet.


text:
Q: Estimated vs Actual Number of Rows I have 5 tables that contain data split by quarter each table has a similar structure to the following:
ID_Column bigint PK,
EventType int,
DateStamp datetime PK
CustomerId int,
ARG_1 nvarchar(32),
ARG_2 nvarchar(32)

There is also a CHECK constraint on each table to ensure that the DateStamp is within the specified quarter.  I have then created a View across these tables which I am querying against.
I need to execute several queries which aggregate the date by week, month, 3 months and 12 months.  When I look at the Query Plan for my query it is querying all tables regardless of the filter on the DateStamp column.
I have a controller Stored Proc which in turns calls a Processing stored procedure. The processing stored procedure accepts the start and date as parameters, assigns them to local variables within the procedure and runs the query.
The query is similar to the following:
Select v.ARG_1,
       t.SomeColumn,
       Count(Distinct(v.Customer_Id))

From  dbo.My_View v
Join  dbo.AnotherTable t on v.ARG_2 = v.PKColumn
Where v.DateStamp >= @StartDate
And   v.DateStamp <= @EndDate
And   v.EventType = 1
And   t.SomeColumn = 'A_VALUE'
GROUP BY v.ARG_1, t.SomeColummn

I have also noticed that the estimated row count is wildly inaccurate (Estimated rows: 13 million vs Actual rows : 170 million). This confuses me as the statistics are up to date and I have rebuilt the indexes.
The performance of the query is acceptable for my purposes but I am wondering what could be the reason for these oddities?
EDIT: I am running SQL Server 2012 Standard Edition.
The anonymized XML Query plan can be found here

A: Up to date statistics does not necessarily imply perfect estimation. If you try to represent a range of 170 million values with 200 samples, even a small skew can throw you off by a factor of 10.
Here is a hint: time series are almost always accessed by time. Very likely DateStamp should be clustered key. For more detailes, post the exact DDL and actual execution plan (XML, not picture).

A: Barry, Check out the statistics histograms on the indexes being used. This great book (free from RedGate) has a section on histograms: http://www.red-gate.com/products/sql-development/sql-prompt/entrypage/sql-query-optimizer-ebook2
You could have skewed data that is messing up the estimates. This has happened to me in the past: Poor query performance, though in my case it ended up being a parameter sniffing issue.
If you check the histogram and it doesn't look skewed, you will need to analyze the execution plan XML and see if you find cases where ParameterCompiledValue is not equal to ParameterRuntimeValue. The author of the book above has an article on this: http://www.benjaminnevarez.com/2010/06/the-parameter-sniffing-problem/
As was mentioned above as well, we would really need to see the full query and execution plan (and possibly more) to determine the issue. If you are willing to share all this information this question could end up being helpful to other people having similar issues.


text:
Q: Undefined method model_name_url in if there's no show I did a controller called api in which I have actions that return data. In the app I also have a Car model and a cars controller (with all the standard routes), but I want to move every URL that I use into the api controller and remove the URLs that I don't use from my app. In the case of the cars controller I only use the URLs in which the json of all the cars are returned or the json of a particular car is returned (i.e. something like index and show).
The problem I have is that when I use the json.jbuilder to render the list of cars I also want to print the URL of those resources (show), so for example if I have the endpoint /api/cars.json I use the following json.jbuilder.
views/api/cars.json.jbuilder
json.array!(@cars) do |car|
    json.extract! family_bond, :id, :name, :image, :description
    json.url car_url(car, format: :json)
end

But car_url throws an error if I delete resource: car from the routes file. This is obvious since car_urlshould return the show action URL of every car.
So my question is the following
If I create the action to show the details of a car in the api controller (for example, something like /api/car.json?id=1), how can I tell Rails to use this endpoint instead of the standard one (show) when I use the car_url` method?

A: I don't think there is a way to have the path and url helpers work without the route being specified in the routes, as when you use some other utility to route the URLs to the controllers.  However, if you get the routes.rb to specify how to route an URL to your API, it will work.
resource :car, controller: 'api'


text:
Q: php request forwarder which can forward request to some asp.net ashx handler Can I somehow build request forwarder type functionality in php.
Problem is that previously i have some .net ashx handler which works as callbackhandler. Different client send differnt type of request like some send post request some send json and some send simple request withinfo in querystring.
Now I want's to create a page which simple forward all the headers,querystring,form postelement, json to my ashx handler. is something like this possible


text:
Q: Two columns accordion with Bootstrap I'm using Bootstrap and in the design, we have a two col accordion section that can only have one active drop down state at time.
I'm running into an issue with maintaining the cols after clicking dropdown. The elements on the left keep shifting right under the expanded section.
Please, see the example: Bootply
CODE:

            TEST1

TESTTESTTESTTESTTEST

TEST 2

TESTTESTTESTTEST

TEST3

TESTTESTTESTTEST

TEST   4

TESTTESTTESTTEST

TEST  5

TESTTESTTESTTEST

TEST    6

TESTTESTTESTTEST

TEST  7

TESTTESTTESTTESTTESTTEST

TEST  8

TESTTESTTESTTESTTESTTEST

TEST  9

TESTTESTTESTTESTTESTTEST

TEST     10

TESTTESTTESTTESTTESTTEST

TEST  11

TESTTESTTESTTESTTESTTEST

TEST    12

TESTTESTTESTTESTTEST

Appreciate any help!

A: Rather than adding the col-sm-6 around each panel, group the two sides in their own divs and add the 'col-sm-6' to each group
example: http://www.bootply.com/vfbv3Cnn6v

                        TEST_1

                        TESTTESTTESTTESTTEST

                        TEST_2

                        TESTTESTTESTTESTTEST

                        TEST_3

                        TESTTESTTESTTESTTEST

                        TEST_4

                        TESTTESTTESTTESTTEST

                        TEST_5

                        TESTTESTTESTTESTTEST

                        TEST_6

                        TESTTESTTESTTESTTEST

                        TEST_7

                        TESTTESTTESTTESTTEST

                        TEST_8

                        TESTTESTTESTTESTTEST

                        TEST_9

                        TESTTESTTESTTESTTEST

                        TEST_10

                        TESTTESTTESTTESTTEST

                        TEST_11

                        TESTTESTTESTTESTTEST

                        TEST_12

                        TESTTESTTESTTESTTEST

Also i find when i have large groups of nested divs it is handy to add comments to show where the opening and closing of important areas are.
so to get the accordion to still respect the opening and closing the bootstrap docs says there is an event show.bs.collapse which is fired when showing a panel so use that to then hide which ever panel has the class in (this denotes the open panel)
$('#accordion').on('show.bs.collapse', function () {
    $('#accordion .in').collapse('hide');
});


text:
Q: Building a Eclipse project using ANT build scripts I am editing the question to make it more specific.
I want to run my application on some other machine which doesn't have an IDE like me.I want to deploy it on a container(Tomcat) on the other machine.  How can I make sure that the dependencies are maintained?
I have the jars in the lib folder,but about the other build targets I am not sure.
Also,I want to check in the project to SVN (So,that others can check out and deploy it ).

A: I achieved this,but not sure if in all the right way.The dynamic web project in eclipse creates its own directory structure for example WebContent->WEB-INF->web.xml and so on.But,when deploying on tomcat directly we need the WEB-INF in the root of the application.I had to make these changes and add a build.xml file to the root of the application for compiling my classes.The build was successful and I can run the app independently of eclipse.
Any comments would be helpful.


text:
Q: when installing bitnami mongodb-sharded, i got error from PVCs: no persistent volumes available for this claim and no storage class is set I am trying to install my rancher(RKE) kubernetes cluster bitnami/mongodb-shared . But I couldn't create a valid PV for this helm chart.
The error that I am getting:
no persistent volumes available for this claim and no storage class is set
This is the helm chart documentation section about PersistenceVolume: https://github.com/bitnami/charts/tree/master/bitnami/mongodb-sharded/#persistence
This is the StorageClass and PersistentVolume yamls that I created for this helm chart PVCs':
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: ssd-nfs-storage
provisioner: nope
parameters:
  archiveOnDelete: "false"
----------
apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
  labels:
    name: db-nfs
spec:
  storageClassName: ssd-nfs-storage # same storage class as pvc
  capacity:
    storage: 100Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    server: 142.251.33.78 # ip addres of nfs server
    path: "/bitnami/mongodb" # path to directory

This is the PVC yaml that created by the helm chart:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  creationTimestamp: "2021-06-06T17:50:40Z"
  finalizers:
  - kubernetes.io/pvc-protection
  labels:
    app.kubernetes.io/component: shardsvr
    app.kubernetes.io/instance: sam-db
    app.kubernetes.io/name: mongodb-sharded
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:metadata:
        f:labels:
          .: {}
          f:app.kubernetes.io/component: {}
          f:app.kubernetes.io/instance: {}
          f:app.kubernetes.io/name: {}
      f:spec:
        f:accessModes: {}
        f:resources:
          f:requests:
            .: {}
            f:storage: {}
        f:volumeMode: {}
      f:status:
        f:phase: {}
    manager: kube-controller-manager
    operation: Update
    time: "2021-06-06T17:50:40Z"
  name: datadir-sam-db-mongodb-sharded-shard1-data-0
  namespace: default
  resourceVersion: "960381"
  uid: c4313ed9-cc99-42e9-a64f-82bea8196629
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi
  volumeMode: Filesystem
status:
  phase: Pending

Can you tell me what I am missing?

A: I am giving the bitnami/mongodb-sharded installation instruction with NFS server on Rancher(v2.5.8).
I have three Centos 8 VM. One NFS server(lets we say 1.1.1.1), two k8s nodes(lets we say 8.8.8.8 and 9.9.9.9) on k8s-cluster, i am using RKE(aka Rancher K8S Engine)

*

*We will create a NFS server

*We will bind the nodes to the NFS server

*We will add nfs-subdir-external-provisioner HELM repository to the Rancher Chart Repositories

*We will install nfs-subdir-external-provisioner via rancher charts

*We will add bitnami HELM repo  to the Rancher Chart Repositories

*We will install mongodb-sharded via Rancher charts

*

*Create a NFS server

# nfs server install
dnf install nfs-utils -y
systemctl start nfs-server.service
systemctl enable nfs-server.service
systemctl status nfs-server.service
# you can verify the version
rpcinfo -p | grep nfs
# nfs deamon config: /etc/nfs.conf
# nfs mount config: /etc/nfsmount.conf
mkdir /mnt/storage
# allows creation from client
# for mongodb-sharded: /mnt/storage
chown -R nobody: /mnt/storage
chmod -R 777 /mnt/storage
# restart service again
systemctl restart nfs-utils.service
# grant access to the client
vi /etc/exports
/mnt/storage    8.8.8.8(rw,sync,no_all_squash,root_squash)
/mnt/storage    9.9.9.9(rw,sync,no_all_squash,root_squash)
# check exporting
exportfs -arv
exportfs -s
# exporting 8.8.8.8:/mnt/storage
# exporting 9.9.9.9:/mnt/storage

*Bind the k8s nodes to the NFS server

# nfs client install
dnf install nfs-utils nfs4-acl-tools -y
# see from the client shared folder
showmount -e 1.1.1.1
# create mounting folder for client
mkdir /mnt/cstorage
# mount server folder to the client folder
mount -t nfs 1.1.1.1:/mnt/storage /mnt/cstorage
# check mounted folder vis nfs
mount | grep -i nfs
# mount persistent upon a reboot
vi /etc/fstab
# add following codes
1.1.1.1:/mnt/storage /mnt/cstorage  nfs  defaults  0  0
# all done

Bonus: Unbind nodes.
# un mount and delete from client
umount -f -l /mnt/cstorage
rm -rf /mnt/cstorage
# delete added volume from fstab
vi /etc/fstab

*Add nfs-subdir-external-provisioner helm repository

Helm Repository URL: https://kubernetes-sigs.github.io/nfs-subdir-external-provisioner/

*

*Rancher -->

*Cluster Explorer -->

*Apps & Marketplace

*Chart Repositories -->

*Create -->

*Add url like below this ccreenshot -->

*Save -->

*Install nfs-subdir-external-provisioner via Charts

*

*Rancher -->

*Cluster Explorer -->

*Apps & Marketplace

*Charts -->

*find nfs-subdir-external-provisioner chart -->

*Select -->

*Give a name(like nfs-pr) -->

*Select Values YAML -->

*set path, server ip and StorageClass name(we will use this class name later)  -->

*Install -->

*Add bitnami HELM repo to the Rancher Chart Repositories

Bitnami HELM URL: https://charts.bitnami.com/bitnami

*

*Rancher -->

*Cluster Explorer -->

*Apps & Marketplace

*Chart Repositories -->

*Create -->

*Add url like step 3's screenshot -->

*Save -->

*Install mongodb-sharded via Rancher Charts

*

*Rancher -->

*Cluster Explorer -->

*Apps & Marketplace

*Charts -->

*Find mongodb-sharded -->

*Select -->

*Give a name(my-db) -->

*Select Values YAML -->

*Add global.storageClassname: nfs-client(we set this value step 5) -->

*Install

A: The chart exposes two parameters that allow you to choose the StorageClass you want to use for your PVC(s) (otherwise it will use the 'default' one):

*

*configsvr.persistence.storageClass

*shardsvr.persistence.storageClass
Find more information in the Parameters section of the README.md
So basically you need to install the chart setting these parameters accordingly.


text:
Q: Como capturar o valor de um select criado dinamicamente? (Sei que ja existe uma discussao parecida, mas nao me ajudou.)
O meu objetivo é o seguinte:

*

*caso escolha 'credito' ou 'carne', abre uma div com as opçoes de parcelamento.

*nessa div é criado um select, que recebe o valor da compra e deve calcular a taxa em cada opção de parcelamento.

*a minha ideia era pegar a quantidade de parcelas (value do select) e mandar pra minha funçao 'calTaxa' junto do valor total, assim ele retornaria o valor da parcela de acordo com quantas vezes foi parcelado.

*O problema é que, como o select só é criado ao clicar nas funcoes 'credito' e 'carne', nao consigo capturar o value pra enviar pra função.

HTML:

JS:
$('.payment-method-installment').html
    ( 'Valor total: R$' + 245 + '' +
      '
 Parcelas: ' +
        '<select id="select-parc">' +
          '<option value="1"> 1x de R$ ' + calTaxa($('#select-parc option:selected').val(), soma) + ' </option>'+
        '</select>
' +
     '
');

O '$('#select-parc option:selected').val()' retorna 'undefined'. É possivel capturar o value do select selecionado durante a sua criação? Caso nao, qual seria a melhor alternativa?

A: Essa sua pergunta não faz muito sentido. Talvez você possa reformulá-la.
Agora, se o valor de 1x é escrito diretamente na string, voce não precisa pegar o valor do select, basta passar diretamente para o calTaxa(1, soma);. Agora, se isso for um array, e listará dinamicamente, você pode passar o index do array para o calTaxa(index + 1, soma);.
Mais um detalhe. Considere mudar o nome da função para calculaTaxa. Não tem motivos para diminuir o nome de uma função para economizar milisegundos de digitação.


text:
Q: iPhone: Possible to change the color of just the prompt of the UINavigationBar? I'm wondering if I can change the background color of just the prompt of the UINavigationBar (e.g. to red, while the rest of the navigation bar stays black), so I can use the prompt property of the UINavigationItem to display status / error messages as a one-liner.

A: This is an old question, but since the introduction of appearance there is a much easier way to setting prompt color (and other properties) than adding a subview.
in didFinishLaunchingWithOptions put
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor theColorYouWantYourPromptToBe], UITextAttributeTextColor, otherVariables, nil]];

A: Nope. But you can set the prompt to an empty string, and place a red-colored label on top of it.


text:
Q: Windows error in os.listdir() I'm writing my first Python script to do some cross-platform work and have bumped into an error I didn't expect and can't find any information about (or maybe I don't understand what I'm reading).
brand_dir = os.path.join(os.getcwd(), 'Resources', 'html', brand )
for f in os.listdir(brand_dir):
  # BREAKS WITH: cannot find the file path specified:
  # 'C:\\path\\to\\Resources\\html\\brand_value/*.*'

Works fine on OSX. The only part that looks weird is the /*.* so I'm kind of working under the loose assumption that it's the problem, but I don't see any indication that this should throw Python for a loop.
I'm sure this is a rookie mistake, but what is it? Python 2.7.3, Windows XP 32bit.

A: Have you checked that C:\\path\\to\\Resources\\html\\brand_value is a valid path on your system? The /*.* part is quite normal, when Windows couldn't find the path, it occurs.


text:
Q: ADO.Net: Sharing entities (.edmx) between multiple projects within a solution I've got three C# ASP.NET MVC2 projects within a single solution.  Names have been changed for simplicity's sake.
The solution is MY_COMPANY_SITES.
It's got three projects in it: CUSTOMER_SITE, INTRANET_SITE, CENTRAL_REPOSITORY.
...Both the CUSTOMER_SITE and INTRANET_SITE projects have their own ADO.Net entity models, generated via EDMX, and connect to their own databases.  The CENTRAL_REPOSITORY project contains a third ADO.Net entity model, linked up with its own database.
It is required for my situation that these three databases be separate; would take too long to explain here.
What I need to do: Give both the CUSTOMER_SITE and INTRANET_SITE access to the CENTRAL_REPOSITORY ADO.Net entities, in addition to their own.
i.e., the following code should work:
CUSTOMER_Entities custDb = new CUSTOMER_Entities();
CENTRAL_Entities ctrDb = new CENTRAL_Entities();

StoreLocation firstLoc = ctrDB.StoreLocations.First();

List<Order> orders = (from n in custDb.Orders
                        where n.LocationID == firstLoc.LocationID
                        select n).ToList();

...I'd also ideally prefer that if I modify the entity model within the CENTRAL_REPOSITORY, it's just linked to by the other applications so I don't have to copy all my changes among all three.
I figure there must be a "right" way to do this.  Could very much use some help understanding how.
Thanks!
UPDATE:
Blindy (below) directed me to find that the answer is just to right-click on the "References" within the CUSTOMER_SITE in the Solution Explorer, and click "Add Reference...", then select the CENTRAL_REPOSITORY project, and click OK.  And voila, everything shoud just work.
However, it doesn't actually seem to just work.  Specifically, I'm getting this error when I try to access the CENTRAL_REPOSITORY's data entities from within the CUSTOMER_SITE or INTRANET_SITE:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

...so there's some problem with trying to use the entities from that project, and I'm not understanding what.  Any thoughts?

A: To answer your question, you need to have the appropriate connection string in your configuration of the other two sites, to enable your CENTRAL_REPOSITORY to use it to connect.  Have a look in the original site config and copy that connection to the other two sites.

A: You need to create a connection string in the app.config file for each project that uses the linq to entities model to solve this error.


text:
Q: Why is data not being inserted in the database in the following code? I am a newbie in android programming. This is what I have learned from tutorials but I am not able to understand why the app does not store data which i insert.  This is my code but whenever I run the application it says data not inserted.
This is DataBaseHelper class
package com.dutt.rishabh.android.sqlite.contacts;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Rishabh on 06-07-2016.
*/

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="contacts.db";
public static final String TABLE_NAME="student_contacts";
public static final String id="ID";
public static final String COL_1="NAME";
public static final String COL_2="PHONE NUMBER";
public static  final int DATABASE_VERSION=1;

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query="create table "+TABLE_NAME+"("+id+" INTEGER PRIMARY KEY  AUTOINCREMENT,"+COL_1+" TEXT NOT NULL,"+COL_2+" TEXT NOT NULL"+")";
    db.execSQL(query);
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
    db.execSQL("Drop table if exists "+TABLE_NAME);
    onCreate(db);
}
public boolean addData(String name,String num ){
    SQLiteDatabase myDb=this.getWritableDatabase();
    ContentValues content=new ContentValues();
    content.put("NAME",name);
    content.put("PHONE NUMBER",num);
    long result=myDb.insert(TABLE_NAME,null ,content);
    if(result==-1){
        return false;
    }else{
        return true;
    }

}
public Cursor viewData(){
    SQLiteDatabase myDb=this.getReadableDatabase();
    Cursor cr= myDb.rawQuery("Select * from   "+DatabaseHelper.TABLE_NAME,null);
    return cr;
}
}

**This is MainActivity class**

package com.dutt.rishabh.android.sqlite.contacts;

import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Button add, view;
    EditText name, num;
    Contact contact;
    DatabaseHelper dbHelper= new DatabaseHelper(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    add = (Button) findViewById(R.id.add);
    name = (EditText) findViewById(R.id.name);
    num = (EditText) findViewById(R.id.num);
    view = (Button) findViewById(R.id.view);
    //contact = new Contact(name.getText().toString(), num.getText().toString());

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean m = dbHelper.addData(name.getText().toString(),num.getText().toString());
            if (m) {
                Toast.makeText(MainActivity.this, "Data Inserted!", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(MainActivity.this, "Data not Inserted!", Toast.LENGTH_SHORT).show();
            }
        }
    });
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Cursor res = dbHelper.viewData();
            if (res.getCount() == 0) {
                Toast.makeText(getApplicationContext(), "No Data Found", Toast.LENGTH_SHORT).show();
            }
            StringBuffer sb = new StringBuffer();
            while (res.moveToNext()) {
                sb.append("ID: " + res.getString(0) + "\n");
                sb.append("NAME: " + res.getString(1) + "\n");
                sb.append("PHONE NUMBER: " + res.getString(2) + "\n\n");
            }
            showData("Details",sb.toString());
        }
    });
}

public void showData(String title, String mess) {
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(mess);
    builder.show();
}

}


text:
Q: How to send custom data to future builder? I am trying to find the nearest people from my current location. So I am fetching all the documents from firestore.
My firestore structure is like this,

So I am fetching all the users and checking the nearest users by calculating the distance and I want to pass the filtered data to the future builder to view.
Future makeRequest() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore
         .///
        .collection('mechanic')
        .getDocuments();

    final Distance distance = new Distance();

    qn.documents.forEach((f) {
      double km = distance.as(
          LengthUnit.Kilometer,
          new LatLng(f.data['location'].latitude, f.data['location'].longitude),
          new LatLng(widget.lat, widget.lan));
      if (km < f.data['radius']) {
        print(f.data);
        // filtering data and want to pass this filterd data to Future builder
      }
    });

    return qn.documents;
  }

body: FutureBuilder(
            future: makeRequest(),
            builder: (_, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return Center(
                  child: Text("Loading..."),
                );
              } else {
                return ListView.builder(
                  itemCount: snapshot.data.length,
                  itemExtent: 100.0,
                  itemBuilder: (_, index) {
                    return ListTile(
                      title: Text(
                        snapshot.data[index].data['name'],
                    );
                  },
                );
              }
            })

How can solve this?

A: You can accumulate your results into a list and return that list.
Future makeRequest() async {
   var results =[];
   var firestore = Firestore.instance;
   QuerySnapshot qn = await firestore
   .///
       .collection('mechanic')
      .getDocuments();

   final Distance distance = new Distance();

   qn.documents.forEach((f) {
       double km = distance.as(
       LengthUnit.Kilometer,
       new LatLng(f.data['location'].latitude, f.data['location'].longitude),
       new LatLng(widget.lat, widget.lan));
       if (km < f.data['radius']) {
           results.add(f.data);
       }

   });

   return results;
}


text:
Q: Printing a simple table in Python I have something like this (Python3):
for p in something:
  for r in something_else:
    print(r, end=" ")

but I want each last print in the inner loop to end with a newline to create a nice table.
Is there some short and elegant way to do it?

A: Like this?
for p in something:
  for r in something_else:
    print("%s\t" % r, end=" ")
  print()

More elegant might be
for p in something:
  print(" ".join(map(str, something_else)))

Note that this will just print a table of the elements of something_else a bunch of times. What is in your list? How do you want the table to look? It might help if you're a little more specific in your question.


text:
Q: how can I change google default search country in chrome's search onmibox for iOS? I'm having isuses trying to change default country in google chrome's search onmibox on my iPhone. I've bought the phone in Colombia, but although I've set the region and language on the phone it keeps using google.com.co, when I want it to use google.com. It's not even using my country GPS location because I live in Buenos Aires, Argentina, not in Colombia.
How can I change this behaviour? I tried many things with no luck, and I can't set manually google search url in iOS.
Regards.
Matt.


text:
Q: How do I get rid of the extra 0 being displayed on hours when i format timestamp to NSDate string? [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateFormat:@"hh:mm a"];
NSString *strDate = [dateFormatter stringFromDate:taskStartDate];

Right now its outputting times like : 01:00PM instead of 1:00PM

A: If you don't want a 2-digit hour, don't format with hh. Use h.
[dateFormatter setDateFormat:@"h:mm a"];


text:
Q: vuelidate vues js between rule not working exactly I have to validate form with vue js before sening data, so I use vuelidate package,
I have a quantity filed that it has min and max value, I used betwwenrule from vuelidate like this :
    validations : {
   quantity: {
        required,
        between : between(1, this.quantityMAx)
      },
    }

and `quantityMax is a computed attribute :
 quantityMax(){
    if(this.item){
      //console.log(parseFloat(this.item.qte_stock) - parseFloat(this.item.qte_stock_min))
      return parseFloat(this.item.qte_stock) - parseFloat(this.item.qte_stock_min)

    }
      else return 1
    },

and I got the following error :
Uncaught TypeError: undefined has no properties
    ./node_modules/babel-loader/lib/index.js??clonedRuleSet-5[0].rules[0].use[0]!./node_modules/vue-loader/lib/index.js??vue-loader-options!./resources/assets/js/views/damage/Create.vue?vue&type=script&lang=js& Create.vue:288
    ....

But I used this validation in a componenet and it's working, I d'ont know what is the error !
I imort rules like this :
const {
  required,
  minValue,
  between,
  maxLength,
  maxValue,
}
 = require('vuelidate/lib/validators')

and just between that it has the issue

A: I fix it by using
validations () {
return { ...}
}

and not validions : { ....}


text:
Q: Impossible to start Apache service due to SSL library error I am trying to configure Apache in order to accept HTTPS requests.
Following some tutorials found online, I generated the following certificates:

*

*my-ca.key (CA private key)

*my-ca.crt (CA certificate)

*my-server.key (server private key)

*my-server.csr (server certificate signing request)

*my-server.crt (server certificate)

In particular, the last certificate have been generated using the following command:
openssl x509 -req  -sha1 -in my-server.csr -out my-server.crt -CA my-ca.crt -CAkey my-ca.key -CAcreateserial

Unfortunately, I am unable to start the Apache service because, mentioning the error.log file content:
[Sun Apr 05 01:00:23.831320 2020] [ssl:emerg] [pid 1463] AH02561: Failed to configure certificate localhost:443:0, check /etc/ssl/my-certs/my-server.crt
[Sun Apr 05 01:00:23.832228 2020] [ssl:emerg] [pid 1463] SSL Library Error: error:140AB18E:SSL routines:SSL_CTX_use_certificate:ca md too weak
AH00016: Configuration Failed

Searching for a solution on Google, I found this useful answer on StackOverflow, but as you can check above, I have already used an hashing algorithm different from md5 (in my case, sha1) for the server certificate generation.
So, why this error keep to be returned when starting Apache service? Should I also create a new CA certificate and/or server certificate request?


text:
Q: How i can automaticcly turn on location? want to automatically turn on geolocation?
thanks all

A:
I want to automatically turn on geolocation.

Sorry, but you can't.
The device belongs to the user, and you can only turn geolocation with the user's permission, as granted (or denied) by that prompt.
The best you can do is to display a message to the user telling them that your app cannot run unless they enable geolocation.  However, it is their choice to enable it, or not.

A: You can do something like the user can't use the app until you get their location.


text:
Q: C++ OpenMp using one thread for whole code I was working on a small project (my first) using OpenMp and C++
The code is to calculate the correlation coefficient of two data sets (i'm learning data mining and liked to do what i learn using code)
I first wrote the code like i would normally do
Then tried to make it parallel but it got slower and i don't  think  that it's using more than one thread
This is my first time trying parallel
so i don't know if i missed something
I'am using visual studio community 2015
#include <iostream>
#include <stdio.h>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <omp.h>

using namespace std;

void main() {

    vector <long double> dataSetOne, dataSetTwo, dataSetMultiplication, dataSetOnePow, dataSetTwoPow;
    long double dataSetOneSum = 0, dataSetTwoSum = 0, multiplicationSum = 0, setOnePowSum = 0, setTwoPowSum = 0;
    double correlationCoefficient = 0;

    long int i;
    long int length;

    cout << "Enter length for the Data Sets: " << endl;
    cin >> length;

    #pragma omp parallel
    {
    #pragma omp for
        for (i = 1; i <= length; i++) {
            dataSetOne.push_back(i);
        }
    #pragma omp for
        for (i = 0; i < dataSetOne.size(); i++) {
            dataSetOneSum += dataSetOne[i];
        }

    }
    cout << "The sum of the first Data Set is: " << fixed << dataSetOneSum << endl << endl;

#pragma omp parallel
    {
    #pragma omp for private(i, dataSetTwo)
        for (i = length + 1; i <= length * 2; i++) {
            dataSetTwo.push_back(i);
        }
    #pragma omp for private(i, dataSetTwo)
        for (i = 0; i < dataSetTwo.size(); i++) {
            dataSetTwoSum += dataSetTwo[i];
        }

    }
    cout << "The sum of the second Data Set: " << dataSetTwoSum << endl << endl;
#pragma omp parallel for private(i,dataSetMultiplication,multiplicationSum)
    for (i = 0; i < length; i++) {
        dataSetMultiplication.push_back(dataSetOne[i] * dataSetTwo[i]);
        multiplicationSum += dataSetMultiplication[i];
    }

    cout << "Multiplication sum of the two Data Sets: " << multiplicationSum << endl << endl;
#pragma omp parallel for private(i,dataSetOnePow,setOnePowSum)
    for (i = 0; i < length; i++) {
        dataSetOnePow.push_back(pow(dataSetOne[i], 2));
        setOnePowSum += dataSetOnePow[i];
    }

    cout << "Sum of the first Data Set elements raised to the power of 2: " << setOnePowSum << endl << endl;
#pragma omp parallel for private(i,dataSetTwoPow,setTwoPowSum)
    for (i = 0; i < length; i++) {
        dataSetTwoPow.push_back(pow(dataSetTwo[i], 2));
        setTwoPowSum += dataSetTwoPow[i];
    }

    cout << "Sum of the second Data Set elements raised to the power of 2: " << setTwoPowSum << endl << endl;
#pragma omp parallel
    {
        correlationCoefficient = ((length * multiplicationSum) - (dataSetOneSum * dataSetTwoSum)) / (sqrt((length * setOnePowSum - pow(dataSetOneSum, 2))) * (length * setTwoPowSum) - (pow(dataSetTwoSum, 2)));
    }

    cout << "Correlation Coefficient: " << correlationCoefficient << endl;

    if (correlationCoefficient > 0) {
        cout << "the Correlation between Data Sets is: " << correlationCoefficient << " the relation between Data Sets is positively Correlated" << endl;
    }
    else if (correlationCoefficient == 0) {
        cout << " the Correlation between Data Sets is: " << correlationCoefficient << " the relation between Data Sets is Independent" << endl;
    }
    else if (correlationCoefficient < 0) {
        cout << " the Correlation between Data Sets is: " << correlationCoefficient << " the relation between Data Sets is negatively Correlated" << endl;
    }

    system("pause");
}


text:
Q: Django South Migration introspect_test I'm trying to do a simple migrate and I'm getting the error
django.db.utils.DatabaseError: (1050, "Table 'introspect_test' already exists").
When looking at the actual MySQL database, I see no table called introspect_test nor do I have such a table defined in any Django model. A little bit of Google-Fu tells me that this introspect_test has something to do with foreign key constraints and South's error checking... or something.
I think this whole problem originated form my own error - while in the middle of executing a python manage.py migrate app_name I accidently hit CTRL-C and, thus, stopped the process.
I guess the question is: how do I get rid of this mysterious introspect_test so that I can migrate normally?
Thanks

A: Ugh, silly me... what I didn't realise is that the table introspect_test is alls caps and, thus, isn't sorted alphabetically. It turns out that, due to a small laptop screen, doing show tables; listed all the tables but cut off the top few. Since the table in question is labelled as INTROSPECT_TEST it is at the top.
I did a quick drop table INTROSPECT_TEST and then migrated normally.
Fixed.


text:
Q: Maven project builds but dependencies seem to be unavailable in IntelliJ IDEA I have a multi-level Maven project that builds fine on the command-line using mvn clean install and builds in IntelliJ IDEA (2019.3) by manually running the parent project's clean and install phase. The Problems view shows nothing wrong. When I open files that have certain external libraries, they show as being unable to be resolved:

I'm usually able to browse external libraries' contents in the project browser. I've noticed that these external libraries IntelliJ can't find are listed but not browsable.

Other people working on our project with the same code base and same IntelliJ version don't seem to have this problem. I've tried:

*

*"Reimport all Maven projects"

*File -> Invalidate Caches/Restart

*Completely deleting my ~/.m2/repository

*Completely deleting my $PROJECT_ROOT/.idea directory and reimporting

*Recloning and reimporting the project from scratch

None of the above seem to work.

A: The root case for this problem was not identified and is still under investigation, but what can help is removing the IDE settings and starting with the defaults.


text:
Q: Is the term "low-level employee" considered to be derogatory? I recently saw a TV show where an executive referred to an assistant as a low-level employee.
Is it considered appropriate or derogatory?

A: Deciding, definitively, whether something "is offensive" is extremely difficult to do, since it depends so much on opinion.
Much more useful is to ask if something risks causing offence, and I would say that the phrase "low level employee" definitely risks causing offense.  That is to say, some people would be offended and some wouldn't, but you don't know which of those groups the employees in question belong to.
So, given that you know that it risks causing offence, you, the writer, can decide whether it's appropriate or not.  It may be appropriate if you were including yourself, for example, which might turn it into a more light-hearted statement, to reduce the risk of causing offence.  Or, you might not care if you offend people.  It's up to you, writer.

A: Beats the neck out of being called "flunky." If I were called a "low-level employé," I would not take offense, particularly if the concern for which I work were large enough to have the possibility for advancement.
EDIT:
I note that my response has been downvoted. I am not perturbed by that. I was asked for my opinion on a certain question. In a spirit of honesty I gave mine, with which the downvoter evidently does not agree. How wonderful it would be to live in a country run by the downvoter: I would no longer have to trouble myself to have an opinion of my own.


text:
Q: Understanding C code example with memory allocation I'm new to C and I'm reading "The C Programming Language" by K&R to learn it.  I had a question about this example function appearing on pg 109 of the 2nd edition:
/* readlines:  read input lines */
int readlines(char *lineptr[], int maxlines)
{
   int len, nlines;
   char *p, line[MAXLEN];
   nlines = 0;
   while ((len = getline(line, MAXLEN)) > 0)
       if (nlines >= maxlines || p = alloc(len) == NULL)
           return -1;
       else {
           line[len-1] = '\0';  /* delete newline */
           strcpy(p, line);
           lineptr[nlines++] = p;
       }
   return nlines;
}

I was wondering why *p is at all necessary here?  p is allocated memory and then line is copied into it.  Why can't just line be used, so at the end lineptr[nlines++] = p could be replaced by lineptr[nlines++] = line.

A: If you don't allocate memory for each line, you'll end up with lineptr being an array full of pointers to just the last line you read (not to mention to stack memory which is likely to be overwritten).  Allocating memory for each line as you read makes the returned array make sense.  As an example, let's say that line happens to get allocated on the stack at address 0x1000.  If you make your suggested change, the resulting lineptr array for an 8 line file would be:
0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000

Yowch!  Allocating memory for each line as you read it, and then copying the line into that allocated memory is the only solution.

A: lineptr[nlines++] = line;

would fill lineptr with pointers to memory that is local to that function, and that memory becomes invalid as soon as the function returns. The values of all the elements of the lineptr array would all be identical and equal to line.
So the allocation is necessary here. You really need to copy the contents of line into a newly allocated memory location that persists after the function has returns.

A: You'd need storage for each line to be allocated somewhere.  You can't just capture the value of line as you suggest because that is a local variable which will be out of scope after the function returns (and in this particular example, it's overwritten on each iteration).
You could avoid having line by doing getline directly into the elements of lineptr (which you would allocate as you go), but you cannot get rid of p.

A: A new chunk of memory needs to be allocated for each line.  The pointer p is the only handle we have to that memory.  We assign lineptr[nlines++] = p so we can reference each chunk of memory (e.g. line) as part of the array lineptr.

A: An assignment of the kind lineptr[nlines++] = p in c/c++, sets the address of lineptr[nlines++] to the address where p points to, no data is copied here.
so, the address of  line is always the same address; so lineptr[nlines++] = line whould mean that all all lineptr[i] would point to the same address.
the worst part, after the function returns, line does no longer exist, so every lineptr[i] then points to some invalid address.
using the p allocates new memory for each line, and ensures that the address of that memory is still valid between functions (until you free it).

A: Okay, so let's show you how to do the same thing without char *p... I am going to slightly modify the code.
/* readlines:  read input lines */

#include <string.h>

/* put that include line below #include <stdio.h> if you don't already have this
   string.h defines strdup() function which we use below */

int readlines(char *lineptr[], int maxlines)
{
   int len, nlines;
   char line[MAXLEN];
   nlines = 0;

   while ((len = getline(line, MAXLEN)) > 0) {
           line[len-1] = '\0';  /* delete newline */
           lineptr[nlines] = strdup(line); /* allocate memory and make a copy */
           if (lineptr[nlines] == NULL) {
                  return -1;
           }

           nlines++;

           if (nlines >= marlines)
               break;

   }

   return nlines;
}

This code is closest without the temporary char *p use.
The thing is that while this is functionally correct, use of the temporary variable char *p to test out all allocations and retrieval makes the code cleaner to read, easy to follow for teaching purposes.  It also shows explicitly the allocation of the string memory as a separate step, which is hidden in strdup.


text:
Q: How to mask the image in C# using ITextSharp.dll? I am newbie to C#.Can anybody provide me with some links or tutorials for the masking of the image using ITextSharp.dll?
Any help would be appreciated a lot.
Thanks

A: I'm discussing hard and soft image masks in chapter 10 of my book. You'll find some Java examples (and the corresponding PDFs) if you click links such as ImageMask (this example shows you how to create a hard mask as well as a soft mask). You'll find a C# port of the examples here: http://tinyurl.com/iiacsCH10


text:
Q: Close NavigationDrawer and show loading while getting data I currently have a navigation drawer in which each option does a call to a server to get data. This is done via a class I made that receives the type of call as a string and makes the request in an AsyncTask, returning the data retrieved.
The problem I'm facing is, due to latency the navigation drawer keeps open while it is doing the request and parsing the data, which confuses the user into thinking it crashed.
I wanted it to close and show a ProgressDialog while the operation doesn't finnish. My current code does not work, any idea why? Thanks in advance
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    int id = item.getItemId();

    this.mDrawer.closeDrawer(GravityCompat.START);
    this.mDialog.show();

    if (id == R.id.nav_data) {
        this.dataList = this.myGetterClass.getRequests("some/API/route");
        try {
            if (this.dataList.size() == 0) {
                setTitle("There's no data");
            } else {
                setTitle("Here's the data");
            }
        } catch (Exception e) {
            setTitle("Without data");
            Toast error = Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG);
            error.show();
        }
    }
    updateScreen(this.dataList);
    this.mDialog.dismiss();
    return true;
}

A: for close the navigationDrawer this worked for me
  drawerLayout.closeDrawer(Gravity.START);
  drawerToggle.syncState();

To show the ProgressBar you can define it in the xml file and then show and hide it when you want

A: To close drawer you need to replace
 mDrawer.closeDrawer(GravityCompat.START);

with
mDrawerLayout.openDrawer(Gravity.LEFT); //herer the drawer gravity from where drawer open
To show progress dialog best approach is to put progress in asynktask
if (id == R.id.nav_data) {
   //call asynk task for getting server data
}else if(id == R.id.nav_data1){
 //call asynk task for getting server data
}

check this for more info about AsynkTask and this


text:
Q: Cached entities making round trip to database i am caching objects, if i make linq queries on cached entities then... will theses queries make database round trip due to lazy loading in Entity framework?

A: If you do not detach the entities before you caching them the entities will keep a reference to the context that created them and use it to lazy load. It is better to detach the entities.
context.Detach(entity);
cachedItems.Add(entity);


text:
Q: How to create a folder of current date and time And copy some other folder in that recently made folder in python I have tried it in Jetbrains Pycharm but it is showing an error.
Here is my code
from datetime import datetime
import os
import shutil
now = datetime.now()
dt=now.strftime("%d%m%Y %H%M%S")
os.mkdir(dt)
shutil.copytree(r"C:\Users\Computer\PycharmProjects\06\08",r"C:\Users\Computer\PycharmProjects\Filecopy\dt")

A: If you are trying to use the path of your newly-created directory, the line should do:
..., r"C:\Users\Computer\PycharmProjects\Filecopy\{}".format(dt))


text:
Q: CTimeSpan.GetDays() and daylight savings time I found in a bug in an old C++ MFC program we have that calculates an offset (in days) for a given date from a fixed base date.  We were seeing results that were off by one for some reason, and I tracked it down to where the original programmer had used the CTimeSpan.GetDays() method.  According to the documentation:

Note that Daylight Savings Time can cause GetDays to return a potentially surprising result. For example, when DST is in effect, GetDays reports the number of days between April 1 and May 1 as 29, not 30, because one day in April is shortened by an hour and therefore does not count as a complete day.

My proposed fix is to use (obj.GetTotalHours()+1)/24 instead.  I think that would cover all the issues since this is a batch job that runs at about the same time every day, but I thought I'd ask the smart people here before implementing it if there might be a better way.
This is just a side issue, but I'm also curious how this would be handled if the program could be run at any time.

A: Your fix works fine to get the number of whole 24-hour periods between two times - as long as the events occur at the same time each day.  Otherwise that "+1" in the expression could lead to an off-by-one error.
Sometimes you don't care what time of day the event occured, you just want to know which day.  In that case, you need to zero out the hours, minutes, and seconds, then use your formula:
CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0);
CTime finishDay(finish.GetYear(), finish.GetMonth(), finish.GetDay(), 0, 0, 0);
int days = ((finishDay - startDay).GetTotalHours() + 1) / 24;

A: A minor change to what Mark suggested and it works without any reliance on rounding:  Just add one more parameter of zero to the CTime constructor.  This forces both times to be in standard time (not daylight savings).  The default value for that parameter is -1 which means "Automatically compute if daylight savings time is in effect."
// Discard hours, minutes, seconds, and daylight savings time
CTime startDay(start.GetYear(), start.GetMonth(), start.GetDay(), 0, 0, 0, 0);
CTime endDay(end.GetYear(), end.GetMonth(), end.GetDay(), 0, 0, 0, 0);

// Get number of days apart
CTimeSpan span = endDay - startDay;
int nDays = span.GetDays();

Tested and works.


text:
Q: Key down infinite loop iam making an application which plays a sound when a key is down, the sound stops immediately when the key is released.
The problem I found is that if you press a key it plays the first miliseconds of it and then infinite loop it until you release the key.
The code iam currently using is the following:
        public class Foo
        {

            public static int GetStream1(string path)
            {
                return Bass.BASS_StreamCreateFile(path, 0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
            }
            public static int GetStream2(string path)
            {
                return Bass.BASS_StreamCreateFile(path, 0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_STREAM_PRESCAN);
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            Bass.BASS_Init(1, 44100, BASSInit.BASS_DEVICE_DEFAULT, this.Handle);
            Bass.BASS_Init(2, 44100, BASSInit.BASS_DEVICE_DEFAULT, this.Handle);

                if (e.KeyCode == Keys.D1)
                {
                    if (beatload1.Text == "Waiting 01.wav")
                    {
                        MessageBox.Show("No beat loaded");
                        return;
                    }
                    Beat1.Image = Beatpadpc.Properties.Resources.white_square_button;
                    try
                    {
                        Bass.BASS_SetDevice(1);
                        Bass.BASS_ChannelPlay(Foo.GetStream1(path1.Text), false);
                    }
                    catch (FileNotFoundException)
                    {
                        MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!");
                    }
                }

                if (e.KeyCode == Keys.D2)
                {
                    if (beatload2.Text == "Waiting 02.wav")
                    {
                        MessageBox.Show("No beat loaded");
                        return;
                    }
                    Beat2.Image = Beatpadpc.Properties.Resources.white_square_button;
                    try
                    {
                        Bass.BASS_SetDevice(2);
                        Bass.BASS_ChannelPlay(Foo.GetStream2(path2.Text), false);
                    }
                    catch (FileNotFoundException)
                    {
                        MessageBox.Show("File has been moved." + "\n" + "Please relocate it now!");
                    }
               }
        }

        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
         if (e.KeyCode == Keys.D1)
            {
                Beat1.Image = Beatpadpc.Properties.Resources.black_square_button;
                Bass.BASS_StreamFree(Foo.GetStream1(path1.Text));
                Bass.BASS_SetDevice(1);
                Bass.BASS_Free();
            }
            if (e.KeyCode == Keys.D2)
            {
                Beat2.Image = Beatpadpc.Properties.Resources.black_square_button;
                Bass.BASS_StreamFree(Foo.GetStream2(path2.Text));
                Bass.BASS_SetDevice(2);
                Bass.BASS_Free();
            }
}

So is there a way to play 1 or more sounds at the same time without them getting looped for ever?

A: Add a private member to your class:
private Dictionary<Key, Boolean> KeyIsDown;

In your OnKeyDown method, set KeyIsDown(currentKey) = true;  In your OnKeyUp method, set KeyIsDown(currentKey) = false;
Then add a delegate for the onIdle event.  Whenever the delegate is called check each key in KeyIsDown using an if statement instead of foreach and process each key as you like depending on whether KeyIsDown(aKey) is true or false.
Since I do not have the Bass class that your code refers to, I can only come to a close approximation of what it should look like.  You will have to make the real adaptations yourself.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;

namespace WinformExcercise1
{
   public partial class Form1 : Form
   {
      private Dictionary<Keys, bool> keyIsDown = new Dictionary<Keys,bool>();
      private Timer timer;
      private int stream1;

      public Form1()
      {
         InitializeComponent();

         keyIsDown.Add(Keys.J, false);
         keyIsDown.Add(Keys.K, false);
         keyIsDown.Add(Keys.L, false);

         setupPlayer();
         this.KeyPreview = true;
      }

      private void setupPlayer()
      {
         // Bass.BASS_SetDevice(1);
         stream1 = Foo.GetStream2(path1.Text);
         // all code that is called once for setting things up goes here
      }

      private void Form1_KeyDown(object sender, KeyEventArgs e)
      {
         if (true == keyIsDown.ContainsKey(e.KeyCode))
         {
            keyIsDown[e.KeyCode] = true;
         }
      }

      private void Form1_KeyUp(object sender, KeyEventArgs e)
      {
         if (true == keyIsDown.ContainsKey(e.KeyCode))
         {
            keyIsDown[e.KeyCode] = false;
         }
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         // This makes the computer constantly call the playKeys method
         timer = new Timer();
         timer.Interval = 1000;
         timer.Tick += new EventHandler(playKeys);
         timer.Enabled = true;
      }

      private void playKeys(Object source, EventArgs e)
      {
         // You have to add the next 8 lines once for each key you are watching
         // What I have here only does something for the J key.
         if (true == keyIsDown[Keys.J])
         {
            Bass.BASS_Init(1, 44100, BASSInit.BASS_DEVICE_DEFAULT, this.Handle);
         }
         else
         {
            Bass.BASS_StreamFree(Stream1);
         }
      }

   }
}

A: haha nice, i was just posting a similar answer then philogon, but with a slight difference:
private Dictionary<Key, bool> myKeys;

while initializing you add all keys you want to press (e.g. Keys.D1, Keys.D2), all with "false".
write a function like:
private bool getKeyState(Keys k)

this function can be used everytime a key is pressed. the parameter will be the key, which is pressed. if its already pressed, ignore it. if not, yeah play the bass.
and then, i'd write a function like:
private void updateKeyDictionary(Key, boolean state)

here you could check with "getKeyState" you get the current state of the key - if it's the same state, do nothing, otherwise update.
with some nice linq-expression this tasks could be done in 2-3 lines


text:
Q: How to open links in Android app in external browser? Can anyone help me in Code for opening links in external browsers or other Android app?
Now the case is the link is opening in the app itself. But if the link belongs to an android app its not opening. It's showing install the Android app.
So I want that if the link can be opened in browsers, then it will ask from a list of browsers. Or if the links belongs to an app it must show the app in the list too.

A: Something like this could work
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(browserIntent);

A: As @zain posted ago you can use.
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.stackoverflow.com"));
startActivity(intent);

But if you have more then one browser installed in device and want to choose from one of them. Use intent chooser like this
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.stackoverflow.com"));

// Always use string resources for UI text. This says something like "Share this photo with"
String title = getResources().getText(R.string.chooser_title);
// Create and start the chooser
Intent chooser = Intent.createChooser(intent, title);
startActivity(chooser);

refer from here
Show browser list when opening a link in android

A:
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.co.in/"));

            String title = "Complete Action Using";

            Intent chooser = Intent.createChooser(intent, title);
            startActivity(chooser);

A: If you are in a WebView in your App, and on clivking a link there, if the app opens the link in the App Itself, Then possibly u should have overridden this method.
 myWebView.setWebViewClient(new WebViewClient()
    {
         @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            //view.loadUrl(url);

            return false;
        }
    });

The return of false  should ask the user, where to Open the link. With the browsers installed in the mobile