问:
Saving multiple images in laravel
I'm trying to save multiple images in an array to the database, but I'm struggling with that. I've managed to be able to upload the multiple images to the folder just not the database.

My controller

```<code>public function store(Request $request)
{

    $content = new Content();

    $request->validate($this->getRules());

    $content->fill($this->getSafeInput($request));

    if($request->hasFile('image'))
    {
        foreach($request->file('image') as $image)
        {
            $destinationPath = 'content_images/';
            $filename = $image->getClientOriginalName();
            $image->move($destinationPath, $filename);
            $content->image = $filename;

        }

    }

    $content->save();

    return redirect()->route('content.index');
}
</code>```

My form

```<code><div class="content-form">
    {{ Form::open(array('route' => 'content.store', 'method' => 'post','files'=>'true' )) }}
        {{ csrf_field() }}

        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" id="title" class="form-control" name="title">
        </div>

        <div class="form-group">
            <input type="file" name="image[]" multiple="multiple">
        </div>

        <input type="submit" class="btn btn-primary" value="Submit"></input>
    {{ Form::close() }}
</div>
</code>```

答:
If you want to save the routes of the images separated by ';' you could do something like

```<code>public function store(Request $request)
{

$content = new Content();

$request->validate($this->getRules());

$content->fill($this->getSafeInput($request));

$allImages = null;

if($request->hasFile('image'))
{
    foreach($request->file('image') as $image)
    {
        $destinationPath = 'content_images/';
        $filename = $image->getClientOriginalName();
        $image->move($destinationPath, $filename);
        $fullPath = $destinationPath . $filename;
        $allImages .= $allImages == null ? $fullPath : ';' . $fullPath;
    }

    $content->image = $allImages;

}

$content->save();

return redirect()->route('content.index');
}
</code>```

This should make $allImagesa string with each of the paths to the images saved and then save it all in the Contentmodel.

Title: Saving multiple images in laravel

Body:
I'm trying to save multiple images in an array to the database, but I'm struggling with that. I've managed to be able to upload the multiple images to the folder just not the database.

My controller

public function store(Request $request)
{

    $content = new Content();

    $request->validate($this->getRules());

    $content->fill($this->getSafeInput($request));

    if($request->hasFile('image'))
    {
        foreach($request->file('image') as $image)
        {
            $destinationPath = 'content_images/';
            $filename = $image->getClientOriginalName();
            $image->move($destinationPath, $filename);
            $content->image = $filename;

        }

    }

    $content->save();

    return redirect()->route('content.index');
}

My form

    {{ Form::open(array('route' => 'content.store', 'method' => 'post','files'=>'true' )) }}
        {{ csrf_field() }}

            Title
            <input type="text" id="title" class="form-control" name="title">

            <input type="file" name="image[]" multiple="multiple">

        <input type="submit" class="btn btn-primary" value="Submit"></input>
    {{ Form::close() }}

Body:
If you want to save the routes of the images separated by ';' you could do something like

public function store(Request $request)
{

$content = new Content();

$request->validate($this->getRules());

$content->fill($this->getSafeInput($request));

$allImages = null;

if($request->hasFile('image'))
{
    foreach($request->file('image') as $image)
    {
        $destinationPath = 'content_images/';
        $filename = $image->getClientOriginalName();
        $image->move($destinationPath, $filename);
        $fullPath = $destinationPath . $filename;
        $allImages .= $allImages == null ? $fullPath : ';' . $fullPath;
    }

    $content->image = $allImages;

}

$content->save();

return redirect()->route('content.index');
}

This should make $allImagesa string with each of the paths to the images saved and then save it all in the Contentmodel.


来源: stackexchange

问:
I want to build google assistant on my android application
i want to build ai speaker to use google assistant on android app not android things.
may be i think i will use grcp because python not execute on android app.
Is there any way I can use Google Assistant already installed in my mobile phone ?
my cellphone already has a google assistant !!</p>

答:
Commit b790b0b puts everything into a single class, making it easier to integrate into other Android devices.

Kindly check the below link.

https://github.com/androidthings/sample-googleassistant/commit/b790b0be91b5a743fb847af6a6c95f19459162de

ContentLicense: CC BY-SA 3.0


问:
Tools for making a site design mobile phone friendly
What tools helps designing sites which would be mobile phone friendly ? Something that would product the right CSS, the right html, etc</p>

答:
To counter Alex's point in his comment, you can certainly find an option for covering all markups and all quirks.

We've developed a mobile markup language (WAPL) that allows you to describe a site in XML, pass it via a web service and get the perfect markup back.

It's called Wapple Architect - and it really is better than anything you've used before.. more devices, more compatibility.. http://wapple.net

ContentLicense: CC BY-SA 2.5


问:
How to “splat” the function arguments for dynamically created function
I am generating some functions in the module:

```<code>defmodule M do
  funs = [do_it: [:arg1, :arg2]]

  Enum.each(funs, fn {name, args} ->
    args = Enum.map(args, & {&1, [], Elixir})
    def unquote(name)(unquote(args)),
      do: IO.inspect(unquote(args))
  end)
end
</code>```

The issue is the generated function obviously accepts one single argument, namely a list of size 2:

```<code>▶ M.__info__(:functions)
#⇒ [do_it: 1]
</code>```

The goal is to dynamically declare the function accepting two arguments. In ruby terminology, it would be to unsplat argument list.

Is there a possibility to accomplish this without pattern matching the resulting AST for {:do_it, blah, [[ list of arguments ]]} and flattening the list manually?

答:
You can use Kernel.SpecialForms.unquote_splicing/1 to "splice" in the args list:

```<code>defmodule M do
  funs = [do_it: [:arg1, :arg2], do_it: [:arg1, :arg2, :arg3]]

  Enum.each(funs, fn {name, args} ->
    def unquote(name)(unquote_splicing(args)), do: :ok
  end)
end
</code>```

```<code>iex(1)> M.__info__(:functions)
[do_it: 2, do_it: 3]
</code>```

Body:
I am generating some functions in the module:

defmodule M do
  funs = [do_it: [:arg1, :arg2]]

  Enum.each(funs, fn {name, args} ->
    args = Enum.map(args, & {&1, [], Elixir})
    def unquote(name)(unquote(args)),
      do: IO.inspect(unquote(args))
  end)
end

The issue is the generated function obviously accepts one single argument, namely a list of size 2:

▶ M.__info__(:functions)
#⇒ [do_it: 1]

The goal is to dynamically declare the function accepting two arguments. In ruby terminology, it would be to unsplat argument list.

Is there a possibility to accomplish this without pattern matching the resulting AST for {:do_it, blah, [[ list of arguments ]]} and flattening the list manually?

Body:
You can use Kernel.SpecialForms.unquote_splicing/1 to "splice" in the args list:

defmodule M do
  funs = [do_it: [:arg1, :arg2], do_it: [:arg1, :arg2, :arg3]]

  Enum.each(funs, fn {name, args} ->
    def unquote(name)(unquote_splicing(args)), do: :ok
  end)
end

iex(1)> M.__info__(:functions)
[do_it: 2, do_it: 3]


问:
HTML onclick button not calling javascript function
My HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <script src="scorecard.js"></script>
</head>
<body>
    <div id="scoreButton"><button onclick="javascript: scorecard();">Calculate Score</button></div>
</body>
</html>
</code>```

My Javascript:

```<code>var a;
var b;
var c;
total;

var scorecard = function()
    {
    a = prompt("What was your score on a?","A");
    b = prompt("What was your score on b?","B");
    c = prompt("What was your score on c?","C");
    total = (a + b + c);
    document.getElementById("A").innerHTML = a;
    document.getElementById("B").innerHTML = b;
    document.getElementById("C").innerHTML = c;
    document.getElementById("Total").innerHTML = total;
    };
</code>```

What am I missing? Everything validates yet I can't get it to run in any browser. I'm sure it must be something obvious, however, I have looked at this code and played with it all day and I'm just lost and very frustrated. Any help would be great.

答:
here you go:</p>

```<code><div id="scoreButton"><button onclick="scorecard()">Calculate Score</button></div>    // I have changed syntax of onclick.
</code>```

Body:
My HTML:

<!DOCTYPE html>

<button onclick="javascript: scorecard();">Calculate Score</button>

My Javascript:

var a;
var b;
var c;
total;

var scorecard = function()
    {
    a = prompt("What was your score on a?","A");
    b = prompt("What was your score on b?","B");
    c = prompt("What was your score on c?","C");
    total = (a + b + c);
    document.getElementById("A").innerHTML = a;
    document.getElementById("B").innerHTML = b;
    document.getElementById("C").innerHTML = c;
    document.getElementById("Total").innerHTML = total;
    };

What am I missing? Everything validates yet I can't get it to run in any browser. I'm sure it must be something obvious, however, I have looked at this code and played with it all day and I'm just lost and very frustrated. Any help would be great.

Body:
here you go:

<div id="scoreButton"><button onclick="scorecard()">Calculate Score</button></div>    // I have changed syntax of onclick.


问:
Error filling print... Error evaluating expression
```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="null" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="478ce75d-1606-47d2-88eb-f8079f50c69b">
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["D:\\newpackage\\"]]></defaultValueExpression>
    </parameter>
    <parameter name="MEMBER_CERTIFICATE_PARAM_SUB" class="java.lang.Integer" isForPrompting="false">
        <defaultValueExpression><![CDATA[Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})]]></defaultValueExpression>
    </parameter>
    <parameter name="MEMBER_CERTIFICATE_PARAM_MAIN" class="java.lang.String">
        <defaultValueExpression><![CDATA[]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[SELECT * FROM table_name WHERE atr = $P{MEMBER_CERTIFICATE_PARAM_SUB}]]>
    </queryString>
    <field name="national_id_number" class="java.lang.String"/>
    <field name="national_pin_number" class="java.lang.String"/>
    <field name="contact_email" class="java.lang.String"/>
    <field name="biometric_member_number" class="java.lang.String"/>
    <title>
        <band height="74" splitType="Stretch">
            <subreport>
                <reportElement x="0" y="0" width="555" height="72" uuid="2cee9cb2-abe3-4739-9b64-ec405bf9912b"/>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\DOCUMENTS\\NetBeansProjects\\NhifHeader\\src\\nhifheader\\PotraitNhifHeader\\PortraitNhifHeader.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </title>
    <pageHeader>
        <band height="56" splitType="Stretch">
            <textField>
                <reportElement x="529" y="13" width="26" height="15" uuid="1d23b617-b659-4f87-acfd-e07b54913ccd"/>
                <textFieldExpression><![CDATA[$F{national_pin_number}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="367" y="13" width="173" height="15" uuid="e02099fe-b171-4a24-bb15-195a046921c8"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Personal Identification Number:]]></text>
            </staticText>
            <componentElement>
                <reportElement x="0" y="1" width="240" height="30" uuid="311343bc-7e09-4658-8a1e-810fe91d1a3f"/>
                <jr:Code39 xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" textPosition="bottom">
                    <jr:codeExpression><![CDATA[$F{biometric_member_number}]]></jr:codeExpression>
                </jr:Code39>
            </componentElement>
            <staticText>
                <reportElement x="367" y="0" width="31" height="15" uuid="fefca1d6-a90f-4dba-996c-1c00883eba1c"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Date]]></text>
            </staticText>
            <textField pattern="MMMMM dd, yyyy">
                <reportElement x="398" y="0" width="142" height="20" uuid="c3c68a84-f1d6-43c9-9c83-8b5eaacd6c38"/>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <line>
                <reportElement x="0" y="33" width="555" height="1" forecolor="#E6DAC3" backcolor="#E6DAC3" uuid="003310a9-85b0-447a-bc29-8f97f0006c1d"/>
            </line>
            <staticText>
                <reportElement x="2" y="35" width="553" height="20" uuid="5d8caf66-df88-403d-b96a-1ba2d0e84087"/>
                <textElement textAlignment="Center"/>
                <text><![CDATA[This is to certify that person shown herein is a member of NHIF: National Hospital Insurance Fund]]></text>
            </staticText>
            <frame>
                <reportElement mode="Opaque" x="179" y="1" width="172" height="21" forecolor="#C0C0C0" backcolor="#C0C0C0" uuid="63309c64-53a9-41e7-b490-fa5278230357"/>
                <staticText>
                    <reportElement mode="Transparent" x="33" y="0" width="113" height="20" forecolor="#000000" backcolor="#000000" uuid="ca2b9d0e-5260-4fb3-9f20-308a4349852e"/>
                    <textElement>
                        <font size="12" isBold="true"/>
                    </textElement>
                    <text><![CDATA[Member Certificate]]></text>
                </staticText>
            </frame>
        </band>
    </pageHeader>
    <detail>
        <band height="67" splitType="Stretch">
            <subreport>
                <reportElement x="0" y="0" width="555" height="66" uuid="27c682e0-71b6-4232-8a7a-9efaad62240f"/>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_MAIN">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_MAIN}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_SUB">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_SUB}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\MemberCertificate\\MemberCertificateAddress.jasper"]]></subreportExpression>
            </subreport>
        </band>
        <band height="68">
            <subreport>
                <reportElement x="0" y="0" width="555" height="67" uuid="169130d8-125e-45c4-b455-4cdced7665d1"/>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_MAIN">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_MAIN}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_SUB">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_SUB}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\MemberCertificate\\MemberCertificateInfo.jasper"]]></subreportExpression>
            </subreport>
        </band>
        <band height="56">
            <subreport>
                <reportElement x="0" y="0" width="555" height="55" uuid="f36d8a91-96b9-44fc-a393-bbc5752b5316"/>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_MAIN">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_MAIN}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_SUB">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_SUB}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\MemberCertificate\\MemberCertificateIsuranceObligation.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>
</code>```

I  have a JasperReports's report with several subreports. I'm using iReport plugin with my NetBeans. I have passed the same integer parameter type to all sub reports and also to main report . Main report has two parameter , one that has prompt option enabled and is of type string. and the other that takes parameter as a string and coverts it to integer Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN}) ( this is found in all sub reports  ). This is how i always pass parameters. But when i run this report i get the following errors.

Error filling print... Error evaluating expression :
      Source text : Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})  net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
      Source text : Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})      at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:244)
      at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:591)
      at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:559)
      at net.sf.jasperreports.engine.fill.JRFillDataset.setFillParameterValues(JRFillDataset.java:994)
      at net.sf.jasperreports.engine.fill.JRFillDataset.setParameterValues(JRFillDataset.java:635)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1280)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:900)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:845)
      at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:87)
      at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:446)
      at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:276)
      at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:745)
      at com.jaspersoft.ireport.designer.compiler.IReportCompiler.run(IReportCompiler.java:891)
      at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1443)
      at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:68)
      at org.openide.util.lookup.Lookups.executeWith(Lookups.java:303)      at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2058)
  Caused by: java.lang.NumberFormatException: null
      at java.lang.Integer.parseInt(Integer.java:542)      at java.lang.Integer.parseInt(Integer.java:615)

答:
The problem is that you declared

```<code><parameter name="MEMBER_CERTIFICATE_PARAM_SUB"...>
</code>```

with default value

```<code><defaultValueExpression><![CDATA[Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})]]></defaultValueExpression>
</code>```

before even declaring what $P{MEMBER_CERTIFICATE_PARAM_MAIN} is. It turns out that file is being read from the beginning and all expressions are evaluating at the time they are read. At time of evaluating "MEMBER_CERTIFICATE_PARAM_SUB" report didn't know what $P{MEMBER_CERTIFICATE_PARAM_MAIN} is.

Body:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="null" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0" uuid="478ce75d-1606-47d2-88eb-f8079f50c69b">
    <parameter name="SUBREPORT_DIR" class="java.lang.String" isForPrompting="false">
        <defaultValueExpression><![CDATA["D:\\newpackage\\"]]></defaultValueExpression>
    </parameter>
    <parameter name="MEMBER_CERTIFICATE_PARAM_SUB" class="java.lang.Integer" isForPrompting="false">
        <defaultValueExpression><![CDATA[Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})]]></defaultValueExpression>
    </parameter>
    <parameter name="MEMBER_CERTIFICATE_PARAM_MAIN" class="java.lang.String">
        <defaultValueExpression><![CDATA[]]></defaultValueExpression>
    </parameter>
    <queryString>
        <![CDATA[SELECT * FROM table_name WHERE atr = $P{MEMBER_CERTIFICATE_PARAM_SUB}]]>
    </queryString>
    <field name="national_id_number" class="java.lang.String"/>
    <field name="national_pin_number" class="java.lang.String"/>
    <field name="contact_email" class="java.lang.String"/>
    <field name="biometric_member_number" class="java.lang.String"/>
    <title>
        <band height="74" splitType="Stretch">
            <subreport>
                <reportElement x="0" y="0" width="555" height="72" uuid="2cee9cb2-abe3-4739-9b64-ec405bf9912b"/>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\DOCUMENTS\\NetBeansProjects\\NhifHeader\\src\\nhifheader\\PotraitNhifHeader\\PortraitNhifHeader.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </title>
    <pageHeader>
        <band height="56" splitType="Stretch">
            <textField>
                <reportElement x="529" y="13" width="26" height="15" uuid="1d23b617-b659-4f87-acfd-e07b54913ccd"/>
                <textFieldExpression><![CDATA[$F{national_pin_number}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="367" y="13" width="173" height="15" uuid="e02099fe-b171-4a24-bb15-195a046921c8"/>
                <textElement>

                </textElement>
                <text><![CDATA[Personal Identification Number:]]></text>
            </staticText>
            <componentElement>
                <reportElement x="0" y="1" width="240" height="30" uuid="311343bc-7e09-4658-8a1e-810fe91d1a3f"/>
                <jr:Code39 xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" textPosition="bottom">
                    <jr:codeExpression><![CDATA[$F{biometric_member_number}]]></jr:codeExpression>
                </jr:Code39>
            </componentElement>
            <staticText>
                <reportElement x="367" y="0" width="31" height="15" uuid="fefca1d6-a90f-4dba-996c-1c00883eba1c"/>
                <textElement>

                </textElement>
                <text><![CDATA[Date]]></text>
            </staticText>
            <textField pattern="MMMMM dd, yyyy">
                <reportElement x="398" y="0" width="142" height="20" uuid="c3c68a84-f1d6-43c9-9c83-8b5eaacd6c38"/>
                <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
            </textField>
            <line>
                <reportElement x="0" y="33" width="555" height="1" forecolor="#E6DAC3" backcolor="#E6DAC3" uuid="003310a9-85b0-447a-bc29-8f97f0006c1d"/>
            </line>
            <staticText>
                <reportElement x="2" y="35" width="553" height="20" uuid="5d8caf66-df88-403d-b96a-1ba2d0e84087"/>
                <textElement textAlignment="Center"/>
                <text><![CDATA[This is to certify that person shown herein is a member of NHIF: National Hospital Insurance Fund]]></text>
            </staticText>
            <frame>
                <reportElement mode="Opaque" x="179" y="1" width="172" height="21" forecolor="#C0C0C0" backcolor="#C0C0C0" uuid="63309c64-53a9-41e7-b490-fa5278230357"/>
                <staticText>
                    <reportElement mode="Transparent" x="33" y="0" width="113" height="20" forecolor="#000000" backcolor="#000000" uuid="ca2b9d0e-5260-4fb3-9f20-308a4349852e"/>
                    <textElement>

                    </textElement>
                    <text><![CDATA[Member Certificate]]></text>
                </staticText>
            </frame>
        </band>
    </pageHeader>
    <detail>
        <band height="67" splitType="Stretch">
            <subreport>
                <reportElement x="0" y="0" width="555" height="66" uuid="27c682e0-71b6-4232-8a7a-9efaad62240f"/>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_MAIN">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_MAIN}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_SUB">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_SUB}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\MemberCertificate\\MemberCertificateAddress.jasper"]]></subreportExpression>
            </subreport>
        </band>
        <band height="68">
            <subreport>
                <reportElement x="0" y="0" width="555" height="67" uuid="169130d8-125e-45c4-b455-4cdced7665d1"/>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_MAIN">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_MAIN}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_SUB">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_SUB}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\MemberCertificate\\MemberCertificateInfo.jasper"]]></subreportExpression>
            </subreport>
        </band>
        <band height="56">
            <subreport>
                <reportElement x="0" y="0" width="555" height="55" uuid="f36d8a91-96b9-44fc-a393-bbc5752b5316"/>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_MAIN">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_MAIN}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="MEMBER_CERTIFICATE_PARAM_SUB">
                    <subreportParameterExpression><![CDATA[$P{MEMBER_CERTIFICATE_PARAM_SUB}]]></subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="SUBREPORT_DIR">
                    <subreportParameterExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <subreportExpression><![CDATA["D:\\MemberCertificate\\MemberCertificateIsuranceObligation.jasper"]]></subreportExpression>
            </subreport>
        </band>
    </detail>
</jasperReport>

I  have a JasperReports's report with several subreports. I'm using iReport plugin with my NetBeans. I have passed the same integer parameter type to all sub reports and also to main report . Main report has two parameter , one that has prompt option enabled and is of type string. and the other that takes parameter as a string and coverts it to integer Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN}) ( this is found in all sub reports  ). This is how i always pass parameters. But when i run this report i get the following errors.

Error filling print... Error evaluating expression :
      Source text : Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})  net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression :
      Source text : Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})      at net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:244)
      at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:591)
      at net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:559)
      at net.sf.jasperreports.engine.fill.JRFillDataset.setFillParameterValues(JRFillDataset.java:994)
      at net.sf.jasperreports.engine.fill.JRFillDataset.setParameterValues(JRFillDataset.java:635)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.setParameters(JRBaseFiller.java:1280)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:900)
      at net.sf.jasperreports.engine.fill.JRBaseFiller.fill(JRBaseFiller.java:845)
      at net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:87)
      at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:446)
      at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:276)
      at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:745)
      at com.jaspersoft.ireport.designer.compiler.IReportCompiler.run(IReportCompiler.java:891)
      at org.openide.util.RequestProcessor$Task.run(RequestProcessor.java:1443)
      at org.netbeans.modules.openide.util.GlobalLookup.execute(GlobalLookup.java:68)
      at org.openide.util.lookup.Lookups.executeWith(Lookups.java:303)      at org.openide.util.RequestProcessor$Processor.run(RequestProcessor.java:2058)
  Caused by: java.lang.NumberFormatException: null
      at java.lang.Integer.parseInt(Integer.java:542)      at java.lang.Integer.parseInt(Integer.java:615)

Body:
The problem is that you declared

<parameter name="MEMBER_CERTIFICATE_PARAM_SUB"...>

with default value

<defaultValueExpression><![CDATA[Integer.parseInt($P{MEMBER_CERTIFICATE_PARAM_MAIN})]]></defaultValueExpression>

before even declaring what $P{MEMBER_CERTIFICATE_PARAM_MAIN} is. It turns out that file is being read from the beginning and all expressions are evaluating at the time they are read. At time of evaluating "MEMBER_CERTIFICATE_PARAM_SUB" report didn't know what $P{MEMBER_CERTIFICATE_PARAM_MAIN} is.


问:
Adding images dynamically to photoswipe
Is there a way to add images dynamically to a photoswipe gallery after it is created.

The situation is this.

I'm fetching image urls from the sever and showing them in a gallery.  As the items are downloaded the anchor and img elements are added to the page.  I would like to be able to at that same time append each to the photoswipe gallery.

currently in the element callback (after the image has been loaded and elements appended) I have

```<code> $elements.photoSwipe({ enableMouseWheel: false , enableKeyboard: false });
</code>```

This works except it creates each element in it's own gallery.  Is there a way to get a handle to an existing gallery and just append to it?

答:
I have committed a pull request for PhotoSwipe

Pull Request

If you do have such need to dynamic prepend/append/remove items without change the state of the current item, you can use this version.

Title: Adding images dynamically to photoswipe

Body:
Is there a way to add images dynamically to a photoswipe gallery after it is created.

The situation is this.

I'm fetching image urls from the sever and showing them in a gallery.  As the items are downloaded the anchor and img elements are added to the page.  I would like to be able to at that same time append each to the photoswipe gallery.

currently in the element callback (after the image has been loaded and elements appended) I have

 $elements.photoSwipe({ enableMouseWheel: false , enableKeyboard: false });

This works except it creates each element in it's own gallery.  Is there a way to get a handle to an existing gallery and just append to it?


问:
Azure AD How to get the Tenant Id from the user when he authenticated to our application
I've created an Asp.net application with Azure Active Directory authentication by using OAuth2 and working as expected.

Now when the user login to my application, I'm getting the user data like User Email id and provider key

Now the requirement is, I need to get user tenant Id from the response.

Is there any chance to get the user tenant id from the response?

Here I'm using GetExternalLoginInfoAsync() to get the authenticated user data.

```<code>  private IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }
   var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
</code>```

Appreciate your help.

答:
Now the requirement is, I need to get user tenant Id from the response.

loginInfo.Login.LoginProvider would look like as follows:

```<code>https://sts.windows.net/{tenant-Id}/
</code>```

Or you could retrieve the tenant Id via the following code snippet:

```<code>var tenantId = loginInfo.ExternalIdentity.FindFirst(c => c.Type == "http://schemas.microsoft.com/identity/claims/tenantid").Value;
</code>```

and make sure that your application should have the following permissions:
1) Read directory data
2) Read all users full profiles
3) Sign in and read user profile

Body:
I've created an Asp.net application with Azure Active Directory authentication by using OAuth2 and working as expected.

Now when the user login to my application, I'm getting the user data like User Email id and provider key

Now the requirement is, I need to get user tenant Id from the response.

Is there any chance to get the user tenant id from the response?

Here I'm using GetExternalLoginInfoAsync() to get the authenticated user data.

  private IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }
   var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

Appreciate your help.

Body:
Now the requirement is, I need to get user tenant Id from the response.

loginInfo.Login.LoginProvider would look like as follows:

https://sts.windows.net/{tenant-Id}/

Or you could retrieve the tenant Id via the following code snippet:

var tenantId = loginInfo.ExternalIdentity.FindFirst(c => c.Type == "http://schemas.microsoft.com/identity/claims/tenantid").Value;

and make sure that your application should have the following permissions:
1) Read directory data
2) Read all users full profiles
3) Sign in and read user profile


答:
Because variable total is undefined. Make sure your total var is something like var total And in addition to that

There should be elements with Id's A,B,C,Total somewhere in document , As you are doing some operation on DOM which isn't in DOM.

parseInt() if u want to add numbers otherwise it was ok.
Hope this will work.

var a;
var b;
var c;
var total;

var scorecard = function()
    {
    a = parseInt(prompt("What was your score on a?","A"));//parseInt() if u want to add numbers otherwise it was ok.
    b = parseInt(prompt("What was your score on b?","B"));
    c = parseInt(prompt("What was your score on c?","C"));
    total = (a + b + c);
    document.getElementById("A").innerHTML = a; //There should be elements with Id's A,B,C,Total somewhere in document.
    document.getElementById("B").innerHTML = b;
    document.getElementById("C").innerHTML = c;
    document.getElementById("Total").innerHTML = total;
    };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="scoreButton"><button onclick="javascript: scorecard();">Calculate Score</button></div>
 <div id = "A"></div>
  <div id = "B"></div>
   <div id = "C"></div>
    <div id = "Total"></div></code>```

Title: HTML onclick button not calling javascript function

Body:
Because variable total is undefined. Make sure your total var is something like var total And in addition to that

There should be elements with Id's A,B,C,Total somewhere in document , As you are doing some operation on DOM which isn't in DOM.

parseInt() if u want to add numbers otherwise it was ok.
Hope this will work.

var a;
var b;
var c;
var total;

var scorecard = function()
    {
    a = parseInt(prompt("What was your score on a?","A"));//parseInt() if u want to add numbers otherwise it was ok.
    b = parseInt(prompt("What was your score on b?","B"));
    c = parseInt(prompt("What was your score on c?","C"));
    total = (a + b + c);
    document.getElementById("A").innerHTML = a; //There should be elements with Id's A,B,C,Total somewhere in document.
    document.getElementById("B").innerHTML = b;
    document.getElementById("C").innerHTML = c;
    document.getElementById("Total").innerHTML = total;
    };

<div id="scoreButton"><button onclick="javascript: scorecard();">Calculate Score</button></div>
 <div id = "A"></div>
  <div id = "B"></div>
   <div id = "C"></div>
    <div id = "Total"></div>


问:
A new table in R based on fields and data from existing one
I need to raise the question again as it was closed as duplicated, but the issue hasn't been resolved.

So, I'm working on international trade data and have the following table at the moment with 5 different values for commodity_code (commod_codes = c('85','84','87','73','29')):

```<code>year trade_flow reporter partner commodity_code                 commodity trade_value_usd
1 2012     Import  Belarus   China             29         Organic chemicals       150863100
2 2013     Import  Belarus   China             29         Organic chemicals       151614000
3 2014     Import  Belarus   China             29         Organic chemicals        73110200
4 2015     Import  Belarus   China             29         Organic chemicals       140396300
5 2016     Import  Belarus   China             29         Organic chemicals       135311600
6 2012     Import  Belarus   China             73 Articles of iron or steel       100484600
</code>```

I need to create a new table that looks simple (commodity codes in top row, years in first column and corresponding trade values in cells):

```<code>year             commodity_code
             29   73  84  85  87
1998        value1      ...   value 5
1999
…
2016
</code>```

* I used reshape() but didn't succeed.

Would appreciate your support.

答:
Provided I understood you correctly, here is a one-liner in base R.

```<code>xtabs(trade_value_usd ~ year + commodity_code, data = df);
#year          29        73
#  2012 150863100 100484600
#  2013 151614000         0
#  2014  73110200         0
#  2015 140396300         0
#  2016 135311600         0
</code>```

Explanation: Use xtabs to cross-tabulate trade_value_usd as a function of year (rows) and commodity_code (columns).

Sample data

```<code>df <- read.table(text =
    "year trade_flow reporter partner commodity_code                 commodity trade_value_usd
1 2012     Import  Belarus   China             29         'Organic chemicals'       150863100
2 2013     Import  Belarus   China             29         'Organic chemicals'       151614000
3 2014     Import  Belarus   China             29         'Organic chemicals'        73110200
4 2015     Import  Belarus   China             29         'Organic chemicals'       140396300
5 2016     Import  Belarus   China             29         'Organic chemicals'       135311600
6 2012     Import  Belarus   China             73 'Articles of iron or steel'       100484600
", header = T, row.names = 1)
</code>```

Body:
I need to raise the question again as it was closed as duplicated, but the issue hasn't been resolved.

So, I'm working on international trade data and have the following table at the moment with 5 different values for commodity_code (commod_codes = c('85','84','87','73','29')):

year trade_flow reporter partner commodity_code                 commodity trade_value_usd
1 2012     Import  Belarus   China             29         Organic chemicals       150863100
2 2013     Import  Belarus   China             29         Organic chemicals       151614000
3 2014     Import  Belarus   China             29         Organic chemicals        73110200
4 2015     Import  Belarus   China             29         Organic chemicals       140396300
5 2016     Import  Belarus   China             29         Organic chemicals       135311600
6 2012     Import  Belarus   China             73 Articles of iron or steel       100484600

I need to create a new table that looks simple (commodity codes in top row, years in first column and corresponding trade values in cells):

year             commodity_code
             29   73  84  85  87
1998        value1      ...   value 5
1999
…
2016

* I used reshape() but didn't succeed.

Would appreciate your support.

Body:
Provided I understood you correctly, here is a one-liner in base R.

xtabs(trade_value_usd ~ year + commodity_code, data = df);
#year          29        73
#  2012 150863100 100484600
#  2013 151614000         0
#  2014  73110200         0
#  2015 140396300         0
#  2016 135311600         0

Explanation: Use xtabs to cross-tabulate trade_value_usd as a function of year (rows) and commodity_code (columns).

Sample data

df <- read.table(text =
    "year trade_flow reporter partner commodity_code                 commodity trade_value_usd
1 2012     Import  Belarus   China             29         'Organic chemicals'       150863100
2 2013     Import  Belarus   China             29         'Organic chemicals'       151614000
3 2014     Import  Belarus   China             29         'Organic chemicals'        73110200
4 2015     Import  Belarus   China             29         'Organic chemicals'       140396300
5 2016     Import  Belarus   China             29         'Organic chemicals'       135311600
6 2012     Import  Belarus   China             73 'Articles of iron or steel'       100484600
", header = T, row.names = 1)


问:
Retrieve and print data from dynamic sql query with linq
I have some existing code that retrieves data from a database using ADO.NET that I want to convert to linq.

What the code does is receives an SQL query via command line, executes it, returns the rows and their column names, then prints them to the screen.  I would like to know how to write this code in linq.

The ENTIRE sql query MUST be given via command line since I want to limit where I select rows from.  This is the only way I want it done, so unless if you have a method that can work this way, I cannot use it.  No one will have access to the program aside from myself, so security is NOT an issue.

```<code>private static SqlConnection sqlConnection = new SqlConnection();

private static void OConnection()
{
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = MyConsoleApp.Properties.Settings.Default.ConnStr;
    sqlConnection.Open();
}
</code>```

...

```<code>string query = Console.ReadLine();
OpenConn();
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader reader = command.ExecuteReader();

if (reader != null)
{
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.Write("| {0}: {1}", reader.GetName(i), reader.GetValue(i));
        }
        Console.WriteLine();
    }
}
</code>```

答:
You can add stored procedures to your database, and then add them into linq.  Linq provides nice code generation to deal with your stored procedures getting and returning rows using deferred execution.

If you have a dynamic query that you wish to execute that isn't a stored procedure then you will need to either stick with ADO.Net or learn how to express your query in LINQ.  Perhaps if you provide the query we could help you do this with your data context.

PS. When we moved to LINQ I found that the amount of boilerplate ADO.Net code we had to write dropped dramatically.  I wrote my SPRoc mapped it to sql and used it straight away :).

OwnerDisplayName: Noit

Body:
I have some existing code that retrieves data from a database using ADO.NET that I want to convert to linq.

What the code does is receives an SQL query via command line, executes it, returns the rows and their column names, then prints them to the screen.  I would like to know how to write this code in linq.

The ENTIRE sql query MUST be given via command line since I want to limit where I select rows from.  This is the only way I want it done, so unless if you have a method that can work this way, I cannot use it.  No one will have access to the program aside from myself, so security is NOT an issue.

private static SqlConnection sqlConnection = new SqlConnection();

private static void OConnection()
{
    sqlConnection = new SqlConnection();
    sqlConnection.ConnectionString = MyConsoleApp.Properties.Settings.Default.ConnStr;
    sqlConnection.Open();
}

...

string query = Console.ReadLine();
OpenConn();
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader reader = command.ExecuteReader();

if (reader != null)
{
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            Console.Write("| {0}: {1}", reader.GetName(i), reader.GetValue(i));
        }
        Console.WriteLine();
    }
}

OwnerDisplayName: Spence


问:
Changing A* to dijkstra's
```<code>function A*(start, goal)

closedSet := {}

openSet := {start}

cameFrom := an empty map

gScore := map with default value of Infinity

gScore[start] := 0

fScore := map with default value of Infinity

fScore[start] := heuristic_cost_estimate(start, goal)

while openSet is not empty
    current := the node in openSet having the lowest fScore[] value
    if current = goal
        return reconstruct_path(cameFrom, current)

    openSet.Remove(current)
    closedSet.Add(current)

    for each neighbor of current
        if neighbor in closedSet
            continue

        if neighbor not in openSet
            openSet.Add(neighbor)

        tentative_gScore := gScore[current] + dist_between(current, neighbor)
        if tentative_gScore >= gScore[neighbor]
            continue

        cameFrom[neighbor] := current
        gScore[neighbor] := tentative_gScore
        fScore[neighbor] := gScore[neighbor] + heuristic_cost_estimate(neighbor, goal)

return failure

function reconstruct_path(cameFrom, current)
total_path := [current]
while current in cameFrom.Keys:
    current := cameFrom[current]
    total_path.append(current)
return total_path
</code>```

If I were to take this A* alorgithim and instead of taking the lowest fScore from openset, take the lowest gscore and not even consider the fScore would that effectively make this dijksta's?

答:
Dijkstra's shortest path algorithm is a special case for A* in which the heuristic is zero although Dijkstra's algorithm (1958) was conceived before 10 years. A* greedily chooses which vertex to look next during search according to f(v), where f(v) = h(v) + g(v). If you set the heuristic (h(v)) to zero, A* becomes to choose vertices considering only the current cost (g(v)), and you achieve to transform informed A* into non-informed Dijkstra.

In short, my answer to your question is "Yes".

Title: Changing A* to dijkstra's

Body:
function A*(start, goal)

closedSet := {}

openSet := {start}

cameFrom := an empty map

gScore := map with default value of Infinity

gScore[start] := 0

fScore := map with default value of Infinity

fScore[start] := heuristic_cost_estimate(start, goal)

while openSet is not empty
    current := the node in openSet having the lowest fScore[] value
    if current = goal
        return reconstruct_path(cameFrom, current)

    openSet.Remove(current)
    closedSet.Add(current)

    for each neighbor of current
        if neighbor in closedSet
            continue

        if neighbor not in openSet
            openSet.Add(neighbor)

        tentative_gScore := gScore[current] + dist_between(current, neighbor)
        if tentative_gScore >= gScore[neighbor]
            continue

        cameFrom[neighbor] := current
        gScore[neighbor] := tentative_gScore
        fScore[neighbor] := gScore[neighbor] + heuristic_cost_estimate(neighbor, goal)

return failure

function reconstruct_path(cameFrom, current)
total_path := [current]
while current in cameFrom.Keys:
    current := cameFrom[current]
    total_path.append(current)
return total_path

If I were to take this A* alorgithim and instead of taking the lowest fScore from openset, take the lowest gscore and not even consider the fScore would that effectively make this dijksta's?


问:
php show array value for variable key
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

```<code>$fr=array();

$fr['hello']="Bonjour";
</code>```

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

```<code>echo $$language[$word];
</code>```

any ideas?
thank you

答:
By default, variables are local to a function. If your dictionary arrays are global, you need to declare them as global, but since the names are variable, you have to access them via $GLOBALS:

```<code>function foo($word, $language) {
  echo $GLOBALS[$language][$word];
}
</code>```

As for a better way, you might want to use just one multi-dimensional array instead of creating one variable for each language:

```<code>$dict = array();
$dict['fr']['hello'] = 'Bonjour';

function foo($word, $language) {
  global $dict;
  echo $dict[$language][$word];
}
</code>```

Title: php show array value for variable key

Body:
I am trying to make a site multi lingual. by building a language dictionary array ( if it is not the best way please don't hesitate to let me know )

$fr=array();

$fr['hello']="Bonjour";

I would like to make a function that does the following :

for every word and language  function ( $word ="hello",$language="fr")

it would return the right value. So far the way I am doing isn't working

echo $$language[$word];

any ideas?
thank you

Body:
By default, variables are local to a function. If your dictionary arrays are global, you need to declare them as global, but since the names are variable, you have to access them via $GLOBALS:

function foo($word, $language) {
  echo $GLOBALS[$language][$word];
}

As for a better way, you might want to use just one multi-dimensional array instead of creating one variable for each language:

$dict = array();
$dict['fr']['hello'] = 'Bonjour';

function foo($word, $language) {
  global $dict;
  echo $dict[$language][$word];
}


问:
How to round to at most 2 decimal places, if necessary
I'd like to round at most two decimal places, but only if necessary.

Input:

```<code>10
1.7777777
9.1
</code>```

Output:

```<code>10
1.78
9.1
</code>```

How can I do this in JavaScript?

答:
I know there are many answers, but most of them have side effect in some specific cases.

Easiest and shortest solution without any side effects is following:

```<code>Number((2.3456789).toFixed(2)) // 2.35
</code>```

It rounds properly and returns number instead of string

```<code>console.log(Number((2.345).toFixed(2)))  // 2.35
console.log(Number((2.344).toFixed(2)))  // 2.34
console.log(Number((2).toFixed(2)))      // 2
console.log(Number((-2).toFixed(2)))     // -2
console.log(Number((-2.345).toFixed(2))) // -2.35

console.log(Number((2.345678).toFixed(3))) // 2.346
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to round at most two decimal places, but only if necessary.

Input:

10
1.7777777
9.1

Output:

10
1.78
9.1

How can I do this in JavaScript?

Body:
I know there are many answers, but most of them have side effect in some specific cases.

Easiest and shortest solution without any side effects is following:

Number((2.3456789).toFixed(2)) // 2.35

It rounds properly and returns number instead of string

console.log(Number((2.345).toFixed(2)))  // 2.35
console.log(Number((2.344).toFixed(2)))  // 2.34
console.log(Number((2).toFixed(2)))      // 2
console.log(Number((-2).toFixed(2)))     // -2
console.log(Number((-2.345).toFixed(2))) // -2.35

console.log(Number((2.345678).toFixed(3))) // 2.346


问:
How can I get username or id of currently logged in user in UWP App
I found this article: Get The Username/User Id Of Currently Logged In User In A UWP App

to get the username of current user logged in in uwp app , but when I tried the accepted answer , it returns null/empty , is there any updated version of that?

NOTE: Iam using a microsoft account

UPDATE: All properties from "KnownUserProperties" returns empty string except for "First Name" & "Last Name"

Thanks

答:
Did enable the User Account Information in the package.appxmanifest ?

Here is the image which shows the manifest file.


答:
Multiple issues with your code

It should be var total instead of total

Elements like A, B, C and Total which you are referencing in your code are missing

You need to convert the values to number as well.

Demo

var a;
var b;
var c;
var total;

var scorecard = function() {
  a = +prompt("What was your score on a?", "A");
  b = +prompt("What was your score on b?", "B");
  c = +prompt("What was your score on c?", "C");
  total = (a + b + c);
  document.getElementById("A").innerHTML = a;
  document.getElementById("B").innerHTML = b;
  document.getElementById("C").innerHTML = c;
  document.getElementById("Total").innerHTML = total;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code>A : <div id="A"></div> <br>
B : <div id="B"></div> <br>
C : <div id="C"></div> <br>

Total : <div id="Total"></div> <br>
<div id="scoreButton"><button onclick="javascript: scorecard();">Calculate Score</button></div></code>```

Body:
Multiple issues with your code

It should be var total instead of total

Elements like A, B, C and Total which you are referencing in your code are missing

You need to convert the values to number as well.

Demo

var a;
var b;
var c;
var total;

var scorecard = function() {
  a = +prompt("What was your score on a?", "A");
  b = +prompt("What was your score on b?", "B");
  c = +prompt("What was your score on c?", "C");
  total = (a + b + c);
  document.getElementById("A").innerHTML = a;
  document.getElementById("B").innerHTML = b;
  document.getElementById("C").innerHTML = c;
  document.getElementById("Total").innerHTML = total;
};

A : <div id="A"></div> <br>
B : <div id="B"></div> <br>
C : <div id="C"></div> <br>

Total : <div id="Total"></div> <br>
<div id="scoreButton"><button onclick="javascript: scorecard();">Calculate Score</button></div>


问:
Can AES-256 work on Android Devices with API Level 26+?
So I'm trying to implement an AES-256 encryption/decryption to my Android application. However, I don't want to include extra jar to enable AES-256 as there are export control policies in place.

I found this in official documentation and it seems like API level 26+ supports AES-256 and AES-128, is there a way to use this algorithms in older API levels?

答:
All versions of AES have been supported on Android for a number of years now.  The policies you refer to are specific to the vanilla JVM, they aren't necessary on Android.  Construct your cipher object like so to use AES-256:</p>

```<code>byte[] key = ... // Your key material, exactly 32 bytes in length.
byte[] iv = ... // A randomly generated IV, exactly 16 bytes in length.
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKey(key, "AES"), new IvParameterSpec(iv));
</code>```

Body:
All versions of AES have been supported on Android for a number of years now.  The policies you refer to are specific to the vanilla JVM, they aren't necessary on Android.  Construct your cipher object like so to use AES-256:

byte[] key = ... // Your key material, exactly 32 bytes in length.
byte[] iv = ... // A randomly generated IV, exactly 16 bytes in length.
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKey(key, "AES"), new IvParameterSpec(iv));


问:
What are the advantages of developing applications in C++ as compared to managed languages?
Hi I want to know why people develop library applications and employee management applications in C++ (this application, for example), when clearly the same thing can be done in C# and VB.NET in a much prettier way. Even banking applications are mostly in C++. Is there a good reason why, apart from the fact that compiled C++ code executes faster?

Can anyone shed some light on this?

答:
Every language has its pros and cons and no one language is best for every application.  Programs in C++are harder to write, but can take advantage of platform-specific hardware and features.  Because they're compiled, they also tend to run a bit faster.  C# programs are easier to write, but aren't able to access underlying resources and can't be ported to non-Windows platforms very easily.

In short, it really depends on the application needs.  If you need raw speed and explicit resource management, go with C++.  If you want ease of coding and clarity, go with C#.


问:
Get first few elements of tuples from list of list of tuples
I have a structure of list of list of tuples like:-

```<code>[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]
</code>```

I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column.
Desired output:-

```<code>[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]
</code>```

&&

```<code>[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]
</code>```

How can this be done in python?

Body:
I have a structure of list of list of tuples like:-

[[(1, 1, 96),
  (1, 2, 95),
  (0, 5, 23),
  (0, 6, 22)],
 [(2, 1, 145),
  (1, 2, 144),
  (10, 3, 143),
  (2, 4, 142)]]

I basically want to obtain 2 list of list of tuples from this. One tuple for the first 2 columns, and the other tuple for the third column.
Desired output:-

[[(1, 1),
  (1, 2),
  (0, 5),
  (0, 6)],
 [(2, 1),
  (1, 2),
  (10, 3),
  (2, 4)]]

&&

[[(96,),
  (95,),
  (23,),
  (22,)],
 [(145,),
  (144,),
  (143,),
  (142,)]]

How can this be done in python?

Body:
Just keep it really simple, and loop over the nested list, and take what you need:

lst = [[(1, 1, 96),
        (1, 2, 95),
        (0, 5, 23),
        (0, 6, 22)],
       [(2, 1, 145),
        (1, 2, 144),
        (10, 3, 143),
        (2, 4, 142)]]

first = []
second = []

for l in lst:
    for tup in l:
        first.append(tup[:-1])
        second.append((tup[-1],))

print(first)
# [(1, 1), (1, 2), (0, 5), (0, 6), (2, 1), (1, 2), (10, 3), (2, 4)]
print(second)
# [(96,), (95,), (23,), (22,), (145,), (144,), (143,), (142,)]

Or with list comprehensions:

first = [tup[:-1] for l in lst for tup in l]
second = [(tup[-1],) for l in lst for tup in l]

Then turn these lists into 2 sublists each:

sublen = len(lst[0])

def split_lists(l, s):
    return [l[i:i+s] for i in range(0, len(l), s)]

print(split_lists(first, sublen))
# [[(1, 1), (1, 2), (0, 5), (0, 6)], [(2, 1), (1, 2), (10, 3), (2, 4)]]

print(split_lists(second, sublen))
# [[(96,), (95,), (23,), (22,)], [(145,), (144,), (143,), (142,)]]


问:
Defining aliases in Cygwin under Windows
I am trying to define some aliases in cygwin, but with no success. I am doing so like this at the end of the .bashrc file.

```<code>alias foo='pwd'
</code>```

I have tried to add this line in a .bashrc file in both inside the home folder of cygwin and in the home folder for the Windows user I am on C:\Users\Nuno\. In both cases I have just appended this line to a copy of the /etc/skel/.bashrc file. In either cases, it didn't work.

I had this working before. I had to reinstall Cygwin and ever since it never worked properly again. I have removed all files (or at least think so, when doing the reinstallation). I have also noticed that in the first install (when it was working) cygwin already was creating .bash files in the home folder. Now, it doesn't.

I am on a machine running Windows 7.

EDIT: My cygwin home folder is set to the Windows home folder C:\Users\Nuno\. I have placed what I think is a valid .bashrc file there, but it still doesn't work.

Thanks in advance.

答:
It works as explained from cygwin:

Create a file ".profile" in your windows home dir. This will load every time when you start cygwin.

You can edit the file with your alias or you can source the .bashrc.

If you'll source, insert "source .bashrc" and save .bashrc also in your windows home dir.
Now you can start editing the .bashrc.

Body:
I am trying to define some aliases in cygwin, but with no success. I am doing so like this at the end of the .bashrc file.

alias foo='pwd'

I have tried to add this line in a .bashrc file in both inside the home folder of cygwin and in the home folder for the Windows user I am on C:\Users\Nuno\. In both cases I have just appended this line to a copy of the /etc/skel/.bashrc file. In either cases, it didn't work.

I had this working before. I had to reinstall Cygwin and ever since it never worked properly again. I have removed all files (or at least think so, when doing the reinstallation). I have also noticed that in the first install (when it was working) cygwin already was creating .bash files in the home folder. Now, it doesn't.

I am on a machine running Windows 7.

EDIT: My cygwin home folder is set to the Windows home folder C:\Users\Nuno\. I have placed what I think is a valid .bashrc file there, but it still doesn't work.

Thanks in advance.


问:
How to make git print paths with back slashes instead of forward slashes in a Windows console
Is it possible to make git print back slashes instead of forward slashes when it prints out paths in a Windows console? I'd like to be able to copy the paths that it outputs and paste it into my future console commands.

Example output:

```<code>C:\vna>git status
On branch herpderp
Your branch is up-to-date with 'origin/herpyderp'.
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Java/HerpDerp/src
    Java/HerpDerp/src/main/java/com/derp/messaging/
    Java/HerpDerp/src/main/java/com/derp/controller/event/
    Java/HerpDerp/src/main/java/com/derp/controller/domain/
    Java/HerpDerp/src/main/java/com/derp/controller/monitor/

nothing added to commit but untracked files present (use "git add" to track)
</code>```

Instead of

```<code>Java/HerpDerp/src/main/java/com/derp/messaging/
</code>```

I'd like to see

```<code>Java\HerpDerp\src\main\java\com\derp\messaging\
</code>```

or even

```<code>Java\\HerpDerp\\src\\main\\java\\com\\derp\\messaging\\
</code>```

Edit: I should have clarified that this was for working with git in a Windows console. Also, it seems the correct answer for my case is to use Git Bash.

答:
I know it's a little old, but you can use environment variable substitution to replace the / with \ or \\:

```<code>C:\> SET FILE=Java/HerpDerp/src
C:\> ECHO %FILE:/=\%
Java\HerpDerp\src

C:\> ECHO %FILE:/=\\%
Java\\HerpDerp\\src

C:\>
</code>```

To take it a step further, you can write a batch file that does it for a command that outputs a bunch of paths:  (git diff --name-only HEAD~1 in the following example)

```<code>SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "usebackq delims=" %%i IN (`git diff --name-only HEAD~1`) DO (
  SET FILE=%%i
  ECHO !FILE:/=\!
)
ENDLOCAL
</code>```

Body:
Is it possible to make git print back slashes instead of forward slashes when it prints out paths in a Windows console? I'd like to be able to copy the paths that it outputs and paste it into my future console commands.

Example output:

C:\vna>git status
On branch herpderp
Your branch is up-to-date with 'origin/herpyderp'.
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Java/HerpDerp/src
    Java/HerpDerp/src/main/java/com/derp/messaging/
    Java/HerpDerp/src/main/java/com/derp/controller/event/
    Java/HerpDerp/src/main/java/com/derp/controller/domain/
    Java/HerpDerp/src/main/java/com/derp/controller/monitor/

nothing added to commit but untracked files present (use "git add" to track)

Instead of

Java/HerpDerp/src/main/java/com/derp/messaging/

I'd like to see

Java\HerpDerp\src\main\java\com\derp\messaging\

or even

Java\\HerpDerp\\src\\main\\java\\com\\derp\\messaging\\

Edit: I should have clarified that this was for working with git in a Windows console. Also, it seems the correct answer for my case is to use Git Bash.

Body:
I know it's a little old, but you can use environment variable substitution to replace the / with \ or \\:

C:\> SET FILE=Java/HerpDerp/src
C:\> ECHO %FILE:/=\%
Java\HerpDerp\src

C:\> ECHO %FILE:/=\\%
Java\\HerpDerp\\src

C:\>

To take it a step further, you can write a batch file that does it for a command that outputs a bunch of paths:  (git diff --name-only HEAD~1 in the following example)

SETLOCAL ENABLEDELAYEDEXPANSION
FOR /F "usebackq delims=" %%i IN (`git diff --name-only HEAD~1`) DO (
  SET FILE=%%i
  ECHO !FILE:/=\!
)
ENDLOCAL


问:
C# Serial DataReceived Event Invoke Function Not Working Properly
I make a winform program to read data from serial port and display it in textbox. The data will be sent from external device at every 5 sec interval. The first data is "1 followed by "2" and then "3" and repeat the same pattern forever.

I will make pictureBox1, pictureBox2, pictureBox3  visisble and play gif when data "1", "2" and "3" received respectively.  The problem is sometime the pictureBox does not switch to the next respective one even though the next data has arrived.  I am not sure whether I am using the invoke function correctly?

```<code>public Form1()
{
    InitializeComponent();
    SerialPortProgram();
    pictureBox1.Image=
    Image.FromFile(@"C:\Users\user\Downloads\Gif#1.gif");
    pictureBox2.Image =
    Image.FromFile(@"C:\Users\user\Downloads\Gif#2.gif");
    pictureBox3.Image =
    Image.FromFile(@"C:\Users\user\Downloads\Gif#3.gif");
}

// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM17", 9600, Parity.None, 8, StopBits.One);

private void SerialPortProgram()
{
    // Attach a method to be called when there
    // is data waiting in the port's buffer
    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

    // Begin communications
    port.Open();

    // Enter an application loop to keep this thread alive
    // Application.Run();        // if this Application.Run() is not commented out, Form1 will not be displayed
}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Show all the incoming data in the port's buffer
    string data = (port.ReadExisting());
    Log(data);
    if (data == "1")
    {
        gif1Showl();
    }

    if (data == "2")
    {
        gif2Show();
    }

    if (data == "3")
    {
        gif3Show();
    }
}

private void Log(string msg)
{
    textBox1.Invoke(new EventHandler(delegate
    {
        textBox1.AppendText(msg);
    }));
}

private void gif1Showl()
{
    this.Invoke(new ThreadStart(() =>
    {
        pictureBox1.Visible = true;
        pictureBox1.Enabled = true;
        pictureBox2.Visible = false;
        pictureBox2.Enabled = false;
        pictureBox3.Visible = false;
        pictureBox3.Enabled = false;
    }));
}

private void gif2Show()
{
    this.Invoke(new ThreadStart(() =>
    {
        pictureBox1.Visible = false;
        pictureBox1.Enabled = false;
        pictureBox2.Visible = true;
        pictureBox2.Enabled = true;
        pictureBox3.Visible = false;
        pictureBox3.Enabled = false;
    }));
}

private void gif3Show()
{
    this.Invoke(new ThreadStart(() =>
    {
        pictureBox1.Visible = false;
        pictureBox1.Enabled = false;
        pictureBox2.Visible = false;
        pictureBox2.Enabled = false;
        pictureBox3.Visible = true;
        pictureBox3.Enabled = true;
    }));
}
</code>```

答:
You should check if invoking is needed and call your delegate. Creating a new thread to update the UI itself is wrong.</p>

```<code>MethodInvoker methodInvokerDelegate = delegate()
{
    pictureBox1.Visible = false;
    pictureBox1.Enabled = false;
    pictureBox2.Visible = false;
    pictureBox2.Enabled = false;
    pictureBox3.Visible = true;
    pictureBox3.Enabled = true;
};

//This will be true if Current thread is not UI thread.
if (this.InvokeRequired)
    this.Invoke(methodInvokerDelegate);
else
    methodInvokerDelegate();
</code>```

Body:
I make a winform program to read data from serial port and display it in textbox. The data will be sent from external device at every 5 sec interval. The first data is "1 followed by "2" and then "3" and repeat the same pattern forever.

I will make pictureBox1, pictureBox2, pictureBox3  visisble and play gif when data "1", "2" and "3" received respectively.  The problem is sometime the pictureBox does not switch to the next respective one even though the next data has arrived.  I am not sure whether I am using the invoke function correctly?

public Form1()
{
    InitializeComponent();
    SerialPortProgram();
    pictureBox1.Image=
    Image.FromFile(@"C:\Users\user\Downloads\Gif#1.gif");
    pictureBox2.Image =
    Image.FromFile(@"C:\Users\user\Downloads\Gif#2.gif");
    pictureBox3.Image =
    Image.FromFile(@"C:\Users\user\Downloads\Gif#3.gif");
}

// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM17", 9600, Parity.None, 8, StopBits.One);

private void SerialPortProgram()
{
    // Attach a method to be called when there
    // is data waiting in the port's buffer
    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

    // Begin communications
    port.Open();

    // Enter an application loop to keep this thread alive
    // Application.Run();        // if this Application.Run() is not commented out, Form1 will not be displayed
}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Show all the incoming data in the port's buffer
    string data = (port.ReadExisting());
    Log(data);
    if (data == "1")
    {
        gif1Showl();
    }

    if (data == "2")
    {
        gif2Show();
    }

    if (data == "3")
    {
        gif3Show();
    }
}

private void Log(string msg)
{
    textBox1.Invoke(new EventHandler(delegate
    {
        textBox1.AppendText(msg);
    }));
}

private void gif1Showl()
{
    this.Invoke(new ThreadStart(() =>
    {
        pictureBox1.Visible = true;
        pictureBox1.Enabled = true;
        pictureBox2.Visible = false;
        pictureBox2.Enabled = false;
        pictureBox3.Visible = false;
        pictureBox3.Enabled = false;
    }));
}

private void gif2Show()
{
    this.Invoke(new ThreadStart(() =>
    {
        pictureBox1.Visible = false;
        pictureBox1.Enabled = false;
        pictureBox2.Visible = true;
        pictureBox2.Enabled = true;
        pictureBox3.Visible = false;
        pictureBox3.Enabled = false;
    }));
}

private void gif3Show()
{
    this.Invoke(new ThreadStart(() =>
    {
        pictureBox1.Visible = false;
        pictureBox1.Enabled = false;
        pictureBox2.Visible = false;
        pictureBox2.Enabled = false;
        pictureBox3.Visible = true;
        pictureBox3.Enabled = true;
    }));
}

Body:
You should check if invoking is needed and call your delegate. Creating a new thread to update the UI itself is wrong.

MethodInvoker methodInvokerDelegate = delegate()
{
    pictureBox1.Visible = false;
    pictureBox1.Enabled = false;
    pictureBox2.Visible = false;
    pictureBox2.Enabled = false;
    pictureBox3.Visible = true;
    pictureBox3.Enabled = true;
};

//This will be true if Current thread is not UI thread.
if (this.InvokeRequired)
    this.Invoke(methodInvokerDelegate);
else
    methodInvokerDelegate();


问:
Python default (mutable) parameter initialization style
Let's have a function make_sandwich that takes a list of ingredients which has a default value of ['ham', 'ham', 'bacon', 'ham']

```<code>def make_sandwich(ingredients=['ham', 'ham', 'bacon', 'ham']):
    print("Making a sandwich with ", ingredients)
</code>```

However, since this default value is susceptible to this python "mutable default argument" <s>bug</s> feature, we should use an immutable instead like this:

```<code>def make_sandwich(ingredients=None):
    # initialized ingredients here
    print("Making a sandwich with ", ingredients)
</code>```

So here's the question. There're two ways that I am aware of to do this, but I am not sure which one is considered a better practice.

The first one:

```<code>if not ingredients:
    ingredients = ['ham', 'ham', 'bacon', 'ham']
</code>```

The second one:

```<code>ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']
</code>```

Personally I use the second one more often. Sometimes, I even inline that if the argument is used only once. e.g.

print("Making a sandwich with ", ingredients or ['ham', 'ham', 'bacon', 'ham'])

Is there any solid reason to prefer one over the others?

答:
None of them is actually the right way to do. What if you want to pass an empty list of ingredients?

A better solution would be

```<code>if ingredients is None:
    ingredients = ['ham', 'ham', 'bacon', 'ham']
</code>```

Body:
Let's have a function make_sandwich that takes a list of ingredients which has a default value of ['ham', 'ham', 'bacon', 'ham']

def make_sandwich(ingredients=['ham', 'ham', 'bacon', 'ham']):
    print("Making a sandwich with ", ingredients)

However, since this default value is susceptible to this python "mutable default argument" <s>bug</s> feature, we should use an immutable instead like this:

def make_sandwich(ingredients=None):
    # initialized ingredients here
    print("Making a sandwich with ", ingredients)

So here's the question. There're two ways that I am aware of to do this, but I am not sure which one is considered a better practice.

The first one:

if not ingredients:
    ingredients = ['ham', 'ham', 'bacon', 'ham']

The second one:

ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']

Personally I use the second one more often. Sometimes, I even inline that if the argument is used only once. e.g.

print("Making a sandwich with ", ingredients or ['ham', 'ham', 'bacon', 'ham'])

Is there any solid reason to prefer one over the others?

Body:
None of them is actually the right way to do. What if you want to pass an empty list of ingredients?

A better solution would be

if ingredients is None:
    ingredients = ['ham', 'ham', 'bacon', 'ham']


问:
How to convert Object array into String arrray and split individual elements from it?

The following is the question prompt:
Create a hash with the following information in the format -

countryname => "capital:population:currency name" create at least 5 records.

Print the details of the country having the largest population
Print the currency name of those countries where capital name starts with "L".

For doing this, I was thinking of populating records with put(), converting the values of hashmap into an array, splitting the array with ":" delimeter, and doing a loop to figure out largest value from the respective column.

I was wondering whether that would be the best way of doing it, or there would be a better approach. If that way is ideal, I am having trouble converting the Object [] countryValues (in the code below) into a String array, so I can use the split function on it.

I expect this to split the values with ":" delimeter.

```<code>HashMap<String,String> countrydata = new HashMap<String, String>();

    countrydata.put("USA", "Washington DC:323,000,000:Dollar");
    countrydata.put("Thailand", "Bangkok:69,000,000:Baht");
    countrydata.put("Vietnam", "Hanoi:93,000,000:Dong");
    countrydata.put("Laos", "Lientiane:7,000,000:Dollar");
    countrydata.put("Belize", "Belmopan:370,000:Dollar");

     Object [] countryValues = countrydata.keySet().toArray();

     for (int i=0; i<countryValues.length; i++){
        String [] splitted = countryValues[i].split(":");
     }

     for (int j=0; j<splitted.length; j++){
         System.out.println(splitted[i]);
     }
</code>```

Error:

Method split(String) is undefined for type Object.

答:
Using java 8 stream it will very simple and efficient such operation as below, just define simple POJO for Country.</p>

```<code>        List<Country> countries = new ArrayList<>();

    countries.add(new Country("USA", "Washington DC", 323000000L, "Dollar"));
    countries.add(new Country("Thailand", "Bangkok", 69000000L, "Baht"));
    countries.add(new Country("Vietnam", "Hanoi", 93000000L, "Dong"));
    countries.add(new Country("Laos", "Lientiane", 7000000L, "Dollar"));
    countries.add(new Country("Belize", "Belmopan", 370000L, "Dollar"));

    Set<String> filteredCountries = countries.stream()
            .filter(p -> p.getCapital().startsWith("L")).map(p -> p.getName())
            .collect(Collectors.toSet());

    Country maxPopulationCountry = countries.stream()
            .max(Comparator.comparing(p -> p.getPopulation())).get();

    System.out.println("Max Population Country Details : " + maxPopulationCountry);
    System.out.println("Countries with Capital starts with L : " + filteredCountries);
</code>```

Body:
The following is the question prompt:
Create a hash with the following information in the format -

countryname => "capital:population:currency name" create at least 5 records.

Print the details of the country having the largest population
Print the currency name of those countries where capital name starts with "L".

For doing this, I was thinking of populating records with put(), converting the values of hashmap into an array, splitting the array with ":" delimeter, and doing a loop to figure out largest value from the respective column.

I was wondering whether that would be the best way of doing it, or there would be a better approach. If that way is ideal, I am having trouble converting the Object [] countryValues (in the code below) into a String array, so I can use the split function on it.

I expect this to split the values with ":" delimeter.

HashMap<String,String> countrydata = new HashMap<String, String>();

    countrydata.put("USA", "Washington DC:323,000,000:Dollar");
    countrydata.put("Thailand", "Bangkok:69,000,000:Baht");
    countrydata.put("Vietnam", "Hanoi:93,000,000:Dong");
    countrydata.put("Laos", "Lientiane:7,000,000:Dollar");
    countrydata.put("Belize", "Belmopan:370,000:Dollar");

     Object [] countryValues = countrydata.keySet().toArray();

     for (int i=0; i<countryValues.length; i++){
        String [] splitted = countryValues[i].split(":");
     }

     for (int j=0; j<splitted.length; j++){
         System.out.println(splitted[i]);
     }

Error:

Method split(String) is undefined for type Object.

Body:
Using java 8 stream it will very simple and efficient such operation as below, just define simple POJO for Country.

        List<Country> countries = new ArrayList<>();

    countries.add(new Country("USA", "Washington DC", 323000000L, "Dollar"));
    countries.add(new Country("Thailand", "Bangkok", 69000000L, "Baht"));
    countries.add(new Country("Vietnam", "Hanoi", 93000000L, "Dong"));
    countries.add(new Country("Laos", "Lientiane", 7000000L, "Dollar"));
    countries.add(new Country("Belize", "Belmopan", 370000L, "Dollar"));

    Set<String> filteredCountries = countries.stream()
            .filter(p -> p.getCapital().startsWith("L")).map(p -> p.getName())
            .collect(Collectors.toSet());

    Country maxPopulationCountry = countries.stream()
            .max(Comparator.comparing(p -> p.getPopulation())).get();

    System.out.println("Max Population Country Details : " + maxPopulationCountry);
    System.out.println("Countries with Capital starts with L : " + filteredCountries);


问:
MySQL JOIN from 3 relative tables
I have 3 tables

1. role (id, ...)

2. permission (id, ...)

3. role_permission (id, role_id, permission_id)

I want to do the next: i should select all roles and all permissions for this roles with help of one query. My test query:

```<code>SELECT `rp`.*, `r`.`role`, `r`.`id` AS `role_id`, `p`.`id` AS
`permission_id`,`p`.`name` AS `permission` FROM `role_permission` AS `rp` RIGHT JOIN
`role` AS `r` ON r.id = rp.role_id RIGHT JOIN `permission` AS `p` ON p.id = rp.permission_id
</code>```

But this query select only those roles, what have permissions. But i need to select all roles and all permissions (exist row in role_permission or not).

Thank you in advance. Sorry for my english.

答:
You need to select all roles in a query, then all permissions in another, cross them and finally left join to role_permissions to produce the full list of roles x permissions

```<code>SELECT rp.*, r.role, r.id AS role_id, p.id AS permission_id,p.name AS permission
FROM permission AS p
CROSS JOIN  role AS r
LEFT JOIN role_permission AS rp ON p.id = rp.permission_id
  AND r.id = rp.role_id
</code>```

The cross join gives you a full matrix of role x permission combinations, and the LEFT join succeeds even if the row in role_permission doesn't have any entries for a row (role, permission) in the full matrix.

Title: MySQL JOIN from 3 relative tables

Body:
I have 3 tables

1. role (id, ...)

2. permission (id, ...)

3. role_permission (id, role_id, permission_id)

I want to do the next: i should select all roles and all permissions for this roles with help of one query. My test query:

SELECT `rp`.*, `r`.`role`, `r`.`id` AS `role_id`, `p`.`id` AS
`permission_id`,`p`.`name` AS `permission` FROM `role_permission` AS `rp` RIGHT JOIN
`role` AS `r` ON r.id = rp.role_id RIGHT JOIN `permission` AS `p` ON p.id = rp.permission_id

But this query select only those roles, what have permissions. But i need to select all roles and all permissions (exist row in role_permission or not).

Thank you in advance. Sorry for my english.

Body:
You need to select all roles in a query, then all permissions in another, cross them and finally left join to role_permissions to produce the full list of roles x permissions

SELECT rp.*, r.role, r.id AS role_id, p.id AS permission_id,p.name AS permission
FROM permission AS p
CROSS JOIN  role AS r
LEFT JOIN role_permission AS rp ON p.id = rp.permission_id
  AND r.id = rp.role_id

The cross join gives you a full matrix of role x permission combinations, and the LEFT join succeeds even if the row in role_permission doesn't have any entries for a row (role, permission) in the full matrix.


问:
Make Java GC logs show MB or GB instead of KB
By default Java GC log output shows the memory details in KB (kilo bytes). I know it might sound silly, but given most of the Jvms I deal with have heap sizes close to 20 to 40GB, I find it quite inconvenient to read the numbers in KB quickly, especially when quickly scanning logs in putty etc.

Is it possible to make Java print these number in fractions of MB or GB instead?

I didn't find any option in JDK documentation.

If it is not possible, are there any ideas around how one can go about adding this feature to GC logging? (not from outside but from with in JVM)

Thank you in advance for your help.

答:
I'm not familiar with this point, but I know that you can try to make gc logging from your application. Read about GarbageCollectorMXBean, GarbageCollectionNotificationInfo and GcInfo.
https://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/GcInfo.html


问:
How to call method in android so able to run code
I want to create a simple calculator in Android, in my way I get an error on calling a fuction that i have already declared. Any Android Expert here that can help me?

```<code>public class CalculatorActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator);
    }

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method

    //I want to call that fucntion, and i get an error
    calculator();

}
</code>```

答:
You should call that method inside OnCreate()

```<code> @Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_calculator);
      calculator();
 }
</code>```

Body:
I want to create a simple calculator in Android, in my way I get an error on calling a fuction that i have already declared. Any Android Expert here that can help me?

public class CalculatorActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_calculator);
    }

    //Start my method

    public void calculator(View v) {
        Button btn0 = (Button) findViewById(R.id.btn0);
        Button btn1 = (Button) findViewById(R.id.btn1);
        Button btn2 = (Button) findViewById(R.id.btn2);
        Button btn3 = (Button) findViewById(R.id.btn3);
        Button btn4 = (Button) findViewById(R.id.btn4);
        Button btn5 = (Button) findViewById(R.id.btn5);
        Button btn6 = (Button) findViewById(R.id.btn6);
        Button btn7 = (Button) findViewById(R.id.btn7);

        TextView textViewResult = (TextView) findViewById(R.id.textView);

        if (btn0.isPressed() == true) {

            textViewResult.setText(textViewResult + "0");
        } else if (btn1.isPressed() == true) {
            textViewResult.setText(textViewResult + "1");

        }

    }
       //End my method

    //I want to call that fucntion, and i get an error
    calculator();

}

Body:
You should call that method inside OnCreate()

 @Override
 protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_calculator);
      calculator();
 }


问:
Do calling a ColdFusion web service using <s:RemoteObject> and <s:WebService> have a difference in performance?
Assuming calling the same ColdFusion web service and all other factors are identical, is there a difference in performance/speed between using the following two tags?

```<code> <s:RemoteObject id="MyService" destination="ColdFusion" source="MyWSFolder.MyService"/>
</code>```

and

```<code><s:WebService id="MyService" wsdl="http://www.myDomain.com/MyWSFolder/MyService.cfc?wsdl"/>
</code>```

Thanks in advance,

Monte

答:
How do you quantify performance?

The WebService tag is used for calling a SOAP WebService.  SOAP requests are very wordy, causing a larger amount of data to be passed back and forth than if you were using AMF.  IF using WebService, you'll also have to write parsing code in the Flex client to make the data useful.

The RemoteObject tag is used for making AMF calls over a Flash Remoting gateway.  AMF is a binary fomat and has shown to give much smaller file sizes for data transport between the server and Flash.  AMF also provides some built in conversion of server side data types (CFCs) to client side data types (AS3 objects).

You should check out James Ward's census application for some performance comparisons.

If you're using ColdFusion as your backend, it would be foolish to use WebService instead of RemoteObject for a flex front end.  I you need to support SOAP clients with your services, the very same CF code can be used to expose a SOAP Web Service as a RemoteObject interface w/o any code changes on your end.

Body:
Assuming calling the same ColdFusion web service and all other factors are identical, is there a difference in performance/speed between using the following two tags?

 <s:RemoteObject id="MyService" destination="ColdFusion" source="MyWSFolder.MyService"/>

and

<s:WebService id="MyService" wsdl="http://www.myDomain.com/MyWSFolder/MyService.cfc?wsdl"/>

Thanks in advance,

Monte