text:
Q: How to specify maven properties in a aggregator POM? I have a project structure like below.In aggregator POM project1 and project 2 are defined as modules.Now if i want to add a maven property that can be accessed in all the projects how can i do it?.
What is the best project structure in this case.?
If i define property like <temp.dir>data</temp.dir> in the aggregator POM then it is not available in project1 pom.xml and project2 POM.xml.I have to duplicate the same property in both the POM's.
project
- project1
- - pom.xml  ---- has parent POM as project A
- project2
- - pom.xml  --- has parent POM as project B
- pom.xml (Aggregator POM)

UPDATE:To clarify more project1 pom and project 2 has different parent POM's.So aggregator POM cannot be set as parent.

A: Here is aggregator's pom:
<groupId>y</groupId>
<artifactId>y</artifactId>
<version>0.0.1</version>
<packaging>pom</packaging>
<modules>
    <module>y1</module>
    <module>y2</module>
</modules>
<properties>
    <x>1</x>
</properties>

This is y1 effective pom (generated by Eclipse):
  <parent>
    <groupId>y</groupId>
    <artifactId>y</artifactId>
    <version>0.0.1</version>
  </parent>
  <groupId>y1</groupId>
  <artifactId>y1</artifactId>
  <version>0.0.1</version>
  <properties>
    <x>1</x>
  </properties>

As you can see property x declared in parent is inherited by child.

A: You need to set the aggregator pom as the parent of project1 and project2.
eg. in project1 and project2 poms add:
<parent>
    <groupId>com.agr</groupId>
    <artifactId>project-aggregator</artifactId>
    <version>1.0.0</version>
</parent>

EDIT:
I understand that project1 and project2 have different parent poms.
The only solution i know about to achieve what You want is to store the properties in parent pom.
I can think only of one solution, to make an inheritance chain:
Project2Parent:
<parent>
    <groupId>com.test</groupId>
    <artifactId>Project1Parent</artifactId>
    <version>0.0.1</version>
</parent>
<artifactId>Project2Parent</artifactId>
<version>0.0.1</version>

Aggregator:
<parent>
    <groupId>com.test</groupId>
    <artifactId>Project2Parent</artifactId>
    <version>0.0.1</version>
</parent>
<artifactId>Aggregator</artifactId>
<version>0.0.1</version>

Project1
<parent>
    <groupId>com.test</groupId>
    <artifactId>Aggregator</artifactId>
    <version>0.0.1</version>
</parent>
<artifactId>project1</artifactId>
<version>0.0.1</version>

Project2
<parent>
    <groupId>com.test</groupId>
    <artifactId>Aggregator</artifactId>
    <version>0.0.1</version>
</parent>
<artifactId>project2</artifactId>
<version>0.0.1</version>


text:
Q: How to detect an operator like '[' in a character-variable Let's say I have character variables like "var" and "var[1]". How could I detect whether there are operators [] in the character?
I have been looking into strsplit and agrep but so far without succes..
Many thanks!

A: Trivial regexp escaping of special characters:
> x=c("var","var[1]")
> grepl("\\[",x)
[1] FALSE  TRUE

Read up on regular expressions: help(regexp)

A: To get values finded with their index:
 x <- "var[22]"
 m <- regexpr("\\[.*\\]", x, perl=TRUE)
 > regmatches(x, m)
 [1] "[22]"

Or to get values:
 > grep("\\[.*\\]", c("var[2]"), perl=TRUE, value=TRUE)
 [1] "var[2]"

to get index:
> grep("\\[.*\\]", c("var[2]"), perl=TRUE, value=FALSE)
[1] 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Copying values from one field to another in a Django model I have a Django model which has fields like: prodId, price, current stock, previous stock etc. The current stock data changes in an hour or so. Now whenever that happens, I need to copy values from current stock column into previous stock column and update the current stock column(along with prodId, price etc.) by fetching data from a server. Also, in the fetched data, I am just getting prodId, price and current stock, not the previous stock. In all, I need to fetch data from server, copy data from one field to another and then populate the model again from the fetched values. How can the desired functionality be achieved using Django?

A: Supposing you are getting the data from the server as a json which when parsed gives a dictionary.
json_data = data_from_server()
dict_data = json.loads(json_data)
prod_id = dict_data['product_id']
product = Product.objects.get(product_id=prod_id)
product.previous_stock = product.current_stock
product.current_stock = dict_data['current_stock']  #update current stock got from server
product.price = dict_data['price']
product.save()


text:
Q: Symfony2: kernel.request, onKernelRequest not loading I mostly using in each bundle kernel.request and everything is working find, but not in one.
The services.yml looks like below:
services:
    crm.addressbook.country_manager:
        class: CRM\AddressBookBundle\Country\CountryManager
        arguments: [ @doctrine.orm.dynamic_entity_manager ]
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

and the CountryManager:
namespace CRM\AddressBookBundle\Country;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\SecurityContext;

class CountryManager {

    protected $em;
    protected static $country;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function onKernelRequest()
    {
        $this->loadCountry();
    }

    private function loadCountry()
    {
        $country = $this->em->getRepository('CRMAddressBookBundle:CountryLang')->findAll();

        foreach($country as $row)
        {
            self::$country[$row->getCountry()->getId()] = $row->getName();
        }
    }

}

Does anyone knows what can be wrong? I am not getting any errors. It is just not starting the code...


text:
Q: Horizontal concatenation of two array how to do horizontal concatenation of two arrays in javascript?
var a = [[1,2],[3,4], [5,6]]
var b = [7,8,9]

I want output like :
c = [[1,2,7], [3,4,8], [5,6,9]]

A: You can use map and use index to access corresponding value from second array

var a = [[1,2],[3,4], [5,6]]
var b = [7,8,9]

let final = a.map((v,i)=> v.concat(b[i]))

console.log(final)


text:
Q: How to Parse a Nested JSON response in Android I Have this JSON response and I need to parse it. How can I do it.
I have the the entire json in
JSONObject response = new JSONObject(result);

How can I parse all JSON arrays and strings from below response.
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]

I'm new to JSON parsing, someone could please write the entire code.
Thanks

A: use following function .just pass your url.
  private void getData(String url) {
    pDialog = new ProgressDialog(this);
    pDialog.setMessage(getResources().getString(R.string.app_name));
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
    //   String url = "http://httpbin.org/html";
    Log.d("soh_into_get", url);

    jsonArray = new JsonArrayRequest(Request.Method.GET, url,
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray data) {
                    try {

                        Log.d("soh_json", String.valueOf(data));

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject jObj = data.getJSONObject(i);
                            ImagesDataModel pModel = new ImagesDataModel();

                            pModel.image_id = jObj.getString("image_id");
                            Log.d("image_id", jObj.getString("image_id"));
                            JSONArray jsonArray = jObj.getJSONArray("comments");
                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jObj1 = jsonArray.getJSONObject(j);
                                ChildListDataModel cModel = new ChildListDataModel();
                                cModel.comment_id = jObj1.getString("comment_id");
                                cModel.user_id = jObj1.getString("user_id");
                                cModel.comment = jObj1.getString("comment");
                                cModel.commented_on = jObj1.getString("commented_on");
                                pModel.childList.add(cModel);

                            }
                            JSONArray jsonArray = jObj.getJSONArray("likes");
                            for (int j = 0; j < jsonArray.length(); j++) {
                                JSONObject jObj1 = jsonArray.getJSONObject(j);
                                ChildListDataModel_like clModel = new ChildListDataModel_like();
                                clModel.like_id = jObj1.getString("like_id");
                                clModel.user_id = jObj1.getString("user_id");
                                clModel.liked_on = jObj1.getString("liked_on");
                                pModel.childList.add(clModel);

                            }

                            questionDataModel_List.add(pModel);
                            // setData();

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    pDialog.dismiss();
                    jsonArray = null;
                }

            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //SetOffLineData();
            pDialog.dismiss();
            // Error handling
            System.out.println("Something went wrong!");
            error.printStackTrace();

        }
    });
    jsonArray.setRetryPolicy(new DefaultRetryPolicy(
            8000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    Volley.newRequestQueue(this).add(jsonArray);
}

create data model ImagesDataModel.class
public class QuestionDataModel {

public String image_id;
public List<ChildListDataModel> childList = new ArrayList<>();
public List<ChildListDataModel_like > childList2 = new ArrayList<>();

}
and two child list classes
public class ChildListDataModel {
public String comment_id;
public String user_id;
public String comment;
public String commented_on;

}

A: Things you need to do
1--> Make JSON Parser seprate class for encoding and decoding JSON String.
2--> Make Aysnc class for JSON data downloading and extract in separate variables or in array with the help of JSON Parser class.
3--> perform Internet and server availability before downloading data by making class or method for it.
4--> After successfully data receiving in OnpostExcecute() Method of Async class show data in UI elements.

JSONParser.java
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public static String Result=null;

    public JSONParser()
    {

    }

    public static JSONObject makeHttpRequest(String url,String method, List<NameValuePair>  pair) {

        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(pair));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(pair, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, HTTP.UTF_8), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Result = json;
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jObj;
    }

}

NetCheck.java in your Activity class
public class NetCheck extends AsyncTask<String,Object,Boolean>
    {

        private ProgressDialog nDialog;
        NetworkInfo netInfo;

        @Override
        protected void onPreExecute() {

            nDialog = new ProgressDialog(NetCheck.this);
            nDialog.setTitle("Checking");
            nDialog.setMessage("Loading..");
            nDialog.setIndeterminate(false);
            nDialog.setCancelable(true);
            nDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Boolean doInBackground(String... params) {

            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            netInfo = cm.getActiveNetworkInfo();

            if (netInfo != null && netInfo.isConnected()) {
                try {
                    URL url = new URL("http:/xxxxxxx");
                    HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
                    urlc.setConnectTimeout(1000);
                    urlc.connect();
                    if (urlc.getResponseCode() == 200) {
                        return true;
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                return true;
            }

            else
            {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean th) {

            if (th)
            {
                nDialog.dismiss();
                new ProcessDataClass().execute();
            }

            else
            {

                new AlertDialog.Builder(NetCheck.this)
                        .setTitle("Record Not Found or Server is Busy")
                                //.setMessage("Are you sure you want to delete this entry?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                // continue with delete
                                nDialog.dismiss();
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
            super.onPostExecute(th);
        }
    }

ProcessDataClass.java in also Activity class
 public class ProcessDataClass extends  AsyncTask<String, Object,Object>
{

    @Override
    protected String doInBackground(String... params) {

        JSONObject json;
        List<NameValuePair> pair = new ArrayList<>();

        //make ypur own pair for reciving data
        //pair.add(new BasicNameValuePair("id", String.valueOf(index)));

        json = JSONParser.makeHttpRequest("http://xxxx","GET",pair);
        Log.d("Route Response", json.toString());

        int success = 0;

        try {
            // Success TAG only deals with API response not neccessory depends on API extracting or from URL TAG's
            success = json.getInt(TAG_SUCCESS);
        }

        catch (JSONException e) {
            e.printStackTrace();
        }

        try {

                if (success == 1) {

                    JSONArray jsonarray;
                    json = new JSONObject(JSONParser.Result);
                    JSONArray jArray = json.getJSONArray("your TAG");

                    for (int i = 0; i <jArray.length(); i++) {

                        jsonarray = jArray.getJSONArray(i);

                       //Do your Logic there

                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {

           //Update UI as per your need

            super.onPostExecute(o);
        }
    }
}

Add following line in Gradle
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

Note: if data is retrieving from server add URL address, if from localhost add System IP address for Emulator and for Mobile check yourself from google


text:
Q: Admin Blank Page with Working Front-End After Updating to Wordpress 4.6 Trying to open my website admin mywebsite.com/wp-admin it giving me internal server error 500
The website working fine from the front end.
How can I access my admin and how to solve this issue?

A: After debugging this problem, I found this error in the PHP error log located at public_html/mywebsite/wp-admin/error_log:
PHP Fatal error:  Call to undefined function wp_raise_memory_limit() in /home/example/public_html/mywebsite/wp-admin/admin.php on line 141

This function wp_raise_memory_limit() should be defined in wp-includes/functions.php but it is not defined in my case due to an unsuccessful update by Wordpress.
So Solution: Do a manual update for wordpress as I did the following:

*

*I downloaded the latest version of wordpress from wordpress.org

*I replaced all files and folders of my site except wp-config.php file and wp-content folder

*I opened my site url, it requested a database update

I pressed on update database and the problem resolved :)


text:
Q: Putting together 2 drop down lists where second is taking data based on the selected option on the first the below code shows the option for only one drop down list but I would like to have more. For example, if I choose color green in the first drop down, to give me the options only for that color within the second drop down like: light green, dark green. Should I repeat the below code for each drop down list?
# here database details
mysqli_connect('hostname', 'username', 'password');
mysqli_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysqli_query($sql);

echo "<select name='username'>";
while ($row = mysqli_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

Thank you in advance!


text:
Q: How to inherit more rendersection in mvc 4? Well, hello every body, I started with mvc4, I don't known how to inherit one View from more RenderSection. Such as PageMain inheritance _Layout, then SubMain1 inheritance PageMain. View my code snippet.
_Layout.cshtml

<body>
This is layout
@RenderBody()
@RenderSection("Main",required: false)
</body>

PageMain.cshtml inherit from _Layout

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
This is PageMain
@section Main{
    This is Main
}
@RenderBody()
@RenderSection("SubMain1",required: false)
@RenderSection("SubMain2",required: false)

SubMain1.cshtml inherit from PageMain

@{
    Layout = "~/Views/PageABC/PageMain.cshtml";
}
This is SubMain1
@section Main{
    This is Main in page SubMain
}
@section SubMain1{
    This is SubMain1
}
@section SubMain2{
    This is SubMain2
}

When i try it, I get error cannot be requested directly because it calls the "RenderSection" method . Can you tell me what the mistake in here and give me adviced for this ? Thank you so much.


text:
Q: Turn off auto-locking for specific applications I'm just wondering if it is possible to disable auto-locking on my iPhone for specific applications? For example, I didn't want to lock screen of iPhone if LUMOback application is running in foreground.

A: This can't be done at the moment. The Auto-Lock setting applies to every app. The only exception to this is if an app asks iOS to prevent sleep.
You can provide feedback to Apple regarding this at the following page:

*

*http://www.apple.com/feedback/iphone.html


text:
Q: How to make all python threads that are created from the main thread are daemon threads? I use a lot of libraries that create their own threads. I want to all threads stop when the main tread is down. Basically, I want that all threads should be a daemon thread. Potentially, I could rewrite all libraries and make them create daemon threads, but it will take a huge amount of time.
So my question is, Is there is a way how to make all threads are daemon threads?


text:
Q: How to approach vector space of matrices? The following is from this Wikipedia page:

Let $\mathbf{F}^{m\times n}$ denote the set of $m\times n$ matrices with entries in $\mathbf{F}$. Then $\mathbf{F}^{m\times n}$ is a vector space over $\mathbf{F}$. Vector addition is just matrix addition and scalar multiplication is defined in the obvious way (by multiplying each entry by the same scalar). The zero vector is just the zero matrix. The dimension of $\mathbf{F}^{m\times n}$ is $mn$. One possible choice of basis is the matrices with a single entry equal to 1 and all other entries $0$.

My question is: Is there a notion of "four fundamental subspaces" in this case as well? If so, then what does it mean to be a "column space" of a vector space of matrices $\mathbf{F}^{m\times n}$? What about the "null space", "row space", and "left null space"?

A: ''Column space'',''row space''and ''null space'' are defined for a Matrix, and are subspaces of the vector space in which the linear transformation represented by the matrix operates.
So, if you have a matrix $A\in M_{n\times n}(\mathbb{R})$ you can define these space as subspace of $\mathbb{R}^m$ or  $\mathbb{R}^n$.  But if you consider the matrix $A$ as an element of  a vector space isomorphic to $\mathbb{R}^{mn}$ than, in this space the matrix becomes a vector and, for such vector  the notions of ''Column space'',''row space'' etc.. has no meaning.


text:
Q: Making custom right-click context menus for my web-app I've a few websites like google-docs and map-quest that have custom drop down menus when you right-click. Somehow they override the browser's behavior of drop-down menu, and I'm now sure exactly how they do it. I found a jQuery plugin that does this, but I'm still curious about a few things:

*

*How does this work? Is the browser's drop-down menu actually being overridden, or is the effect just simulated? If so, how?

*What does the plugin abstract away? What's going on behind the scenes?

*Is this the only way of achieving this effect?

See several custom-context menus in action

A:

<!DOCTYPE html>

    <title>Right Click</title>

    <link href="https://swisnl.github.io/jQuery-contextMenu/dist/jquery.contextMenu.css" rel="stylesheet" type="text/css" />

    Right Click Me

A: As Adrian said, the plugins are going to work the same way.  There are three basic parts you're going to need:
1: Event handler for 'contextmenu' event:
$(document).bind("contextmenu", function(event) {
    event.preventDefault();
    $("
Custom menu
")
        .appendTo("body")
        .css({top: event.pageY + "px", left: event.pageX + "px"});
});

Here, you could bind the event handler to any selector that you want to show a menu for.  I've chosen the entire document.
2: Event handler for 'click' event (to close the custom menu):
$(document).bind("click", function(event) {
    $("div.custom-menu").hide();
});

3: CSS to control the position of the menu:
.custom-menu {
    z-index:1000;
    position: absolute;
    background-color:#C0C0C0;
    border: 1px solid black;
    padding: 2px;
}

The important thing with the CSS is to include the z-index and position: absolute
It wouldn't be too tough to wrap all of this in a slick jQuery plugin.
You can see a simple demo here: http://jsfiddle.net/andrewwhitaker/fELma/

A: here is an example for right click context menu in javascript:
Right Click Context Menu
Used raw javasScript Code for context menu functionality. Can you please check this, hope this will help you.
Live Code:

(function() {

  "use strict";

  /*********************************************** Context Menu Function Only ********************************/
  function clickInsideElement( e, className ) {
    var el = e.srcElement || e.target;
    if ( el.classList.contains(className) ) {
      return el;
    } else {
      while ( el = el.parentNode ) {
        if ( el.classList && el.classList.contains(className) ) {
          return el;
        }
      }
    }
    return false;
  }

  function getPosition(e) {
    var posx = 0, posy = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) {
      posx = e.pageX;
      posy = e.pageY;
    } else if (e.clientX || e.clientY) {
      posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }
    return {
      x: posx,
      y: posy
    }
  }

  // Your Menu Class Name
  var taskItemClassName = "thumb";
  var contextMenuClassName = "context-menu",contextMenuItemClassName = "context-menu__item",contextMenuLinkClassName = "context-menu__link", contextMenuActive = "context-menu--active";
  var taskItemInContext, clickCoords, clickCoordsX, clickCoordsY, menu = document.querySelector("#context-menu"), menuItems = menu.querySelectorAll(".context-menu__item");
  var menuState = 0, menuWidth, menuHeight, menuPosition, menuPositionX, menuPositionY, windowWidth, windowHeight;

  function initMenuFunction() {
    contextListener();
    clickListener();
    keyupListener();
    resizeListener();
  }

  /**
   * Listens for contextmenu events.
   */
  function contextListener() {
    document.addEventListener( "contextmenu", function(e) {
      taskItemInContext = clickInsideElement( e, taskItemClassName );

      if ( taskItemInContext ) {
        e.preventDefault();
        toggleMenuOn();
        positionMenu(e);
      } else {
        taskItemInContext = null;
        toggleMenuOff();
      }
    });
  }

  /**
   * Listens for click events.
   */
  function clickListener() {
    document.addEventListener( "click", function(e) {
      var clickeElIsLink = clickInsideElement( e, contextMenuLinkClassName );

      if ( clickeElIsLink ) {
        e.preventDefault();
        menuItemListener( clickeElIsLink );
      } else {
        var button = e.which || e.button;
        if ( button === 1 ) {
          toggleMenuOff();
        }
      }
    });
  }

  /**
   * Listens for keyup events.
   */
  function keyupListener() {
    window.onkeyup = function(e) {
      if ( e.keyCode === 27 ) {
        toggleMenuOff();
      }
    }
  }

  /**
   * Window resize event listener
   */
  function resizeListener() {
    window.onresize = function(e) {
      toggleMenuOff();
    };
  }

  /**
   * Turns the custom context menu on.
   */
  function toggleMenuOn() {
    if ( menuState !== 1 ) {
      menuState = 1;
      menu.classList.add( contextMenuActive );
    }
  }

  /**
   * Turns the custom context menu off.
   */
  function toggleMenuOff() {
    if ( menuState !== 0 ) {
      menuState = 0;
      menu.classList.remove( contextMenuActive );
    }
  }

  function positionMenu(e) {
    clickCoords = getPosition(e);
    clickCoordsX = clickCoords.x;
    clickCoordsY = clickCoords.y;
    menuWidth = menu.offsetWidth + 4;
    menuHeight = menu.offsetHeight + 4;

    windowWidth = window.innerWidth;
    windowHeight = window.innerHeight;

    if ( (windowWidth - clickCoordsX) < menuWidth ) {
      menu.style.left = (windowWidth - menuWidth)-0 + "px";
    } else {
      menu.style.left = clickCoordsX-0 + "px";
    }

    // menu.style.top = clickCoordsY + "px";

    if ( Math.abs(windowHeight - clickCoordsY) < menuHeight ) {
      menu.style.top = (windowHeight - menuHeight)-0 + "px";
    } else {
      menu.style.top = clickCoordsY-0 + "px";
    }
  }

  function menuItemListener( link ) {
    var menuSelectedPhotoId = taskItemInContext.getAttribute("data-id");
    console.log('Your Selected Photo: '+menuSelectedPhotoId)
    var moveToAlbumSelectedId = link.getAttribute("data-action");
    if(moveToAlbumSelectedId == 'remove'){
      console.log('You Clicked the remove button')
    }else if(moveToAlbumSelectedId && moveToAlbumSelectedId.length > 7){
      console.log('Clicked Album Name: '+moveToAlbumSelectedId);
    }
    toggleMenuOff();
  }
  initMenuFunction();

})();
/* For Body Padding and content */
body { padding-top: 70px; }
li a { text-decoration: none !important; }

/* Thumbnail only */
.thumb {
  margin-bottom: 30px;
}
.thumb:hover a, .thumb:active a, .thumb:focus a {
  border: 1px solid purple;
}

/************** For Context menu ***********/
/* context menu */
.context-menu {  display: none;  position: absolute;  z-index: 9999;  padding: 12px 0;  width: 200px;  background-color: #fff;  border: solid 1px #dfdfdf;  box-shadow: 1px 1px 2px #cfcfcf;  }
.context-menu--active {  display: block;  }

.context-menu__items { list-style: none;  margin: 0;  padding: 0;  }
.context-menu__item { display: block;  margin-bottom: 4px;  }
.context-menu__item:last-child {  margin-bottom: 0;  }
.context-menu__link {  display: block;  padding: 4px 12px;  color: #0066aa;  text-decoration: none;  }
.context-menu__link:hover {  color: #fff;  background-color: #0066aa;  }
.context-menu__items ul {  position: absolute;  white-space: nowrap;  z-index: 1;  left: -99999em;}
.context-menu__items > li:hover > ul {  left: auto;  padding-top: 5px  ;  min-width: 100%;  }
.context-menu__items > li li ul {  border-left:1px solid #fff;}
.context-menu__items > li li:hover > ul {  left: 100%;  top: -1px;  }
.context-menu__item ul { background-color: #ffffff; padding: 7px 11px;  list-style-type: none;  text-decoration: none; margin-left: 40px; }
.page-media .context-menu__items ul li { display: block; }
/************** For Context menu ***********/
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Thumbnail Gallery (Right click to see the context menu)

                 Delete This Photo

                 Photo Option 2

                 Photo Option 3

                 Photo Option 4

                 Photo Option 5

                 Add Photo to

 Album One

 Album Two

 Album Three

 Album Four

A: The browser's context menu is being overridden. There is no way to augment the native context menu in any major browser.
Since the plugin is creating its own menu, the only part thats really being abstracted is the browser's context menu event. The plugin creates an html menu based on your configuration, then places that content at the location of your click.
Yes, this is the only way to go about creating a custom context menu. Obviously, different plugins do things slightly different, but they will all override the browser's event and place their own html-based menu in the correct place.

A: I know this question is very old, but just came up with the same problem and solved it myself, so I'm answering in case anyone finds this through google as I did. I based my solution on @Andrew's one, but basically modified everything afterwards.
EDIT: seeing how popular this has been lately, I decided to update also the styles to make it look more like 2014 and less like windows 95. I fixed the bugs @Quantico and @Trengot spotted so now it's a more solid answer.
EDIT 2: I set it up with StackSnippets as they're a really cool new feature. I leave the good jsfiddle here for reference thought (click on the 4th panel to see them work).
New Stack Snippet:

// JAVASCRIPT (jQuery)

// Trigger action when the contexmenu is about to be shown
$(document).bind("contextmenu", function (event) {

    // Avoid the real one
    event.preventDefault();

    // Show contextmenu
    $(".custom-menu").finish().toggle(100).

    // In the right position (the mouse)
    css({
        top: event.pageY + "px",
        left: event.pageX + "px"
    });
});

// If the document is clicked somewhere
$(document).bind("mousedown", function (e) {

    // If the clicked element is not the menu
    if (!$(e.target).parents(".custom-menu").length > 0) {

        // Hide it
        $(".custom-menu").hide(100);
    }
});

// If the menu element is clicked
$(".custom-menu li").click(function(){

    // This is the triggered action name
    switch($(this).attr("data-action")) {

        // A case for each action. Your actions here
        case "first": alert("first"); break;
        case "second": alert("second"); break;
        case "third": alert("third"); break;
    }

    // Hide it AFTER the action was triggered
    $(".custom-menu").hide(100);
  });
/* CSS3 */

/* The whole thing */
.custom-menu {
    display: none;
    z-index: 1000;
    position: absolute;
    overflow: hidden;
    border: 1px solid #CCC;
    white-space: nowrap;
    font-family: sans-serif;
    background: #FFF;
    color: #333;
    border-radius: 5px;
    padding: 0;
}

/* Each of the items in the list */
.custom-menu li {
    padding: 8px 12px;
    cursor: pointer;
    list-style-type: none;
    transition: all .3s ease;
    user-select: none;
}

.custom-menu li:hover {
    background-color: #DEF;
}

First thing

Second thing

Third thing

Right click me

Note: you might see some small bugs (dropdown far from the cursor, etc), please make sure that it works in the jsfiddle, as that's more similar to your webpage than StackSnippets might be.

A: You can watch this tutorial: http://www.youtube.com/watch?v=iDyEfKWCzhg
Make sure the context menu is hidden at first and has a position of absolute. This will
ensure that there won't be multiple context menu and useless creation of context menu. The link to the page is placed in the description of the YouTube video.
$(document).bind("contextmenu", function(event){
$("#contextmenu").css({"top": event.pageY +  "px", "left": event.pageX +  "px"}).show();
});
$(document).bind("click", function(){
$("#contextmenu").hide();
});

A: I know that this is rather old also. I recently had a need to create a context menu that I inject into other sites that have different properties based n the element clicked.
It's rather rough, and there are probable better ways to achieve this.
It uses the jQuery Context menu Library Located Here
I enjoyed creating it and though that you guys might have some use out of it.
Here is the fiddle. I hope that it can hopefully help someone out there.
$(function() {
  function createSomeMenu() {
    var all_array = '{';
    var x = event.clientX,
      y = event.clientY,
      elementMouseIsOver = document.elementFromPoint(x, y);
    if (elementMouseIsOver.closest('a')) {
      all_array += '"Link-Fold": {"name": "Link", "icon": "fa-external-link", "items": {"fold2-key1": {"name": "Open Site in New Tab"}, "fold2-key2": {"name": "Open Site in Split Tab"}, "fold2-key3": {"name": "Copy URL"}}},';
    }
    if (elementMouseIsOver.closest('img')) {
      all_array += '"Image-Fold": {"name": "Image","icon": "fa-picture-o","items": {"fold1-key1": {"name":"Download Image"},"fold1-key2": {"name": "Copy Image Location"},"fold1-key3": {"name": "Go To Image"}}},';
    }
    all_array += '"copy": {"name": "Copy","icon": "copy"},"paste": {"name": "Paste","icon": "paste"},"edit": {"name": "Edit HTML","icon": "fa-code"}}';
    return JSON.parse(all_array);
  }

  // setup context menu
  $.contextMenu({
    selector: 'body',
    build: function($trigger, e) {
      return {
        callback: function(key, options) {
          var m = "clicked: " + key;
          console.log(m);
        },
        items: createSomeMenu()
      };
    }
  });
});

A: I have a nice and easy implementation using Bootstrap as follows.
<select class="custom-select" id="list" multiple></select>

Actions

    Option 1
    Option 2

A: Simple One

*

*show context menu when right click anywhere in document

*avoid context menu hide when click inside context menu

*close context menu when press left mouse button

Note:
dont use display:none instead use opacity to hide and show

var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {
            e.preventDefault();
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';
             menu.style.opacity = 1;
        });

  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
.context_menu{

width:70px;
background:lightgrey;
padding:5px;
 opacity :0;
}
.context_menu div{
margin:5px;
background:grey;

}
.context_menu div:hover{
margin:5px;
background:red;
   cursor:pointer;

}

menu 1

menu 2

extra css

var menu= document.querySelector('.context_menu');
document.addEventListener("contextmenu", function(e) {
            e.preventDefault();
            menu.style.position = 'absolute';
            menu.style.left = e.pageX + 'px';
            menu.style.top = e.pageY + 'px';
             menu.style.opacity = 1;
        });

  document.addEventListener("click", function(e){
  if(e.target.closest('.context_menu'))
  return;
      menu.style.opacity = 0;
  });
.context_menu{

width:120px;
background:white;
border:1px solid lightgrey;

 opacity :0;
}
.context_menu div{
padding:5px;
padding-left:15px;
margin:5px 2px;
border-bottom:1px solid lightgrey;
}
.context_menu div:last-child {
border:none;
}
.context_menu div:hover{

background:lightgrey;
   cursor:pointer;

}

menu 1

menu 2

menu 3

menu 4


text:
Q: Find possible move for backgammon Find an possible moves in Backgammon games.
I written an brute force approach which can detect possible moves.

*

*Added an dices value into turn player checker
// let possibleMoves: number[];
  let possibleMoves = [];
  let possibleMoveDice =[];
  for(let dice of dices){
    for(let entry of p1){
        let num = entry + dice;
        if(num < 24){
            possibleMoves.push(num);
        }
    }

  possibleMoveDice.push(possibleMoves);
  //Make possible move blank
  possibleMoves=[];

  }

*Compare this possible move with opponent checker if opponent checker
more than one in pile than this possible move should excluded.
//Check available move with second checker
 for (let checker of possibleMoveDice) {
   for (let posMove of checker) {
     let count :number =0;
      for (let entry of p2) {
         if (posMove == entry) {
            count++;
            if(count > 1){
            //Remove from the possible moves
            }
         }
      }
   }
}

Time complexity of this algorithm quadratic but I am looking for algorithm
  that use less time complexity.  If anyone have better approach or any
  suggestion to improve in code it would be highly appreciate.


text:
Q: distinguish between local scope and global scope variables with same name in swift how to distinguish between local scope and global scope variables with same name in "swift" (and in "objective-c")
For eg:
var a = 10
for i in 1...10 {
  var a = 20
  a = 40
}

in this code snippet, how can I save 40 to the global variable "a" ?
Sorry if it's a duplicate question.
Edit
Changing any variable name is obviously possible, but I want to know if there any way to do this.

A: Its a bad practice as Paulw11 has mentioned. But actually you can do it.
The top level namespaces are modules.By default, app is a module and hence a namespace.This namespace's name is the name of the app.
So you can access it as:-
    <ModuleName>.a = 40

Here ModuleName will be the name of your app.


text:
Q: Error: package exists in another module: com.company.feature.apimodule in Intellij I created a small project in Intellij Idea to mimic what I am seeing trying to migrate a large legacy codebase to OPENJDK16.  Here is the directory structure:
$ tree
/cygdrive/c/projects/play
 |--api
 |----api.iml
 |----src
 |------module-info.java (module com.company.feature.apimodule)
 |------com
 |--------company
 |----------feature
 |------------ApiRunnable.java
 |--home
 |----home.iml
 |----src
 |------module-info.java (module com.company.feature.homemodule)
 |------com
 |--------company
 |----------feature
 |------------Runnable1.java
 |--Modules
 |----.idea (Idea stuff in here)
 |----out
 |------production
 |--------api
 |--------home

module com.company.feature.apimodule
{
    exports com.company.feature;
}

package com.company.feature;
public interface ApiRunnable
{
    public void play(String[] strings);
}

module com.company.feature.homemodule
{
    requires com.company.feature.apimodule;       //Error Module not found
//    requires apimodule;                         //Error Module not found
//    requires com.company.feature.ApiRunnable;   //Error Module not found
}

package com.company.feature;
public class Runnable1 implements ApiRunnable
{
    @Override
    public void play(String[] strings)
    {
        int count = 1;
        for (String str : strings)
        {
            System.out.println("String " + count++ + " " + str);
        }
    }
    public static void main(String[] args)
    {
        Runnable1 myRun = new Runnable1();
        myRun.play(args);
    }
}

Note the directory structure is identical in api and home.  This is intentional as my legacy codebase has this structure.  This small example seems to duplicate the problems I am having and I can't figure out if the structure is the problem.  It did compile and run fine using the unnamed-module.
Error #1 when doing a rebuild
C:\Projects\play\home\src\com\company\feature\Runnable1.java
java: package exists in another module: com.company.feature.apimodule

Does this mean that I can't have identical package trees in api and home?
Error #2
The homemodule cannot see the apimodule, I keep getting (Module not found) no matter what I put in the requires line.
Is this related to Error #1?  If not, how do I fix this without resorting to the unnamed module for everything?

A: This problem was resolved by putting the module-info.java in the right directory.  This is poorly documented and was found by trial and error.
The right directory is api:
module apimodule
{
    exports com.company.feature;
}

and home:
module homemodule
{
    requires apimodule;
}

It appears that once the module-info.java files are in place, the Runnable1.java doesn't need the import statements, since the imported package is the same as the local one.


text:
Q: Merge list of python dictionaries using multiple keys I want to merge two lists of dictionaries, using multiple keys.
I have a single list of dicts with one set of results:
l1 = [{'id': 1, 'year': '2017', 'resultA': 2},
      {'id': 2, 'year': '2017', 'resultA': 3},
      {'id': 1, 'year': '2018', 'resultA': 3},
      {'id': 2, 'year': '2018', 'resultA': 5}]

And another list of dicts for another set of results:
l2 = [{'id': 1, 'year': '2017', 'resultB': 5},
      {'id': 2, 'year': '2017', 'resultB': 8},
      {'id': 1, 'year': '2018', 'resultB': 7},
      {'id': 2, 'year': '2018', 'resultB': 9}]

And I want to combine them using the 'id' and 'year' keys to get the following:
all = [{'id': 1, 'year': '2017', 'resultA': 2, 'resultB': 5},
       {'id': 2, 'year': '2017', 'resultA': 3, 'resultB': 8},
       {'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 7},
       {'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 9}]

I know that for combining two lists of dicts on a single key, I can use this:
l1 = {d['id']:d for d in l1}

all = [dict(d, **l1.get(d['id'], {})) for d in l2]

But it ignores the year, providing the following incorrect result:
all = [{'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 5},
       {'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 8},
       {'id': 1, 'year': '2018', 'resultA': 3, 'resultB': 7},
       {'id': 2, 'year': '2018', 'resultA': 5, 'resultB': 9}]

Treating this as I would in R, by adding in the second variable I want to merge on, I get a KeyError:
l1 = {d['id','year']:d for d in l1}

all = [dict(d, **l1.get(d['id','year'], {})) for d in l2]

How do I merge using multiple keys?

A: Instead of d['id','year'], use the tuple (d['id'], d['year']) as your key.

A: You can combine both list and groupby the resulting list on id and year. Then merge the dict together that have same keys.
Grouping can be achieved by using itertools.groupby, and merge can be done using collection.ChainMap
>>> from itertools import groupby
>>> from collections import ChainMap

>>> [dict(ChainMap(*list(g))) for _,g in groupby(sorted(l1+l2, key=lambda x: (x['id'],x['year'])),key=lambda x: (x['id'],x['year']))]
>>> [{'resultA': 2, 'id': 1, 'resultB': 5, 'year': '2017'}, {'resultA': 3, 'id': 1, 'resultB': 7, 'year': '2018'}, {'resultA': 3, 'id': 2, 'resultB': 8, 'year': '2017'}, {'resultA': 5, 'id': 2, 'resultB': 9, 'year': '2018'}]

Alternatively to avoid lambda you can also use operator.itemgetter
 >>> from operator import itemgetter
 >>> [dict(ChainMap(*list(g))) for _,g in groupby(sorted(l1+l2, key=itemgetter('id', 'year')),key=itemgetter('id', 'year'))]

A: Expanding on @AlexHall's suggestion, you can use collections.defaultdict to help you:
from collections import defaultdict

d = defaultdict(dict)

for i in l1 + l2:
    results = {k: v for k, v in i.items() if k not in ('id', 'year')}
    d[(i['id'], i['year'])].update(results)

Result
defaultdict(dict,
            {(1, '2017'): {'resultA': 2, 'resultB': 5},
             (1, '2018'): {'resultA': 3, 'resultB': 7},
             (2, '2017'): {'resultA': 3, 'resultB': 8},
             (2, '2018'): {'resultA': 5, 'resultB': 9}})


text:
Q: spryker extend DummyPaymentHandlerPlugin class I am new to spryker and I want to extend this class DummyPaymentHandlerPlugin. I tried by adding the class to the factory but is not working. Can anyone help me to do this

A: Extending plugins in Spryker is possible. But instead of changing the factory method, you just have to change the use statement in the appropriate dependency provider.
In your case, it's \Pyz\Yves\CheckoutPage\CheckoutPageDependencyProvider::extendPaymentMethodHandler:
    protected function extendPaymentMethodHandler(Container $container): Container
    {
        $container->extend(static::PAYMENT_METHOD_HANDLER, function (StepHandlerPluginCollection $paymentMethodHandler) {
            $paymentMethodHandler->add(new DummyPaymentHandlerPlugin(), DummyPagmentConfig::PAYMENT_PROVIDER_NAME);

            return $paymentMethodHandler;
        });

        return $container;
    }


text:
Q: Return 2 random images from an array I'm trying to get back 2 unique images form an array. Right now I'm refreshing the page until I get 2 unique images. This is not ideal. How can I modify this code to back 2 unique images with out refreshing the page till it hapens.
Can I do it in this layer or do I need to check for unique numbers in the data layer?
 Picture dlPicture = new Picture();
        DataTable DTPictures = dlPicture.GetRandomPicture();
        Picture dlPicture2 = new Picture();
        DataTable DTPictures2 = dlPicture2.GetRandomPicture();

        // the variables to hold the yes and no Id's for each set
        string firstNoPicId = "";
        string firstYesPicId = "";
        string secondNoPicId = "";
        string secondYesPicId = "";

        foreach (DataRow row in DTPictures.Rows)
        {
            firstYesPicId = row["PicID"].ToString();
            secondNoPicId = firstYesPicId;
            FirstPicMemberNameLabel.Text = row["MemberName"].ToString();
            FirstPicLink.ImageUrl = "Pictures/" + row["PicLoc"];

        }

        foreach (DataRow row in DTPictures2.Rows)
        {
            secondYesPicId = row["PicID"].ToString();
            firstNoPicId = secondYesPicId;
            SecondPicMemberNameLabel.Text = row["MemberName"].ToString();
            SecondPicLink.ImageUrl = "Pictures/" + row["PicLoc"];

        }
        if (firstYesPicId != secondYesPicId)
        {

            FirstPicLink.PostBackUrl = "default.aspx?yesId=" + firstYesPicId + "&noId=" + firstNoPicId;
            SecondPicLink.PostBackUrl = "default.aspx?yesId=" + secondYesPicId + "&noId=" + secondNoPicId;
        }
        else
        {
            Response.Redirect("Default.aspx");
        }

A: There two pretty obvious ways to deal with this

*

*Add an overload  dlPicture.GetRandomPicture(int picID) This will accept an ID so that it won't return an already used picID

*restructure your code so that it loops until the secondYesPicId != firstYesPicId
Something like
 secondYesPicId = firstYesPicId;
 while (firstYesPicId == secondYesPicId)
 {  DataTable DTPictures2 = dlPicture2.GetRandomPicture();

     foreach (DataRow row in DTPictures2.Rows)
    {
        secondYesPicId = row["PicID"].ToString();
        SecondPicMemberNameLabel.Text = row["MemberName"].ToString();
        SecondPicLink.ImageUrl = "Pictures/" + row["PicLoc"];

    }
 }

A: Perhaps a better solution would be adding code to your datalayer.GetRandomPicture to make sure it can't return the same picture twice in a row?
in this Picture class add a LastRandomPictureID variable and do a 'WHERE NOT ID = LastRandomPictureID' on your query (you might want to make it a bit more robust to handle the case where only 1 picture exists).

A: var rnd = new Random();
int randomPicIndex1 = rnd.Next(numOfPictures);
int randomPicIndex2;
do {
    randomPicIndex2 = rnd.Next(numOfPictures);
} while (randomPicIndex1 == randomPicIndex2);

Then use these indexes in order to get random rows from your table.
DataRow row1 = DTPictures.Rows[randomPicIndex1];
DataRow row2 = DTPictures.Rows[randomPicIndex2];


text:
Q: Making raw_input capitalize specific letters to match dictionary keys and values I am developing a text-based RPG.  Right now, I am creating a combat mechanic that provides the player with their options of attack, and executing code based off the items a player has in their inventory dictionary, like so (I will keep the code simple for obvious reasons):
inventory = {'Weapons': ['Iron Longsword', 'Dagger'],
            'Gold': 10,
            'Spells': [' ']}

print "Your attack methods are: [Melee] -- %s, [Spells] -- %s" % (inventory["Weapons"], inventory["Spells"]

attack = raw_input("Choose an attack method provided above: ")
if attack == inventory["Weapons"] or attack == inventory["Spells"]:
     #Initiate combat...

I could be understanding this concept incorrectly, but the problem I am facing is when an item is added to the inventory, it is shown in proper capitalization, e.g. "Iron Longsword" vs. "iron longsword".  I think the issue is that when the if statement goes to check the dictionary for the items the player typed in under the raw_input 'attack', it doesn't recognize the item unless it is capitalized correctly.  However, I want to allow the player to just type in the weapon or spell regardless of pre-existing capitalization.
I figured there may be one real solutions to the problem, again I could definitely be wrong about this.  The solution being to edit the raw input to translate to proper caps, just like I do when the characters should be all lower case with '.lower()'
I appreciate any help with simple problems like this.  Thanks again stack overflow for being so fantastic to me while I try to learn programming languages.

A: It has been a while since i have used python but the below code segment should test if the input is equal to one of the attacks or spells no matter what the capitalization is. You can either make both string capitalized or lower case when you test them. I would suggest doing this any time your testing a string in the future so your users doesn't need to type his input Case sensitively.
if attack.lower() == inventory["Weapons"].lower() or attack == inventory["Spells"].lower():

A: you can compare two strings like
str1 = 'Longsword'
str2 = 'LongSword'

print str1.lower() == str1.lower()

evaluates True.
So you can use the lower() method and have non-capitalized keys and values.
You should also use
if attack in [x.lower() for x in inventory["Weapons"]]

instead of comparing a string to a list like you do now.


text:
Q: If $\frac{\cos x}{\cos y}+\frac{\sin x}{\sin y}=-1$, then what's the value of $4\left(\frac{\cos^3y}{\cos x}+\frac{\sin^3y}{\sin x}\right)$? I was trying to solve this problem:

If
  $$\frac{\cos x}{\cos y}+\frac{\sin x}{\sin y}=-1$$
  then what is the value of
  $$S=4\left(\frac{\cos^3y}{\cos x}+\frac{\sin^3y}{\sin x}\right)$$

I tried to solve this problem using a change of variables
$\cos^3y=a\cos x$ and $\sin^3y=b \sin x$.
So:
$$\frac{S}{4}=a+b$$
$$\frac{\cos^6y}{a^2}+\frac{\sin^6y}{b^2}=1$$
and
$$\frac{\cos^2y}{a} + \frac{\sin^2y}{b}=-1$$
I tried to manipulate these equations, but it gives no result

A: I don't know if this helps, but this is what I've discovered so far
The first equation can be written as
$$\cos x \sin y + \sin x \cos y = -\cos y \sin y$$
or using the double angle formula
$$\sin (x+y) = -\cos y \sin y$$
By the triple angle formulas for sine and cosine, we have that
$$\sin^3(y)=\frac{3\sin(y)-\sin(3y)}{4}, \, \cos^3(y) = \frac{3\cos(y) + \cos(3y)}{4}$$
Plugging this in and simplifying the fractions, we get
$$S=\frac{3\cos(y)\sin(x) + \cos(3y)\sin(x) +3\sin(y)\cos (x)-\sin(3y)\cos(x)}{\cos x \sin x}$$
Rearranged, this is
$$S=\frac{3\cos(y)\sin(x) +3\sin(y)\cos (x) + \cos(3y)\sin(x) -\sin(3y)\cos(x)}{\cos x \sin x}$$
And using the sum and difference of angle formulas for sine, we get
$$S=\frac{3\sin(x+y) + \sin(x-3y)}{\cos x \sin x}$$
EDIT: Using the graphing software desmos and plugging in test values for $x,y$ that satisfy the first equation, we get $\fbox{4 }$. I guess I'll leave it up to someone smarter to prove why is works, instead of just showing that it does.

A: http://comentario.fariasbrito.com.br/vest/index.php?vid=68 There you go (it's the seventh question).
It's a pretty interesting problem, but I think when you're searching problems from IME or ITA, you should first check the sites of courses that are about them if the problems aren't from before 2000 (like the one I sent and Poliedro).
@edit: A person told me that I should outline the solution here, so here I go:
$$S = \frac{(3\sin (x+y) + \sin(x-3y))}{\sin x \cos x}$$
(as found by D.R.)
Then defining $a = 3\sin (x+y) + \sin(x-3y)$, $b = \sin x \cos x$ and seeing that $\frac{\cos x}{\cos y} + \frac{\sin x}{\sin y} = -1 \Rightarrow \sin y \cdot \cos x + \sin x \cdot \cos y = -\sin y \cdot \cos y \Rightarrow 2\sin(x+y) +\sin 2y = 0 = c$ we get:
$$S = \frac ab$$
$$a-4b-2c = a-4b = 3\sin (x+y) + \sin(x-3y) - 2\sin 2x - 4\sin (x+y) - 2\sin2y = -\sin (x+y) + \sin(x-3y) - 2\sin 2x - 2\sin2y = 2\sin (-2y)\cdot \cos (x-y) - 2\cdot 2\sin (x+y) \cdot \cos(x-y)$$
Since $2\sin(x+y) = -\sin 2y$ we get:
$$a - 4b = -2\sin 2y \cdot \cos (x-y) + 2\sin 2y \cdot \cos (x-y) = 0 \Rightarrow a = 4b$$
Thus: $$S = \frac {4b}{b} \Rightarrow S = 4$$
In the link there's another solution that is bigger, but I think it should be more acessible to people that don't want the trick of using $a, b$ and $c$.


text:
Q: Use multiple namespace in wash_out gem in ruby I have following request to be created in my SOAP API and using this gem https://github.com/inossidabile/wash_out/
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Header>
    <OGHeader xmlns="http://example.com">
    </OGHeader>
  </soap:Header>
  <soap:Body>
    <BookingRequest xmlns="http://example.com/Booking.wsdl">
      <Reservation Action="CREATE">
        <UniqueIDList xmlns="http://example.com/Unique/">
          <UniqueID type="FAR" xmlns="www.uio.com/Common/">201801111429</UniqueID>
        </UniqueIDList>
      </Reservation>
    </BookingRequest >
  </soap:Body>
</soap:Envelope>

How to use wash_out to create such request with particular namespace defined in each xmlns?


text:
Q: Unable to reactivate windows on a new PC I had earlier asked a question here on SU.SE. It was suggested to me that I should firstly deactivate windows on older PC and then try to activate windows on the  new PC. I have deactivated windows on the older PC by slmgr /upk, but I am unable to activate windows on the new PC.
I have followed Activation> Troubleshoot> I changed hardware on this device recently> Unable to Activate Windows >  See other devices linked to your Microsoft account, I get the following message (attached as image). In the attached image my windows is listed, but mentions as Windows isn't Activated and I do not get the option to select the windows.
Have I followed a wrong procedure? What should I do next?

PS: I have a Retail license of Windows

A: To add on @I say Reinstate Monica 's comment, note that if you use the "I changed hardware" for 3 times, it won't allow the 4th time.


text:
Q: PyGTKDeprecationWarning: What am I missing? My code works just fine, but I get this warning in the terminal when I run the script. What am I missing?
abc.py:10: PyGTKDeprecationWarning: Using positional arguments with the GObject constructor has been deprecated. Please specify keyword(s) for "label" or use a class specific constructor. See: https://wiki.gnome.org/PyGObject/InitializerDeprecations
actor_act = Gtk.Button("Click Here")

Name of the script: abc.py
Actual code:
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

def actor(button):
    print('Simple Button')

boxy = Gtk.Window(title="Hello")
boxy.set_default_size(500,500)
actor_act = Gtk.Button("Click Here")
boxy.add(actor_act)

actor_act.connect("clicked", actor)
boxy.connect("destroy", Gtk.main_quit)

boxy.show_all()
Gtk.main()

A:
Gtk.Button:
class: new_with_label (label)
Creates a GtkButton widget with a GtkLabel child containing the given
text.
Parameters:  label #The text you want the GtkLabel to hold.
Returns: The newly created GtkButton widget.

Gtk.Button.new_with_label("Click Here")


text:
Q: How create SQL pagination difficult join query with duplicate data? I have several tables in the database.
Users, profiles and user roles.
The relationship of profiles and users one to one.
The relationship of roles and users many to many.

To select all users, I send the following request:
SELECT A.role_id, A.role_name, A.user_id,B.user_username, B.user_password, B.profile_color_text, B.profile_color_menu, B.profile_color_bg FROM
  (SELECT Roles.role_id, Roles.role_name, UserRoles.user_id
      FROM Roles INNER JOIN UserRoles ON Roles.role_id = UserRoles.role_id) AS A
LEFT JOIN
  (SELECT Users.user_username, Users.user_password, Profiles.profile_color_text, Profiles.profile_color_menu, Profiles.profile_color_bg, Profiles.profile_id
      FROM Users INNER JOIN Profiles ON Users.user_id = Profiles.profile_id) AS B
ON A.user_id = B.profile_id;

The question is how do I select a pagination?

A: I would get the 10 users first, then perform the joins. Two reasons for this:

*

*Since you don't want specifically 10 results but just the results of 10 users, which could contain any number of rows, you can't get all the data then limit it, otherwise you could be getting 10 rows containing data for 5 users;

*Even if point 1 were irrelevant because there was always a 1-1 relationship, and especially if the number of results is small like 10, it's faster to get those results first and then join on that smaller "table", rather than doing all your joins on all the data and then limiting it.

.
SELECT
    u.user_id,
    u.user_username,
    u.user_password,
    r.role_id,
    r.role_name,
    p.profile_id,
    p.profile_color_text,
    p.profile_color_menu,
    p.profile_color_bg
FROM (
    SELECT user_id, user_username, user_password
    FROM users
    ORDER BY ???
    OFFSET 10
    LIMIT 10
) AS u
LEFT JOIN profiles AS p
    ON u.user_id = p.profile_id
LEFT JOIN userroles AS ur
    ON u.user_id = ur.user_id
LEFT JOIN roles AS r
    ON ur.role_id = r.role_id

I assume you'll want some order, so I've put an ORDER BY in there - to be completed.
OFFSET added to get the second page of results; first page wouldn't require it, or would be OFFSET 0. Then a LIMIT of course to limit the page size.
I've also restructured the joins in a way that made more sense to me.


text:
Q: AFP / Apple Filling Protocol aka Netatalk access over Internet I got a simple cloud server and thought it would be nice to have mac native afp
Volumes accesss. Installed Netatalk and this seems to work pretty nice.
No sensitive data or something but I don't like to wake up someday and have
my www docs rm-rfed by some kid h4x0r.
Q1: Is afp encrypted?
Q2: How can I make it (semi)secure?
Q3: Does VPN makes sense for this?
Q4: What would you do to get afp working over net?
Opening any service meant for Lan only is a basic flaw, i know - but me be ignorant about it. According to Apple Dev only the authentication is encrypted or am I mssing something?

A: *

*AFP is not encrypted.

*Use a VPN.

*Yes, and is the only way I'd consider making either AFP or CIFS shares accessible over the public internet.

*See #2.


text:
Q: How to control several servos with ESP32 I'm new with arduino/ESP32. I want to control several servo motors with the help of ESP32. I want to control all servos at different speeds and want to use sine wave logic to control the speed.
I have code that can control 2 servos seperataly. I have attached the code here,
#include <ESP32Servo.h>
#include "esp32-hal-ledc.h"
// create two servo objects
Servo servo1SV;
Servo servo2SV;

// Published values of servos; adjust if needed
int minUs = 550;
int maxUs = 2250;

// These are all GPIO pins on the ESP32
// Recommended pins include 2,4,12-19,21-23,25-27,32-33
int servo1SVPin = 15;   //outlet valve
int servo2SVPin = 16;   //inlet valve

int pos = 0;      // position in degrees
ESP32PWM pwm;
void setup() {
    Serial.begin(115200);
    servo1SV.setPeriodHertz(50);      // Standard 50hz servo
    servo2SV.setPeriodHertz(50);      // Standard 50hz servo
}

void loop() {
    servo1SV.attach(servo1SVPin, 500, maxUs);
    servo2SV.attach(servo2SVPin, minUs, maxUs);

//// About outlet valve

    for (pos = 0; pos <= 85; pos += 1) { // sweep from 0 degrees to 85 degrees
        // in steps of 1 degree
        servo1SV.write(pos);
        delay(10);             // Opening of outlet valve
    }
 delay(5000);            // Outlet valve stay openned for 5 sec

    for (pos = 85; pos >= 0; pos -= 1) { // sweep from 85 degrees to 0 degrees
        servo1SV.write(pos);
        delay(10);            // closing of outlet valve
    }

// About inlet valve

    for (pos = 0; pos <= 70; pos += 1) { // sweep from 0 degrees to 70 degrees
        // in steps of 1 degree
        servo2SV.write(pos);
        delay(10);             // Opening of inlet valve
    }
  delay(5000);            // Inlet valve stay openned for 5 sec

    for (pos = 70; pos >= 0; pos -= 1) { // sweep from 70 degrees to 0 degrees
        servo2SV.write(pos);
        delay(10);            // Opening of inlet valve
    }

    servo1SV.detach();
    servo2SV.detach();
    delay(5000);
}

I want the same output that is given by this code but using sine wave. But I don't know how to implement sine wave logic in ESP32. How can I do that?

A: I'm not sure what you mean with

sine wave logic

but assuming that you want the servo position over time is a sine function and your question is how to get that sine function:
Either you use Arduinos sin() function or you use a LUT.
The latter is more common as you don't have to calculate the sin values every time which is quite expensive. Just define an pre-calculated array of values that contains your sin values for every servo step.


text:
Q: Local variable unused in a using statement When implementing a using block for the benefit of dispose, such as
using (var window = new DialogWindow(Dialogs.MyDialogType))
{
    //Some action here
}

I get an obvious resharper / visual studio warning that the local variable window is never used, since it is not mentioned in the using body.
This is technically correct, is there a way to declare variables like this that aren't explicitly used in the using body, but who's dispose method will get called once the using statement terminates?
Call me a sucker for neatness but I do not like having the gray warnings popping up all over the place.

A: Just leave it out if you're not using it.  The below is perfectly valid:
using (new DialogWindow(Dialogs.MyDialogType))
{
    //Some action here
}

We use this quite often in our infrastructure as we use IDisposable to log entry/exit from blocks of code, so we can just do:
using (_log.Enter("some block")) {

}

There's no variable being assigned to, but the using will dispose of the object as normal.

A: If you don't use variable it is enough to do the following
//unused variable will not give warning
using (new DialogWindow(Dialogs.MyDialogType))
{
   //Some action here
}


text:
Q: How serve web-folder in Spring Boot out from /resources/ I need help, my Spring Boot 2 Server from a first web generate other web site (folder with html,css ext ext) from a template, but these web sites/html aren't accessible, Spring give me error 404, not found.
I will build the project with Maven in .jar
The gerarchy of the project is this:
---
 |_folder (Directory with webapps generated, NOT DELIVERED)
 . |_webapp1
 . |_webapp2
 |_src
 . |_main
 . . |_java
 . . |_resources
 . . . |_public (With first web)
 . . . |_static (Template used to generate other web site, i simply copy this directoy in other directory, doing  templateServices.copyDirectory("target/classes/static/", "folder/webapp1");
---

I tried with this configuration, but dont work.
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/", FileController.uploadingDir};

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }
}

A: If the web server is going to generate websites, as you said, then you should save the files outside the Spring Boot scope; just in a folder of your filesystem. An example could be:
@Configuration
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
        .addResourceHandler("/**")
        .addResourceLocations("file:/var/www/websites/");
  }
}

If you have dynamic websites (you said it depends on the users) you can inside the method get all users in the system, and add ResourceHandlers for them in specific locations.


text:
Q: Email Settings API - Signature I am trying to update the signature of all the users of my company and have looked for days and cannot find any proper solution. I have used code snippets of python, Google apps script but none seem to work. Could anybody guide me to do build such application.

A: I solved it guys. Two sleepless night and bam...
import gdata.apps.emailsettings.client
from gdata.client import BadAuthentication
from gdata.client import RequestError
import urllib2
import requests
import json

# replace these values with yours
CONSUMER_KEY = 'XXXXXX'
CONSUMER_SECRET = 'XXXXXXXXXXXXXXXXXXX'
company_name = 'XXXXXXXXXXXXX'
admin_username = 'admin'

# request a 2-legged OAuth token
requestor_id = admin_username + '@' + CONSUMER_KEY
two_legged_oauth_token = gdata.gauth.TwoLeggedOAuthHmacToken(
CONSUMER_KEY, CONSUMER_SECRET, requestor_id)

#calling the emailsettings api
email_settings_client = gdata.apps.emailsettings.client.EmailSettingsClient(domain=CONSUMER_KEY)

email_settings_client.auth_token = two_legged_oauth_token
email_settings_client.UpdateSignature(username='xxx.xxx@xxxx.com', signature='yor_signature')


text:
Q: out of memory exception I am getting this exception every now and then and its quite bugging me up.In my app we just scan a barcode and it sends the data from barcode to server.I have tried many things to clean memory and to avoid memory leaks but nothing seems to work .Any help will be appriciated.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.zxing.client.android/com.example.mypackage.filename}: android.view.InflateException: Binary XML file line #12: Error inflating class at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1652)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:2852)
at android.app.ActivityThread.access$1600(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:940)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #12: Error inflating class
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:212)
at android.app.Activity.setContentView(Activity.java:1657)
at com.example.mypackage.filename.onCreate(TaskSelector.java:164)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1616)
... 12 more Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 23 more Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
at android.graphics.Bitmap.nativeCreate(Native Method) at android.graphics.Bitmap.createBitmap(Bitmap.java:477)
at android.graphics.Bitmap.createBitmap(Bitmap.java:444)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:349)
at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:498)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:473)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
at android.content.res.Resources.loadDrawable(Resources.java:1709)
at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
at android.view.View.(View.java:1951) at android.view.View.(View.java:1899)
at android.view.ViewGroup.(ViewGroup.java:286) at android.widget.RelativeLayout.(RelativeLayout.java:173) ... 26 more

A: <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

use this code this might be helpful or let me know i have other solutions even

A: Your bitmaps are too big, or you are loading too many at once.


text:
Q: Thermal Monocular live streaming I have a AGM TM160 thermal monocular that creates its own ad hoc WiFi network. iOS and Android phones can use the T-Vision app to connect to this device and control all settings and view a live stream from the unit.
I would like to live stream this video or better yet be able to remote into a monocular's WIFI from hundreds of miles away.
For example… I have a monocular set up deep in the woods. I have buried cables carrying Fiber gigabit to a WiFi router along with power. All of this is set up and working perfectly. But I need the ad hoc WiFi from the monocular to somehow connect to the wireless routers WiFi(probably impossible) or can I use a WiFi to either-net adapter to connect the ad hoc WiFi to a lan port on the router.
My objective is to either stream the monocular video live 24/7, or better yet remotely connect to the ad hoc monocular WiFi network from my main home in the city.
Again, both the city and woods location have AC power and High-speed internet. The Problem is… unlike a security camera that connects to a WiFi network, this thermal monocular creates its own ad hoc network requiring a cell phone to be in close (40 yards) proximity to it. I would like to bridge the distance and connect my cell to it from my city network and change the settings on it in real time. And of course view it.

A: As nobody else is taking a shot at this...
The ad-hoc network is a separate WiFi network the moncular is broadcasting. You haven't specified what exactly is "router", but by the way you frame the question I assume it's a WiFi router. In that case it is bcasting its own WiFi network and no, you cannot connect one to the other. I'm also extremely suspicious about the possibility of using an Ethernet/Wifi adapter to connect to the ad-hoc - the router manufacturer's documentation would be the first place to check.
I've been racking my head around this for a couple of hours now. The easiest way might be to add a RasPi to where the router is, or directly to the cable. You could then connect the RasPi wirelessly to the monocular.
There are several options to run Android on RasPi such as LineageOS and EmteriaOS (source: https://pimylifeup.com/raspberry-pi-android-lineageos/, but the linked LineageOS specifically states:

The only feature missing from these builds of Android is support for hardware decoding and encoding of video. You may experience some slowdowns when trying to play video files through Android.

That said, although the LineageOS page dates from March 21, the OS itself is already 5 years old, so I'm pretty sure someone has taken a shot at tackling this specific problem. Also the page isn't exactly clear whether same applies to EmteriaOS.


text:
Q: CSS "all" Transition is not working I need help my css transition because it seems to be not working at all. Here's my css code. Do you you think that I missed something?
   /*header navigation in homepage*/
    .home header#main-header {
        position: absolute;
        top: auto !important;
        bottom: 0px !important;
        background: rgba(0, 0, 0, 0.7);
        transition: all 3s ease-in-out;
    }
    .home header#main-header.et-fixed-header {
        position: fixed !important;
        top: 0px !important;
        bottom: auto !important;
        transition: all 3s ease-in-out;
    }
    /*end of header navigation in homepage*/
    /*full width slider in homepage*/
    .fs{
      position:absolute;
      top:0; right:0; bottom:0; left:0;
      z-index: 10;
      background-position:bottom;
      background-size: inherit;
    }
    .home #page-container{margin-top:100vh !important;}
    /*end of full width slider in homepage*/

Oh, here's a link for the website --> http://concept1.mystudioengine.site/
What I'm trying to do is header nav bar supposed to have an animation on scroll. Please help. Any advice will be much appreciated.

A: First, is not a good idea use all in this case, add a transition for each specific property that you want to animate.
So, there are some properties and values that you can't animate, like top: auto to top: 0px.
But animate properties like top, is not recommended for performance questions, I suggest you to read this post about achieving 60 FPS animations, and about Critical Rendering Path.
In this case, the best option is to use something like this to animate your header for a fixed position:
/*header navigation in homepage*/
.home header#main-header {
    position: absolute;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    transform: translateY(-100%);
    transition: transform 3s ease-in-out;
}
.home header#main-header.et-fixed-header {
    position: fixed;
    transform: translateY(0);
}
/*end of header navigation in homepage*/


text:
Q: Django rest framework : extend user model for customer - one to one field I have a customer model in Bcustomer app that extends the django User model, So I will save the basic details such as name in User table and the remaining data (city, etc) in customer table.
When I call the below code through API, it shows the following error. But data is saving in the tables. I also want to implement the get and put calls for this api.
Got AttributeError when attempting to get a value for field `city` on serializer `CustomerSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'city'.

my Bcustomer/models.py
class BCustomer(models.Model):

    customer = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True, blank=True )
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=256)
    state = models.CharField(max_length=50)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, on_delete=models.CASCADE, related_name='customer_creator')
    # more fields to go

    def __str__(self):
        # return str(self.name) (This should print first and last name in User model)

    class Meta:
        app_label = 'bcustomer'

my Bcustomer/serializers.py
from django.contrib.auth import get_user_model
from models import BCustomer

class CustomerSerializer(serializers.HyperlinkedModelSerializer):

    city = serializers.CharField()

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'email','city')

    def create(self, validated_data):
        userModel = get_user_model()
        email = validated_data.pop('email', None)
        first_name = validated_data.pop('first_name', None)
        city = validated_data.pop('city', None)

        request = self.context.get('request')
        creator = request.user

        user = userModel.objects.create(
            first_name=first_name,
            email=email,
            # etc ...
        )

        customer = BCustomer.objects.create(
            customer=user,
            city=city,
            user=creator
            # etc ...
        )

        return user

my Bcustomer/views.py

class CustomerViewSet(viewsets.ModelViewSet):
    customer_photo_thumb = BCustomer.get_thumbnail_url
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
    queryset = BCustomer.objects.all()
    serializer_class = CustomerSerializer

my Bcustomer/urls.py
router.register(r'customer', views.CustomerViewSet, 'customers')

POST request format
{
  "first_name":"Jsanefvf dss",
  "city":"My City",
  "email":"myemail@gmail.com",
  #more fields
}

I also need to implement put and get for this api. Now data is saving in both tables but shows the error.

A: Sure it complains.
Validation goes well, so does the creation but once it's created, the view will deserialize the result and return it to the client.
This is the point where it goes south. Serializer is configured to think that city is a field of the default user while it actually is part of BCustomer. In order to work this around, you should set the source argument to the city field. You might need to update the serializer's create/update to reflect that change, not sure about that one.


text:
Q: ipv6 route slightly modified I am running GNU/Linux version 3.4.113+ with a 6in4 tunnel to a tunnel broker. If I run command
ip -6 route list table local

I see a lot of routes. And one of this route entries is this
local ::1 via :: dev lo  proto none  metric 0

This is the situation after a reboot of the server for several hours. Under certain circumstances this entry changes to this
local ::1 via :: dev lo  proto none  metric 0  rtt 18ms rttvar 15ms cwnd 10

Till now I couldn't figure out why. Are there any ideas what could cause this change ?

A: After days of looking into logs and analyzing I found the reason. I am using a reverse SSH tunnel on this server. But this doesn't happen if the tunnel is opened. It happens if the tunnel is used actively the first time. As I am not always using this tunnel it took a while until I found the reason.


text:
Q: C# Get Permanent Authentication Token Google Sheets API I have a C# program that will add data to a Google Sheets spreadsheet. It authenticates with OAuth 2.0. I have it working with a single time code. However, in the samples Google provides they say:

Once the user authorizes with Google, the request token can be exchanged  for a long-lived access token.

Does anyone know how to get this long-lived access token?


text:
Q: iconv command is not changing the encoding of a plain text file to another encoding In Linux I created a plain text file. using "file -i" I am seeing file encoding is "us-ascii" . After trying below commands it is still showing output file encoding as "us-ascii". Could you please tell me how to change encoding? or Is there any way to download some encoded file which I can't read.

*

*iconv -f US-ASCII -t ISO88592//TRANSLIT -o o.txt ip.txt

*iconv -f UTF-8 -t ISO-8859-1//TRANSLIT -o op.txt ip.txt

I am expecting either iconv change the encoding or I can download some encoded file.

A: If your file contains only ASCII character, then there's no difference between the ASCII, UTF-8 and different ISO8859-x encoding. So after conversion, you will end up with the exactly same file.
A text file does not store any information about what encoding was used. Therefore, the file applies a few rules but at the end of the day, it's just a guess. And as the files are identical, the result will alwazys be the same.
To see a difference, you will must use characters that are encoded differently with the different encoding or are not avaialbe at all in one of the encodings, e.g. ă, € or .


text:
Q: FreeRDP USB Redirection Not Working on Hyper-V? I have compiled FreeRDP from the tip of the Master branch on (and for), an ARM v7 processor, (see cmake command line below).
It all seems to build correctly and the basic xfreerdp client works for a full remote desktop.
I cannot however determine how to get the USB redirection working with a remote virtual server running under Microsoft Hyper-V. I have tried many different command line switch options all without any success, (they also don't produce any error messages).
Reading the "USB Redirection" wiki entry it appears that there should also be a kernel module and service as well as the FreeRDP plugin. I haven't been able to locate any further information on these?
I have also provided a typical xfreerdp command line, (see below), that I have been using in my testing. The remote Hyper-V virtual server is a Windows Server 2012 R2 machine which has been tested and is fully functional with the Microsoft RDP client.
Any help would be greatly appreciated...
My CMAKE Command Line:

/usr/local/bin/cmake -DVENDOR=CloudTerminal -DTARGET_ARCH=ARM
  -DMONOLITHIC_BUILD=OFF -DBUILD_SHARED_LIBS=ON -DCMAKE_BUILD_TYPE=Release -DWITH_SSE2=OFF -DWITH_NEON=ON -DARM_FP_ABI=hard -DWITH_GSTREAMER_0_10=ON -DWITH_JPEG=ON -DWITH_CUPS=ON -DWITH_PULSE=ON -DWITH_ALSA=ON -DWITH_CHANNELS=ON -DCHANNEL_URBDRC=ON .

My XFREERDP Command Line:

/usr/local/bin/xfreerdp /bpp:24 /f +compression -clipboard -fonts
  -aero -decorations -window-drag -menu-anims -themes -wallpaper /t:"Test Terminal" /cert-ignore /sec:tls /d:"DOMAIN"
  /v:"my.server.com" /usb:id,dev:0c45:6128

I've also tried other USB redirection switches such as:

/usb:id,dev:0c45:6128 /rfx
/dvc:urbdrc,id,dev:0c45:6128
/dvc:urbdrc,id,dev:0c45:6128 /rfx
/usb:id,dev:0c45:6128 /vc:usbrdr

etc...
My XFREERDP Response:

loading channel drdynvc
Unable to find a match for unix timezone: Etc/UTC
Loading Dynamic Virtual Channel urbdrc
VID: 0x0C45 PID: 0x6128
Regist Device: Vid: 0x0C45 Pid: 0x6128 InterfaceClass = 0xFF

A: I eventually got it working by following the Serial Redirection instructions on this page:
https://github.com/awakecoding/FreeRDP-Manuals/blob/master/User/FreeRDP-User-Manual.markdown
The USB device I was trying to redirect was an FTDI USB-RS232 adaptor.
BTW: This was the only Serial Redirection reference I could find which actually shows a correct example of the command line syntax...
Note: In my case I didn't have to manually map the remote COM port.


text:
Q: Creating boxes in Angular via *ngFor I'm new to Angular, Bootstrap and front-end programming.
I'd like to create several boxes.
After clicking on the box, detailed view of it should display above all boxes section.
This is what I'm trying to create:

and then after clicking on box number 1:

But now it looks like this:

I'm creating these boxes via Angular *ngFor loop like this:

{{ coin }}

{{ coins[coin].USD | currency:'USD':true}}

CHANGE(30 dni)

            <canvas id="canvas{{i}}">{{ chart[i] }}</canvas>

MARKET CAP

{{details.MKTCAP}}

CHANGE(24h)

{{ details.CHANGE24HOUR }} ({{ details.CHANGEPCT24HOUR }}%)

MAX (24h)

{{ details.HIGH24HOUR }}

A: It's difficult to answer specifically without seeing your component code, but what you are probably missing, conceptually, is an understanding of how to break a UI like this into components and then pass data between those components in the "Angular" way.  There are several ways to attack this.  Ideally, I think you would move the details div to a separate component that has an input that receives the details, then create a separate component for the clickable divs that have an output that fires a custom event when clicked.  These would both be instantiated in the template of a parent component, which would hold the current state of the clicked detail.
So, when you click a clickable component, it passes its details data back up to the parent, where it's set on the details property.  Since the input on the display/canvas component is bound to that property, angular change detection will handle updating that component for you.
Here is a stackblitz with a simplified example of the communication pattern I am describing.  You could also do something like create a shared service that you inject into both and then update that when a component is clicked.
https://angular-azmcxt.stackblitz.io
Stackblitz Editor Link


text:
Q: Connection from local machine installed Zeppelin to Docker Spark cluster I am trying to configure Spark interpreter on a local machine installed Zeppelin version 0.10.0 so that I can run scripts on a Spark cluster created also local on Docker. I am using docker-compose.yml from https://github.com/big-data-europe/docker-spark and Spark version 3.1.2. After docker compose-up, I can see in the browser spark-master on localhost:8080 and History Server on localhost:18081. After reading the ID of the spark-master container, I can also run shell and spark-shell on it (docker exec -it xxxxxxxxxxxx /bin/bash). As host OS I am using Ubuntu 20.04, the spark.master in Zeppelin is set now to spark://localhost:7077, zeppelin.server.port in zeppelin-site.xml to 8070.
There is a lot of information about connecting a container running Zeppelin or running both Spark and Zeppelin in the same container but unfortunately I also use that Zeppelin to connect to the Hive via jdbc on VirtualBox Hortonworks cluster like in one of my previous posts and I wouldn't want to change that configuration now due to hardware resources. In one of the posts (Running zeppelin on spark cluster mode) I saw that such a connection is possible, unfortunately all attempts end with the "Fail to open SparkInterpreter" message.
I would be grateful for any tips.

A: You need to change the spark.master in Zeppelin to point to the spark master in the docker container not the local machine. Hence spark://localhost:7077 won't work.
The port 7077 is fine because that is the port specified in the docker-compose file you are using. To get the IP address of the docker container you can follow this answer. Since I suppose your container is named spark-master you can try the following:
docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' spark-master

Then specify this as the spark.master in Zeppelin: spark://docker-ip:7077


text:
Q: Retrieve many live stock quotes to one CSV file using Python This code correctly prints all four live stock quotes from Interactive Brokers using ib_insync. Stock is an imported function within ib_insync.
stocks = ['SPY','ANGL','GDX','TMV']

test = list()
for stock in stocks:
    stock = Stock(stock, 'SMART','USD')
    contract = ib.qualifyContracts(stock)
    test.append(ib.reqMktData(contract[0],snapshot=True))
    ib.sleep(1)
for stock in test:
    print(stock.last)

This code below will only print the last quote in the list, in this case TMV. I believe this is because the 'w' is overwriting the entire file every time the loop is run? Or is the loop not setup correctly.
import csv
from ib_insync import *
stocks = ['SPY','ANGL','GDX','TMV']

stocks = ['SPY', 'TVIX']
while True:
test = list()

    for stock in stocks:
        stock = Stock(stock, 'SMART','USD')
        contract = ib.qualifyContracts(stock)
        test.append(ib.reqMktData(contract[0],snapshot=True))
        ib.sleep(15)

    for stock in test:
        f = open('spy-price.csv','w')
        f.write(str(stock.last))
        f.close()

How would I get the quotes to be setup so all four quotes are in the same file?

A: use f = open('spy-price.csv','w+') to append to file
w = write
w+ = append


text:
Q: Python - Need to use the python packages without installing using pip/command prompt I am trying to install a python package but I'm not able to install using Pip/Command prompt because I'm having user access at work where I'm not able to open the command prompt. so I can't install anything using pip/conda.
I can able to download the package from GitHub. Is there any option from here to use the package in the python package in your own program?

A: There should be a setup.py file when you download the package. You can run the following command to install it.
python setup.py install


text:
Q: Exception Handling ScheduledExecutorService I am using ScheduledExecutorService to run threads at a fixed interval of 1 min.
One instance of ScheduledExecutorService runs one thread and another instance runs another thread.
Example:
ses1.scheduleAtFixRate(..) // for thread 1
ses2.scheduleAtFixRate(..) // for thread 2

I was encountering some exceptions by which the further execution stops. I want to catch the exception for a systematic shutdown of my application.
Should I handle the exception using a third thread that monitors both futures and handles the Exception or is there any other better way? Will it affect the other threads.
Any and all help is appreciated!

A:
I was encountering some exceptions by which the further execution
  stops.

That is the expected behavior of ScheduledExecutorService.scheduleAtFixRate() according to the specification :

If any execution of the task encounters an exception, subsequent
  executions are suppressed.

About your need :

I want to catch the exception for a systematic shutdown of my
  application.
  Should I handle the exception using a third thread that monitors both
  futures and handles the Exception or is there any other better way?

Handling the future return with ScheduledFuture.get() looks the right.
According to ScheduledFuture.scheduleAtFixedRate() specification :

Otherwise, the task will only terminate via cancellation or
  termination of the executor.

So you don't even need to create a new scheduled future.
Just run two parallel tasks (with ExecutorService or two threads is also possible) that wait on get() of each Future and that stops the application in case of exception thrown in the task  :
Future<?> futureA = ses1.scheduleAtFixRate(..) // for thread 1
Future<?> futureB = ses2.scheduleAtFixRate(..) // for thread 2
submitAndStopTheApplicationIfFail(futureA);
submitAndStopTheApplicationIfFail(futureB);

public void submitAndStopTheApplicationIfFail(Future<?> future){
      executor.submit(() -> {
      try {
        future.get();
      } catch (InterruptedException e) {
        // stop the application
      } catch (ExecutionException e) {
        // stop the application
      }
    });
}


text:
Q: Using predict() on statsmodels.formula data with different column names using Python and Pandas I've got some regressions results from running statsmodels.formula.api.ols. Here's a toy example:
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf

example_df = pd.DataFrame(np.random.randn(10, 3))
example_df.columns = ["a", "b", "c"]
fit = smf.ols('a ~ b', example_df).fit()

I'd like to apply the model to column c, but a naive attempt to do so doesn't work:
fit.predict(example_df["c"])

Here's the exception I get:
PatsyError: Error evaluating factor: NameError: name 'b' is not defined
    a ~ b
        ^

I can do something gross and create a new, temporary DataFrame in which I rename the column of interest:
example_df2 = pd.DataFrame(example_df["c"])
example_df2.columns = ["b"]
fit.predict(example_df2)

Is there a cleaner way to do this? (short of switching to statsmodels.api instead of statsmodels.formula.api)

A: You can use a dictionary:
>>> fit.predict({"b": example_df["c"]})
array([ 0.84770672, -0.35968269,  1.19592387, -0.77487812, -0.98805215,
        0.90584753, -0.15258093,  1.53721494, -0.26973941,  1.23996892])

or create a numpy array for the prediction, although that is much more complicated if there are categorical explanatory variables:
>>> fit.predict(sm.add_constant(example_df["c"].values), transform=False)
array([ 0.84770672, -0.35968269,  1.19592387, -0.77487812, -0.98805215,
        0.90584753, -0.15258093,  1.53721494, -0.26973941,  1.23996892])

A: If you replace your fit definition with this line:
fit = smf.ols('example_df.a ~ example_df.b', example_df).fit()

It should work.
fit.predict(example_df["c"])

array([-0.52664491, -0.53174346, -0.52172484, -0.52819856, -0.5253607 ,
       -0.52391618, -0.52800043, -0.53350634, -0.52362988, -0.52520823])


text:
Q: Delete (a,b) from a python list of tuples if (b,a) exists From a python list of tuples (which is essentially a cartesian product of a list with itself) I want to delete (a,b) if (b,a) is in the list.Only one of (a,b) or (b,a) must be retained. So a list
[(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]

must reduce to
[(1,2),(1,3),(2,3)]

(Although deleting (1,2) and retaining (2,1) is fine)
I tried doing this but I am not sure about deleting from a list while iterating over it. This doesn't work. (Gives me [(1, 2), (2, 1), (2, 3), (3, 1), (3, 3)])
[pairs.remove((a,b)) for (a,b) in pairs if ((b,a) in pairs)]

A: Why delete the incorrect ones from the list?
Use itertools.combinations to generate the correct ones instead.
>>> import itertools
>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]

A: >>> [el for el in pairs if el[0] < el[1]]
[(1,2),(1,3),(2,3)]

A: pairs = [(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2),(3,3)]
new_pairs = []

for a, b in pairs:
    if (a, b) in new_pairs or (b, a) in new_pairs:
        pass
    else:
        new_pairs +=  [(a,b)]

new_pairs = [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]


text:
Q: updating jsx with the response of the axios et call After getting the response from the get Axios call, I need to update the HTML but when updating the jsx like the following:
instance.get('/done.json').then(response => {
    task = response.data[Object.keys(response.data).pop()][props.match.params.id-1]
     console.log(task)
    // setseletectask(task)
        taskHmtl = (
        <Fragment>

{task.title}

{task.done}

        </Fragment>
    )
    }).catch(error=>console.log(error))

it doesn't update, so I have to create a new state and update it with the response value.
I need to know why the first approach didn't work correctly.

A:
it doesn't update, so I have to create a new state and update it with the response value

Correct

I need to know why the first approach didn't work correctly.

The component is already rendered, and assigning a value to a global variable doesn't trigger a re-render. This is why state exists in React.


text:
Q: lines of code within a class in python? I'm trying to find the number of lines of code within class or function that are stored in a python file
my code is like this... what I want is to find number of lines of code in the a class not all the file ... is there any good way to do so??
import inspect
import foo
for a,b in inspect.getmembers(foo):
    if inspect.isclass(b):
        print a  # find a class within the file

A: len(inspect.getsourcelines(a)[0])

From inspect.getsourcelines docs:

Return a list of source lines and starting line number for an object.

That's why you need the 0 index

A: You can still use inspect,
In [6]: from test import A

In [7]: import inspect

In [8]: inspect.getsourcelines(A)
Out[8]:
(['class A(object):\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n',
  '    pass\n'],
 1)

len(inspect.getsourcelines(A)[0]) will return you want.