text:
Q: Displaying a Walkthrough using ARKit in ios I have got a requirement of a walkthrough of a medical device through ARKit. The requirement is like, we have to feed the images of the device to the app to train it about the device. Then once we show the ARKit app over the medical device, it should show a walkthrough of the medical device in the app's camera. It should highlight each button of the device and describe about it. I have been trying it around with the World Tracking and Image Tracking. Can someone guide me through with some links or so?

A: Basically, what I am understanding is you need to detect the medical machine which itself a 3D object so what you can do is Apple itself provide a scanner app to make a 3D model of an object (below is the download link)

https://developer.apple.com/documentation/arkit/scanning_and_detecting_3d_objects

Which will give you the .arobject file after successful scanning
and also you need to create a 3d file of the medical machine with a complete description of it or .dae file of the same medical machine using some designing tool to show in SCNScene after successful detection of the object.
Below are the reference link tutorial on how to implement the same:

https://blog.usejournal.com/an-introduction-to-arkit-2-object-scanning-68963b9be43a
Video link for same: https://www.youtube.com/watch?v=FEqBW3cKF2k

Hope this helps you.


text:
Q: Problem while reading objects from file in c++ I am doing a small college project where I have to add, edit and search records in/from file using OOP concept. Adding into file is working fine but whenever I try to read from file it is printing in unreadable texts.
Here is full code and output.
main.cpp
#include <iostream>
#include <cstdlib>
#include <fstream>
#define MIN 20
#define MAX 100
#include "student.h"

using namespace std;

void add_student();
void edit_student();
void search_student();
void addToFile(const Student&);
Student* fetchFromFile();
int getFileSize();
void updateFile(Student*);

// Student stud[MAX];
int main()
{
  int choice;
  system("cls");
  system("Color B0");
  while(1)
  {
    cout<<"\n\t\tWhat do you want to do?"<<endl;
    cout<<"\t\t----------------------"<<endl;
    cout<<"\t\t1-Add student"<<endl;
    cout<<"\t\t2-Edit student"<<endl;
    cout<<"\t\t3-Search student"<<endl;
    cout<<"\t\t4-Quit Program"<<endl;
    cout<<"\t\t----------------------"<<endl;
    cout<<"Enter your choice: ";
    cin>>choice;
    switch(choice)
    {
      case 1:
        add_student(); //calling add_student function to add records.
        break;
      case 2:
        edit_student();
        break;
      case 3:
        search_student();
        break;
      case 4:
        return 0;
        break;
      default:
        cout<<"Invalid choice";
        break;
    }
}
  return 0;
}

int Student::id = getFileSize() - 1; //Initialize id equals to size of file

// setData function of class Student definition
void Student :: setData()
{
  // taking input from user
  cout<<"Enter student roll no in format(1XXX): ";
  cin>>roll;
  cout<<"Enter student name: ";
  cin>>name;
  cout<<"Enter stduent date of birth(dd/mm/yy): ";
  cin>>dob;
  cout<<"Enter stduent phone no: ";
  cin>>phone;
  cout<<"Enter student address: ";
  cin>>address;
  stdId = Student::id;
}

void Student :: showData()
{
  cout<<stdId<<"  ";
  cout<<roll<<"   ";
  cout<<name<<"     ";
  cout<<dob<<"\t";
  cout<<phone<<"   ";
  cout<<address<<"\n\n";
}

const int Student :: getRoll()
{
  return roll;
}

Student& Student::operator = (const Student& newObj)
{
  stdId = newObj.stdId;
  roll = newObj.roll;
  name = newObj.name;
  dob = newObj.dob;
  phone = newObj.phone;
  address = newObj.address;
  return *this;
}

void add_student()
{
  Student stud;
  Student::incrementId();
  stud.setData();
  addToFile(stud); //adding records to file
  system("CLS");
  cout<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"---------------------------Student updated record Table---------------------------------"<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"ID      "<<"Roll      "<<"Name      "<<"DOB      "<<"Phone no         "<<"Address\n\n";
  cout<<"--------------------------------------------------------------------------------"<<endl;

  Student* student = fetchFromFile(); //getting records from file in array of objects
  int length = getFileSize(); //getting length of array of objects

  for(int i=0; i<(length-1); i++)
  {
    student[i].showData(); //showing all the data
  }

  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"---------------------------------FINISH-----------------------------------------"<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"You want to add more?(Y/n):  ";
  char c;
  cin>>c;
  if(c=='y' || c=='Y')
  {
    add_student();
  }
  else{
    system("pause");
  }
}

void edit_student(){
  //Showing existing record first before editing
  cout<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"---------------------------Student Existing record Table---------------------------------"<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"ID   "<<"Roll   "<<"Name      "<<"DOB      "<<"Phone no         "<<"Address\n\n";
  cout<<"--------------------------------------------------------------------------------"<<endl;

  Student* student = fetchFromFile(); //fetching all records from file
  int length = getFileSize();

  for(int i=0; i<(length-1); i++)
  {
    student[i].showData();
  }
  int idnumber;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"Which ID number your want to edit: ";

  cin>>idnumber;            //Asking the user at which ID he wants to make a change.
  //checking for valid id number
  if(idnumber>length || idnumber<0)
  {
    cout<<"\nInvalid ID Number."<<endl;
  }
  //showing existing information about that specific record
  cout<<"\nExisted information about this record.\n\n";
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"ID   "<<"Roll   "<<"Name      "<<"Father\tCell no.      "<<"DOB          "<<"Address\n\n";
  cout<<"--------------------------------------------------------------------------------"<<endl;
  student[idnumber].showData();
  cout<<"\n\nEnter new data for above shown record.\n\n";
  student[idnumber].setData();         //Inputting data for that specific record.
  updateFile(student);
  cout<<"\n\nRecord updated successfully."<<endl;
  cout<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"---------------------------Updated record Table---------------------------------"<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"ID   "<<"Roll   "<<"Name      "<<"DOB      "<<"Phone no         "<<"Address\n\n";
  cout<<"--------------------------------------------------------------------------------"<<endl;
  for(int i=0; i<(length-1); i++) //Showing updated record Table
  {
    student[i].showData();
  }
}

void search_student(){
  Student* student = fetchFromFile();
  int fileLenth = getFileSize() - 1;
  int searchkey;
  cout<<"Enter roll_no of student you want to search: ";
  cin>>searchkey;     //roll_no as the search key can be entered by user.
  for(int i=1; i<fileLenth; i++)
  {
    if(searchkey==student[i].getRoll()) //checking for roll no
    {
      student[i].showData();
    }
  }
  cout<<"--------------------------------------------------------------------------------"<<endl;
  cout<<"---------------------------------FINISH-----------------------------------------"<<endl;
  cout<<"--------------------------------------------------------------------------------"<<endl;
  system("pause");
}

//FILE HANDLING

void addToFile(const Student& obj)
{
  ofstream fout;
  fout.open("records.txt", std::ofstream::app | std::ofstream::binary);
  fout.write((char*)&obj, sizeof(obj));
  cout<<"Added to file successfully!"<<endl;
  fout.close();
}

Student* fetchFromFile()
{
  int i=0;
  Student obj;
  Student* returnObj = new Student[MAX];
  ifstream fin;
  fin.open("records.txt", std::ifstream::binary);
  while(!fin.eof())
  {
    fin.read((char*)&obj, sizeof(obj));
    returnObj[i] = obj;
    i++;
  }
  fin.close();
  delete[] returnObj;
  return returnObj;
}

int getFileSize()
{
  int i=0;
  Student obj;
  ifstream fin;
  fin.open("records.txt", std::ifstream::binary);
  while(!fin.eof())
  {
    fin.read((char*)&obj, sizeof(obj));
    i++;
  }
  fin.close();
  return i;
}

void updateFile(Student* student)
{
  ofstream fout;
  fout.open("records.txt", std::ofstream::binary);
  fout.write((char*)&student, sizeof(student));
  fout.close();
}

student.h header file
// A student class that hold students attributes like id, name, address and class
// Object of this class will be craeted to store student details
class Student
{
  int stdId;
  int roll;
  std::string name;
  std::string dob;
  std::string phone;
  std::string address;
public:
  static int id; //we will increase 'id' whenever student is added to the record
  //Member functions declaration
  void setData(); //this function will take input from user and set the data to attributes of class
  void showData(); //This function will give student data to user when called
  static void incrementId()
  {
    id++;
  }
  const int getRoll();
  Student& operator = (const Student&);
};

Sample output 1
When I add a student object to file
Sample output 2
Reading all records from file
Problem1: Showing garbage value of id.
Sample output 3
Adding another object to file
Sample output 4
Reading all objects from file
Sample output 5
Now went back and chose to edit record
Problem2: See how the records are printing in unreadable form.
Why is this happening. Now if I close program and run it again then it is still showing in unreadable text.
Hope you get my issue. I want to have detailed explanation about this. Also, if I have done other miscellaneous mistakes, please let me know.
Thank you!

A: Student is  too complicated to read with unformatted IO like read and write. In technical terms, it is not Trivially Copyable because it contain std::strings, and string is not Trivially Copyable.
The easiest thing to do is to abandon read and write. Most of your data is string data, so write << and >> overloads for Student and store everything as text.
    friend std::ostream & operator<<(std::ostream & out,
                                     const Student & stu)
    {
        out << stu.stdId << ',' <<stu.roll << ','<< stu.name... <<'\n';
        return out;
    }

Reading the data back in is a bit trickier
    friend std::istream & operator>>(std::istream & in,
                                     Student & stu)
    {
        std::string line;
        if (std::getline(in, line))
        {
            std::stringstream strm(line);
            if (!(strm >> stu.stdId >> comma >> stu.roll >> comma) ||
                !std::getline(strm, stu.name, ',') ||
                !std::getline(strm, stu.dob, ',') ||
                ...))
            { // If any read failed, mark the stream as failed so the caller knows.
                out.setstate(std::ios_base::failbit);
            }
        }
        return out;
    }

A:  First, a minor trick, add a empty constructor for class to initailial all members, integers{0}, and string{}, which will elminiate some unwanted gabages.
 Student::Student() :stdId(0), roll(0), name{}, dob{}, phone{}, address{} {;}

 Your major problem arised from the function fetchfomrfile() where you delete the fetched Student array, therefore the caller received a undefined data array:
Student* fetchFromFile()
{
  int i=0;
  Student obj;
  Student* returnObj = new Student[MAX];

  //reading records from file
  fin.close();
  delete[] returnObj;// <<<< youe deleted
  return returnObj; // and return it as undefined
}

 Since you are able to calculate the size of file, I suggest in the caller function:
void search_student(){
 // Student* student = fetchFromFile();
    Student *student = new Stduent [getFileSize()];
     fecchFromFile(student); // use this array in fetch_file
  // other things
 }

 Rewrite fetchFromFile as :
viod fetchFromFile(Stduent *ss)
{
  // read file data to array ss[i];
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use Android PropertyValuesHolder with proguard I'm using PropertyValuesHolder to animate some views in my Android application. The animations run fine on my device until I do a release build where there is no animation whatsoever. (I'm thinking the problem has to do with obfuscation since the property name is referred to as a String name eg "Panel1W")
There is no exception thrown. Just no animation. The closest thing I could find on http://proguard.sourceforge.net/index.html#manual/troubleshooting.html  is NoSuchMethodException where we need to use -keep command in proguard.cfg. I tried the following in my proguard.cfg but without success
-keep public class com.mycompany.myapp.HomeActivity { java.lang.Integer getPanel1W(); }
-keep public class com.mycompany.myapp.HomeActivity { void setPanel1W(java.lang.Integer); }
-keep public class com.mycompany.myapp.HomeActivity { java.lang.Integer getPanel2W(); }
-keep public class com.mycompany.myapp.HomeActivity { void setPanel2W(java.lang.Integer); }
-keep public class com.mycompany.myapp.HomeActivity { java.lang.Integer getPanel3W(); }
-keep public class com.mycompany.myapp.HomeActivity { void setPanel3W(java.lang.Integer); }

Am I missing anything? Here's the code below. Thanks.
PropertyValuesHolder[] arrayOfPropertyValuesHolder = new PropertyValuesHolder[3];
arrayOfPropertyValuesHolder[0] = PropertyValuesHolder.ofInt("Panel1W", mPanel1.getWidth(), 0);
arrayOfPropertyValuesHolder[1] = PropertyValuesHolder.ofInt("Panel2W", 360, 1280);
arrayOfPropertyValuesHolder[2] = PropertyValuesHolder.ofInt("Panel3W", 0, (int)(screenWidth * 0.65));

ObjectAnimator localObjectAnimator = ObjectAnimator.ofPropertyValuesHolder(this,
arrayOfPropertyValuesHolder).setDuration(time);
localObjectAnimator.setInterpolator(sCollapseInterpolator);
localObjectAnimator.start();

I have the getter and setter methods too.
    public int getPanel1W() {
        return ((ViewGroup.MarginLayoutParams) mPanel1.getLayoutParams()).width;
    }

    public void setPanel1W(int paramInt) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mPanel1.getLayoutParams();
        lp.width = paramInt;
        mPanel1.setLayoutParams(lp);
    }

    public int getPanel2W() {
        return ((ViewGroup.MarginLayoutParams) mPanel2.getLayoutParams()).width;
    }

    public void setPanel2W(int paramInt) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mPanel2.getLayoutParams();
        lp.width = paramInt;
        mPanel2.setLayoutParams(lp);
    }

    public int getPanel3W() {
        return ((ViewGroup.MarginLayoutParams) mPanel3.getLayoutParams()).width;
    }

    public void setPanel3W(int paramInt) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) mPanel3.getLayoutParams();
        lp.width = paramInt;
        mPanel3.setLayoutParams(lp);
    }

A: The trick is the fact that the methods called by the PropertyValuesHolder are either set* or get*, so the ProGuard rules to keep such methods are:
void set*(***);
*** get*();

So, based on that, if your animated target is only one of a few classes, add this per animated target class:
-keep class my.package.MyClass {
    void set*(***);
    *** get*();
}

If all your targets extend some base class, you can add a single rule to save them all:
-keep class * extends my.package.MyBaseClass {
    void set*(***);
    *** get*();
}

A: please check if String "Panel1W","Panel2W" and "Panel3W" were mixed by proguard.I think you can define these strings in class and -keep in proguard.cfg to protect these strings.


text:
Q: Can multiple people share the same shelve set in TFS? I am looking for an alternative to branching in TFS with the goal of allowing multiple developers to continually integrate into a single changeset that is not in branch (aka a shelveset).
I know that a single user can update their own shelveset, and other users can pull that shelveset - but is it possible to allow several users to modify the same shelveset?
I understand that branching is preferred but I would still like to know if it is possible, maybe by using some sort of TFS powertool or modification.

A: No this is not possible. A shelveset is owned by a single user. it's also not recommended, as the shelveset is only a single snapshot of the change.
If you'd like something like this, you could consider git tf to create a local git repository which can be synced between two developers. Once they're finished one of the developers can push the change(s) back into TFS.
Moving from TFVC to Git has become easier with the release of TFS 2015u1:

Team Services | TFS 2015
In Team Foundation Server 2015 Update 1, a project administrator can add a Git repo to a team project created with Team Foundation Version Control (TFVC). You can also add a TFVC repo to a team project created with Git. This allows you to adopt a new version control system while preserving all the data in your team project.

As to ways to persuade people to move, that's a hard question. You'd first need to understand what is holding them back, explain the, what advantages Git brings, what disadvantages you see in the current setup. You will probably need to hand-hold or train them so they get comfortable with Git. Using git-tf for a while may give them more confidence to make the move.


text:
Q: Exponential Function Expansion but with Double Factorials Considering:  $\sum_n \frac{z^n}{n!}=e^{z}$
I was wondering if there is anything similar for: $\sum_{n:\text{ odd or even} }\frac{z^n}{n!!}$
That is, when you replace $n!$ with $n!!$ and add for all odd $n$'s or even $n$'s.
Thanks.

A: $$\sum_{n=0}^\infty \frac{z^n}{n!!}=e^{\frac{z^2}{2}} \left(1+\sqrt{\frac{\pi }{2}}\,
   \text{erf}\left(\frac{z}{\sqrt{2}}\right)\right)$$ where appears the error function
$$\sum_{n=0}^\infty \frac{z^{2n}}{(2n)!!}=e^{\frac{z^2}{2}}$$
$$\sum_{n=0}^\infty \frac{z^{2n+1}}{(2n+1)!!}=\sqrt{\frac{\pi }{2}} e^{\frac{z^2}{2}} \text{erf}\left(\frac{z}{\sqrt{2}}\right)$$


text:
Q: Why does java.time.Period have no constructor? Instead, Period.of(int, int, int) must be used, or another static method in the same vein.
What's the reasoning behind this?

A: The main reason - it is util class and most of util classes should be used in static manner (at least java architects wish so). You can compare it with using java.lang.Math.
The second reason, I suggest - it is reflection and serialization. I think dealing with Period.class is more convinient, but it's only suggestion. Inside implementation they have static method create() and always use create() instead of constructor.
You can also look at source code. For example, here: http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/e63cf6b55a95/src/java.base/share/classes/java/time/Period.java
public static final Period ZERO = new Period(0, 0, 0);

public static Period of(int years, int months, int days) {
    return create(years, months, days);
}
private static Period create(int years, int months, int days) {
    if ((years | months | days) == 0) {
        return ZERO;
    }
    return new Period(years, months, days);
}
private Period(int years, int months, int days) {
    this.years = years;
    this.months = months;
    this.days = days;
}

A: Period is final class so can not be extended, so everyone can that Period is unmutable. Private contructor is another way to ensure that Period will be created correctly.


text:
Q: In TypeScript, is there a way to omit a type of true or false? This was my best attempt at trying this. Is it possible or even necessary? Maybe there is something I'm missing about typescript that makes more sense.
const TrueOrFalse = True | False;

const OnlyTrue = Omit<TrueOrFalse, false>;

A: Omit removes properties from an object type. What you want to do is exclude a type from a union. You can do this with the built-in conditional type Exclude.
type X = Exclude<boolean, true> // X is false

Playground Link
Exclude will take out of the first type parameter, any type that is a subtype of the second parameter.
You can read more about exclude here
Exclude and its cousin Extract can be useful also in manipulating discriminated unions, to extract or exclude a specific constituent from a union, even if you only know the discriminant not the whole the type:
type Shape = { type: "sq", size: number } | { type: "circle", radius: number }

type Square = Exclude<Shape, { type: "circle" }> //  { type: "sq", size: number }
type Circle = Extract<Shape, { type: "circle" }> //  { type: "circle", radius: number }

Playground Link


text:
Q: Removing inline styles using php I am using php to output some rich text. How can I strip out the inline styles completely?
The text will be pasted straight out of MS Word, or OpenOffice, and into a  which uses TinyMCE, a Rich-Text editor which allows you to add basic HTML formatting to the text.
However I want to remove the inline styles on the  tags (see below), but preserve the  tags themselves.

A patrol of Zograth apes came round the corner, causing Rosette to pull Rufus into a small alcove, where she pressed her body against his. “Sorry.” She said, breathing warm air onto the shy man's neck. Rufus trembled.

Rosette checked the coast was clear and pulled Rufus out of their hidey hole. They watched as the Zograth walked down a corridor, almost out of sight and then collapsed next to a phallic fountain. As their bodies hit the ground, their guns clattered across the floor. Rosette stopped one with her heel and picked it up immediately, tossing the other one to Rufus. “Most of these apes seem to be dying, but you might need this, just to give them a helping hand.”

A: Use HtmlPurifier

A: I quickly put this together, but for 'inline styles' (!) you will need something like
$text = preg_replace('#(<[a-z ]*)(style=("|\')(.*?)("|\'))([a-z ]*>)#', '\\1\\6', $text);

A: You could use regular expressions:
$text = preg_relace('#<(.+?)style=(:?"|\')?[^"\']+(:?"|\')?(.*?)>#si', '', $text);

A: You can use: $content = preg_replace('/style=[^>]*/', '', $content);

A: You can also use PHP Simple HTML DOM Parser, as follows:
$html = str_get_html(SOME_HTML_STRING);

foreach ($html->find('*[style]') as $item) {
   $item->style = null;
}

A: Here is a preg_replace solution I derived from Crozin's answer. This one allows for attributes before and after the style attribute fixing the issue with anchor tags.
$value = preg_replace('/(<[^>]*) style=("[^"]+"|\'[^\']+\')([^>]*>)/i', '$1$3', $value);

A: Couldn't you just use strip_tags and leave in the tags you want eg
,  etc?

A: Why don't you just overwrite the tags. So you will have clean tags without inline styling.

A: I found this class very useful for doing strip attributes (especially where there's crazy MS Word formatting all through the text):
http://semlabs.co.uk/journal/php-strip-attributes-class-for-xml-and-html

A: I am did need to clear style from img tags and did resolved  by this code:
$text = preg_replace('#(<img (.*) style=("|\')(.*?)("|\'))([a-z ]*)#', '<img \\2\\6', $text);
echo  $text;


text:
Q: Partial self-answering etiquette I asked why some error occurred in my code and why some programs behave in a different way than I expect from reading other questions/documentation. Then I found a workaround bypassing the problem in the one place where it occurred, but I didn't understand why the error happened and how to prevent it returning like a boomerang, and I still see some weird things that might become harmful later. So I consider this workaround as a very partial solution.
I can post my workaround as an answer or as an edit. I know of several questions asking for this in general (like this one); however, partial answers are somewhat harder to resolve and have been discussed several times (like here or here), so I don't see this question as their exact duplicate.
Not related to the case of the question and answer I wrote about, I have few questions on a general partial self-answering policy:

*

*is there any significant set of answers that could be valid as an
answer for other's question but should be included as an edit is
made by the OP?
Clarifying the question should always be included in
the question, and I feel my intended answer is close to
clarification ("I need explaining what's going on, I already have
some working code, I don't need more improvements on it" - focus of
the question). If it should be posted as an answer, but has some
"clarification" aspect as well - should I both answer and edit my
question, or is a partial answer enough?

*are "does it help anyone else?" and perhaps clarification/partial
answer border (point 1) the only criteria to tell whether something
permissible as an answer otherwise should be posted as an answer?
What other factors are there, if any?
I'm not absolutely sure whether that my answer will help anyone else, probably yes, so I'll wait for community's opinion here, think it over few more times and probably post it, without accepting it.
Tl;dr: what to take care of besides "will it be useful to anyone else" while giving partial answers on my own questions? When should I add partial answer as an answer, when as an edit and when both?

A: Accepting is the least of your concerns. Whether you want to post it as an answer or an edit to your question depends primarily on you and the partial answer.
Is the answer enough to stand on its own? Is it really an answer to your question? If you ask why does X happen? answering with you can workaround it like this might not qualify as an answer to the actual question.
Do you consider it as an answer to your question? Does it solve the case for you or not? If it doesn't, you might want to edit instead of answer. The workaround might have serious caveats. Answering with such a post might be harmful to others, which is less a concern if you put it in your question, where users know it might be broken.

A: It's ok to post your own partial answer; another matter is whether to accept it at answer.
Adding potential workarounds or partial to the question itself would only make it more messy, which doesn't help producing a complete answer.


text:
Q: Updated data on Parse Cloud is not Loading I have created a comment class where the users can comment their opinions. But when I send write the new comment is does not refresh the comment I have to restart the activity for the comments to load. I don't understand how can that be achieved. Tried referring to a lot of tutorials online but I couldn't find a solution to that.
I call this RemoteDataTask Method in my onCreate
  private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {
            parseCommentsList = new ArrayList<>();
            try {
                ParseQuery<ParseObject> query = new ParseQuery<>(
                        "Comments");
                query.whereEqualTo("videoId", videoID);
                query.setCachePolicy(ParseQuery.CachePolicy.NETWORK_ELSE_CACHE);
                query.orderByDescending("createdAt");
                ob = query.find();
                for (ParseObject country : ob) {
                    ParseComments map = new ParseComments();
                    ParseFile dp = (ParseFile)country.get("profilepictures");
                    String comments = country.getString("Comment");
                    String commentUser = country.getString("senderName");
                    map.setComments(comments);
                    map.setProfileName(commentUser);
                    map.setProfilePic(dp.getUrl());
                    parseCommentsList.add(map);
                }
            } catch (ParseException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            listView = (ListView) findViewById(R.id.comments_list);
            adapter = new CommentsAdapter(SingleVideoView.this,
                    parseCommentsList);
            listView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
    }

Here is the Adapter for the comments
public class CommentsAdapter extends BaseAdapter {
    // Declare Variables
    Context context;
    LayoutInflater inflater;
    private List<ParseComments> parseCommentsList = null;
    private ArrayList<ParseComments> arraylist;

    public CommentsAdapter(Context context,
                           List<ParseComments> parseCommentsList) {
        this.context = context;
        this.parseCommentsList = parseCommentsList;
        inflater = LayoutInflater.from(context);
        this.arraylist = new ArrayList<ParseComments>();
        this.arraylist.addAll(parseCommentsList);
    }

    public class ViewHolder {
        TextView comment;
        TextView name;
        ImageView profilePic;
    }

    @Override
    public int getCount() {
        return parseCommentsList.size();
    }

    @Override
    public Object getItem(int position) {
        return parseCommentsList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.comments_layout, null);
            // Locate the TextViews in listview_item.xml
            holder.comment = (TextView) view.findViewById(R.id.comments);
            holder.name = (TextView)view.findViewById(R.id.name);
            holder.profilePic = (ImageView)view.findViewById(R.id.profilePic);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.comment.setText(parseCommentsList.get(position).getComments());
        holder.name.setText(String.valueOf(parseCommentsList.get(position).getProfileName()));
        Picasso.with(context)
                .load(parseCommentsList.get(position).getProfilePic())
                .transform(new CircleTransform())
                .resize(70,70)
                .into(holder.profilePic);
        return view;
    }
}


text:
Q: How to change Symfony2 FOSUser register form error message? I have customized my register_content.html.twig like that
            <form class="form-horizontal" action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST">

                        {{ form_widget(form.username, { 'attr': {'class': 'form-control', 'placeholder': 'Pick a username' } }) }}
                        {{ form_errors(form.username) }}

 ...

And now, when I'm getting an errors, those errors looks like that
fos_user.username.already_used
fos_user.email.already_used
fos_user.password.mismatch

I just want to change those messages, could anyone help me?

A: Once you enable the translator service, e.g.,
app\config\config.yml:
framework:
    translator:      { fallback: "%locale%" }

copy the appropriate FOSUserBundle.{locale}.yml from ...vendor/friendsofsymfony/userbundle/Resources/translations to ...app/Resources/translations.  In the copied file, change the messages for
fos_user.username.already_used
fos_user.email.already_used
fos_user.password.mismatch


text:
Q: Complex irreducible representation of solvable lie algebra How can one infer from the Lie's theorem (in terms of existence of a common eigenvector) that a complex irreducible representation of a solvable lie algebra has dimension 1?
What I know is that one can write $\sigma(x)(v) \in \mathbb{C}.v$ if $\sigma$ is the representation so that $\mathbb{C}.v$ is invariant. How to complete the argument from here?


text:
Q: Solving an equation representing pair of line yields two parallel lines but the original equation have a solution to it. Why? Given equation for pair of straight line is
$$4x^2 + 4xy + y^2 -6x -3y -4=0$$
Solution given to me is that as following
If we shift origin for this equation this will become a homogenous equation. As we know angle between two line will remain same irrespective of origin chosen so let's assume we choose such an origin for which any term with degree not equal to 2 will vanish yielding
$$4x^2 + 4xy + y^2=0$$
which is $$(2x+y)^2=0$$
This will be equation for two individual lines in shifted origin so we bring are origin back  to original position which will give these equations an extra constants $$(2x+y+a)(2x+y+b)=0$$
comparing this to original equation
that is $$(2x+y+a)(2x+y+b)=0=4x^2 + 4xy + y^2 -6x -3y -4$$
solving this
$$4x^2 +y^2 +4xy +2x(a+b) +y(a+b) +ab=4x^2 + 4xy + y^2 -6x -3y -4$$
comparing coefficient of y $a+b=-3$ and constant $ab=-4$
solving yields $$a=1$$ and $$b=-4$$
This two lines $2x+y+1=0$ and $2x+y-4=0$ are certainly parallel which implies these two lines do not have any point of intersection
The why does point $(0,-1)$ satisfies $4x^2 + 4xy + y^2 -6x -3y -4=0$?
Is it solution for imaginary line? If yes please elaborate solution of lines yielded by above equation.
Also tell what's wrong with above method?
I can assure lines in result are correct because they can be also calculated lie this $$y= \frac{-(4x-3)±\sqrt{(4x-3)^2-4(4x^2-6x-4)}}{2}$$

A: Though it would be convenient, "let's assume we choose such an origin for which any term with degree not equal to 2 will vanish" is not how it works. (Does it work starting from $x^2+y=0$?) One would need to make a literal substitution $u=x-a$, $v=y-b$ to see what the new equation is.


text:
Q: How Do I Fix My Super Statements? I put my super statements in the correct format, yet my only error is that it states that the  constructor object in class java.lang.object can't be applied to given types for this part of the code:
       super (openFile (filename));

Here is my current code now:
     import    java.io.BufferedReader;
     import java.io.ByteArrayOutputStream;
     import java.io.File;
     import java.io.FileNotFoundException;
     import java.io.FileReader;
     import java.io.IOException;
     import java.io.OutputStream;
     import java.io.OutputStreamWriter;
         import java.security.MessageDigest;
         import java.security.NoSuchAlgorithmException;
         import java.util.Vector;import java.io.PrintWriter;
         import java.io.BufferedWriter;
         import java.io.FileWriter;
         import java.io.InputStream;
         import java.io.InputStreamReader;
         import java.io.Reader;

       public class Buffin
      {
 private static boolean temp;
 /////////////////////////////////
 private boolean isKeyboard;

 /** Connect to the disk file with the given name.  If this
  *  cannot be done, connect to the keyboard instead. */

 public Buffin (String filename)
 {    super (openFile (filename));
      isKeyboard = temp;
 }    //======================

 private static Reader openFile (String filename)
 {    try
      {    temp = false;
           return new FileReader (filename);  // IOException here
      }catch (IOException e)
      {    temp = true;
           return new InputStreamReader (System.in);
      }
 }    //======================

 /** Read one line from the file and return it.
  *  Return null if at the end of the file. */

 public String readLine()
 {    if (isKeyboard)
      {    System.out.print (" input> ");
           System.out.flush();  // flush the output buffer
      }
      try
      {    return super.readLine(); // in BufferedReader
      }catch (IOException e)
      {    System.out.println ("Cannot read from the file");
           return null;
      }
 }    //============
}[/code]

A: Your class extends only the Object class, and it doesn't have a method or constructor called openFile. You would be fine if you remove the super call altogether.

A: At the moment, your class Buffin does not specify a super class; that means it has one super class, and that  is java.lang.Object. There is no constructor that takes a Reader in java.lang.Object.
You could store a Reader as a field in your Buffin class, or you might extend a super class that accepts one in the constructor.

A: Super involves the constructor of the superclass, I see that the Class Buffin inherits no class. As @Sotirios Delimanolis said, no constructor accepting Reader in Object class.


text:
Q: JSON Post method is not working swift I am Parsing json data from google maps api in swift, am trying to show current location using google maps api, getting current location latitude and longitude using didUpdateLocations. inside the serviceLocationupdate()
posting lat and long values using post method but am not getting the response from the json. how can I get the response(data) from the json.
this is the code
var lat  = ""
var long = ""
var latlng:String = ""

         func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

                let location:CLLocationCoordinate2D = manager.location!.coordinate
                self.lat = String(location.latitude)
                self.long = String(location.longitude)
                latlng = self.lat+"," + self.long

}

func serviceLocationupdate()
        {

            var request = URLRequest(url: URL(string: "http://maps.googleapis.com/maps/api/geocode/json")!)

     let session = URLSession.shared

            request.httpMethod = "POST"

      ----->> let bodyData = "latlng=\(latlng)&sensor=\("true")"

            print("bodydata",bodyData)

            request.httpBody = bodyData.data(using: String.Encoding.utf8);

            let task = session.dataTask(with:request,completionHandler:{(d,response,error)in

                do{

                    if let data = d{
                        do{
                            let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                            if let results = jsonResult["results"] as? [[String : AnyObject]] {

                                for result in results{

                                    if let addressComponents = result["address_components"] as? [[String : AnyObject]] {

                                        print(addressComponents)
                                    }
                                }
                            }

                        } catch
                        {

                        }

                    }

            }
            })

            task.resume()
        }

if i can use this api its working fine getting proper data
var request = URLRequest(url: URL(string:"http://maps.googleapis.com/maps/api/geocode/json?latlng=13.026811,77.593773&sensor=true")!)
I want display the current location using latitude and longitude

A: This works in a playground:
//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

func serviceLocationupdate()
{
    let session = URLSession.shared
    if let url = URL(string: "http://maps.googleapis.com/maps/api/geocode/json"),
        var params = URLComponents(url: url, resolvingAgainstBaseURL: false) {

        params.queryItems = [URLQueryItem]()
        params.queryItems?.append(URLQueryItem(name: "latlng", value: "33.9250675,-84.339827"))
        params.queryItems?.append(URLQueryItem(name: "sensor", value: "true"))

        guard let finalURL = params.url else {
            print("Failed to create URL")
            return
        }
        var request = URLRequest(url: finalURL)
        request.httpMethod = "POST"

        let task = session.dataTask(with:request,completionHandler:{(data,response,error)in

            if let error = error {
                print("Error is \(error)")
                return
            }

            if let resp = response as? HTTPURLResponse {
                print("Response status code \(resp.statusCode)")

                guard let data = data else {
                    return
                }

                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary,
                        let results = jsonResult["results"] as? [[String : AnyObject]] {

                        for result in results {
                            if let addressComponents = result["address_components"] as? [[String : AnyObject]] {
                                print(addressComponents)
                            }
                        }

                    } else {
                        print("Could not coerce into a dictionary")
                    }
                } catch _ {
                    print("An error occurred")
                }

            } else {
                print("Invalid response")
            }
        })
        task.resume()
    }
}

serviceLocationupdate()

A: Looks like the API works with the url you mentioned (http://maps.googleapis.com/maps/api/geocode/json?latlng=13.026811,77.593773&sensor=true), then you can just use GET instead of POST. Try the following:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            let location:CLLocationCoordinate2D = manager.location!.coordinate
            self.lat = String(location.latitude)
            self.long = String(location.longitude)
            latlng = self.lat+","+self.long
            serviceLocationupdate()
}

func serviceLocationupdate()
    {

        var request = URLRequest(url: URL(string: "http://maps.googleapis.com/maps/api/geocode/json?latlng=\(latlng)&sensor=true")!)

        let task = session.dataTask(with:request,completionHandler:{(d,response,error)in

                if let data = d{
                    do{
                        let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                        if let results = jsonResult["results"] as? [[String : AnyObject]] {

                            for result in results{

                                if let addressComponents = result["address_components"] as? [[String : AnyObject]] {

                                    print(addressComponents)
                                }
                            }
                        }

                    } catch
                    {

                    }

                }
        })

        task.resume()
    }


text:
Q: Exporting a Java text-based program into an executable JAR? I am using Eclipse as my IDE.
I have previously made and exporting my different programs in eclipse as executable jar files, but those were all programs involving frames. I was messing around with the classic text based programs I had and decided that I wanted to export the said text-based programs. However, when I try and do this I am left with a jar file that does not run or do anything. I have had no success in having my text-based programs to run outside of Eclipse.

A: The odds are that the jar file IS running. But the problem is that (I'm assuming here) you're using System.out and System.in for your i/o. When you're running a jar file (with double-click ) you have no visible console.
There are two ways to combat this:
-Either create a gui and use that as your i/o
-Or you can run the jar file from the command line ("java -jar yourjar.jar" <- on windows cmd) and the input and output will be done through the command window you used to run the jar.
EDIT: Added some information about fixing: "java is not a recognized..."
You have two options here, when you're running your jar with the command "java -jar yourjar.jar"; you could replace "java" with the full path to your java executable, so for example:
"C:\Program Files\Java\jdk1.8.0_05\bin\java" -jar yourjar.jar

or
"C:\Program Files\Java\jdk1.8.0_05\jre\bin\java" -jar yourjar.jar

This does become annoying though, so the best things to do is set up java in your system environmental variables. Open your 'Start Menu', right-click on 'Computer' and select 'Properties'. Once you're here select 'Advanced System Settings', and then click on the 'Environmental Variables' button.
Now what I like to do is create another two variables (if you don't plan on doing any of this on other users, just do it in your user-variables for your account section), "JDK_HOME" and "JAVA_HOME". I personally have both of these point to the same place just because of a little error I was having with something. However in your case it sounds like you only need one, we'll go with JDK_HOME:
So add your variable:

And then we want to actually have it on the Systems Path, so look through the variables and find one called "PATH", edit this one and we're going to be adding the JDK_HOME variables directory and the bin folder to it:

When appending multiple directories to the Path variable, each are separated by a semi-colon. You'll note that I am adding the variable JDK_HOME by specifying %JDK_HOME%, but I am then adding '/bin' to it, this is because we are interested in using the Java executable within the bin directory. Now that you have that sorted, close out of your environmental variables configuration, and try again, you should now have the command "java" work.
-Thomas


text:
Q: Is it possible to do "if .. || if .."? I had a question regarding the || operator in javascript. To my understanding it can be used as either an 'OR' operator, or a null coalescing operator.
My question is, can I use if statements in conjunction with the || null coalescing operator? For example,
if (x=y){
alert("Yup");
}||if (x=0){
alert("Nope);
}

Thanks in advance.

A: No.  Just use else
The JavaScript grammar distinguishes between statements like
if (condition) statement else statement

and expressions like
expr || expr

A statement can contain expressions with few restrictions° via the ExpressionStatement production, but expressions can only contain statements in a very limited way°°.
So
{statement} || {statement}

is neither a valid statement nor a valid expression because the JavaScript parser sees the || where it expects a statement to appear and reports a parse error.

Second, || is not really "null-coalescing".  To see why, consider
alert(false || null)  // alerts "null" not "false"
alert(0     || null)  // alerts "null" not "0"
alert(""    || null)  // alerts "null" not the empty string
alert((0/0) || null)  // alerts "null" not "NaN"

Since the left-hand-sides of the || are falsey the null is given preference which is not what you would expect if only nulls were coalesced.

° - the { key: value } object constructor is ambiguous with blocks, and named function expressions are ambiguous with function declarations so both are banned unless parenthesized.
°° - a function expression like function () { ... } can contain statements in its body.


text:
Q: What's the difference between admin.b360 and developer.api Autodesk's services? I'm trying to implement Forge API endpoints wrapper and I faced with situation, where I can create user via this endpoint https://developer.api.autodesk.com/hq/v1/accounts/:account_id/users but I can't find endpoint for removing users (not inactivation). I found that for user deleting WebUI of BIM360 actually using https://admin.b360.eu.autodesk.com/users/:user_id/destroy endpoint, but I can't find description of this endpoint anywhere. What's the difference between developer's API and admon.b360 stuff?

A: I cannot find that endpoint on our API documentation. If you only see it under the dev tools, it could be an internal endpoint of the BIM360 services that can only be accessed by BIM360 itself.
Commonly, user-accessible BIM360 APIs are exposed under the base URL https://developer.api.autodesk.com/. If you don't see it listed on the Forge BIM360 API documentation, it means the function you're looking for is not available at this moment, unfortunately.
https://forge.autodesk.com/en/docs/bim360/v1/reference/http/


text:
Q: Firefox ignoring height: 100% I have the following snippet that works in chrome and explorer, however I can't seem to get firefox to make the left bar .leftpanel stretch to the full height of the parent .viewer
JSfiddle
Snippet

html,
body {
  border: 0;
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
ul {
  margin: 0;
  padding: 0;
}
li {
  display: inline-block;
  list-style-type: none;
}
.fullscreen {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: pink;
  display: table;
  z-index: 1;
}
.centeralign {
  vertical-align: middle;
  width: 100%;
  height: 100%;
  display: table-cell;
  background-color: blue;
  text-align: center;
  padding: 2em;
}
.viewer {
  text-align: left;
  display: inline-block;
  width: 90%;
  height: 90%;
  position: relative;
  background-color: green;
  padding: 1em;
  min-height: 35.45em;
}
.leftpanel {
  width: 15em;
  /*Alter depending on how much space this takes*/
  float: left;
  height: 100%;
  position: relative;
  background-color: yellow;
}
.leftpanel .slide {
  width: 15em;
  height: 9.706em;
  display: block;
  margin-bottom: 1em;
  background-color: red;
}
.leftpanel .comments_container {
  display: table;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 14em;
  width: 15em;
  background-color: orange;
}

            Test

            <form action="new_comment.php">
              <input type="text" name="comment" />
              <input type="submit" name="Send" />
            </form>

        X

A: At first sight, your issue is you are setting a big min-height to your parent .viewer, so just remove it because you already have set a height as 90% within another parent.

html,
body {
  border: 0;
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
ul {
  margin: 0;
  padding: 0;
}
li {
  display: inline-block;
  list-style-type: none;
}
.fullscreen {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: pink;
  display: table;
  z-index: 1;
}
.centeralign {
  vertical-align: middle;
  width: 100%;
  height: 100%;
  display: table-cell;
  background-color: blue;
  text-align: center;
  padding: 2em;
}
.viewer {
  text-align: left;
  display: inline-block;
  width: 90%;
  height: 90%;
  position: relative;
  background-color: green;
  padding: 1em;
  /* min-height: 35.45em; remove this line */
}
.leftpanel {
  width: 15em;
  /*Alter depending on how much space this takes*/
  float: left;
  height: 100%;
  position: relative;
  background-color: yellow;
}
.leftpanel .slide {
  width: 15em;
  height: 9.706em;
  display: block;
  margin-bottom: 1em;
  background-color: red;
}
.leftpanel .comments_container {
  display: table;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 14em;
  width: 15em;
  background-color: orange;
}

            Test

            <form action="new_comment.php">
              <input type="text" name="comment" />
              <input type="submit" name="Send" />
            </form>

        X

A: Although your question has already been answered, here is the 'general' solution:
.clearfix:before,
.clearfix:after     { content: ''; display: table }
.clearfix:after     { clear: both }
Your viewer class needs the well known 'clearfix' added in the HTML, search google for a proper explanation on that. Modify your viewer HTML
 and add the class to your global CSS (for general use) and you are good to go.

A: Unfortunately I can't tell you why firefox is doing this or what is causing this, however, I can give you a possible fix for this problem, which doesn't include that much of a change in your code.
The solution is simple, use display:flex instead of display:inline-block on your .viewer element and give the children, in this case the .leftpanel element the property align-items:stretch
To read more on this check out either this css-tricks guide or this MDN guide.
Your updated code will look like this:
HTML: Nothing changed.
CSS:
.viewer {
    text-align: left;
    display: flex; /* changed the display to flex */
    width: 90%;
    height: 90%;
    position: relative;
    background-color: green;
    padding: 1em;
    min-height: 35.45em;
}

.leftpanel {
    width: 15em; /*Alter depending on how much space this takes*/
    float: left;
    height: 100%;
    position: relative;
    background-color: yellow;
    align-items: stretch; /* Added the align-items property */
}

JSFiddle
Hope this helps!


text:
Q: Python extract multi-level nested lists Having this list
l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]

I would like to get a function extracting all nested lists and return
l = [['a', 'b', 'c', 'd'],["d","d"],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]

like flatten but keeping the list formation of every nested list.
This is the closest I have been and I feel like there is a way of accomplishing my goal without using an extra structure to filter duplicates. Also, order matters in string and list level.
def get_all_nested_list(l,returned_list):
    nested_list = l
    while isinstance(nested_list, list):
        for elem in nested_list:
            get_all_nested_list(elem,returned_list)
        if isinstance(nested_list[0], str):
            returned_list.append(nested_list)
        nested_list = nested_list[0]

if __name__ == '__main__':
    l = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]
    l2 = []
    get_all_nested_list(l,l2)
    print(l2)

Any other ways of doing it the above either by using itertools or suggesting an actually proper way of using yield instead of passing another list as argument are more than welcome.

A: You could try a recursive function
my_nested_list = [['a', 'b', 'c', 'd'],[[["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]

def flatten(nested_list):
    for item in nested_list:
        if not isinstance(item[0],list):
            yield item
        else:
            yield from flatten(item)

flat_list = [item for item in flatten(my_nested_list)]
print(flat_list)

A: You can do it like this:
from itertools import chain

my_nested_list = [['a', 'b', 'c', 'd'],['e', ['r'], [["d","d"]],['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]]

def flatten(nested_list):
    for item in nested_list:
        if not isinstance(item,list):
            yield item
        elif list(chain(*item)) == item:
            yield item
        else:
            yield from flatten(item)

flat_list = list(flatten(my_nested_list))
# [['a', 'b', 'c', 'd'], 'e', ['r'], ['d', 'd'], ['z', 'x', 'g', 'd'], ['z', 'C', 'G', 'd']]

Thanks


text:
Q: Is this sentence ambiguous? ("it is not" followed by -ing) English is not my first language. I found the following sentence:

It is not having fear that is the problem.

Am I right thinking that it is ambiguous? I can think of the following different meanings:

*

*"It is not having fear that is the problem." -> The lack of fear is the problem.

*"It is not having fear that is the problem." -> The lack of fear is not the problem.

*"It is not having fear that is the problem." -> The subject "it" is something that is different from "having fear that is the problem", where "that" refers to something else.

*"It is not having fear that is the problem." -> The subject "it" is something that is equal to "not having fear that is the problem", where "that" refers to something else.

A: Yes, with no context, it is ambiguous.  However, if options 3 or 4 are intended then one would expect quotation marks setting off the phrases that you italicized in the question (or indeed italic type).  Furthermore, in the second case I would expect something further describing the actual problem, most likely an additional phrase starting with but.
Therefore, even in the absence of context, the ambiguity can be resolved in favor of the first option with a fairly high probability, with a small possiblity of the second option.


text:
Q: how to use \timing in postgres I want to know the time that it takes to execute a query in Postgres, I see a lot of response that propose to use \timing, but I'm newbie in Postgres and I don't know how to use it, can anyone help
thank you in advance

A: You can use \timing only with the command line client psql, since this is a psql command.
It is a switch that turns execution time reporting on and off:
test=> \timing
Timing is on.
test=> SELECT 42;
┌──────────┐
│ ?column? │
├──────────┤
│       42 │
└──────────┘
(1 row)

Time: 0.745 ms
test=> \timing
Timing is off.


text:
Q: Only getting one result from sub select in inner join in mysql Hi I have run into a dilemma, I am doing this query:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories, pr.promo_name, pr.add_value_text, c.contract_id, c.cmeal_plan, c.cmin_markup, c.civa, c.tax_include, c.hotel_id, hi.hname, hi.hstars, im.image_file, pl.plan_name, ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi ON hi.hotel_id = c.hotel_id AND hi.destination_id = '6460'
INNER JOIN images AS im ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl ON pl.plan_code = c.cmeal_plan AND pl.lang = '1'
INNER JOIN hotel_categories AS hc ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca ON ca.category_code = hc.category_code AND ca.lang = '1'
LEFT JOIN
                    (SELECT
                              r.hotel_id, AVG(r.double) AS price
                    FROM
                              rates AS r ) AS ra
                    ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr ON pr.hotel_id = hi.hotel_id AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0 AND pr.book_start <= '2012-11-01' AND pr.book_end >= '2012-11-02' AND travel_start <= '2012-11-23' AND travel_end >=  '2012-11-30' AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01' AND c.cend >= '2012-11-01'
AND hi.status = '1'
AND im.type ='1'
GROUP BY hi.hotel_id

I am getting all the desired results except for the sub select query.. each hotel has a price but it is only giving me back one result and the rest are all null. Is there an error in my query? If any additional information is needed please let me know and thank you in advance for any help!

A: You are missing the GROUP BY in your subquery, so MySQL will only return one-value.  If you want all hotel_id's then you need to GROUP BY that field:
SELECT GROUP_CONCAT(DISTINCT(ca.category_name) SEPARATOR ', ') AS categories,
    pr.promo_name,
    pr.add_value_text,
    c.contract_id,
    c.cmeal_plan,
    c.cmin_markup,
    c.civa,
    c.tax_include,
    c.hotel_id,
    hi.hname,
    hi.hstars,
    im.image_file,
    pl.plan_name,
    ra.price
FROM contracts AS c
INNER JOIN hotel_info AS hi
    ON hi.hotel_id = c.hotel_id
    AND hi.destination_id = '6460'
INNER JOIN images AS im
    ON im.foreign_id = hi.hotel_id
INNER JOIN meal_plan AS pl
    ON pl.plan_code = c.cmeal_plan
    AND pl.lang = '1'
INNER JOIN hotel_categories AS hc
    ON hc.hotel_id = hi.hotel_id
INNER JOIN categories AS ca
    ON ca.category_code = hc.category_code
    AND ca.lang = '1'
LEFT JOIN
(
    SELECT r.hotel_id, AVG(r.double) AS price
    FROM rates AS r
    GROUP BY r.hotel_id  <-- add a GROUP BY hotel_id then you will get avg() for each hotel
) AS ra
    ON ra.hotel_id = hi.hotel_id
LEFT JOIN promotions AS pr
    ON pr.hotel_id = hi.hotel_id
    AND FIND_IN_SET(c.contract_id, pr.contract_id) > 0
    AND pr.book_start <= '2012-11-01'
    AND pr.book_end >= '2012-11-02'
    AND travel_start <= '2012-11-23'
    AND travel_end >=  '2012-11-30'
    AND pr.lang = '1'
WHERE c.cstart <= '2012-11-01'
    AND c.cend >= '2012-11-01'
    AND hi.status = '1'
    AND im.type ='1'
GROUP BY hi.hotel_id


text:
Q: How to make 'Reactjs Modal' appearing in screen flying from right to centre I have a react Modal. When it is invoked, it opens up in the center of browser window. I want some changes in the Modal opening style.
When Modal is invoked, it should come flying from right to center. I dont know about the property/attribute which can enable such appearance. can someone please help.
This is my current styling:
customStyles = {
overlay: {
  position: 'fixed',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundColor: 'rgba(255,255,255,0.75)'
},
content: {
  display: 'relative',
  position: 'absolute',
  textAlign: 'Center',
  top: '20%',
  left: '20%',
  right: '20%',
  bottom: '4%',
  border: '6px solid #ccc',
  background: '#fff',
  overflow: 'auto',
  WebkitOverflowScrolling: 'touch',
  borderRadius: '4px',
  outline: 'none',
  padding: '20px',
  paddingLeft: '40px'
}};

A: Add this class name
example:
.modal-center{
      animation: left-to-center linear 1s;
      animation-iteration-count: 1;
      transform-origin: 50% 50%;
      -webkit-animation: left-to-center linear 1s;
      -webkit-animation-iteration-count: 1;
      -webkit-transform-origin: 50% 50%;
      -moz-animation: left-to-center linear 1s;
      -moz-animation-iteration-count: 1;
      -moz-transform-origin: 50% 50%;
      -o-animation: left-to-center linear 1s;
      -o-animation-iteration-count: 1;
      -o-transform-origin: 50% 50%;
      -ms-animation: left-to-center linear 1s;
      -ms-animation-iteration-count: 1;
      -ms-transform-origin: 50% 50%;
    }

    @keyframes left-to-center{
      0% {
        transform:  translate(250px,0px)  ;
      }
      100% {
        transform:  translate(0px,0px)  ;
      }
    }

    @-moz-keyframes left-to-center{
      0% {
        -moz-transform:  translate(250px,0px)  ;
      }
      100% {
        -moz-transform:  translate(0px,0px)  ;
      }
    }

    @-webkit-keyframes left-to-center {
      0% {
        -webkit-transform:  translate(250px,0px)  ;
      }
      100% {
        -webkit-transform:  translate(0px,0px)  ;
      }
    }

    @-o-keyframes left-to-center {
      0% {
        -o-transform:  translate(250px,0px)  ;
      }
      100% {
        -o-transform:  translate(0px,0px)  ;
      }
    }

    @-ms-keyframes left-to-center {
      0% {
        -ms-transform:  translate(250px,0px)  ;
      }
      100% {
        -ms-transform:  translate(0px,0px)  ;
      }
    }

A: Add
transform: 'translate(-50%, -50%)'

to your Content class.
Another alternative is to use a different react modal component such as https://www.npmjs.com/package/react-modal-slider


text:
Q: Fusionchart custom message display inside the canvas I need to display message inside the fusionchart (I use Bar 2D Chart). I checked the API but I couldn't.
I need pass the xml message (I attached the image)
Can you please help me.
(gray color is the boarder of the chart)

A: Any way I found a way to implement this, but it used js (not using xml).
http://jsfiddle.net/shamasis/WzNKT/

This url help me lot, thank for the developer.
var myChart = new FusionCharts( "FusionCharts/Column3D.swf",
      "myChartId", "400", "300", "0" );
      myChart.setXMLUrl("Data.xml");
      myChart.render("chartContainer");

function myChartListener(eventObject, argumentsObject) {
    myChart.ref.showChartMessage("Hello... the world ends here, take a peek before its gone!", true);
    }
 myChart.addEventListener ("rendered" , myChartListener );

When this message display it effect some black background color (like below image)

If you want to change the style of the message or background color then you can change the css of SVG
.xxxxx div span svg rect {
    fill-opacity: 0;
}
.xxxxx div span svg g rect {
    fill-opacity: 1;
}
.xxxxx div span svg text tspan {
    fill: black;
    font-size: 12px;
}

(This css to get same as top image)


text:
Q: Java Error whilst attempting to run a web-client I'm having some problems while trying to open a web-client for a game that I play. I get this error and I don't know what to do. Help would be appreciated. If you need any more information please let me know and I will do the best I can to get it.
load: class client.class not found.
java.lang.ClassNotFoundException: client.class
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Exception: java.lang.ClassNotFoundException: client.class

A: It seems you are running your web client like this:
$ java client.class

Try running this instead:
$ java client


text:
Q: C# Interlocked functions as a lock mechanism? While I was reading about ReaderWriterLockSlim lock mechanism , There was this guy who suggested that Interlock Functions can be used for a  finer locking
Also, I found here another answer from Marc :

...Writes make their change to a cloned copy, then use
  Interlocked.CompareExchange to swap the reference (re-applying their
  change if another thread mutated the reference in the interim).

Well , Currently all I know about Interlocked object , is that it is used (in a multithreaded environment) to do atomic additions, compare , compareExchange operations. (and I know how to use it)
But (and here is my question) —
Question
How can I use it  as a lock ?  ( sample code will be much appreciated)
edit
For simplicity  , I'm pasting this code ( which is  not thread safe - if  Go was called by two threads simultaneously, it would be possible to get a division-by-zero error) :
class ThreadUnsafe
 {
   static int _val1 = 1, _val2 = 1;

   static void Go()
       {
        if (_val2 != 0) Console.WriteLine (_val1 / _val2);
        _val2 = 0;
       }
}

How can I use Interlock to replace the lock (which would have solved the problem) ?

A: Interlocked is used to implement lockless algorithms and data structures. It's therefore not "finer locking", or even locking at all. It lets you do small and well-defined operations safely in a multi-threaded environment: for instance, if you want two threads to increment the same variable, you can use Interlocked to do it instead of acquiring a heavyweight lock and using the "regular increment".
However, there are many, many things that you can't do with Interlocked that you could do under a regular lock. For instance, anything that involves modifying more than one variable atomically generally can't be done with Interlocked, so you wouldn't be able to use it for your example.
Interlocked can, however, help developers implement locking mechanism, though you might as well use the built-in ones. Most locks require kernel support to interrupt the blocked thread until the lock becomes available. Therefore, the only kind of lock that you can implement with Interlocked alone is a spin lock: a lock that threads continually try to acquire until it works.
class InterlockedLock
{
    private int locked;

    public void Lock()
    {
        while (Interlocked.CompareExchange(ref locked, 1, 0) != 0)
            continue; // spin
    }

    public void Unlock()
    {
        locked = 0;
    }
}

In this example, locked is initially zero. When a thread tries to acquire it for the first time, locked becomes 1, and subsequent threads trying to Lock it will spin until someone calls Unlock to make locked 0 again.

A: Interlocked.CompareExchange can be used to implement the equivalent of a SpinLock.
However it is perhaps better to lock at Interlocked as a way of avoiding locks entirely. As @zneak stated "Interlocked is used to implement lockless algorithms and data structures."
However I'm not sure that I agree with @zneak in the statement that "there are many, many things that you can't do with Interlocked". Not entirely true. Everything can be done with Interlocked. Its more a question of what is the point of using a mechanism built for avoiding locks in order to implement a lock... Just because it can be done does not mean it is a good idea. Kind of like trying to play soccer with a ping pong ball. Or using a formula 1 go kart to tow a ton of bricks. Sure you can do it, but... would you? really...
Note: In the code sample from @zneak a change is needed for it to be atomic (not read / write to L2 cache or some register etc...). In C# all writes are volatile by default but reads are not.
Either:
private int locked;

should be (to make the reads volatile)
private volatile int locked;

OR:
locked = 0;

should be (to force invalidation of any cached copies of this variable)
Interlocked.Exchange(ref locked, 0);

There are many valid use cases for using Interlocked.CompareExchange as a lock free mechanism.
For example singleton logic in say trimming an object pool by spinning of a task are X number of events. When starting the task to trim the object pool we do not know if the previous instance has finished. In other words execute the block of code only of another thread is not already executing it.
Another scenario is where you might want a lock that is a system of gates. In other words if state is 1 then do blah, if 2 then do blah blah, if 3 then do blah blah blah.
Here are some examples:
A thread safe looping counter: https://github.com/tcwicks/ChillX/blob/master/src/ChillX.Core/Structures/ThreadsafeCounter.cs
A lock free thread safe queue:
https://github.com/tcwicks/ChillX/blob/master/src/ChillX.Core/Structures/LockFreeQueue.cs
Note: It is important to realize is that in non trivial lock free implementations using Interlocked we will usually either spending a bit of cpu time spinning, or skipping tasks and coming back to them later, and/or compromising on some functions. For example it is "probably" impossible to implement a reliable threadsafe enumerator for the lock free queue above.
Note regarding using Interlocked, Monitor, ReaderWriterLock, ReaderWriterLockSlim etc... these will enforce a memory barrier which is quite expensive:
From: https://learn.microsoft.com/en-us/archive/msdn-magazine/2005/october/understanding-low-lock-techniques-in-multithreaded-apps

Unfortunately, interlocked operations are relatively expensive, on the order of several dozen to up to hundreds of times the cost of a normal instruction. The lower bound on the cost is related to the fact that interlocked operations guarantee that the update is atomic. This requires the processor to insure that no other processor is also trying to execute an interlocked operation on the same location at the same time. This round-trip communication with the memory system can take dozens of instruction cycles. The upper bound on the cost relates to the ordering guarantee these instructions provide. Interlocked instructions need to ensure that caches are synchronized so that reads and writes don't seem to move past the instruction. Depending on the details of the memory system and how much memory was recently modified on various processors, this can be pretty expensive (hundreds of instruction cycles).

Also bear in mind that depending on how long the lock is to be held a spinlock can provide better performance than the alternative mechanisms. However in these same scenarios Spinlock will outperform trying to do the same using Interlocked.CompareExchange. This is simply because the memory barrier is enforced when entering the Spinlock and optionally when we exit Spinlock.Exit(true). On the other hand (see code example below) with spinning on an Interlocked.CompareExchange we are enforcing a memory barrier multiple times again and again as we spin and once when we exit using Interlocked.Exchange.
From the same reference:

In a spin lock, exiting the lock does not require an interlocked operation because only the thread that owns the lock has access to the isEntered memory.

On true multiprocessor machines it is better to busy-wait rather than force a context switch with Sleep(0). Busy-waits should be done through something like System.Threading.SpinWait so that hyperthreaded processors are told that no useful work is being done and another logical CPU can use the hardware

Compare the performance of the lock free queue:
https://github.com/tcwicks/ChillX/blob/master/src/TestApps/ChillX.MQServer.Benchmark/LockFreeQueue.cs
against its equivalent which uses locking:
https://github.com/tcwicks/ChillX/blob/master/src/ChillX.Core/Structures/ThreadSafeQueue.cs
Above lock free queue is an extended version of Julian M Bucknall's Lock Free Queue. https://secondboyet.com/Articles/LockfreeQueue.html
His standard implementation is faster however it creates an object allocation on every insert which needs to then be cleared by the Garbage collector. The end result under heavy use or benchmark is 60% time spent in GC.
The extended version above uses memory pooled linked list nodes. However it still cannot keep up with the performance of its counterpart which uses locking. It comes close but considering that it has the additional overhead of linked list nodes which create GC pressure it is simply inferior since it cannot even match its counterparts performance.
This link below is a 99% lock free structure implemented from scratch without pooling but using a queue of ring buffers to minimize allocations. Its performance is twice as fast as the LockFreeQueue above. 367ms vs 607ms for 1000000 queue / dequeue operations across 8 threads. however it is still 50% slower than ThreadSafeQueue which uses ReaderWriterLockSlim.
https://github.com/tcwicks/ChillX/blob/master/src/ChillX.Core/Structures/LockFreeRingBufferQueue.cs
Since you asked for an example of using Interlocked as a lock. The following code demonstrates a SpinLock using Interlocked.CompareExchange instead of SpinLock.
In this code example if syncronization does not work then then RunCounter will move to -1 or 2. If it works then RunCounter will stay within the values of 0 and 1.
private static volatile int StopSignal = 0;
private static int IsRunning = 0;
private static int RunCounter = 0;
private static object locker = new object();
private static void ContendIncDec()
{
    while (StopSignal == 0)
    {
        //equivalent of SpinLock.Enter().
        while (Interlocked.CompareExchange(ref IsRunning, 1, 0) != 0)
        {
            //And we are spinning.
            //But why not SpinLock.Enter() instead cause it is a far better version the same thing...
            //Sure we could do a Thread.Sleep(0); but Monitor does a far better job by blocking the thread.
        }
        if (RunCounter == 0) { RunCounter++; }
        //Do more cool stuff here

        //equivalent of SpinLock.Exit().
        Interlocked.Exchange(ref IsRunning, 0);

        //equivalent of SpinLock.Enter().
        while (Interlocked.CompareExchange(ref IsRunning, 1, 0) != 0)
        {
            //And we are spinning.
            //But why not SpinLock.Enter() instead cause it is a far better version the same thing...
            //Sure we could do a Thread.Sleep(0); but Monitor does a far better job  by blocking the thread once and resuming once.
        }
        if (RunCounter == 1) { RunCounter--; }
        //Do more cool stuff here

        //equivalent of SpinLock.Exit().
        Interlocked.Exchange(ref IsRunning, 0);
    }
}

static void Main(string[] args)
{
    List<Thread> testThreads = new List<Thread>();
    for (int I = 0; I < 10; I++)
    {
        Thread T = new Thread(new ThreadStart(ContendIncDec));
        testThreads.Add(T);
        T.Start();
    }
    Stopwatch swTest = new Stopwatch();
    swTest.Start();
    while (swTest.ElapsedMilliseconds < 5000)
    {
        Thread.Sleep(0);
    }
    Interlocked.Exchange(ref StopSignal, 1);
    foreach(Thread t in testThreads)
    {
        t.Join();
    }
    Console.WriteLine(@"FinalCount is: {0}  (Note: this should be either 1 or 0 if the locking structure works.)", RunCounter);

As a final note here are some benchmarks where the work done within the locked section is the smallest possible realistic work. In this case 4 threads are queueing 10,000 items each while another 4 threads are DeQueueing the 40,000 items. All 8 threads are competing for the same shared queue. Threads are started and then blocked using a ManualResetEvent so they all started doing their work simultaneously.
Using the Interlocked structure in the code sample above has the worst and most inconsistent performance of the lot with some runs taking 80ms and some taking 521 ms.
An interesting note is that in such a do minimal work scenario SpinLock.Enter() should have won over ReaderWriterLockSlim.EnterWriteLock().
However ReaderWriterLockSlim.EnterWriteLock() is almost 4 times faster.
BenchmarkDotNet=v0.13.1, OS=Windows 10.0.19044.1645 (21H2)
AMD Ryzen Threadripper 3970X, 1 CPU, 64 logical and 32 physical cores
.NET SDK=6.0.202
  [Host]   : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT  [AttachedDebugger]
  .NET 6.0 : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT

Job=.NET 6.0  Runtime=.NET 6.0

|                Method |           m_TestMode | numRepititions | numThreads |      Mean |     Error |     StdDev | Completed Work Items | Lock Contentions | Allocated |
|---------------------- |--------------------- |--------------- |----------- |----------:|----------:|-----------:|---------------------:|-----------------:|----------:|
| Bench_LockPerformance |     LockReaderWriter |          40000 |          4 | 166.47 ms | 15.845 ms |  46.719 ms |                    - |                - |  22,672 B |
| Bench_LockPerformance | LockReaderWriterSlim |          40000 |          4 |  19.93 ms |  1.047 ms |   3.053 ms |                    - |                - |      24 B |
| Bench_LockPerformance |          LockMonitor |          40000 |          4 |  21.73 ms |  0.896 ms |   2.643 ms |                    - |         111.4063 |       4 B |
| Bench_LockPerformance | SpinLock.Exit(false) |          40000 |          4 |  80.75 ms |  6.081 ms |  17.643 ms |                    - |                - |      96 B |
| Bench_LockPerformance |  SpinLock.Exit(true) |          40000 |          4 |  89.09 ms |  6.515 ms |  19.108 ms |                    - |                - |      60 B |
| Bench_LockPerformance |      LockInterlocked |          40000 |          4 | 321.08 ms | 54.203 ms | 159.818 ms |                    - |                - |      69 B |

Here are the benchmark results for LockFreeRingBufferQueue  versus ThreadSafeQueue (ReaderWriterLockSlim) versus the standard ConcurrentQueue
OS=Windows 10.0.19044.1645 (21H2)
AMD Ryzen Threadripper 3970X, 1 CPU, 64 logical and 32 physical cores
.NET SDK=6.0.202
  [Host]   : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT  [AttachedDebugger]
  .NET 6.0 : .NET 6.0.4 (6.0.422.16404), X64 RyuJIT

Job=.NET 6.0  Runtime=.NET 6.0

| Method                 | m_TestMode           | numRepititions | numThreads | Mean      | Error      | StdDev     | Lock Contentions  |     Gen 0  |     Gen 1  |    Gen 2  | Allocated  |
|----------------------- |--------------------- |--------------- |----------- |----------:| ----------:| ----------:| -----------------:| ----------:| ----------:| ---------:| ----------:|
| Bench_QueuePerformance | RingBufferQueue      | 1000000        | 1          | 80.31 ms  | 3.194 ms   | 8.742 ms   | -                 | 3400.0000  | 1400.0000  | -         | 28,566 KB  |
| Bench_QueuePerformance | ThreadSafeQueue      | 1000000        | 1          | 96.60 ms  | 1.910 ms   | 3.901 ms   | -                 | -          | -          | -         | 1 KB       |
| Bench_QueuePerformance | ConcurrentQueueCount | 1000000        | 1          | 70.94 ms  | 1.410 ms   | 2.750 ms   | -                 | 500.0000   | 500.0000   | 500.0000  | 2,948 KB   |
| Bench_QueuePerformance | ConcurrentQueueTry   | 1000000        | 1          | 49.13 ms  | 2.274 ms   | 6.704 ms   | 0.1250            | -          | -          | -         | 283 KB     |
| Bench_QueuePerformance | RingBufferQueue      | 1000000        | 4          | 367.08 ms | 10.954 ms  | 32.128 ms  | -                 | 3000.0000  | 1000.0000  | -         | 28,566 KB  |
| Bench_QueuePerformance | ThreadSafeQueue      | 1000000        | 4          | 253.59 ms | 12.344 ms  | 36.398 ms  | -                 | -          | -          | -         | 1 KB       |
| Bench_QueuePerformance | ConcurrentQueueCount | 1000000        | 4          | 341.09 ms | 12.249 ms  | 36.116 ms  | 18.5000           | -          | -          | -         | 1,540 KB   |
| Bench_QueuePerformance | ConcurrentQueueTry   | 1000000        | 4          | 266.15 ms | 13.365 ms  | 39.408 ms  | 11.6667           | 333.3333   | 333.3333   | 333.3333  | 2,223 KB   |

Benchmark implementation if you want to try it out is here:
https://github.com/tcwicks/ChillX/blob/master/src/TestApps/ChillX.MQServer.Benchmark/Bench_Queue.cs
If you download the repository https://github.com/tcwicks/ChillX and run ChillX.MQServer.Benchmark console app - choose 2 from the menu to benchmark queues

A: Locking with Interlocked is done by replacing a new value with an old value only if the old value hasn't changed. If it has we try again until it doesn't (spinning).
This can be used to replace fine grained locks that only update a single value or to implement a lightweight locking mechanism like SpinLock.
Example:
private int _value;

int oldValue;
int originalValue;
do
{
    oldValue = _value;
    originalValue = Interlocked.CompareExchange(ref _value, newValue, oldValue);
}
while (originalValue != oldValue);

Instead of:
lock(_lock)
{
    _value = newValue;
}


text:
Q: Winform control inside HTML page We are trying to develop a web enabled application to read serial port data (weigh bridge data). We developed a winform control to real the serial/com port.
We added the control inside an html file and published it.
For testing we created a simple label in winform and tried to access it via javascript.
Winform with label

    using System;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    namespace WindowsFormsControlLibrary1
    {
        [ComVisible(true)]
        public partial class UserControl1: UserControl
        {
            public UserControl1()
            {
                InitializeComponent();
            }
            public void SendMessage(string msg)
            {
                _lblMessage.Text = msg;
            }
        }
    }

Javascript function inside HTML

    function SendMessageToWinControl()
        {
         var winCtrl = document.getElementById("MyWinControl");
         winCtrl.SendMessage("Message sent from the HTML page!!");
        }

Declared the object uisng the classid

    classid="http:WindowsFormsControlLibrary1.dll#WindowsFormsControlLibrary1.UserControl1"

We provided everyone access to the folder. Added the Allow Extension from path in ISAPI.
But what we get is the following screen,

Can someone please help? We are using .net 4.0
Thanks in advance.


text:
Q: Is DwmIsCompositionEnabled still of use in Windows 8? According to Enable and Control DWM Composition:

Note  As of Windows 8, the information in this section is no longer
  valid. DWM can no longer be programmatically disabled, nor is it
  disabled when an application attempts to draw to the primary display
  surface. The following information applies to only Windows 7 and
  earlier systems.

OK. So we can no longer programmatically disable DWM. But can it still be disabled? Will pfEnabled of DwmIsCompositionEnabled always be set to TRUE on Windows 8?
If composition can be disabled somehow, is DwmIsCompositionEnabled still somewhat useful in any manner?

A: According to Desktop Window Manager is always on (Windows) on MSDN:

In Windows 8, Desktop Window Manager (DWM) is always ON and cannot be
disabled by end users and apps.
In Windows 8, DWM desktop composition is a core operating system
component and cannot be disabled. With a few exceptions, desktop
composition is always on; it's started before the user logon and
remains active for the duration of a session.
All of the options for disabling desktop composition that exist in
Window 7 are removed
Apps cannot use DwmEnableComposition to disable desktop composition.
In order to maintain backward compatibility, a call to this API will
return success; however, desktop composition is not disabled

Well, there's a pretty definitive answer. I'm somewhat curious what the "with a few exceptions" refers to, though... please add a comment if you happen to know. :)

A: Contrary to what people mention ("they removed the code", "the Basic theme is no longer there", etc.)  the old visual style is alive and well in Windows 8.
The only problem is that it's not so clear how to use it for normal applications!
This isn't disabling DWM per se, but it is certainly disabling composition: just download the PowerToy Calculator for Windows XP and try running it in compatibility mode in Windows 8, and you'll see the old theme is still there:


text:
Q: 500 Internal Server Error heroku По нажатию кнопки получаю список ближайших больниц, но на heroku дает ошибку 500.
check.html
<form action="/check" method="POST">
    <button type="check" class="btn btn-primary">Nearest Hospitals</button>
</form>

   {% for place in places %}

{{ place.name }}

   {% endfor %}

python
from googleplaces import GooglePlaces, types, lang
import geocoder

g = geocoder.ip('me')
lt_lg = g.latlng

lt = lt_lg[0]
lg = lt_lg[1]

@app.route('/check', methods=['POST'])
def check():
    API_KEY = 'API_KEY'

    google_places = GooglePlaces(API_KEY)

    query_result = google_places.nearby_search(
            lat_lng ={'lat': lt, 'lng': lg},
            radius = 5000,
            types =[types.TYPE_HOSPITAL])

    if query_result.has_attributions:
        print (query_result.html_attributions)

    for place in query_result.places:
        return render_template('check.html', places=query_result.places)

Полез в логи, там такая ошибка. Как решить, может кто сталкивался. Спасибо.
GooglePlacesError: Request to URL https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.808%2C-76.0284&type=hospital&radius=1000&key=MY_KEY&language=en&sensor=false failed with response code: OVER_QUERY_LIMIT


text:
Q: How to solve this system of equations systematically? This might seem a trivial problem, but I have some trouble in arranging the data. So suppose you are given $f(x,y)=x^2y^2(1+x+2y)$ and you want to find it's critical points. Thus we find
$$\frac{\partial f}{\partial x}(x,y)=xy^2(2+3x+4y)\textrm{ and }\frac{\partial f}{\partial y}(x,y)=2x^2y(1+x+3y).$$
Now we set $f_x= 0$ and $f_y=0.$  Thus we get a system
$$
\begin{split}
xy^2(2+3x+4y) &=0\\
2x^2y(1+x+3y) &=0
\end{split}
$$
Now we have a bunch of cases. The way I think about this is as follows:
$$((x=0)\lor(y=0)\lor(3x+4y=-2))\land((x=0)\lor(y=0)\lor(x+3y=-1)).$$
Then I consider each possibility separately, but this seems to be slow and sometimes I forget some solutions. Thus I was wondering if there are any other methods which one can use to solve such type of problems.

A: For $xy^2(2+3x+4y) =0$ we have the set of solutions
$$S_1 = \{x = 0, y = 0, 2+3x+4y = 0\}$$
For $2x^2y(1+x+3y) =0$ we have the set of solutions
$$S_2 = \{x = 0, y = 0, 1+x+3y = 0\}$$
So for the system of equations we have
$$S_1 \cap S_2  = \{x = 0, y = 0, (2+3x+4y = 0)\cap(1+x+3y = 0)\} =  \{x = 0, y = 0\}\cup \{x=-\frac 25, y = -\frac 15\}$$

A: Use the converse of the distributive property:
$((x=0)\lor(y=0)\lor(3x+4y=-2))\land((x=0)\lor(y=0)\lor(x+3y=-1))\\\equiv(x=0)\lor(y=0)\lor[(3x+4y=-2)\land(x+3y=-1)]$
$3x+4y+2=0=x+3y+1$ is just a pair of straight lines (linear equations) intersecting at $(-2/5,-1/5)$. Therefore, you have $(x=0)\lor(y=0)\lor(x=-2/5\land y=-1/5)$


text:
Q: Bounded Linear Operator from $C_0([0,1])$ to $C([0,1])$
Define
$$
C_0([0,1]) := \left\{f\in C([0,1]) : \int_0^1f(t)\, \mathrm dt=0\right\}.
$$
Show that $T : C_0([0,1]) \to C([0,1])$, given by
$$
(Tf)(x) := \int_0^x(t-x) f(t) \, \mathrm dt,
$$
defines a bounded linear operator.

I proved $\Vert T \Vert \leq \frac 1 2$, but I could not find some $f \in C_0([0,1])$ such that $\Vert f \Vert = 1$ and $\Vert T f \Vert = \frac 1 2$.
Here is how to prove $\|T\|\leq \frac12$.
Note that
$$\|Tf\|=\sup_{x\in[0,1]}\,\left|\int_0^x\,(t-x)\,f(t)\,\text{d}t\right|\leq \sup_{x\in [0,1]}\,\int_0^x\,|t-x|\,\big|f(t)\big|\,\text{d}t\,.$$
Since $\big|f(t)\big|\leq \|f\|$ for all $t\in[0,1]$, we get
$$\|Tf\|\leq \sup_{x\in[0,1]}\,\int_0^x\,|t-x|\,\|f\|\,\text{d}t\leq \sup_{x\in[0,1]}\,\|f\|\,\int_0^x\,(x-t)\,\text{d}t\,.$$
Therefore,
$$\|Tf\|\leq \|f\|\,\sup_{x\in[0,1]}\,\int_0^x\,(x-t)\,\text{d}t\leq \|f\|\,\sup_{x\in [0,1]}\,\int_0^x\,(1-t)\,\text{d}t\,.$$
So,
$$\|Tf\|\leq \|f\|\,\int_0^1\,(1-t)\,\text{d}t=\frac{1}{2}\,\|f\|\,.$$

A: Let $f\in \mathcal{C}_0\big([0,1]\big)$.  Fix $x\in[0,1]$.  Note that
$$-Tf(x)=\int_0^x\,(x-t)\,f(t)\,\text{d}t=\int_0^x\,\int_t^x\,f(t)\,\text{d}s\,\text{d}t=\int_0^x\,\int_0^s\,f(t)\,\text{d}t\,\text{d}s\,.$$
Write
$$If(x):=\int_0^x\,f(t)\,\text{d}t\,.$$
Then,
$$-Tf(x)=\int_0^x\,If(s)\,\text{d}s\,.$$
Observe that
$$\big|If(x)\big|\leq \int_0^x\,\big|f(t)|\,\text{d}t\leq \|f\|_\infty\,x$$
and
$$\big|If(x)\big|=\big|If(1)-If(x)\big|=\left|\int_x^1\,f(t)\,\text{d}t\right|\leq \|f\|_\infty\,(1-x)\,.$$
Thus,
$$\big|If(x)\big|\leq \|f\|_\infty\,\min\{x,1-x\}\,.$$
Ergo,
$$\big|Tf(x)\big|\leq \int_0^x\,\big|If(s)\big|\,\text{d}s\leq \|f\|_\infty\,\int_0^x\,\min\{s,1-s\}\,\text{d}s\,.$$
This implies
$$\big\|Tf\big\|_\infty\leq \|f\|_\infty\,\int_0^1\,\min\{s,1-s\}\,\text{d}s=\frac{1}{4}\,\|f\|_\infty\,.\tag{*}$$
Therefore, $\|T\|_\text{op}\leq \dfrac14$.
Note that (*) is an equality if and only if $f\equiv 0$, since the equality case occurs only when there exists $\epsilon$ such that $|\epsilon|=1$ and $If(x)=\epsilon\,\|f\|_\infty\,\max\{x,1-x\}$ for all $x\in[0,1]$.  This condition, along with the fact that $f$ is continuous, implies that $f\equiv 0$ is the only possible choice.  However, we can find a sequence $\left(f_n\right)_{n=1}^\infty$ of functions $f_n\in\mathcal{C}_0\big([0,1]\big)$ satisfying $\|f_n\|_\infty=1$ and $\lim\limits_{n\to\infty}\,\|Tf_n\|_\infty=\dfrac14$.  For each $n=1,2,3,\ldots$, take
$$f_n(x)=\left\{
\begin{array}{ll}
-1&\text{if }0\leq x\leq \dfrac{1}{2}-\dfrac1{2n}\,,\\
2n\left(x-\dfrac12\right)&\text{if }\dfrac{1}{2}-\dfrac{1}{2n}<x<\dfrac12+\dfrac1{2n}\,,\\
+1&\text{if }\dfrac12+\dfrac1{2n}\leq x\leq 1\,.
\end{array}
\right.$$
Observe that
$$\|Tf_n\|_\infty=Tf_n(1)=\dfrac14-\dfrac1{12n^2}$$
for every positive integer $n$.


text:
Q: How can I check if a string of a key from a ComboBox is pressed in VB.NET? I have a combobox in my form. It contains all these keys:
BACKSPACE
BREAK
CAPS LOCK
DELETE
END
ENTER
ESC
HELP
HOME
INSERT
NUM LOCK
PAGE DOWN
PAGE UP
PRINT SCREEN
SCROLL LOCK
TAB
UP ARROW
DOWN ARROW
LEFT ARROW
RIGHT ARROW
F1
F2
F3
F4
F5
F6
F7
F8
F9
F10
F11
F12
F13
F14
F15
F16

For example when the key selected in the combobox is pressed do something. How can I do that?

A: There's a number of ways I could see this going. One would be to create an object with two attributes: one being the key name string and the other being the key itself. Then bind this to the combo box with the key name string as the displayed item.
Another would be to convert the text of your combobox to the key itself using this function:
Public Function KeyFromString(theKey As String) As Keys
    Dim kc As KeysConverter = New KeysConverter()
    Return CType(kc.ConvertFrom(theKey), Keys)
End Function

like so in whatever key pressed event you are using:
if e.key = KeyFromString(combobox.text) then
'do work
end if


text:
Q: Sort array of arrays by another array's elements JS Many similar questions but none seem to really apply to this.
I am trying to sort the order of arrays in ArrayA based on the elements in ArrayB in JavaScript
For example, ArrayA and ArrayB are as follows.
ArrayA = [
    ['1', '123', '321'],
    ['2', '456', '654'],
    ['3', '789', '987'],
    ['4', '420', '314']
]

ArrayB = ['2', '1', '4', '3'];

I basically want to map the order of the arrays inside ArrayA to match the order of the elements in ArrayB. I want to be able to do this with any sized arrays not just 4... (assuming they are the same size)
The desired output is below:
ArrayA = [
    ['2', '456', '654'],
    ['1', '123', '321'],
    ['4', '420', '314'],
    ['3', '789', '987']
]

I've tried many .sort() solutions and manual loops and nothing seems to work (such as the one below and yes I know its wrong). So just wondering if anyone has any ideas. TIA!
ArrayA.sort((a, b) => ArrayB.indexOf(a.ArrayA) - ArrayB.indexOf(b.ArrayA));

A: You can use Array#sort with Array#indexOf as follows:

const
    ArrayA = [
        ['1', '123', '321'],
        ['2', '456', '654'],
        ['3', '789', '987'],
        ['4', '420', '314']
    ],

    ArrayB = ['2', '1', '4', '3'],

    Ordered = ArrayA.sort(
        //since each element of ArrayA is an array with 3 elements
        //[a] or [a,,] denotes the first element as a
        //[b] or [b,,] is also the first element of the element of
        //ArrayA being compared, else you have to use:
        //(a,b) => ArrayB.indexOf(a[0]) - ArrayB.indexOf(b[0])
        ([a],[b]) => ArrayB.indexOf(a) - ArrayB.indexOf(b)
    );

    console.log( Ordered );

REF
Destructuring

A: using normal for loop

const ArrayA = [
  ["1", "123", "321"],
  ["2", "456", "654"],
  ["3", "789", "987"],
  ["4", "420", "314"],
];

const ArrayB = ["2", "1", "4", "3"];

const sorted = (a, b) => {
  let result = [];

  for (let i = 0; i < a.length; i++) {
    for (let j = 0; j < b.length; j++) {
      if (a[i][0] === b[j]) {
        result.push(a[j]);
        break;
      }
    }
  }

  return result;
};

console.log(sorted(ArrayA, ArrayB));

basically, we check if the number in arrayA is equal to the number in B,
if yes we push the current array, and we break the loop and continue repeating until we finish

this solution is great if you want:

*

*without any other external methods

*native code


text:
Q: Django- ListView returning a list of users with a given tag in a tag field I'm trying to return a list of users with a particular skill and skills is a TagField (django taggit) in a CustomUser model. I'm struggling to get the queryset right in my ListView (skill_list.html). I want to be able to click on the skill listed on a user's profile (profile.html) and then have that return the skill list page with a list of all users that have that skill.
models.py:
class CustomUser(AbstractUser):
    objects = CustomUserManager()
    position = models.CharField(max_length =200, null=True, default='',
    blank=True)
    bio = models.CharField(max_length=400, null=True, default='',
    blank=True)
    skills = TaggableManager(help_text="A comma-separated list of tags.")

views.py:
class SkillView(ListView):
model = CustomUser
template = 'skill_list.html'
queryset = CustomUser.objects.all()

def get_queryset(self):
    queryset = CustomUser.objects.filter(skills__name__in=
    [self.kwargs['skill']])
    return queryset

profile.html:

            {% for skill in user.skills.all %}

{{ skill.name }}

            {% endfor %}

skill_list.html:

    {% for user in object_list %}

{{ user.first_name }}&nbsp{{ user.last_name }}

{{user.position}}

I have the url set up on the profile page to return the 'skill_list.html', however I get an key error on the skill_list page: Exception value "skill."

A:
I want to be able to click on the skill listed on a user's profile (profile.html) and then have that return the skill list page

In that case, the URLs need to include the skill in them, e.g. /skills/python/ or /skills/sql/.
You can do this by changing the URL to something like:
path('skills/<slug:skill>', views.SkillView.as_view(), name='skills')

Now self.kwargs['skill'] will work in the SkillView.get_queryset method.
You now need to include the skill in the URL tag, for example:
{% url 'skills' skill %}

Finally, since you are only using a single item in your list,
queryset = CustomUser.objects.filter(skills__name__in=[self.kwargs['skill']])

you can remove the __in and change the query to:
queryset = CustomUser.objects.filter(skills__name=self.kwargs['skill'])

A: I think it should be :request.user instead of user in profile.html

A: Then why dont you just use a 'Q' search query. Check it in the docs


text:
Q: Cloud Run error: Container failed to start. Failed to start and then listen on the port I have done everything precisely as I think I should. My application works if I run it on the cloud.
The commands I run:
gcloud builds submit --tag gcr.io/****
gcloud run deploy *** --region us-central1 --platform managed --image gcr.io/t*** --allow-unauthenticated --port=26951
Dockerfile:
FROM mcr.microsoft.com/dotnet/sdk

COPY . /app

WORKDIR /app

RUN dotnet publish -c Release -o out

ENTRYPOINT ["dotnet", "Test.dll"]

Program:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Server
{
    class Program
    {
        private static TcpListener tcpListener;
        public static void Main(string[] args)
        {

            tcpListener = new TcpListener(IPAddress.Any, 26951);

            tcpListener.Start();

            tcpListener.BeginAcceptTcpClient(TCPConnectCallback, null);

        }
        private static void TCPConnectCallback(IAsyncResult _result)
        {
            TcpClient _client = tcpListener.EndAcceptTcpClient(_result);
        }
    }
}

CSProj:
<Project Sdk="***">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

</Project>

All of which are in the same location

A: The solution is to alter the dockerfile like so:
FROM mcr.microsoft.com/dotnet/sdk:3.1 WORKDIR /app

COPY . .

ENTRYPOINT ["dotnet", "run"]