text:
Q: Display ASP.NET generated pdf byte[] to web page without saving the file I'm using iTextSharp for generating a pdf. I can save the PDF file from the PDF byte[].
byte[] outputPDF = cnt.CreateBreakPDF();
File.WriteAllBytes(pdfOutPutPath, outputPDF);

What is the best way to display the output byte[] to a web page?
I want to show the PDF inside a div in my page. Not the PDF as a full response.
I've seen answers for MVC, but I'm using ASP.NET Web Application.
Is there a better way than using HTTP handlers to do so? I don't want to send all the details for creating PDF as query string.

A: Try this
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", outputPDF.Length.ToString());
Response.BinaryWrite(outputPDF);

A: I have being using Convert.ToBase64String(content) for some projects without any issue, until today with a 18 page file at about 1 MB. The error from Chrome's console is Failed to load resource: net::ERR_INVALID_URL. I guess it's because of the string size?!
I ended up using web api and just return it as FileStreamResult instead of Base64 string.
var stream = new MemoryStream();
await stream.WriteAsync(content, 0, content.Length);
stream.Position = 0;
return new FileStreamResult(stream, "application/pdf");

Update: It's basically the same to display it on a razor page. I just copied my code for retrieving fax content using RingCentral here. And better yet, just use FileContentResult as you already have the byte[].

public async Task<IActionResult> OnGet(string messageId)
{
    try
    {
        using (var rc = new RingCentral.RestClient(setting.ClientId, setting.ClientSecret, setting.Production, "Fax"))
        {
            await rc.Authorize(setting.UserName, setting.Extension, setting.Password);
            var extension = rc.Restapi().Account().Extension();
            var outputPDF = await extension.MessageStore(messageId).Content(messageId).Get();

            return new FileContentResult(outputPDF, "application/pdf");
        }
        return Page();
    }
    catch (Exception ex)
    {
        _logger.Error(ex.Message);
        throw;
    }
}

A: I tried this in jsFiddle, and it works well in Chrome & FF,  need to check on other browsers as well.
Convert the byte[] to Base64 using,
string base64PDF = System.Convert.ToBase64String(outputPDF, 0, outputPDF.Length);

All I had to do is specify the MIME type as data:application/pdf;base64, in the source and give the Base64 version of the PDF.
<object data="data:application/pdf;base64, JVBERi0xLjQKJeLjz9MKMyA..." type="application/pdf" width="160px">
    <embed src="data:application/pdf;base64, JVBERi0xLjQKJeLjz9MKMyA..." type="application/pdf" />
</object>

I couldn't be able to hide the top toolbar which appears in FF by appending #toolbar=0&navpanes=0&statusbar=0.
IE8 needs a saved pdf file to be displayed.

A: Would something like this work?

<object data="myPDF.pdf" type="application/pdf" width="200" height="500">
alt : myPDF.pdf
</object>

You would just need to pass your pdf into the object data source.


text:
Q: deleting a node from a link list in c ++, by comparing string values Problem: i am facing problem in deleting a node, let me tell you how i am inserting in it first, i have a Student LinkList, each node have an ID(Int) and Student Name(String), and code to insert nodes in the list is this:
void FileHandling::readLine(char filePath[], StudentList* sl1){

ifstream read_file;
string line;
read_file.open(filePath, std::ifstream::in);

if(read_file.is_open()){
        while(read_file.good()){
            getline(read_file,  line);
            if(line.substr(0,1)!= "#" && !line.empty() ){
                //cout<<line<<endl;

                std::stringstream ss(line);
                int id;
                std::string first_name, surname;
                ss >> id >> first_name >> surname;
                std::string name = first_name + " " + surname;
                //cout<< id <<", "<<name<<endl;
                sl1->insertSort(id,name); // insert node in an alphabetic order
            }
        }
}

}
This is how i require to delete by getting name from user: note when i get name like "abc xyz", my string name; variable only contain xyz in it and skip the initial name.
void StudentList::deleteWN(StudentList* sl1){
//Deleting from list by getting name from user
string name;
while(true){
    cout << "Deleting: Student Name 0r press 'q' to quit"<<endl;
    cin >> name;
    cout<<name<<endl;
    if(name=="q")
        break;
    sl1->deleteWithNmae(name);
    sl1->printList();
}

}
void StudentList::deleteWithNmae(const string& name1){

// CASE 1: Deleting from an empty list
if(head == 0){
    cout<< "Node can not be deleted from an Empty List"<<endl;
}else{
// Traversing the list to find Exact Node
    Student* curr = head;
    Student* prev = 0;
    while(curr != 0){
        if(curr->name == name1){
            // node found, break the while loop
            // Never compare the name of curr node with the user input
            // i also tried curr->name.length() == name1.length()
            //and comparing the strings but i m sure i m doing something
            // wrong here and cant find my node in any case.

            break;
        }else{
            prev = curr;
            curr = curr->next;
        }
    }
    // CASE 2: Node not found
    if(curr == 0){
        // always execute this code, i never able to find my node
        cout<< "Student "<<name1<<" not Found .."<<endl;
    }else{
            //CASE 3: Deleting node from the head
        if(curr == head){
            head = head->next;
        }else{
            //CASE 4: Deleteing node beyond the head
            prev->next = curr->next;
        }
        delete curr;
        size--;
    }

}

}
Help me out with this problem Thanks in advance.

A: You already do the right thing in your insert code. The only difference here is that you have to check for "q" after you have read the first name. If it's not "q" then you can read the last name. Like this
void StudentList::deleteWN(StudentList* sl1){
//Deleting from list by getting name from user
string firstName, lastName;
while(true){
    cout << "Deleting: Student Name 0r press 'q' to quit"<<endl;
    cin >> firstName;
    if(firstName=="q")
        break;
    cin >> lastName;
    std::string name = first_name + " " + surname;
    sl1->deleteWithNmae(name);
    sl1->printList();
}

A: You need to use std::getline(std::cin, name) to read entire line. cin >> name will read text before space, and not the entire line.
Example from here:
#include <iostream>
#include <string>

int main ()
{
  std::string name;

  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!\n";

  return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: FPC/Lazarus and Android development? Hi,

I've heard something about component to Lazarus to develop Android apps... I understand pascal very well and Im not sure if it will be easier to learn Java, or make applications in Pascal ... What do you think? It will be better to work with Pascal and do something in something other than it should be, or to learn Java? thats my question,

thx for responses

A: Please use the official Android Studio provided by Google as it will be a lot easier to search for problems/solutions when you're coding with the Android&Java combination than Android&Pascal


text:
Q: R.id suddenly unrecognize Android Studio I was worked about my project a few hours today, and suddenly all the "R.id..." was unrecognized. all the R is in Red color, and when I put the mouse on it say

Cannot resolve symbol R

I was tried to delete all the changed (with ctrl+z on all the pages) but nothing fixed.
its not a specific item, is all the "R.id.." codes that I have in the project, in all the activities and fragments.
what can I do? where is the problem? can i restore my job somehow?

A: You have to check your Xml file. If there is an error then you can't resolve this error.
Else :
Click on Build -> Rebuild Project and then click Tools -> Android -> Sync Project with Gradle Files.


text:
Q: dayJS date function to PHP Carbon I have the following date processing in dayjs which I am trying to replicate in PHP but failing. I expect both to return Monday 27 July 2020.  Can someone help?
JS - returns Monday 27 July 2020
var firstOfMonth = dayjs('2020-08-01'),
    weekOneStart = firstOfMonth.clone().day(1); // Monday

console.log(weekOneStart);

PHP - returns Monday 3 August 2020
$d = Carbon::createFromFormat('Y-m-d', '2020-08-01');
echo $d->firstOfMonth(1);

A: The two functions are different, as the JS function gets the first Monday of the week, while the Carbon function gets the first Monday of the month. You can see this in the Carbon code for firstOfMonth:
public function firstOfMonth($dayOfWeek = null)
{
    $this->startOfDay();

    if ($dayOfWeek === null) {
        return $this->day(1);
    }

    return $this->modify('first '.static::$days[$dayOfWeek].' of '.$this->format('F').' '.$this->year);
}

If you want to get the first day of the week, then you need to use $d->startOfWeek();
$d = Carbon::createFromFormat('Y-m-d', '2020-08-01');
$d->startOfWeek();
// object(Carbon\Carbon)(
//   'date' => '2020-07-27 00:00:00.000000',
//   'timezone_type' => 3,
//   'timezone' => 'America/New_York'
// )


text:
Q: Gnome: Prevent turning off screen when locked I am using Ubuntu 17.10 with gnome shell, and want my monitors to stay alive when screen gets locked.
Background: It's a Notebook connected to external monitors which need ages to wake after every time they get black. Locking is necessary and needs to happen after an idle time and manually, so Caffeine is no option.
Any hints on how to achieve that behavior? Possibly an extension?


text:
Q: Converting NSArray to char** and returning the c array I need to convert an NSarray filled with NSStrings and return this c array to the function.
-(char**) getArray{
        int count = [a_array count];
        char** array = calloc(count, sizeof(char*));

        for(int i = 0; i < count; i++)
        {
             array[i] = [[a_array objectAtIndex:i] UTF8String];
        }
        return array;
}

I have this code, but when should i free the memory if I'm returning stuff?

A: You need to allocate memory for each string in the array as well.  strdup() would work for this.  You also need to add a NULL to the end of the array, so you know where it ends:
- (char**)getArray
{
    unsigned count = [a_array count];
    char **array = (char **)malloc((count + 1) * sizeof(char*));

    for (unsigned i = 0; i < count; i++)
    {
         array[i] = strdup([[a_array objectAtIndex:i] UTF8String]);
    }
    array[count] = NULL;
    return array;
}

To free the array, you can use:
- (void)freeArray:(char **)array
{
    if (array != NULL)
    {
        for (unsigned index = 0; array[index] != NULL; index++)
        {
            free(array[index]);
        }
        free(array);
    }
}

A: array you return will be caught in some char** identifier in calling environment of getArray() function using that you can free the memory which you have allocated using calloc() inside getArray() function
int main()
{
 char **a=getArray();
 //use  a as your requirement
 free(a);
}


text:
Q: Diffusion current and depletion region with doping I've been told that depletion region width decreases when we increase doping in a P-N junction. But doesn't this contradicts the fact that diffusion current increases with current? I'm probably mixing things up. What I would like to know is:

*

*How does diffusion current varies with doping

*How does the width of depletion region varies with doping

*How does the charge (and then, the electric field and the voltage) of depletion region varies with doping. Why is it said the voltage cannot increase more than $0.7$ V for a silicon junction?


text:
Q: How can I update my Gnome Extension? I have this extension, which I created as a spin off of this one and is basically the same, it just removes the adding of buttons to the panel (I did this to make it easier to use on a computer with a small screen).
I have created a few updates for it, but I cannot work out how to upload them.
Is there a place I can find documentation to do this (here)

A: (that was easy)
Updating the version number properly and then uploading the zip file here worked.


text:
Q: Material design table not displaying full width Angular2 Hello I have a simple angular application which displays the following when the component loads

The table for some reason is not displaying full width inside the left panel
template code is as follows

Tasks Page

              Material
              Quantity
              Unit price

              Acrylic (Transparent)
              25
              $2.90

              Plywood (Birch)
              50
              $1.25

              Laminate (Gold on Blue)
              10
              $2.35

Any ideas how I can display the table full width ?

A: Just change this line with

with

try this one with col-12

Updated Working Plunker


text:
Q: Accessing data in hashed_unique in boost::multi_index I'm trying for the first time to work with boost's multi-index and I can't seem to be able to wrap my head around all the code I see on the web.
First of all: My aim is to have a container with an enum as the key for direct access as well as to be able to iterate over it based on the original order of insertion.
I have defined my boost elements like so:
struct VarMapEle {
    SolutionVariableNames first;
    uint    second;
};

struct var_tag {};
struct rand_tag {};

typedef multi_index_container<
    VarMapEle,
    indexed_by<
        random_access<tag<rand_tag>>, // this index represents insertion order
        hashed_unique<tag<var_tag>, member<VarMapEle, SolutionVariableNames,     &VarMapEle::first>>
        >
> VariableMap;

How can I do either of the tasks I mentioned before?

A: A multi_index_container can be thought of as a bunch of containers (in your example, one std::vector-like --random_acces-- and the other similar to a std::unordered_set --hashed_unique--) which happen to act on the same underlying collection of elements. Each "container" or index is accessed with get<tag>() or get<n>()where n is the 0-based order of the index as specified in the indexed_by section. So, to iterate over the elements in their order of insertion you need to access index #0 and use it as you'd do with a std::vector:
for(const VarMapEle& e:m.get<rand_tag>()){
    std::cout<<e.first<<","<<e.second<<"\n";
}

Similarly, lookup facilities are provided by index #1:
auto it=m.get<var_tag>().find(SolutionVariableNames{1});
std::cout<<it->second<<"\n";


text:
Q: Windows 8 certificate issues I am experiencing significant certificate generation issues in Windows 8.
The first issue I encoutered was with Hyper-V being unable to generate a certificate. See this question for more detail: Hyper-V not working on Windows 8.
Since then, I've tried to deploy a self-signed application through click-once. When clicking Create Test Certificate I receive this message:
Access is denied. Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)

After I receive that error, I can manually choose the certificate that was generated by selecting Select from File.... Then, when I try to install the deployed application, I receive this error:
Cannot continue. The application is improperly formatted.
Contact the application vendor for assistance.

I am running VS as an administrator. Am at a total loss on how where to go next. Any suggestions?

A: I guess you don't have read access.
Right click on the file, and ensure that you have read access. Or, give that right to Everyone just to quickly test and then by user.
Some times, the key lives here C:\Users\All Users\Microsoft\Crypto\RSA which also needs to be updated.


text:
Q: Extract e-mail address from string using r These are 5 twitter user descriptions. The idea is to extract the e-mail from each string.
This is the code i've tried, it works but there is probably something better.
I'd rather avoid using unlist() and do it in one go using regex. I've seen other questions of the kind for python/perl/php but not for R.
I know i could use grep(..., perl = TRUE) but that should't be the only way to do it.
If it works, of course it helps.
ds <- c("#MillonMusical | #PromotorMusical | #Diseñador | Contacto :        ezequielife@gmail.com | #Instagram : Ezeqielgram | 01-11-11 |           @_MillonMusical @flowfestar", "LipGLosSTudio by: SAndry RUbio           Maquilladora PRofesional estudiande de diseño profesional de maquillaje     artistico lipglosstudio@hotmail.com/", "Medico General Barranquillero   radicado con su familia en Buenos Aires para iniciar Especialidad       Medico Quirurgica. email jaenpavi@hotmail.com", "msn =
    rdt031169@hotmail.comskype = ronaldotorres-br", "Aguante piscis /       manuarias17@gmail.com  buenos aires"
    )

ds <- unlist(strsplit(ds, ' '))
ds <- ds[grep("mail.", ds)]

> print(ds)
[1] "\t\tezequielife@gmail.com"  "lipglosstudio@hotmail.com/"
[3] "jaenpavi@hotmail.com"       "rdt031169@hotmail.comskype"
[5] "/\t\tmanuarias17@gmail.com"

It would be nice to separate this one "rdt031169@hotmail.comskype"
perhaps asking it to end in .com or .com.ar that would make sense for what i'm working on

A: Here's one alternative:
> regmatches(ds, regexpr("[[:alnum:]]+\\@[[:alpha:]]+\\.com", ds))
[1] "ezequielife@gmail.com"     "lipglosstudio@hotmail.com" "jaenpavi@hotmail.com"      "rdt031169@hotmail.com"
[5] "manuarias17@gmail.com"

Based on @Frank's comment, if you want to keep country identifier after .com as in your example .com.ar then, look at this:
> ds <- c(ds, "fulanito13@somemail.com.ar")  # a new e-mail address
> regmatches(ds, regexpr("[[:alnum:]]+\\@[[:alpha:]]+\\.com(\\.[a-z]{2})?", ds))
[1] "ezequielife@gmail.com"      "lipglosstudio@hotmail.com"  "jaenpavi@hotmail.com"       "rdt031169@hotmail.com"
[5] "manuarias17@gmail.com"      "fulanito13@somemail.com.ar"


text:
Q: Altering a struct that has been passed by caller? (constructing binary search tree from preorder) I have programmed in Java for a few years now, and I am attempting to learn C++.
I would like some tips about what is wrong with this piece of code specifically, but more importantly, I'd like to know whether I am approaching this question correctly or not.
The task is to return TreeNode *root to a BST, given vector<int>& preorder.
The general idea is clear to me: recursively find left and right bounds, and build the tree using this.
I have tried:

*

*using a helper method that returns a TreeNode * - this caused AddressSanitizer: heap-buffer-overflow errors

*converting the helper method to return type void, and passing a TreeNode *ptr as a parameter - this causes runtime error: member access within null pointer of type 'TreeNode' errors
My code:
class Solution {
public:
    TreeNode* bstFromPreorder(vector<int>& preorder) {
        TreeNode* root = new TreeNode();
        constructSubtree(preorder, root, 0, preorder.size());
        return root;
    }
private:
    void constructSubtree(vector<int>& preorder, TreeNode* ptr, int start, int end) {
        if(start == -1 || start >= end) {
            return;
        }
        ptr->val = preorder[start];
        int split = -1; // first idx where preorder[idx] > preorder[start]
        for(int i = start + 1; i < end; ++i) {
            if(preorder[i] > preorder[start]) {
                split = i;
                break;
            }
        }
        constructSubtree(preorder, ptr->left, start + 1, split);
        constructSubtree(preorder, ptr->right, split, end);
    }
};

some example input: [8,5,1,7,10,12]
Can someone explain what I'm doing wrong?
As I said, I am still learning C++, and I would also really like to hear general tips about working with pointers (and who is responsible for freeing their content).

A: ptr of constructSubtree() should be allocated before call, because it's not allocated in the function. so you should allocate ptr->left and ptr->right before call the function constructSubtree() recursively.
below is working code(though not so neat)
class   TreeNode
{
public:
    TreeNode() { val = 0; left = nullptr; right = nullptr; }
    int val;
    TreeNode    *left;
    TreeNode    *right;

    void    print()
    {
        if(left != nullptr)
            left->print();
        std::cout << val << std::endl;
        if(right != nullptr)
            right->print();
    }

    void    remove()
    {
        if(left != nullptr)
            left->remove();
        if(right != nullptr)
            right->remove();
    }
};

class Solution {
public:
    TreeNode* bstFromPreorder(std::vector<int>& preorder) {
        constructSubtree(preorder, &root, 0, preorder.size());
        return root;
    }
private:
    TreeNode    *root;
    void constructSubtree(std::vector<int>& preorder, TreeNode** ptr, int start, int end) {
        if(start == -1 || start >= end) {
            return;
        }
        *ptr = new TreeNode();
        (*ptr)->val = preorder[start];
        int split = -1; // first idx where preorder[idx] > preorder[start]
        for(int i = start + 1; i < end; ++i) {
            if(preorder[i] > preorder[start]) {
                split = i;
                break;
            }
        }
        if(split != -1)
        {
            constructSubtree(preorder, &((*ptr)->left), start + 1, split);
            constructSubtree(preorder, &((*ptr)->right), split, end);
        }
    }
};


text:
Q: Calling Class Attributes in Python I'm reading a Python Programming text where it's creating a scene within a game with the following code:
class Death(Scene):

    quips = [
        "You died.  You kinda suck at this.",
        "Your Mom would be proud...if she were smarter.",
        "Such a luser.",
        "I have a small puppy that's better at this.",
        "You're worse than your Dad's jokes."

    ]

    def enter(self):
        print(Death.quips[randint(0, len(self.quips)-1)])

My question is just over the last line. What's the difference when using a specific class name, in this case Death.quips as opposed to self.quips. The latter is how I've always seen it but it's used differently here. My first thought was maybe it bypasses needing to first create an object, but in this example self.quips requires the object anyways.

A: Essentially, they are accomplishing the same thing in the scenario. Death.quips is calling to the quips attribute of the class. Using self.quips is referring to the specific object of the class. You can change attributes on objects as well.
For example, if you changed Death.quips to self.quips you could do the following:
>>> a = Death()
>>> a.enter()
Such a luser.
>>> a.quips = [
        "a",
        "b",
        "c",
        "d",
        "e"

    ]
>>> a.enter()
c
>>>

But, if you were to keep it Death.quips, this would be the result:
>>> a = Death()
>>> a.enter()
You died.  You kinda suck at this.
>>> a.quips = [
        "a",
        "b",
        "c",
        "d",
        "e"

    ]
>>> a.enter()
Such a luser.
>>>

Self refers to the attributes of the instantiated object, while Death is referring to the unchanged attribute of the overall class.
I hope this helps and makes sense

A: in this you can directly access the quips list as x = Death.quips without intialise it.
if you used self then you need to intialise the class first (using def __init__()) and in that you need to define quips. then you could access it as
x = Death()
quips_ = x.quips

else to directly access it, you needed to add the @staticmethod before a class method which provide u the list


text:
Q: $\int^b_a \dot x^2(t) dt\geq \frac{\pi ^2}{4(b-a)^2}\int^b_a x^2(t)dt$ $\forall x(t)\in C^1[a,b],x(a)=0,\int^b_a \dot x^2(t) dt\geq \frac{\pi ^2}{4(b-a)^2}\int^b_a x^2(t)dt$
I tried to prove this by following steps:
(1)let $k^2=\frac{\pi ^2}{4(b-a)^2}$,for $x(t)\in C^2[a,b],x(b)=B$, solve E-L equations and we get $ \ddot x(t)+k^2x=0$, so $x(t)=sin(k(x-a)+\phi)-sin\phi$, so that the proposition right.
(2)
for $x(t)\in C^1[a,b]$,we can use function series in$C^2$ to approximate $x(t)$.
The problem is, E-L equations only gives the local maximum value,so this proof actually doesn't work.
So I wanna know if the method above can be improve, or if there are other elementary methods(maybe without using Fourier series or too advanced functional analysis, only the undergraduate Mathematical analysis level)
to solve this problem.

A: WLOG: $a=0, b=\pi/2$.
We have:
$$\begin{align}
\int_0^{\pi/2} x^2(t)dt &= \int_0^{\pi/2} \left( \int_0^{t} \dot{x}(s)ds \right)^2dt
\\
&\stackrel{ \text{Holder}}{\le}\int_0^{\pi/2} \left( \int_0^{t} \dot{x}^2(s)\frac{1}{\cos (s)}ds \right)\left( \int_0^t \cos(s)ds \right) dt
\\
&= \int_0^{\pi/2} \int_0^t \dot{x}^2(s)\frac{\sin(t)}{\cos (s)}dsdt \\
&\stackrel{\text{Fubini}}{=} \int_0^{\pi/2}\int_{s}^{\pi/2}\dot{x}^2(s)\frac{\sin(t)}{\cos (s)}dtds
\\
&= \int_0^{\pi/2}\dot{x}^2(s)ds
\end{align}$$
QED.


text:
Q: Sql select rows containing part of string I want to write a comparation procedure (t-sql) for site seo.
I have a table with field 'url' (nvarchar()) that contain a part of site url's.
Ex: 'mysyte.com/?id=2'. Also this table for each url contains metadata, that i need to extract.
The main problem is that full url on site looks like 'mysyte.com/?id=2&region=0&page=1', and i just need to ignore everething, except url in table:
I mean: 'mysyte.com/?id=2' => is a part of 'mysyte.com/?id=2&region=0&page=1'

A: You can use the LIKE operator to compare the content of a T-SQL string, e.g.
SELECT * FROM [table] WHERE [field] LIKE '%stringtosearchfor%'

The percent character '%' is a wild card- in this case it says return any records where [field] at least contains the value "stringtosearchfor".

A: SELECT *
FROM myTable
WHERE URL = LEFT('mysyte.com/?id=2&region=0&page=1', LEN(URL))

Or use CHARINDEX
http://msdn.microsoft.com/en-us/library/aa258228(v=SQL.80).aspx

A: you can use CHARINDEX in t-sql.
select * from table where CHARINDEX(url, 'http://url.com/url?url...') > 0


text:
Q: 3-fingers Multi-Touch Support in Web Apps Is it possible to handle more than 2-finger touch events in Javascript? In my tests, events stop firing when a third finger is added. I created an example using jQuery and the official jQuery Plugin: Pointer Events Polyfill. Tested in Chrome and Microsoft Edge on Windows 10 Professional using a Wacom Cintiq 22HD Touch Monitor.
http://jsfiddle.net/po4a3e1L/2/
(function ($) {
    var pointers = [];

    $('#pointerTarget').on('pointerdown pointerover pointerenter', function (event) {
        var id = event.originalEvent.pointerId;
        if (!pointers[id]) {
            pointers[id] = $(`<div id="${id}"><p>pointerId: ${id}</p></div>`).appendTo('body');
        }
    });

    $('#pointerTarget').on('pointerup pointerout pointerleave', function (event) {
        var id = event.originalEvent.pointerId;
        if (pointers[id]) {
            pointers[id].remove();
            pointers.splice(id, 1);
        }
    });
})(jQuery);

A: This turned out to be an issue with my Wacom drivers. Under Touch Options there are two choices for Gesture Recognizer: Use Windows Gestures and Use Wacom Gestures. I had to select the former.


text:
Q: Adding SQL result table into mail message I want to add this table to e-mail message:
foreach ($songs as $key => $value) {
            echo "
" . ucfirst($key) . "	" . $value . "
";
        }

But something like this won't work:
$message = '

Hi, ' . ucfirst($name) . '

Heres the table

' .
                foreach ($songs as $key => $value) {
            echo "
" . ucfirst($key) . "	" . $value . "
";
        }
                . '

';

Thanks in advance! :)

A: The problem is you are echoing instead of appending.
$message = '

Hi, ' . ucfirst($name) . '

Heres the table

';
                foreach ($songs as $key => $value) {
            $message .= "
" . ucfirst($key) . "	" . $value . "
";
        }
$message .= '

';

A: Why not generate the table into a variable, and then included that into your message...
foreach ($songs as $key => $value) {
   $mytable .= "
" . ucfirst($key) . "	" . $value . "
";
}

$message = "blah blah" . $mytable . "blah blah";

A: You need to end the assignment of a value to $message, e.g.:
...

'; // stop here

THEN do your foreach, appending the results to $message via concatenation operator, e.g:
foreach ($songs as $key => $value) {
   $message .= '
' . ucfirst($key) . '	' . $value . '
';
}

THEN continue on with the $message string again:
$message = '

';


text:
Q: Setting value for each item in for loop to true or false I am trying to create a v-for that shows a list of exercises containing several sets. I have created a loop with a row for each set underneath each exercise.
my data looks like this.
const exercises = [
{ id: 1, name: exercise1, sets: 3 },
{ id:2, name: exercise2, sets: 2 }
{ id:3, name: exercise3, sets: 4 }
]

And my component looks something like this:
 <template v-for="exercise in exercises" :key="exercise.id">
    {{ exercise.name }}
    <template v-for="set in exercise.sets" :key="set">
       {{ set }}
    </template>
  </template>

Now I want to be able to mark each set as completed by setting the value on each set to either true or false through a click event. But I am not sure about how to do this since each set doesn't have a property to set a value because it's looping through a number.
What would be the right approach to this problem?

A: First and foremost, you can't loop through a number. To be able to loop the sets, you'd have to
<template v-for="let set = 0; set < exercise.sets; set++" :key="set">
     {{ set }}
</template>

However, setting a property on a number is equally impossible. You have to prepare your data to be able to make that adjustment:
const exercises = [
{ id: 1, name: 'exercise1', sets: 3 },
{ id: 2, name: 'exercise2', sets: 2 } ,
{ id: 3, name: 'exercise3', sets: 4 }
].map(exercise => ({
    id: exercise.id,
    name: exercise.name,
    sets: Array.from(
        { length: exercise.sets },
        () => ({ completed: false })
    ),
}))

A: You can create array with finished sets and compare it (try the snippet pls):

new Vue({
  el: "#demo",
  data() {
    return {
      exercises: [{ id: 1, name: 'exercise1', sets: 3 }, { id: 2, name: 'exercise2', sets: 2 }, { id: 3, name: 'exercise3', sets: 4 }],
      finishedSets: []
    }
  },
  computed: {
    checkAll() {
      return this.exercises.reduce((acc, curr) => acc + curr.sets, 0) === this.finishedSets.length
    }
  },
  methods: {
    compareObjects(o1, o2) {
      return Object.entries(o1).sort().toString() !== Object.entries(o2).sort().toString()
    },
    findObject(id, set) {
      return this.finishedSets.find(f => f.id === id && f.set === set)
    },
    completeSet(id, set) {
      this.findObject(id, set) ?
        this.finishedSets = this.finishedSets.filter(f => {return this.compareObjects(f, this.findObject(id, set))}) :
        this.finishedSets.push({id, set})
    },
    isFinished(id, set) {
      return this.findObject(id, set) ? true : false
    },
  }
})
.set {
  width: 70px;
  cursor: pointer;
}
.finished {
  background-color: seagreen;
}
.finished__not {
  background-color: tomato;
}

    {{ exercise.name }}

 {{ set }}
      finished

  <button v-if="checkAll">submit</button>

{{finishedSets}}


text:
Q: How to finish every activity on the stack except the first in Android I'm porting an iPhone app to Android and I can't seem to find a means to pop each activity on the stack except the root activity.
In objective-c I would do something like the below
[navController popToRootViewControllerAnimated:YES];

Anyone know if I can effectively call "finish()" on each activity after some action?

A: If you want to start one Activity, say, your homescreen, and remove every other Activity in your application's stack, you can use:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Removes other Activities from stack
startActivity(intent);

If you also want to provide this event in the MainActivity (such as a logo click in the title bar), you can add the FLAG_ACTIVITY_SINGLE_TOP flag as well to make sure it does not add another instance of itself to the stack.

A: Look at http://developer.android.com/reference/android/content/Intent.html#FLAG_ACTIVITY_CLEAR_TOP: you can startActivity on the root activity with this flag, and it will blow away all activities above it. You should read the docs carefully about the intent delivery behavior.


text:
Q: Laravel Vue web-notification component errors I am trying to display Notification Bar from component vue to layout/app.blade but errors occures in the console.

[Vue warn]: Error in created hook: "TypeError: Cannot read property 'userId' of undefined"

and,

TypeError: Cannot read property 'userId' of undefined

my app.js is like below.
require('./bootstrap');
window.Vue = require('vue');
window._ = require('lodash');
window.$ = window.jQuery = require('jquery');

Vue.component('estate', require('./components/EstateNotification.vue'));

const app = new Vue({
    el: '#app',
    data: {
        estates: '',
    },
    created(){
      if (window.Laravel.userId){
          axios.post('/notification/estate/notification').then(response => {
              this.estates = response.data;
              console.log(response.data)
          });

          Echo.private('App.User.'+ window.Laravel.userId).notification((response) => {
              data = {"data":response};
              this.estates.push(data);
              console.log(response);
          });
      }
    }
});

In my route:
Route::post('/notification/estate/notification', 'EstateController@notification');

Controller:
public function notification()
    {
        return auth()->user()->unreadNotifications;
    }

But I couldn't figure it, why is userId being undefined? where am I doing wrong? Really thanks for any help!

A: Try this in app.blade :
<div id ="app">
    <estate v-bind:estates="estates"></estate>
</div>

const app = new Vue({
       el: '#app'  //this ID
   });


text:
Q: Show AlertDialog on top of another AlertDialog I'm taking some personal details from user in a form which is actually a custom Alertdialog. Now when user presses Submit button present within the Alertdialog, if there is an validation error; I'm trying to display another Alertdialog with error message like Please Enter First Name.
What is happening is when 2nd Alertdialog is being displayed due to a validation error, the main Alertdialog (registration form) gets disappeared.
Any reason what might me causing this. Any help appreciated.
Edit
Please note that I have considered setError but I also have some other views like Spinner, RadioButton in my layout. So just using setError for EditText is not whole solution for my problem.

A: you can make the validation before dismissing the dialogue and setErrorText on the edittexts, so it is visible to the user, without leaving the view.

A: If displaying another dialog on the existing dialog is your Application's requirement then, i would recommend you to create a new activity just for displaying that custom alert dialog.
Add that activity to your Manifest and set the theme to "@android:style/Theme.Dialog".
<activity android:theme="@android:style/Theme.Dialog" android:name="LocationDialog"> </activity>

and onClick listener of your Dialog Interface just start the dialog activity for displaying the validation error.
 public void onClick(DialogInterface arg0, int arg1) {
         Intent errorDialog = new Intent(YourActivity.this, ErrorDialogActivity.class);
         startActivity(errorDialog);
  }


text:
Q: How to display date time in jquery count down clock? I have a database attribute "deadline" whose data type is date time in format "MM/dd/yyyy hh:mm:ss", requirement is to get date time from data base and pass it in count down clock which will show days, hours, minutes and seconds remaining. I go through these links: link1 and link2. And take code from link1. Include all files, but no count down clock is visible on browser. here is code:

    <title>Index</title>
    <link href="~/Content/jquery.countdown.css" rel="stylesheet" />
    <link rel="stylesheet" href="jquery.countdown.css">

Counting down to 26 January 2014.

Can any one please tell why this clock is not visible on browser and how can I achieve my above mention requirement?
Code will be appreciated. Thanks in advance.


text:
Q: Process requests with and without @RequestBody in the @Around advice I have such aspect-based logging:
@Pointcut("@annotation(Loggable)")
public void loggableAnnotation() {}

@Around("loggableAnnotation()")
public Object simpleProcess(ProceedingJoinPoint joinPoint) throws Throwable {
  return this.processWithBody(joinPoint, null);
}

@Around("loggableAnnotation() && args(@org.springframework.web.bind.annotation.RequestBody body,..)")
public Object processWithBody(ProceedingJoinPoint joinPoint, Object body) throws Throwable {
  // do things
}

And it works fine when I perform request with @RequestBody, advice processWithBody() is triggered. But when I perform request that doesn't have a @RequestBody (only @PathVariable and @RequestParam) the simpleProcess() is not triggered, instead in the processWithBody() I receive path variable value as the body parameter.
Why does it happen and how do I pocess two types of requests differently (in the same advice if possible)?

A: You are making three basic miskates:

*

*You are trying to match parameter argument annotations from within args(), but there it has no effect, which is why processWithBody(..) matches an unwanted parameter and binds it to body. It should be transferred to an execution() pointcut.

*Your pointcut syntax is wrong, even if you transfer it to execution(), i.e. something likeexecution(* *(@org.springframework.web.bind.annotation.RequestBody *, ..)) would match if the type(!) of the parameter has a @RequestBody annotation, not the parameter itself.In order to achieve that you need to put the parameter itself into parentheses like (*), i.e. execution(* *(@org.springframework.web.bind.annotation.RequestBody (*), ..)).

*You have to make sure that the pointcuts are mutually exclusive, otherwise multiple advices shall match on the same joinpoint. To be precise, you need to differentiate between the following cases:

*

*methods annotated by @Loggable with a first method parameter annotated by @RequestBody

*methods annotated by @Loggable with a first method parameter not annotated by @RequestBody

*methods annotated by @Loggable without any parameters

Here is an example in plain Java + AspectJ (no Spring or Spring AOP), but the aspect syntax should be identical in Spring AOP:
Annotation + driver application:
package de.scrum_master.app;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target(METHOD)
public @interface Loggable {}

package de.scrum_master.app;

import org.springframework.web.bind.annotation.RequestBody;

public class Application {
  public static void main(String[] args) {
    Application application = new Application();
    application.doNotLogMe("foo", 11);
    application.doNotLogMeEither();
    application.doNotLogMeEither("foo", 11);
    application.logMe("foo", 11);
    application.logMeToo("foo", 11);
    application.logMeToo();
  }

  public void doNotLogMe(@RequestBody String body, int number) {}
  public void doNotLogMeEither() {}
  public void doNotLogMeEither(String body, int number) {}
  @Loggable public void logMe(@RequestBody String body, int number) {}
  @Loggable public void logMeToo(String body, int number) {}
  @Loggable public void logMeToo() {}
}

Aspect:
As you can see, I am using the differentiating the three cases mentioned above and also satisfy your need for a common helper method which I called logIt(..). There you can put all the complex logging stuff you want to use without having any duplicate code in your advice methods.
package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAspect {
  @Pointcut("@annotation(de.scrum_master.app.Loggable)")
  public void loggableAnnotation() {}

  @Around(
    "loggableAnnotation() && " +
    "execution(* *())"
  )
  public Object simpleProcessWithoutParameters(ProceedingJoinPoint joinPoint) throws Throwable {
    return logIt(joinPoint, null);
  }

  @Around(
    "loggableAnnotation() && " +
    "execution(* *(!@org.springframework.web.bind.annotation.RequestBody (*), ..))"
  )
  public Object simpleProcessWithParameters(ProceedingJoinPoint joinPoint) throws Throwable {
    return logIt(joinPoint, null);
  }

  @Around(
    "loggableAnnotation() && " +
    "execution(* *(@org.springframework.web.bind.annotation.RequestBody (*), ..)) && " +
    "args(body, ..)"
  )
  public Object processWithBody(ProceedingJoinPoint joinPoint, Object body) throws Throwable {
    return logIt(joinPoint, body);
  }

  private Object logIt(ProceedingJoinPoint joinPoint, Object body) throws Throwable {
    System.out.println(joinPoint + " -> " + body);
    return joinPoint.proceed();
  }
}

Console log:
execution(void de.scrum_master.app.Application.logMe(String, int)) -> foo
execution(void de.scrum_master.app.Application.logMeToo(String, int)) -> null
execution(void de.scrum_master.app.Application.logMeToo()) -> null

P.S.: The difference between execution(* *(@MyAnn *)) and execution(* *(@MyAnn (*))) is subtle and thus tricky. Unfortunately, it is not properly documented here where it should be. To be precise, the latter case is not documented at all, only maybe in some AspectJ release notes and of course in unit tests. But no normal user would look there.


text:
Q: compact() issue with compass I have just started using compass and need to use it in a Fuel project so running compass create is not viable for me.
I have imported the files manually but it is putting compact() over all my mixins making them not work.
I have reinstalled the gem and still no luck.
Any ideas?

A: I think the likely problem is that the compact() function is defined in Ruby by Compass, so is not being included. The easiest solution is to reimplement the function in Sass.
Somebody else posted the appropriate solution here: "Compact" function in Bourbon with SASS not called


text:
Q: Check internet connectivity android in kotlin I tried the answer from this (the accepted answer). I can use the "PING" method but the UI went black since it says it will block the UI Thread. It didn't look good and was disturbing so I tried to use the second method "Connect to a Socket on the Internet" but I don't know how to use the class in Kotlin.
This is the result of converted Java to kotlin by android studio
package com.mockie.daikokuten.helpers

import android.os.AsyncTask.execute
import android.os.AsyncTask
import java.io.IOException
import java.net.InetSocketAddress
import java.net.Socket

internal class InternetCheck(private val mConsumer: Consumer) : AsyncTask<Void, Void, Boolean>() {
interface Consumer {
    fun accept(internet: Boolean?)
}

init {
    execute()
}

override fun doInBackground(vararg voids: Void): Boolean? {
    try {
        val sock = Socket()
        sock.connect(InetSocketAddress("8.8.8.8", 53), 1500)
        sock.close()
        return true
    } catch (e: IOException) {
        return false
    }

}

override fun onPostExecute(internet: Boolean?) {
    mConsumer.accept(internet)
}
}

but I DONT KNOW HOW TO USE IT. I tried this way:
InternetCheck{ internet-> Log.d("test", "asdasdas") }

It didnt work and results in an error. It says I have to pass "Consumer".
My question is How to use that class?

A: Add these permission on top in Manifest
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <uses-permission android:name="android.permission.INTERNET"/>

and this function should do the trick. It will return boolean based on its connectivity
fun isOnline(context: Context): Boolean {
    val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val n = cm.activeNetwork
        if (n != null) {
            val nc = cm.getNetworkCapabilities(n)
    //It will check for both wifi and cellular network
            return nc!!.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        }
        return false
    } else {
        val netInfo = cm.activeNetworkInfo
        return netInfo != null && netInfo.isConnectedOrConnecting
    }
}

It has a deprecated method as well as a latest one based on your api version.

A: Update:
Since Android 10 the use of the NetWorkInfo class and its methods are obsolete, now you must use the ConectivityManager class and getNetworkCapabilities () method from NetworkCapabilities Class.
How to check connectivity in Android?
Kotlin :
fun isOnline(context: Context): Boolean {
    val connectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (connectivityManager != null) {
        val capabilities =
            connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
                return true
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
                return true
            }
        }
    }
    return false
}

Java:
public static boolean isOnline(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager != null) {
        NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
        if (capabilities != null) {
            if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR");
                return true;
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI");
                return true;
            } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET");
                return true;
            }
        }
    }

    return false;
}

both methods require the permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>

A: Shortest version
val Context.isConnected: Boolean
    get() {
        return (getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager)
           .activeNetworkInfo?.isConnected == true
    }

A: Try this utility method to check for the availability of internet.
fun isNetworkAvailable(context: Context): Boolean {
        val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        var activeNetworkInfo: NetworkInfo? = null
        activeNetworkInfo = cm.activeNetworkInfo
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting
    }

Hope this helps.

A:
Check internet connectivity in android kotlin

fun isNetworkAvailable(context: Context?): Boolean {
    if (context == null) return false
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                    return true
                }
            }
        }
    } else {
        val activeNetworkInfo = connectivityManager.activeNetworkInfo
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected) {
            return true
        }
    }
    return false
}

A: I modified your class to this
internal class InternetCheck(private val onInternetChecked: (Boolean) -> Unit) :
AsyncTask<Void, Void, Boolean>() {
 init {
     execute()
 }

 override fun doInBackground(vararg voids: Void): Boolean {
     return try {
         val sock = Socket()
         sock.connect(InetSocketAddress("8.8.8.8", 53), 1500)
         sock.close()
         true
     } catch (e: IOException) {
         false
     }

 }

 override fun onPostExecute(internet: Boolean) {
     onInternetChecked(internet)
 }
}

So you could use lambda function and you also dont have to deal with null check in there:
InternetCheck{ internet-> Log.d("Connection", "Is connection enabled? "+internet) }

A: You can use it like this:
   InternetCheck(object : InternetCheck.Consumer {
      override fun accept(internet: Boolean?) {
         Log.d("test", "asdasdas")
      }
   })

For more infos you can see this thread:
https://youtrack.jetbrains.com/issue/KT-7770

A: Call the AsyncTask this way, it should work. You don't need to change anything in your InternetCheck AsyncTask. Basically you need to pass in an object that implements the Consumer interface that's defined in the InternetCheck class.
InternetCheck(object : InternetCheck.Consumer {
    override fun accept(internet: Boolean?) {
        Log.d("test", "asdasdas")
    }
})

A:  fun verifyAvailableNetwork(activity:AppCompatActivity):Boolean{
      val connectivityManager=activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
      val networkInfo=connectivityManager.activeNetworkInfo
      return  networkInfo!=null && networkInfo.isConnected
}

A: Monitoring Internet Connection in Realtime using LiveData - Kotlin
I came across this amazing tutorial on YouTube. We simply need to add a utility file which extends LiveData and can observe it in our Activity or Fragment.
Usage
    private lateinit var connectionLiveData: ConnectionLiveData

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityInternetConnectionTestBinding.inflate(layoutInflater)
        setContentView(binding.root)

        connectionLiveData = ConnectionLiveData(this)
        connectionLiveData.observe(this) { isNetworkAvailable ->
            isNetworkAvailable?.let {
                updateUI(it)
            }
        }
    }

Utility File
const val TAG = "MyTagConnectionManager"

class ConnectionLiveData(context: Context) : LiveData<Boolean>() {

    private lateinit var networkCallback: ConnectivityManager.NetworkCallback
    private val connectivityManager =
        context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
    private val validNetworks: MutableSet<Network> = HashSet()

    private fun checkValidNetworks() {
        postValue(validNetworks.size > 0)
    }

    override fun onActive() {
        networkCallback = createNetworkCallback()
        val networkRequest = NetworkRequest.Builder()
            .addCapability(NET_CAPABILITY_INTERNET)
            .build()
        connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
    }

    override fun onInactive() {
        connectivityManager.unregisterNetworkCallback(networkCallback)
    }

    private fun createNetworkCallback() = object : ConnectivityManager.NetworkCallback() {

        override fun onAvailable(network: Network) {
            Log.d(TAG, "onAvailable: $network")
            val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
            val hasInternetCapability = networkCapabilities?.hasCapability(NET_CAPABILITY_INTERNET)
            Log.d(TAG, "onAvailable: ${network}, $hasInternetCapability")

            if (hasInternetCapability == true) {
                // Check if this network actually has internet
                CoroutineScope(Dispatchers.IO).launch {
                    val hasInternet = DoesNetworkHaveInternet.execute(network.socketFactory)
                    if (hasInternet) {
                        withContext(Dispatchers.Main) {
                            Log.d(TAG, "onAvailable: adding network. $network")
                            validNetworks.add(network)
                            checkValidNetworks()
                        }
                    }
                }
            }
        }

        override fun onLost(network: Network) {
            Log.d(TAG, "onLost: $network")
            validNetworks.remove(network)
            checkValidNetworks()
        }
    }

    object DoesNetworkHaveInternet {

        fun execute(socketFactory: SocketFactory): Boolean {
            // Make sure to execute this on a background thread.
            return try {
                Log.d(TAG, "PINGING Google...")
                val socket = socketFactory.createSocket() ?: throw IOException("Socket is null.")
                socket.connect(InetSocketAddress("8.8.8.8", 53), 1500)
                socket.close()
                Log.d(TAG, "PING success.")
                true
            } catch (e: IOException) {
                Log.e(TAG, "No Internet Connection. $e")
                false
            }
        }
    }
}

A: Java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.util.Log;

public class ConnectionManager {

public static boolean isConnected(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    try {
        if (connectivityManager != null) {
            NetworkCapabilities capabilities;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR");
                        return true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI");
                        return true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET");
                        return true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
                        Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET");
                        return true;
                    }
                }
            } else {
                NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
                if (networkInfo != null) {
                    for (NetworkInfo info : networkInfo) {
                        if (info.getState() == NetworkInfo.State.CONNECTED) {
                            Log.i("Internet", "Internet is Connected.");
                            return true;
                        }
                    }
                }
            }
        }
    } catch (Throwable tr) {
        return false;
    }
    return false;
}

}

Kotlin
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build

val Context.isNetworkConnected: Boolean
get() {
    val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        manager.getNetworkCapabilities(manager.activeNetwork)?.let {
            it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                    it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                    it.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) ||
                    it.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
                    it.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
        } ?: false
    else
        @Suppress("DEPRECATION")
        manager.activeNetworkInfo?.isConnectedOrConnecting == true
}


text:
Q: how to switch between roles in spring-security I was struggling for days on how can I implement a switch between roles with one userAccount within a Spring Boot application via Spring Security.
There is an example in my case:
I have a class [UserAccount]{Id,username,password,isActive} and [Role]{Id,roleName,description} with which I'm implementing a successful simple login system with some @Secured RESTful methods.
My roles are: ADMIN, TEACHER & STUDENT
Now, I want to create a class for each role (e.g. StudentUser, TeacherUser, AdminUser) or something like that, to be able to add some new attributes which are not common between all users.
For example:

* A StudentUser will be related to Grades, Courses, Exams, etc.

* A TeacherUser will be related to departement, Course, ResearchTeam, etc.

* Or in some cases, a user with multiple roles (TEACHER & STUDENT) like a PhD student, want to switch between his frontend spaces (different views).
How can I deal with that in a best and efficient way? Thanks.

A: The problem is that you want to bind few entities together - Account, Person, Role. I would suggest you to separate them like this:

*

*Person - just basic data such as name

*Person can have an Account. Person without an Account cannot login.

*Student/Teacher/Admin has/is a Person - Student/Teacher/Admin contain info specific to each role. When designing this relationship, it's necessary to figure out whether a Person can have more Student/Teacher/Admin profiles of the same type (what if a Person has multiple studies). If you design it as a one-to-one relationship, it can be modeled as inheritance in Java (Student/Teacher/Admin is a Person).

In Spring Security, assign GrantedAuthority-s (roles) according to what (active) Student/Teacher/Admin relationships the Account's Person has.
In your frontent, you will see what roles the logged-in Person has and you can allow them to switch between the role based views.
Update
For clarification, this is what the class diagram could look like:

You don't need to have a separate class/table for roles, since roles are determined by the presence of Student/Teacher/Admin objects for a given Person. But if you need it for some reason, you can add it there - probably Account would have 1..n Roles.

A: Thank you all, I solved the problem by : inheriting from the Profile each role has it's own profile class, so the user will've multiple profiles.


text:
Q: Iterating through a JSON object to get specific values I wrote web app in flask to receive POST  request from another app in JSON format...
import os
from flask import Flask,request,json,abort

app=Flask(__name__)

@app.route('/webhook',methods=['POST'])
def webhook():
    if request.method == 'POST':
        print(request.json)
        return '',200
    else:
        abort(400)

if __name__=='__main__':
    app.run()

the data I get :
{'channel': {'address': '00000', 'name': "nobody's Talking": 0000", 'uuid': 'fec375b2-d025-4a89-8688-2b1785dfb5d4'}, 'contact': {'name': 'Nets', 'urn': 'tel:+256704909243', 'uuid': 'af7065f4-192f-4a3a-9e08-75828394fb99'}, 'flow': {'name': 'webhook-test', 'revision': 4, 'uuid': '5041343f-4364-4518-a000-f4a4a7ff657f'}, 'input': {'attachments': [], 'channel': {'address': '00000', 'name': "nobody's Talking: 00000", 'uuid': 'fec375b2-d025-4a89-8688-2b1785dfb5d4'}, 'created_on': '2020-01-28T10:48:57.778339+03:00', 'text': 'whtest', 'type': 'msg', 'urn': {'display': '0704 909243', 'path': '+254704888680', 'scheme': 'tel'}, 'uuid': '554e6bfb-695e-4692-94ff-7ea9bfd936d0'}, 'path': [{'arrived_on': '2020-01-28T10:48:57.778606+03:00', 'exit_uuid': '', 'node_uuid': '23c305fb-da32-4217-9cf0-9bbf5d70ae56', 'uuid': '3a18d969-4880-484a-826a-60f18483623e'}], 'results': {}, 'run': {'created_on': '2020-01-28T10:48:57.778600+03:00', 'uuid': '32ec37f1-1ef6-4460-af89-305903114096'}}

I want to iterate through this json object and retrieve only three items from the object. I have not worked with json before. Here is my attempt
def rp_webhook():
    if request.method == 'POST':
        results=(request.json)
        for i in jsonobj['results']:
            print(i['date created'],['flow'],['display'])
        return '',200
    else:
        abort(400)

A: I was able to retrieve the specific items from the JSON... with this code
def rp_webhook():
    if request.method == 'POST':
        results= request.json
        x=json.dumps(results)
        y=json.loads(x)


text:
Q: Is this .NET Framework bug with Me.Top? I think I have found a bug when setting or getting the Me.Top property of a form.
I am using VS2010 VB.NET .NET framework 4.0
My monitor setup is slightly unusual:

*

*Primary 1600 x 900

*1680 x 1050

*1680 x 1050

On monitor number 1 everything works as expected. On monitor 2 or 3 if I set Me.Top = 0 then the form appears 150 pixels from the top of the screen so it thinks that it is using the resolution of the primary monitor.
I have to set Me.Top = -150 to get the form to the top of the screen.
Has anyone seen this before / know of a fix or workaround?

A: It's not a bug. The coordinate system is related to the primary screen.
In your layout of screens the screens 2 and 3 has their top bound "higher" than the screen 1 (the primary screen).
If you want layout your window to the top bound of the screen, you should use the Screen class.


text:
Q: What do "core wages" mean in this context? Does it mean "wages for core employees, such as full-time employees?
Does The Economist think that a rise in wages of peripheral workers would push up the wages of core workers  in Japan? or Does it mean "basic wages for all employees" in Japan?
Market forces do not affect large swathes of Japan's workforce. The pay of full-time workers in big firms is not responsive to labour-market tightness, according to a study published by the BoJ. These beneficiaries of life-time employment do not fear layoffs in hard times and cannot expect pay rises in good. But these workers do demand higher pay to offset past inflation. So, if peripheral workers' pay rises by enough to lift consumer prices a little, that will eventually result in stronger core wages, adding to inflationary momentum.
Wanted: stroppier employees, The Economist, April 8 issue
http://www.economist.com/news/finance-and-economics/21720282-high-employment-combined-undemanding-workers-japans-labour-market

A: Core wages isn't really a thing but has some use as an expression. In the cited Economist article, it's obviously the wages of the core workers mentioned earlier in the same paragraph. Normally, it will be the core part of any worker's wages but the more common expression is base pay or wages.


text:
Q: Trouble Understanding Definition: Expected Value I'm having a little bit of trouble understanding the definition below, in which the full text can be found at: https://github.com/mtomassoli/papers/blob/master/inftheory.pdf
Definition 3. If $X$ is a random variable and $f$ a function, then $Z=f(X)$ is a random variable such that, for all $z$,
$$\begin{align}
p(z)&=~P(Z=z)\\&=~P(f(X) =z)\\&=~P(X \in f^{-1}(z)) \\&=~\sum_{x:f(x)=z}p(x)
\end{align}$$
I'm having trouble understanding the logic behind the last two bits $f^{-1}(z)) =\sum_{x:f(x)=z}p(x)$, including what the notation $x:f(x)=z$ means. Thanks y'all :-)

A: Summing up the comments:

*

*$\sum_{x: f(x)=z}$ refers to summing over all values $x$ such that $f(x)=z$ (and presumably, you are working with discrete random variables so that the range is countable).

*It is not $f^{-1}(z)$ but $P(X\in f^{-1}(z))$ that is equal to the following sum (but this may have been a typo...).

*$f(X)=z$ if and only if $X\in f^{-1}(z)$, where $f^{-1}(z)$ is the inverse image of $z$, i.e. the set $f^{-1}(z):=\{y:f(y)=z\}$.


text:
Q: Vue plugin from CDN raises error - Unknown custom element:  - did you register the component correctly? I'm trying to use vue-js-grid using CDN but it raises an error.
Can you help me to import it?
https://www.jsdelivr.com/package/npm/vue-js-grid
This is in my html
<script src="https://cdn.jsdelivr.net/npm/vue-js-grid@1.0.1/dist/index.js"></script>

<grid ... >...</grid>

JS raises:
[Vue warn]: Unknown custom element: <grid> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I tried also
Vue.use(Grid)

JS raises:
(index):519 Uncaught ReferenceError: Grid is not defined
    at (index):519


text:
Q: Общий член ряда Тейлора Никак не получается найти общую формулу для вычисления n элементов. Нашел зависимость Un = x^(2*n) / 2n!, но к сожалению она не подходит к первому элементу.

A: Не тянет на ответ, но как вставить в комментарий формулу?...

Только вы спросили, как лучше держать микроскоп при забивании гвоздей, а не как забить гвоздь. Мне так кажется...
Если вы начнете при программировании вычислять каждый член по общей формуле - значит, мне не кажется :)
Намек:

A: Она подходит, потому что 0! считается равным 1, а x^0=1.
И умноженное на (-1)^n.
U(2n+2)=-u(2n)*x*x/(2n+1)(2n+2)


text:
Q: fix header on mobile version at our site www.ftina-pc.gr (prestashop based) I need to align the mobile menu with the logo.
I have tried float etc but can't find a way to fix this.
The desktop version is OK. only the mobile version has the problem.
I have attached a mockup on how it should look.
Can anyone please help me ?
Kind Regards

A: display:inline-block; on both elements and give them fixed percentage width. Post your code if you want more detail from someone

A: @media (min-width: 700px) {
    // something
}

And so on have you tried to do different styles for mobile and desktop? That might be problem.

A: So to solve this I did this (always under @media (max-width: 768px):
#logo-theme.logo-theme {width:80%;}
.pts-megamenu .navbar .navbar-header .navbar-toggle {
    margin-top: -60px !important;
    z-index: 99;
}
.pts-megamenu .navbar{min-height: 0px !important}

Hope this makes sense.
Seems to work though. if Anyone cares to look at the code it is would be great!
thanks everyone


text:
Q: Intuition about the lack of a quadratic term in geometric expansions Let $(\Sigma,g)$ be a Riemannian 2-manifold and let $p\in\Sigma$. It turns out that the circumference $C(r)$ of a geodesic circle $S_r(p)$ of radius $r$ around $p$ satisfies
$$
C(r)=2\pi r-\frac{\pi}{3}Kr^3+O(r^4),
$$
where $K$ denotes the Gaussian curvature of $\Sigma$ in $p$. On the other hand, if $\gamma$ is a smooth arc length parametrized curve in $\Sigma$ with $\gamma(0)=p$, then the geodesic distance from $p$ to $\gamma(t)$ satisfies
$$
d(p,\gamma(t))=t-\frac{k_g^2}{24}t^3+O(t^4),
$$
where $k_g$ denotes the geodesic curvature of $\gamma$ in $p$. Now here's the question. Can somebody give me an intuitive reason why there are no quadratic terms in these expansions? At least for the second expansion I have a vague idea why this is plausible but maybe there is a neat explanation for this. Of course, the proofs of the statements "explain" somehow, that/why there are no quadratic terms but I'm really looking for some heuristics/an intuitive explanation.

A: (1) Consider $$  f(0)=f'(0)=0,\ f(t)=f(-t),\ f'(t)>0\ (t>0)$$
With $t=0$, we rotate $f$. Then $$ r(s):={\rm length}\ \{ (t,f(t))|
0\leq t\leq s \} =\int_0^s \sqrt{ 1+(f')^2 },\ r'(0)=1 $$
If $f'(t)=c_1t+c_2t^2+\cdots$ (cf. Taylor series), $$r(s)=\int_0^s
(1+c_3t^2 + c_4t^3 +\cdots )\ dt =s+c_5s^3 +\cdots $$
(2) That is in the revolution surface (i.e., fixed point is
corresponded to $t=0$), length of geodesic sphere of radius $r$ is
$$ l(r)/(2\pi )=s= r - c_6 r^3 + \cdots
$$
(3) Consider two spheres $S^2(r),\ S^2(R),\ r< R $ If $M$ is a
surface and if curvature $K$ at $p\in M$ has $K(p)>0$, then for
given $\epsilon >0$, we have $\delta$ s.t. on $B_\delta (p)$,
$$ |K-K(p) | <\epsilon
$$
So we have $$ \frac{1}{R^2} < K < \frac{1}{r^2} $$
That is three surfaces are tangent at fixed point and on
$\delta$-balls except fixed point do not intersect. So intuitively
$$ l_{S^2(r)} (t) < l_M (t) < l_{S^2(R)} (t) $$
That is $M$ does not have quadratic term


text:
Q: Remote connect to SQL server - trusted connection, windows credentials Sorry for the confusing name, I did not know of better one. There is a network with SQL 2005 server. I am provided with the windows account information to this computer so I can use remote desktop or map its drives. The SQL uses trusted connection. I am thinking whether I can connect remotely only to the SQL server? Thanks

A: This is based on my experience with SQL Server, but may not be entirely complete in scope.
SQL Server Manager will let you connect to the server instance with windows credentials, but to access the database tables you will need to create a login within SQL Server. Using SQL Server Manager, you can do this under the Security folder of the hierarchy of objects in the left column.
Next you will need to create a database (if one doesn't already exist that you are interested in using) and in that database's Security folder, create a user that corresponds to the login. When doing this you will also need to assign the permissions of the user (select, insert, delete, etc.).
Once that is complete, you can access the server anywhere on the network with the appropriate credentials, but you will need to make sure that there are no blocked ports, etc. from a network perspective.
In C# the statement to create a new connection looks like this:
SqlConnection conn = new SqlConnection("user id = username; " +
    "password = secret; " +
    "server = servername\sqlexpress; " +
    "database = databasename; " +
    "connection timeout = 30");

Hope that helps.


text:
Q: Spark : java.lang.NoClassDefFoundError: com/mongodb/hadoop/MongoInputFormat I'm trying to read data from mongodb with spark using mongo-hadoop connector.
I tried different versions of hadoop-mongo connector jar but still getting this error.
There's no error during the compile time
What can i do to resolve this??
Thanks in advance.
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/hadoop/MongoInputFormat
    at com.geekcap.javaworld.wordcount.Mongo.main(Mongo.java:47)
Caused by: java.lang.ClassNotFoundException: com.mongodb.hadoop.MongoInputFormat
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

My Code
     import com.mongodb.hadoop.BSONFileOutputFormat;
    import com.mongodb.hadoop.MongoInputFormat;
    import com.mongodb.hadoop.MongoOutputFormat;
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.LinkedList;
    import java.util.Queue;

    import org.apache.hadoop.conf.Configuration;
    import org.apache.spark.SparkConf;
    import org.apache.spark.api.java.JavaPairRDD;
    import org.apache.spark.api.java.JavaRDD;
    import org.apache.spark.api.java.JavaSparkContext;
    import org.apache.spark.api.java.function.FlatMapFunction;
    import org.bson.BSONObject;

public class MongoTest {
    // Set configuration options for the MongoDB Hadoop Connector.
public static void main(String[] args) {
 SparkConf conf = new SparkConf().setMaster("local").setAppName("App1");

    JavaSparkContext sc = new JavaSparkContext(conf);

    Configuration mongodbConfig;
    mongodbConfig = new Configuration();

    mongodbConfig.set("mongo.job.input.format", "com.mongodb.hadoop.MongoInputFormat");
    mongodbConfig.set("mongo.input.uri","mongodb://localhost:27017/MyCollectionName.collection");

    JavaPairRDD<Object, BSONObject> documents = sc.newAPIHadoopRDD(
            mongodbConfig, // Configuration
            MongoInputFormat.class, // InputFormat: read from a live cluster.
            Object.class, // Key class
            BSONObject.class // Value class
    );

    documents.saveAsTextFile("b.txt");
  }
 }

pom.xml dependencies:

    <!-- Import Spark -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>1.4.0</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.0.4</version>
    </dependency>
    <dependency>
        <groupId>hadoopCom</groupId>
        <artifactId>com.sample</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>/home/sys6002/NetBeansProjects/WordCount/lib/hadoop-common-2.7.1.jar</systemPath>
    </dependency>

       <dependency>
        <groupId>hadoopCon1</groupId>
        <artifactId>com.sample1</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>/home/sys6002/Downloads/mongo-hadoop-core-1.3.0.jar</systemPath>
    </dependency>
</dependencies>

A: After several trails & changes, got this worked.
   <dependencies>
              <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-sql_2.11</artifactId>
            <version>1.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>1.5.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.14</version>
        </dependency>
        <dependency>
            <groupId>org.mongodb.mongo-hadoop</groupId>
            <artifactId>mongo-hadoop-core</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>

Java code
  Configuration conf = new Configuration();
    conf.set("mongo.job.input.format", "com.mongodb.hadoop.MongoInputFormat");
    conf.set("mongo.input.uri", "mongodb://localhost:27017/databasename.collectionname");
    SparkConf sconf = new SparkConf().setMaster("local").setAppName("Spark UM Jar");

    JavaRDD<User> UserMaster = sc.newAPIHadoopRDD(conf, MongoInputFormat.class, Object.class, BSONObject.class)
            .map(new Function<Tuple2<Object, BSONObject>, User>() {
                @Override
                public User call(Tuple2<Object, BSONObject> v1) throws Exception {
                    //return User
                }

            }


text:
Q: Node React app / error handling : How to send custom error for login when wrong email provided? Sorry for this probably very basic question but I dont fully understand error handling.
I have a login route. I want to send an error msg for example the case where a wrong email is provided
const user = await User.findOne({email})
if (!user) return res.status(404).send({error: "email not found"});

However that one is never received in my client. The only err I see when i log it is
[AxiosError: Request failed with status code 404]

How do I do it? Thanks !!
const authReducer = (state, action) => {
    switch (action.type) {
        case 'add_error':
            return {...state, errorMessage: action.payload}
        case 'signin_success':
            return {errorMessage: '', token: action.payload}
        default:
            return state;
    }
};

const login = dispatch => async ({email, password}) => {
    try {
        const response = await API.login(email, password); // I also tried to put in outside the try block to maybe then get the err msg in the response but didnt
        await AsyncStorage.setItem('token', response.data.token);
        dispatch({type: 'signin_success', payload: response.data.token});
        Navigation.navigate('Tabs', { screen: 'Home' });
    } catch (err) {
        dispatch({type: 'add_error', payload: 'Something went wrong with signing up'})
    }
};

let API = {
    login: (email, password) => {
        return BaseAPI.post('/login', {email, password})
    }
}

route handler
   app.use(router.post('/login', (req, res) => {
        const { email, password } = req.body;
        if (!email || !password) {
            return res.status(422).send({error: "-Must provide email and password"})
        }
        const user = await User.findOne({email})
        if (!user) return res.status(404).send({error: "email not found"});
        try {
            await user.comparePassword(password);
            const token = jwt.sign({userId: user._id}, 'MY_SECRET_KEY')
            res.send({token});
        } catch (err) {
            return res.status(422).send({error: 'Invalid password or me'});
        }
    }


text:
Q: How do I import a second photo library into iCloud Photos? Since my MacBook doesn't have enough disk space for all my photos, I took an external USB HDD and created a second photo library. That was back then with Aperture. Now I have moved to the new Photos app and the iCloud photo library.
How do I move the pictures from the external HDD library to iCloud Photos? The Photos app refuses to use iCloud Photos when switching to the external library:

A: I have two solutions now. First, there seems to be some software out there, namely Powerphotos, which can manage multiple libraries for the Photos app.
Second, one can select the external library as the system library and then sync it with iCloud. This is obviously a bit stupid if you want to keep the libraries separate. But in my case this is ok, since I merely want to get all my pictures into the iCloud Photos.
If you still need multiple libraries, you probably should use PowerPhotos and copy pictures from the dedicated libraries to the system library using that tool.


text:
Q: How to open and read number of files in the same directory and how to define global variable to read files I want to open and read number of files in the same directory one by one. and perform two functions on them. I'm facing two problems:
1 I don't know how to define a global variable for the threshold_file which used in another function as well.
2 This code returns the name of the files correctly but an error occurred
for file in os.listdir("C:/Users/Mariam/PycharmProjects/Group/Copy"):
        if file.endswith('b.txt'):
            threshold_file = open(file,'r')
            readThreshold_file()
            position_comparisonFn()

threshold_file = open(file,'r')

FileNotFoundError: [Errno 2] No such file or directory: '1000b.txt'

A: The file variable in your code only stores the file name.
But while opening a file you should provide the relative path as well.
In your case just append C:/Users/Mariam/PycharmProjects/Group/Copy to the file variable and your code will work fine.

A: First - Declare the file variable as a global outside of the function as follows (without quotes)
"global threshold_file". Then specify to the function that you are using a global variable.
Second - Should be same as 'Shrey's comment'. Detailed below
def func1():
    global threshold_file
    for file in os.listdir("C:/Users/Mariam/PycharmProjects/Group/Copy"):
        if file.endswith('b.txt'):
            threshold_file = open("C:/Users/Mariam/PycharmProjects/Group/Copy/"+file,'r')
            readThreshold_file()
            position_comparisonFn()

def func2():
    global threshold_file
    ...
    ...

A: For your two questions:
1. To define a global variable for the threshold_file
Outside of the functions, usually at the top of the code after your 'imports' section, setup your 'global' variables that you want to share like so:
# Globals
threshold_file = ""

Then, in each function that you want to use that variable, you have to tell Python that you want to use that 'global' variable with the global prefix, like so:
def foo():
    global threshold_file  # Here
    for file in os.listdir("C:/Users/Mariam/PycharmProjects/Group/Copy"):
        if file.endswith('b.txt'):
            threshold_file = open(file,'r')
            readThreshold_file()
            position_comparisonFn()

Note: You can use the variable without the global prefix, but you'll just have read-only access. In the foo function above, you need it, since you intend to update/write-to the value
2. Error
Store the "C:/Users/Mariam/PycharmProjects/Group/Copy" as a var, perhaps as a global, now that you know how
p = r"C:/Users/Mariam/PycharmProjects/Group/Copy"  # prefix with 'r' for literal string

and use the var in your open() function
...
threshold_file = open(p + r'/' + file,'r')  # 'file' is just the filename... need the full path
...


text:
Q: Spring JMS message converters with extended messages classes Using Spring boot 1.5.9 and JMS 2.0.1 with Java 9.0.....
Talking with IBM's MQ (version 9) with their MQQueueConnectionFactory which delivers to an @JmsListener an com.ibm.jms.JMSMessage that extends the javax.jms.Message class.  This means the normal type reflection by a MessageConverter isn't used.  Not sure where in the Spring JMS pipeline I can transform the JMSMessage into a normal Message and then activate conversion?  When testing I would like to use an embedded active mq that produces Message objects not JMSMessage.
Thus it would be great if the annotated receiver method accepted Message not JMSMessage.
Update 1
The following signature has to be used otherwise the Spring pipeline fails with no defined MessageConverter for a IBM JMSMessage:
@JmsListener(destination = "${mq.queue}")
public void receive(
  JMSMessage message,
  @Header(JmsHeaders.MESSAGE_ID) String messageId
) ... {
   ....
}

I want to have a signature that looks like:
@JmsListener(destination = "${mq.queue}")
public void receive(
  Message message,
  @Header(JmsHeaders.MESSAGE_ID) String messageId
) ... {
   ....
}

Otherwise, when testing (with an embedded jms queue manager) the receiving method doesn't have a consistent signature.  Must exist a spot in the Spring JMS pipeline (e.g. MessageListener) where I can intercept the JMSMessage, pull out it's delegate Message and send that onto the JmsListener.
Update 2
False alarm.  Redid tests with a live configuration and a receive signature that accepts a plain java.jmx.Message and just as M.D. pointed out it worked.  As well, the default simple message converter that uses the ClassUtils to turn the underlying JMSTextMessage into a string.


text:
Q: Android hide status bar, compatibility I have the following code to hide the status bar taken from http://developer.android.com/training/system-ui/status.html and Hide status bar android
    //hide statut bar
    if (Build.VERSION.SDK_INT < 16) { //ye olde method
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    } else { // Jellybean and up, new hotness
        View decorView = getWindow().getDecorView();
        // Hide the status bar.
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
        // Remember that you should never show the action bar if the
        // status bar is hidden, so hide that too if necessary.
        ActionBar actionBar = getActionBar();
        actionBar.hide();
    }

I get an error on View.SYSTEM_UI_FLAG_FULLSCREEN;
it seems that SYSTEM_UI_FLAG_FULLSCREEN doesn't exist anymore in View.
How to fix it? please thanks you

A: It exists since API16. You must build your app against API16 (or higher)


text:
Q: In proxy mediation get-property('To') returns unexpected value I have a strange problem with WSO2 ESB mediation.
Product version: WSO2 ESB 4.5.1
The mediation code is look like this:
<proxy xmlns="http://ws.apache.org/ns/synapse" name="CacheWSAPrx" transports="https,http" statistics="disable" trace="enable" startOnLoad="true">
   <target>
  <inSequence>
     <log level="full">
        <property xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" name="WSA_To" expression="get-property('To')"/>
     </log>
     <send>
        <endpoint>
           <address uri="http://localhost:9083/TestCacheWeb/sca/MaketWSSoapExport1"/>
        </endpoint>
     </send>
  </inSequence>
  <outSequence>
     <send>
        <endpoint>
           <default/>
        </endpoint>
     </send>
  </outSequence>
 </target>
 <publishWSDL key="conf:/repository/wsdl/service.wsdl"/>
 <description></description>
 </proxy>

When I try to invoke this service with soapUI 4.0.1 the log mediator prints that the WSA_To property value (filled by get-property('To') function) is /services/CacheWSAPrx. This is strange and unexpected for me because the SOAP request, sended via soapUI contains another value in To header:
<soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Action>http://eisgkh.ru/maket/ws/Maket.WS2.Service.Action</wsa:Action><wsa:To>http://www.exampleaddr.com</wsa:To></soapenv:Header>

So, my question is: why the get-property('To') returns /services/CacheWSAPrx value, I think that it must return http://www.exampleaddr.com?

A: No. If you want to get http://www.exampleaddr.com, get-property is not the required expression. Follow http://rajikak.blogspot.com/2010/04/xpath-functions-and-properties-avilable.html . You may need something like $header/wsa:To to get what you want. When get-property is used it gets a property from MessageContext as I think.


text:
Q: Detect mentions joined by commas in php I have a string like this:
*"Hola @user1,@user2. ¿Que tal ayer con@user3 en #el_parque?"*

I want to extract the @mentions and analyze if user exists. If not exists i will remove the @ tag.
how can i parse the string?
I develop on this function
if(!empty($Timeline)){
        $CI =&get_instance();

        $words = explode(" ", $Timeline);
        $renderTimeline = "";

        $patternu = '@([a-zA-Z09]+)';
        $patternm = '/([#]{1})([a-zA-Z0-9\_]+)/';

        if(!isset($CI->usuarios_model)){$CI->load->model('usuarios_model');}
        if(!isset($CI->juegos_model)){$CI->load->model('juegos_model');}

        foreach($words as $word){
            if(preg_match($patternu,$word)){ //mencion
                $word = preg_replace($patternu, '$0', $word);
                echo $word;
                $usuario = $CI->usuarios_model->get(null,preg_replace($patternu, '\2', $word));
                if(!$usuario){$word = substr($word,1);}
            }elseif(preg_match($patternm,$word)){ //juego
                $juego = $CI->juegos_model->existJuego(null,preg_replace($patternm, '\2', $word));
                if(!$juego){$word = substr($word,1);}
            }

            $renderTimeline.=" ".$word;
        }

        return trim($renderTimeline);
    }

A: You can use REGEX for this, something like "@([a-zA-Z09]+)" should do the trick. Later on if your user does not exist, just replace matcher.group() with matcher.group(1). First one has the whole captured string with @ and second one has only first group (eg.username without @)

A: Check this out:
$string =  "Hola @userA,@userB. ¿Que tal ayer con@userC en #el_parque?" ;
$matches = array() ;
$pattern = "/@[a-zA-Z0-9]+/" ;

preg_match_all($pattern, $string, $matches);

var_dump($matches[0]);


text:
Q: Cordova, Android, deprecated Gradle features, incompatibility Yes, I am aware of this thread: Cordova - Android - Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0
Its "solution" does not work for me!  Hence the reason I'm posting here.
I am getting a "Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0" error message when I try "cordova build android" on my Cordova Android project.
My current config:
Cordova:  11.0.0
Gradle:   7.5.1 (it was 6.8.3 before I upgraded per the advice of the thread I linked)
Java:     11.0.16-amzn (I have tried several others, both v8.x and 11.x)
Computer: Mac mini (M1, 2020)
OS:       macOS Monterey (version 12.1)

BTW, I am using the export CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL=https\://services.gradle.org/distributions/gradle-7.5.1-all.zip trick in my .zshrc file to force Cordova to use Gradle version 7.5.1, otherwise it downloads and installs Gradle 7.1.1 when I run "cordova build android" (and that also fails with this same stupid "Deprecated Gradle features..." error).
I have been searching for HOURS now with no luck.  I still get that stupid "Deprecated Gradle features.." error message, no matter what I try.
It tells me to use '--warning-mode all' to "show the individual deprecation warnings and determine if they come from your own scripts or plugins" but when I try "cordova build android --warning-mode all" it gives me an error message: "The platform 'all' does not appear to have been added to this project.
So I have two questions:

*

*does anyone know how to make this stupid thing build?  What version of Gradle do I need?  Is there something else I need to upgrade to make it work?  Why is this happening all of the sudden?  I've built many apps before with zero problems, and I've changed literally nothing on my system, yet somehow this app is giving me this error.

*if not, does anyone know how to make cordova build with "--warning-mode all" so I can at least see what specific thing is causing this "deprecated" error?
Thanks

A: This is a warning and not an error; can be ignored unless building with Gradle 8.0. And even if, --warning-mode all has no meaning unless you'd provide the relevant console output. Most often the cause are outdated Gradle plugins. For Gradle 8.0 there might be a new version of Cordova.
./gradlew :assembleDebug --warning-mode all

One can also define --warning-mode all for run configurations (GUI).

A:
So when you see this, what do you think is causing the problem, hmmm?  The "Build Failed" message occurs IMMEDIATELY after the Gradle message.  So you'd assume that Gradle is causing the problem, no?
APPARENTLY NOT!!!
cordova build android --verbose gives me MANY more error messages -- including the one that actually fixed the problem.  The cordova-plugin-barcodescanner plugin I was using is supposed to require some code added to config.xml:
<config-file target="AndroidManifest.xml" parent="/*" mode="merge">
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
</config-file>

But apparently that is repeated somewhere else because the ACTUAL error that was stopping the build was Element uses-feature#android.hardware.camera at AndroidManifest.xml:39:5-85 duplicated with element declared at AndroidManifest.xml:35:5-60
Once I removed that code from the config.xml file, it finally builds successfully.
Good Lord, how ridiculous!!


text:
Q: Querying MySQL database for unique counts of column values I have a table structure that is similar to the following:
Table: poll_answers
----------------------------------------------------------------
| LONG id | LONG question_id | LONG user_id | TEXT answer      |
----------------------------------------------------------------

Users' answers to a poll gets stored into the database as such. poll_answer is a string and many answers by different users can be the same.
I would like to query the database to list the number of each unique poll_answer.
Example of a poll question with id 123 may be:

What month was xyz born in?

The database might look like this:
----------------------------------------------------------------
| LONG id | LONG question_id | LONG user_id | TEXT answer      |
----------------------------------------------------------------
| 0       | 123              | 1000         | monday           |
| 1       | 123              | 1001         | tuesday          |
| 2       | 123              | 1003         | monday           |
| 3       | 123              | 1002         | monday           |
| 4       | 123              | 1004         | thursday         |
| 5       | 123              | 1025         | monday           |
----------------------------------------------------------------

How can I query the database such that I get a list like this:
monday => 4
tuesday => 1
thursday => 1

The only one I can think of uses n number of queries where n is the number of different possible poll_answer.
SELECT UNIQUE answer FROM poll_answers

For each of the result,
SELECT COUNT(*) FROM poll_answers where answer = {the_answer}

Is there a more efficient way?
EDIT:
As a bonus, I would also like to know if efficiency-wise, it would be a good practice to generate and store a hash (MD5) of answer in the table and group by the hash instead.

A: try this:
SELECT answer,COUNT(*) as uniqans FROM poll_answers group by answer

A: If you need to get answers for ALL questions then try to use this query. It also orders answers for each query by popularity :
SELECT question_id,
       answer,
       COUNT(*) as answerCount
   FROM poll_answers
   GROUP BY question_id, answer
   ORDER BY question_id, answerCount DESC

SQLFiddle demo


text:
Q: In Modern OpenGL, drawing filled circle with GL_TRIANGLE weird z-axis behaviour I am trying to draw filled circle in modern opengl using GL_TRIANGLE. I am filling circle array for circle vertices, and then I am filling points array using circle vertices to use vertices in triangle.I am using vec4(homogeneous coordinates) and setting vertices z-axis value to 0.0 and using default projection which should be from -1 to 1 ranges for each axis. But somehow, I am getting all screen painted with color instead of circle. Weirdly when I set z-axis value of points other than [0-0.4] range, I can get circle be drawn and when I increase the value of z, it acts like perspective and no matter what I have set to radius, it is getting smaller when z is increased. I could not figure out why z value acts like that.
using namespace Angel;

const int NumVertices = 90;
const double PI = 3.141592653589793238463;

const GLint width = 500;
const GLint height = 500;

vec4 points[NumVertices];
vec4 colors[NumVertices];

vec4 circle[30];
vec4 color = { 1.0,0.0,0.0,1.0 };
vec4 center = { 0.0,0.0,0.0,1.0 };

GLfloat radius = 0.5;

int Index = 0;

void triangle(int b, int c) {
    colors[Index] = color; points[Index] = center; Index++;
    colors[Index] = color; points[Index] = circle[b%30]; Index++;
    colors[Index] = color; points[Index] = circle[c%30]; Index++;
}

void fill() {
    for (int i = 0; i < 30; i++)
    {
        float angle = 2 * PI * i / 30;
        vec4 point;
        point.x = center.x + (GLfloat)cos(angle) * radius;
        point.y = center.y + (GLfloat)sin(angle) * radius;
        point.z = 0.0 ; // PROBLEM !!
        circle[i] = point;
    }

    for (int i = 0; i <= 29; i++) {
        triangle(i, i + 1);
    }
}

void init()
{
    fill();

    // Create a vertex array object
    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    // Create and initialize a buffer object
    GLuint buffer;
    glGenBuffers(1, &buffer);
    glBindBuffer(GL_ARRAY_BUFFER, buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(points) + sizeof(colors),
        NULL, GL_STATIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(points), points);
    glBufferSubData(GL_ARRAY_BUFFER, sizeof(points), sizeof(colors), colors);

    // Load shaders and use the resulting shader program
    GLuint program = InitShader("vshader.glsl", "fshader.glsl");
    glUseProgram(program);

    // set up vertex arrays
    GLuint vPosition = glGetAttribLocation(program, "vPosition");
    glEnableVertexAttribArray(vPosition);
    glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0,
        BUFFER_OFFSET(0));

    GLuint vColor = glGetAttribLocation(program, "vColor");
    glEnableVertexAttribArray(vColor);
    glVertexAttribPointer(vColor, 4, GL_FLOAT, GL_FALSE, 0,
        BUFFER_OFFSET(sizeof(points)));

    glEnable(GL_DEPTH_TEST);
    glClearColor(1.0, 1.0, 1.0, 1.0);
}
void myDisplay(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glDrawArrays(GL_TRIANGLES, 0, NumVertices);

    glutSwapBuffers();
}

int main(int argc, char **argv) {
    glutInit(&argc, argv);

    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
    glutInitWindowSize(width, height);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("PirateFace");
    glewExperimental = GL_TRUE;
    glewInit();

    init();

    glutDisplayFunc(myDisplay);
    glutMainLoop();
    return 0;
}

vertex shader :
#version 150

in  vec4 vPosition;
in  vec4 vColor;
out vec4 color;

void main()
{
  gl_Position = vPosition;
  color = vColor;
}

fragment shader :
#version 150

in  vec4 color;
out vec4 fColor;

void main()
{
    fColor = color;
}

A:
I am using vec4(homogeneous coordinates)

You need to properly initialize the w component of your vec4 values to 1.0.
Note that you do not need to store homogenous coordinates in your input vertex arrays in most scenarios. You can keep the in vec4 in the vertex shader and just use 3-dimensional vectors as input, and the GL will automatically extend the vector to (x,y,z,1).


text:
Q: Converting a 4 byte block to the corresponding int in python 2.7 I am passing a sequence of bytes from my arduino which are the sensor readings and i need the integer values of these bytes. My byte blocks size is sizeof(int) * 18(because i have 18 sensors) where sizeof(int) is 4.
Can somebody please tell me how I can find the int value of 4 bytes in python? I need to do this for each sensor reading.

A: You can use struct.unpack:
>>> import struct
>>> # assume the `sensor_values` is come from sensors.
>>> sensor_values = struct.pack('!18i', *range(100, 1900, 100))
>>> print struct.unpack('!18i', sensor_values)
(100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800)

! indicates the data is packed with network(big-endian). Use < if the data is packed with little-endian.