text:
Q: Using Zend_Controller_Route to automatically determine the controller based on the user role: how? I am currently figuring out a way to the the above.
My current application structure is as follows:
/modules
 / modulename
  /controllers
    /ProjectController.php

The application has 3 different user roles, each with functionality contained within these modules. I'd like to prevent having multiple actions for each user role in one controller as I think it makes my code less readable and ugly. So, I was thinking about a structure like this:
/modules
 / modulename
  /controllers
    /ProjectController.php
    /EmployeeProjectController.php
    /ExecutiveProjectController.php

This should work as follows:

*

*Projectcontroller.php should be loaded for admin users

*EmployeeProjectController.php should be loaded for employees

*ExecutiveProjectController.php should be loaded for executives

Of course, I could relatively easy a different URL scheme to provide for this for each user role, but I do not want this. I want a uniform URL scheme.
Next step would then be to create routes for each of the controllers to rewrite them to another controller. I'd like to prevent this as well.
I want a way to globally tell the router to prefix controllers with 'Executive' or 'Employee' or whatever, based on the user role.
What would be the best way to this?

A: Sounds like you could use a front controller plugin with a routeStartup() method that examines the Zend_Auth instance and adds the role-specific routes (from INI or XML file, for example).
Something like this:
class My_Controller_Plugin_RouteByAuth extends Zend_Controller_Plugin_Abstract
{
    public function routeStartup()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()){
            return;
        }
        $identity = $auth->getIdentity();
        if ($identity->isAdmin()){
            $this->_addRoutes('routes_admin.ini');
        } else if ($identity->isEmployee()){
            $this->_addRoutes('routes_employee.ini');
        } else if ($identity->isExecutive()){
            $this->_addRoutes('routes_executive.ini');
        } else {
            return;
        }
    }

    protected function _addRoutes($file)
    {
        $front = Zend_Controller_Front::getInstance();
        $router = $front->getRouter();
        $routes = new Zend_Config_Ini(APPLICATION_PATH . '/configs/ ' . $file);
        $router->addConfig($routes);
    }
}

Not tested, but I hope this conveys a core of a workable idea.

A: I have spent quite some time figuring out how to use Zend_Controller_Router_Route to do this and have come up with as solution that works:

class App_Controller_Router_Route_Rolebasedcontroller extends Zend_Controller_Router_Route_Module
{
    /**
     * Roles that should be rewritten automatically
     *
     * @var array
     */
    protected $_rewriteRoles = array('employee', 'executive');

    /**
     * Matches a user submitted path. Assigns and returns an array of variables
     * on a successful match.
     *
     * If a request object is registered, it uses its setModuleName(),
     * setControllerName(), and setActionName() accessors to set those values.
     * Always returns the values as an array.
     *
     * @param string $path Path used to match against this routing map
     * @return array An array of assigned values or a false on a mismatch
     */
    public function match($path, $partial = false)
    {
        $result = parent::match($path, $partial);

        $role = Plano_Acl::getInstance()->getCurrentRole();

        if (null !== $role && in_array($role, $this->_rewriteRoles))
        {
            if (isset($result[$this->_controllerKey]))
            {
                $result[$this->_controllerKey] = $role . ucfirst($result[$this->_controllerKey]);
            }
        }

        return $result;
    }

    /**
     * Assembles user submitted parameters forming a URL path defined by this route
     * Removes fole prefixes when required
     *
     * @param array $data An array of variable and value pairs used as parameters
     * @param bool $reset Weither to reset the current params
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = true, $partial = false)
    {
        if (!$this->_keysSet) {
            $this->_setRequestKeys();
        }

        $params = (!$reset) ? $this->_values : array();

        foreach ($data as $key => $value) {
            if ($value !== null) {
                $params[$key] = $value;
            } elseif (isset($params[$key])) {
                unset($params[$key]);
            }
        }

        $params += $this->_defaults;

        $url = '';

        if ($this->_moduleValid || array_key_exists($this->_moduleKey, $data)) {
            if ($params[$this->_moduleKey] != $this->_defaults[$this->_moduleKey]) {
                $module = $params[$this->_moduleKey];
            }
        }
        unset($params[$this->_moduleKey]);

        $controller = $params[$this->_controllerKey];

        // remove role prefix from url when required
        $role = Plano_Acl::getInstance()->getCurrentRole();
        if (null !== $role && in_array($role, $this->_rewriteRoles))
        {
            if (substr($params[$this->_controllerKey], 0, strlen($role)) == $role)
            {
                $controller = lcfirst(substr($params[$this->_controllerKey], strlen($role)));
            }
        }

        unset($params[$this->_controllerKey]);

        $action = $params[$this->_actionKey];
        unset($params[$this->_actionKey]);

        foreach ($params as $key => $value) {
            $key = ($encode) ? urlencode($key) : $key;
            if (is_array($value)) {
                foreach ($value as $arrayValue) {
                    $arrayValue = ($encode) ? urlencode($arrayValue) : $arrayValue;
                    $url .= '/' . $key;
                    $url .= '/' . $arrayValue;
                }
            } else {
                if ($encode) $value = urlencode($value);
                $url .= '/' . $key;
                $url .= '/' . $value;
            }
        }

        if (!empty($url) || $action !== $this->_defaults[$this->_actionKey]) {
            if ($encode) $action = urlencode($action);
            $url = '/' . $action . $url;
        }

        if (!empty($url) || $controller !== $this->_defaults[$this->_controllerKey]) {
            if ($encode) $controller = urlencode($controller);
            $url = '/' . $controller . $url;
        }

        if (isset($module)) {
            if ($encode) $module = urlencode($module);
            $url = '/' . $module . $url;
        }

        return ltrim($url, self::URI_DELIMITER);
    }
}


text:
Q: difference between dynamic allocation static allocation MY question is
In any programming language is dynamic memory allocation faster than static memory allocation?
int main(int, char**)
{
    int *pa = new int; // faster than
    int a;             // ?
    return 0;
}

A:
is dynamic memory allocation faster than static memory allocation

What you are comparing is allocating on the stack (automatic) vs allocating on the heap (dynamic), static allocation is not involved here.
Allocating on the stack is fast in C++, once function is entered the space for automatic variables has been allocated. It is just a matter of subtracting the size of the required space from the stack pointer.
Heap allocation is generally slower than allocating on the stack. It involves carving out chunks of memory from the OS and then breaking down those chunks into smaller pieces to serve user's allocation requests. Heap managers can be pretty complex libraries, see memory management.

A: This is not static allocation but automatic allocation (your variables are locals). Static allocation is for static local, and global (file-scope) variables.
Nonetheless, dynamic allocation is never faster. In C and C++ it's a system call, which are slow.
Even if it wasn't so slow, automatic and static allocation are instantaneous. Static allocation happens at program start, and is just more space reserved for your process by the OS. Automatic allocation is just the stack pointer going a few bytes further when your function gets called. In either case, nothing more (CPU-wise) is done than if you hadn't allocated your variable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unboxing modifies items collection Having a problem with this Winforms project. Trying to use the SelectedIndexChanged event on a combBox that that was populated with the dictionary propList via:
comboBox1.DataSource = new BindingSource(propList, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

This is the event itself:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox comboBox = (ComboBox)sender;
    //comboBox.DataSource = null;
    System.Collections.Generic.KeyValuePair<int, string> dummy =
        (System.Collections.Generic.KeyValuePair<int, string>)
            comboBox.SelectedItem;

    //comboBox1.DataSource = new BindingSource(propList, null);
    PopulateCollars(dummy.Key);
}

It then throws this on the KeyValuePair cast:
Items collection cannot be modified when the DataSource property is set

I know this is the appriopriate cast, since debugging shows that:
SelectedItem  ~~~  object System.Collections.Generic.KeyValuePair<int,string>}

My question is then, why does an explicit cast modify the items collection? Being brought up on C++, where casts do not modify the data they are casting, this doesn't make sense to me.
As a note, using the lines commented out causes a null reference exception since apparently setting the data source to null wipes all members in the comboBox.

A: By any chance, are you modifying either dummy.Key or dummy itself in PopulateCollars?  Since I've never seen a cast change the data of an object either, that routine seems more likely to be the culprit.  As I commented above, sometimes VS is just plain wrong about what line threw the error.
ETA:  Okay, that's not it.  Here's an idea.  Examine the stack trace of the exception, and see whether there's any interesting layers between your method and the method that (in the framework) threw the exception.  Also make sure that this method is not being recursively invoked through something in PopulateCollars that causes the list to change.
If you are trying to reuse the same combo box with other data while handling a change caused by the combo box, that probably won't work.


text:
Q: Are there any first order linear maps from vector valued functions to vector valued functions other than curl? Let $V$ be the vector space of $\mathbb{C}^\infty$ functions from $\mathbb{R}^n$ to $\mathbb{R}^n$ and consider some linear map $L:V\rightarrow V$ such that $L$ can be expressed strictly in terms of first order derivatives. Also, $L$ should be invariant under isometries of $\mathbb{R}^n$, that is, if $\forall x\in\mathbb{R}^n, f_2(x)=f_1(Ax+b)$ and $g_2(x)=g_1(Ax+B)$ for some vector $b$ and matrix $A$ such that $A^TA=I$, then $L(f_1)=g_1\iff L(f_2)=g_2$. For example, the curl map $f\rightarrow \nabla\times f$ is such a map. Notice these maps are closed under linear combination and thus form a vector space that I will call $W_n$.
I would like a basis for $W_n$ for each $n$. For example, for $n=1$, the derivative operator can be taken to be the single element of such a basis. Further more, I suspect $W_2$ is $0$ dimensional (please let me know if I am wrong here). For $3$ dimensions, I only know curl to have these properties and so I suspect $dim(W_3)=1$. For $W_n$ with $n≥4$, I have no idea.
Finally, I suspect this question can be better phrased (especially the isometry invariance condition) so if you know how to rephrase it better and would like to, go ahead. Also the title could probably be rephrased.


text:
Q: Converting raw print codes to a printer using a VB.net web page I've run into a situation I've never encountered before. I'm working with a shipping API for an e-commerce site and I've retrieved a shipping label. The problem is that the code used for the label is what appears to be raw print codes. They look something like this:
N
Q822,24
R40,0
S4
D15
ZB

A760,120,1,1,1,1,N,"Interlink Express"
A735,080,1,1,1,1,N,"www.interlinkexpress.com"
A706,033,1,1,1,1,N,"Sender"
.... more codes like this
LO001,330,765,10
LO001,025,765,1
LO001,192,590,1
LO001,330,765,10
.... more codes like this
P1

What I'd like to be able to do is convert it to a graphic or something else that I can print from a web page. The problem is that I can't find any ways to deal with this particular type of information, since it's not in a web-standard format (it's not HTML, XML, JSON, etc.)
How would I deal with something like this?
Thanks.

A: In the end, I solved this a different way. Apparently the shipping company was able to use an Accept: text/html header from my HttpWebRequest and I got an HTML-formatted printer label. So we're good. Thanks.


text:
Q: How to setUp UiTableViewController below the battery bar newBie here. I have added an UItableViewController into storyBoard. I use this as a setting page.
HomeVC ---->  Setting VC
In code : I use the below code to bring the tableView below the battery Bar:
 self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)

Problem:
How to move the TableView down below the battery bar so that I can add a button above the table in StoryBoard
Please help.

A: For this you should use a normal view controller and drag a table on the view controller this way you can make the table size whatever you like. This will also allow you to place buttons wherever you like.
Don't forget to assign the TableViewDataSource and TableViewDelegate to your view controller.
Good luck!

A: After doing some search on UiTableViewController, to use it as setting page I have to set static cell to it. This UiTableViewController will occupy the entire view.
To set the tableView below the battery icon,
use:self.tableView.contentInset = UIEdgeInsets(top: 20,left: 0,bottom: 0,right: 0)
However, No need to do so. In the first TableViewSection, you can create a few tableView cell, just leave the first cell blank which acts as a margin below the battery bar.


text:
Q: How to check brightness of a background color to decide text color written on it I have a simple question, but I wasn't able to find an answer to this.
Note, that I'm almost a complete beginner.
So I have an app (it's not mine, but I'm contributing to it), and in there is writing on a color background, which can be changed by the user.
The writing should appear black if the background is bright enough but stay white if it isn't.
The application is a school diary app for elementary and high-school students that connects to the state-wide school diary service in Hungary. Here, the best note is 5, the worst is 1. The user can set the colors of each grade in the settings. Right now, only the code for the note "4" is hard-coded to have black text (because the background is yellow by default on "4" notes), all others have white. This is what I want to automate.
Example of white text
Example of black text
This is the main screen of the app for reference
Page where user can change color for a kind of note
Code right now:
switch (evaluation.NumberValue) {
    case 1:
      bColor = globals.color1;
      fColor = Colors.white;
      break;
    case 2:
      bColor = globals.color2;
      fColor = Colors.white;
      break;
    case 3:
      bColor = globals.color3;
      fColor = Colors.white;
      break;
    case 4:
      bColor = globals.color4;
      fColor = Colors.black; //This should be white if color4 is dark enough. Same applies to all of them.
      break;
    case 5: //I'm looking for something like this:
      bColor = globals.color5;
      fColor = (lightLevel(globals.color5) > 50) ? Colors.black : Colors.white;
      break;
    default:
      bColor = Colors.black;
      fColor = Colors.white;
      break;
  }

I'm looking for something like this:
 case 5: //I'm looking for something like this:
  bColor = globals.color5;
  fColor = (lightLevel(globals.color5) > 50) ? Colors.black : Colors.white;
  break;

Thank you for any help!

A: I can suggest 2 options:

*

*ThemeData.estimateBrightnessForColor method e.g.

Color calculateTextColor(Color background) {
  return ThemeData.estimateBrightnessForColor(background) == Brightness.light ? Colors.black : Colors.white;
}

*Color.computeLuminance method e.g.

Color calculateTextColor(Color background) {
  return background.computeLuminance() >= 0.5 ? Colors.black : Colors.white;
}

Keep in mind that both are computationally expensive to calculate. The former uses the latter one under the hood. The difference is in how to compute the threshold between light and dark.

A:
Brightness.estimateBrightnessForColor method e.g.
Color calculateTextColor(Color background) {
  return Brightness.estimateBrightnessForColor(background) == Brightness.light ? Colors.black : Colors.white;
}

I found that the method estimateBrightnessForColor is now part of the class ThemeData, so need to be called like this now:
ThemeData.estimateBrightnessForColor(background)


text:
Q: Javascript disable button I am wondering if someone can help me out with this.
I have a button defined as:
<input type="button" id="myButton" name="myButton" value="ClickMe!!" onClick="callMe()"/>

I can use jQuery, standard javascript or Dojo to disable the button with onClick event:
$('#myButton').attr('disabled', 'disabled');

The problem I am facing is, even though this code disables the button, onClick event still triggers the function callMe() if I click on the button.
How do I make the disabled button not call the onClick function?

A: With jQuery you can bind a function that checks if your button is disabled:
$('#myButton').click(function() {
  if (!$(this).is(':disabled')) {
    callMe();
  }
});

A: Since you're using jQuery, use
$('#myButton').click(function() { callMe(); this.unbind(); });

instead of onClick.

A: $('#myButton').click(function(){
    if( !$(this).is('[disabled=disabled]') ){
       ...
    }
});

A: In the same code where you disable it, simply remove the onclick event handler.

A: you should be using jQuery to attach the click handlers, not adding them inline*
Just add a check to your click function
$('#myButton').click(function(){
  var $this;
  $this = $(this);
  if ( $this.is(':disabled') ) return;
  callMe();
});

Alternatively,
$('#myButton').click(callMe);

callMe()
{
  var $this;
  $this = $(this);
  if ($this.is(':disabled')) return;
  ...the rest of your code...
}

Or if you insist on using it inline:
onclick="if ($(this).is(':disabled')) return; callMe();"

* I regularly rant about how HTML, CSS & JS fit the definition of MVC

A: instead of using onclick attribute, bind to the event
$('#myButton').click(function(e){
    // try it without this
    if($(this).attr('disabled'))
        return false;
    callMe();
    e.preventDefault();
});

try it without the check, not sure if its necessary.

A: This is one way of doing.
$('#myButton').click(function(){
  if(!$(this).hasClass("disabled")){
     //Do stuff here
  }
});

To disable the buttons just add the disabled class to it.
$('#myButton').addClass("disabled");

Add appropriate styles in the disabled class to make button look like disabled or you can also set the disabled property along with setting the class.

A: Instead of ...
$('#myButton').attr('disabled', 'disabled');

... use ...
$('#myButton')
   .prop('disabled', 'disabled')  // Sets 'disabled' property
   .prop('onclick', null)         // Removes 'onclick' property if found
   .off('click');                 // Removes other events if found


text:
Q: Wordpress page title fxn in echo p This is probably super simple but I just cant seem to figure it out.
How can I pass the current Wordpress page title into this code?
Below is a snippet from Formidable Forms WP plug-in which basically prints statistics from forms within my website.
In this case, the # of entries for a specific form (55jqi) and a specific field(50) are displayed on the pages, showing how many other people also submitted that form.
Im trying to skip needing to update each page (4,380 pages) with the stats output snippet.. and instead call the current page into the stats display code, to show stats for that particular page being viewed.. using an elementor custom post type template.
I need this:
echo FrmProStatisticsController::stats_shortcode(array('id' => '55jqi', 'type' => 'count', 50 => 'runtz'));

To work like this:
echo FrmProStatisticsController::stats_shortcode(array('id' => '55jqi', 'type' => 'count', 50 => 'single_post_title();'));

Replace the input area 'Runts' with the current page title, using
single_post_title()

Or similar.
Any help would be amazing!!
There is also a short code available which works the similarly.
[frm-stats id=55jqi type=count 50="Runtz"]

Formidable Forms Plugin shortcode and php page for reference: https://formidableforms.com/knowledgebase/add-field-totals-and-statistics/#kb-field-filters

A: You are using single_post_title function in a wrong way. By default, this function will echo the output but in the shortcode, you need to return the output.
This function accepts 2 param: 1: $prefix 2: $display
You need to pass $display as false, which will tell the function to return the value.
so you'll have to make a call like this `single_post_title( '', false )``
and your shortcode call will be like this:
echo FrmProStatisticsController::stats_shortcode(
    array(
        'id'   => '55jqi',
        'type' => 'count',
        '50'   => single_post_title( '', false ),
    )
);


text:
Q: How do I can I access elements in json file (API) using javascript? I am trying to display all names in this JSON file,
https://next.json-generator.com/api/json/get/41P1_UhSI

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>testing</title>
</head>
<body>
    <script>

        const api_url = 'https://next.json-generator.com/api/json/get/41P1_UhSI';
        async function getAPI() {
            const response = await fetch(api_url);
            const data = await response.json();
            console.log(Object.values(data.name)); //or console.log(data.name);
        }
        getAPI();
    </script>

</body>
</html>

I am getting an error: "undefined" when I run this code.
Would be great if anyone could point me in the right direction, thanks!

A: data isn't an object with a name property, so name is undefined on it.
data is an array containing many objects with name properties.

A: Try this:
const api_url = 'https://next.json-generator.com/api/json/get/41P1_UhSI'
async function getAPI() {
  await fetch(api_url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      data.map(it =>
      console.log(it.name))
    });
}
getAPI();


text:
Q: Matching on a particular type of a parametric type I'm trying to work with an external library that has provided a parametric type like this:
data ParametricType a = TypeConstructor a

I have a typeclass, something like this:
class GetsString a where
    getString :: a -> String

and I'd like to execute some code if ParametricType's a is a specific type. I've tried narrowing the type when instantiating the typeclass:
data HoldsString = HoldsString String

instance GetsString (ParametricType HoldsString) where
    getString (TypeConstructor (HoldsString str)) = str

which errors with Illegal instance declaration for'GetsString (ParametricType HoldsString)'(All instance types must be of the form (T a1 ... an)
and I've tried pattern matching on the type:
instance GetsString (ParametricType a) where
    getString (TypeConstructor (HoldsString str)) = str

for which I receive Couldn't match expected type 'a' with actual type 'HoldsString''a' is a rigid type variable bound by the instance declaration.
Is there a way to do this, or am I conceptually on the wrong track here?

A: You're just missing the FlexibleInstances extension. Put {-# LANGUAGE FlexibleInstances #-} at the top of your file, or do :set -XFlexibleInstances if you're typing into GHCi directly, and then your first attempt will work.


text:
Q: How do I count the number of unique interactions between turtles in my model? I am writing a NetLogo model to describe the food exchange interactions between pairs of bees until the food is distributed evenly among all. I have two breeds of "fulls" and "hungries" in my model. Right now I am counting the number of interactions until the model stops, like this:
ask turtles [
     set neighborhood other hungries-on neighbors
     set target one-of neighborhood with-min [distance myself]
     ifelse target != nobody
       [ exchange-food
         set counter counter + 1]
     ;if there are no hungry neighbors continue moving and searching for one
        [continue ]
]

The counter here, counts all the exchange-food interactions but I am also interested in the number of unique interactions. Does it mean that I have to keep a list of tuples as a turtle-own variable for each turtle! But I don't even need the actual ids, I just want to count the number of unique interaction. How can I keep track of this? Any simpler ideas?


text:
Q: how to specify port number with ip for registering server for gcm Hi i am trying to register my server ip for gcm notification.
My test server url was
 http://xxx.xxx.x.xxx/mHealth_new/
and it was working fine...than i changed ip to live which is
  http://xxx.xx.xxx.xx:8086/mhealth_app/
but i cant configure this url with port 8086 it gives me error

please help me....

A: In "Accept requests from these server IP addresses" section, you should fill the IP address of your current server, which is xxx.xx.xxx.xx. 8086 is the port number you use to access your server using http, not the port number used when your server sends the request to gcm server. The port that is used to send the request to gcm server is randomly assigned by the operating system.


text:
Q: Protobuf-net IsPacked=true for user defined structures Is it currently possible to use IsPacked=true for user defined structures? If not, then is it planned in the future?
I'm getting the following exception when I tried to apply that attribute to a field of the type ColorBGRA8[]: System.InvalidOperationException : Only simple data-types can use packed encoding
My scenario is as follows: I'm writing a game and have tons of blitable structures for various things such as colors, vectors, matrices, vertices, constant buffers. Their memory layout needs to be precisely defined at compile time in order to match for example the constant buffer layout from a shader (where fields generally? need to be aligned on a 16 byte boundary).
I don't mean to waste anyone's time, but I couldn't find any recent information about this particular question.
Edit after it has been answered
I am currently testing a solution which uses protobuf-net for almost everything but large arrays of user defined, but blitable structures. All my fields of arrays of custom structures have been replaced by arrays of bytes, which can be packed. After protobuf-net is finished deserializing the data, I then use memcpy via p/invoke in order to be able to work with an array of custom structures again.
The following numbers are from a test which serializes one instance containing one field of either the byte[] or ColorBGRA8[]. The raw test data is ~38MiB of data, e.g. 1000000 entries in the color array. Serialization was one in memory using MemoryStream.
Writing
Platform.Copy + Protobuf: 51ms, Size: 38,15 MiB
Protobuf: 2093ms, Size: 109,45 MiB
Reading
Platform.Copy + Protobuf: 43ms
Protobuf: 2307ms
The test shows that for huge arrays of more or less random data, a noticeable memory overhead can occur. This wouldn't have been such a big deal, if not for the (de)serialization times. I understand protobuf-net might not be designed for my extreme case, let alone optimized for it, but it is something I am not willing to accept.
I think I will stick with this hybrid approach, as protobuf-net works extremely well for everything else.

A: Simply "does not apply". To quote from the encoding specification:

Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire types) can be declared "packed".

This doesn't work with custom structures or classes. The two approaches that apply here are strings (length-prefixed) and groups (start/end tokens). The latter is often cheaper to encode, but Google prefer the former.
Protobuf is not designed to arbitrarily match some other byte layout. It is its own encoding format and is only designed to process / output protobuf data. It would be like saying "I'm writing XML, but I want it to look like {non-xml} instead".


text:
Q: react css imported in jsx module not applied I import my css file like:
import styles from "./Documentation.module.css";

Use the style here:
<button
    className={styles.button}
    onClick={(e) => selectDoc(m.id)}
    >
    <b>{m.title}</b>
</button>

The css for the button looks like:
.button {
    color: "#d0e6a5";
    background-color: "#5d684b";
    border: "none";
    border-left: "4px solid #d0e6a5";
    font-size: "28px";
    padding: "6px 12px";
    margin: "3px";
    width: "200px";
}

but the css doesnt get applied to the button element. This happens to all styles. I have no more idea what the proplem could be.
Using inlined or "style" is no option for me here, sice the css will get a bunch more.
Any idea how i could diagnose the problem here?

A: The bug is in the css file the syntax is incorrect. You dont have to put quotes in he values. Try to replace it with the following css
.button {
color: #d0e6a5;
background-color: #5d684b;
border: none;
border-left: 4px solid #d0e6a5;
font-size: 28px;
padding: 6px 12px;
margin: 3px;
width: 200px;}


text:
Q: Valores nulos en hashtable - Java Estoy desarrollando una pequeña app en Java, en la cual hago una conexion a una base de datos y obtengo un campo JSON, ese JSON lo transformo a objeto, y posteriormente los voy insertando a un hashtable, y finalmente retorno el hashtable...
El Asunto esta, en que en la base de datos tengo 4 rows, y en la App al momento de agregar a la tabla los datos del hashtable, solo toma 3... Si agrego otro dato a la base ded atos solo toma 4 de 5... y asi sucesivamente
Codigo: (DatabaseConnection.java)
    public static <T> Hashtable<Integer, T> GetList(String Table) throws Exception{

    T obj = null;
    Hashtable<Integer, T> objs = new Hashtable<Integer, T>();
    int id = 0;
    String data;
    Connection Connector = Connect();

    try{

        Statement Stats = Connector.createStatement();
        String sql = "SELECT * FROM " + Table;
        ResultSet result = Stats.executeQuery(sql);

        while(result.next()){
            id = result.getInt(1);
            data = result.getString(2);

            obj = SerializerClass.Deserialize(data);
            objs.put(id, obj);
            System.out.println(id);
        }

    }catch(SQLException sqlEx){
        throw new Exception("Exeption Ocurred. " + sqlEx.getMessage());
    }

    return objs;
}

Codigo #2 (PrincipalForm.java)
public void UpdateGUI(){
    Columns = new String[] {"Nombre", "Servicio", "Fecha", "Estado"};
    n = new DefaultTableModel(Columns, 0);
    SessionsTable.setModel(n);

    try{
        this.SesionesList = DataBaseConnection.GetList("sesiones");
        if (!SesionesList.isEmpty()) {
            for (int i = 0; i < SesionesList.size(); i++) {
                if (SesionesList.get(i) != null) {
                    String Name = SesionesList.get(i).Name;
                    PaqueteCasual Service = SesionesList.get(i).Servicio;
                    String fecha = SesionesList.get(i).Fecha;
                    Estado State = SesionesList.get(i).State;

                    Object[] data = { Name, Service, fecha, State };

                    n.addRow(data);
                }else { System.out.println("Is null"); }
            }
        }else{
            System.out.print("Its Empty.");
        }

    } catch (Exception ex) {
        System.err.print("ERROR: " + ex.getMessage());
        Logger.getLogger(SesionesPrincipalForm.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Por lo que he notado, es que al llegar al 4to valor, devuelve un null. Como podran notar en el Codigo #2, tengo un IF que confirma si es null o no, y efectivamente.. con los 3 primeros valores los toma, pero el 4to es Nulo

A: for (int i = 0; i < SesionesList.size(); i++) {
            if (SesionesList.get(i) != null) {
                String Name = SesionesList.get(i).Name;

Estás intentando recorrer un Map como si fuera un List. No funciona así.
En las listas, buscas por índice, y sabes que va por orden. Así que el primer elemento será 0, luego 1, así hasta size() - 1.
En los mapas relacionas una clave con el elemento, y buscas por la clave. Si hay 10 elementos, no tienes porqué poder recuperarlos usando como claves los números de 0 a 9, sino las claves que se usaron.
Por ejemplo
Map mapa = new Hashtable();
mapa.put("Hola", "Mundo");
System.out.println(mapa.get("Hola")); // Imprime "Mundo"
System.out.println(mapa.get(0));  // Imprime null, porque no hay ningún elemento que tenga 0 como clave.

Si quieres iterar, dos opciones:

*

*Usa una lista o array, que para eso están.

*El método keys() devuelve un Enumeration con todas las claves definidas. Iteras sobre esas claves, y para cada una de esas claves haces el get correspondiente.


text:
Q: Can not connect HM10 to Android device I am having problems connecting an Android device to my HM10 with an Arduino. I have managed to connect it with an iPhone, but the problem is when trying with Android. It gets to the function public boolean connect(final String address), which is a function that is called when trying to connect to a device, but does not seem actually to connect to the device.
The code I used this project had been used earlier with a RedBearLabs BLE Shield and the code worked for that BLE device. Same thing for my Swift code for iPhone, but when changing to HM10 I only had to change the UUID and then everything was fine. This however does not seem to be the only change that I have to do for Android.
These are the UUID I use for Android:
public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
public static String BLE_SHIELD_RX_TX = "0000FFF1-0000-1000-8000-00805f9b34fb";
public static String BLE_SHIELD_SERVICE = "0000FFF0-0000-1000-8000-00805f9b34fb";

The UUID for BLE_SHIELD_SERVICE and BLE_SHIELD_RX_TX I asked from the manufacturer (Feasycom).
These UUID is used for iPhone (should be the same?):
var characteristicUUID = CBUUID(string:"FFF1")
var serviceUUID = CBUUID(string:"FFF0")

Probably I forgot to mention something important, so please ask if there is anything that is unclear.


text:
Q: Add Computed Column and Put Index on it I have a table which include,
CREATE TABLE [dbo].[ProductsAttributesValues](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [ProductId] [int] NOT NULL,
    [AttributeId] [int] NOT NULL,
    [Value] [nvarchar](3000) NOT NULL
)

this table include huge amount of rows. The problem is that lot of time the [Value] column include float or int values but sometimes it include text as well. Now, I am thinking to add an Index on float or int values so that the index will use <, >, <=, >= and BETWEEN operators efficiently. So, how can I create a computed column which will cast the value to float and then add index to this computed column? Is this possible?

A: A float expression is considered imprecise and cannot be a key of an index; a float expression can be used in an indexed view but not as a key. This is true also for computed columns. Any function, expression, or user-defined function is considered imprecise if it contains any float expressions. This includes logical ones (comparisons).
However, you You can create an index on a computed column that is defined with a deterministic, but imprecise, expression if the column is marked PERSISTED in the CREATE TABLE or ALTER TABLE statement. Taken from here.
-- This will add your float computed column:
ALTER TABLE ProductsAttributesValues ADD Value_Float AS
(
    CASE WHEN ISNUMERIC([Value]) = 1 THEN
        CONVERT(float, [Value])
    ELSE
        NULL
    END
) PERSISTED;

-- This will create the index:
CREATE INDEX IX_ProductsAttributesValues_Value_Float
ON ProductsAttributesValues (Value_Float);


text:
Q: Creating a Proof of Concept Infrastructure in Azure I'm looking for some guidance and/or maybe some pre-existing examples of standing up an example infrastructure in Azure.
Specifically, I'm looking at setting up some sort of load balanced web front end that talks to a load balanced database backend.
The goal is to have a PoC/Demo infrastructure running to validate external connectivity as well as ensure load balancing is working on both the web and database side of things.
Before running in-house applications, it would be nice to be able to stand up an environment for testing purposes that is completely standalone and is very simple to setup with a basic web page and database connection.
If anyone has any suggestions it would be appreciated. It doesn't have to be Azure specific mind you, but the goal is to set it up or replicate it's functionality in Azure.
Thanks!

A: just create 2 sets of vms with 1 lb for each set, you can easily find examples of this setup online (https://github.com/Azure/azure-quickstart-templates/tree/master/201-2-vms-loadbalancer-lbrules) and put databases\websites on the vms.


text:
Q: What is the difference between a term and a word? I know a word is more specific compared to a term but i don't know which one is definitive or the actual meaning of the two.

A: A word is language that is officially accepted,has an official definition, and is understood the same by everyone in general. A term is language used formally or informally that may be understood among some or a specific group (such as within an industry, a gang, a culture) but not everyone. For example slang.

A: We say "term" when discussing a word that has a specific meaning in a special context. Like someone might say, "What is the term in chemistry for a substance that ..." "Word" is more general. "The" and "dog" are words. You'd rarely refer to them as "terms".
Also, a "term" can be more than one word. Like you might say, "The term for that is 'style injection'", i.e. two words making up a single term.


text:
Q: Prove that $(x+1)^x-x^x(x-1)$ only has one (real) root For $x>0$, I want to prove that $(x+1)^x-x^x(x-1)$ only has one root

A: Write your equation as
$$ (1+1/x)^x = x-1 $$
Note that $x > 1$ is required for both sides to have the same sign, and then
$$ x \log(1+1/x) - \log(x-1) = 0$$
Call the left side $g(x)$.  Now show that

*

*$g(x)$ is convex.

*$\lim_{x \to 1+} g(x) = +\infty$

*$\lim_{x \to \infty} g(x) = -\infty$.

EDIT: As Clclstdnt comments, $g'' = \frac{x^3+x^2+3x-1}{x(x^2-1)^2}$.  For $x > 1$, both numerator and denominator are positive, so $g$ is convex on $(1,\infty)$.  Since $\lim_{x \to \infty} g(x) = -\infty$, this implies $g' < 0$ (i.e. if $g'(b) \ge 0$ for some $b$, we'd have $g'(x) \ge 0$ for $x \ge b$, and then $\lim_{x\to\infty} g(x)$ couldn't be $-\infty$).  That tells you $g$ has at most one zero.  On the other hand, (2) and (3) and the Intermediate Value Theorem say there is at least one.

A: My answer is definitely going to pull from some ideas of Robert Israel.
So first we re-write the equation as
$$(1+1/x)^x = x-1$$ as previously suggested.  Then we consider these as two separate functions and ask when they intersect.
Let $f(x) = (1+1/x)^x$ and let $g(x)=x-1$.
Motivated from the following answer How to prove $(1+1/x)^x$ is increasing when $x>0$?
we see that $\log(f(x))' = \log(1+\frac{1}{x})-\frac{1}{x+1}$ is increasing and hence $f(x)$ is too. Likewise one can easily show that $\log(f(x))'' = -\frac{1}{x(1+x)^2}<0$ this shows that $f$ is log-convex and hence convex (this follows from the following The composition of two convex functions is convex since $Exp$ is convex and $\log(f)$ is convex hence $f=Exp[\log(f)]$ is too).
$g(1)=0$ and $f(1)=2$ so $g<f$ at $x=1$. Now that we have established $f$ is convex it follows that once $g$ (a straight line) is greater than $f$ it is always greater. It follows there is one and only one solution for the equation equivalently $g$ intersects $f$ exactly once.


text:
Q: Trace Flag 3688 not working on SQL Server 2014 We are using some third party tools that fill up the SQL Server logs with entries like:

SQL Trace ID 1 was started by login "sa".
SQL Trace ID 2 was started by login "XX\xxxxx".
SQL Trace stopped. Trace ID = '2'. Login Name = 'XX\xxxxx'.
SQL Trace ID 2 was started by login "XX\xxxxx".

I am trying to suppress these by enabling TF 3688 but it is not working on SQL Server 2014, 2012 or SQL 2008 R2. Here is a snapshot of the configuration. Please let me know if I am missing anything:

I have restarted the instance and verified that the trace flag is active using DBCC TRACESTATUS:

A: That trace flag isn't documented and shouldn't be used in production environments.
That said, it appears that the trace flag stopped working in SQL Server 2008 R2 and newer.  As it's undocumented Microsoft won't take a support ticket to fix it as you shouldn't have been using an undocumented trace flag.
All undocumented commands and features can be changed at Microsoft's whim.


text:
Q: sync woocommerce stock quantity with external API I'm trying to sync my woocommerce store products quantity to an external API.
I need all product stock quantities in my shop to be retrieved from the supplier's website API.
I always sync all stock quantities manually but it's a huge work when you have more than 70 products with 5-6 variations each, so I decided to try their API to always have my product stock in sync with theirs automatically (note that I only need to retrieve stock info from them, not the other way round).
This is the code they provide:
require_once("client_v1.1/tl_api_client_class.php");

ini_set("error_reporting", E_ALL | E_NOTICE);
ini_set("display_errors", "on");
header("content-type: text/html; charset=utf-8");

//all API errors will be send through an Excepion
try {
  //create a tl_api_client passing the login information (key, user, password)
  $tl_client = new tl_api_client(
                                 "YOUR_API_KEY",
                                 "YOUR_API_USER",
                                 "YOUR_API_PASSWORD"
                                );

  //get english language details for the product with id 1149
  //null if no result
  $product = $tl_client->get_details(1149, "en", "USD");

  //get quantity for each color
  $color_quantity = array();

  foreach( $product->attributes as $attribute ){
    $result = $tl_client->get_quantity(20, 1);
    /*Return null if no result for this param or a GetQuantityResult object
      object(
      [product_id]
      [attributes_id]
      [quantity]
      )
    */
    $color_quantity[$attribute->attributes_name] = $result->quantity;
  }

} catch (Exception $e) {
  //catch error
  echo $e->getMessage();
  exit;
}

//Do something with the result
?>

<?php echo $product->parts_code; ?> - <?php echo $product->products_price; ?> EUR

            color

            quantity

        <?php foreach ($color_quantity as $color => $quantity): ?>

              <?php echo $color; ?>

              <?php echo $quantity; ?>

        <?php endforeach; ?>

I already have and API key, a user and a password. My guess is I need to make a new plugin, put the first part of this code in it (until it creates a tl_api_client), and then use a function to update my whole stock. Could anybody help with this last part (given my first assumption is correct)?
Thanks a lot in advance
Alessio
EDIT: Ok, I got it 90% done, but I'm missing one last bit, the part where a variation's stock is updated with the new $stock value. what I did til now (and it works):
require_once("client_v1.1/tl_api_client_class.php");

ini_set("error_reporting", E_ALL | E_NOTICE);
ini_set("display_errors", "on");
header("content-type: text/html; charset=utf-8");

add_filter( 'init', 'update_stock', 10, 1);

   function update_stock( $stock ){

       $args = array(

               'post_type' => 'product'

               );

       $i=0;

       $loop = new WP_Query( $args );

       if ( $loop->have_posts() ) {

           while ( $loop->have_posts() ) : $loop->the_post();

              global $woocommerce, $product, $post;
              $colorvalues = get_the_terms( $product->id, 'pa_color');
              $available_variations = $product->get_available_variations();

              foreach ( $available_variations as $available_variation) {

                    $variation_id = $available_variation['variation_id'];
                    $variation_object = get_post($variation_id);
                    $parentsku = $product->get_sku();
                    $tlsku = (int)substr($parentsku, -4);
                    $varsku = get_post_meta( $variation_object->ID, '_sku', true);
                    $tlvarid = (int)substr($varsku, -1);
                    try {
                      //create a tl_api_client passing the login information (key, user, password)
                      $tl_client = new tl_api_client(
                                                   "**",
                                                   "***",
                                                   "****"
                                                  );
                      $stock = $tl_client->get_quantity($tlsku, $tlvarid);
                    } catch (Exception $e) {
                      //catch error
                      echo $e->getMessage();
                      exit;
                    }

              }

               $i++;

           endwhile;

       } else {

           echo __( 'No products found' );

       }

       wp_reset_postdata();

   }


text:
Q: Is Excel coauthoring possible with Microsoft Graph? We want to manipulate cells (+ read cell data) of an Excel workbook stored on Sharepoint. A C# service will be used for this automation. A human user plus the automation are supposed to look at the same workbook without harming each other.
Is the Graph api suitable for this at all?
I only had a brief look at Graph and followed a simple tutorial. I would now have to write a test app to see if our requirements are met, but I was hoping someone here has done something similar.
Currently, we are using Excel interop (yes, it is a bad idea to use it in a service) and we know no other automated approach to coauthoring.

A: Yes, coauthoring works with Microsoft Graph. We replaced our previous interop solution and it works like a charm.


text:
Q: Navigation title color I have implemented a navigation controller through Drag and Drop, now I want to set the my own custom colour of RGB:
[UIColor colorWithRed:0.992 green:0.443 blue:0.173 alpha:1.0].

while I implement the following code it gives me another Color.
[self.navigationController.navigationBar setTitleTextAttributes:
 @{NSForegroundColorAttributeName:[UIColor colorWithRed:0.992 green:0.443 blue:0.173 alpha:1.0]}];

How can i get my required color...?

A: The RGB you are setting is of Orange color ,
[UIColor colorWithRed:0.992 green:0.443 blue:0.173 alpha:1.0].

This means  R = 253 G = 113 B = 44
Check it on this link
For Light blue color this will help .
R=164  , G=224 , B= 254 .
You need to code like this
[UIColor colorWithRed:164/255.0f green:224/255.0f  blue:254/255.0f  alpha:1.0].

Hope this Helps!


text:
Q: I am writing query for database using SQL and during that i get the following error code......Duplicate value and error code is 1062. What should i do My query is as follows
CREATE DATABASE CRICKET
SHOW DATABASES
USE CRICKET;
CREATE TABLE INDIAXI(
   MATCHES         INT                   NOT NULL,
   NAME            VARCHAR (20)          NOT NULL,
   AGE             INT                   NOT NULL,
   RUNS            INT                   NOT NULL,
   AVERAGE         DECIMAL               NOT NULL,
   PRIMARY KEY (NAME)
);

INSERT INTO INDIAXI (MATCHES, NAME, AGE, RUNS, AVERAGE)
VALUES (155, 'TENDULKAR', 26,  9000, 45.6);

INSERT INTO INDIAXI (MATCHES, NAME, AGE, RUNS, AVERAGE)
VALUES (160, 'VIRENDRA', 27, 18000, 46.6);

INSERT INTO INDIAXI (MATCHES, NAME, AGE, RUNS, AVERAGE)
VALUES (165, 'UMESH', 28, 11000, 47.6);

INSERT INTO INDIAXI (MATCHES, NAME, AGE, RUNS, AVERAGE)
VALUES (170, 'RAHUL', 29, 10500, 48.6);

INSERT INTO INDIAXI (MATCHES, NAME, AGE, RUNS, AVERAGE)
VALUES (175, 'VVS', 30, 6000, 50.0);

INSERT INTO INDIAXI (MATCHES, NAME, AGE, RUNS, AVERAGE)
VALUES (180, 'KAIF', 31, 9000, 61.6);

A: The NAME field value yo are trying to insert is already there in the table. PRIMARY KEY implies value must be unique.

*

*either do not insert the same value twice

*or do not make NAME the primary key


text:
Q: Call dictionary from variable python I have a dictionary:
dictionary_a = {
    "name": "a"
}

and a variable:
dictionary_selection = "dictionary_a"

Is there a way to get elements from the dictionary determined by the variable?
E.g.
Is there some way to get a script like this to work?
print(dictionary_selection["name"])

Not sure if this is possible or if the title is correct

A: You may have a try on globals() and locals() functions.
>>> dictionary_a = {"name":"a"}
>>> dictionary_selection = "dictionary_a"
>>> globals().get(dictionary_selection)["name"]
'a'
# locals() use like globals()

But the better way may be:
data = {}
data["dictionary_a"] = {"name":"a"}
dictionary_selection = "dictionary_a"
data.get(dictionary_selection)["name"]
# this way can control the data by yourself with out the constraint of namespaces

emmm,hope can help you .

A: It can be done like this.
dictionary_a = {"name": "a"}
dictionary_selection = "dictionary_a"
key="name"
index=eval(dictionary_selection+"["+"'"+key+"'"+"]")
print(index)

A: Say you have a dictionary d
d={'apple': 'fruit', 'onion':'vegetable'}

Trying to do the following will give you an error:
dict_name='d'
print(d['apple'])

This is because dict_name stores a string with value d. Even though d is the name of a variable, python does not know to evaluate it as such and you will get an error like
TypeError: string indices must be integers

You could evaluate the string by doing this:
eval(dict_name)['apple']

This will evaluate the variable, see that it is a dictionary, and give you the output apple.
However, this is not a good way to do it. You would be better off using another dictionary or list to keep track of all your dictionaries.
with list:
dict_list=[d, d1, ...]
print(dict_list[0]['apple'])

with dictionary:
all_dicts{'d':d}
print(all_dicts['d']['apple'])


text:
Q: Lightroom CC freezes whole PC I don't know what else to try, so I decided to ask here.
Sometimes Lightroom freezes the whole PC and I have to reboot. It doesn't happen anywhere else but in Lightroom, not even with games. For a few days it didn't happen, but it came back a few mins ago: the 2 monitors lost signal, and a couple of seconds later it rebooted. Temperatures look fine after this. I checked the Event viewer and there's nothing weird apart from the Kernel-Power event (cutting off the power).
My setup is

*

*Ryzen 7 2700,

*32GB RAM,

*Radeon Vega 56 8GB,

*NZXT HALE82 650w power supply

*Not overclocked.

With my old setup (same but i5 3570k + OC and 16gb DDR3) Lightroom 5.7 worked fine.
I'd blame Lightroom, but I can't be sure, because it's hard to replicate. I tried disabling GPU acceleration and it didn't happen anymore (while I was testing at least), but I turned it back on and it didn't happen either.
Any help will be more than welcome. Thanks a lot in advance.


text:
Q: Multiple summations over indices in R I would have put some sample data but I do not know the first thing on how to interprete the image below in R.

I've looked at
Fastest way to do this double summation?
but could not extrapolate the answer there to my problem.

A: You can use aperm and exploit the vectorization. You must indicate which are the "common" dimensions (i.e. the dimensions contained in both X and C), permute X and multiply. Something like:
#declare which are the dimensions in X common to C
commonDims<-c(3,4)
#the other dimensions are the "uncommon" ones
uncommonDims<-setdiff(seq_along(dims),commonDims)
#then you can get the sum
sum(as.vector(aperm(X,c(commonDims,uncommonDims)))*as.vector(C))

We test the result above with the one obtained with for loops:
set.seed(456)
dims<-c(5,6,2,3,8)
commonDims<-c(3,4)
uncommonDims<-setdiff(seq_along(dims),commonDims)
C<-array(runif(prod(dims[commonDims])),dims[commonDims])
X<-array(runif(prod(dims)),dims)
sum(as.vector(aperm(X,c(commonDims,uncommonDims)))*as.vector(C))
#[1] 371.3749
#Calculation through loops
rsum<-0
for (i in 1:dims[1])
  for (j in 1:dims[2])
   for (k in 1:dims[3])
    for (r in 1:dims[4])
     for (t in 1:dims[5]) rsum<-rsum + X[i,j,k,r,t]*C[k,r]
rsum
#[1] 371.3749


text:
Q: Computed Property not working I'm writing the todo app and I can't get computed properties working. I want to implement computed properties in the todos/index controller so that the template can appropiately display the amount of todos undone remaining (based on the isCompleted attribute of the models).
This is the code:
todos/index.hbs
{{input type="text" id="new-todo" placeholder="What needs to be done?" value=newValue action="createTodo"}}

        {{#each model as |todo|}}
            {{todo-item todo=todo edit="editTodo" destroy="destroyTodo"}}
        {{/each}}

    <input type="checkbox" id="toggle-all">

         {{remaining}}  todos left

            All

            Active

            Completed

    <button id="clear-completed">
        Clear completed {{completed}}
    </button>

todos/index.hbs
import Ember from 'ember';

export default Ember.ArrayController.extend({
  remaining: function() {
    var todos = this.get('model');
    return todos.filterBy('isCompleted', false).get('length');
  }.property('todos.@each.isCompleted'),
  completed: function() {
    var todos = this.get('model');
    return todos.filterBy('isCompleted', true).get('length');
  }.property('todos.@each.isCompleted'),
  actions: {
    createTodo: function() {
      this.get('newValue');
      var newTodo = this.store.createRecord('todo', {title: this.get('newValue'), isCompleted: false});
      this.set('newValue', '');
    },
    editTodo: function(todo) {
      if (Ember.isEmpty(todo.get('title'))) {
        this.send('destroyTodo', todo);
      }
      else {
        todo.save();
      }
    },
    destroyTodo: function(todo) {
      debugger;
      todo.deleteRecord();
    }
  }
});

In case it helps: https://github.com/FranGoitia/todo
Thanks.

A: You should be watching for changes on model.@each.isCompleted, todos is not a property of your controller (it's just a local variable inside your computed property).


text:
Q: Returning multiple columns with subquery and 'where in' I'm having some trouble getting a select query to return the data I need. See the simplified example below.
Sku table
Sku         SkuId
==================
ABC-123     123
DEF-456     456
GHI-789     789
JKL-987     987

SkuCombo table
SkuId       SkuComboId  Qty
===========================
123         456         1
123         789         2
123         987         1

A "combo" item is a sku number given to an item that consists of multiple items. For example, for the sku ABC-123, you would need to look up the Sku from the Sku table to get the SkuId(123), then use the SkuId to get the SkuComboIds (456, 789, 987) from the SkuCombo. Then use those on the Sku table to get he corresponding Sku. The following query almost gets me there, but I don't know how to get the Qty column from the SkuCombo table?:
select *
from Skus
where SkuId in (Select SkuComboId
                from SkuCombo  sc
                join Skus s on s.SkuId = sc.SkuId
                where s.Sku = 'ABC-123')

Desired result
Sku         SkuId       Qty
============================
DEF-456     456         1
GHI-789     789         2
JKL-987     987         1

A: You need SELF JOIN :
select sk1.Sku , sk1.SkuId, skc.qty
from Sku sk inner join
     SkuCombo skc
     on skc.SkuId = sk.SkuId inner join
     Sku sk1
     on sk1.SkuId = skc.SkuComboId;

A: Not sure if I'm oversimplifying, or don't understand your question 100%, but wouldn't an Inner Join be the answer here:
Select *
from Skus s
join SkuCombo sc on s.SkuId = sc.SkuComboId

A: This can be done easily done using inner join as there are no null values in either of the table.
SELECT s.Sku, s.SkuId, sc.Qty
FROM SkuCombo sc
    INNER JOIN Skus s ON sc.SkuComboId = s.SkuId


text:
Q: virtual memory concepts I am confused about some topics regarding virtual memory. So, i am going to pointwise list them and ask questions. While answering i will prefer if you also list some source where i can  clear that doubt. I will be talking with reference to a linux elf executable file.

*

*I have heard that every process has the address space of 4gb in a 32 bit system. When i checked the objdump of one of my executable relocatable file i saw that it had limits from 00000000 to ffffffff. Also it contained the kernel space. This is the address space of the file. Is this the virtual memory we talk about? If yes then i had read that virtual memory mechanism allows processes of very big sizes to run and that process size is not limited by main memory size(we can bring required pages to main memory upon demand- demand paging). Then if virtual memory is just 4gb, doesn't it limit the maximum size of programs to 4gb? Also, i checked another file's objdump and it had the same address(i.e. 00000000 to ffffffff). So, what does this mean? Does that mean that our file is some kind of relocatable file to which starting addresses will again be added(although this seems absurd because it is already an executable relocatable object file).

*I had read that in a memory where segmentation has been implemented, the cpu produces virtual(logical) address. This address has three parts - the segment, the offset within the segment. Also, the segments being talked about here are code, data, stack etc.
In the process address space, these segments are located starting from specific locations. So, what are the contents of the virtual address of the cpu? Does the virtual address produced range from 00000000 to ffffffff? If yes then is the process of accessing the content at the virtual address, the folllowing:-
The segment part is looked up in the segment descriptor table to find the segment's
starting address in linear address space. Then the offset is indexed within the segment and
the resulting address is the linear address. Then, we look up the page table and map the
address to physical address. If the page is not currently in the main memory, it is
brought.

This again arises the fact that no process can be fully in the main memory at any time,   because then entire memory will be occupied by just one process(as the address space of process is itself 4gb).
Also, if all process have address space from 00000000 to ffffffff, and more than one process can exist in main memory at a time, then all processes should have their own segment descriptor table which returns the segment's address in the linear address space

*I read that the operating system is loaded into the main memory at boot up. Then what is the difference between that OS and the kernel code in the kernel space of a particular process? Also, do all processes have their own copy of kernel code in their kernel space?

A: This is a very open-ended question that has many confused uses of different terms.  I'll try to address as much of your question as I can, and provide some other useful information that may help.

*

*"I have heard that every process has the address space of 4gb in a 32 bit system."  Not precisely true.  Every process has a maximum addressable space of 3.2GB in a 32-bit system.  That doesn't mean that this memory is ever allocated, and it certainly isn't allocated as soon as a process launches.
"Is this the virtual memory we talk about?"  No.  Virtual memory is nothing directly to do with the addressable space of a process.  More on this later.

*This question doesn't really make sense, for reasons I will explain below.  It's worth noting, though, that multiple processes clealy do fit in memory at one time, because the processes don't automatically allocate their full potentially-available memory.  (If a text editor allocated 4GB of memory as soon as it was opened, it would not be a popular text editor!)

*I'm no expert, but I highly doubt that every program has its own copy of kernel code at runtime.  The security and performance issues alone make this a very unlikely solution.
So now, some definitions that may help you.

*

*Physical memory is (typically!) the RAM in your PC.  It is fast, physical memory that your CPU works directly with when running any program.  When you specify a physical memory address you are specifying an exact position in memory according to the memory hardware itself.

*Virtual memory is (typically!) stored on slower media like your Hard Disk Drive (in what's often called a paging file).  When your computer is running low on memory for running processes, it will copy some of the current physical memory contents to the page file, typically from an idle or background application.  This makes room in physical memory so that an active process can run.  If a program that is no longer in physical memory needs to process data, its data must be reloaded from the page file into physical memory - which may in turn require another program to be paged out of physical memory to make room.  The term "Virtual" versus "Physical" memory is used to highlight that this memory doesn't really exist, but it is nonetheless available to the computer.  Virtual memory use is very costly in terms of performance, but it can support much larger sizes: indeed, it is possible to have an arbitrarily large amount of virtual memory available, but the performance hit prevents this being a practical solution beyond certain limits.

*Logical memory addresses are those used by a single process and allow a process to address its own memory without having to care about where in physical memory the process has been loaded.  Your 00000000 to fffffff range is the logical range available to the process, and this is the address that will be used within the process to reference memory.  The kernel will translate this to a physical address that is used by the CPU when actually executing code, based on the physical offset (and segmentation) of the process' memory.  This physical location could be located anywhere in the available memory space and, if the aplication is paged out and in, the physical location may change during the lifetime of the application.  However, the application itself need only ever refer to its own logical address space.  The term "logical" versus "physical" address is used to highlight that an address is not the real address, but is the address relative to the relevant subset of memory - that is, to the process' own memory space.

I'm no expert on this, but I hope this helps clarify some of your questions.


text:
Q: Permutation induced by a partition Let $\lambda$ be a partition of length $n$ and suppose its largest diagonal block, the Durfee square of $\lambda$, has size $r$. By this I mean that $\lambda = (\lambda_1,\ldots,\lambda_n)$ is a non-increasing sequence of numbers, which I depict by the following diagram
\begin{align*}
&\square \cdots \square \square \quad (\lambda_1 \text{ squares })\\
&\square  \cdots \square \quad (\lambda_2 \text{ squares }) \\
&\quad\vdots \\
&\square \quad(\lambda_n \text{ squares })
\end{align*}
and the largest $i\times i$ block one can fit to the topmost left is of size $r\times r$. The conjugate partition $\lambda'$ is given by reflecting the drawing above along the diagonal. If $\alpha_i$ and $\beta_i$ denote the
sequence of numbers of blocks to the right of the diagonal in the $i$th row, and below the diagonal in the $i$th column, we write $\lambda = (\alpha_1,\ldots,\alpha_r\mid \beta_1,\ldots,\beta_r)$.
For example, for the partition $(5,4,2,1,1)$ has diagram
$$
\begin{align}
&\blacksquare\square\square\square\square\\
&\square\blacksquare\square\square\\
&\square\square\\
&\square\\
&\square
\end{align}
$$
and its conjugate is $(5,3,2,2,1)$. Its diagonal has length $2$, and in Frobenius notation we have $\lambda = (4,2\mid 4,1)$.
How can one show that the numbers $\lambda_1',\lambda_2'-1,\ldots,\lambda_r'-r+1,r+1-\lambda_{r+1},\ldots,n-\lambda_n$ form a permutation of $1,\ldots,n$? If $\lambda = (\alpha\mid \beta)$ in Frobenius notation, this is equivalent to the identity
$$\sum_{i=1}^n t^i (1-t^{-\lambda_i}) = \sum_{j=1}^r (t^{\beta_j+1}-t^{-\alpha_j})$$
which is Example 4 in page 11 of MacDonald's Symmetric Functions and Hall Polynomials, which he states without proof, so presumably this is easy.
Continuing with the example, we compute that the sequence for $\lambda = (5,4,2,1,1)$ is
$$5,3-1,3-2,4-1,5-1=5,2,1,3,4$$
a permutation of $1,2,3,4,5$.
In $(1.7)$ MacDonald proves that if we take $m\geqslant \lambda_1$ and $n\geqslant\lambda_1'$ then the numbers
$$\lambda_i+n-i,1\leqslant i\leqslant n,\quad n-1+j-\lambda_j',1\leqslant j\leqslant m$$
are a permutation of $0,\ldots,m+n-1$ by labelling the vertical and horizontal edge-lines on the diagram of $\lambda$ fitted inside the diagram of $(m^n)$, but I haven't been able to come up with a proof similar to this.

A: The concept here, although I'm not sure how far I can formalise it, is to extend the diagonal as far as the bottom of the Ferrers diagram. Then consider only the lower triangle. So your example
$$\begin{align}
&\blacksquare\square\square\square\square\\
&\square\blacksquare\square\square\\
&\square\square\\
&\square\\
&\square
\end{align}$$
becomes
$$\begin{align}
&\blacksquare\\
&\blacksquare\blacksquare\\
&\blacksquare\blacksquare\square\\
&\blacksquare\square\square\square\\
&\blacksquare\square\square\square\square
\end{align}$$
where $\blacksquare$s were in the original Ferrers diagram and $\square$s were not.
Now the elements $\lambda_1',\lambda_2'-1,\ldots,\lambda_r'-(r-1)$ correspond to vertical lines of $\blacksquare$ and the elements $r+1-\lambda_{r+1},\ldots,n-\lambda_n$ correspond to horizontal lines of $\square$. We can extract the permutation by considering the bottom-left space: if it is in the Ferrers diagram then we remove the left edge, which is a vertical line of $\blacksquare$; otherwise we remove the bottom edge, which is a horizontal line of $\square$. We then repeat on the resulting triangle, whose edge size has been reduced by one, until we have nothing left.

A: We will prove that $\lambda_j'-j+1 \neq k-\lambda_k$ (*) for every $j,k$, by induction on $n+\lambda_1$ (the sum of lengths of $\lambda, \lambda'$). As we mentioned in comments, this proves the lemma. Note that (*) rewrites as $(j-\lambda_j') +(k-\lambda_k) \neq 1$.
$n+\lambda_1 = 1$: $\lambda= \lambda'=(1)$. In this case $(1-1)+(1-1) \neq 0$.
Let's see the inductive step. Consider a partition $\lambda$. Let's say that an index is little (L) if it is $\le r$, big (B) otherwise. We have to prove four cases for the indexes $j,k$: (LL), (LB), (BL), (BB).
Let's prove (LB). Focus on the first $r$ columns. If we take out the famous top-left $r\times r$ square, we are left with a $n-r < n$ partition $\mu$ such that:

*

*$\lambda_{r+k}= \mu_k$ for $1 \le k \le n-r$;

*$\lambda'_j = r+\mu'_j$ for $1 \le j \le r$.

We know that $\mu$ satisfies not-equalities (*) by inductive hypotheses. Thus we have, for $r+1 \le r+k $, $1 \le j \le r$ :
$$ (j-\lambda_j')+ (k+r-\lambda_{k+r}) = (j-\mu_j'-r)+ (k+r-\lambda_{k+r}) = (j-\mu_j')+ (k-\mu_k) \neq 1 $$
Now we show (BL) by duality. Apply the previous reasoning to $\lambda'$. This yields
$$(j-\lambda_j') +(k-\lambda_k) \neq 1$$
for $1 \le k \le r, r+1 \le j $.
Let's prove (LL). Here $\lambda_k \ge r \ge k, \lambda'_j \ge r \ge j$, thus $ (j-\lambda_j')+(k-\lambda_k) \le 0 < 1$. Similarly, for (BB) we have $r+1 \le j,k$ and $\lambda_k, \lambda'_j \le r$. Thus $(j-\lambda_j')+(k-\lambda_k) \ge 2 > 1$.
Yuppi!


text:
Q: open corel draw files on debian So I have .cdr files on my PC and I want to open them on my Debian 7 box. What software do I need to be able to open it?`
I have:

*

*512 MB RAM

*3 GHz processor

*256 MB graphics

*with Debian 7

A: Gimp
I would see if you can open the .cdr files with Gimp. According to this page Gimp supports editing these files. Gimp should be available in the Debian repos, look for the name gimp.
I downloaded this sample image, cup.cdr (uncompressed 18K), from this Corel website. However I wasn't able to open it, there might be a plugin for Gimp.
Inkscape
The other method you could try (which worked for me) is to convert the .cdr image using the command line tool uniconvertor, and then open it up in Inkscape.
$ uniconvertor cup.cdr cup.svg

Once you've created the .svg file you simply open it in Inkscape.

If you don't want to try the above, you can take a look at the Inkscape FAQ, there is a guide on how to import .cdr files as well. The FAQ section is titled: Can I open/import *.cdr (Corel Draw Vector drawing file) files in Inkscape?.
Your mileage may vary?
I found this thread regarding the conversion process.
excerpt

On Tue, Jan 17, 2012 at 3:20 AM, Sveinn í Felli wrote:

Inkscape can import some versions of .CDR files (ver. 7-X4), from there one
    can export/save as .SVG. Don't know if there are bugs in that process (e.g.
    multipage documents, text/font problems, etc.)

Inkscape uses the very same converter as Scribus. It's called
  UniConvertor and only supports paths with flat fills and strokes (and
  maybe bitmaps, but I'm not entirely sure). There has been no progress
  re CDR support in UC in last few years (the primary developer is busy
  rewriting things yet again), and unfortunately I don't see it changing
  any time soon.
However there has been quite a bit of progress on reverse-engineering
  CDR recently on the re-lab side recently, and hopefully things will
  change now that there is libcdr by one of LibreOffice developers.

source: http://lists.scribus.info/pipermail/scribus/2012-January/045476.html

A: I was able to open a corel draw .cdr file perfectly using LibreOffice Draw, no file conversion needed. I had no such luck with converting to .svg and opening in Inkscape.


text:
Q: issue with root access etc I cannot do anything in ubuntu without being root all of a sudden. When I run emacs it says it cannot access files (and will run in sudo and works fine). firefox throws security issues until im root etc. and have no idea how to fix this.
I dropped down into su and purged sudo and reinstalled thinking this would fix it (bc at one point i edited my sudoers file with emacs vs visudo) but to no avail. any ideas? this is a very annoying experience
edit: for more information. prior to this I was trying to run Virtualbox as sudo (the gui version) and was having issues with it saying it could not access a given machine. So i wanted to ensure ALL my commands were ran as root so i added myself into sudoers file (username (ALL) = (All) etc. syntax) and everything was ok for some time. then these issues came about with firefox and emacs etc. so I am guessing somehow I have unknowingly removed myself from groups that did have access to these files in the past
edit no.2: for the specific error when emacs start it says "cannot open load file :/home/path.../.emacs.d/elpa/asynch-20151104.2113/async-pkg ... now this ONLY happens when I do not run as sudo from terminal. could it be I messed with the pkg permission? The firefox error was similar to this  (Error code: sec_error_bad_signature) however I cannot replicate the issue after deleting my ~/.modzilla folder. any ideas?

A: It sounds like you have root-owned files in your home directory.
This may have been caused by running applications with sudo in the past, and those applications saving files to your home directory.
To find a list of root-owned files in your home directory, try
find /home/ -uid 0

You can then chown them back to your user as appropriate.
chown myuser:myuser -R [files]

Where files is the particular files or subdirectory.  It's usually not a good idea to run a command like this across your whole home directory, on the off chance that some file ownerships are deliberate or necessary for something.
As to what caused the problem, certain applications will store files in your home directory during their normal operation, such as configuration or cache files.  This is very common with graphical applications, but some non-graphical applications may still do this.  Now, if you use sudo, and an application does this, it will create root-owned files in your home directory.  Then, future attempts to run this application without root may fail, because now there are files that can only be opened by root.
The solution is to change the owner of those files back to your user, or to delete them if you don't think they are vital.
To avoid this problem in future, when using sudo, you could use
sudo -H [command]

If it's a graphical application you could alternatively use
gksudo [command]

This tells the application to use the root user's home directory instead of your own home directory.


text:
Q: How to get cells value from previous visible row in excel formulas Is it possible to write a formulas in Excel,to calculate value based on the previous visible row?
By applying a Filter on the columns, the previous visible row changes but the usual formals does not consider visibility of the previous row, so the result does not change by applying filters. For example:
Let's original values of the spreadsheet cells be:
   A | B | C | D
1: 5   3   1
2: 9   1   1
3: 2   3   0
4: 7   8   1   =A3-B4 equals 2-8=-6

Now assume that we make a filter on C column to hide the third row so we have
   A | B | C | D
1: 5   3   1
2: 9   1   1
4: 7   8   1   =A3-B4 is still equals -6 but I want to get: 9-8=1

Is it possible to get such a formulas? Thank you very much.

A: Try this formula
=LOOKUP(2,1/SUBTOTAL(3,OFFSET(A$1,ROW(A$1:A3)-ROW(A$1),0)),A$1:A3)-B4
The SUBTOTAL/OFFSET part returns a 1 or zero for each value in column A depending on whether it's visible or not, LOOKUP finds the last 1 (equivalent to the last visible value) and gives that value.


text:
Q: Подстановка в условие if всех индексов Как в питоне сделать так, чтобы не проверять каждый индекс отдельно, а проверить все индексы сразу?
Например, есть список
a = input().split()
num_list = list(map(int, a))

Для того, чтобы проверить первый элемент, надо писать
if num_list[0] == 100:
    print(2)

А как сделать так, чтобы проверить все элементы? Написать if num_list[0,1,2,3,4,5] == 100 не получается

A: можно использовать filter
a = input().split()
num_list = list(map(int, a))

for x in filter(lambda n:n==100, num_list):
    ...

A: Вот один из вариантов:
a = input().split()
num_list = list(map(int, a))

count = len([x for x in num_list if x > 100])

for i in range(count):
    print(1)

# input: 101 200 1 2 3
# console: 1 1


text:
Q: Cassandra batch isolation guarantee I have a question regarding Cassandra batch isolation:
Our cluster consist of a single datacenter, replication factor of 3, reading and writing in LOCAL_QUORUM.
We must provide a news feed resembling an 'after' trigger, to notify clients about CRUD events of data in the DB.
We thought of performing the actual operation, and inserting an event on another table (also in another partition), within a batch. Asynchronously, some process would read events from event table and send them through an MQ.
Because we're writing to different partitions, and operation order is not necessarily maintained in a batch operation; is there a chance our event is written, and our process read it before our actual data is persisted?
Could the same happen in case our batch at last fails?
Regards,
Alejandro

A: From ACID properties, Cassandra can provide ACD. Therefore, don't expect Isolation in its classical sense.
Batching records will provide you with Atomicity. So it does guarantee that all or none of the records within a batch are written. However, because it doesn't guarantee Isolation, you can end up having some of the records persisted and others not (e.g. wrote to your queue table, but not master table).
Cassandra docs explain how it works:

To achieve atomicity, Cassandra first writes the serialized batch to the batchlog system table that consumes the serialized batch as blob data. When the rows in the batch have been successfully written and persisted (or hinted) the batchlog data is removed. There is a performance penalty for atomicity.

Finally, using Cassandra table as MQ is considered anti-pattern.


text:
Q: How to open a custom app from clicking 'view event' of calender reminder I have set reminder event in a app using Eventkit framework. I used following link for creating reminder in iCal. And also set alarm for the event. Now when alarm is displayed in alert view, while clicking 'View Event' button , nothing happens. How to open the app to show the notes saved when alert view button clicked? Thanks in advance.

A: Create a function that does that. And in action: just put the name of the function. That way, the action will be fired as soon as the alert button is tapped.


text:
Q: How to join three tables together in MySQL? I have a table location that stores countries, provinces and cities.
I want when search a city by its id; I can see its province and country too! I have tried too much but I really don't know what exact query I need to write.
My table name is location and these are my fields with example data:
id             enName         localName   type     in_location
1              Iran              ایران    country          0
2              Fars             فارس      province         1
3              shiraz         شیراز       city             2
4              marvdasht        مرو دشت    city            2

I want when I search id = 3 get this results:

country / province / city
Iran / Fars / Shiraz

How I can write this query? I know I must join the table for 3 times but don't know how exactly do that.
The code I have tried :
SELECT
    in_location ,
    enName
FROM
    location
WHERE
    id = 12321 as a
INNER JOIN
    SELECT
        *
    FROM
        `fzxit_location` as b
    on a.in_location = b.id

A: WHERE statment should always come at the end. I think this is what your looking for. You'll be fixed for relationships with 3 children or less though.
SELECT a.enName, b.enName, c.enName FROM location as a
LEFT JOIN location as b ON a.in_location = b.id
LEFT JOIN location as c ON b.in_location = c.id
WHERE a.id = 3

A: Although you have not specified other Tables name, you can try this..
select a.countryName,
       b.proviceName,
       c.cityName
from ((country a
         left join province b on a.countryId = b.countryId)
         left join city c on a.countryId = c.countryId)
where id = 3;

A: this query may help you!
select from p.province_name,
            ct.country_name,
            c.city_name
from city as c
   INNER JOIN provinces as p ON c.province_id=p.province_id
   INNER JOIN countries as ct ON c.country_id = ct.country_id
where c.city_id = "requested value";


text:
Q: Verifying that a Regular Expression Matches I have a regex that, according to what I can tell and to what RegexPal says, does not match the full string I am testing (only its rightmost part). However, matcher.matches() returns true!
So, what is the most reliable way to determine whether a java.util.regex Matcher actually fully matches a string?
Also, suppose that one wants to use matcher.find() as follows:
if (a match was found)
{
    while (matcher.find())
    {
        // Do whatever
    }
]

Is there any way of implementing the "a match was found" condition check?

A: Don't use find, use matches.

A: Well, I've never had matches() not work, but you can use find(), then use
 matcher.start()==0&&matcher.end()==string.length()

I don't think you need the if, because the while(matcher.find()) should check , but if you do...
if(matcher.find()){
    do{
        //whatever
    } while(matcher.find());
}

A: matches() returning true would mean there some match. Whether it's the "full" string or not, simply depends on what your regex is.
E.g.
"a"

would match all of the following
"a"
"abb"
"bab"
"bba"

if you're looking to match full string, your regex must begin with ^ and end with $
E.g.
"^a$"

would match "a", but none of the following
"abb"
"bab"
"bba"


text:
Q: How Set environment variables using Symfony CLI on windows 10 I'm working to build Single Page Application project (back-end in symfony as API and Preact in the front AS API consumer), and i have to set ENV_API_ENDPOINT on windows cmd prompt using this cmd :
sudo API_ENDPOINT=`symfony var:export SYMFONY_DEFAULT_ROUTE_URL --dir=..` yarn encore dev

But it doesn't work :  'API_ENDPOINT' is not recognized as an internal or external command
I want to set the API_ENDPOINT environment variable. How can I achieve it?

A: maybe with "set"?
set VARIABLE_TO_DEFINE=
set API_ENDPOINT=`symfony var:export SYMFONY_DEFAULT_ROUTE_URL --dir=..` yarn encore dev

A: Maybe a little late but i had the same problem and i ended up running the command in git bash and that solved it for me!


text:
Q: How can I perform a cross-domain GET, without the browser loading referenced images? I'm using $.get() in an environment that allows cross-domain HTTP requests, namely, a chrome extension. I'm using it to grab a page, and scrape off information to display to the user. This works.
The only problem is that the browser attempts to load every single image referenced in the scraped page, which both dramatically increases the data transfer, and fills up the inspector with errors when relative URLs are found.
Here's my code:
$.get('http://somewebsite.com/page-with-lots-of-images.htm', function(data) {
    var thingsICareAbout = $(data).find('#some-id, #some-other-id');
    foo(thingsICareAbout);
});

How can I get #some-id and #some-other-id wihout loading all the images in the document?

EDIT: The images are only loaded once the $(data) call is made. Somehow, calling that on the html string triggers the images to load. Any alternative?

A: Why this is happening is explained here:

If the HTML is more complex than a single tag without attributes, the actual creation of the elements is handled by the browser's innerHTML mechanism. In most cases, jQuery creates a new  element and sets the innerHTML property of the element to the HTML snippet that was passed in.

So when you do $(data) it inserts all that html on your page.
How to avoid it. If something you are searching for doesn't require complex jquery selectors, maybe you can parse html yourself (for example with... regular expressions *gulp*).

A: Unless you're inserting this HTML into the DOM, it's just a string and I doubt the browser would start fetching images.
Before inserting it into the DOM you could do a search-replace for src="..." and replace it with something line xxx="...".


text:
Q: Ubuntu 16.04 Hidpi support? I just bought the new skylake Dell XPS 13 developer edition which came with 14.04, it had a bunch of issues slowing down the system, but the resolution was fine for my 3200x1800 screen.
I decided to fresh install 16.04, which fixed all the issues, however the resolution makes everything tiny. Is there support for this? Or some drivers I need to install? I changed the scale, but that isn't a great fix for much really.
Suggestions??


text:
Q: Как создать выпадающий список в django видел такой вариант
from django.utils.translation import gettext_lazy as _

class Student(models.Model):

    class YearInSchool(models.TextChoices):
        FRESHMAN = 'FR', _('Freshman')
        SOPHOMORE = 'SO', _('Sophomore')
        JUNIOR = 'JR', _('Junior')
        SENIOR = 'SR', _('Senior')
        GRADUATE = 'GR', _('Graduate')

    year_in_school = models.CharField(
        max_length=2,
        choices=YearInSchool.choices,
        default=YearInSchool.FRESHMAN,
    )

    def is_upperclass(self):
        return self.year_in_school in {
            self.YearInSchool.JUNIOR,
            self.YearInSchool.SENIOR,
        }

###########
# human readable text can then be called by...
Student.YearInSchool.Junior.label

# or from an instance by <instance>.get_<innerclass name>_display() like...
student_inst.get_yearinschool_display()

но он мне не очень понятен и хотелось бы, что-то по проще типо PySimpleGUI.Combo или что-то в этом духе


text:
Q: Cannot resolve method 'forEach()' in Android Studio I have just added Java 8 support to my app with
jackOptions {
    enabled true
}

and
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

I have this code:
for (Company company : companies) {
    save(company);
}

and Android Studio tells me that it

Can be replaced with foreach call

After replace it, it looks like this:
companies.forEach((Company company) -> {
    save(company);
});

But now it's complaning:

Cannot resolve method 'forEach()'

I can compile and run my app properly. It's all about the editor.
Any idea? I'm using Android Studio 2.3.3


text:
Q: Nav bar on 1 line but one element on 2 lines I would like to put an element of my nav bar on two lines.
But when I just add a
 inside, it breaks everything.
Here is what I want :

Here is what I have :

Here is my html code:
div class="nav-top-home-page">

BLOG

CONTACT

ME CONNECTER

M'INSCRIRE

Vous êtes
 GESTIONNAIRE ?

Here is my css code :
.nav-top-home-page{
  height:600px;
  position: relative;
  z-index: 5;
  background-color: #6f8ab1;
  text-align: center;
}

.nav-top-home-page::before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url(assets/img/home/slide1.png) white center top no-repeat;
  background-size: cover;
}

.nav-top-home-page nav div{
  padding-top: 10px;
  margin-left: 20px;
  margin-right: 20px;
}

.nav-top-home-page nav .logo{
  float:left;
}

.nav-top-home-page nav ul{
  padding: 0px;
  margin: 0px;
  float: right;
}

.nav-top-home-page nav li{
  display: inline;
}

.nav-top-home-page nav li a{
  color: white;
  font-size: 1em;
  line-height: 70px;
  padding: 5px 15px;
  cursor: pointer;
  font-family: Raleway, arial;
}

.nav-top-home-page nav li {
  cursor: pointer;
}

#nav-gestionnaire{
  display: inline;
}

I tried changing the width, or adding whitespace: nowrap and many other things, but nothing worked.
Can someone help me pls ? :/

A: Remove line-height property and add display:inline-block on anchor tags
.nav-top-home-page nav li a{
  font-size: 1em;
  padding: 5px 15px;
  cursor: pointer;
  font-family: Raleway, arial;
  display:inline-block;
}

A: Try with this,  Use display:table-cell
Here is code

A: Wrap them inside divs as such

Vous êtes

GESTIONNAIRE

A: Try using max-width property and display:inline-block;  and remove line-height on anchor tag
CSS
.nav-top-home-page nav li {
    cursor: pointer;
    display: inline-block;
}

.nav-top-home-page nav li a {
    color: white;
    font-size: 1em;
    padding: 5px 15px;
    cursor: pointer;
    font-family: Raleway, arial;
    color: #212121;
    max-width: 180px;
    display: inline-block;
}


text:
Q: How to write R function, to scrape several data series (same indicator, different countries) from Quandl database? I want to download data series for the same indicator for different countries, from an online database called Quandl. I can use the same URL for each request, but I only need to change the country code.
The code below does not work, could someone help me with the right R code?
This is my first question on stackoverflow, apologies if I am not up to par yet with all stackoverflow rules. I have tried searching for an answer using google etc. No succes so far...
install.packages("Quandl")
library(Quandl)

x.df <- data.frame(x)

countries <- c("BE", "ESP")

for(i in countries){
    temp.df <- Quandl("AMECO/", i, "_1_0_319_0_UBLGAPS", start_date = "1995-12-30", collapse = "annual")
    x.df <- merge(x.df, temp.df, all=TRUE)
    }

I get this error message:

Error in match.arg(transform) :
    'arg' should be one of "", "diff", "rdiff", "normalize", "cumul", "rdiff_from"

A: To explain the reason for the particular error that is being thrown. This call:
 Quandl("AMECO/", i, "_1_0_319_0_UBLGAPS", start_date = "1995-12-30", collapse = "annual")

.... has a bunch of unnamed arguments and the third argument, "_1_0_319_0_UBLGAPS" is getting positionally matched to the transform parameter in the Quandl function which only accepts the values listed in the error message. This running example modified from the Quandl/R help page shows that Eric Lecoutre's advice was on-point:
> data <- Quandl(code=paste0("WIKI/", "FB.", 11),
                 start_date="2014-01-01",
                 end_date="2014-12-31",
                 collapse="monthly",
                 transform="diff")
> str(data)
'data.frame':   11 obs. of  2 variables:
 $ Date      : Date, format: "2014-12-31" ...
 $ Adj. Close: num  0.32 2.71 -4.05 4.22 2.17 ...
 - attr(*, "freq")= chr "daily"

Moral of this tale: when faced with a match.arg error, go back and name all your function arguments.


text:
Q: Multiple buttons in for loop doesn't work because of the same id So i want to build a website that has some cointainers for each object in my database and the same 2 buttons on each, "reguli" and "cumpara", everything works fine until i press the buttons. They work only for the first cointainer. My guess is that having the same id for each button of all containers, they work only as one. How could i change the id's of the buttons for each object in the database?

        •EVENIMENTE•

          {% for obj in events %}

{{obj.Nume}}

"{{obj.Descriere}}"

Price {{obj.Pret}}

                        <button id="btnRM" onclick="rmtxt()">REGULI</button>

Biletele se cumpara cu cardul
                                    nu se poate da refund
                                    distractie faina!

                                <button id="btnRL">READ LESS</button>

                        <button id="btncumpara" onclick="rmtxt()">CUMPARA</button>

                {% endfor %}

A: You must have different IDs, so you can use obj.id(id="btnRM-{{obj.id}}" ) or forloop.counter (id="btnRM-{{forloop.counter}}") to set different id for each container buttons:
{% for obj in events %}

{{obj.Nume}}

"{{obj.Descriere}}"

Price {{obj.Pret}}

          <button id="btnRM-{{obj.id}}" onclick="rmtxt()">REGULI</button>

Biletele se cumpara cu cardul
                    nu se poate da refund
                    distractie faina!

                <button id="btnRL">READ LESS</button>

            <button id="btncumpara-{{obj.id}}" onclick="rmtxt()">CUMPARA</button>

{% endfor %}


text:
Q: Toggle icons in a selected row Working stacklitz - https://stackblitz.com/edit/github-rlkrzv?file=src/app/play-list-page/play-list-page.component.html
Im trying to toggle between play and pause icons of a selected row, but when a song starts playing,
the whole table gets a "pause" icon (examples below).
Highlighting a specific row works fine, toggle between play and pause functions and icons also,
its just toggling the icons in the selected row..
Paused Song

Playing Song

Component.html

                         {{song.name}}
                        {{song.artists_names}}
                        {{song.album_name}}
                        {{song.release_date | date: 'yyyy-MM-dd'}}

Component.ts

 isPlaying:boolean=false

  setClickedRow(index: any) {
    this.selectedRow = index;
 }

togglePlaystateSong(id: number,index:number) {

    // let image = <HTMLInputElement>document.getElementById("imgClickAndChange");
    let image2 = <HTMLInputElement>(
      document.getElementById("imgClickAndChange2"));

    if (!this.selectedSong || this.selectedSong.track_id !== id) {
      const token = this.playListsAPI.generateToken();
      const songUrl = `http://api.sprintt.co/spotify/play/${id}?access=${token}`;
      this.player.src = songUrl;
      this.player.load();
      this.player.play();
      console.log("row's index:", index);
this.isPlaying=true;
      // (<HTMLInputElement>document.getElementById("bars")).value="0";
      // this.player.currentTime=0;

      // image.src = "../assets/pause_line_icon.png";
      image2.src = "../assets/controller_icons/bar_pause.png";
    } else {
      if (this.player.paused) {
        this.isPlaying=true;
        this.player.play();
        // image.src = "../assets/pause_line_icon.png";
        image2.src = "../assets/controller_icons/bar_pause.png";

      } else {
        this.player.pause();
        this.isPlaying=false;
        // image.src = "../assets/play_line_icon.png";
        image2.src = "../assets/controller_icons/bar_play.png";
      }
    }
  }

Component.css

.selected {
    background: rgba(29, 185, 84, 0.2) !important;
    /* color: white; */
}
.playBtn {
  visibility: hidden;
  /* content: url("/assets/play_line_icon.png"); */
}
.tableWrapper table tr:hover .playBtn {
  visibility: visible;
  padding-top: 3px;
  cursor: pointer;
}

.selected .pauseBtn {
    content: url("/assets/pause_line_icon.png");
    visibility: visible;
    width: 19.98px;
    height: 20px;
    padding-top: 3px;
}

.selected .playBtn {
    content: url("/assets/play_line_icon.png");
    visibility: visible;
    width: 19.98px;
    height: 20px;
    padding-top: 3px;
}

Much appreciated!

A: You are showing the pause picture for every song, you need to make sure you are only showing it for the selected item, make the following change in your template:

the change is adding *ngIf="selectedRow === i" on the img
see working stackblitz