text:
Q: Can't get the values from multiple select with $_GET request I'd like some help please.
I'm sending with a GET request from a multiple select field the selected values to my proccess page (archive.php)
<form id="form1" class="four columns" action="archive.php" method="get" name="form1">
<select id="select2" multiple="multiple" name="location[]">
<option value="103001000">value1</option>
<option value="103002000">value2</option>
<option value="103003000">value3</option>
<option value="103004000">value4</option>
</select>

I get the selected locations on my url like this
location[]=103002000&location[]=103003000

and in the archive.php I'm trying to fetch data from the database like this
if (( isset($_GET['location']) && !empty($_GET['location']) )) {
    die(var_dump($_GET['location'])); // the var_dump doesn't return an array at all
    $loc = implode(', ', $_GET['location']);

    $sql="SELECT  * FROM locations WHERE AreaID IN (". $loc.")";
}

but I'm getting the following error: Error: Unknown column 'Array' in 'where clause'.
How can I fix this?

A: try with as below it might be simple
 if (( isset($_GET['location']) && !empty($_GET['location']) )) {
        die(var_dump($_GET['location'])); // the var_dump doesn't return an array at all
        //$loc = implode(', ', $_GET['location']);
        $_GET['location'] = array('first'=>'loc1','second'=>'loc2','third'=>'loc3');
        $loc = implode('","', $_GET['location']);
        $loc ='"'.$loc.'"';

        $sql='SELECT  * FROM locations WHERE AreaID IN ('.$loc.')';
        echo $sql;
    }

result query

SELECT * FROM locations WHERE AreaID IN ("loc1","loc2","loc3")


text:
Q: use scatteredInterpolant variable in embedded matlab function in simulink Is there any way to do i.e.
Surface = scatteredInterpolant(measurement_xz(:,1)*1E-3,measurement_xz(:,2)*1E-3,measurement_xz(:,3));

where measurement_xz is some data in a startup script for my simulink model and then use Surface in an embedded matlab function in the simulink model, i.e.
///embedded matlab function
function V = fcn(x,z)
V = Surface(x,z);

?
When I i.e. try to use Surface as a parameter for V like
function V = fcn(x,z,Surface)
V = Surface(x,z);

with Surface set as parameter in the Ports and data manager I get the error
Expression 'Surface' for initial value of data 'Surface' must
evaluate to a numeric or logical.

A: What you are trying to do is not supported by the Matlab Function block, MATLAB is unable to generate code for it. The problems are:

*

*You are trying to access the variable Surface which is not visible in the scope

*scatteredInterpolant is not supported at all for code generation (at least in my MATLAB version, might be improved in recent Versions).

To fix this on a code level, you could switch to interpreted MATLAB code. This can be done either switching to a Interpreded MATLAB block or using coder.extrinsic. It is a quick and simple fix, but I recommend not to do this because it will probably result in a slow model. Instead I recommend to switch to a lookup table, which is also capable of interpolating.

redpajama_set_name: RedPajamaStackExchange


text:
Q: On the alleged circularity of the definition of implication and double implication Note: I'll use the convention adopted by my professor: "$\rightarrow$" is the symbol for implication and "$\implies$" for deduction.
Our professor defined implication as

The connective such that $(p\rightarrow q)$ is false only if $p$ is true and $q$ is false.

and double implication as

The connective such that $(p\leftrightarrow q)$ is true if and only if $p,q$ have the same truth value.

My problem with such definitions is that both use what they are defining: only if and if and only if are just the english expressions respectively for "$\rightarrow$" and "$\leftrightarrow$". I remember an answer here on MSE where it was indeed stated that the first one is circular, but the author somewhat accepted it. Why should we? In particular, why aren't

Implication is the connective such that $$\begin{cases}
p   \\
p\rightarrow q
\end{cases} \implies q .$$

and

Double implication is the connective given by the conjuction of an implication and its inverse.

better?

A: Because you're misunderstanding the definition. (It's not your fault; it's due to the fact that the notation used by your professor is imprecise, but it is the conventional notation.)
He/she did not define the implication and equivalence symbols using themselves. Rather he defined how to interpret the truth-value of certain kinds of strings of symbols called well-formed formulae. A string like "$A \land B$" has no meaning whatsoever until it is interpreted. To interpret one has to break it down into its smallest pieces and interpret piece by piece. In propositional logic these smallest pieces are atoms, each of which is interpreted as either true or false. Then based on how the original formula is built up from atoms and logical symbols, it is recursively interpreted. The first definition you are asking about could have been stated much more clearly as:

Given well-formed formulae $p$ and $q$, the formula $p + ``\rightarrow\text{"} + q$ has truth-value $false$ if and only if $p$ has truth-value $true$ but $q$ has truth-value $false$.

Remember that formulae are just meaningless strings until interpreted! Also, "$+$" in the above denote string concatenation. Thus you can see that given such rules of interpretation of well-formed formulae, one can recursively evaluate its truth-value if one knows the truth-value of the smallest pieces.
So these definitions are not circular because we are simply defining how to interpret strings. (You can trivially write a computer program to do it too!) In short, the implication symbol is totally not the implication in the English expressions, although its interpretation as defined above is indeed intended to reflect the external concept of a conditional assertion (if $p$ is true, then $q$ is true) that is true exactly when it is not a false assertion (think of "false promise", which only occurs when $p$ is true but $q$ is false).
Now for your second question, the answer is that it is circular. I answered essentially the same question at https://math.stackexchange.com/a/1334753/21820 before. Your proposal does not at all solve the problem, because you cannot define "$\Rightarrow$" without the same circularity.

A: If you define implication as satisfying {p, (p $\rightarrow$ q)} ⟹ q, then what can get said about the truth-table for $\rightarrow$?
 →
 p \ q  0  1
 0
 1      0  1

But notice that we don't have to fill in the 0 row for this function.  Consequently, there exist four two-valued truth functions which satisfy your rule.  Consequently, if we did define implication as you proposed, it would not consist of a function in the context of two-valued logic.  Also, logical equivalence wouldn't qualify as distinguishable from implication.
Thus, there is no such thing as "the connective" for what you defined.


text:
Q: Orchard CMS - Difference between Layer & Content Type I'm adding a 'contact form' page to an Orchard site (that I'm making to learn Orchard).
First I added it as a layer. Then I found out you can add it as a Content Type.
I find this all very confusing.
What is the difference & relationship between layers, content types, modules & widgets. And why are there no pages?!
Why is TripelFirst a layer for example - not a widget?
Why can't I just make a 'contact' page and add a widget to it called 'Contact Form'?!
What's the difference between modules & widgets - they sound like the same thing.
What would be the best practice way to add a Contact Us page - as a layer or a Content Type?
Thanks.

A: What is the difference & relationship between layers, content types,
modules & widgets. And why are there no pages?!

Layers control which widgets appear in which zones (designated by the theme) on a particular page. They have rules, so for example, I could have a layer called NotHomePage and give it the rule not url("~/") and any widgets added to zones on that layer would appear everywhere but the home page.
Content types are just that--types of the content you create on the site. A Page is a content type you get out of the box with Orchard. It contains a part called Route so one of the first properties you have the option of creating is the slug e.g. mydomain.com/sweet-page.
Modules are basically MVC areas that create specific functionality for a website. A module may contain some custom parts, some script, some styling, etc. There are a couple contact form modules out there, but you'd probably learn more if you used the Custom Forms module that is already cooked in the default Orchard recipe (I think you have to enable it, but it's there.)
Widgets are like code snippets you add to zones (designated by the theme) on a layer where you can have as many widgets as you like. Maybe your home page has a "MainContent" zone where your customer would like to have their tagLine and a small form to sign up for a newsletter. You could add an HTML widget for the tagline (which contains basic information like a WYSIWYG editor for the HTML) and a Custom Form widget (which will handle creating s sign up request.)
Why is TripelFirst a layer for example - not a widget?

TripelFirst should not be a layer, it should be a zone in the TheThemeMachine theme i.e. an area on the page that may or may not contain widgets.
Why can't I just make a 'contact' page and add a widget
to it called 'Contact Form'?!

You can, but you would need to define a couple things first.

*

*Create a content type called ContactFormRequest (you might need to enable 'Content Types' module)

*Add fields (first name, last name, etc) like you would add properties to a class definition

*Create a page called Contact with the slug /contact

*Create a layer called ContactLayer with the rule url("/contact")

*Add a Custom Form widget to ContactLayer and be sure to select ContactFormRequest as the content type

*party

This should give you the basic behavior you're looking for. You can, of course, customize this further.
What would be the best practice way to add a Contact Us page -
as a layer or a Content Type?

Personally, I prefer the flexibility of using my own content type e.g. ContactFormRequest. If, in the future, my customer wants to add height, weight and age as properties to the contact form, I have only to add these fields to the content type and Orchard handles the rest.


text:
Q: Interpolating 3D noisy data I have some noisy 3D data that looks like this:
SeedRandom[0];
data = Join @@ Table[{x, y, Sin[x*y] + RandomReal[NormalDistribution[0, 0.2]]}, {x, 0, 2 Pi, 0.2}, {y, 0, 2 Pi, 0.2}];

I would like to find a smooth interpolation for the data, like the one in this answer (which only works for 2D data): https://mathematica.stackexchange.com/a/162145
How can I do this?

A: The following approach is somewhat simplistic and limited but it might be good enough.
1. We find Quantile Regression fit for each data subset corresponding to a unique x-axis value. We make a x-value dispatch function that gives a z-value for a pair of x-and-y values.
2. We find Quantile Regression fit for each data subset corresponding to a unique y-axis value. We make a y-value dispatch function that gives a z-value for a pair of x-and-y values.
3. We make the function QFunc that averages the values of the distpatch functions.
4. We apply QFunc over the same x-y-grid of the original data.
Import["https://raw.githubusercontent.com/antononcube/MathematicaForPrediction/master/QuantileRegression.m"]

nKnots = 9;

(* 1 *)
qXFuncs =
  Association[#[[1, 1]] ->
      QuantileRegression[#[[All, {2, 3}]], nKnots, {0.5}][[1]] & /@
    GatherBy[data, #[[1]] &]];

(* 2 *)
qYFuncs =
  Association[#[[1, 2]] ->
      QuantileRegression[#[[All, {1, 3}]], nKnots, {0.5}][[1]] & /@
    GatherBy[data, #[[2]] &]];

(* 3 *)
QFunc[x_, y_] := Mean[{qXFuncs[x][y], qYFuncs[y][x]}];

(* 4 *)
dataSmooth =
  Join @@ Table[{x, y, QFunc[x, y]}, {x, 0, 2 Pi, 0.2}, {y, 0, 2 Pi, 0.2}];

GraphicsGrid[{{
  ListPlot3D[data, PlotRange -> All, PlotLabel -> "Original data"],
  ListPlot3D[dataSmooth, PlotRange -> MinMax[data[[All, 3]]], PlotLabel -> "Smoothed data"]}}, ImageSize -> 800]


text:
Q: AsyncIterator exits "for await-of" loop abruptly I'm trying to build a buffer backed AsyncIterator to produce the values from the buffer when buffer is not empty & await on a Promise if buffer is empty.

class PushGenerator {
  constructor() {
    this.buffer = []
    this.pending = null
  }

  // push values to iterator. `null` will stop the iterator
  push(value) {
    if (this.pending) {
      this.pending(value)
      this.pending = null
      return
    }
    this.buffer.push(value)
  }

  async *[Symbol.asyncIterator]() {
    let event = null

    while(true) {
        if (this.buffer.length > 0) event = this.buffer.shift()
      else event = await new Promise(r => this.pending = r)

      if (event !== null) yield event
      else break
    }
  }
}

async function main() {
  const gen = new PushGenerator()
  setTimeout(() => gen.push(10), 10)

  for await (const item of gen) {
     console.log("---", item)
  }

  setTimeout(() => gen.push(null), 3000)
  console.log('Im not called!')
}

main().then(v => console.log('never called', v))
  .catch(e => console.log('never called', e))

For most parts it works fine, except that if I push the values after the await for-of loop, its completely ignored. Infact the async main itself terminates without resolving/rejecting the promise!. My expectation is that for await-of loop to wait for values until loop is broken or null is sent to the PushGenerator
Behaviour is same both in nodejs & also in chrome. Googling didnt help much & not able to find any similar question in SO as well.
What am I missing?


text:
Q: SQL Guide Plan not being used? I'm try to get force Parameterization on a simple adhoc SQL query.As explained in this article https://www.simple-talk.com/sql/performance/fixing-cache-bloat-problems-with-guide-plans-and-forced-parameterization/
But even trying to do this with the simplest query I cant get it to work
CREATE TABLE fruit
(
 id BIGINT PRIMARY KEY(id)
,title VARCHAR(150)
)
INSERT INTO fruit VALUES ( 1, 'Apple') , ( 2, 'Banana'), ( 3, 'Orange'), ( 4, 'Pear')

DECLARE @params nvarchar(max);
DECLARE @stmt nvarchar(max);
EXEC sp_get_query_template N'SELECT title FROM fruit WHERE id = 4',@stmt OUTPUT, @params OUTPUT;

--SELECT @params
EXEC sp_create_plan_guide
    N'fruitGuide',
    @stmt,
    N'TEMPLATE',
    NULL,
    @params,
    N'OPTION(PARAMETERIZATION FORCED)';
GO

SELECT title FROM fruit WHERE id = 1

Plan XML:
Shows a compile and doesn't use the plan guide, is there something i'm missing here? Where am i going wrong?
<?xml version="1.0" encoding="utf-16"?>
<ShowPlanXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="1.5" Build="13.0.1601.5" xmlns="http://schemas.microsoft.com/sqlserver/2004/07/showplan">
  <BatchSequence>
    <Batch>
      <Statements>
        <StmtSimple StatementCompId="1" StatementEstRows="1" StatementId="1" StatementOptmLevel="TRIVIAL" CardinalityEstimationModelVersion="130" StatementSubTreeCost="0.0032831" StatementText="select title from fruit where id = @0" StatementType="SELECT" QueryHash="0xC02C3539A6CB7253" QueryPlanHash="0x257948D9E7B502E7" RetrievedFromCache="true" SecurityPolicyApplied="false">
          <StatementSetOptions ANSI_NULLS="true" ANSI_PADDING="true" ANSI_WARNINGS="true" ARITHABORT="true" CONCAT_NULL_YIELDS_NULL="true" NUMERIC_ROUNDABORT="false" QUOTED_IDENTIFIER="true" />
          <QueryPlan DegreeOfParallelism="1" CachedPlanSize="16" CompileTime="1" CompileCPU="1" CompileMemory="104">
            <MemoryGrantInfo SerialRequiredMemory="0" SerialDesiredMemory="0" />
            <OptimizerHardwareDependentProperties EstimatedAvailableMemoryGrant="256000" EstimatedPagesCached="64000" EstimatedAvailableDegreeOfParallelism="2" />
            <RelOp AvgRowSize="86" EstimateCPU="0.0001581" EstimateIO="0.003125" EstimateRebinds="0" EstimateRewinds="0" EstimatedExecutionMode="Row" EstimateRows="1" LogicalOp="Clustered Index Seek" NodeId="0" Parallel="false" PhysicalOp="Clustered Index Seek" EstimatedTotalSubtreeCost="0.0032831" TableCardinality="4">
              <OutputList>
                <ColumnReference Database="[DV]" Schema="[dbo]" Table="[fruit]" Column="title" />
              </OutputList>
              <RunTimeInformation>
                <RunTimeCountersPerThread Thread="0" ActualRows="1" ActualRowsRead="1" Batches="0" ActualEndOfScans="1" ActualExecutions="1" ActualExecutionMode="Row" ActualElapsedms="0" ActualCPUms="0" ActualScans="0" ActualLogicalReads="2" ActualPhysicalReads="0" ActualReadAheads="0" ActualLobLogicalReads="0" ActualLobPhysicalReads="0" ActualLobReadAheads="0" />
              </RunTimeInformation>
              <IndexScan Ordered="true" ScanDirection="FORWARD" ForcedIndex="false" ForceSeek="false" ForceScan="false" NoExpandHint="false" Storage="RowStore">
                <DefinedValues>
                  <DefinedValue>
                    <ColumnReference Database="[DV]" Schema="[dbo]" Table="[fruit]" Column="title" />
                  </DefinedValue>
                </DefinedValues>
                <Object Database="[DV]" Schema="[dbo]" Table="[fruit]" Index="[PK__fruit__3213E83F1B7D3288]" IndexKind="Clustered" Storage="RowStore" />
                <SeekPredicates>
                  <SeekPredicateNew>
                    <SeekKeys>
                      <Prefix ScanType="EQ">
                        <RangeColumns>
                          <ColumnReference Database="[DV]" Schema="[dbo]" Table="[fruit]" Column="id" />
                        </RangeColumns>
                        <RangeExpressions>
                          <ScalarOperator ScalarString="CONVERT_IMPLICIT(bigint,[@0],0)">
                            <Convert DataType="bigint" Style="0" Implicit="true">
                              <ScalarOperator>
                                <Identifier>
                                  <ColumnReference Column="@0" />
                                </Identifier>
                              </ScalarOperator>
                            </Convert>
                          </ScalarOperator>
                        </RangeExpressions>
                      </Prefix>
                    </SeekKeys>
                  </SeekPredicateNew>
                </SeekPredicates>
              </IndexScan>
            </RelOp>
            <ParameterList>
              <ColumnReference Column="@0" ParameterCompiledValue="(1)" ParameterRuntimeValue="(1)" />
            </ParameterList>
          </QueryPlan>
        </StmtSimple>
      </Statements>
    </Batch>
  </BatchSequence>
</ShowPlanXML>

A: Your plan guide is being applied, and the query is being forced parameterized.
Unfortunately, this is not so easy to see in your particular situation, for a couple of reasons:

Reason 1: Post-execution plans do not show plan guide properties
A quick and reliable way to see that your query is using the plan guide is to request a pre-execution (estimated) plan.
So, without running the query, the execution plan shown in SSMS will have a root node with two extra properties (compared with the plan provided in the question):

These properties do not appear in post-execution plans, nor in prepared cached plans.
Side note
In the post-execution (actual) plan you provided, the only (undocumented) indication that parameterization was forced is that the first parameter marker is @0 in the Seek tooltip:

Without the plan guide, your test query still qualifies for simple parameterization, but the parameter marker in the tooltip is @1:

Reason 2: You have optimize for ad hoc workloads enabled
With this configuration option enabled, the first time you run the adhoc query, no plan is cached, just a plan stub.
You would need to run the query twice to see the plan stub populated.
There still won't be a full plan (just a root SELECT node) but this node will have the TemplatePlanGuideDB and TemplatePlanGuideName properties populated:

Notice also that the ParameterizedPlanHandle property points to the plan handle of the fully parameterized (prepared) query plan in cache. The prepared plan does not contain the extra plan guide properties, as mentioned previously.
Without the adhoc option, the adhoc compiled plan will show the important plan guide properties.

A: Where are you getting the plan from?  Can you try to retrieve the plan from cache and you should see the guide.
select st.*,st1.*,cp.* from sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) st
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st1
where cp.objtype='Adhoc'


text:
Q: How to get a Virtual Machine Network information via SNMP from ESXi I want to monitor the inbound/outbound traffic of a VM inside ESXi through SNMP. I activated SNMP protocol on ESXi and can get information with snmpwalk and snmpget. But I don't know which OID is the wright one to get the network info of my desired VM.
I want to get some information like the ones that the following commands return inside ESXi shell:
esxcli network vm list
esxcli network vm port list -w
esxcli network port stats get -p
Any help is appreciated.

A: *

*Make sure you've configured SNMP Agent properly: Configure SNMP for ESXi

*ESXi supports all standard MIBs like IF-MIB, HOST-RESOURCES-MIB, BRIDGE-MIB and others.

*Also it does support some vendor specific MIBs: VMWARE-RESOURCES-MIB, VMWARE-ENV-MIB and some others


text:
Q: Variation of Hooke's Law Confirmation If we have a spring with natural length $l$, modulus of elasticity $\lambda$ and it has a weight of $m_1g$ attached to it, then its extension, $x_1$, is
$$\frac{m_1gl}{\lambda}$$
If we add on another mass with weight $m_2g$ then we find the change in extension, $x_2$, is $$\frac{m_2gl}{\lambda}$$
after some manipulation.
Hooke's law states that the tension in a spring, $T$, is equal to the spring constant, $k$, multiplied by the extension of the spring, $x$:
$$T=kx=\frac{\lambda x}{l}~~(\text{as the spring constant is equal to $\frac{\lambda }{l}$})$$
Therefore, is it correct to state Hooke's law somewhat differently:
$$\Delta T=\frac{\lambda\Delta x}{l}$$
where $\Delta T$ is the change in tension in the spring.
Mathematically this seems sound; I'd just like to verify this is true.
EDIT:
There seems to be some confusion about the measurements and terms that I have used. To clarify:
The spring constant, $k$, is equal to $\lambda/l$; so my question is equivalently: is the following variation of Hooke's Law correct?
$$\Delta T=k\Delta x$$
where $\Delta T$ is the change in tension in the spring and $\Delta x$ is the change in extension.

A: There is a dimensional mistake, if you write $x_1=\frac{m_1gl}{\lambda}$ you are wrting dimensionally this: $$m=\frac{kg\cdot m\cdot m}{\frac{N}{m}\cdot s^2}$$ you are saying that $m=m^2$ but it's impossbile. Remember that Hooke's law is the following: $$\vec{F}=\lambda(\vec{x}-\vec{x}_0)$$ The force is directly proportional to the displacement.
So if you add a weight you find that $x_1=\frac{m_1g}{\lambda}$ if you add another mass $m_2$ you have the following equation: $$\vec{x}_2=\frac{(m_1+m_2)\vec{g}}{\lambda}$$


text:
Q: How to tweak/customize GTK theme? I installed Ubuntu with Unity desktop environment and then I installed GTK Theme, which is called Numix Dark. I really like the theme, but I would love to change some colors of the theme. I want to change the accent color from red to blue and change folders color from yellow to blue.
If someone could tell me how to do that would be really grateful. Do I have to only just change some text in a file in order to do that ?
After some Googling I found a thread that explains how to change the accent color from red to blue, but it didn't change all the colors from red to blue. And I still don't know how to make the folders blue.
After following  the steps on I changed the accent color from red to blue,like so:

But I couldn't change the controls that minimize, resize and close a window from red to blue. See this image to see what I'm talking about.

If would be really happy if you could tell me how to change window control colors from red to blue when hovered. Thank you.

A: Remember when you were installing the GTK+ themes how you were hit with a .tar file. If you extract that file, you will get a magical folder of files. If you read the comments in each of the file, and if you know a little bit of the language, then you can easily start tweaking the themes...
For your purpose of just changing colors, it shouldn't be that hard to change the color, but again, I don't know which theme package you are dealing with, so just burn through the code and learn!
If on the other hand, you were looking for a GUI tool which you could use, there is none.

A: There is not standard method for this and it is a lengthy process
You have to make changes in CSS files of theme which can be found it /usr/share/themes/<theme name>/.
Now here look for the colour you want to change, most probably it will be defined at the beginning of CSS file. You might wanna use a colour picker for this Agave is good.
After you found the colour to replace, run the following command
cd /usr/share/themes/<theme name>/
find . -type f | xargs sed -i 's/abc/xyz/g'

in above command replace abc with the colour name you dont want to see, and replce xyz with the colour you would like to see.
It would replace all occurrence of old colour in all files


text:
Q: Query in PHP wont pull data that is already in the system I'm trying to check if a given email exists in the database, but the query returned is null and I'm not sure why.
I've tried manually inputting the email address as recorded in the table but its still not working.
user.php :
function emailExists()
{

    $query = "SELECT id, firstname, lastname, access_level, password,
status from " . $this->table_name . " where email = ?";

    //prepare this query
    $stmt = $this->conn->prepare($query);

login.php :
//get database connection
$database = new Database();
$db = $database->getConnection();

//initialize objects
$user = new User($db);

//check if email and password are in the database
$user->email=$_POST['email'];

//check if email exists, also get user details using this emailExists() method
$email_exists = $user->emailExists();

Database class:
class Database{

    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "games_for_sale";
    private $username = "root";
    private $password = "";
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}

User class:
class User{
    //database connection
    private $conn;
    private $table_name = "users";

    //object properties
    public $id;
    public $firstname;
    public $lastname;
    public $email;
    public $contact_number;
    public $address;
    public $password;
    public $access_level;
    public $access_code;
    public $status;
    public $created;
    public $modified;

    //constructor
    public function _construct($db){
        $this->conn = $db;
    }

    //check if given email exist in the database
    function emailExists()
    {

        $query = "SELECT id, firstname, lastname, access_level, password, status from " . $this->table_name . " where email = ?";

        //prepare this query
        $stmt = $this->conn->prepare($query);

        //sanitize
        $this->email = htmlspecialchars(strip_tags($this->email));

        //bind given email value
        $stmt->bindParam(1, $this->email);

        //execute the query
        $stmt->execute();

        //get number of rows
        $num = $stmt->rowCount();

        //if email exists, assign values to object properties for easy access and use for php sessions
        if ($num > 0) {

            //get record details / values
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            //assign values to object properties
            $this->id = $row['id'];
            $this->firstname = $row['firstname'];
            $this->lastname = $row['lastname'];
            $this->access_level = $row['access_level'];
            $this->password = $row['password'];
            $this->status = $row['status'];

            //return true because email exists in the database
            return true;
        }

        //retturn false if email does not exist in the database
        return false;
    }

}

The error I get:

Fatal error: Uncaught Error: Call to a member function prepare() on
  null in user.php:34 Stack trace:
  #0 login.php(34): User->emailExists()
  #1 {main} thrown in user.php on line 34


text:
Q: asp.net Gridview Una duda, como puedo hacer, para que cuando le haga un zoom al navegador el gridview aun siga ocupando todo el ancho de la pantalla.
Actualmente hago zoom de 45% como en la imagen, y se ve hace mas chico el gridview y yo busco que aun siga ocupando todo el ancho de pantalla..
Este es el codigo tras el grid.
          <asp:GridView ID="grdPDFView" runat="server" Width="100%" AllowPaging="false" ColumnAutoWidth="false"
                AutoGenerateColumns="False"
                CssClass="table table-striped table-bordered table-hover table table-responsive"
                DataKeyNames="ID,Clave" OnDataBound="OnDataBound"
                ondatabinding="grdPDFView_DataBinding" Visible="False"
                onrowdeleting="grdPDFView_RowDeleting"
                onrowcommand="grdPDFView_RowCommand" onrowdatabound="grdPDFView_RowDataBound"
                onrowcancelingedit="grdPDFView_RowCancelingEdit"
                onrowediting="grdPDFView_RowEditing"
                onrowupdating="grdPDFView_RowUpdating">
            <Columns>
           <asp:TemplateField HeaderText="#"  HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Justify">
                        <ItemTemplate>
        <asp:LinkButton ID="LinkButton5" disabled="disabled" OnClientClick="return false;" runat="server" href='<%# string.Format("http://localhost:58701/RevisionMotoresEmis.aspx?Clave={0}",Eval("Clave")) %>' Text='<%# Eval("ID", "{0}") %>'></asp:LinkButton>

        <%-- <asp:LinkButton ID="LinkButton5" runat="server" OnClientClick="showProgress();" href='<%# string.Format("http://amrnmcvpwi02/ControlDocumentos/RevisionMotoresEmis.aspx?Clave={0}",Eval("Clave")) %>' Text='<%# Eval("ID", "{0}") %>'></asp:LinkButton>--%>
                       </ItemTemplate>
                       <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                       <ItemStyle HorizontalAlign="Justify"></ItemStyle>
                        </asp:TemplateField>
                       <asp:TemplateField HeaderText="Clave                        " HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Justify">
                         <ItemTemplate>

                             <asp:LinkButton ID="LinkButton3" runat="server" OnClientClick="openInNewTab();" OnClick="OpenDocument" Text='<%# Eval("Clave") %>'></asp:LinkButton>
                             <asp:LinkButton ID="LinkButtoLink10emis" runat="server" href='<%#Eval("Link")%>' Text='<%#Eval("Clave")%>' Target="_blank"></asp:LinkButton>
                            </ItemTemplate> <HeaderStyle HorizontalAlign="Left"></HeaderStyle>
                     <ItemStyle HorizontalAlign="Justify"></ItemStyle>
                    </asp:TemplateField>
                   <asp:BoundField DataField="DescripcionArchivo" HeaderStyle-HorizontalAlign="Center" ReadOnly="true" HeaderText="Título                                                   "  SortExpression="DescripcionArchivo"  />
                   <asp:BoundField DataField="Revision" ReadOnly="true" HeaderText="Revisión" SortExpression="Revision" HeaderStyle-HorizontalAlign="Center" />
                 <asp:BoundField DataField="FechaRevision" ReadOnly="true" HeaderText="Fecha revisión" HeaderStyle-HorizontalAlign="Center" SortExpression="FechaRevision" DataFormatString="{0:dd/MM/yyyy}" />
                 <asp:BoundField DataField="RevisadoPor" ReadOnly="true" HeaderText="Revisado por                         " SortExpression="RevisadoPor" />

                 <asp:BoundField DataField="AprobadoPor" ReadOnly="true" HeaderText="Aprobado por" HeaderStyle-HorizontalAlign="Center" SortExpression="AprobadoPor" />
                 <asp:BoundField DataField="Area1" ReadOnly="true" HeaderText="Área1                        " SortExpression="Area1" HeaderStyle-HorizontalAlign="Center" />
                 <asp:BoundField DataField="Area2" ReadOnly="true" HeaderText="Área2                                 " HeaderStyle-HorizontalAlign="Center" />
                 <asp:BoundField DataField="Area3" ReadOnly="true" HeaderText="Área3                    " SortExpression="Area3" HeaderStyle-HorizontalAlign="Center" />
                  <asp:BoundField DataField="Area4" ReadOnly="true" HeaderText="Área4                            " HeaderStyle-HorizontalAlign="Center"/>
                 <asp:BoundField DataField="TipodeInstruccion" ReadOnly="true" HeaderText="Tipo de instrucción" SortExpression="TipodeInstruccion" HeaderStyle-HorizontalAlign="Center" />
                 <asp:BoundField DataField="FrameMaquinaCell" ReadOnly="true" HeaderText="Frame máquina /cell"  SortExpression="FrameMaquinaCell" HeaderStyle-HorizontalAlign="Center"  />
           </Columns>
           </asp:GridView>

          ```

  [1]: https://i.stack.imgur.com/SF6bO.jpg


text:
Q: Getting "Unexpected HTTP status code [0]" on payment transactions We are using a TSYS Global Payments Genius payment gateway with eCommerce activated so I do have the Web API key. I'm using the "TSYS Genius" payment method within the official GlobalPayments WooCommerce plugin: https://wordpress.org/plugins/global-payments-woocommerce/
I'm getting the error message "Unexpected HTTP status code [0]" when I run an order.
What can I do to resolve this error message? I don't see any method to enable any debugging or logging so I don't see any way to get more information.
Any help would be great!
Thank you!


text:
Q: Store reads, but the store.records.length is always 0 Ext.define('myApp.model.SensorStation', {
    extend: 'Ext.data.Model',
    config: {
        fields: [
            {

                name: 'name',
                type: 'string',
                mapping: '@name'
                //convert: function (value, record) {
                //    Ext.Msg.alert(value,record.raw);
                //    //var nodes = rec.raw.querySelectorAll('');
                //}
            },
            {
                name: 'lat',
                mapping: '@latitude',
                type: 'float'
            },
            {
                name: 'lng',
                mapping: '@longitude',
                type: 'float'
            },
            {
                name: 'locid',
                mapping:'@locid',
                type: 'string'
            }
        ]
    },
    proxy: {
        type: 'ajax',
        url: 'http://webtrak.bksv.com/mel/configuration',
        reader: {
            type: 'xml',
            record:'locations',
            rootProperty: 'nmts'
        }
    }
});

Ext.define('myApp.store.SensorStationStore', {
    extend: 'Ext.data.Store',
    requires: ['myApp.model.SensorStation'],
    config:{
        model: 'myApp.model.SensorStation',
        storeId: 'SensorStore'
    },
    autoLoad: true
});

Ext.define('myApp.controller.SensorStations', {
    extend: 'Ext.app.Controller',
    requires: ['Ext.MessageBox'],
    config: {
        refs: {
            mapComponent: 'main map'
        },
        control: {
            mapComponent: {
                maprender: 'onMaprender'
            }
        }
    },

    onMaprender: function (mapComponent, googleMap) {
        var store, latlng, marker;

        // Use Store name when testing on devices
        // Use Store ID when testing in browsers
        var sensorStore = Ext.data.StoreManager.get('SensorStore');
        if (!sensorStore) {
            console.log("Store not found");
            Ext.Msg.alert('error', "store not found");
            return;
        }
        //else {
        //    console.log("Store found");
        //    Ext.Msg.alert('great', "store found");
        //    //return;
        //}

        sensorStore.load({
            callback: function (records, operation, success) {

                mapComponent.setMapOptions({
                    center: new google.maps.LatLng(-37.899328, 144.843333)
                });

                if (success) {
                    Ext.Msg.alert('success', records);
                }
                else {
                    Ext.Msg.alert('error', operation);
                }

                Ext.Msg.alert('records.count = ' + records.length, 'haha');

            }
        });

    }

});

The records.length is always 0.
Could you please point out where I get wrong?
Also I'd like to know the data structure of the records.
Many thanks

A: In your model put the proxy: {} inside config:{} and in store put autoload: trueinside config:{}


text:
Q: PFXplus/powerflex .dat file converstion I have the task of moving a PFXplus .dat files into a new Microsoft SQL server. The program in use was made probably around 2003 and hasn't been updated since. I see there is a PFXodbc driver for sale for $459 USD but i am not going to fork over that kind of money for a conversion job or even if that is the product i need. So simple question is there a way to convert the .dat PFXplus files to something usable? Anything in the Linux world perhaps?

A: Do you have access to a powerflex runtime?  Or even better, a developer environment?  Or just the database?
You can use the powerflex provided reporter to create a CSV file, especially if the database is not too big.  It is a compiled program call "pfrep" and needs to be invoked using the runtime.
Do you know what version the data file is?  If it is Mark 1 (and maybe even Mark 2), then you could also look for a dataflex tool.  If it is Mark 3, then no.


text:
Q: ReactiveUI RaiseAndSetIfChanged hit when lose focus on textbox I'm using ReactiveCommand:
LoginCommand = new ReactiveCommand(this.WhenAny(x => x.UserName, x => x.Password, (r, g) => !string.IsNullOrEmpty(r.Value)  &&!string.IsNullOrEmpty(g.Value)));
LoginCommand.Subscribe(async _ =>
{
var user = await _authenticationService.AuthenticateUser(_userName, _password);
                if (user.Error != null)
                {
                    MessageBox.Show("The user was not found. Please try again!", "User Not Found", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    return;
                }
                screen.Router.Navigate.Execute(new MainViewModel(screen));
            });

And UserName, Password field for binding:
public string Password
{
   get { return _password; }
   set { this.RaiseAndSetIfChanged(ref _password, value); }
}

And Textbox for this binding to:
 <TextBox x:Name="txtPassword" Text="{Binding Password}" Grid.Column="1" Grid.Row="2" Margin="3,3,0,3" MinWidth="100" HorizontalAlignment="Left" Width="10" Height="30"/>

This code work but when I lose focus on textbox. Is there any proper way to do this when I start writing on textbox with reactiveUI.

A: Use UpdateSourceTrigger property. As the name implies, this means that whenever there is a change in the Text property of TextBox, RaiseAndSetIfChanged fires.
<TextBox x:Name="txtPassword" Text="{Binding Password, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Grid.Row="2" Margin="3,3,0,3" MinWidth="100" HorizontalAlignment="Left" Width="10" Height="30"/>


text:
Q: Localstorage change event + react I'm using React. I have a function that listen to localstorage event change like window.addEventListener("storage", () => {....}. If I change value of a key that I listen in storage manually by my hand, this code work. But if I use setItem to change value. It doesn't work anytime. Help me. Thanks a lot

A: It's because The StorageEvent doesn't work on the same page that is making the changes.
For more info check here Responding to storage changes with the StorageEvent


text:
Q: How to iterate arraylist from inner loop in that way every time will point next address element There are two for loops and I want to iterate inner loop array in that way, every time will point next address element. How I can do that?
I have used below code after iterating first time from inner loop its break but i want to point next address of element when will iterate second time.
ArrayList<String> location;
ArrayList<String> distanceInMiles;

for (String strloc : location){
    for (int i = 0; i < distanceInMiles.size(); i++){
        String strDist = distanceInMiles.get(i);
        System.out.println("For Location :" + strloc + "Zip code 30303" + "Distance in Miles:" + strDist);
        //When iterate second time i want to point i=1 instead of i=0 but its pointing to i = 0

        double value = Double.parseDouble(strDist);
        value++;
        distanceInMiles.set(i, String.valueOf(value));

        break;
    }
}

A:
I want to iterate inner loop array in that way, every time will point next address element.

I interpret this to mean that you want each iteration of the inner loop to also advance the outer loop as well.  If so, then just use a single loop here:
for (int i=0; i < location.size(); ++i) {
    String strloc = location.get(i);
    String strDist = distanceInMiles.get(i);
    String msg = "For Location :"+strloc+"Zip code 30303"+"Distance in Miles:"+strDist;
    System.out.println(msg);
    double value = Double.parseDouble(strDist);
    value++;
    distanceInMiles.set(i, String.valueOf(value));
}

This of course assumes that I read your question correctly, and that both lists are the same size (or you can live with partially using one of the lists).


text:
Q: How to identify vertical text with yob/pdf-reader? I have some code which uses the yob/pdf-reader gem to fetch the text from a PDF file and search for certain strings in it. Recently I got the issue that vertical text may interfere with my logic to identify text that belongs to the same line.
My question is: Does someone know a way to distinguish text orientation with pdf-reader?


text:
Q: ORACLE Join tables on a single field and account for minor difference (specific example provided) I am trying to join two tables on a field (FILE_NAME); however, there are a couple records in just one of the table, in which a timestamp is appended to the end of the file name and before the file extension.  I'm not sure how to account for these.  I found an Oracle function,
 REGEXP SUBSTR (https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions131.htm), that seems like it may give me what I need, but I have to admit that this is extremely advanced to me and am not sure how to apply it.
My sample tables are:
FILE_INFO Table:
FILE_NAME | FILE_ID
REGIONS_ACCOUNTED.xlsx | 21
TSM_INSAT.xml | 14

FILE_PARAMETERS Table:
FILE_NAME
TSM_INSAT.xml
REGIONS_ACCOUNTED-08112017.xlsx

From what I can tell, it seems that the timestamps are always prefixed with a dash (-) so I originally thought to approach it by finding the index of a dash then use substr to concat the before and afters of the timestamp but can't figure out how to do that in a query or how to account for date ranges (e.g.:
REGIONS_ACCOUNTED-07102017-07142017.xlsx

At this point, I just have a basic Join:
SELECT a.file_name, b.file_location
FROM reports.file_info a
LEFT OUTER JOIN reports.file_parameters b on (a.file_name = b.file_name);

The SQL above of course excludes those reports with dates/date ranges in the filename.  It would be better to use a file_id, I'm sure; however, there is no file_id in the file_parameters.
Any guidance would be greatly appreciated!

A: You seem to be looking for match of filenames from FILE_INFO in FILE_PARAMETERS.
SELECT a.file_name,
       b.file_location
  FROM reports.file_info a
  LEFT OUTER JOIN reports.file_parameters b
    ON b.file_name LIKE CONCAT('%', SUBSTR(a.file_name, 1, INSTR(a.file_name,'.',-1)-1), '%', SUBSTR(a.file_name, INSTR(a.file_name,'.',-1), LENGTH(a.file_name)), '%');

A: @Hepc provided the correct answer (in the comments).  The modified version to account for date ranges is:
REGEXP_REPLACE(a.file_name,'\-[\d\w\-\_]+.,'.')


text:
Q: Tridion 2009 - Determine who published a page We need to determine who triggered the publishing of a Tridion 2009 page: editor or code.
Please use as an example:
Publication A
Publication B which inherits from A
Now when we publish a page in publication A using "Also publish/unpublish in Child Publications" the event system will be triggered for the page in
publication A and also for the page in publication B.
In this case we want to use the event system only on the page from publication A
Something like:
public override void OnPageSetPublishedToPost(Page page, string publicationTarget, bool published, string user)
{
  if (!page.IsTriggeredByParent)
  {
  // do stuff
  }
}

The problem is we don`t know how to determine the value for "IsTriggeredByParent".
Thank you for your time

A: In SDL Tridion 2009 this is impossible, the COM Based event system there has no way of identifying where an event came from.
In the SDL Tridion 2011 .NET event system, you have access to the event stack. This means you can detect if an action is performed as part of another action (for example, a Save on a VersionedItem with the parameter true will also Check-In the item and raise that event as part of the Save event). So to accomplish your task I think you require an upgrade.


text:
Q: ajax function not going to php codeigniter controller I have a ajax function written which is posting different numbers.
Here is the ajax function.
self.giveCashtoChild = function(){
            $.ajax({
                type: 'POST',
                url: BASEURL + '/index.php/main/addUserChildrenCash'+"/"+self.selectedchild(),
                contentType: 'application/json; charset=utf-8'
            })
            .done(function() {

            })
            .fail(function(xhr, status, error) {
                alert(status);
            })
            .always(function(data){
            });
        }

self.selectedchild() has the value of 2 , so Basically the url is addUserChildrenCash/2 but then it does not go to the codeigniter controller and change the page. Here is the controller function.
public function addUserChildrenCash($childID){
            if (!$this->session->userdata('user_id')){
                redirect('main'); // the user is not logged in, redirect them!
            }

                $userid= $this->session->userdata('user_id');
                $this->load->model('main_page');
                $childname =  $this->main_page->getChildName($childID, $userid);

                $data = array(
                    'name' => $childname['children_name']
                );
                $this->load->view('header2_view');
                $this->load->view('add_user_children_cash_view' , $data);
                $this->load->view('footer_view');

        }

A: You define ajax as POST but you sending it via GET
 type: 'POST',
 url: BASEURL + '/index.php/main/addUserChildrenCash'+"/"+self.selectedchild(),

So your code should be
In Ajax
var id = self.selectedchild(); # Assign data to here
$.ajax(
    {

        type:"post",
        url: "<?php echo base_url(); ?>index.php/main/addUserChildrenCash",
        data:{ id:id},
        success:function()
        {

        }
        error:function()
        {

        }
        always:function(){

        }
    });

In controller
public function addUserChildrenCash()
{
    $id = $this->input->post("id");
    echo $id
}

A: self.giveCashtoChild = function(){
            var id = self.selectedchild();
            $.ajax({
                type: 'POST',
                url: BASEURL + '/index.php/main/addUserChildrenCash/"+id,
                contentType: 'application/json; charset=utf-8'
            })
            .done(function() {

            })
            .fail(function(xhr, status, error) {
                alert(status);
            })
            .always(function(data){
            });
        }

A: In your codeigniter use case I would pass your ajax parameter like this:
 $.ajax({
   type: 'post',
   url: BASEURL +'/index.php/main/addUserChildrenCash',
   data: { 'childID': self.selectedchild() },
   })
  ...

In the codeigniter controller I would receive the parameter like this:
public function addUserChildrenCash() {
    $childID = $this->input->post("childID");
    ...
    }

You should also check wether your BASEURL has the correct value assigned. Hope this helps.


text:
Q: why do my django urls render the wrong template? I'm suprised that I cannot access my product detail page through the url and I don't understand why since I've already done this basic thing plenty of times...
I have a page where all my products are displayed, when the user click on a product he is redirected to the product detail, that's it.
Somehow when I click a link linked to the product detail or type de correct path to the url it loads the same page where all the product are shown but it doesn't even call the product detail view, why so ?
Here are the views :
def rcdex(request):
    list = Liste.objects.all()
    return render(request, 'rcdex.html', {'list':list,})

def rc_detail(request, id):
    list = Liste.objects.get(id=id)
    return render(request, 'rc_detail.html', {'list':list,})

Here are the urls :
url(r'^', views.rcdex, name="rcdex"),
url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'),

Here is how I call the rc_detail view on the template :
{{ l.entreprise }}

I don't get why it doesn't show me the correct template (rc_detail.html) but instead reload rcdex.html ?

A: You haven't terminated your rcdex urlpattern, so it matches everything. You should use a $:
url(r'^$', views.rcdex, name="rcdex"),

A: you can also do like this..
url(r'^rc/(?P<id>\d+)/$', views.rc_detail, name='rc_detail'),
url(r'^', views.rcdex, name="rcdex"),


text:
Q: Как перекрасить адресную строку браузера
Господа, подскажите, как можно перекрасить адресную строку браузера? Сколько не рылся в коде, ничего подходящего не нашел.

A: здесь есть описание для разработчиков: https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android
пример кода:
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

A: Используйте метатег:
<meta name="theme-color" content="#db5945">


text:
Q: R asking for unknown dependency when loading package I'm the maintainer for the package 'rase' (link).
I haven't changed the code at all since Nov 9, 2015, when the package could load without problems. However, I have received emails asking about the following problem when loading the package:
> library(rase)
Error in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]) :
  there is no package called 'Biostrings'
Error: package or namespace load failed for 'rase'

I tried then to do it in my own computer, and I received the same message. Between the last time I loaded the package successfully (Nov 2015) and now, I upgraded R to v 3.2.3. Naively, I reinstalled v3.2.2, but the same error appears. I have checked rase code (git here) thoroughly, but no changes have been made and there is no reference whatsoever to 'Biostrings' (or any function within). 'rase' dependencies and imports do not include 'Biostrings'.
Any help would be much appreciated as I don't know why this is happening (I'm a novice when creating packages). I guess I could install 'Biostrings', but I don't want to make a seemingly unnecessary dependency.
Here is my sessionInfo:
> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-apple-darwin13.4.0 (64-bit)
Running under: OS X 10.11.2 (El Capitan)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ape_3.4          data.table_1.9.6

loaded via a namespace (and not attached):
 [1] quadprog_1.5-5          lattice_0.20-33         mvtnorm_1.0-3           msm_1.6
 [5] MASS_7.3-43             chron_2.3-47            grid_3.2.2              nnls_1.4
 [9] nlme_3.1-121            magrittr_1.5            Matrix_1.2-2            splines_3.2.2
[13] tools_3.2.2             igraph_1.0.1            maps_3.0.2              parallel_3.2.2
[17] numDeriv_2014.2-1       survival_2.38-3         mnormt_1.5-3            clusterGeneration_1.3.4
[21] animation_2.4           expm_0.999-0

A: Biostrings is a BioConductor package which you install following the instructions on this page:
## try http:// if https:// URLs are not supported
source("https://bioconductor.org/biocLite.R")
biocLite("Biostrings")

If you add BioC as a known repository on your system, it will be installable via install.packages() too.  Eg this would do
r <- getOption("repos")
r["CRAN"] <- "http://cran.rstudio.com"
r["BioCsoft"] <- "http://www.bioconductor.org/packages/release/bioc"
options(repos = r)

in your .Rprofile or Rprofile.site.


text:
Q: Changing user agent on headless chrome I have an issue with changing the user agent.
I am trying to use the following line in my runner.js file in the browsers array :
chrome:headless:userAgent=Mozilla/5.0\ \(Linux\;\ Android\ 5.0\;\ SM-G900P\ Build/LRX21T\)\ AppleWebKit/537.36\ \(KHTML,\ like\ Gecko\)\ Chrome/57.0.2987.133\ Mobile\ Safari/537.36

However, the best I can get is Mozilla/5.0 (Linux in the actual user agent.
The guide doesn't say anything explicit about user agents and how to escape them.
Could someone help me with using a custom user agent for the headless chrome? I can't seem to get over the escaping problem. Thanks.

A: I actually found the answer, you need to escape with \\ every ; character.
E.g:
chrome:headless:userAgent=Mozilla/5.0 (X11\\; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36

will work.
In case of using in cli command you need to double escape. (I didn't have success in that)


text:
Q: Can any body tell me how to open a FIle with .dat extension in cent os? In my new Ruby on rails application I want to find the users country code.
So I am using MaxMind GeoIp. when I downloaded the gzip file after gunzip it gives me a GeoIP.dat file and I am stuck here. Can any one help.
If their is a program to open it or some procedure to use it.
Or if any one can suggest me the other way.

A: As @Kyle pointed out, you can download "human-readable" CSV files instead of binary DAT files.  MaxMind's "GeoLite" downloads are here.
The CSV file format is described here.
But note (from the link above):

Due to the large size of geolocation databases, we generally recommend using our binary format with one of our APIs, since they are highly optimized for speed and disk space. On the other hand, if you have a requirement to import the data into a SQL database, the CSV format is recommended.

The APIs are listed here.  There is no Javascript API listed, but there are a couple of options for Ruby.
So to answer your question directly:  You would not "open" the dat file directly as you would a spreadsheet document.  Instead you would write your own program that uses their API to read the dat file, and perform whatever tasks or queries you design it to do.  Check out their API documentation for details of how you might get started with that.

A: .dat is just a file extension. The contents could be anything. Text. Binary data etc...
There is no way anyone could reliably tell you how to open the file.
I would attempt to view the contents of the file from the command line:
less file_name.dat

You can open the file and read line by line in ruby like this:
IO.readlines('file_name.dat').each do |line|
  # do something with the line
end

Edit: I think I found the file you're refering to. Why not go here and download a csv version? The .dat version is not in plain text.


text:
Q: Is it possible to view queries with resolved variables in ODI's code executions? In ODI's operator tab you can check the state of an execution, and inside each execution the SQL used for each transformation. On the project i'm working on we use a lot of variables when developing our ODI projects. The problem is that to debug the SQL code we have to replace the variable names with the values by hand.
Is it possible to view the executed code with the variables resolved? What would be a good workaround for this? Thanks.

A: First thing you need to do is to execute the mapping with log level 6 (by default it is in 5).

Then you need to click in the icon on the top-right when you check the executed code in the operator:

I hope this works for you.


text:
Q: Visual Studio and Anaconda Terminal Error I am a newbie to the anaconda environment. A couple of days back I installed keras and tensorflow through anaconda prompt. tensorflow installed successfully but keras didn't. After, whenever I open the terminal the following error is showing. Please help me out.
my installation commands are:
conda create -n tf tensorflow

conda install -c conda-forge keras

C:\Users\venkatesh>SET DISTUTILS_USE_SDK=1

C:\Users\venkatesh>SET MSSdk=1

C:\Users\venkatesh>SET "VS_VERSION=15.0"

C:\Users\venkatesh>SET "VS_MAJOR=15"

C:\Users\venkatesh>SET "VS_YEAR=2017"

C:\Users\venkatesh>set "MSYS2_ARG_CONV_EXCL=/AI;/AL;/OUT;/out"

C:\Users\venkatesh>set "MSYS2_ENV_CONV_EXCL=CL"

C:\Users\venkatesh>set "PY_VCRUNTIME_REDIST=\bin\vcruntime140.dll"

C:\Users\venkatesh>set "CXX=cl.exe"

C:\Users\venkatesh>set "CC=cl.exe"

C:\Users\venkatesh>set "VSINSTALLDIR="

C:\Users\venkatesh>for /F "usebackq tokens=*" %i in (`vswhere.exe -nologo -products * -version [15.0,16.0) -property installationPath`) do (set "VSINSTALLDIR=%i\" )

C:\Users\venkatesh>if not exist "" (for /F "usebackq tokens=*" %i in (`vswhere.exe -nologo -products * -requires Microsoft.VisualStudio.Component.VC.v141.x86.x64 -property installationPath`) do (set "VSINSTALLDIR=%i\" ) )

C:\Users\venkatesh>if not exist "" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\" )

C:\Users\venkatesh>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" )

C:\Users\venkatesh>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\" )

C:\Users\venkatesh>if not exist "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\" (set "VSINSTALLDIR=C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\" )

C:\Users\venkatesh>IF NOT "" == "" (
set "INCLUDE=;"
 set "LIB=;"
 set "CMAKE_PREFIX_PATH=;"
)

C:\Users\venkatesh>call :GetWin10SdkDir

C:\Users\venkatesh>call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 exit /B 1

C:\Users\venkatesh>exit /B 0

C:\Users\venkatesh>for /F %i in ('dir /ON /B "\include\10.*"') DO (SET WindowsSDKVer=%~i )
The system cannot find the file specified.

C:\Users\venkatesh>if errorlevel 1 (echo "Didn't find any windows 10 SDK. I'm not sure if things will work, but let's try..." )  else (echo Windows SDK version found as: "" )
Windows SDK version found as: ""

C:\Users\venkatesh>IF "win-64" == "win-64" (
set "CMAKE_GEN=Visual Studio 15 2017 Win64"
 set "BITS=64"
)  else (
set "CMAKE_GEN=Visual Studio 15 2017"
 set "BITS=32"
)

C:\Users\venkatesh>pushd C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
The system cannot find the path specified.

C:\Users\venkatesh>CALL "VC\Auxiliary\Build\vcvars64.bat" -vcvars_ver=14.16
The system cannot find the path specified.

C:\Users\venkatesh>popd

C:\Users\venkatesh>IF "" == "" SET "CMAKE_GENERATOR=Visual Studio 15 2017 Win64"

C:\Users\venkatesh>call :GetWin10SdkDirHelper HKLM\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE\Wow6432Node  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 call :GetWin10SdkDirHelper HKLM\SOFTWARE  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 call :GetWin10SdkDirHelper HKCU\SOFTWARE  1>nul 2>&1

C:\Users\venkatesh>if errorlevel 1 exit /B 1

C:\Users\venkatesh>exit /B 0

A: I had a similar set of errors created by theano, which a package of interest required.
conda uninstall theano and the error was gone.
If you need to use theano, I recommend making a new conda environment and isolating it there.

A: I was trying to create a virtual environment in anaconda for a very old version of tensorflow=1.3.0 and keras=2.0.9, and I got the similar error above after using conda install -c conda-forge keras==2.0.9.
conda uninstall theano
conda uninstall -c conda-forge keras==2.0.9 (but Proceed ([y]/n)? n ---select no)
pip install keras == 2.0.9

solves the problems, and Tensorflow, Keras runs properly now.


text:
Q: Wrong working directory, if bash script is opened via double-click I wrote a bash script in order to directly start eclipse from different workplace locations. Each workplace contains the script, after running it, eclipse is started with the respective workspace set.
#!/bin/bash

# relative path
#ECLIPSE_DIR='../../'
ECLIPSE_DIR='/Users/mike/Development/java/'
ECLIPSE="${ECLIPSE_DIR}eclipse/eclipse.app"

AUTHOR='mike'

# current directory is workspace
WORKSPACE=`pwd`
echo "WORKSPACE = $WORKSPACE"

# start eclipse from current directory
#open -n $ECLIPSE --args -data $WORKSPACE -vmargs -Duser.name='$AUTHOR'

The script is working, when I run it from the terminal. But when I double-click it, it uses the home directory as working directory and thus starts eclipse not from the directory that contains the script.
Apparently scripts are executed from ~/., which is the cause for my trouble. What can I do to fix this? Or how can I change my script to get the desired behavior?

A: If your script is stored at ~/workspaces/myproject/launch.sh and you want to be in that directory when you run, change to that directory, you can get the directory where the script is saved with this one liner:
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )

So the first few lines of your script become:
#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd "${DIR}"
...the rest of your script...

This will put you in the directory where the script is stored no matter how your run the script.
If you want to learn more about detecting the location on disk of a script at execute time see this excellent StackOverflow answer.


text:
Q: InfluxDB select top n results from a group by tag I have a data set of devices and the number of (un)instalmments of my app that are done daily.
A sample data would be:
 time | device_name | daily_installs | daily_uninstall
  t1  |   device1   |       0        |       1
  t1  |   device2   |       2        |       0
  t2  |   device2   |       2        |       0
  t2  |   device3   |       12       |       0

I can group them by device_name and get the total of install that I have by month (or any other range) for example.
But the amount of device is huge, hence I would like to filter only the top 10.
How can I achieve that using InfluxDB?

A: The answer depends on which version of InfluxDB you're using.
Version 1.1-
Step 1
Select the monthly counts into a new measurement
SELECT count(daily_uninstall) as monthly_uninstall
INTO newmeasurement
FROM mymeasurement
WHERE time > now() - 4w
GROUP BY device_name

Step 2
Select the top 10 results from the new measurement
SELECT top(monthly_uninstall, 10), device_name
FROM newmeasurement

Version 1.2+
In versions 1.2+ of InfluxDB you'll be able to do this in a single step using subqueries.
SELECT top(monthly_uninstalls,10), device_name
FROM (SELECT count(daily_uninstall) as monthly_uninstall
      FROM mymeasurement
      WHERE time > now() - 4w
      GROUP BY device_name)

A: Version 1.3.4
SELECT top(monthly_uninstalls,device_name,10)
FROM (SELECT count(daily_uninstall) as monthly_uninstall
      FROM mymeasurement
      WHERE time > now() - 4w
      GROUP BY device_name)

Please note that the syntax is "top("field_name", "tag", "topN") from ...."


text:
Q: 32-bit PCI riser cards: different types? I'm duplicating an existing compact PC; I'd love to replace it with modern components, but for various reasons I can't.
I'm having a tough time finding the correct 32-bit PCI right-angle riser card. I bought a new one, and the dimensions are the same, but the wiring is different, and the system doesn't recognize the inserted card (an audio card).
The old, working riser (green in the pictures below) has five capacitors, and the wiring doesn't look straight-through. When I toned it out, it seemed to be straight-through, although several pairs of adjacent pins were connected. It's at least a three-layer board with an internal ground plane.
The new, not-working-for-me riser (red) is pretty clearly straight-through, with no components other than the connector. I toned it, and no adjacent pins are shorted. It's just two layers; no ground plane.
Strange thing: plugging the audio card straight into the motherboard works fine, which suggests that a straight-through riser should work.
So, the question is: are there different types of PCI riser cards? How can I find one that's electrically equivalent to the old one? (And, why won't the new straight-through riser work, when the audio card works if plugged directly into the motherboard?)


text:
Q: Bug unsubscribing from Ubuntu One Mobile I have an Ubuntu One Mobile subscription, which I can see in my subscriptions page:
one.ubuntu.com/account/subscription/756082
I no longer need my Ubuntu One Mobile subscription, so click the link to cancel the Mobile service subscription:
one.ubuntu.com/account/cancel/756082/
Then confirm that request to cancel:
one.ubuntu.com/account/cancel/756082/confirm/
But the process ends there showing a "Something has gone wrong page", and my subscription remains active :(
The same problem occurred when I attempted the same a few weeks back, so not a temporary problem I'm thinking.
Any input gratefully received.
I would like to report this problem directly to the maintainer of this part of the Ubuntu site but cannot see how to do that.

A: Thank you for reporting this. I have found the issue and a fix is under way.
Meanwhile, I'm going to cancel your subscription manually. It will continue to work until it expires.

A: Ask Ubuntu isn't usually the best place for bug reports.
The best way for you to report this problem is using Ubuntu One's support form. I'm sure they will be very grateful if you send them a message.


text:
Q: Documentar funciones y constructores sobrecargados Tengo el siguiente constructor de clase:
class Logger {
  /** @constructs
      @param { number } minlevel Minimal level to shown log
      @param { function } callback to really do the process
  */
  constructor( minlevel, callback ) {
    if( minlevel instanceof Logger ) {
      // Duplicar el objeto.
      this.$callback = minlevel.$callback;

      if( typeof( callback ) === 'number' ) {
        this.$minLevel = callback;
      } else {
        this.$minLevel = minlevel.$minLevel;
      }
    } else {
      // Nueva instancia.
      if( typeof( callback ) != 'function' ) throw TypeError( );

      this.$minLevel = minlevel;
      this.$callback = callback;
    }
  }
}

Este constructor posee 2 sobrecargas (casos de uso, con distintos tipos de argumentos y distinto resultado). Expresado en TypeScript (para clarificar), seria así:

*

*constructor( other : Logger, minlevel? : number )
Usado para clonar una instancia; genera una copia, con un argumento minlevel opcional.

*constructor( minlevel : number, callback : Function )
Usado para crear una nueva instancia sin depender de ninguna otra.
Me gustaría documentar ambas sobrecargas usando JSDoc, pero no encuentro la forma correcta. Tal y como está ahora, genera

que es lo que espero para la segunda sobrecarga.
¿ Como puedo documentar funciones/constructores/getters/setters sobrecargados usando JSDoc ?

A: Finalmente, encontré la solución (en inglés): How Do I Document an Overloaded Constructor
En ese enlace, se indica literalmente

You need to nestle the start and end of each comment

Sin embargo, creo mas adecuado indicar que las descripciones de las distintas sobrecargas han de colocarse inmediatamente consecutivos unas de otras:
class Logger {
  /**
    @constructs
    @param { number } minlevel Minimal level to shown logs
    @param { function } callback to really do the process
  *//**
    @constructs
    @param { Logger } instance Instance to copy
    @param { number } minlevel Minimal level to shown logs
  */
  constructor( minlevel, callback ) {
    if( minlevel instanceof Logger ) {
      // Duplicar el objeto.
      this.$callback = minlevel.$callback;

      if( typeof( callback ) === 'number' ) {
        this.$minLevel = callback;
      } else {
        this.$minLevel = minlevel.$minLevel;
      }
    } else {
      // Nueva instancia.
      if( typeof( callback ) != 'function' ) throw TypeError( );

      this.$minLevel = minlevel;
      this.$callback = callback;
    }
  }
}

El resultado obtenido, ahora si, es satisfactorio:


text:
Q: Modifier System C# I am trying to figure out a system that can easily modify objects on the fly.
here is an example, Lets say I have an Entity2D that inherits from Entity. Entity2D has a Position property.
Now I have a class called ModifyPosition that inherits from Modifier.
Here is some code
public class Entity
{
/// <summary>
/// Applies the modifier to this entity.
/// </summary>
/// <param name="modifier">The modifier to apply.</param>
public void ApplyModifier(Modifier modifier)
{
    modifier.Apply(this);
}
}

/// <summary>
/// Modifies an entities position
/// </summary>
public class ModifyPosition : Modifier
{
    /// <summary>
    /// Initializes a new instance of the <see cref="ChangePosition"/> class.
    /// </summary>
    /// <param name="position">The position.</param>
    public ChangePosition(Vector2 position)
    {
        this.Position = position;
        this.IsModifyingChildren = false;
    }

    /// <summary>
    /// Gets the position.
    /// </summary>
    /// <value>The position.</value>
    public Vector2 Position { get; private set; }

    /// <summary>
    /// Applies this change to the specified entity.
    /// </summary>
    /// <param name="entity">The entity.</param>
    internal override void Apply(Entity entity)
    {
        ((Entity2D)entity).X += this.Position.X;
        ((Entity2D)entity).Y += this.Position.Y;
    }
}

But if you are calling this multiple times per second I would think that the casting would slow it down.
Is there another way to go about this without having to cast?

A: if you use an interface IEntity
interface IEntity
{
 double X{get;}
 double Y{get;}
}

have Entity implement that interface
public class Entity: IEntity
{
...
}

and use that as the parameter type for Apply
internal override void Apply(IEntity entity)
    {
        entity.X += this.Position.X;
        entity.Y += this.Position.Y;
    }

then you don't have to cast

A: With C# you have to ensure that the type you're modifying supports your modification (not true with some languages).  So your modifiers will have to know explicitly which types they're modifying.  (Alternately your entities could know about the modifiers, but it seems more reasonable to give the modifiers the knowledge.)
I don't actually have an answer for you at this point; this is my attempt, but I get a compiler error in the ModifyPosition.Apply declaration stating that you cannot specify type constraints on an overridden method implementation.
public interface IPositionableEntity
{
    Vector2 Position { get; set; }
}

public class Entity
{
    public void ApplyModifier<T>(T modifier) where T : Modifier
    {
        modifier.Apply(this);
    }
}

public class Entity2D : Entity, IPositionableEntity
{
    public Vector2 Position { get; set; }
}

public class Vector2
{
    public double X { get; set; }
    public double Y { get; set; }
}

public abstract class Modifier
{
    public abstract void Apply<T>(T entity);
}

public class ModifyPosition : Modifier
{
    public ModifyPosition(Vector2 position)
    {
        Position = position;
    }

    public Vector2 Position { get; private set; }

    //Compiler error here:
    //Constraints for explicit interface implementation method are inherited
    //from the base method, so they cannot be specified directly
    public override void Apply<T>(T entity) where T : IPositionableEntity
    {
        entity.Position.X += Position.X;
        entity.Position.Y += Position.Y;
    }
}

EDIT - Here's one that at least compiles.  The only change is to ModifyPosition.
public class ModifyPosition : Modifier
{
    public ModifyPosition(Vector2 position)
    {
        Position = position;
    }

    public Vector2 Position { get; private set; }

    public override void Apply(object entity)
    {
        if (!(entity is IPositionableEntity))
        {
            return; //throw, whatever
        }

        var positionableEntity = (IPositionableEntity) entity;
        positionableEntity.Position.X += Position.X;
        positionableEntity.Position.Y += Position.Y;
    }
}

A: Try something like this:
class CatEntity : Entity, IModifiablePosition
{
  // Interface method
  public void ModifyPosition(Vector2 blah) { ... }
...
}

class RobotEntity : Entity, IModifiableShader, IModifiablePosition
{
// Interface method
public void PushShader(RobotEffect bleh) { ... }
public void ModifyPosition(Matrix blah) { ... }
...
}

class ShaderModifier : IModifier
{
  public override void Apply(IModifiableShader obj)
  {
    obj.PushShader(m_furryEffect);
  }
}

class PositionModifier : IModifier
{
  public override void Apply(IModifiablePosition obj)
  {
    obj.ModifyPosition(m_mxTranslation);
  }
}

This seems easily readable and safe -- hope it works for ya.


text:
Q: Automatically partially invoice when shipped I need to invoice my order automatically whenever shipment is done, but if say I ship only one item of multiple items order then invoice should also be created for only that item not for all.
I am using following code after setting a observer whenever shipped but it is invoicing all items even if I ship just one:
public function invoicedStatusChange($observer)
    {
       $shipment = $observer->getEvent()->getShipment();
       $order = $shipment->getOrder();
       if($order->canInvoice())
       {
           $invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
           $invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
           $invoice->register();
           $transactionSave = Mage::getModel('core/resource_transaction')
           ->addObject($invoice)
           ->addObject($invoice->getOrder());
           $transactionSave->save();
       }

Thanks in advance

A: Take a look at https://magento.stackexchange.com/a/11075/519
You need to include the qty of each item shipped
if($order->canInvoice()){
  foreach(get item collection just ship){
    $qtys[$item->getId()] = $item->getQtyShipped();
  }

  Mage::getModel('sales/service_order', $order)->prepareInvoice($qtys);

}

Take a look at database table sales_flat_order_item
qty_canceled
qty_invoiced
qty_ordered
qty_refunded
qty_shipped

Note: you may need to get the qty from the $shipment, since the above fields store the total


text: Q: How to find solutions of coin weighing problems with multiple light coins and prove optimality So the classical coin weighing problem with $3^n$ coins all equal weight except for one light coin, where we want to find the one light coin, can be solved optimally with $n$ uses of a balancing scale, assuming that the scale either tips in the heavy direction or balances if the two weights are equal. But what if we have $N$ coins (it's possible that $N$ should be parametrized for simplicity, like $N = 3^n$ but I'm not sure how), and we know there are $k$ lighter coins all of equal weight (so there are $N \choose k$ possibilities for which coins might be lighter). How can the scale optimally be used to find the $k$ lighter coins? And what if the $k$ lighter coins are all of different weights and we want to know the $k$ lighter coins as well as their ordering according to weight? Then there are $k! {N \choose k}$ possibilities. Again how can the scale optimally be used to find the $k$ lighter coins and their weight ordering?


text:
Q: Why didn't Kotlin follow Java syntax? I'm in the process of learning Kotlin as an Android developer!
Out of curiosity, why didn't the JetBrains guys follow the Java style syntax (where they could have), and made it easier on developers to learn Kotlin?
For example, defining a simple function in Kotlin:
fun simpleFunc(x: Int): Int {

// do stuff

}

Why didn't they do:
fun Int simpleFunc(Int x) {

// do stuff

}

I would appreciate hearing your opinion on this

A: Java is like a coffee, and Kotlin means that coffee with a little bit sugar in there. In some cases, Kotlin does increase the efficiency and make the programming more enjoyable.
Comparing with Java, Kotlin is more effective and actually can work with Java pretty well.
Check the example in that picture here about Safe Calls on the official kotlinlang.org,

In Chains, when there's a null value,you need to use if function to determine whether the value is null,but there's only one sentence method needed for Kotlin.
Plus, when you are using Gradle daemon and Smart Compilation,Kotlin shows a faster compile speed than Java.

the horizontal axis means ten consecutive incremental builds with one core file changed.
You can see that the Gradle daemon still takes two or three runs to warm up, but after that the performance of both languages is very similar. With no changes, Java takes 4.6 seconds per warm build, while Kotlin averages 4.5 seconds. When we change a file that isn't used by any other files, Java requires an average of 7.0 seconds to do a warm build, and Kotlin clocks in at 6.1. And finally, when we change a file that is imported by many other files in the project, Java requires 7.1 seconds to do an incremental build once the Gradle daemon is warmed up, while Kotlin averages 6.0 seconds.
Citations: 1. https://kotlinlang.org/docs/reference/null-safety.html

*https://medium.com/@johnkorly/kotlin-vs-java-performance-drill-down-which-to-choose-2514bdf91916

A: The kotlin team describes here why the type declarations (like in your example) are on the right:

Why have type declarations on the right?
We believe it makes the code more readable. Besides, it enables some nice syntactic features. For instance, it is easy to leave type annotations out. Scala has also proven pretty well this is not a problem.

A: As mentioned in the Kotlin FAQ, Kotlin's syntax makes it more natural to omit type declarations when they can be inferred by the compiler (which isn't supported by Java). Also, from our experience with Kotlin, we see no evidence that Kotlin's type declaration syntax presents a difficulty for people learning Kotlin.
(Note that your suggested syntax is also different from Java, so it's not clear why you think it would be easier to learn.)


text:
Q: open lightning action in subtab I'm actually using the service console, and I saw that if I set my account as the main tab, I can open an account, and each related record that i open , will open as subtabs. This is very good, fine.
Now I have an action, when i execute the action which will create a new record, it open the new record as a Main tab and not subtab of the account, even if the record created is related to the main, which is my account.
How can I specify my standard action to open the record as subtab and not a main tab ?
If i'm using a lightning component, as action, I may have more flexibility, but I'm not able to use the subtab() method as the method takes a URL as parameter, and in lightning, we don't use URL but methods to navigate to component. How can I achieve this?


text:
Q: How to make spawn process inherit stdio only or error? In general i'm making builds and i want to get output only when an error occurs.
Right now im inheriting stdio as you can see in my code but it outputs alot of unnecessary noise.
Is there a way to only output errors ?
getDirectories(__dirname).map(dirName => {
  try {
    process.chdir(dirName);
    spawn('npm run build', { stdio: 'inherit', shell: true });
    process.chdir('../');
  } catch (err) {
    console.error(`chdir: ${err}`);
  }
});

A: As of child process documentation, you may filter only the stderr using following options,
// Spawn child sharing only stderr
spawn('npm run build', [], { stdio: ['pipe', 'pipe', 'inherit']});

or
// Spawn child sharing only stderr
spawn('npm run build', [], { stdio: ['pipe', 'pipe', process.stderr] });

For further information please follow the stdio.options documentation.


text:
Q: Why is an anti-pattern letting a react component to edit its own props? I was searching for an answer to another problem and I found this answer (link) I'm just curious why is it that modifying its own props is an anti-pattern, and why isn't it that modifying its own state is not and anti-pattern?

A: In react, props is an object of data that is unlikely to change in the lifecycle of the component, and state is data that is likely to change in the lifecycle of the component.
It helps create explicit rules for where developers should put things that do/do-not change.
React update pages very quickly by knowing exactly that data changes will either come strictly from a parent(as props) or come internally as state.
the exact function checks loosely if state/props are the same, then https://github.com/facebook/react/blob/master/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js#L881-L883
I'd recommend reading about how react "reconciles" data for changes and making updates to the dom.
https://facebook.github.io/react/docs/reconciliation.html


text:
Q: Pydev not found in ubuntu Software center I installed eclipse  and then wanted to install pydev plugin to execute python programs.
But it gives an error "pydev not found at https://pydev.org/updates" .
How can I overcome this? And is there any other any alternative?

A: You should be able to install it through Eclipse. The PyDev page has the instructions on how to do this.
If you are not using Aptana, scroll down to Installing with the update site and start there. You'll start by going through Help > Install New Software...
I just did it myself on 12.04 and so far everything seems to be working fine.

A: In Ubuntu 16.04 and later, open the terminal and type:
sudo apt install eclipse-pydev eclipse-mylyn-context-pydev

Optionally you can also install GNU Debugger along with PyDev.
 sudo apt install gdb


text:
Q: Run method in parallel in C# and collate results I have a method that returns a object. In my parent function I have a list of IDs.
I would like to call the method for each ID I have and then have the objects added to a list. Right now I have written a loop that calls the method passing each ID and waits for the returned object and then goes to the next ID.
Can this be done in parallel? Any help here would be most helpful.

A: I think Task parallel libraries will help you
Task[] tasks = new Task[2];
tasks[0] = Task.Factory.StartNew(() => YourFunction());
tasks[1] = Task.Factory.StartNew(() => YourFunction());
Task.WaitAll(tasks);// here it will wait untill all the functions get completed

A: Something like this maybe:
  List<int> ids = new List<int>();
  List<object> result = new List<object>();
  Parallel.ForEach(ids, (id, state, index) => {
    result.Add(new { Id = id }); // You class instance here.
  });


text:
Q: Factoring a polynomial of $4$th degree I was wondering how would you factor $$x^4+4x^3+21x^2-20x+25=0\text{ ?}$$ I cannot find a number that allows the expression to equal zero.

A: One of the universal principles in mathematics is the ability to make a good guess and then eventually prove the guess. Note that $-\omega,-\omega^2$, where $\omega$ is the non-real cube roots of unity, satisfies the equation. This means $x^2-x+1$ is a factor. Using this, the polynomial factors as
$$(x^2-x+1)(x^2+5x+25)$$

A: You really can do this yourself.
A lemma of Gauss says that a polynomial with integer coefficients factors over the integers if it factors over the rationals. in practice, this means there are just four possible products that might work, with integers $A,B$:
$$ (x^2 + A x - 5)(x^2 + B x - 5) $$
$$ (x^2 + A x + 5)(x^2 + B x + 5) $$
$$ (x^2 + A x - 1)(x^2 + B x - 25) $$
$$ (x^2 + A x + 1)(x^2 + B x + 25). $$
In all, $A + B = 4$ because of the $4 x^3.$ In the second one, this gives $20 x,$ so the second one is out, but the first one gives $-20x.$ The first then gives $(AB - 10) x^2,$ so $AB = 31. $ As $31$ is prime, we get either $A+B = \pm 32,$ so the first one is out.
In the third we get $(-25 A - B)x,$ so $-25A-B = -20,$ or $25A + B = 20.$ With $A+B = 4,$ we have $24A = 16,$ so $A$ is not an integer.
In the fourth, we get $(25 A + B)x,$ so $25A+B = -20.$  With $A+B = 4,$ we have $24A = -24,$ so $A=-1$ and $B=5.$ We then confirm that
$$ (x^2 -  x + 1)(x^2 + 5 x + 25) $$
works.


text:
Q: SQL Select data from two tables (one row -> multiple rows) Suppose I have two SQL tables: Customers and PhoneNumbers.
Suppose that Customers has the following columns: customerId (primary key), fName, lName.
Suppose that PhoneNumbers has the following columns: phoneNumberId (primary key), phoneNumber, customerId (foreign key).
What I understand so far is that if each customer has one phone number, I can select the fName, lName, and phoneNumber of each customer with the following SQL:
SELECT
    customer.fName, customer.lName, phone.phoneNumber
FROM
    Customers customer
        INNER JOIN phoneNumbers phone ON
            customer.customerId = phone.customerId

What if a customer may have more than one phone number?  How do I get a list of customers with the list of phone numbers of each customer?
My programming language to drive the SQL is C#/.NET.

A: As you say, if there is exactly one PhoneNumber per customer, your query will work.
Customers with more than one Phone Number will also be returned, but the customer record will be duplicated for each different phone number.
The other condition you need to consider is customers with no phone numbers. If you INNER JOIN the tables, then these customers will be excluded from the result set. To include such customers, you need to use an OUTER JOIN.

A: The query you've given will return multiple phone numbers if they exist. You'll see rows with customer.fName and customer.lName repeated, each with a different phone.phoneNumber.

A: You can do the exact same thing. The query you currently list should retrieve the exact results you want; one row per phone number per customer.

A: You'll get several rows for one customer if it has several numbers.


text:
Q: How to formally prove that $A \subseteq \mathcal P(A)$? Since the the powerset is defined as $\mathcal {P}(A)=\{x\mid x\subseteq A\} $, it seems obvious that $A \subseteq \mathcal P(A)$. But I don't know how to show it formally.
Is it okay to say that $x\subseteq A$ (definition of a powerset), thus $A\subseteq \mathcal P(A)$?
It seems trivial, yet I don't know how to prove it.

A: Let $A=\{1\}$. Then $\mathcal P(A)$ has two elements: $\emptyset$ and $\{1\}$. But $A$ has one element: $1$. This element is not an element of $\mathcal P(A)$, so $A\not\subseteq\mathcal P(A)$. Note that $\{1\}$ and $1$ are not equal.

A: $A \in \mathcal {P}(A)$ but in general $A \not\subseteq \mathcal {P}(A)$ because the elements of $A$ are not necessarily subsets of $A$.
Note the difference between $\in$ (is an element of) and $\subseteq$ (is a subset of).


text:
Q: Allow single session per user IdentityServer4 With IdentityServer4 I need to allow a single user session per time. If the user authenticates with device A and then with B, session and access token must be invalidated for A and, even better, client A could receive a notification that user has logged out in a second step.The main thing is making the server force invalidate session and token. There are similar questions, one of them redirects us to the following link:
https://github.com/IdentityServer/IdentityServer4/issues/736
where it is explained to use backchannel logout and in the login method of the identity server to obtain the previous IdentityServer sessionID that should have been persisted somewhere. Then I should send logout tokens to all clients.
Another solution is given here
How to Logout user from a particular session Identity Server 4, .Net Core?
telling us to use an ITicketStore implementation to be able to invalidate the session.
The configuration used is IdentityServer4 with authorizaton code flow with PKCE. Which approach is best for my case? Is there another approach where I could simply delete the access token in the id server database?

A: I think in your case probably a combination of both. In our real-world implementation we combine server-side storage of sessions via ITicketStore (stored in a custom database with sessions linked to user accounts and also storing the list of client IDs for each session) with the ability to trigger back-channel logout of any session at any time (i.e. not just via the default user-triggered mechanism).
In our case we do this to be able to invalidate sessions for other reasons (e.g. password or other security setting changes, a "log me out of everything" feature, impersonation rights being revoked etc) but this approach could form the foundation of a "single session per user" feature should you wish.


text:
Q: convert  xml tag to java config After searching everywhere I don't find a solution for this question yet.
I need to convert the following code snippet to java config.
<jsp-config>
 <jsp-property-group>
  <url-pattern>*.jsp</url-pattern>
  <page-encoding>UTF-8</page-encoding>
 </jsp-property-group>
</jsp-config>

Is that possible?
Thank you
edit: It seems that should be a duplicated question. The question which refers is too old and maybe dead. I think starting a new question is much better although that the other question has a valid answer it does not solve my problem because it is understandable how to apply that solution.


text:
Q: Understanding a power switch circuit that includes Schottky diodes at its input In the following design, I couldn't find the datasheet for the part U25.
All I could find from Orcad that chip part name is: G5027C.
Anyway, I don't have contact with the person who created this circuit, and I'm trying to understand the design in order to learn and try to use a similar design in other project.
This circuit is a part of reference design for a motherboard that includes a CPU that I want to implement in a motherboard of my own. It's my first motherboard project as a board designer, and I'm to understand this reference design in order to see how it makes sense in terms of signals names as described in datasheets.
As a start, I'm going through the power diagram and following the signals and trying to check mark that I understand the purpose of every signal.
Intuitively, I'd think that U25 is a PWR Switch whose purpose is to deliver "+VCCSTG_CPU" voltage once "GPPC_H_18_CPU_C10_GATE_N" signal is low.
When the signal is LOW, that corresponds to the N at the end of "GPPC_H_18_CPU_C10_GATE_N" signal name, that way the diode connected to it will pass current since pin 1 has a lower voltage that pin 2 (CR28).
Regarding the second diode, with the pin 2 name CR30, it will not conduct. Therefore the ON pin of the "PWR switch" will be low.
My question: What is the designer trying to achieve here with this mechanism? And is my initial analysis correct?
Note 1: Since some of the signals in this circuit come from the CPU, I need to take them into account and know what the best configuration is to use them. In this design, there is a suggested method of using diodes in order to control how CPU\PCH signals affect power delivery (in this case VCCSTG_CPU is the CPU Sustain Gated Power Rail). I want to make sure I understand the purpose of using these diodes, since it might be a standard mechanism that is used many times and could be helpful to implement it in my design, but surely after understanding it.
Note 2: In the OrCAD design, it's clear that U25 is a switch, and it logical regarding the pinout of the device.
I added screenshots that include all the details I have for this device.


text:
Q: Add string to the requested URL I have a route established like the return a particular blog entry when accessed
It looks like this
www.mywebsite.com/100

However I want that when returning the page I also add the blog title to the URL
For e.g. user may enter the above url but when he gets the page back the url must look like this:
www.mywebsite.com/100/My-Blog-Title

Just like it happens here on Stakoverflow that:
I enter this URL
http://stackoverflow.com/questions/11227809/

And after the request is received the URL looks like this:
http://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-an-unsorted-array

How can achieve this in my MVC project? Can anyone please help.
Please also comment over the SEO friendliness while suggesting your preffered approach.
Thankyou

A: It seems to be a simple redirection. See http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.redirecttoaction(v=vs.108).aspx

A: You can use JavaScript for it.
Return the blog title stored in a JavaScript variable somewhere.
var blogTitle = "My-Blog-Title"

Read the blog title and read this link to change the url without redirecting.

A: If you open the Network tab in the Chrome Developer tools and load up the address (id only) to this question (http://stackoverflow.com/questions/21005768/), you'll see that you get back a an HTTP 301 response - a permanent redirect to the friendly url (http://stackoverflow.com/questions/21005768/add-string-to-the-requested-url/).
To respond with this in ASP.NET MVC you would do something like the following:
public ActionResult GetThingy(int id)
{
    var title = GetTitle(id);
    return RedirectPermanent(Url.Action("GetThingy", new { id = id, title = title} );
}

that would redirect to another action on the controller like:
public ActionResult GetThingy(int id, string title)
{
    //do your thing here
}