问:
How can I pass an object as an url variable in flask?
I am new to python and Flask. I am currently working on a project where I need to render different pages for different actions but they both need to have access to the one same object.

for example:

```<code>@app.route("/", methods =['GET','POST'])
def funtionA()
    objs = somefunction() // returns an object list
    render_template("/results/'+objs+'")

@app.route("/results/<objs>", methods =['GET','POST'])
def functionB(objs)
    for obj in objs
       print(objs[i].attr)
</code>```

I am able to pass string, integer even path as a parameter. I couldn't find any references to see if passing an object is doable or not. Appreciate your responses!

Thanks,
Deepak

答:
You could use an application global. This is accessible via flask.g

http://flask.pocoo.org/docs/0.12/api/#application-globals

Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request.

Body:
I am new to python and Flask. I am currently working on a project where I need to render different pages for different actions but they both need to have access to the one same object.

for example:

@app.route("/", methods =['GET','POST'])
def funtionA()
    objs = somefunction() // returns an object list
    render_template("/results/'+objs+'")

@app.route("/results/<objs>", methods =['GET','POST'])
def functionB(objs)
    for obj in objs
       print(objs[i].attr)

I am able to pass string, integer even path as a parameter. I couldn't find any references to see if passing an object is doable or not. Appreciate your responses!

Thanks,
Deepak


来源: stackexchange

问:
Add a dictionary to a dictionary
I'd like if it would be possible to do something like this :

```<code>pre_dict = {'pictures'}
to_add = {'extension' : 'jpeg'}
'pictures'.update(to_add)?
</code>```

So that I could end up getting this :

```<code>pre_dict = {'pictures' : {'extension' : 'jpeg'}
</code>```

And add other elements such as this :

```<code>'pictures'.update({'size':10000})
</code>```

To finally get this:

```<code> pre_dict = {'pictures' : {'extension' : 'jpeg', 'size':10000}
</code>```

Thank you !

答:
yes, define your pre_dict value as an empty dictionary (it is currently a set):

```<code>pre_dict = {'pictures':{}}
to_add = {'extension' : 'jpeg'}
pre_dict['pictures'].update(to_add)
pre_dict['pictures'].update({'size':10000})  # your other update operation
print(pre_dict)
</code>```

result:

```<code>{'pictures': {'size': 10000, 'extension': 'jpeg'}}
</code>```

Note that update is overkill to add a single value (but useful for inputs like {'extension' : 'jpeg', 'size':10000}). For one value just do:

```<code>pre_dict['pictures']['size'] = 10000
</code>```

ContentLicense: CC BY-SA 3.0

Title: Add a dictionary to a dictionary

Body:
I'd like if it would be possible to do something like this :

pre_dict = {'pictures'}
to_add = {'extension' : 'jpeg'}
'pictures'.update(to_add)?

So that I could end up getting this :

pre_dict = {'pictures' : {'extension' : 'jpeg'}

And add other elements such as this :

'pictures'.update({'size':10000})

To finally get this:

 pre_dict = {'pictures' : {'extension' : 'jpeg', 'size':10000}

Thank you !

Body:
yes, define your pre_dict value as an empty dictionary (it is currently a set):

pre_dict = {'pictures':{}}
to_add = {'extension' : 'jpeg'}
pre_dict['pictures'].update(to_add)
pre_dict['pictures'].update({'size':10000})  # your other update operation
print(pre_dict)

result:

{'pictures': {'size': 10000, 'extension': 'jpeg'}}

Note that update is overkill to add a single value (but useful for inputs like {'extension' : 'jpeg', 'size':10000}). For one value just do:

pre_dict['pictures']['size'] = 10000


问:
Accessing Properties of the code-behind from aspx page in web application project
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
<div>
<%= x2 %>
<%# x2 %>
</div>
</form>
</body>
</html>
</code>```

Codebehind file :

```<code>using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}
</code>```

It is working fine when I use the same technique in my website project
Kindly help
Thanks

答:
This works for me. Are you sure there's a value in ViewState? On form load add a value to test.

```<code>ViewState["FormMode"] = "ViewApplicant";
lblMessage.DataBind();
</code>```

Also make sure the label has some text to view. It could be showing but is empty.

```<code><asp:Label ID="lblMessage" runat="server"
    Text="some text"
    Visible='<%# FormMode == "View" || FormMode == "ViewApplicant" %>'>
</asp:Label>
</code>```

Body:
I have a property x in my code-behind file in a web application project. It gives me compile time error while it does not give any error in website project

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="test.WebForm1" %>
<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

<%= x2 %>
<%# x2 %>

</form>

Codebehind file :

using System;
namespace test
{public partial class WebForm1 : System.Web.UI.Page
{
    public int x2 = 2;
    protected void Page_Load(object sender, EventArgs e)
    {
    }
   }
}

It is working fine when I use the same technique in my website project
Kindly help
Thanks

Body:
This works for me. Are you sure there's a value in ViewState? On form load add a value to test.

ViewState["FormMode"] = "ViewApplicant";
lblMessage.DataBind();

Also make sure the label has some text to view. It could be showing but is empty.

<asp:Label ID="lblMessage" runat="server"
    Text="some text"
    Visible='<%# FormMode == "View" || FormMode == "ViewApplicant" %>'>
</asp:Label>


问:
Call a word SynonymInfo object variable from Excel VBA
There might be something fairly simple I am missing here, but I can't quite figure out why I am getting an "Object variable or Object With block not set" error. I am trying to take a string from Excel, and use VBA to call a Word function that yields synonyms. Here is some reproducible simple code that will cause the error I am running into:

```<code>Public Sub Tester()
    Dim WD As Word.Application
    Dim Syn As Word.SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = WD.SynonymInfo(wrd)
End Sub
</code>```

I made sure I went to Tools→References and selected the Microsoft Word Object Library, and I also entered the following code into a Word Application without error:

```<code>Public Sub Tester()
    Dim Syn As SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = SynonymInfo(wrd)
End Sub
</code>```

I am wondering if there is some reference I am not calling? I am trying to replicate from Excel the example seen here and wondering declaration I am missing from within Excel VBA to call this. Thanks much for your help!

答:
You haven't created your Word Application object so, in your existing code, WD is still Nothing - therefore you are effectively trying to execute the statement:

```<code>Set Syn = Nothing.SynonymInfo(wrd)
</code>```

Correct code would be:

```<code>Public Sub Tester()
    Dim WD As Word.Application
    Dim Syn As Word.SynonymInfo
    Dim wrd As String
    'Create a Word Application object
    Set WD = New Word.Application
    wrd = "Car"
    Set Syn = WD.SynonymInfo(wrd)
End Sub
</code>```

Body:
There might be something fairly simple I am missing here, but I can't quite figure out why I am getting an "Object variable or Object With block not set" error. I am trying to take a string from Excel, and use VBA to call a Word function that yields synonyms. Here is some reproducible simple code that will cause the error I am running into:

Public Sub Tester()
    Dim WD As Word.Application
    Dim Syn As Word.SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = WD.SynonymInfo(wrd)
End Sub

I made sure I went to Tools→References and selected the Microsoft Word Object Library, and I also entered the following code into a Word Application without error:

Public Sub Tester()
    Dim Syn As SynonymInfo
    Dim wrd As String
    wrd = "Car"
    Set Syn = SynonymInfo(wrd)
End Sub

I am wondering if there is some reference I am not calling? I am trying to replicate from Excel the example seen here and wondering declaration I am missing from within Excel VBA to call this. Thanks much for your help!

Body:
You haven't created your Word Application object so, in your existing code, WD is still Nothing - therefore you are effectively trying to execute the statement:

Set Syn = Nothing.SynonymInfo(wrd)

Correct code would be:

Public Sub Tester()
    Dim WD As Word.Application
    Dim Syn As Word.SynonymInfo
    Dim wrd As String
    'Create a Word Application object
    Set WD = New Word.Application
    wrd = "Car"
    Set Syn = WD.SynonymInfo(wrd)
End Sub


问:
Error CS0433: The type 'JsonValue' exists in both 'System.Json, Version=2.0.5.0' and 'Xamarin.Auth' (CS0433)
I'm trying to create an app in Visual studio for mac with Xamarin.Forms. In this app I'm using Xamarin.Auth to store some user details. Now I want to add a connection with an API by using JSON. I added System.Json and added my code. But the problem is I get the error:

Error CS0433: The type 'JsonValue' exists in both 'System.Json,
  Version=2.0.5.0' and 'Xamarin.Auth' (CS0433).

I removed and added Xamarin.Auth to the project. I removed the OBJ and BIN folders while visual studio was closed, started VS, cleaned the solution, rebuild the solution and tried it again but still the same error. I can't seem to find out what the problem is.

I'm not quite sure if it will help but here is one snippet of code where the error occurs, I know the function does not return anything at the moment but I'm just trying to figure out how to do JSON/API calls and get the code to compile without errors:

```<code>public class DBhandler
{
    public async Task<List<Object>> GetItemsFromApiASync(Type callingClass,    string apiDir, string apiFile)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(ApiAddress + apiDir + apiFile));
        request.ContentType = "application/json";
        request.Method = "Get";

        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                System.Json.JsonValue jsonDoc = await Task.Run(() => System.Json.JsonObject.Load(stream));
                object[] parametersArray = new object[] { jsonDoc };
                MethodInfo methodInfo = callingClass.GetMethod("ConvertApiResultToObject");
                methodInfo.Invoke(methodInfo, parametersArray);
            }
        }

        return null;
    }
</code>```

答:
All of a sudden I did remember how to solve this: I was helped by the comments on the question(thanks @Tcraft, @DiegoRafaelSouza). I added System.Json to the references on the different platforms(I use a shared project, so on project.IOS and project.Android). Right clicked on properties and ticked Local Copy. Then I added an alias SystemJsonAlias. And used using SystemJsonAlias = System.Json in all my .cs files where needed.

Perhaps this helps someone else.

Body:
I'm trying to create an app in Visual studio for mac with Xamarin.Forms. In this app I'm using Xamarin.Auth to store some user details. Now I want to add a connection with an API by using JSON. I added System.Json and added my code. But the problem is I get the error:

Error CS0433: The type 'JsonValue' exists in both 'System.Json,
  Version=2.0.5.0' and 'Xamarin.Auth' (CS0433).

I removed and added Xamarin.Auth to the project. I removed the OBJ and BIN folders while visual studio was closed, started VS, cleaned the solution, rebuild the solution and tried it again but still the same error. I can't seem to find out what the problem is.

I'm not quite sure if it will help but here is one snippet of code where the error occurs, I know the function does not return anything at the moment but I'm just trying to figure out how to do JSON/API calls and get the code to compile without errors:

public class DBhandler
{
    public async Task<List<Object>> GetItemsFromApiASync(Type callingClass,    string apiDir, string apiFile)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(ApiAddress + apiDir + apiFile));
        request.ContentType = "application/json";
        request.Method = "Get";

        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                System.Json.JsonValue jsonDoc = await Task.Run(() => System.Json.JsonObject.Load(stream));
                object[] parametersArray = new object[] { jsonDoc };
                MethodInfo methodInfo = callingClass.GetMethod("ConvertApiResultToObject");
                methodInfo.Invoke(methodInfo, parametersArray);
            }
        }

        return null;
    }


问:
Automating a input slider over time
I have a range input on my website like this:

```<code><input type="range"  min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/>
</code>```

I have some D3 code that loads a visualization onto the page. It's online here:

https://bl.ocks.org/KingOfCramers/raw/5c166e770c4a865d861452dd184b54f4/

Over the period of 10 seconds, I want to automate the value of the slider from it's min value to it's max value. The thumb slider should move accordingly.

I need this function (probably setTimeout?) to fire after the visualization has finished loading my D3 code (which is currently wrapped in a d3.queue function), and allow for the user to move the slider after it's reached the max value.

How would I do this in Javascript?

答:
Over the period of 10 seconds, I want to automate the value of the
  slider from it's min value to it's max value. The thumb slider should
  move accordingly

If you want a d3 way to do this, you can transition the slider with a d3 transition:

```<code>d3.select("#slider")
  .transition()
  .attr("value",maxValue)
  .duration(time); // in ms
</code>```

This simple implementation is shown below. If you want it execute after the visualization draws, place the transition at the end of your queue ready function.

d3.select("#slider")
  .transition()
  .attr("value",1510462800000)
  .duration(10000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<input type="range"  min="1036000000000" max="1510462800000" value="1036000000000" class="slider" id ="slider"/></code>```

The default easing is cubic in/out, which is shown above. If you want to change the easing, you can use d3.ease, this next snippet shows linear easing:

d3.select("#slider")
  .transition()
  .attr("value",1510462800000)
  .ease(d3.easeLinear)
  .duration(10000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<input type="range"  min="1036000000000" max="1510462800000" value="1036000000000" class="slider" id ="slider"/></code>```

You can update the value of another element as well with a slight modification, use the transition attrTween method to access the current value of the slider as it is being updated (you might want to format the number). This approach also lets you update your visualization as you transition the slider fairly easily:

d3.select("#slider")
  .transition()
  .attrTween("value",function() {
     return function(t) {
      var i = d3.interpolate(1036000000000, 1510462800000);
      d3.select("#text").html(i(t));
      d3.select("#input").attr("value",i(t));
      return i(t);
     }
  })
  .duration(1000);
  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<input type="range"  min="1036000000000" max="1510462800000" value="1036000000000" class="slider" id ="slider"/>

<p id="text"> </p>
<input type="text" id="input" value="0"/></code>```

Title: Automating a input slider over time

Body:
I have a range input on my website like this:

<input type="range"  min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/>

I have some D3 code that loads a visualization onto the page. It's online here:

https://bl.ocks.org/KingOfCramers/raw/5c166e770c4a865d861452dd184b54f4/

Over the period of 10 seconds, I want to automate the value of the slider from it's min value to it's max value. The thumb slider should move accordingly.

I need this function (probably setTimeout?) to fire after the visualization has finished loading my D3 code (which is currently wrapped in a d3.queue function), and allow for the user to move the slider after it's reached the max value.

How would I do this in Javascript?

Body:
Over the period of 10 seconds, I want to automate the value of the
  slider from it's min value to it's max value. The thumb slider should
  move accordingly

If you want a d3 way to do this, you can transition the slider with a d3 transition:

d3.select("#slider")
  .transition()
  .attr("value",maxValue)
  .duration(time); // in ms

This simple implementation is shown below. If you want it execute after the visualization draws, place the transition at the end of your queue ready function.

d3.select("#slider")
  .transition()
  .attr("value",1510462800000)
  .duration(10000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<input type="range"  min="1036000000000" max="1510462800000" value="1036000000000" class="slider" id ="slider"/>

The default easing is cubic in/out, which is shown above. If you want to change the easing, you can use d3.ease, this next snippet shows linear easing:

d3.select("#slider")
  .transition()
  .attr("value",1510462800000)
  .ease(d3.easeLinear)
  .duration(10000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<input type="range"  min="1036000000000" max="1510462800000" value="1036000000000" class="slider" id ="slider"/>

You can update the value of another element as well with a slight modification, use the transition attrTween method to access the current value of the slider as it is being updated (you might want to format the number). This approach also lets you update your visualization as you transition the slider fairly easily:

d3.select("#slider")
  .transition()
  .attrTween("value",function() {
     return function(t) {
      var i = d3.interpolate(1036000000000, 1510462800000);
      d3.select("#text").html(i(t));
      d3.select("#input").attr("value",i(t));
      return i(t);
     }
  })
  .duration(1000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>

<input type="range"  min="1036000000000" max="1510462800000" value="1036000000000" class="slider" id ="slider"/>

<p id="text"> </p>
<input type="text" id="input" value="0"/>


问:
SSL Self-Signed CA Certificates and PHP Issue/Authentication
I've been writing an authentication routine in PHP to allow company users to access a new tool over Internet.  I've got most everything figured out, but when it comes to how to safely 'remember' an authenticated user between sessions, I'm curious about something.

Based on the dearth of information surrounding it, I get the feeling not a lot of people use client-side SSL certificates to verify if a user is coming from a trusted computer.  In my mind, so long as you can get the user to trust your CA (not an issue inside a company), why isn't there a nice, simple way to request, sign, issue, and install a new client cert that helps prevent MITM much better than say a cookie would?

I'm not expecting the client cert to be the end all be all, but is there some resource I am missing that would help further me along down this path?  Or is the rabbit hole far too deep and the only thing my exhaustive searches lack is the word "nightmare" to expose how crappy this really is?

Thanks!

答:
A lot of people use client-side certificates. Pretty much the entire US Federal Government does.

The problem is that it takes a lot of know-how to do it correctly. But, done correctly, it works great, and can provide far stronger security than password based authentication.

ContentLicense: CC BY-SA 2.5


问:
create UITableViewCell constraint programmatically
This is all taking place within this class:

```<code>class CustomCell2: UITableViewCell {
</code>```

When I print the value of an existing width constraint (label = 0.7 * width of the cell) that was set in Storyboard, I see this:

```<code><NSLayoutConstraint:0x36b8750 UILabel:0x3d2aac0'Label'.width == 0.7*appName.CustomCell2:0x3e01880'CustomCell2'.width>
</code>```

When I try to create the same constraint programmatically, I get the error "The view hierarchy is not prepared for the constraint:"

```<code><NSLayoutConstraint:0xee08590 UILabel:0x3d2aac0'Label'.width == 0.9*appName.CustomCell2:0x3e01880'CustomCell2'.width>
</code>```

Seems exactly the same, so why can't that constraint be added?

Constraint code in awakeFromNib() of CustomCell2:

```<code>let widthConstraint = NSLayoutConstraint(item: labelName, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 0.9, constant: 0)
labelName.addConstraint(widthConstraint)
</code>```

Rest of the error message:

```<code>When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.
2017-12-03 20:18:51.183 appName[899:684382] View hierarchy unprepared for constraint.
    Constraint: <NSLayoutConstraint:0xee08590 UILabel:0x3d2aac0'Label'.width == 0.9*appName.CustomCell2:0x3e01880'CustomCell2'.width>
    Container hierarchy:
<UILabel: 0x3d2aac0; frame = (281 43; 674 54); text = 'Label'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x4233d30>>
    View not found in container hierarchy: <appName.CustomCell2: 0x3e01880; baseClass = UITableViewCell; frame = (0 0; 963 160); layer = <CALayer: 0xee08250>>
    That view's superview: NO SUPERVIEW
Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. constraint:<NSLayoutConstraint:0xee08590 UILabel:0x3d2aac0'Label'.width == 0.9*appName.CustomCell2:0x3e01880'CustomCell2'.width> view:<UILabel: 0x3d2aac0; frame = (281 43; 674 54); text = 'Label'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x4233d30>>
</code>```

Thanks!

答: A user on Apple's Developer Forums pointed me in the right direction. The constraint was between the label and the cell (the cell being referred to as 'self' in the class for the custom cell) and the answer here was that I had to addConstraint to the cell instead of adding it to the label. Same exact constraint definition, but it only worked as self.addConstraint() and gave the error "The view hierarchy is not prepared for the constraint" when coded as labelName.addConstraint()</p>

Body:
This is all taking place within this class:

class CustomCell2: UITableViewCell {

When I print the value of an existing width constraint (label = 0.7 * width of the cell) that was set in Storyboard, I see this:

<NSLayoutConstraint:0x36b8750 UILabel:0x3d2aac0'Label'.width == 0.7*appName.CustomCell2:0x3e01880'CustomCell2'.width>

When I try to create the same constraint programmatically, I get the error "The view hierarchy is not prepared for the constraint:"

<NSLayoutConstraint:0xee08590 UILabel:0x3d2aac0'Label'.width == 0.9*appName.CustomCell2:0x3e01880'CustomCell2'.width>

Seems exactly the same, so why can't that constraint be added?

Constraint code in awakeFromNib() of CustomCell2:

let widthConstraint = NSLayoutConstraint(item: labelName, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.width, multiplier: 0.9, constant: 0)
labelName.addConstraint(widthConstraint)

Rest of the error message:

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.
2017-12-03 20:18:51.183 appName[899:684382] View hierarchy unprepared for constraint.
    Constraint: <NSLayoutConstraint:0xee08590 UILabel:0x3d2aac0'Label'.width == 0.9*appName.CustomCell2:0x3e01880'CustomCell2'.width>
    Container hierarchy:
<UILabel: 0x3d2aac0; frame = (281 43; 674 54); text = 'Label'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x4233d30>>
    View not found in container hierarchy: <appName.CustomCell2: 0x3e01880; baseClass = UITableViewCell; frame = (0 0; 963 160); layer = <CALayer: 0xee08250>>
    That view's superview: NO SUPERVIEW
Unable to install constraint on view.  Does the constraint reference something from outside the subtree of the view?  That's illegal. constraint:<NSLayoutConstraint:0xee08590 UILabel:0x3d2aac0'Label'.width == 0.9*appName.CustomCell2:0x3e01880'CustomCell2'.width> view:<UILabel: 0x3d2aac0; frame = (281 43; 674 54); text = 'Label'; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x4233d30>>

Thanks!


问:
Mysql - speed up select query from 2 million rows
I have a table like below,

```<code>Field    Type      Null Key Default               Extra

id       bigint(11) NO  PRI NULL                  auto_increment
deviceId bigint(11) NO  MUL NULL
value    double     NO      NULL
time    timestamp   YES MUL 0000-00-00 00:00:00
</code>```

It has more than 2 million rows. When I run select * from tableName; It takes more than 15 mins.

When I run select value,time from sensor_value where time > '2017-05-21 04:47:48' and deviceId>=812; It takes more than 45 sec to load.

Note :  512 has more than 92514 rows.
Even I have added index for column like below,

```<code>ALTER TABLE `sensor_value`
 ADD INDEX `IDX_FIELDS1_2` (`time`, `deviceId`) ;
</code>```

How do I make select query fast?(load in 1sec) Am I doing indexing wrong?

答:
Only 4 columns?  Sounds like you have very little RAM, or innodb_buffer_pool_size is set too low.  Hence, you were seriously I/O-bound and/or swapping.

```<code>WHERE time > '2017-05-21 04:47:48'
  AND deviceId >= 812
</code>```

is two ranges.  There is no thorough way to optimize that.  Either of these would help.  If you have both, the Optimizer might pick the better one:

```<code>INDEX(time)
INDEX(deviceId)
</code>```

When using a 'secondary' index in InnoDB, the query first looks in the index BTree; when there is a match there, it has to look up in the 'data' BTree (using the PRIMARY KEY for lookup).

Some of the anomalous times you saw when trying INDEX(time, deviceId) were because the filtering kept from having to reach over into the data as often.

Do you use id for anything other than uniqueness?  Is the pair deviceId & time unique?  If the answers are 'no' and 'yes', then get rid of id and change to PRIMARY KEY(deviceId, time).  Or you could swap those two columns.  What other queries do you have?

Getting rid of id shrinks the table some, thereby cutting down on I/O.

Body:
I have a table like below,

Field    Type      Null Key Default               Extra

id       bigint(11) NO  PRI NULL                  auto_increment
deviceId bigint(11) NO  MUL NULL
value    double     NO      NULL
time    timestamp   YES MUL 0000-00-00 00:00:00

It has more than 2 million rows. When I run select * from tableName; It takes more than 15 mins.

When I run select value,time from sensor_value where time > '2017-05-21 04:47:48' and deviceId>=812; It takes more than 45 sec to load.

Note :  512 has more than 92514 rows.
Even I have added index for column like below,

ALTER TABLE `sensor_value`
 ADD INDEX `IDX_FIELDS1_2` (`time`, `deviceId`) ;

How do I make select query fast?(load in 1sec) Am I doing indexing wrong?

Body:
Only 4 columns?  Sounds like you have very little RAM, or innodb_buffer_pool_size is set too low.  Hence, you were seriously I/O-bound and/or swapping.

WHERE time > '2017-05-21 04:47:48'
  AND deviceId >= 812

is two ranges.  There is no thorough way to optimize that.  Either of these would help.  If you have both, the Optimizer might pick the better one:

INDEX(time)
INDEX(deviceId)

When using a 'secondary' index in InnoDB, the query first looks in the index BTree; when there is a match there, it has to look up in the 'data' BTree (using the PRIMARY KEY for lookup).

Some of the anomalous times you saw when trying INDEX(time, deviceId) were because the filtering kept from having to reach over into the data as often.

Do you use id for anything other than uniqueness?  Is the pair deviceId & time unique?  If the answers are 'no' and 'yes', then get rid of id and change to PRIMARY KEY(deviceId, time).  Or you could swap those two columns.  What other queries do you have?

Getting rid of id shrinks the table some, thereby cutting down on I/O.


问:
Conditional string representation based on variable type
I would like to create a string representation of a datetime object that could contain a None value. So far, I came up with a solution, but I was looking at a better/cleaner way of doing it.

Let's say I have the following two variables:

```<code>import datetime as dt

a = None
b = dt.datetime(2017, 11, 30)

def str_format(str):
    return '{:%Y-%m-%d}'.format(str)
</code>```

The following would return a formatted string:

```<code>str_format(b)
'2017-11-30'
</code>```

But the following would return an error:

```<code>str_format(a)
TypeError: unsupported format string passed to NoneType.__format__
</code>```

So far I can up with the following solution:

```<code>def str_format(str):
    if isinstance(str, type(None)) is False:
        return '{:%Y-%m-%d}'.format(str)
    else:
        return '{}'.format(str)

str_format(a)
'None'

str_format(b)
'2017-11-30'
</code>```

However, I was looking at a more efficient/cleaner way of writing the function.

答:
Often times these types of things are wrapped in a try/except

```<code>def str_format(str):
  try:
    return '{:%Y-%m-%d}'.format(str)
  except TypeError:
    # unrecognized type, return blank or whatever you want to return
    return ''
</code>```

The answer on this question explains why you typically use try/except instead of a conditional check fairly well.

Body:
I would like to create a string representation of a datetime object that could contain a None value. So far, I came up with a solution, but I was looking at a better/cleaner way of doing it.

Let's say I have the following two variables:

import datetime as dt

a = None
b = dt.datetime(2017, 11, 30)

def str_format(str):
    return '{:%Y-%m-%d}'.format(str)

The following would return a formatted string:

str_format(b)
'2017-11-30'

But the following would return an error:

str_format(a)
TypeError: unsupported format string passed to NoneType.__format__

So far I can up with the following solution:

def str_format(str):
    if isinstance(str, type(None)) is False:
        return '{:%Y-%m-%d}'.format(str)
    else:
        return '{}'.format(str)

str_format(a)
'None'

str_format(b)
'2017-11-30'

However, I was looking at a more efficient/cleaner way of writing the function.

Body:
Often times these types of things are wrapped in a try/except

def str_format(str):
  try:
    return '{:%Y-%m-%d}'.format(str)
  except TypeError:
    # unrecognized type, return blank or whatever you want to return
    return ''

The answer on this question explains why you typically use try/except instead of a conditional check fairly well.


问:
python - getting error (urllib2.URLError) using pandas model
I am doing a project which requires having stocks data (currant and past). I am planning to show the data with a nice Gui engine which will have some nice features.

I have read on the pandas model and decided to use it, it seemed to support what I need. But I just have a little problem - it does not work. I did exactly what I read and saw. To them it work, but not for me! Here is what I have tried: (pandas installed from pip (pip install pandas))

```<code>import datetime
import pandas.io.data as data

start = datetime.datetime(2016, 12, 1)
end = datetime.datetime(2016, 1, 1)
apple = data.DataReader('AAPL', 'yahoo', start, end)
</code>```

when I do this an error pops out :
urllib2.URLError: urlopen error [Errno 11001] getaddrinfo failed

And when I tried replacing 'yahoo' with 'google' it succeeded, but returned None.

I have tried this code from several devices and all the same result (I am using python 2.7)

Can someone help me please?

答:
Few issues in the code:
pandas.io is not supported; use pandas_datareader instead

but I think the main issue is that your start_date > end_date here
switching them around fixed the issue

Body:
I am doing a project which requires having stocks data (currant and past). I am planning to show the data with a nice Gui engine which will have some nice features.

I have read on the pandas model and decided to use it, it seemed to support what I need. But I just have a little problem - it does not work. I did exactly what I read and saw. To them it work, but not for me! Here is what I have tried: (pandas installed from pip (pip install pandas))

import datetime
import pandas.io.data as data

start = datetime.datetime(2016, 12, 1)
end = datetime.datetime(2016, 1, 1)
apple = data.DataReader('AAPL', 'yahoo', start, end)

when I do this an error pops out :
urllib2.URLError: urlopen error [Errno 11001] getaddrinfo failed

And when I tried replacing 'yahoo' with 'google' it succeeded, but returned None.

I have tried this code from several devices and all the same result (I am using python 2.7)

Can someone help me please?


问:
non-standard syntax; use '&' to create a pointer to member error when assigning member function to vector

Im trying to add a member function of Player Class to a vector of functions.

This is the vector of functions that require a Keyboard::Key as parameter.

```<code>vector<function<void(Keyboard::Key)>> KeyEvent;
</code>```

Then i have the Players implementation

```<code>Player::Player() {
    KeyEvent.push_back(OnKey); //error: non-standard syntax; use '&' to create a pointer to member
}

void Player::OnKey(Keyboard::Key key) {
    //do something with key...
}
</code>```

I have other instances where something code similair works fine, but not with member functions.

```<code>vector<function<void()>> UpdateEvent;

UpdateEvent.push_back(HandleInputUpdate);

void HandleInputUpdate() {
    for (size_t i = 0; i < pressedKeys.size(); i++) {
        for (size_t e = 0; e < KeyEvent.size(); e++) {
            KeyEvent[e](pressedKeys[i]);
        }
    }
}
</code>```

Is it possible to add an a member function to this vector and if not, how could I create something similair? I am very new to C++ and I created the vector so I could replicate C# Actions. This is how far i have come until I ran into problems. This is an early concept as I still need to add a way to remove functions from the vector.

答:
OnKey is a non-static member function of Player and thus requires an instance of Player to be called on. Even if you got the pointer-to-member-function syntax right, you'd still have that exact problem, because there is no automatic binding; in other words, the instance pointed to by this is not automatically used to produce a callable object usable as a std::function<void(Keyboard::Key)>.

A very easy way to achieve what you want to do here is to use a lambda:

```<code>KeyEvent.push_back([this](auto key) { OnKey(key); });
</code>```

The OnKey(key); call in the function is equivalent to this->OnKey(key);.

A more complicated (in my opinion) way would be to use std::bind:

```<code>using namespace std::placeholders;
KeyEvent.push_back(std::bind(&Player::OnKey, this, _1));
</code>```

Generally speaking, with lambdas and std::function in modern C++, use cases for pointers to member functions have become extremely rare.

Body:
Im trying to add a member function of Player Class to a vector of functions.

This is the vector of functions that require a Keyboard::Key as parameter.

vector<function<void(Keyboard::Key)>> KeyEvent;

Then i have the Players implementation

Player::Player() {
    KeyEvent.push_back(OnKey); //error: non-standard syntax; use '&' to create a pointer to member
}

void Player::OnKey(Keyboard::Key key) {
    //do something with key...
}

I have other instances where something code similair works fine, but not with member functions.

vector<function<void()>> UpdateEvent;

UpdateEvent.push_back(HandleInputUpdate);

void HandleInputUpdate() {
    for (size_t i = 0; i < pressedKeys.size(); i++) {
        for (size_t e = 0; e < KeyEvent.size(); e++) {
            KeyEvent[e](pressedKeys[i]);
        }
    }
}

Is it possible to add an a member function to this vector and if not, how could I create something similair? I am very new to C++ and I created the vector so I could replicate C# Actions. This is how far i have come until I ran into problems. This is an early concept as I still need to add a way to remove functions from the vector.

Body:
OnKey is a non-static member function of Player and thus requires an instance of Player to be called on. Even if you got the pointer-to-member-function syntax right, you'd still have that exact problem, because there is no automatic binding; in other words, the instance pointed to by this is not automatically used to produce a callable object usable as a std::function<void(Keyboard::Key)>.

A very easy way to achieve what you want to do here is to use a lambda:

KeyEvent.push_back([this](auto key) { OnKey(key); });

The OnKey(key); call in the function is equivalent to this->OnKey(key);.

A more complicated (in my opinion) way would be to use std::bind:

using namespace std::placeholders;
KeyEvent.push_back(std::bind(&Player::OnKey, this, _1));

Generally speaking, with lambdas and std::function in modern C++, use cases for pointers to member functions have become extremely rare.


问:
Three.js Loading .OBJ error in Azure but not Locally
I am using three.js for webGL to load .obj
but I have a problem when loading .obj in Windows Azure runnning Windows Server 2008
I using Google chrome browser and it gives the error below:

GET http://websiteaddress.net/webGL/obj/test.mtl 404 (Not Found)

even, I used their original source code to load .obj file it has the same error

and when i try to navigate other images file in the server i can preview it
eg: (website.net/images/test.gif) - i can see the test.gif image in the browser

but when i navigate to .obj, i receive error in the browser:
(eg : website.net/obg/test.obj)

404 - File or directory not found.
The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.

i can view my .obj locally but not when I put it in Azure!
can anyone helps me? Thanks!

答:
I thought I should add what I ended up doing after finding this post. I'm using .mtl files for material (in addition to the .obj) for a THREE JS project. Since I'm using MTLLoader to get the materials as well (my models aren't just flat-color), I had to add the following line:

web.config

```<code> <!-- Instruct IISNODE to treate .obj+.mtl models as application/octet data -->
<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".obj" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".mtl" mimeType="application/octet-stream" />
        </staticContent>
    </system.webServer>
</configuration>
</code>```

Body:
I thought I should add what I ended up doing after finding this post. I'm using .mtl files for material (in addition to the .obj) for a THREE JS project. Since I'm using MTLLoader to get the materials as well (my models aren't just flat-color), I had to add the following line:

web.config

 <!-- Instruct IISNODE to treate .obj+.mtl models as application/octet data -->
<configuration>
    <system.webServer>
        <staticContent>
            <mimeMap fileExtension=".obj" mimeType="application/octet-stream" />
            <mimeMap fileExtension=".mtl" mimeType="application/octet-stream" />
        </staticContent>
    </system.webServer>
</configuration>


问:
replacement of words in strings
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

```<code>a1<- c(" the classroom is ful ")
a2<- c(" full")
</code>```

In this case I would be replacing ful for full in a1

答:
Take a look at the hunspell package. As the comments have already suggested, your problem is much more difficult than it seems, unless you already have a dictionary of misspelled words and their correct spelling.

```<code>library(hunspell)
a1 <- c(" the classroom is ful ")
bads <- hunspell(a1)
bads
# [[1]]
# [1] "ful"
hunspell_suggest(bads[[1]])
# [[1]]
#  [1] "fool" "flu"  "fl"   "fuel" "furl" "foul" "full" "fun"  "fur"  "fut"  "fol"  "fug"  "fum"
</code>```

So even in your example, would you want to replace ful with full, or many of the other options here?

The package does let you use your own dictionary. Let's say you're doing that, or at least you're happy with the first returned suggestion.

```<code>library(stringr)
str_replace_all(a1, bads[[1]], hunspell_suggest(bads[[1]])[[1]][1])
# [1] " the classroom is fool "
</code>```

But, as the other comments and answers have pointed out, you do need to be careful with the word showing up within other words.

```<code>a3 <- c(" the thankful classroom is ful ")
str_replace_all(a3,
                paste("\\b",
                      hunspell(a3)[[1]],
                      "\\b",
                      collapse = "", sep = ""),
                hunspell_suggest(hunspell(a3)[[1]])[[1]][1])
# [1] " the thankful classroom is fool "
</code>```

Update

Based on your comment, you already have a dictionary, structured as a vector of badwords and another vector of their replacements.

```<code>library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"
</code>```

Update 2

Addressing your comment, with your new example the issue is back to having words showing up in other words. The solutions is to use \\b. This represents a word boundary. Using pattern "thin" it will match to "thin", "think", "thinking", etc. But if you bracket with \\b it anchors the pattern to a word boundary. \\bthin\\b will only match "thin".

Your example:

```<code>a <- c(" thin, thic, thi")
badwords.corpus <- c("thin", "thic", "thi" )
goodwords.corpus <- c("think", "thick", "this")
</code>```

The solution is to modify badwords.corpus

```<code>badwords.corpus <- paste("\\b", badwords.corpus, "\\b", sep = "")
badwords.corpus
# [1] "\\bthin\\b" "\\bthic\\b" "\\bthi\\b"
</code>```

Then create the vect.corpus as I describe in the previous update, and use in str_replace_all.

```<code>vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a, vect.corpus)
# [1] " think, thick, this"
</code>```

Title: replacement of words in strings

Body:
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

How can I search a string, a word that matches and replace it?

The expected result is the following example:

a1<- c(" the classroom is ful ")
a2<- c(" full")

In this case I would be replacing ful for full in a1

Body:
Take a look at the hunspell package. As the comments have already suggested, your problem is much more difficult than it seems, unless you already have a dictionary of misspelled words and their correct spelling.

library(hunspell)
a1 <- c(" the classroom is ful ")
bads <- hunspell(a1)
bads
# [[1]]
# [1] "ful"
hunspell_suggest(bads[[1]])
# [[1]]
#  [1] "fool" "flu"  "fl"   "fuel" "furl" "foul" "full" "fun"  "fur"  "fut"  "fol"  "fug"  "fum"

So even in your example, would you want to replace ful with full, or many of the other options here?

The package does let you use your own dictionary. Let's say you're doing that, or at least you're happy with the first returned suggestion.

library(stringr)
str_replace_all(a1, bads[[1]], hunspell_suggest(bads[[1]])[[1]][1])
# [1] " the classroom is fool "

But, as the other comments and answers have pointed out, you do need to be careful with the word showing up within other words.

a3 <- c(" the thankful classroom is ful ")
str_replace_all(a3,
                paste("\\b",
                      hunspell(a3)[[1]],
                      "\\b",
                      collapse = "", sep = ""),
                hunspell_suggest(hunspell(a3)[[1]])[[1]][1])
# [1] " the thankful classroom is fool "

Update

Based on your comment, you already have a dictionary, structured as a vector of badwords and another vector of their replacements.

library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"

Update 2

Addressing your comment, with your new example the issue is back to having words showing up in other words. The solutions is to use \\b. This represents a word boundary. Using pattern "thin" it will match to "thin", "think", "thinking", etc. But if you bracket with \\b it anchors the pattern to a word boundary. \\bthin\\b will only match "thin".

Your example:

a <- c(" thin, thic, thi")
badwords.corpus <- c("thin", "thic", "thi" )
goodwords.corpus <- c("think", "thick", "this")

The solution is to modify badwords.corpus

badwords.corpus <- paste("\\b", badwords.corpus, "\\b", sep = "")
badwords.corpus
# [1] "\\bthin\\b" "\\bthic\\b" "\\bthi\\b"

Then create the vect.corpus as I describe in the previous update, and use in str_replace_all.

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a, vect.corpus)
# [1] " think, thick, this"


问:
Angular 5: How to get Current queryparams [Routing]
I am having trouble trying to get the queryparams into a component. For now, I just want to console.log(...) it.
I am using the ActivatedRoute from @angular/router for this task.

I am redeveloping a certain platform for work so unfortunately some irrelevant code will have be to substituted with "..."

My Component.ts code:

```<code>import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}
</code>```

When I do console.log(this.activatedRoute.queryParams.value.reportName), the console spits out the queryparams (which is exactly what I wanted) HOWEVER it also says

"Property 'value' does not exist on type 'Observable' "

so I believe this not the correct way of tackling it.

答:
Nothing surprising there!
activatedRoute.queryParams is an observable, and therefore you need to subscribe to it as per https://angular.io/api/router/ActivatedRoute#queryParams

You need to do the following :

```<code>ngOnInit() {
    this.activatedRoute.queryParams.subscribe(values => {
      console.log(values);//Which will print the properties you have passed
    });
  }
</code>```

Body:
I am having trouble trying to get the queryparams into a component. For now, I just want to console.log(...) it.
I am using the ActivatedRoute from @angular/router for this task.

I am redeveloping a certain platform for work so unfortunately some irrelevant code will have be to substituted with "..."

My Component.ts code:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}

When I do console.log(this.activatedRoute.queryParams.value.reportName), the console spits out the queryparams (which is exactly what I wanted) HOWEVER it also says

"Property 'value' does not exist on type 'Observable' "

so I believe this not the correct way of tackling it.

Body:
Nothing surprising there!
activatedRoute.queryParams is an observable, and therefore you need to subscribe to it as per https://angular.io/api/router/ActivatedRoute#queryParams

You need to do the following :

ngOnInit() {
    this.activatedRoute.queryParams.subscribe(values => {
      console.log(values);//Which will print the properties you have passed
    });
  }

ContentLicense: CC BY-SA 4.0


问:
WHERE inside CASE statement
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

```<code>Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....
</code>```

What I want to do is something like this.

```<code>-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END
</code>```

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

答:
If its performance your after start using DECLARE and SET.
It only needs to execute ONCE!!!</p>

```<code>DECLARE @UnkownExists AS INT
    SET @UnkownExists = (select count(*) from Status_table where ID = 3)

-- big nasty ugly query with various CTEs, selects, and joins
  WHERE (@UnkownExists=1 AND Item_Table.Status != 3) OR @NoUnknown=0
</code>```

Title: WHERE inside CASE statement

Body:
I have seen lots of posts about putting CASE statements inside WHERE clauses.  However, in my case, I want to put a WHERE statement inside a CASE statement, which I don't think can be done.

My situation is that I have a view that is going on many, many databases.  In half of them, I need to have a WHERE clause.  In the other half, I don't need the WHERE clause.  Leaving it in isn't harmful, in that I don't get bad data, but it slows the query down considerably given that it has to read and sort a large table when it is unnecessary.

Status_Table
ID    Status
1     Active
2     Inactive
3     Unknown    --this row of data will not exist in some DBs

Item_table
Item_ID    Status    value1    value2
1001          3      .....     .....
1002          1      .....     .....

What I want to do is something like this.

-- big nasty ugly query with various CTEs, selects, and joins
CASE    WHEN (SELECT MAX(ID) FROM Status_table) = 3
        THEN WHERE Item_Table.Status != 3
        ELSE WHERE 1=1
END

Ultimately, I can probably swing this by constructing the query using dynamic SQL, but I was hoping for a more elegant solution.

Body:
If its performance your after start using DECLARE and SET.
It only needs to execute ONCE!!!

DECLARE @UnkownExists AS INT
    SET @UnkownExists = (select count(*) from Status_table where ID = 3)

-- big nasty ugly query with various CTEs, selects, and joins
  WHERE (@UnkownExists=1 AND Item_Table.Status != 3) OR @NoUnknown=0


问:
FFI: returning three Int#'s on the stack
Is there any way to return three Int# on the stack from a foreign function call? Here is the C code (or C code that generates an object file equivalent to the one I'm actually interested in):

```<code>struct Tuple {
  int bezout1, bezout2, gcd;
}

struct Tuple extendedGcd(int a, int b) {
  /* elided */
}
</code>```

This won't compile since (# Int#, Int#, Int# #) isn't supported by ccall:

```<code>foreign import ccall "extendedGcd"
  extendedGcd :: Int# -> Int# -> (# Int#, Int#, Int# #)
</code>```

All my uses of the following (which compiles, albeit with MagicHash, GHCForeignImportPrim, ForeignFunctionInterface, UnboxedTuples, and MagicHash) seg-fault:

```<code>foreign import prim "extendedGcd"
  extendedGcd :: Int# -> Int# -> (# Int#, Int#, Int# #)
</code>```

I can find some evidence that there was some effort to get around this sort of problem:

thread on the mailing list

a proposed (but abandoned) CStructures GHC extension (by the same person)

I imagine this is a common issue, yet I can't find any working examples. Is this at all possible? If it isn't does anyone care about this anymore (is there a Trac ticket somewhere?)

答:
If you can implement your procedure in assembly directly, rather than C, it's pretty easy to do this. See: http://brandon.si/code/almost-inline-asm-in-haskell-with-foreign-import-prim/ . Maybe for a GCD algorithm this will be okay for you.

There is a complete cabal project I put together here.

Body:
Is there any way to return three Int# on the stack from a foreign function call? Here is the C code (or C code that generates an object file equivalent to the one I'm actually interested in):

struct Tuple {
  int bezout1, bezout2, gcd;
}

struct Tuple extendedGcd(int a, int b) {
  /* elided */
}

This won't compile since (# Int#, Int#, Int# #) isn't supported by ccall:

foreign import ccall "extendedGcd"
  extendedGcd :: Int# -> Int# -> (# Int#, Int#, Int# #)

All my uses of the following (which compiles, albeit with MagicHash, GHCForeignImportPrim, ForeignFunctionInterface, UnboxedTuples, and MagicHash) seg-fault:

foreign import prim "extendedGcd"
  extendedGcd :: Int# -> Int# -> (# Int#, Int#, Int# #)

I can find some evidence that there was some effort to get around this sort of problem:

thread on the mailing list

a proposed (but abandoned) CStructures GHC extension (by the same person)

I imagine this is a common issue, yet I can't find any working examples. Is this at all possible? If it isn't does anyone care about this anymore (is there a Trac ticket somewhere?)


问:
CLIPS (Expert System) write rules that add and remove values from the queue
I need help to write two rules, that add and remove values from queue. Rule that removes value from queue must use forall structure.

As far as I know, CLIPS does not have arrays, stack, lists or any other type of collections. So I have started with defining template queue with a slot item, that should represent value of a queue, but have not succeeded with the rules. Does anyone have any idea how this can be done?

答:
CLIPS has multifield objects which act as lists.

You can define your queue as a global variable and modify it in your rules as for this example (LIFO queue).

```<code>CLIPS> (defglobal ?*queue* = (create$))
; add "foo" to the queue
CLIPS> (bind ?*queue* (insert$ ?*queue* 1 "foo"))
("foo")
; add "bar" to the queue
CLIPS> (bind ?*queue* (insert$ ?*queue* 1 "bar"))
("bar" "foo")
; remove first element from the queue
(bind ?*queue* (delete$ ?*queue* 1 1))
("foo")
</code>```

Body:
CLIPS has multifield objects which act as lists.

You can define your queue as a global variable and modify it in your rules as for this example (LIFO queue).

CLIPS> (defglobal ?*queue* = (create$))
; add "foo" to the queue
CLIPS> (bind ?*queue* (insert$ ?*queue* 1 "foo"))
("foo")
; add "bar" to the queue
CLIPS> (bind ?*queue* (insert$ ?*queue* 1 "bar"))
("bar" "foo")
; remove first element from the queue
(bind ?*queue* (delete$ ?*queue* 1 1))
("foo")


问:
NullPointerException using getSystemResource(..)
I try building a texture class for LWJGL 3 in Java.

My loadTexture function looks like this:

```<code>   public static Texture loadTexture(String filename) {
        int id = -1;

        try {
            File texture = new File(filename);

            if (!texture.exists()) {
                System.err.println("File '" + filename + "' does not exist.");
                return null;
            }

            // crash in following line
            InputStream stream = ClassLoader.getSystemResource(filename).openStream();
            PNGDecoder decoder = new PNGDecoder(stream);

            // Some code between here

            return new Texture(id, new Vector2i(decoder.getWidth(), decoder.getHeight()));
        } catch (IOException e) {
            e.printStackTrace();
            return new Texture(id, new Vector2i());
        }
    }
</code>```

The stacktrace is following:

```<code>Exception in thread "main" java.lang.NullPointerException
    at org.citynopolisproject.graphics.Texture.loadTexture(Texture.java:49)
    at org.citynopolisproject.Game.<init>(Game.java:30)
    at org.citynopolisproject.Game.<init>(Game.java:33)
    at org.citynopolisproject.Game.main(Game.java:188)
</code>```

The location of the file is: citynopolisproject/res/splash.png and the source file of the Texture.java (if needed) is stored in citynopolisproject/src/org/citynopolisproject/graphics.

But I don't get why it crashes and throws a NPE.
You have any ideas?

Greetings

答:
The issue (I suspsect) is that ClassLoader.getSystemResource(filename) is returning null. This could be because the file you are looking for is not on the classpath or because the classloader can't find the resource by the name you reference it.

In order to help we'd need to know more about the structure of your project. Where is this file you are looking for and is this being run in a Jar file?

You may need to look up more info on how to reference resources on the classpath. And remember that once you build the jar you wont be able to reference it with new File(filename) normally.

EDIT

You most likely do not want to bypass getting your resource from that classpath. If you are ever going to jar this program then you should be using something that will work even after it has been jarred.

Body:
I try building a texture class for LWJGL 3 in Java.

My loadTexture function looks like this:

   public static Texture loadTexture(String filename) {
        int id = -1;

        try {
            File texture = new File(filename);

            if (!texture.exists()) {
                System.err.println("File '" + filename + "' does not exist.");
                return null;
            }

            // crash in following line
            InputStream stream = ClassLoader.getSystemResource(filename).openStream();
            PNGDecoder decoder = new PNGDecoder(stream);

            // Some code between here

            return new Texture(id, new Vector2i(decoder.getWidth(), decoder.getHeight()));
        } catch (IOException e) {
            e.printStackTrace();
            return new Texture(id, new Vector2i());
        }
    }

The stacktrace is following:

Exception in thread "main" java.lang.NullPointerException
    at org.citynopolisproject.graphics.Texture.loadTexture(Texture.java:49)
    at org.citynopolisproject.Game.<init>(Game.java:30)
    at org.citynopolisproject.Game.<init>(Game.java:33)
    at org.citynopolisproject.Game.main(Game.java:188)

The location of the file is: citynopolisproject/res/splash.png and the source file of the Texture.java (if needed) is stored in citynopolisproject/src/org/citynopolisproject/graphics.

But I don't get why it crashes and throws a NPE.
You have any ideas?

Greetings


问:
What's the term for linking two or more databases to one big database?
What's the term for linking two or more databases to one big database ?
To explain more : i have an idea to make a program for a multi branch company. So the thing that i want to make for each branch a small database and all of these branches are linked directly to the mother branch where the big database is situated .
Any suggestions for terms to use in order to find what i want online and learn ?</p>

答: You can try looking for Datawarehouse if you are dealing with BigData. If you would want to make Data marts and make some dashboards for the management it would come handy.</p>


问:
Adaptive Cards: Slack downrendering of AdaptiveCards not working
We are using AdaptiveCards.We have this working in both channels (Slack and Web), even in slack the adptive card appear as an image while web mode appears in text.

Since this week, slack adptive card is not working, whenever we make a request to show the card it appears the space of the image but the image does not have any content.

I already request support, but regarding I need to close this, I would request if someone face the same problem and how to solve that.

We are using last version of BotBuilder: 3.12.2.4

GitHub Issue

Thank you

答:
This is a known issue discussed at https://github.com/Microsoft/AdaptiveCards/issues/985. It seems a Windows update affected the WPF rendering used by Adaptive Cards, thus sometimes it fails delivering a blank image.

The Adaptive Cards team is still managing the rollout and patching.

Update 12/6

This is now fixed.


答:
Version 0.28.0 and later of the google-cloud-bigquery library use a Row class to parse rows from a table or query.

For example to print out the results from a query with a schema

```<code>[
   {
        u'type': u'STRING',
        u'name': u'word',
        u'mode': u'NULLABLE'
    },
    {
        u'type': u'INTEGER',
        u'name': u'word_count',
        u'mode': u'NULLABLE'
    },
    {
        u'type': u'INTEGER',
        u'name': u'corpus_date',
        u'mode': u'NULLABLE'
    },
]
</code>```

as in your example, one could do

```<code>query = client.query('...')
rows = query.result()
for row in rows:
    # Access by column index.
    print('word: {}'.format(row[0]))
    # Access by column name.
    # The library parses the result into an integer object,
    # based on the schema.
    print('word_count: {}'.format(row['word_count']))
    # Access by column name, like an attribute.
    print('corpus_date: {}'.format(row.corpus_date))
</code>```

In version 0.29.0 (not yet released as of 2017-12-04), there will be methods for keys(), values(), items(), and get(), just like a built-in dictionary object. (Added in PR #4393) So, to convert rows to a JSON-like dictionary in 0.29.0:

```<code>query = client.query('...')
rows = query.result()
for row in rows:
    row_json = dict(row.items())
</code>```

Title: Parsing data to create a json data object with Python

Body:
Here is my data from google bigquery to parse:

{
    u'kind': u'bigquery#queryResponse',
    u'rows': [
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'995'
                },
                {
                    u'v': u'1600'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'942'
                },
                {
                    u'v': u'1607'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'937'
                },
                {
                    u'v': u'1599'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'894'
                },
                {
                    u'v': u'1598'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'848'
                },
                {
                    u'v': u'1592'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'841'
                },
                {
                    u'v': u'1590'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'786'
                },
                {
                    u'v': u'1603'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'779'
                },
                {
                    u'v': u'1609'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'762'
                },
                {
                    u'v': u'1597'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'753'
                },
                {
                    u'v': u'1594'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'740'
                },
                {
                    u'v': u'1596'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'738'
                },
                {
                    u'v': u'1612'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'718'
                },
                {
                    u'v': u'1590'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'717'
                },
                {
                    u'v': u'1610'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'715'
                },
                {
                    u'v': u'1602'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'680'
                },
                {
                    u'v': u'1606'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'674'
                },
                {
                    u'v': u'1603'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'639'
                },
                {
                    u'v': u'1603'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'637'
                },
                {
                    u'v': u'1603'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'634'
                },
                {
                    u'v': u'1590'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'633'
                },
                {
                    u'v': u'1599'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'616'
                },
                {
                    u'v': u'1596'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'614'
                },
                {
                    u'v': u'1596'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'612'
                },
                {
                    u'v': u'1595'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'607'
                },
                {
                    u'v': u'1603'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'579'
                },
                {
                    u'v': u'1593'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'570'
                },
                {
                    u'v': u'1600'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'541'
                },
                {
                    u'v': u'1599'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'525'
                },
                {
                    u'v': u'1608'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'520'
                },
                {
                    u'v': u'1599'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'518'
                },
                {
                    u'v': u'1602'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'486'
                },
                {
                    u'v': u'1595'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'470'
                },
                {
                    u'v': u'1593'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'433'
                },
                {
                    u'v': u'1609'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'429'
                },
                {
                    u'v': u'1607'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'421'
                },
                {
                    u'v': u'1611'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'399'
                },
                {
                    u'v': u'1592'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'363'
                },
                {
                    u'v': u'0'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'353'
                },
                {
                    u'v': u'1594'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'287'
                },
                {
                    u'v': u'1609'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'106'
                },
                {
                    u'v': u'0'
                }
            ]
        },
        {
            u'f': [
                {
                    u'v': u'the'
                },
                {
                    u'v': u'57'
                },
                {
                    u'v': u'1609'
                }
            ]
        }
    ],
    u'jobReference': {
        u'projectId': u'670640819051',
        u'jobId': u'job_5bf745fcee8b470e997d8ea90f380e68'
    },
    u'jobComplete': True,
    u'totalRows': u'42',
    u'schema': {
        u'fields': [
            {
                u'type': u'STRING',
                u'name': u'word',
                u'mode': u'NULLABLE'
            },
            {
                u'type': u'INTEGER',
                u'name': u'word_count',
                u'mode': u'NULLABLE'
            },
            {
                u'type': u'INTEGER',
                u'name': u'corpus_date',
                u'mode': u'NULLABLE'
            }
        ]
    }
}

Being a Python newbee, I really have no idea about how to go about parsing this data to create a json object like below:

[
     {'count': 200, 'year': 2008},
     {'count': 240, 'year': 2010},
     {'count': 290, 'year': 2009}
]

Can any one give me any hint about how to get started?

Example

[{u'v': u'the'}, {u'v': u'995'}, {u'v': u'1600'}]

In this for the word 'the', count is 995 and year is 1600. And so it follows.

Body:
Version 0.28.0 and later of the google-cloud-bigquery library use a Row class to parse rows from a table or query.

For example to print out the results from a query with a schema

[
   {
        u'type': u'STRING',
        u'name': u'word',
        u'mode': u'NULLABLE'
    },
    {
        u'type': u'INTEGER',
        u'name': u'word_count',
        u'mode': u'NULLABLE'
    },
    {
        u'type': u'INTEGER',
        u'name': u'corpus_date',
        u'mode': u'NULLABLE'
    },
]

as in your example, one could do

query = client.query('...')
rows = query.result()
for row in rows:
    # Access by column index.
    print('word: {}'.format(row[0]))
    # Access by column name.
    # The library parses the result into an integer object,
    # based on the schema.
    print('word_count: {}'.format(row['word_count']))
    # Access by column name, like an attribute.
    print('corpus_date: {}'.format(row.corpus_date))

In version 0.29.0 (not yet released as of 2017-12-04), there will be methods for keys(), values(), items(), and get(), just like a built-in dictionary object. (Added in PR #4393) So, to convert rows to a JSON-like dictionary in 0.29.0:

query = client.query('...')
rows = query.result()
for row in rows:
    row_json = dict(row.items())


答:
If the databases have the same schema, you probably could use SQL-Hub.
At their website you can also find some information concerning the topic database-merging.</p>

Title: What's the term for linking two or more databases to one big database?

Body:
What's the term for linking two or more databases to one big database ?
To explain more : i have an idea to make a program for a multi branch company. So the thing that i want to make for each branch a small database and all of these branches are linked directly to the mother branch where the big database is situated .
Any suggestions for terms to use in order to find what i want online and learn ?


问:
Reference click method from another source file in XAML?
I have a button with a click method assigned to it. I'd like to move that method to another CS file so I may reuse it in other places. Is it possible in XAML to reference a method, click method, from a CS source file outside of the Pages source file?

<Button x:Name="TheRedButton" Click="DoNotPressTheRedButton_Click" />

I want to locate DoNotPressTheRedButton_Click in another source file.

ButtonMethods.cs

and then use it in my Page from XAML

MyPage.xaml

What do I need to write in XAML in order to do this?

I thought I need:

xmlns:helpermethods="using:CoreProject.HelperMethods"

then,

<Button x:Name="TheRedButton" Click="helpermethods:ButtonMethods.DoNotPressTheRedButton_Click" />

But I'm getting compiler errors... CS1002 and CS1513. So obviously it's not the right syntax. Is this even possible?

答:
Easy peasy:

```<code><Button Click="{x:Bind helpermethods:ButtonMethods.ButtonClick}" />
</code>```

Or in WPF:

```<code><Button Click="{x:Static helpermethods:ButtonMethods.ButtonClick}" />
</code>```

C#:

```<code>public static class ButtonMethods
{
    public static RoutedEventHandler ButtonClick => Button_Click;

    public static void Button_Click(object sender, RoutedEventArgs e)
    {
        // stuff
    }
}
</code>```

Body:
Easy peasy:

<Button Click="{x:Bind helpermethods:ButtonMethods.ButtonClick}" />

Or in WPF:

<Button Click="{x:Static helpermethods:ButtonMethods.ButtonClick}" />

C#:

public static class ButtonMethods
{
    public static RoutedEventHandler ButtonClick => Button_Click;

    public static void Button_Click(object sender, RoutedEventArgs e)
    {
        // stuff
    }
}


问:
Service discovery (Spring cloud - Eureka) and Routing(Zuul) in Elastic beanstalk
I am trying to develop a spring cloud micro service using spring and spring cloud. And I would like to deploy my micro service application in AWS elastic beanstalk. I have doubt in including Spring cloud tools in my micro service.

Whether Elastic beanstalk provide service discovery and routing like spring cloud Zuul when i am taking a Elastic beanstalk account, Or I need to implement those all with my micro service implementations?

When I am exploring Spring cloud micro services, I found that eureka and Zuul spring cloud tools. Then I added eureka server and registered my spring boot micro service as a client to eureka server. And also added the Zuul for routing. But I have still confusions in adding spring cloud in my micro services and for deployment.

When I deploying my current micro services, I need to deploy all spring boot applications(1-eureka server, 2- Micro service , 3- Zuul)?? Or Elastic beanstalk will provide all services(Means I only need to deploy my micro service and elastic beanstalk will provide service discovery routing services for spring cloud)??

答:
Elastic beanstalk won't provide service discover or routing. It will only ease the devops work. You still need to have discovery service and zuul as dockerized containers.

You can use AWS Elastic Beanstalk(EB) or EC2 Container Service(ECS) for microservices deployment.

If you want to control your scaling and capacity use ECS, ECS will give you control, as you have to specify the size and number of nodes in the cluster and whether or not auto-scaling should be used.

If you want to focus on the app and not much on DevOps use Elastic Beanstalk. For Elastic Beanstalk just provide a Dockerfile and EB takes care of scaling your provisioning of number and size of nodes, you basically can forget about the infrastructure with the EB route.


问:
STL and release/debug library mess
I'm using some 3rd party. I'm using it's shared library version, since the library is big (~60MB) and is used by several applications.

Is there a way at application startup to find out that release/debug version of library is used respectively for release/debug version of my application?

Longer description

The library which exposes C++ interface. One of API methods return std::vector<std::string>.

The problem when I compile my application in debug mode, debug version of the library should be used. Same for release. If incorrect version of the library is used application is crashed.

According to gcc (see http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt03ch17s04.html)

but with a mixed mode standard library
  that could be using either debug-mode
  or release-mode basic_string objects,
  things get more complicated

P.S. 1

It looks like proposal of Timbo is a possible solution - use different soname for debug and release libraries. So, what should be passed to ./configure script to change library soname?

P.S. 2

My problem is not at link time, but rather at run time.

P.S. 3

Here is question demonstrating problem I is facing with.

答: Give the debug and release versions of the DLL different names and link the correct one through library dependency. Your application then wont start unless it finds the correct DLL.</p>

Title: STL and release/debug library mess


问:
PHP trim() not working

trim() is supposed to delete all whitespace.

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset = "utf-8">
        <title>Aufgabe 7</title>
    </head>
    <body>
        <?php
        $EingabeText = "L27Q6Z7123515756S234939Z942yZ33z02M665z2z-Z982493d64Zn96z52z34uZ-z72P72Z6H461034zP321Z23";
        echo "Zeichenkette vor Veränderung: " . $EingabeText . "<br>";
// a)
        $Anzahl_Z = 0;
        $Anzahl_z = 0;

        $Uebergabe = array( $EingabeText, $Anzahl_Z, $Anzahl_z );

        function ZundzLoeschenUndZaehlen( $MischArray )
        {
            $ZeichenkettenLaenge;
            $ZeichenkettenLaenge = strlen($MischArray[0]);
            echo "Zeichenkettenlänge: " . $ZeichenkettenLaenge . "<br>";
            for( $i = 0; $i < $ZeichenkettenLaenge - 1; $i++ )
            {
                if( $MischArray[0][$i] == "Z" )
                {
                    $MischArray[1] ++;
                }
                if( $MischArray[0][$i] == "z" )
                {
                    $MischArray[2] ++;
                }
            }
            //strpos(str, suche [,offset])
            $MischArray[0] = str_replace("Z", " ", $MischArray[0]);
            echo "Erstes str_replace: " . $MischArray[0] . "<br>";
            $MischArray[0] = str_replace("z", " ", $MischArray[0]);
            echo "Zweites str_replace: " . $MischArray[0] . "<br>";

            $ZeichenKette1;
            $ZeichenKette1 = $MischArray[0];
            var_dump($ZeichenKette1);

            echo "<br><br><br>" . (function_exists(trim)) . "<br><br><br>";
            //$ZeichenKette=trim($ZeichenKette," ");
            //$ZeichenKette1=trim($ZeichenKette1,' ');
            $ZeichenKette1 = trim($ZeichenKette1);
            $MischArray[0] = $ZeichenKette1;
            echo "Ohne Leerzeichen: " . $MischArray[0] . "<br>";

            /*
              //Removing spaces the hard way
              for();
              {
              string chunk_split ( string $body [, int $chunklen [, string $end]] )
              }
             */
            return $MischArray;
        }
        $Uebergabe = ZundzLoeschenUndZaehlen($Uebergabe);

//$Uebergabe[0];
//echo "Debug: ".$Anzahl_Z." ".$Anzahl_z."<br>";
        echo "Debug: " . $Uebergabe[1] . " " . $Uebergabe[2] . "<br>";
//echo "Zeichenkette nach der Veränderung: ".$EingabeText."<br>";
        echo "Zeichenkette nach der Veränderung: " . $Uebergabe[0] . "<br>";

// b)
// c)
//Zählen von Klein- und Großbuchstaben sowie Zahlen
//G=15 , K=11 , Z=60

        function GroßKleinZahlen( $Zeichenkette )
        {
            $ZL = strlen($Zeichenkette);
            $Großbuchstabe  = 0;
            $Kleinbuchstabe = 0;
            $Zahl           = 0;
            for( $i = 0; $i < $ZL; $i++ )
            {
                if( (($Zeichenkette[$i] >= "A") && ($Zeichenkette[$i] <= "Z") ) )
                {
                    $Großbuchstabe++;
                }

                if( (($Zeichenkette[$i] >= "a") && ($Zeichenkette[$i] <= "z") ) )
                {
                    $Kleinbuchstabe++;
                }

                if( (($Zeichenkette[$i] >= "0") && ($Zeichenkette[$i] <= "9") ) )
                {
                    $Zahl++;
                }
            }
            echo "Anzahl Großbuchstaben:" . $Großbuchstabe . "<br>";
            echo "Anzahl Kleinbuchstaben:" . $Kleinbuchstabe . "<br>";
            echo "Anzahl Zahlen:" . $Zahl . "<br>";
        }

        /* Großbuchstaben:
          (($var>="A") && ($var<="Z"))

          //Kleinbuchstaben:
          (($var>="a") && ($var<="z"))

          //Zahlen:
          (($var>="0") && ($var<="9"))
         */
        GroßKleinZahlen($EingabeText);
        ?>
    </body>
</html>
</code>```

all spaces deleted

none

Dunkel wars, der Mond schien helle

(sp. 19. Jh.)

Dunkel wars, der Mond schien helle,
schneebedeckt die grüne Flur,
als ein Wagen blitzeschnelle
langsam um die Ecke fuhr.

Drinnen saßen stehend Leute,
schweigend ins Gespräch vertieft,
als ein totgeschoss'ner Hase
auf der Sandbank Schlittschuh lief.

Und ein blondgelockter Jüngling
mit kohlrabenschwarzem Haar
saß auf einer blauen Kiste,
die rot angestrichen war.

Neben ihm 'ne alte Schachtel,
die kaum zählte sechzehn Jahr.
Und sie aß ein Butterbrot,
das mit Schmalz bestrichen war.

Droben auf dem Apfelbaume,
der sehr süße Birnen trug,
hing des Frühlings letzte Pflaume
und an Nüssen noch genug.

Und der Wagen fuhr im Trabe
rückwärts einen Berg hinauf.
Droben zog ein alter Rabe
grade eine Turmuhr auf.

Ringsumher herrscht tiefes Schweigen
und mit fürchterlichem Krach
spielen in des Grases Zweigen
zwei Kamele lautlos Schach.

Von der regennassen Straße
wirbelte der Staub empor.
und ein Junge bei der Hitze
mächtig an den Ohren fror.

Beide Hände in den Taschen
hielt er sich die Augen zu.
denn er konnte nicht ertragen,
wie nach Veilchen roch die Kuh.

Und zwei Fische liefen munter
durch das blaue Kornfeld hin.
Endlich ging die Sonne unter
und der graue Tag erschien.

Und das alles dichtet Goethe
als er in der Morgenröte
liegend auf dem Nachttopf saß
und dabei die Zeitung las.

Just for the shitty JS

"Must write useless words"()

The difference between concise and a lot of words.

答:
trim() only deletes whitespace from begining or end of string.   if you want to delete all whitespace, you would have to do something like this, which replaces all occurances.

function deleteAllWhitespace($string) {
    return str_replace(" ", "", $string);
}

str_replace will replace what ever the first property is (" ") with whatever the second property is ("") in the passed in third property.  In this case, we take all spaces, and replace them with nothing.

Things to note.  This could potentially slow down your site to do this str_replace, so use with caution.

ref: String Replace Documentation

ref: Trim Documentation

Title: PHP trim() not working

Body:
trim() is supposed to delete all whitespace.

<!DOCTYPE html>

        <meta charset = "utf-8">
        <title>Aufgabe 7</title>

        <?php
        $EingabeText = "L27Q6Z7123515756S234939Z942yZ33z02M665z2z-Z982493d64Zn96z52z34uZ-z72P72Z6H461034zP321Z23";
        echo "Zeichenkette vor Veränderung: " . $EingabeText . "
";
// a)
        $Anzahl_Z = 0;
        $Anzahl_z = 0;

        $Uebergabe = array( $EingabeText, $Anzahl_Z, $Anzahl_z );

        function ZundzLoeschenUndZaehlen( $MischArray )
        {
            $ZeichenkettenLaenge;
            $ZeichenkettenLaenge = strlen($MischArray[0]);
            echo "Zeichenkettenlänge: " . $ZeichenkettenLaenge . "
";
            for( $i = 0; $i < $ZeichenkettenLaenge - 1; $i++ )
            {
                if( $MischArray[0][$i] == "Z" )
                {
                    $MischArray[1] ++;
                }
                if( $MischArray[0][$i] == "z" )
                {
                    $MischArray[2] ++;
                }
            }
            //strpos(str, suche [,offset])
            $MischArray[0] = str_replace("Z", " ", $MischArray[0]);
            echo "Erstes str_replace: " . $MischArray[0] . "
";
            $MischArray[0] = str_replace("z", " ", $MischArray[0]);
            echo "Zweites str_replace: " . $MischArray[0] . "
";

            $ZeichenKette1;
            $ZeichenKette1 = $MischArray[0];
            var_dump($ZeichenKette1);

            echo "

" . (function_exists(trim)) . "

";
            //$ZeichenKette=trim($ZeichenKette," ");
            //$ZeichenKette1=trim($ZeichenKette1,' ');
            $ZeichenKette1 = trim($ZeichenKette1);
            $MischArray[0] = $ZeichenKette1;
            echo "Ohne Leerzeichen: " . $MischArray[0] . "
";

            /*
              //Removing spaces the hard way
              for();
              {
              string chunk_split ( string $body [, int $chunklen [, string $end]] )
              }
             */
            return $MischArray;
        }
        $Uebergabe = ZundzLoeschenUndZaehlen($Uebergabe);

//$Uebergabe[0];
//echo "Debug: ".$Anzahl_Z." ".$Anzahl_z."
";
        echo "Debug: " . $Uebergabe[1] . " " . $Uebergabe[2] . "
";
//echo "Zeichenkette nach der Veränderung: ".$EingabeText."
";
        echo "Zeichenkette nach der Veränderung: " . $Uebergabe[0] . "
";

// b)
// c)
//Zählen von Klein- und Großbuchstaben sowie Zahlen
//G=15 , K=11 , Z=60

        function GroßKleinZahlen( $Zeichenkette )
        {
            $ZL = strlen($Zeichenkette);
            $Großbuchstabe  = 0;
            $Kleinbuchstabe = 0;
            $Zahl           = 0;
            for( $i = 0; $i < $ZL; $i++ )
            {
                if( (($Zeichenkette[$i] >= "A") && ($Zeichenkette[$i] <= "Z") ) )
                {
                    $Großbuchstabe++;
                }

                if( (($Zeichenkette[$i] >= "a") && ($Zeichenkette[$i] <= "z") ) )
                {
                    $Kleinbuchstabe++;
                }

                if( (($Zeichenkette[$i] >= "0") && ($Zeichenkette[$i] <= "9") ) )
                {
                    $Zahl++;
                }
            }
            echo "Anzahl Großbuchstaben:" . $Großbuchstabe . "
";
            echo "Anzahl Kleinbuchstaben:" . $Kleinbuchstabe . "
";
            echo "Anzahl Zahlen:" . $Zahl . "
";
        }

        /* Großbuchstaben:
          (($var>="A") && ($var<="Z"))

          //Kleinbuchstaben:
          (($var>="a") && ($var<="z"))

          //Zahlen:
          (($var>="0") && ($var<="9"))
         */
        GroßKleinZahlen($EingabeText);
        ?>

all spaces deleted

none

Dunkel wars, der Mond schien helle

(sp. 19. Jh.)

Dunkel wars, der Mond schien helle,
schneebedeckt die grüne Flur,
als ein Wagen blitzeschnelle
langsam um die Ecke fuhr.

Drinnen saßen stehend Leute,
schweigend ins Gespräch vertieft,
als ein totgeschoss'ner Hase
auf der Sandbank Schlittschuh lief.

Und ein blondgelockter Jüngling
mit kohlrabenschwarzem Haar
saß auf einer blauen Kiste,
die rot angestrichen war.

Neben ihm 'ne alte Schachtel,
die kaum zählte sechzehn Jahr.
Und sie aß ein Butterbrot,
das mit Schmalz bestrichen war.

Droben auf dem Apfelbaume,
der sehr süße Birnen trug,
hing des Frühlings letzte Pflaume
und an Nüssen noch genug.

Und der Wagen fuhr im Trabe
rückwärts einen Berg hinauf.
Droben zog ein alter Rabe
grade eine Turmuhr auf.

Ringsumher herrscht tiefes Schweigen
und mit fürchterlichem Krach
spielen in des Grases Zweigen
zwei Kamele lautlos Schach.

Von der regennassen Straße
wirbelte der Staub empor.
und ein Junge bei der Hitze
mächtig an den Ohren fror.

Beide Hände in den Taschen
hielt er sich die Augen zu.
denn er konnte nicht ertragen,
wie nach Veilchen roch die Kuh.

Und zwei Fische liefen munter
durch das blaue Kornfeld hin.
Endlich ging die Sonne unter
und der graue Tag erschien.

Und das alles dichtet Goethe
als er in der Morgenröte
liegend auf dem Nachttopf saß
und dabei die Zeitung las.

Just for the shitty JS

"Must write useless words"()

The difference between concise and a lot of words.


问:
Mono c# embedding, mono_runtime_invoke crash app
I'm embedding Mono to my c++ app. And I'm having problems with mono_runtime_invoke().

Here is the method that calls mono_runtime_invoke:

```<code>void CSScript::CallFunction(MonoMethod * function, void ** parameter)
{
   inside_function = true;
   MonoObject* exception = nullptr;

   MonoObject* obj = mono_runtime_invoke(function, mono_object, parameter, &exception);

   if (exception)
   {
       mono_print_unhandled_exception(exception);
   }
}

//---------------------

CallFunction(start, nullptr);
</code>```

And here the c# funtion I'm calling (Start()):

```<code>public class Nngf
{
   void Start ()
   {
       GameObject go = null;
       go.SetName("Hi!");
   }
}
</code>```

As you can see, the Start method is calling a method (SetName) from a null class (Gameobject) and I should get a NullReference exception in the c++ CallFunction() method. But instead, the app crashes:

I have tested the c# script in Unity and I'm getting the NullReference error.

What I need to do? I'm missing something?

答: Solved. I just had to deactivate the option "Break when this exception is thrown" and app continues and I can get the exception message.</p>

Body:
I'm embedding Mono to my c++ app. And I'm having problems with mono_runtime_invoke().

Here is the method that calls mono_runtime_invoke:

void CSScript::CallFunction(MonoMethod * function, void ** parameter)
{
   inside_function = true;
   MonoObject* exception = nullptr;

   MonoObject* obj = mono_runtime_invoke(function, mono_object, parameter, &exception);

   if (exception)
   {
       mono_print_unhandled_exception(exception);
   }
}

//---------------------

CallFunction(start, nullptr);

And here the c# funtion I'm calling (Start()):

public class Nngf
{
   void Start ()
   {
       GameObject go = null;
       go.SetName("Hi!");
   }
}

As you can see, the Start method is calling a method (SetName) from a null class (Gameobject) and I should get a NullReference exception in the c++ CallFunction() method. But instead, the app crashes:

I have tested the c# script in Unity and I'm getting the NullReference error.

What I need to do? I'm missing something?