问:
References to roslyn compiled from file from another project
I am trying to build an assembly dynamically, using roslyn, and to later be loaded from the
ASP.NET CORE 'AddApplicationParts' extension method, at the startup phase of my web app.

I am loading a .cs file externally from another project, where it works great.

Here is the code, i got everything to work, but i cannot seem to figure out how to load 'references' from the external project, i tried the so called 'add references' from metadatafile but no luck.

```<code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Reflection;
using System.Collections.Immutable;

namespace WebApplication1
{

    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            Pr2.Main2();

            host.Run();
        }
    }

    public class Pr2
    {
        public static void Main2()
        {
            string code = File.ReadAllText(@"c:\users\victor\documents\visual studio 2017\Projects\WebApplication2\WebApplication2\Controllers\HomeController.cs");
            SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code);

            CSharpCompilation compilation = CreateCompilation(tree);
            SemanticModel model = compilation.GetSemanticModel(tree);

            ShowLocalDeclarations(tree, model);
            ShowDiagnostics(compilation);
            ExecuteCode(compilation);

        }

        private static void ShowLocalDeclarations(SyntaxTree tree, SemanticModel model)
        {
            IEnumerable<LocalDeclarationStatementSyntax> locals = tree.GetRoot()
                             .DescendantNodes()
                             .OfType<LocalDeclarationStatementSyntax>();

            foreach (var node in locals)
            {
                Microsoft.CodeAnalysis.TypeInfo type = model.GetTypeInfo(node.Declaration.Type);
                Console.WriteLine("{0} {1}", type.Type, node.Declaration);
            }
        }

        private static Assembly ExecuteCode(CSharpCompilation compilation)
        {
            Assembly roRet;
            using (var stream = new MemoryStream())
            {
                compilation.Emit(stream);

                roRet = Assembly.Load(stream.GetBuffer());
            }

            return roRet;
        }

        private static void ShowDiagnostics(CSharpCompilation compilation)
        {
            ImmutableArray<Diagnostic> diagnostics = compilation.GetDiagnostics();
            foreach (var diagnostic in diagnostics)
            {
                // OVER HERE WE SEE THE ERRORS.
                Console.WriteLine(diagnostic.ToString());
            }
        }

        private static CSharpCompilation CreateCompilation(SyntaxTree tree)
        {
            CSharpCompilationOptions options = new CSharpCompilationOptions(
                                            OutputKind.DynamicallyLinkedLibrary);

            PortableExecutableReference reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            CSharpCompilation compilation =
                CSharpCompilation.Create("test")
                                 .WithOptions(options)
                                 .AddSyntaxTrees(tree)
                                 .AddReferences(reference);
            return compilation;
        }
    }
}
</code>```

The external file is in another asp.net core project, started fresh from vs2017 core templates, using the 4.6.2 framework. !!

```<code>using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}
</code>```

答:
The issue is that you're referencing only mscorlib when compiling the file, but you need to reference all assemblies the file depends on. You could try to do this one assembly at a time, but I think a better option is to take advantage of the fact that you have a second csproj, which contains all the information you need. You just need to get the information from there somehow.

To do that, you can use MSBuild. Reference the Microsoft.Build and Microsoft.Build.Tasks.Core packages and then use this code (adapted from this answer):

```<code>private static IEnumerable<string> GetReferences(string projectFileName)
{
    var projectInstance = new ProjectInstance(projectFileName);
    var result = BuildManager.DefaultBuildManager.Build(
        new BuildParameters(),
        new BuildRequestData(projectInstance, new[]
        {
            "ResolveProjectReferences",
            "ResolveAssemblyReferences"
        }));

    IEnumerable<string> GetResultItems(string targetName)
    {
        var buildResult = result.ResultsByTarget[targetName];
        var buildResultItems = buildResult.Items;

        return buildResultItems.Select(item => item.ItemSpec);
    }

    return GetResultItems("ResolveProjectReferences")
        .Concat(GetResultItems("ResolveAssemblyReferences"));
}

// in Main2
var references = GetReferences(@"C:\code\tmp\roslyn references\WebApplication2\WebApplication2.csproj");

CSharpCompilation compilation = CreateCompilation(tree, references);

// in CreateCompilation
CSharpCompilation compilation =
    CSharpCompilation.Create("test")
        .WithOptions(options)
        .AddSyntaxTrees(tree)
        .AddReferences(references.Select(path => MetadataReference.CreateFromFile(path)));
</code>```

Body:
I am trying to build an assembly dynamically, using roslyn, and to later be loaded from the
ASP.NET CORE 'AddApplicationParts' extension method, at the startup phase of my web app.

I am loading a .cs file externally from another project, where it works great.

Here is the code, i got everything to work, but i cannot seem to figure out how to load 'references' from the external project, i tried the so called 'add references' from metadatafile but no luck.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Reflection;
using System.Collections.Immutable;

namespace WebApplication1
{

    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseApplicationInsights()
                .Build();

            Pr2.Main2();

            host.Run();
        }
    }

    public class Pr2
    {
        public static void Main2()
        {
            string code = File.ReadAllText(@"c:\users\victor\documents\visual studio 2017\Projects\WebApplication2\WebApplication2\Controllers\HomeController.cs");
            SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(code);

            CSharpCompilation compilation = CreateCompilation(tree);
            SemanticModel model = compilation.GetSemanticModel(tree);

            ShowLocalDeclarations(tree, model);
            ShowDiagnostics(compilation);
            ExecuteCode(compilation);

        }

        private static void ShowLocalDeclarations(SyntaxTree tree, SemanticModel model)
        {
            IEnumerable<LocalDeclarationStatementSyntax> locals = tree.GetRoot()
                             .DescendantNodes()
                             .OfType<LocalDeclarationStatementSyntax>();

            foreach (var node in locals)
            {
                Microsoft.CodeAnalysis.TypeInfo type = model.GetTypeInfo(node.Declaration.Type);
                Console.WriteLine("{0} {1}", type.Type, node.Declaration);
            }
        }

        private static Assembly ExecuteCode(CSharpCompilation compilation)
        {
            Assembly roRet;
            using (var stream = new MemoryStream())
            {
                compilation.Emit(stream);

                roRet = Assembly.Load(stream.GetBuffer());
            }

            return roRet;
        }

        private static void ShowDiagnostics(CSharpCompilation compilation)
        {
            ImmutableArray<Diagnostic> diagnostics = compilation.GetDiagnostics();
            foreach (var diagnostic in diagnostics)
            {
                // OVER HERE WE SEE THE ERRORS.
                Console.WriteLine(diagnostic.ToString());
            }
        }

        private static CSharpCompilation CreateCompilation(SyntaxTree tree)
        {
            CSharpCompilationOptions options = new CSharpCompilationOptions(
                                            OutputKind.DynamicallyLinkedLibrary);

            PortableExecutableReference reference = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            CSharpCompilation compilation =
                CSharpCompilation.Create("test")
                                 .WithOptions(options)
                                 .AddSyntaxTrees(tree)
                                 .AddReferences(reference);
            return compilation;
        }
    }
}

The external file is in another asp.net core project, started fresh from vs2017 core templates, using the 4.6.2 framework. !!

using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers
{
    public class TestController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}

Body:
The issue is that you're referencing only mscorlib when compiling the file, but you need to reference all assemblies the file depends on. You could try to do this one assembly at a time, but I think a better option is to take advantage of the fact that you have a second csproj, which contains all the information you need. You just need to get the information from there somehow.

To do that, you can use MSBuild. Reference the Microsoft.Build and Microsoft.Build.Tasks.Core packages and then use this code (adapted from this answer):

private static IEnumerable<string> GetReferences(string projectFileName)
{
    var projectInstance = new ProjectInstance(projectFileName);
    var result = BuildManager.DefaultBuildManager.Build(
        new BuildParameters(),
        new BuildRequestData(projectInstance, new[]
        {
            "ResolveProjectReferences",
            "ResolveAssemblyReferences"
        }));

    IEnumerable<string> GetResultItems(string targetName)
    {
        var buildResult = result.ResultsByTarget[targetName];
        var buildResultItems = buildResult.Items;

        return buildResultItems.Select(item => item.ItemSpec);
    }

    return GetResultItems("ResolveProjectReferences")
        .Concat(GetResultItems("ResolveAssemblyReferences"));
}

// in Main2
var references = GetReferences(@"C:\code\tmp\roslyn references\WebApplication2\WebApplication2.csproj");

CSharpCompilation compilation = CreateCompilation(tree, references);

// in CreateCompilation
CSharpCompilation compilation =
    CSharpCompilation.Create("test")
        .WithOptions(options)
        .AddSyntaxTrees(tree)
        .AddReferences(references.Select(path => MetadataReference.CreateFromFile(path)));


来源: stackexchange

问:
How to Calculate the Area of a Triangle with HTML
I am trying to create a table with two boxes in which you type the height and the base of a triangle and then you can get the resulting area at the bottom this is what I got so far as for the other shapes. But I can not figure it out for a triangle. I am new so sorry in advance. </p>

```<code>    <h3>Calculo de Areas</h3>
        <p>Ingrese la Informacion requerida para sacar el Area de las siguientes Figuras.</p>
        <p>Nota:Los Resultados estan dados en la misma unidad que se introduce.</p>
            <table>
        <tr>
            <th>
<p>
  <label>Radio de un Circulo</label>
  <input id="inputradio" type="number" placeholder="Radio" oninput="LengthConverter9(this.value)" onchange="LengthConverter9(this.value)">
</p>
<p>Area: <span id="outputArea"></span></p>

<script>
function LengthConverter9(valNum9) {
  document.getElementById("outputArea").innerHTML=(valNum9*valNum9)*3.14159265359;
}
                </script>
            </th><th>
<p>
  <label>Lado de un Cuadrado</label>
  <input id="inputLado" type="number" placeholder="Largo" oninput="LengthConverter10(this.value)" onchange="LengthConverter10(this.value)">
</p>
<p>Area: <span id="outputArea1"></span></p>

<script>
function LengthConverter10(valNum10) {
  document.getElementById("outputArea1").innerHTML=(valNum10*valNum10);
}
</script>

    <tr><th>
        <p>
  <label>Base de un Triangulo Rectangulo</label>
  <input id="inputBase" type="number" placeholder="Ancho" oninput="LengthConverter11(this.value)" onchange="LengthConverter11(this.value)">
</p>
        <p>
  <label>Altura de dicho Triangulo</label>
  <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter12(this.value)" onchange="LengthConverter12(this.value)">
</p>
<p>Area: <span id="outputArea4"></span></p>
<script>
function LengthConverter11(valNum11){
  document.getElementById("outputMetros4").innerHTML=(LengthConverter11*LengthConverter12)/2;
}
                </script>

        </th></tr>
    </table>
</code>```

<p>The only one that i cant get to work is the triangle one, Thanks in advance. </p>

答:
Looking at this

```<code>  <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter12(this.value)" onchange="LengthConverter12(this.value)">
</code>```

You haven't define any function for LengthConverter12

Looking at this (calculating area of triangle)

```<code>document.getElementById("outputMetros4").innerHTML=(LengthConverter11*LengthConverter12)/2;
</code>```

You are multipy a function defined by an undefined function?

I suggest you place all your js codes in one section, this way it is very easy to debug and read. However using your layout and building on what you have, here is a snippet below

Calculo de Areas

Ingrese la Informacion requerida para sacar el Area de las siguientes Figuras.

Nota:Los Resultados estan dados en la misma unidad que se introduce.

        Radio de un Circulo
        <input id="inputradio" type="number" placeholder="Radio" oninput="LengthConverter9(this.value)" onchange="LengthConverter9(this.value)">

Area:

        Lado de un Cuadrado
        <input id="inputLado" type="number" placeholder="Largo" oninput="LengthConverter10(this.value)" onchange="LengthConverter10(this.value)">

Area:

            Base de un Triangulo Rectangulo
            <input id="inputBase" type="number" placeholder="Ancho">

            Altura de dicho Triangulo
            <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter11(this.value)" onchange="LengthConverter11(this.value)">

Area:

```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a table with two boxes in which you type the height and the base of a triangle and then you can get the resulting area at the bottom this is what I got so far as for the other shapes. But I can not figure it out for a triangle. I am new so sorry in advance.

Calculo de Areas

Ingrese la Informacion requerida para sacar el Area de las siguientes Figuras.

Nota:Los Resultados estan dados en la misma unidad que se introduce.

  Radio de un Circulo
  <input id="inputradio" type="number" placeholder="Radio" oninput="LengthConverter9(this.value)" onchange="LengthConverter9(this.value)">

Area:

  Lado de un Cuadrado
  <input id="inputLado" type="number" placeholder="Largo" oninput="LengthConverter10(this.value)" onchange="LengthConverter10(this.value)">

Area:

  Base de un Triangulo Rectangulo
  <input id="inputBase" type="number" placeholder="Ancho" oninput="LengthConverter11(this.value)" onchange="LengthConverter11(this.value)">

  Altura de dicho Triangulo
  <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter12(this.value)" onchange="LengthConverter12(this.value)">

Area:

The only one that i cant get to work is the triangle one, Thanks in advance.

Body:
Looking at this

  <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter12(this.value)" onchange="LengthConverter12(this.value)">

You haven't define any function for LengthConverter12

Looking at this (calculating area of triangle)

document.getElementById("outputMetros4").innerHTML=(LengthConverter11*LengthConverter12)/2;

You are multipy a function defined by an undefined function?

I suggest you place all your js codes in one section, this way it is very easy to debug and read. However using your layout and building on what you have, here is a snippet below

<h3>Calculo de Areas</h3>
<p>Ingrese la Informacion requerida para sacar el Area de las siguientes Figuras.</p>
<p>Nota:Los Resultados estan dados en la misma unidad que se introduce.</p>
<table>
  <tr>
    <th>
      <p>
        <label>Radio de un Circulo</label>
        <input id="inputradio" type="number" placeholder="Radio" oninput="LengthConverter9(this.value)" onchange="LengthConverter9(this.value)">
      </p>
      <p>Area: <span id="outputArea"></span></p>

      <script>
        function LengthConverter9(valNum9) {
          document.getElementById("outputArea").innerHTML = (valNum9 * valNum9) * 3.14159265359;
        }
      </script>
    </th>
    <th>
      <p>
        <label>Lado de un Cuadrado</label>
        <input id="inputLado" type="number" placeholder="Largo" oninput="LengthConverter10(this.value)" onchange="LengthConverter10(this.value)">
      </p>
      <p>Area: <span id="outputArea1"></span></p>

      <script>
        function LengthConverter10(valNum10) {
          document.getElementById("outputArea1").innerHTML = (valNum10 * valNum10);
        }
      </script>

      <tr>
        <th>
          <p>
            <label>Base de un Triangulo Rectangulo</label>
            <input id="inputBase" type="number" placeholder="Ancho">
          </p>
          <p>
            <label>Altura de dicho Triangulo</label>
            <input id="inputAltura" type="number" placeholder="Alto" oninput="LengthConverter11(this.value)" onchange="LengthConverter11(this.value)">
          </p>
          <p>Area: <span id="outputArea4"></span></p>
          <script>
            function LengthConverter11(height) {
              var base = document.getElementById("inputBase").value.trim();
              console.log(base, height);
              height = height.trim();

              document.getElementById("outputArea4").innerHTML = (base * height) / 2;
            }
          </script>

        </th>
      </tr>
</table>


问:
Building a hex string from ArrayList<Integer>
I have already calculated the remainders, but my problem is the actual conversion from the remainders to the new hexadecimal characters. All I need to do in the Dec2Hex class is get the remainder arraylist from the superclass (which I have done) and then convert it into a string by using the character array hexDigits[]. I have to step though the remainder arraylist in a loop and build the hex string, but I am not sure how to go about this.

```<code>//this is the Binary to Decimal implementation which hex2dec is based off of

package business;

import java.util.ArrayList;

/**
 *
 * @author
 */
public class Bin2Dec implements Conversion{
    public static final String VALUEDESC ="Binary";
    public static final String RESULTDESC ="Decimal";
    private String origval, result;
    private ArrayList<String> resultsteps;
    private String emsg;
    private boolean valid;

    public Bin2Dec(String value) {
        emsg = "";
        origval = value;
        if (valid =isValid(value)) {  //valid will be true or false
            convert(value);
        } else {
            emsg = "Illegal, binary value (must be only zeros and ones";
        }
    }
    private boolean isValid(String v) {
        for (int i=0; i< v.length(); i++) {
            if (v.charAt(i) != '1' && v.charAt(i) != '0') {
                return false;
            }
        }
        return true;
    }
    // we can do isValid because we declared private boolean valid
    @Override
    public boolean isValid() {
        return this.valid;
    }
    private void convert(String v) {
        long r = 0;
        String reverse = new StringBuilder(v).reverse().toString();
        resultsteps = new ArrayList<>();
        for (int i=0; i < reverse.length(); i++) {
            if (reverse.charAt(i) == '1') {
                long p = (long) Math.pow(2,i);
                r += p;
                resultsteps.add("There is a(n) " + p + " in the number (2^" + i + ")" );
            }
        }
        this.result = String.valueOf(r);
    }
    @Override
    public String getResult() {
        return this.result;
    }
    @Override
    public ArrayList<String> getProcessLog() {
        return this.resultsteps;
    }
    @Override
    public String getErrorMsg() {
        return this.emsg;
    }
    @Override
    public String getValue() {
        return this.origval;
    }

}
</code>```

Implementation

```<code>//this is the hex2dec implementation I created

package business;

import java.util.ArrayList;

/**
 *
 * @author
 */
public class Dec2Hex extends Dec2Num {
    public static final String VALUEDESC="Decimal";
    public static final String RESULTDESC="Hexadecimal";
//    private ArrayList<String> codes;
    public static final int BASE=16;
    private String binaryresult;
    char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'A', 'B', 'C', 'D', 'E', 'F'};
    String hex = "";

    public Dec2Hex(String value) {
        super(value, Dec2Hex.BASE);
        this.binaryresult="";

    }

    @Override
    public String getResult() {
        if(!super.isValid()) {return "Invalid Value";}
        for(Integer i : super.getRemainders()) {                             //we deleted remainders in Dec2Bin so we call super
            String hex = Integer.toHexString(i);
            this.binaryresult += String.valueOf(i);
        }
        switch (hex) {

        }

       return this.binaryresult;
    }

//    public ArrayList<String> getHexConversion(int d) {
//        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
//              'A', 'B', 'C', 'D', 'E', 'F'};
//        String hex = "";
//        while (d > 0) {
//            int digit = d % BASE;
//            hex = hexDigits.charAt(digit) + hex;
//            d = d / BASE;
//        }
//    return codes;
//    }

    //    public ArrayList<String> getHexConversion(int d) {
//
//        String hex = "";
//        while (d > 0) {
//            int digit = d % BASE;
//            char hexDigits = (hex <= 9 && hex >= 0);
//            (char)(hexDigits + '0') : (char)(hexDigits- 10 + 'A');
//        }
//    return this.binaryresult;
//    }
}
</code>```

Interface and abstract implementation

```<code>//interface

public interface Conversion {
    public String getValue();
    public String getResult();
    public boolean isValid();
    public ArrayList<String> getProcessLog();
    public String getErrorMsg();
    //each subclass should fulfill these methods
}

//abstract implementation

public abstract class Dec2Num implements Conversion{
    private String origval, emsg;
    private boolean valid;
    private int base;
    private ArrayList<String> resultsteps;
    private ArrayList<Integer> remainders;

    public Dec2Num(String value, int base) {  //int base b/c it needs to know what to divide down by
       emsg ="";
       origval = value;
       this.base = base;
       try {
           long n = Long.parseLong(value);
           if (n < 0 ) {
               emsg = "Bad decimal value: must be positive.";
               this.valid = false;
           } else {
              this.valid = true;
              resultsteps = new ArrayList<>();
              remainders = new ArrayList<>();
              convertByRecur(n);
           }
        } catch (NumberFormatException e) {
           emsg = "Illegal value: not a decimal integer";
           this.valid = false;
        }
    }//end of constructor
        @Override
    public boolean isValid() {
        return this.valid;
    }
    private void convertByRecur(long n) {
        int r = 0;

        r = (int)(n % this.base);
        long newval = n / this.base;
        resultsteps.add(n + " divided by " + this.base + "="
                        + newval + " w/remainder of: "  +r);

        if (newval > 0) {
            convertByRecur(newval);  //recursive call
        }
        remainders.add(r);
    }
    @Override
    public ArrayList<String> getProcessLog() {
        return this.resultsteps;
    }
    @Override
    public String getErrorMsg() {
        return this.emsg;
    }
    @Override
    public String getValue() {
        return this.origval;
    }
    @Override
    public abstract String getResult();

    protected ArrayList<Integer> getRemainders() {
        return this.remainders;
    }
}
</code>```

答:
First, calling Integer.toHexString() should work, but it bypasses the idea of your hexDigits array. Only potential issue is it will give you lowercase letters a though f where you may want the uppercase equivalents.

String.valueOf(i) is incorrect. It will give you 7 if i is 7, but 11 if i 11, where you want B, the hex digit. You could do just

```<code>        this.binaryresult += hex;
</code>```

You don’t need your switch statement at all.

Supposing you do want to use your hexDigits array:

To get the correct char out of the array, just use hexDigits[i].

You can append the char directly to a String without converting it to a String first:

```<code>    this.binaryresult += yourChar;
</code>```

I will let you struggle with it a bit before offering my version of the code. I believe you can do it.

Body:
I have already calculated the remainders, but my problem is the actual conversion from the remainders to the new hexadecimal characters. All I need to do in the Dec2Hex class is get the remainder arraylist from the superclass (which I have done) and then convert it into a string by using the character array hexDigits[]. I have to step though the remainder arraylist in a loop and build the hex string, but I am not sure how to go about this.

//this is the Binary to Decimal implementation which hex2dec is based off of

package business;

import java.util.ArrayList;

/**
 *
 * @author
 */
public class Bin2Dec implements Conversion{
    public static final String VALUEDESC ="Binary";
    public static final String RESULTDESC ="Decimal";
    private String origval, result;
    private ArrayList<String> resultsteps;
    private String emsg;
    private boolean valid;

    public Bin2Dec(String value) {
        emsg = "";
        origval = value;
        if (valid =isValid(value)) {  //valid will be true or false
            convert(value);
        } else {
            emsg = "Illegal, binary value (must be only zeros and ones";
        }
    }
    private boolean isValid(String v) {
        for (int i=0; i< v.length(); i++) {
            if (v.charAt(i) != '1' && v.charAt(i) != '0') {
                return false;
            }
        }
        return true;
    }
    // we can do isValid because we declared private boolean valid
    @Override
    public boolean isValid() {
        return this.valid;
    }
    private void convert(String v) {
        long r = 0;
        String reverse = new StringBuilder(v).reverse().toString();
        resultsteps = new ArrayList<>();
        for (int i=0; i < reverse.length(); i++) {
            if (reverse.charAt(i) == '1') {
                long p = (long) Math.pow(2,i);
                r += p;
                resultsteps.add("There is a(n) " + p + " in the number (2^" + i + ")" );
            }
        }
        this.result = String.valueOf(r);
    }
    @Override
    public String getResult() {
        return this.result;
    }
    @Override
    public ArrayList<String> getProcessLog() {
        return this.resultsteps;
    }
    @Override
    public String getErrorMsg() {
        return this.emsg;
    }
    @Override
    public String getValue() {
        return this.origval;
    }

}

Implementation

//this is the hex2dec implementation I created

package business;

import java.util.ArrayList;

/**
 *
 * @author
 */
public class Dec2Hex extends Dec2Num {
    public static final String VALUEDESC="Decimal";
    public static final String RESULTDESC="Hexadecimal";
//    private ArrayList<String> codes;
    public static final int BASE=16;
    private String binaryresult;
    char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'A', 'B', 'C', 'D', 'E', 'F'};
    String hex = "";

    public Dec2Hex(String value) {
        super(value, Dec2Hex.BASE);
        this.binaryresult="";

    }

    @Override
    public String getResult() {
        if(!super.isValid()) {return "Invalid Value";}
        for(Integer i : super.getRemainders()) {                             //we deleted remainders in Dec2Bin so we call super
            String hex = Integer.toHexString(i);
            this.binaryresult += String.valueOf(i);
        }
        switch (hex) {

        }

       return this.binaryresult;
    }

//    public ArrayList<String> getHexConversion(int d) {
//        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
//              'A', 'B', 'C', 'D', 'E', 'F'};
//        String hex = "";
//        while (d > 0) {
//            int digit = d % BASE;
//            hex = hexDigits.charAt(digit) + hex;
//            d = d / BASE;
//        }
//    return codes;
//    }

    //    public ArrayList<String> getHexConversion(int d) {
//
//        String hex = "";
//        while (d > 0) {
//            int digit = d % BASE;
//            char hexDigits = (hex <= 9 && hex >= 0);
//            (char)(hexDigits + '0') : (char)(hexDigits- 10 + 'A');
//        }
//    return this.binaryresult;
//    }
}

Interface and abstract implementation

//interface

public interface Conversion {
    public String getValue();
    public String getResult();
    public boolean isValid();
    public ArrayList<String> getProcessLog();
    public String getErrorMsg();
    //each subclass should fulfill these methods
}

//abstract implementation

public abstract class Dec2Num implements Conversion{
    private String origval, emsg;
    private boolean valid;
    private int base;
    private ArrayList<String> resultsteps;
    private ArrayList<Integer> remainders;

    public Dec2Num(String value, int base) {  //int base b/c it needs to know what to divide down by
       emsg ="";
       origval = value;
       this.base = base;
       try {
           long n = Long.parseLong(value);
           if (n < 0 ) {
               emsg = "Bad decimal value: must be positive.";
               this.valid = false;
           } else {
              this.valid = true;
              resultsteps = new ArrayList<>();
              remainders = new ArrayList<>();
              convertByRecur(n);
           }
        } catch (NumberFormatException e) {
           emsg = "Illegal value: not a decimal integer";
           this.valid = false;
        }
    }//end of constructor
        @Override
    public boolean isValid() {
        return this.valid;
    }
    private void convertByRecur(long n) {
        int r = 0;

        r = (int)(n % this.base);
        long newval = n / this.base;
        resultsteps.add(n + " divided by " + this.base + "="
                        + newval + " w/remainder of: "  +r);

        if (newval > 0) {
            convertByRecur(newval);  //recursive call
        }
        remainders.add(r);
    }
    @Override
    public ArrayList<String> getProcessLog() {
        return this.resultsteps;
    }
    @Override
    public String getErrorMsg() {
        return this.emsg;
    }
    @Override
    public String getValue() {
        return this.origval;
    }
    @Override
    public abstract String getResult();

    protected ArrayList<Integer> getRemainders() {
        return this.remainders;
    }
}

Body:
First, calling Integer.toHexString() should work, but it bypasses the idea of your hexDigits array. Only potential issue is it will give you lowercase letters a though f where you may want the uppercase equivalents.

String.valueOf(i) is incorrect. It will give you 7 if i is 7, but 11 if i 11, where you want B, the hex digit. You could do just

        this.binaryresult += hex;

You don’t need your switch statement at all.

Supposing you do want to use your hexDigits array:

To get the correct char out of the array, just use hexDigits[i].

You can append the char directly to a String without converting it to a String first:

    this.binaryresult += yourChar;

I will let you struggle with it a bit before offering my version of the code. I believe you can do it.


问:
How to get the objectName of a modified QSpinBox?
I want to keep track of the user modifying the company's forecast in my custom made app.
I created it using qt designer and PyQt4, and I'm using QSpinBox for the quantities (easy way to control range of values and masking the fields to be number only).
The problem I'm having is when I want to get the QSpinBox that triggered my function.
At this moment it's being triggered using valueChanged.connect but could be using anything else.
I can get the int in the spinbox but not the spinbox's name.
Thanks beforehand for the help!

SOLUTION

The QSpinBox element

```<code>self.Item = QtGui.QSpinBox(self.centralwidget)
self.Item.setObjectName(_fromUtf8("ItemName"))
</code>```

Trigger

```<code>self.Item.valueChanged.connect(self.foo)
</code>```

The function it calls

```<code>def foo(self,obj):
    sender = MainWindow.sender()
    print sender.objectName()
</code>```

In this case "MainWindow" is my QtCore.QObject

答:
AS the question tagged C++. I am answering in both C++ and pyQt4. I never worked in pyQt4. So please excuse me for syntax.

In the "valueChanged" slot use QObject::sender() to get the spin box which triggered it.

And then call "objectName()".

```<code>QObject* obj = sender();
QString objName = obj->objectName();
</code>```

May be in python:

```<code> sender = QtCore.QObject.sender()
 str = sender.objectName()
</code>```

Body:
I want to keep track of the user modifying the company's forecast in my custom made app.
I created it using qt designer and PyQt4, and I'm using QSpinBox for the quantities (easy way to control range of values and masking the fields to be number only).
The problem I'm having is when I want to get the QSpinBox that triggered my function.
At this moment it's being triggered using valueChanged.connect but could be using anything else.
I can get the int in the spinbox but not the spinbox's name.
Thanks beforehand for the help!

SOLUTION

The QSpinBox element

self.Item = QtGui.QSpinBox(self.centralwidget)
self.Item.setObjectName(_fromUtf8("ItemName"))

Trigger

self.Item.valueChanged.connect(self.foo)

The function it calls

def foo(self,obj):
    sender = MainWindow.sender()
    print sender.objectName()

In this case "MainWindow" is my QtCore.QObject

Body:
AS the question tagged C++. I am answering in both C++ and pyQt4. I never worked in pyQt4. So please excuse me for syntax.

In the "valueChanged" slot use QObject::sender() to get the spin box which triggered it.

And then call "objectName()".

QObject* obj = sender();
QString objName = obj->objectName();

May be in python:

 sender = QtCore.QObject.sender()
 str = sender.objectName()


问:
MATLAB find cell array substrings in a cell array of strings
Let's say we have a cell array of substrings arrayOfSubstrings = {substr1;substr2} and a cell array of strings arrayOfStrings = {string1;string2;string3;stirng4}. How can I get a logical map into the cell array of strings where at least one of the substrings is found? I have tried

cellfun('isempty',regexp(arrayOfSubstrings ,arrayOfStrings ))

and

cellfun('isempty', strfind(arrayOfSubstrings , arrayOfStrings ))

and some other permutations of functions, but am not getting anywhere.

答:
If you are using R2016b or R2017a you can just use contains:

```<code>>> strings = {'ab', 'bc', 'de', 'fa'};
>> substrs = {'a', 'b', 'c'};
>> contains(strings, substrs)

ans =

  1×4 logical array

   1   1   0   1
</code>```

Contains is also the fastest, especially if you use the new string datatype.

```<code>function profFunc()

    strings = {'ab', 'bc', 'de', 'fa'};
    substrs = {'a', 'b', 'c'};

    n = 10000;

    tic;
    for i = 1:n
        substrs_translated = regexptranslate('escape', substrs);

        matches = false(size(strings));

        for k = 1:numel(strings)
            matches(k) = any(~cellfun('isempty', regexp(strings{k}, substrs_translated)));
        end
    end
    toc

    tic;
    for i = 1:n
        cellfun(@(s)any(~cellfun('isempty', regexp(s, substrs))), strings);
    end
    toc

    tic;
    for i = 1:n
        pattern = ['(', strjoin(regexptranslate('escape', substrs), '|'), ')'];
        output = ~cellfun('isempty', regexp(strings, pattern)); %#ok<NASGU>
    end
    toc

    tic;
    for i = 1:n
        contains(strings,substrs);
    end
    toc

    %Imagine you were using strings for all your text!
    strings = string(strings);

    tic;
    for i = 1:n
        contains(strings,substrs);
    end
    toc
end
</code>```

Timing results:

```<code>>> profFunc
Elapsed time is 0.643176 seconds.
Elapsed time is 1.007309 seconds.
Elapsed time is 0.683643 seconds.
Elapsed time is 0.050663 seconds.
Elapsed time is 0.008177 seconds.
</code>```

Body:
If you are using R2016b or R2017a you can just use contains:

>> strings = {'ab', 'bc', 'de', 'fa'};
>> substrs = {'a', 'b', 'c'};
>> contains(strings, substrs)

ans =

  1×4 logical array

   1   1   0   1

Contains is also the fastest, especially if you use the new string datatype.

function profFunc()

    strings = {'ab', 'bc', 'de', 'fa'};
    substrs = {'a', 'b', 'c'};

    n = 10000;

    tic;
    for i = 1:n
        substrs_translated = regexptranslate('escape', substrs);

        matches = false(size(strings));

        for k = 1:numel(strings)
            matches(k) = any(~cellfun('isempty', regexp(strings{k}, substrs_translated)));
        end
    end
    toc

    tic;
    for i = 1:n
        cellfun(@(s)any(~cellfun('isempty', regexp(s, substrs))), strings);
    end
    toc

    tic;
    for i = 1:n
        pattern = ['(', strjoin(regexptranslate('escape', substrs), '|'), ')'];
        output = ~cellfun('isempty', regexp(strings, pattern)); %#ok<NASGU>
    end
    toc

    tic;
    for i = 1:n
        contains(strings,substrs);
    end
    toc

    %Imagine you were using strings for all your text!
    strings = string(strings);

    tic;
    for i = 1:n
        contains(strings,substrs);
    end
    toc
end

Timing results:

>> profFunc
Elapsed time is 0.643176 seconds.
Elapsed time is 1.007309 seconds.
Elapsed time is 0.683643 seconds.
Elapsed time is 0.050663 seconds.
Elapsed time is 0.008177 seconds.


问:
Mergesort in python - too slow?
I'm trying to learn merge sort but I'm not sure I got this quite right. It works and I've tried optimizing this e.g. with deques for leftpop but I still get times that are roughly 4 times slower than the builtin sorted() function. Is this supposed to happen? Or am I missing some obvious bottlenecks?

```<code>import random
from time import time
from collections import deque

unsorted = [random.randint(0, 1000) for r in xrange(101101)]

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []
    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new.append(left_sorted.popleft())
            if not left_sorted:
                new += right_sorted
        else:
            new.append(right_sorted.popleft())
            if not right_sorted:
                new += left_sorted
    return new

s = time()
print merge_sort(unsorted)
e = time()
print e - s

s = time()
print sorted(unsorted)
e = time()
print e - s
</code>```

Edit: A somewhat optimized version below:

```<code>def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []

    new_append = new.append
    left_pop = left_sorted.popleft
    right_pop = right_sorted.popleft

    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new_append(left_pop())
        else:
            new_append(right_pop())

    if not left_sorted:
        new += right_sorted
    if not right_sorted:
        new += left_sorted

    return new
</code>```

答:
It is slow because you copy the two half (unsorted) lists instead of using indexes.</p>

```<code>def merge(liste):
    def order(start1,middle,stop2):
        stop1=start2=middle
        index1=start1
        index2=start2
        merge_list=[]
        while index1<stop1 and index2<stop2:
            if liste[index1]<liste[index2]:
                merge_list.append(liste[index1])
                index1+=1
            else:
                merge_list.append(liste[index2])
                index2+=1
        if index1<stop1:
            merge_list.extend(liste[index1:stop1])
        if index2<stop2:
            merge_list.extend(liste[index2:stop2])
        liste[start1:stop2] = merge_list

    def sort(start,stop):
        middle=(start+stop)//2
        if start+1<stop:
            sort(start,middle)
            sort(middle,stop)
            order(start,middle,stop)

    sort(0,len(liste))
    return liste
</code>```

Title: Mergesort in python - too slow?

Body:
I'm trying to learn merge sort but I'm not sure I got this quite right. It works and I've tried optimizing this e.g. with deques for leftpop but I still get times that are roughly 4 times slower than the builtin sorted() function. Is this supposed to happen? Or am I missing some obvious bottlenecks?

import random
from time import time
from collections import deque

unsorted = [random.randint(0, 1000) for r in xrange(101101)]

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []
    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new.append(left_sorted.popleft())
            if not left_sorted:
                new += right_sorted
        else:
            new.append(right_sorted.popleft())
            if not right_sorted:
                new += left_sorted
    return new

s = time()
print merge_sort(unsorted)
e = time()
print e - s

s = time()
print sorted(unsorted)
e = time()
print e - s

Edit: A somewhat optimized version below:

def merge_sort(unsorted_list):
    length = len(unsorted_list)
    if length <= 1:
        return unsorted_list

    left = unsorted_list[:length / 2]
    right = unsorted_list[length / 2:]

    left_sorted = deque(merge_sort(left))
    right_sorted = deque(merge_sort(right))

    new = []

    new_append = new.append
    left_pop = left_sorted.popleft
    right_pop = right_sorted.popleft

    while left_sorted and right_sorted:
        if left_sorted[0] < right_sorted[0]:
            new_append(left_pop())
        else:
            new_append(right_pop())

    if not left_sorted:
        new += right_sorted
    if not right_sorted:
        new += left_sorted

    return new

Body:
It is slow because you copy the two half (unsorted) lists instead of using indexes.

def merge(liste):
    def order(start1,middle,stop2):
        stop1=start2=middle
        index1=start1
        index2=start2
        merge_list=[]
        while index1<stop1 and index2<stop2:
            if liste[index1]<liste[index2]:
                merge_list.append(liste[index1])
                index1+=1
            else:
                merge_list.append(liste[index2])
                index2+=1
        if index1<stop1:
            merge_list.extend(liste[index1:stop1])
        if index2<stop2:
            merge_list.extend(liste[index2:stop2])
        liste[start1:stop2] = merge_list

    def sort(start,stop):
        middle=(start+stop)//2
        if start+1<stop:
            sort(start,middle)
            sort(middle,stop)
            order(start,middle,stop)

    sort(0,len(liste))
    return liste


问:
Javascript Node API pass res value to all my other function without calling the function
Need Help
Can anyone please suggest me How can i pass token_value to my all other function. token_value is the sucs response value. If i call the login() function
it requires me to pass username and password. so I cant call the function. But I need to pass the token_value that generated once i login.

$("#submit_login").click(login);

```<code>   var token_value = "";
 function login(){
        var login = {
               username: $("#username > input").val(),
               password: $("#password > input").val()
        };
        $.ajax({
            type: "POST",
            url: "http://localhost:9000/login",
            contentType: "application/json",
            data: JSON.stringify(login)
        })
        .done(function(res){
          token_value = res.token;
              $("#test2").append(token_value);
          alert("You are logged in successfully");
        })
        .fail(function(error){
            console.log(error);
                    alert ("could not sign in");
        });

      return  token_value;
    };
</code>```

答: Have you tried storing token value in cookie and getting it from there whenever the token value is required.</p>

Body:
Need Help
Can anyone please suggest me How can i pass token_value to my all other function. token_value is the sucs response value. If i call the login() function
it requires me to pass username and password. so I cant call the function. But I need to pass the token_value that generated once i login.

$("#submit_login").click(login);

   var token_value = "";
 function login(){
        var login = {
               username: $("#username > input").val(),
               password: $("#password > input").val()
        };
        $.ajax({
            type: "POST",
            url: "http://localhost:9000/login",
            contentType: "application/json",
            data: JSON.stringify(login)
        })
        .done(function(res){
          token_value = res.token;
              $("#test2").append(token_value);
          alert("You are logged in successfully");
        })
        .fail(function(error){
            console.log(error);
                    alert ("could not sign in");
        });

      return  token_value;
    };


问:
JSPM doesn't load dependencies as expected
I've forked the official Bootstrap repository (4.0.0-alpha.6) to implement Gulp rather than Grunt, and to start theming Bootstrap for our own needs.

The project we're developing uses JSPM for its package management. When we try and install our custom Bootstrap project, the dependencies aren't loading correctly.

Running;

```<code>jspm install bootstrap=github:TomFoyster/bootstrap@4.0.0-alpha6-ntt-0.0.3
</code>```

Gives;

```<code>Looking up github:TomFoyster/bootstrap
Updating registry cache...
Looking up npm:jquery
ok   Installed npm:jquery@3 (3.1.1)
ok   Installed bootstrap as github:TomFoyster/bootstrap@4.0.0-alpha6-ntt-0.0.3 (4.0.0-alpha6-ntt-0.0.3)
Installed Forks

                           npm:jquery 2.2.4 3.1.1

To inspect individual package constraints, use jspm inspect registry:name.

ok   Install complete.
</code>```

However, install the official Bootstrap package;

```<code>jspm install bootstrap@4.0.0-alpha.6
</code>```

Gives;

```<code>Updating registry cache...
Looking up github:twbs/bootstrap
Looking up npm:jquery
Looking up github:HubSpot/tether
ok   Installed github:HubSpot/tether@^1.1.1 (1.4.0)
ok   Installed bootstrap as github:twbs/bootstrap@4.0.0-alpha.6 (4.0.0-alpha.6)
ok   Install tree has no forks.

ok   Install complete.
</code>```

You can see the custom repo doesn't install Tether as a dependency, and also installs the jQuery forks - whereas the official package has no forks?

Both of the package.json files in each of the repositories contian the following;

```<code>"dependencies": {
    "jquery": ">=1.9.1",
    "tether": "^1.4.0"
},
</code>```

What have I missed?

答:
When you install a package through jspm it queries the jspm-registry to check if there is a defined alias or override for that package. So doing

```<code>jspm install bootstrap@4.0.0-alpha.6
</code>```

Will check the registry and find out that there is a custom override defined for bootstrap@4, which reads:

```<code>{
  "main": "dist/js/bootstrap",
  "files": null,
  "ignore": [
    "dist/js/npm"
  ],
  "shim": {
    "dist/js/bootstrap": {
      "deps": [
        "jquery",
        "tether"
      ],
      "exports": "$"
    }
  },
  "dependencies": {
    "jquery": "*",
    "tether": "github:HubSpot/tether@^1.1.1"
  }
}
</code>```

And this config overrides whatever is defined in github:twbs/bootstrap.

Your fork isn't present in the registry, so it installs just what's defined in package.json

Body:
I've forked the official Bootstrap repository (4.0.0-alpha.6) to implement Gulp rather than Grunt, and to start theming Bootstrap for our own needs.

The project we're developing uses JSPM for its package management. When we try and install our custom Bootstrap project, the dependencies aren't loading correctly.

Running;

jspm install bootstrap=github:TomFoyster/bootstrap@4.0.0-alpha6-ntt-0.0.3

Gives;

Looking up github:TomFoyster/bootstrap
Updating registry cache...
Looking up npm:jquery
ok   Installed npm:jquery@3 (3.1.1)
ok   Installed bootstrap as github:TomFoyster/bootstrap@4.0.0-alpha6-ntt-0.0.3 (4.0.0-alpha6-ntt-0.0.3)
Installed Forks

                           npm:jquery 2.2.4 3.1.1

To inspect individual package constraints, use jspm inspect registry:name.

ok   Install complete.

However, install the official Bootstrap package;

jspm install bootstrap@4.0.0-alpha.6

Gives;

Updating registry cache...
Looking up github:twbs/bootstrap
Looking up npm:jquery
Looking up github:HubSpot/tether
ok   Installed github:HubSpot/tether@^1.1.1 (1.4.0)
ok   Installed bootstrap as github:twbs/bootstrap@4.0.0-alpha.6 (4.0.0-alpha.6)
ok   Install tree has no forks.

ok   Install complete.

You can see the custom repo doesn't install Tether as a dependency, and also installs the jQuery forks - whereas the official package has no forks?

Both of the package.json files in each of the repositories contian the following;

"dependencies": {
    "jquery": ">=1.9.1",
    "tether": "^1.4.0"
},

What have I missed?

Body:
When you install a package through jspm it queries the jspm-registry to check if there is a defined alias or override for that package. So doing

jspm install bootstrap@4.0.0-alpha.6

Will check the registry and find out that there is a custom override defined for bootstrap@4, which reads:

{
  "main": "dist/js/bootstrap",
  "files": null,
  "ignore": [
    "dist/js/npm"
  ],
  "shim": {
    "dist/js/bootstrap": {
      "deps": [
        "jquery",
        "tether"
      ],
      "exports": "$"
    }
  },
  "dependencies": {
    "jquery": "*",
    "tether": "github:HubSpot/tether@^1.1.1"
  }
}

And this config overrides whatever is defined in github:twbs/bootstrap.

Your fork isn't present in the registry, so it installs just what's defined in package.json


问:
PHPinfo returns blank page
I am totally new to programming.. Was installing the wampserver.. I'm using windows, and I have a file called test.php inside the folder C:\wamp\www . Inside the test.php file, I have this code

```<code><?php phpinfo(); ?>
</code>```

Then I opened the firefox browser and then entered the statement below but it returns a blank page. Is the url below right?
http://localhost/www/test.php

Am I doing the right thing? Tried using the search function but couldn't get it to work. Thanks!

答: A blank page means that an error occurred before output began, and you have error display disabled. Check your web server error log.</p>

ContentLicense: CC BY-SA 2.5

Title: PHPinfo returns blank page

Body:
I am totally new to programming.. Was installing the wampserver.. I'm using windows, and I have a file called test.php inside the folder C:\wamp\www . Inside the test.php file, I have this code

<?php phpinfo(); ?>

Then I opened the firefox browser and then entered the statement below but it returns a blank page. Is the url below right?
http://localhost/www/test.php

Am I doing the right thing? Tried using the search function but couldn't get it to work. Thanks!


问:
Mixing events in a python turtle program
I am trying to write a python turtle program that behaves similarly to a regular event-driven program that uses a game loop. The program tries to mix mouse, keyboard and timer events as is as posted below.

My problem is that python doesn't seem to be able to mix the onkey() events with the ontimer() loop. When run, the program will animate the turtle and the onclick() event will work. The key press isn't even registered until the mouse is first clicked. Then, when the key is pressed to quit, I get a large list of errors in the shell. The bye() method seems to be terminating the program in a brutish fashion and not shutting down elegantly.

I think that I have the commands in the correct order.

Any suggestions will be appreciated!

```<code>import turtle

playGround = turtle.Screen()
playGround.screensize(800, 600, 'light blue')

bob = turtle.Turtle()
bob.color('red')
bob.pencolor('red')
bob.ht()

def teleport(x,y):
    bob.goto(x,y)

def quitThis():
    playGround.bye()

def moveAround():
   bob.fd(10)
   bob.rt(15)
   playGround.ontimer(moveAround,30)

playGround.onclick(teleport,btn=1)
playGround.onkey(quitThis,'q')

moveAround()

playGround.listen()
playGround.mainloop()
</code>```

答:
One problem I see with your code is you need to keep the moveAround() from happening during the teleport() otherwise you get confusing visuals.  I find with turtle that it helps to disable the event handler when inside the event hander and reenable it on the way out.

I believe the following will smooth out your events and allow them all to fire at the appropriate time.  I've added a state variable to help control the activity:

```<code>from turtle import Turtle, Screen

def teleport(x, y):
    global state

    playGround.onclick(None)  # disable handler inside handler

    if state == "running":
        state = "teleporting"
        bob.goto(x, y)
        state = "running"

    if state != "quitting":
        playGround.onclick(teleport)

def quitThis():
    global state

    state == "quitting"

    playGround.onkey(None, 'q')

    playGround.bye()

def moveAround():
    if state == "running":
        bob.fd(10)
        bob.rt(15)

    if state != "quitting":
        playGround.ontimer(moveAround, 30)

playGround = Screen()
playGround.screensize(800, 600, 'light blue')

bob = Turtle(visible=False)
bob.color('red')

playGround.onclick(teleport)
playGround.onkey(quitThis, 'q')
playGround.listen()

state = "running"

playGround.ontimer(moveAround, 100)

playGround.mainloop()
</code>```

when the key is pressed to quit, I get a large list of errors in the
  shell. The bye() method seems to be terminating the program in a
  brutish fashion

This is typical of turtle. If it really bothers you, see my answer to the question about Turtle window exit errors for one possible solution.

Body:
I am trying to write a python turtle program that behaves similarly to a regular event-driven program that uses a game loop. The program tries to mix mouse, keyboard and timer events as is as posted below.

My problem is that python doesn't seem to be able to mix the onkey() events with the ontimer() loop. When run, the program will animate the turtle and the onclick() event will work. The key press isn't even registered until the mouse is first clicked. Then, when the key is pressed to quit, I get a large list of errors in the shell. The bye() method seems to be terminating the program in a brutish fashion and not shutting down elegantly.

I think that I have the commands in the correct order.

Any suggestions will be appreciated!

import turtle

playGround = turtle.Screen()
playGround.screensize(800, 600, 'light blue')

bob = turtle.Turtle()
bob.color('red')
bob.pencolor('red')
bob.ht()

def teleport(x,y):
    bob.goto(x,y)

def quitThis():
    playGround.bye()

def moveAround():
   bob.fd(10)
   bob.rt(15)
   playGround.ontimer(moveAround,30)

playGround.onclick(teleport,btn=1)
playGround.onkey(quitThis,'q')

moveAround()

playGround.listen()
playGround.mainloop()

Body:
One problem I see with your code is you need to keep the moveAround() from happening during the teleport() otherwise you get confusing visuals.  I find with turtle that it helps to disable the event handler when inside the event hander and reenable it on the way out.

I believe the following will smooth out your events and allow them all to fire at the appropriate time.  I've added a state variable to help control the activity:

from turtle import Turtle, Screen

def teleport(x, y):
    global state

    playGround.onclick(None)  # disable handler inside handler

    if state == "running":
        state = "teleporting"
        bob.goto(x, y)
        state = "running"

    if state != "quitting":
        playGround.onclick(teleport)

def quitThis():
    global state

    state == "quitting"

    playGround.onkey(None, 'q')

    playGround.bye()

def moveAround():
    if state == "running":
        bob.fd(10)
        bob.rt(15)

    if state != "quitting":
        playGround.ontimer(moveAround, 30)

playGround = Screen()
playGround.screensize(800, 600, 'light blue')

bob = Turtle(visible=False)
bob.color('red')

playGround.onclick(teleport)
playGround.onkey(quitThis, 'q')
playGround.listen()

state = "running"

playGround.ontimer(moveAround, 100)

playGround.mainloop()

when the key is pressed to quit, I get a large list of errors in the
  shell. The bye() method seems to be terminating the program in a
  brutish fashion

This is typical of turtle. If it really bothers you, see my answer to the question about Turtle window exit errors for one possible solution.


问:
What does this line mean in C# r => r.Item1?
r => r.Item1 == dFName

Its part of this line

```<code>dFName = PropertyUtil.GetName<kUpdate>(r => r.Resolution);
fld2Lup = map.DTField2LookupMap[domType].First(r => r.Item1 == dFName );
</code>```

答:
That is essentialy..

Return the First item of the "DTField2LookupMap[domType]" collection where the items property "Item1" is equal to dfName

this is a lambda expression: https://msdn.microsoft.com/en-us/library/bb397687.aspx

Body:
r => r.Item1 == dFName

Its part of this line

dFName = PropertyUtil.GetName<kUpdate>(r => r.Resolution);
fld2Lup = map.DTField2LookupMap[domType].First(r => r.Item1 == dFName );


问:
Apache2 return php source code
I installed Apache2 in my Xubunt, but I have a problem, When I see a Html file it works but when I see a Php file, Apache shows my sources code and I don't see my site and my script don't works.

See my desktop:

答: Try installing libapache2-mod-php7.0. This package should get all scripts. If it is installed or won't help check logs in /var/log/apache2/* to see what is the problem. –</p>

Title: Apache2 return php source code


问:
Nesting an array in Jekyll with YAML
If I have this block in YAML:

```<code>- project:
  -
    name: Whiskers
    top_category: Cats
    thumb_url: thumb.jpg
    main:
      - image: cat.jpg
</code>```

Is it possible to chain one of the lines, as in:

```<code>- project:
  -
    name: Whiskers
    top_category: Cats
    thumb_url: thumb.jpg
    main:
      - image_data: cat.jpg, Somealttext!
</code>```

And then access it as:

?

If so, what would the Liquid layout look like?

```<code>{% for main in project.main %}
    {{ ??? }}
{% endfor %}
</code>```

答:
Let's consider having a data file _data/project.yml:

```<code>- project:
  -
    name: Whiskers
    top_category: Cats
    thumb_url: thumb.jpg
    main:
      - image_data: cat.jpg, Somealttext!
</code>```

Then we access main:

```<code>{% assign main = site.data.project[0].project[0].main[0] %}
</code>```

And split the content of image_data assuming the image_alt won't contain any commas:

```<code>{% assign data = main.image_data|split:"," %}
</code>```

Then we can access its values as:

```<code>{{ data[0] }}
<br>
{{ data[1] }}

<img src="{{data[0]}}" alt="{{data[1]}}" />
</code>```

Title: Nesting an array in Jekyll with YAML

Body:
If I have this block in YAML:

- project:
  -
    name: Whiskers
    top_category: Cats
    thumb_url: thumb.jpg
    main:
      - image: cat.jpg

Is it possible to chain one of the lines, as in:

- project:
  -
    name: Whiskers
    top_category: Cats
    thumb_url: thumb.jpg
    main:
      - image_data: cat.jpg, Somealttext!

And then access it as:

?

If so, what would the Liquid layout look like?

{% for main in project.main %}
    {{ ??? }}
{% endfor %}

Body:
Let's consider having a data file _data/project.yml:

- project:
  -
    name: Whiskers
    top_category: Cats
    thumb_url: thumb.jpg
    main:
      - image_data: cat.jpg, Somealttext!

Then we access main:

{% assign main = site.data.project[0].project[0].main[0] %}

And split the content of image_data assuming the image_alt won't contain any commas:

{% assign data = main.image_data|split:"," %}

Then we can access its values as:

{{ data[0] }}
<br>
{{ data[1] }}

<img src="{{data[0]}}" alt="{{data[1]}}" />


问:
Is it better to use DataTrigger instead of a databinding?
If I wanted to hide(or change visibility, color, etc) of an element in WPF is it better to use DataTrigger or a binding with a converter?

Sounds like two ways to achieve the same goal. When is it better to user one over another?

答:
The short answer is it depends.

Data Triggers only offer equality operations against a single data source.

If you need to have parameters or multi-value binding you would need to use a converter.


问:
Redshift JDBC connection fails authentication when user password with # character in it
I've run into a problem with JDBC connections to Redshift that I can't quite solve.  Using the example given in the documentation I can easily connect to a Redshift cluster when a user has a plain password, but when a user has a password with a # character in it I get an authentication failure.  I am able to connect to the cluster using SQL Workbench/J using both sets of credentials.  When I use the following, no connection problem.

```<code>        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoe");
        props.setProperty("password", "superSecret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);
</code>```

When I use the following,

```<code>        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoehash");
        props.setProperty("password", "superDouble#Secret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);
</code>```

I get the an authentication error

```<code>java.sql.SQLException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";
  at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(ErrorResponse.java:1830)
  at com.amazon.redshift.client.InboundDataHandler.read(InboundDataHandler.java:454)
  at com.amazon.support.channels.AbstractSocketChannel.readCallback(Unknown Source)
  at com.amazon.support.channels.PlainSocketChannel.read(Unknown Source)
Caused by: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";
</code>```

I can log onto the cluster with both accounts using SQL Workbench/J but for some reason I can't connect through my application.  Any ideas on what I'm doing wrong?

答:
I don't have enough points to comment.  I don't know if this will solve your issue or not.  But try this:

props.setProperty("password", "superDouble& #35;Secret");

Without the space between "&" and "#35;"

Alternatively

props.setProperty("password", "superDouble%23Secret");

Body:
I've run into a problem with JDBC connections to Redshift that I can't quite solve.  Using the example given in the documentation I can easily connect to a Redshift cluster when a user has a plain password, but when a user has a password with a # character in it I get an authentication failure.  I am able to connect to the cluster using SQL Workbench/J using both sets of credentials.  When I use the following, no connection problem.

        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoe");
        props.setProperty("password", "superSecret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);

When I use the following,

        DriverManager.setLoginTimeout(60);
        Properties props = new Properties();
        props.setProperty("user", "johndoehash");
        props.setProperty("password", "superDouble#Secret");
        props.setProperty("tcpKeepAlive", "true");

        Connection connection = DriverManager.getConnection("jdbc:redshift://xxxxxxx.us-east-1.redshift.amazonaws.com:5439/dev", props);

I get the an authentication error

java.sql.SQLException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";
  at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(ErrorResponse.java:1830)
  at com.amazon.redshift.client.InboundDataHandler.read(InboundDataHandler.java:454)
  at com.amazon.support.channels.AbstractSocketChannel.readCallback(Unknown Source)
  at com.amazon.support.channels.PlainSocketChannel.read(Unknown Source)
Caused by: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: password authentication failed for user "johndoehash";

I can log onto the cluster with both accounts using SQL Workbench/J but for some reason I can't connect through my application.  Any ideas on what I'm doing wrong?


问:
Render the same template with different text?
I have about 4-5 templates for my Django project. I want to use each template across about 10 pages(with 10 different sets of content/text) each.

I've been using contexts to fill out the relevant content on each page when it is rendered.

However, I'm not sure about any potential performance loss because the content is quite large. Is there a neat and efficient way to render one template with content relevant to a link clicked on a previous page.

what I'm currently doing:

index.html

```<code><div class='well well-sm well-md well-lg'>

<h1> {{variable1}} </h1>

</div>
</code>```

views.py

```<code>def page1(request):

   variable1 = 'Long text for each variable. Many variables on each page so
   lots of long text overall. '

   return render(request, 'index/base.html', {'variable': variable1})

def page2(request):

   variable1 = 'More long text. '

   return render(request, 'index/base.html', {'variable': variable1})
</code>```

Basically I want to know if there is a way of doing the above without having to use contexts. Or will I have to create a template for each page?

答:
Check django tutorial doc
In url:

```<code>url(r'^(?P<page_id>[0-9]+)/$', views.page, name='page'),
</code>```

In view:

```<code>def page(request, page_id):
   // have a dict or list, get result using the page_id
   return render(request, 'index/base.html', {'variable': variable})
</code>```

Or if you don't have a page_id/name system, you can use:

```<code>def page(request):
    url = request.path
    value = dict[url]
    render (...)
</code>```

Body:
I have about 4-5 templates for my Django project. I want to use each template across about 10 pages(with 10 different sets of content/text) each.

I've been using contexts to fill out the relevant content on each page when it is rendered.

However, I'm not sure about any potential performance loss because the content is quite large. Is there a neat and efficient way to render one template with content relevant to a link clicked on a previous page.

what I'm currently doing:

index.html

 {{variable1}}

views.py

def page1(request):

   variable1 = 'Long text for each variable. Many variables on each page so
   lots of long text overall. '

   return render(request, 'index/base.html', {'variable': variable1})

def page2(request):

   variable1 = 'More long text. '

   return render(request, 'index/base.html', {'variable': variable1})

Basically I want to know if there is a way of doing the above without having to use contexts. Or will I have to create a template for each page?

Body:
Check django tutorial doc
In url:

url(r'^(?P<page_id>[0-9]+)/$', views.page, name='page'),

In view:

def page(request, page_id):
   // have a dict or list, get result using the page_id
   return render(request, 'index/base.html', {'variable': variable})

Or if you don't have a page_id/name system, you can use:

def page(request):
    url = request.path
    value = dict[url]
    render (...)


问:
Get response from PHP code by Ajax
I try to send the data from the HTML form to php code by Ajax and it does not get the response

the html form get user_id from the user entry then send it by java script function that handle ajax code and send the user_id to php code to get user_id by $user_id = $_GET['user_id']; and search by the user_id then show what ever in php code in the other html code to show div content showdocument.getElementById("content").innerHTML=xmlhttp.responseText; response from php

function showUser(str) {
  if (str == "") {
    document.getElementById("content").innerHTML = "";
    return;
  }
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("POST", "http://localhost/gpms/admin_modify_user.php?user_id=" + str, true);
  xmlhttp.send();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <script src="http://localhost/gpms/admin_user.js"></script>
</head>

<body>
  <form method=post>
    <label> Enter User ID: </label>
    <input id="user_id" type=text name=user_id>
    <br><br>
    <input id="modify" type=submit value=Modify onclick="<script>showUser(user_id);</script>">
  </form>

</body></code>```

<?php

    $user_id = $_GET['user_id'];

    //create connection
    $conn = mysqli_connect("localhost","root","","gpms");

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM user WHERE user_id = '$user_id' ";
    $result = mysqli_query($conn, $sql);

    if (mysqli_query($conn, $sql)) {
        $row = mysqli_fetch_assoc($result);
        if ($row == 0) {
            echo "No Results";
        }
        else {
            $id = $row['user_id'];
            $name = $row['user_name'];
            $password = $row['user_password'];
     $email = $row['user_email'];
            $department = $row['user_department'];

            echo "
";
                echo "
";
                    echo "
";
                        echo " ID 	 Name 	 Password 	 E-mail 	 Department 	";
                    echo "
";
                    echo "
";
                        echo ' '. $id .' 	 '. $name .' 	 '. $password .' 	 '. $email .' 	 '. $department .' 	';
                    echo "
";
                echo "
";

                echo "<button onclick = 'editUser(\"$id\",\"$name\",\"$password\",\"$email\",\"$department\")' > Edit </button>";
                echo "<button onclick = 'deleteUser(".$id.")' > Delete </button>";
            echo "
";
        }
    }
    else {
        echo "Error: " . $sql . "
" . mysqli_error($conn);
    }

    $conn->close();
    ?>```

答:
Your onclick attribute is wrong. It should just be the Javascript code, it shouldn't have  around it.

```<code><input id="modify" type=submit value=Modify onclick="showUser(user_id);">
</code>```

If you had looked in your Javascript console you would have seen it complain of a syntax error when you clicked.

And in the PHP, this line:

```<code>if (mysqli_query($conn, $sql)) {
</code>```

should be:

```<code>if ($result) {
</code>```

Otherwise you do the same query twice, which is unnecessary.

Title: Get response from PHP code by Ajax

Body:
I try to send the data from the HTML form to php code by Ajax and it does not get the response

the html form get user_id from the user entry then send it by java script function that handle ajax code and send the user_id to php code to get user_id by $user_id = $_GET['user_id']; and search by the user_id then show what ever in php code in the other html code to show div content showdocument.getElementById("content").innerHTML=xmlhttp.responseText; response from php

function showUser(str) {
  if (str == "") {
    document.getElementById("content").innerHTML = "";
    return;
  }
  if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
      document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
  }
  xmlhttp.open("POST", "http://localhost/gpms/admin_modify_user.php?user_id=" + str, true);
  xmlhttp.send();
}

  <form method=post>
     Enter User ID:
    <input id="user_id" type=text name=user_id>

    <input id="modify" type=submit value=Modify onclick="">
  </form>

<?php

    $user_id = $_GET['user_id'];

    //create connection
    $conn = mysqli_connect("localhost","root","","gpms");

    // Check connection
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "SELECT * FROM user WHERE user_id = '$user_id' ";
    $result = mysqli_query($conn, $sql);

    if (mysqli_query($conn, $sql)) {
        $row = mysqli_fetch_assoc($result);
        if ($row == 0) {
            echo "No Results";
        }
        else {
            $id = $row['user_id'];
            $name = $row['user_name'];
            $password = $row['user_password'];
     $email = $row['user_email'];
            $department = $row['user_department'];

            echo "
";
                echo "
";
                    echo "
";
                        echo " ID 	 Name 	 Password 	 E-mail 	 Department 	";
                    echo "
";
                    echo "
";
                        echo ' '. $id .' 	 '. $name .' 	 '. $password .' 	 '. $email .' 	 '. $department .' 	';
                    echo "
";
                echo "
";

                echo "<button onclick = 'editUser(\"$id\",\"$name\",\"$password\",\"$email\",\"$department\")' > Edit </button>";
                echo "<button onclick = 'deleteUser(".$id.")' > Delete </button>";
            echo "
";
        }
    }
    else {
        echo "Error: " . $sql . "
" . mysqli_error($conn);
    }

    $conn->close();
    ?>

Body:
Your onclick attribute is wrong. It should just be the Javascript code, it shouldn't have <script>...</script> around it.

<input id="modify" type=submit value=Modify onclick="showUser(user_id);">

If you had looked in your Javascript console you would have seen it complain of a syntax error when you clicked.

And in the PHP, this line:

if (mysqli_query($conn, $sql)) {

should be:

if ($result) {

Otherwise you do the same query twice, which is unnecessary.


问:
MinGW in Code::Blocks not linking static OpenSSL Library
I'm trying to take advantage of some of OpenSSL's EC cryptography and ECDSA functionality to make a rudimentary blockchain simulation, but I've run into a major roadblock. I'm using the Code::Blocks IDE, and I've installed OpenSSL using the 64-bit binary found here: https://slproweb.com/products/Win32OpenSSL.html.

In Linker Settings, I added OpenSSL-Win64\lib\openssl.lib

In Search Directories > Compiler, I added OpenSSL-Win64\include

In Search Directories > Linker, I added OpenSSL-Win64\lib

However, when I compile, I get the "undefined reference to (function name)" error for every OpenSSL function I try to use. However, the compiler seems to be successfully including the header files, since it recognizes the new data types like EC_KEY. I suspect a linking error, but I'm not sure what could be wrong, since I have the link paths and static library linked as above.

Here is my build log:

```<code>mingw32-g++.exe -LD:\OpenSSL-Win64\lib -LD:\OpenSSL-Win64\include -LD:\OpenSSL-Win64 -o bin\Debug\BlockchainSim.exe obj\Debug\main.o     obj\Debug\src\Block.o obj\Debug\src\BlockchainNode.o obj\Debug\src\Transaction.o     obj\Debug\src\Valuable.o   D:\OpenSSL-Win64\lib\openssl.lib
obj\Debug\src\BlockchainNode.o: In function `ZN14BlockchainNodeC2Ei':
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:18: undefined reference to `EC_KEY_new_by_curve_name'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:21: undefined reference to `BN_new'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:22: undefined reference to `EC_KEY_set_private_key'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:25: undefined reference to `BN_CTX_new'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:26: undefined reference to `BN_CTX_start'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:28: undefined reference to `EC_KEY_get0_group'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:29: undefined reference to `EC_POINT_new'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:30: undefined reference to `EC_POINT_mul'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:31: undefined reference to `EC_KEY_set_public_key'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:34: undefined reference to `EC_POINT_free'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:35: undefined reference to `BN_CTX_end'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:36: undefined reference to `BN_CTX_free'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:37: undefined reference to `BN_clear_free'
obj\Debug\src\BlockchainNode.o: In function `ZN14BlockchainNodeD2Ev':
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:42: undefined reference to `EC_KEY_free'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
15 error(s), 0 warning(s) (0 minute(s), 0 second(s))
</code>```

I'm hoping I'm just missing something simple here since I'm new to linking static libraries. A lot of similar issues seem to be solved by adding options to compile commands, but since I'm using Code::Blocks and linking OpenSSL as a static library, I'm not sure if those apply here. Any help is greatly appreciated.

答:
Figured it out. The issue was that I had no C:/MinGW folder (as Code::Blocks installed MinGW within its own directory). I'm guessing the binary I used tries to detect existing compilers and compiles the library differently depending on what it finds.

I fixed it by installing default MinGW (with MSYS, in case that matters) with the default path (C:/MinGW) and then reinstalling the 32-bit binary OpenSSL linked in the original question, also in the default path (C:/OpenSSL-Win32). This made it so that within the C:/OpenSSL-Win32/lib folder, there was a new MinGW folder which I then included in the linker search directories.

Body:
I'm trying to take advantage of some of OpenSSL's EC cryptography and ECDSA functionality to make a rudimentary blockchain simulation, but I've run into a major roadblock. I'm using the Code::Blocks IDE, and I've installed OpenSSL using the 64-bit binary found here: https://slproweb.com/products/Win32OpenSSL.html.

In Linker Settings, I added OpenSSL-Win64\lib\openssl.lib

In Search Directories > Compiler, I added OpenSSL-Win64\include

In Search Directories > Linker, I added OpenSSL-Win64\lib

However, when I compile, I get the "undefined reference to (function name)" error for every OpenSSL function I try to use. However, the compiler seems to be successfully including the header files, since it recognizes the new data types like EC_KEY. I suspect a linking error, but I'm not sure what could be wrong, since I have the link paths and static library linked as above.

Here is my build log:

mingw32-g++.exe -LD:\OpenSSL-Win64\lib -LD:\OpenSSL-Win64\include -LD:\OpenSSL-Win64 -o bin\Debug\BlockchainSim.exe obj\Debug\main.o     obj\Debug\src\Block.o obj\Debug\src\BlockchainNode.o obj\Debug\src\Transaction.o     obj\Debug\src\Valuable.o   D:\OpenSSL-Win64\lib\openssl.lib
obj\Debug\src\BlockchainNode.o: In function `ZN14BlockchainNodeC2Ei':
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:18: undefined reference to `EC_KEY_new_by_curve_name'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:21: undefined reference to `BN_new'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:22: undefined reference to `EC_KEY_set_private_key'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:25: undefined reference to `BN_CTX_new'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:26: undefined reference to `BN_CTX_start'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:28: undefined reference to `EC_KEY_get0_group'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:29: undefined reference to `EC_POINT_new'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:30: undefined reference to `EC_POINT_mul'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:31: undefined reference to `EC_KEY_set_public_key'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:34: undefined reference to `EC_POINT_free'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:35: undefined reference to `BN_CTX_end'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:36: undefined reference to `BN_CTX_free'
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:37: undefined reference to `BN_clear_free'
obj\Debug\src\BlockchainNode.o: In function `ZN14BlockchainNodeD2Ev':
F:/School/Barrett/BlockchainSim/src/BlockchainNode.cpp:42: undefined reference to `EC_KEY_free'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
15 error(s), 0 warning(s) (0 minute(s), 0 second(s))

I'm hoping I'm just missing something simple here since I'm new to linking static libraries. A lot of similar issues seem to be solved by adding options to compile commands, but since I'm using Code::Blocks and linking OpenSSL as a static library, I'm not sure if those apply here. Any help is greatly appreciated.


问:
Is it possible to know what text is displaying nearby the mouse?
I am just planning to implement some features like "Look up in Dictionary" when the mouse hovers over some text/words on the screen on the Mac OS X platform.

How can I get the displaying text/words nearby the mouse on the screen, even if they're not in my own application.

What I can do is:

Using WorkSpace to know what applications are running.

Use accessibility API to know the top UIElement on the screen.

Use accessibility API to know the selected string of a UIElement if the application use something like NSTextView (I get get it by check the "selected text" attribute of the UIElement).

What I can't do is:

Some applications like Safari, using WebKit framework, the only things I can get from Accessibility API are "value attribute", which is the current content of the HTML, and some attributes named like "AXTextMarker". These attributes can't not be found in Google or any document.

Some applications even do not support Accessibility API, what I can get is just a screen shot of it.

Is there any way to call system API to recognize the text in the image? In Snow Leopard, there is a handwriting recognizer feature for input in Chinese or Japanese, so should it be some OCR feature? I can't find any open API for it.

答:
What you can probably do is this:

Use a meta-key + a key chord to activate the dictionary once text is selected.  I'd actually find it incredibly obnoxious if whenever I was near text for a bit, a dictionary popped up.  Particularly because I read a tremendous number of white papers, where almost any dictionary imaginable would spend most of its time choking and dying.


问:
How would i get rid of a frame, whats placed on a frame when wanting to display another frame?
As you can see by the code, on the MainWindow it should display a blue and a green box, one ontop of the other and then the SecondMainWindow should have a red and yollow box displaying on ontop of the other. By running the code you can see that from the login window to the MainWindow all the frames remain as they should due to them only being on the MainWindowand the SecondMainWindow
However the problem persists when you go from the MainWindow to the SecondMainWindow where the fames are getting mixed up with which window thier on. I've set the background to MainWindow and SecondMainWindow to different colours to further develop an understanding on what frame should be shown.

```<code>import tkinter as tk
class start(tk.Tk):
  def __init__(self):
     tk.Tk.__init__(self)
     self.frame = login()
     self.frame.grid()

  def change(self, frame):
    self.frame.grid_forget()
    self.frame = frame()
    self.frame.grid()

class login(tk.Frame):
  def __init__(self, master=None, **kwargs):
    tk.Frame.__init__(self, master, **kwargs)
    self.master.geometry('300x300')
    self.master.configure(bg='orange')

    button1 = tk.Button(self.master, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)

  def ChangeFrame(self):
    self.master.change(MainWindow)

class MainWindow (tk.Frame):
  def __init__(self, master=None, **kwargs):
    tk.Frame.__init__(self, master, **kwargs)
    self.master.geometry('300x300')
    self.master.configure(bg='white')

    self.master.grid_rowconfigure(0, weight=2)
    self.master.grid_rowconfigure(1, weight=3)

    self.master.grid_columnconfigure(0, weight=1)

    Frame1 = tk.Frame(self.master, background='blue', bd=1, relief='sunken')
    Frame1.grid(row=0,column=0,padx=10,pady=10,sticky='nsew')

    Frame2 = tk.Frame(self.master, background='green', bd=1, relief='sunken')
    Frame2.grid(row=1,column=0,padx=10,pady=10,sticky='nsew')

    button1 = tk.Button(Frame1, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)

  def ChangeFrame(self):
    self.master.change(SecondMainWindow)

class SecondMainWindow (tk.Frame):
  def __init__(self, master=None, **kwargs):
    tk.Frame.__init__(self, master, **kwargs)
    self.master.geometry('300x300')
    self.master.configure(bg='grey')

    self.master.grid_rowconfigure(0, weight=1)
    self.master.grid_rowconfigure(1, weight=1)

    self.master.grid_columnconfigure(0, weight=1)
    self.master.grid_columnconfigure(1, weight=1)

    Frame3 = tk.Frame(self.master, background='yellow', bd=1, relief='sunken')
    Frame3.grid(row=1,column=1,padx=10,pady=10,sticky='nsew')

    Frame4 = tk.Frame(self.master, background='red', bd=1, relief='sunken')
    Frame4.grid(row=0,column=1,padx=10,pady=10,sticky='nsew')

    button1 = tk.Button(Frame4, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)

  def ChangeFrame(self):
    self.master.change(MainWindow)

app = start()
app.mainloop()
</code>```

With only self being used

With only self.master being used

As you can see when using, just self it alters with the layout, how would i fix this?

答:
You are placing widgets for every window in self.master but the code that you copied from was designed so that each window is an independent object. All of the widgets in a single window must be children of that window.

In short, instead of this:

```<code>class SecondMainWindow (tk.Frame):
    def __init__(self, master=None, **kwargs):
        ...
        Frame3 = tk.Frame(self.master, ...)
        Frame4 = tk.Frame(self.master, ...)
        ...
</code>```

You should be doing this:

```<code>class SecondMainWindow (tk.Frame):
    def __init__(self, master=None, **kwargs):
        ...
        Frame3 = tk.Frame(self, ...)
        Frame4 = tk.Frame(self, ...)
        ...
</code>```

If you want every window to put widgets directly in the root window, there's no reason for you to create classes that inherit from tk.Frame.

Body:
As you can see by the code, on the MainWindow it should display a blue and a green box, one ontop of the other and then the SecondMainWindow should have a red and yollow box displaying on ontop of the other. By running the code you can see that from the login window to the MainWindow all the frames remain as they should due to them only being on the MainWindowand the SecondMainWindow
However the problem persists when you go from the MainWindow to the SecondMainWindow where the fames are getting mixed up with which window thier on. I've set the background to MainWindow and SecondMainWindow to different colours to further develop an understanding on what frame should be shown.

import tkinter as tk
class start(tk.Tk):
  def __init__(self):
     tk.Tk.__init__(self)
     self.frame = login()
     self.frame.grid()

  def change(self, frame):
    self.frame.grid_forget()
    self.frame = frame()
    self.frame.grid()

class login(tk.Frame):
  def __init__(self, master=None, **kwargs):
    tk.Frame.__init__(self, master, **kwargs)
    self.master.geometry('300x300')
    self.master.configure(bg='orange')

    button1 = tk.Button(self.master, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)

  def ChangeFrame(self):
    self.master.change(MainWindow)

class MainWindow (tk.Frame):
  def __init__(self, master=None, **kwargs):
    tk.Frame.__init__(self, master, **kwargs)
    self.master.geometry('300x300')
    self.master.configure(bg='white')

    self.master.grid_rowconfigure(0, weight=2)
    self.master.grid_rowconfigure(1, weight=3)

    self.master.grid_columnconfigure(0, weight=1)

    Frame1 = tk.Frame(self.master, background='blue', bd=1, relief='sunken')
    Frame1.grid(row=0,column=0,padx=10,pady=10,sticky='nsew')

    Frame2 = tk.Frame(self.master, background='green', bd=1, relief='sunken')
    Frame2.grid(row=1,column=0,padx=10,pady=10,sticky='nsew')

    button1 = tk.Button(Frame1, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)

  def ChangeFrame(self):
    self.master.change(SecondMainWindow)

class SecondMainWindow (tk.Frame):
  def __init__(self, master=None, **kwargs):
    tk.Frame.__init__(self, master, **kwargs)
    self.master.geometry('300x300')
    self.master.configure(bg='grey')

    self.master.grid_rowconfigure(0, weight=1)
    self.master.grid_rowconfigure(1, weight=1)

    self.master.grid_columnconfigure(0, weight=1)
    self.master.grid_columnconfigure(1, weight=1)

    Frame3 = tk.Frame(self.master, background='yellow', bd=1, relief='sunken')
    Frame3.grid(row=1,column=1,padx=10,pady=10,sticky='nsew')

    Frame4 = tk.Frame(self.master, background='red', bd=1, relief='sunken')
    Frame4.grid(row=0,column=1,padx=10,pady=10,sticky='nsew')

    button1 = tk.Button(Frame4, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)

  def ChangeFrame(self):
    self.master.change(MainWindow)

app = start()
app.mainloop()

With only self being used

With only self.master being used

As you can see when using, just self it alters with the layout, how would i fix this?

Body:
You are placing widgets for every window in self.master but the code that you copied from was designed so that each window is an independent object. All of the widgets in a single window must be children of that window.

In short, instead of this:

class SecondMainWindow (tk.Frame):
    def __init__(self, master=None, **kwargs):
        ...
        Frame3 = tk.Frame(self.master, ...)
        Frame4 = tk.Frame(self.master, ...)
        ...

You should be doing this:

class SecondMainWindow (tk.Frame):
    def __init__(self, master=None, **kwargs):
        ...
        Frame3 = tk.Frame(self, ...)
        Frame4 = tk.Frame(self, ...)
        ...

If you want every window to put widgets directly in the root window, there's no reason for you to create classes that inherit from tk.Frame.


问:
Why is my Line Chart.JS starting in the middle?
I am trying to add some JS chart to my webpage, but somehow the line starts in the middle of the graph. (No matter how many data points there are)

See Below:

There are only 3 data points, but the line starts only at the very end. And only one label shows up even there are 3 data point

Does anyone have any idea why?  Thanks!

Code:

```<code> // Line chart
  var ctx = document.getElementById("instance_countChart");
  var instance_countChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: [
       "gukumar_skb_regression_03_17_17_23.45",

       "gukumar_skb_regression_03_18_17_23.45",

       "gukumar_skb_regression_03_19_17_23.45",
                ],
      datasets: [{
      label: "instance_count",
        backgroundColor: "transparent",
        borderColor: "rgba(38, 185, 154, 0.7)",
        pointBorderColor: "rgba(38, 185, 154, 0.7)",
        pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointBorderWidth: 1,
      //backgroundColor: "#26B99A",
      data: [  7409085.0,  7409085.0,  7409041.0,
    ]
    }]
    },

  });
</code>```

How I am calling it:

```<code>    <div class="col-md-4 col-sm-6 col-xs-12">
          <div class="x_panel">
            <div class="x_title">
              <h2>instancecount </h2>
              <ul class="nav navbar-right panel_toolbox">
                <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                </li>
                <li class="dropdown">
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><i class="fa fa-wrench"></i></a>
                  <ul class="dropdown-menu" role="menu">
                    <li><a href="#">Settings 1</a>
                    </li>
                    <li><a href="#">Settings 2</a>
                    </li>
                  </ul>
                </li>
                <li><a class="close-link"><i class="fa fa-close"></i></a>
                </li>
              </ul>
              <div class="clearfix"></div>
            </div>
            <div class="x_content">
              <canvas id="instance_countChart" width="400" height="200"></canvas>
            </div>
          </div>
        </div>
</code>```

答:
Not sure why it happens, after reading the documentation, and doing some experiments.  If I turn off the XAxes, the line starts from the beginning. But with the Axes label on, I am still not able to get it correctly. </p>

```<code>   options: {
       scales: {
           xAxes: [{
               display: false
           }]
       }
   }
</code>```

Body:
I am trying to add some JS chart to my webpage, but somehow the line starts in the middle of the graph. (No matter how many data points there are)

See Below:

There are only 3 data points, but the line starts only at the very end. And only one label shows up even there are 3 data point

Does anyone have any idea why?  Thanks!

Code:

 // Line chart
  var ctx = document.getElementById("instance_countChart");
  var instance_countChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: [
       "gukumar_skb_regression_03_17_17_23.45",

       "gukumar_skb_regression_03_18_17_23.45",

       "gukumar_skb_regression_03_19_17_23.45",
                ],
      datasets: [{
      label: "instance_count",
        backgroundColor: "transparent",
        borderColor: "rgba(38, 185, 154, 0.7)",
        pointBorderColor: "rgba(38, 185, 154, 0.7)",
        pointBackgroundColor: "rgba(38, 185, 154, 0.7)",
        pointHoverBorderColor: "rgba(220,220,220,1)",
        pointBorderWidth: 1,
      //backgroundColor: "#26B99A",
      data: [  7409085.0,  7409085.0,  7409041.0,
    ]
    }]
    },

  });

How I am calling it:

instancecount

Settings 1

Settings 2

              <canvas id="instance_countChart" width="400" height="200"></canvas>

Body:
Not sure why it happens, after reading the documentation, and doing some experiments.  If I turn off the XAxes, the line starts from the beginning. But with the Axes label on, I am still not able to get it correctly.

   options: {
       scales: {
           xAxes: [{
               display: false
           }]
       }
   }