问:
Teradata syntax?
is there syntax like </p>

```<code>SET IDENTITY_INSERT <TABLE_NAME> ON | OFF  ------- SQL SERVER
</code>```

<p>in teradata ?? </p>

答: I don't think there is an option to switch on/off identity column value generation but there are options like GENERATED BY DEFAULT and GENERATED ALWAYS which can conditionally control value generation

Title: Teradata syntax?

Body:
is there syntax like

SET IDENTITY_INSERT <TABLE_NAME> ON | OFF  ------- SQL SERVER

in teradata ??


来源: stackexchange

问:
Knockout - data-bind overriging other elements inside an html element
I am trying to make a demo app with tweet-like list items and I have run into a problem. I have a h4 element to which I want to bind text and also have some span elements inside of it, but only the bound text is shown and the other elements inside the h4 element are overrided.
This is the problematic part I want to make:

This is what I get the way I'm trying to implement it with knockout:

The shole item should look like this:

The specific part of template where I'm trying to implement this kind of heading:

```<code> <h4 class="media-heading" data-bind="text: name"><a><span>@</span><span data-bind="text: name"></span></a><span class="timeAgo">  4 minutes ago</span></h4>
</code>```

Fiddle with my application:
fiddle

Since I'm doing it wrong in the template my question is - how would I implement the heading with account name and time ago part by using knockout?

答:
The text binding replaces all of the element's contents. This means there's no point in "nesting" text bindings. (Or any other bindings inside a text-bound element).

To solve your specific issue, you can either add another  inside your
:

```<code><h4>
  <span data-bind="text: name"></span>
  <a>
    <span>@</span>
    <span data-bind="text: name"></span>
  </a>
  <span class="timeAgo">4 minutes ago</span>
</h4>
</code>```

Personally, I'd clean this up to:

```<code><h4>
  <span data-bind="text: name"></span>
  <a data-bind="text: '@' + name()"></span>
  <span>4 minutes ago</span>
</h4>
</code>```

Or, if you don't want the extra , you can use a virtual binding:

```<code><!--ko text: name--><!--/ko-->
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a demo app with tweet-like list items and I have run into a problem. I have a h4 element to which I want to bind text and also have some span elements inside of it, but only the bound text is shown and the other elements inside the h4 element are overrided.
This is the problematic part I want to make:

This is what I get the way I'm trying to implement it with knockout:

The shole item should look like this:

The specific part of template where I'm trying to implement this kind of heading:

@  4 minutes ago

Fiddle with my application:
fiddle

Since I'm doing it wrong in the template my question is - how would I implement the heading with account name and time ago part by using knockout?

Body:
The text binding replaces all of the element's contents. This means there's no point in "nesting" text bindings. (Or any other bindings inside a text-bound element).

To solve your specific issue, you can either add another <span> inside your <h4>:

<h4>
  <span data-bind="text: name"></span>
  <a>
    <span>@</span>
    <span data-bind="text: name"></span>
  </a>
  <span class="timeAgo">4 minutes ago</span>
</h4>

Personally, I'd clean this up to:

<h4>
  <span data-bind="text: name"></span>
  <a data-bind="text: '@' + name()"></span>
  <span>4 minutes ago</span>
</h4>

Or, if you don't want the extra <span>, you can use a virtual binding:

<!--ko text: name--><!--/ko-->


问:
How to test nested asynchronous calls in Nodejs?
I would like to unit-test the function getAuthorizedUsers from the following module. The core functionality that I need to test is in the callback function of DB.getUsers. I could not find a way to mimic the callback of DB.getUsers.

```<code>(function () {
    const DB = require('./DB');

    function getAuthorizedUsers(req, res, callback) {
        DB.getUsers(req.db, req.userId, function(err, users) {
            users.push({id: 0});
            req.users = users;
            callback(req, res);
        });
    }

    module.exports = {
        getAuthorizedUsers: getAuthorizedUsers
    };
})();
</code>```

Here is what I have so far:

```<code>(function () {
    "use strict";

    var chai = require("chai");
    var User = require("./User");

    suite("API", function () {
        suite("getAuthorizedUsers", function() {
            var req = {
                db: {},
                userId: '',
            };
            var res = {};
            test("adds admin to list of authorized users", function() {
                User.getAuthorizedUsers(req, res, function(req, res) {
                    //assert that req contains the correct list of authorized users
                });
            });
        });
    });
}());
</code>```

I have changed names, and logic of code for simplification. So, forgive me if code does not follow the best practices or does not make sense.

EDIT: Do you have any suggestions on how to stub the "DB.getUsers"?

答:
I assume that you do testing for node.js

Use jasmine or mocha frameworks - they support clean syntax for testing async stuff. http://tobyho.com/2015/12/16/mocha-with-promises/

Stick to use promises instead of callbacks for most situations. It will make your life a lot easier, with some tradeoff's on edge-cases.

You don't need to use IIFE in node.js since each module has it's own globals.

These will help you to mock node modules:

https://github.com/mockery/mockery

https://github.com/thlorenz/proxyquire

Body:
I would like to unit-test the function getAuthorizedUsers from the following module. The core functionality that I need to test is in the callback function of DB.getUsers. I could not find a way to mimic the callback of DB.getUsers.

(function () {
    const DB = require('./DB');

    function getAuthorizedUsers(req, res, callback) {
        DB.getUsers(req.db, req.userId, function(err, users) {
            users.push({id: 0});
            req.users = users;
            callback(req, res);
        });
    }

    module.exports = {
        getAuthorizedUsers: getAuthorizedUsers
    };
})();

Here is what I have so far:

(function () {
    "use strict";

    var chai = require("chai");
    var User = require("./User");

    suite("API", function () {
        suite("getAuthorizedUsers", function() {
            var req = {
                db: {},
                userId: '',
            };
            var res = {};
            test("adds admin to list of authorized users", function() {
                User.getAuthorizedUsers(req, res, function(req, res) {
                    //assert that req contains the correct list of authorized users
                });
            });
        });
    });
}());

I have changed names, and logic of code for simplification. So, forgive me if code does not follow the best practices or does not make sense.

EDIT: Do you have any suggestions on how to stub the "DB.getUsers"?


问:
How to make TextInputLayout hint asterisk red for required fields
Is it possible to make just the asterisk in the hint red when using a TextInputLayout from the design support library? I have seen information on styling the entire hint, but this is a little more complex since only the * should be red, not the whole message.

The Material Design example shows this, but the design library doesn't seem to have any option to style it this way using a TextInputLayout and EditText.

Reference:
https://www.google.com/design/spec/components/text-fields.html#text-fields-required-fields

Example (the top, with focus, has the red asterisk; the bottom without focus does not have a red asterisk):

I looked into setting the hint to a SpannableString (see here How to get a red asterisk in a <string> entry) in an OnFocusChangeListener (see here Having the mandatory symbol to the edit text (red color asterisk) which is inside the textinputlayout), but the hint is a CharSequence.

Is there any way to do this without extending TextInputLayout?

答:
Could you be adding a spanned string From Html?

```<code>   String grey = "Legal first name*";
   Spanned redStar;
   String html = "<string style="color:grey;">Legal first name<span style="color:red;">*</span></string>";

   if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
   redStar = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
   } else {
   redStar = Html.fromHtml(html);
   }
</code>```

And change the hint upon focus.

```<code>   textInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
   public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus)
        myEditText.setHint(redStar.toString);
    else
        myEditText.setHint(grey);
}
</code>```

Body:
Could you be adding a spanned string From Html?

   String grey = "Legal first name*";
   Spanned redStar;
   String html = "<string style="color:grey;">Legal first name<span style="color:red;">*</span></string>";

   if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
   redStar = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY);
   } else {
   redStar = Html.fromHtml(html);
   }

And change the hint upon focus.

   textInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
   public void onFocusChange(View v, boolean hasFocus) {
    if (hasFocus)
        myEditText.setHint(redStar.toString);
    else
        myEditText.setHint(grey);
}


答:
YOu can try

```<code>Select DISTINCT SD1.[Week],
    SD1.[Allocation],
    SD1.[Subsidiaries],
    SD1.[Month],
    SD1.[Date],
    SUM(Daily Sale) as 'Running Total'
from [dbo].[Solar data] SD1
where SD1.[Subsidiaries]='WCL'
group by SD1.[Allocation],
    SD1.[Month],
    SD1.[Subsidiaries],
    SD1.[Daily Sale],
    SD1.[Week],SD1.[Date]
order by SD1.[Week]
</code>```

This would sum up the sales in one row

Title: How do I show distinct week?

Body:
I am executing the SQL code based on "Running total" concept.My code is calculating accurate running total but i need to show the running total only after completion of every week not by dates.?

Select DISTINCT SD1.[Week],
    SD1.[Allocation],
    SD1.[Subsidiaries],
    SD1.[Month],
    SD1.[Date],
    (SD1.[Daily Sale]+IsNull(SUM(SD2.[Daily Sale]),0)) as 'Running Total'
from [dbo].[Solar data] SD1
    left join [dbo].[Solar data] SD2 on SD1.[Subsidiaries]=SD2.[Subsidiaries]
        and SD2.[Date]<SD1.[Date] And SD1.[Month]=SD2.[Month]
where SD1.[Subsidiaries]='WCL'
group by SD1.[Allocation],
    SD1.[Month],
    SD1.[Subsidiaries],
    SD1.[Daily Sale],
    SD1.[Week],SD1.[Date]
order by SD1.[Week]

+---------------+------------+------------+-----------+--------+-------+
| Subsidiaries  | Allocation | Daily Sale |   Date    | Month  | Week  |
+---------------+------------+------------+-----------+--------+-------+
| WCL           |       1075 | 44.93      | 2-Jan-17  | Jan-17 | Week1 |
| WCL           |       1075 | 44.51      | 3-Jan-17  | Jan-17 | Week1 |
| WCL           |       1075 | 53.68      | 8-Jan-17  | Jan-17 | Week2 |
| WCL           |       1075 | 41.45      | 9-Jan-17  | Jan-17 | Week2 |
| WCL           |       1075 | 40.97      | 15-Jan-17 | Jan-17 | Week3 |
| WCL           |       1075 | 55.9       | 16-Jan-17 | Jan-17 | Week3 |
| WCL           |       1075 | 43.89      | 22-Jan-17 | Jan-17 | Week4 |
| WCL           |       1075 | 44.36      | 23-Jan-17 | Jan-17 | Week4 |
| WCL           |       1075 | 35.13      | 29-Jan-17 | Jan-17 | Week5 |
+---------------+------------+------------+-----------+--------+-------+

Expected Result:

+--------+---------------+
| Week   | Running total |
+--------+---------------+
| Week1  | 89.44         |
| Week2  | 184.57        |
| Week3  | 281.44        |
| Week4  | 369.69        |
| Week5  | 404.82        |
+--------+---------------+

Body:
YOu can try

Select DISTINCT SD1.[Week],
    SD1.[Allocation],
    SD1.[Subsidiaries],
    SD1.[Month],
    SD1.[Date],
    SUM(Daily Sale) as 'Running Total'
from [dbo].[Solar data] SD1
where SD1.[Subsidiaries]='WCL'
group by SD1.[Allocation],
    SD1.[Month],
    SD1.[Subsidiaries],
    SD1.[Daily Sale],
    SD1.[Week],SD1.[Date]
order by SD1.[Week]

This would sum up the sales in one row


问:
How can I find the micro-ops which instructions on Intel's x86 CPUs decode to?
The Intel Optimization Reference, under Section 3.5.1, advises:

"Favor single-micro-operation instructions."

"Avoid using complex instructions (for example, enter, leave, or loop) that have more than 4 micro-ops and require multiple cycles to decode. Use sequences of simple instructions instead."

Although Intel themselves tell compiler writers to use instructions which decode to few micro-ops, I can't find anything in any of their manuals which explains just how many micro-ops each ASM instruction decodes to! Is this information available anywhere? (Of course, I expect that the answers will be different for different generations of CPUs.)

答:
It has already been pointed out that Agner Fog's optimization manuals are an excellent resource, and in particular, his Instruction Tables, which are nearly comprehensive for all of the x86 microarchitectures of interest.

But you do have another option: Intel's Architecture Code Analyzer (IACA). There is a write-up of how to use it here on Stack Overflow, but it's pretty simple to get going (although a bit tedious for one-off analysis). You just download the executable, emit some prologue and epilogue code surrounding the block of instructions you want to be analyzed (it includes a C header for this purpose (iacaMarks.h) that works with various compilers, or you can just instruct your assembler to emit the appropriate bytes), and then run your binary through iaca.exe. The current version (v2.2) supports only 64-bit binaries, but that's not a major limitation, since the instruction-level analysis won't be substantially different for 32-bit and 64-bit modes. The current version also supports all modern Intel microarchitectures that might be of interest to a professional software developer, from Nehalem to Broadwell.

The output you get from this tool will tell you which ports a particular instruction can execute on, as well as how many µops that instruction will decompose to, on the specified microarchitecture.

That is as close as you're going to get to a direct answer to your question, since as Hans Passant pointed out in the comments, the exact µops that each instruction decomposes to are intentionally kept secret by Intel. Not only are they a proprietary trade secret, but Intel wants to be free to change how it works from one microarchitecture to another. In fact, though, how many µops an instruction decomposes to is all you would ever want to know when optimizing code. It doesn't matter which µops the instruction decomposes to.

But I would reiterate one portion of Peter Cordes's answer: "It's easy to guess in some cases, though". If you have to look up this type of detailed information for each instruction you're considering, you're going to waste a lot of time. You're also going to drive yourself mad, since as you already know, it varies from one microarchitecture to another. The real trick here is getting an intuitive feel for which instructions in the x86 ISA are "simple" and which are "complex". It should be pretty obvious from reading the documentation, and that intuitive feeling is really all that Intel's optimization recommendations are driving you towards. Avoid "complex" (old CISC-style) instructions like LOOP, ENTER, LEAVE, and so forth. For example, prefer DEC+JNZ over LOOP. Relatively speaking, there are only a small minority of "classic" x86 instructions that decode to more than one or two µops.* Studying the output of a good optimizing compiler will also lead you in the right direction, since you'll never see compilers use these "complex" instructions.

Somewhat contra Peter's answer, though, I'm pretty sure that the quoted section of Intel's optimization manuals are not referring to the SIMD instructions. They're talking about the old-school CISC instructions that are implemented in microcode and that they would have dropped already if they didn't have to support them for backwards compatibility. If you need the behavior of SSE3's HADDPS, then you are probably better off using HADDPS instead of trying to break it down into "simpler" components. (Unless, of course, you can better schedule those operations by interleaving them within unrelated code. But that's awfully hard to do in practice.)

*To be completely accurate, there are certain seemingly-simple instructions that are actually implemented using microcode and decompose to multiple µops. A 64-bit division (DIV) is an example. If I remember correctly, this is microcoded using something like 30–40 µops (variable). However, this is not an instruction that you should avoid, which shows that Intel's manuals are being very general in dispensing advice here. If you need to do a division, use a DIV. Obviously prefer not doing divisions when optimizing for speed, but don't try to write your own division algorithm just to avoid the microcoded DIV, either!

The other big exception here are the string instructions. The performance calculus for those is a bit more complicated than "avoid because they decode to multiple µops", though.

Fortunately, one thing is simple: never use the string instructions without a REP prefix. That just doesn't make sense, and you will get significantly better performance by "decomposing" the instruction into the simpler "component" instructions yourself—for example, MOVSB → MOV  AL, [ESI]+MOV  ES:[EDI], AL+INC/DEC  ESI+INC/DEC  EDI.

Where it gets a bit trickier to decide is when you start taking advantage of the REP prefix. Although this does cause the instruction to decode into many µops, it is sometimes still more efficient to use the repeated string instructions than to code the loop manually yourself. But not always. There's been lots of discussion on this issue already on Stack Overflow and elsewhere; for example, see this question.

A detailed analysis is really beyond the scope of this answer, but my quick rule of thumb is that you can forget about REP LOADS, REP SCAS, and REP CMPS entirely. On the other hand, REP MOVS and REP STOS are useful when you need to repeat a reasonably large number of times. Always use the largest word size possible: DWORD on 32-bit, QWORD on 64-bit (but note that on modern processors, you may be better off using MOVSB/STOSB, since they can move larger quantities internally. And even when all these conditions are met, if your target has vector instructions available, you probably want to verify that it wouldn't be faster to implement the move/store with vector moves.

See also Agner Fog's general advice on page 150.


问:
how to use pragrammable chat of twilio in c#
can enyone help me out to undersatnd this Here's a link! how to use in c#
i want to know how to use it
how to use pragrammable chat of twilio in c#</p>

答:
Twilio developer evangelist here.

There is a full tutorial for using Twilio Programmable Chat from C# right here.

You might also find that the Chat fundamentals documentation will help. The key is that you need to run a server which you can use to generate an access token for your users so that they can access the Chat service. Once you have done that, you can build the rest of the application in the front end. You can also perform actions from C# using the REST API.


问:
How to find strings
I have a df as below

df:

```<code>Name               |Code
-------------------+-----
aman               |abc
akash              |bcd
rudra              |cde
Tushar             |def
Kartik             |efg
aman,akash         |fgh
akash,rudra        |ghi
akash,rudra,aman   |ijk
aman,Tushar        |jkl
Kartik,Tushar      |klm
rudra,Kartik,akash |lmn
</code>```

i want to search code for below df

```<code>Name            |
----------------+
aman,akash,rudra|
Tushar,aman     |
Kartik          |
rudra,akash     |
</code>```

to get below result

```<code>Name            |code
----------------+-----
aman,akash,rudra|ijk
Tushar,aman     |jkl
Kartik          |efg
rudra,akash     |ghi
</code>```

Please note that combo of "rudra,akash"occur three times, in that case it returns the result alphabatical order of code

let me know if there is some way to achieve this.

答:
We can use cSplit from splitstackshape to split the 'Name' column and reshape it to 'long' format ('dfN'), grouped by 'Code', and run-length-id of 'Code', we paste the 'Name' after sorting.  Do the same with 'df2', match the 'Name' columns in both the dataset and get the 'Code' in 'dfN' that corresponds to create a new column 'code' in 'df2'

```<code>library(splitstackshape)
dfN <- cSplit(df, "Name", ",", "long")[, .(Name = paste(sort(Name), collapse=",")),
             by =  .(grp = rleid(Code), Code)]
df2$grp <- seq_len(nrow(df2))
df2$code <-  cSplit(df2, "Name", ",", "long")[, .(Name = paste(sort(Name),
     collapse=",")), .(grp)][, dfN$Code[match(Name, dfN$Name)]]
df2$grp <- NULL
df2
#              Name code
#1 aman,akash,rudra  ijk
#2      Tushar,aman  jkl
#3           Kartik  efg
#4      rudra,akash  ghi
</code>```

Title: How to find strings

Body:
I have a df as below

df:

Name               |Code
-------------------+-----
aman               |abc
akash              |bcd
rudra              |cde
Tushar             |def
Kartik             |efg
aman,akash         |fgh
akash,rudra        |ghi
akash,rudra,aman   |ijk
aman,Tushar        |jkl
Kartik,Tushar      |klm
rudra,Kartik,akash |lmn

i want to search code for below df

Name            |
----------------+
aman,akash,rudra|
Tushar,aman     |
Kartik          |
rudra,akash     |

to get below result

Name            |code
----------------+-----
aman,akash,rudra|ijk
Tushar,aman     |jkl
Kartik          |efg
rudra,akash     |ghi

Please note that combo of "rudra,akash"occur three times, in that case it returns the result alphabatical order of code

let me know if there is some way to achieve this.

Body:
We can use cSplit from splitstackshape to split the 'Name' column and reshape it to 'long' format ('dfN'), grouped by 'Code', and run-length-id of 'Code', we paste the 'Name' after sorting.  Do the same with 'df2', match the 'Name' columns in both the dataset and get the 'Code' in 'dfN' that corresponds to create a new column 'code' in 'df2'

library(splitstackshape)
dfN <- cSplit(df, "Name", ",", "long")[, .(Name = paste(sort(Name), collapse=",")),
             by =  .(grp = rleid(Code), Code)]
df2$grp <- seq_len(nrow(df2))
df2$code <-  cSplit(df2, "Name", ",", "long")[, .(Name = paste(sort(Name),
     collapse=",")), .(grp)][, dfN$Code[match(Name, dfN$Name)]]
df2$grp <- NULL
df2
#              Name code
#1 aman,akash,rudra  ijk
#2      Tushar,aman  jkl
#3           Kartik  efg
#4      rudra,akash  ghi


问:
Highcharts series data array not working
From the servlet I am getting back 3 arrays activeArray,inActiveArray and rejectedArray. I would like to pick these arrays in the java script and come up with a high charts that plots the categories as the blood group names like A+, A- etc.
The series names will be Active, Inactive and rejected.
The series data will have to be the arrays mentioned above.
I was able to achieve only the categories but the series data does not get plotted. I have included the script code below.

```<code><script>
var nameArray ="${nameArray}";

var bloodNames = [
<c:forEach items="${nameArray}" var="name">
    '<c:out value="${name}" />',
</c:forEach>
];

var  activeValue = new Array();
activeValue = [
<c:forEach items="${activeArray}" var="data">
    '<c:out value="${data}" />',
</c:forEach>
];

var seriesData = [
    {
        name: 'Active',
        data:activeValue
    },{
        name:'InActive',
        data:[3, 01, 03,0,0,0]
    },
    {
        name:'Rejected',
        data:[4, 01, 03,0,2,0]
    }
]
$(function () {
var myChart = Highcharts.chart('container', {
chart: {
    type: 'column'
},
title: {
    text: 'Donar Status Report'
},
subtitle: {
    text: 'Blood Name Wise'
},
xAxis: {
    categories:
       bloodNames
    ,
    crosshair: true
},
yAxis: {
    min: 0,
    title: {
        text: 'Person (in Counts)'
    }
},
tooltip: {
    headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
    pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
        '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
    footerFormat: '</table>',
    shared: true,
    useHTML: true
},
plotOptions: {
    column: {
        pointPadding: 0.2,
        borderWidth: 0
    }
},
series: seriesData
});
</code>```

});

答:
You can use Map function to convert array of string to array of number.Rest of your chart is ok

 var activeValue= ["1","3","2","2","1","2","0","1","0","0"]
 activeValue=activeValue.map(Number)
 console.log(activeValue)```


问:
Append image to FormData, "stream.on is not a function" error
I'm trying to append an image into a form-data.
When I call the function append, I have the error "stream.on is not a function".

HTML:

```<code><input id="432bb3b4-dbef-4591-89eb-5e8fd3ff7174_field_0" data-bind="event: { change: function() { uploadImage($element.files[0]) } }" type="file">
</code>```

JavaScript:

```<code>ViewModel.prototype.uploadImage = function (file) {
    var data = new FormData();
    data.append('filed', file);
};
</code>```

I know there are other post about use FormData, but no one had experienced this error.

答:
I've figured out my mistake.
I used require("form-data") in my script and that generated the error. To use FormData in the client, it is not necessary to specify any "require".

Body:
I'm trying to append an image into a form-data.
When I call the function append, I have the error "stream.on is not a function".

HTML:

<input id="432bb3b4-dbef-4591-89eb-5e8fd3ff7174_field_0" data-bind="event: { change: function() { uploadImage($element.files[0]) } }" type="file">

JavaScript:

ViewModel.prototype.uploadImage = function (file) {
    var data = new FormData();
    data.append('filed', file);
};

I know there are other post about use FormData, but no one had experienced this error.


问:
Call RSS Feed in VBA and Scrape Certain Data
I am writing a script in VBA within PowerPoint. I am trying to grab the following line from an RSS Feed: <div>Highest Projected Forecast Available: 1.2 ft</div>

From that line I need to extract just the "1.2" or whatever value appears in that place. The problem I am coming across is that it is not formatted like a standard XML file. It does not have tags at the beginning of each line, instead they are character combinations like you see in the example line above. Is this normal for an RSS feed? Click the link above to see exactly what I am referring to.

Any ideas how I would be able to grab that value and store it as a variable with VBA in PowerPoint? Any help would be much appreciated. Thank you!

答:
Hi Please check the following code hope that helps:</p>

```<code>Function GetRSSResults() As String
GetRSSResults = GetHTTPResponse("https://water.weather.gov/ahps2/rss/fcst/fdyo1.rss")
r = GetRSSResults
s1 = Replace(r, ">", ">")
s2 = Replace(s1, "<", "<")
searchTerm = "Highest Projected Forecast Available: "
s = InStr(s2, searchTerm) + Len(searchTerm)
l = InStr(s, s2, "ft")
Debug.Print Trim(Mid(s2, s, l - s))
End Function
'------------------------------------------
Function GetHTTPResponse(url As String) As String
Dim msXML As Object
Set msXML = CreateObject("Microsoft.XMLHTTP")
With msXML
  .Open "Get", url, False
  .setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=utf-8"
  .send
  GetHTTPResponse = .responseText
End With
Set msXML = Nothing
End Function
</code>```

Body:
Hi Please check the following code hope that helps:

Function GetRSSResults() As String
GetRSSResults = GetHTTPResponse("https://water.weather.gov/ahps2/rss/fcst/fdyo1.rss")
r = GetRSSResults
s1 = Replace(r, "&#x3E;", ">")
s2 = Replace(s1, "&#x3C;", "<")
searchTerm = "Highest Projected Forecast Available: "
s = InStr(s2, searchTerm) + Len(searchTerm)
l = InStr(s, s2, "ft")
Debug.Print Trim(Mid(s2, s, l - s))
End Function
'------------------------------------------
Function GetHTTPResponse(url As String) As String
Dim msXML As Object
Set msXML = CreateObject("Microsoft.XMLHTTP")
With msXML
  .Open "Get", url, False
  .setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=utf-8"
  .send
  GetHTTPResponse = .responseText
End With
Set msXML = Nothing
End Function


问:
Python lxml: Ignore XML declaration (errors)
I am trying to parse the file browser Thunar's custom actions files (~/.config/Thunar/uca.xml) with the lxml Python module.

For some reason, Thunar obviously writes a malformed declaration into these files:

```<code><?xml encoding="UTF-8" version="1.0"?>
</code>```

Obviously, the version is expected to appear as the first "attribute" in the declaration. lxml raises an XMLSyntaxError if I try to parse the file.

And no, I cannot simply correct the declaration, becaue Thunar keeps overwriting it with the bogus one.

This might very likely be a bug in Thunar.

Nevertheless, I would like to know how to ignore the XML declaration with lxml.

I know that I could pre-process the XML document to filter out the XML declaration. But this doesn't seem very elegant. Since XML seems to default to version 1.0 and UTF-8 encoding, there surely is a possibility to just ignore the declaration and assume that in lxml. I didn't find anything in the documentation or on google, I might have overlooked something.

答:
I know very little about Thunar, but if it produces the XML declaration in the question, then that is a bug. Having an incorrect XML declaration makes the document ill-formed.

The XML grammar specifies one correct order for the items in the XML declaration. version must come first and encoding second. See http://w3.org/TR/xml/#NT-XMLDecl.

However, with lxml you can parse using a parser instance that has the recover option set to True. It works in this case. The bad XML declaration is ignored.

```<code>from lxml import etree

parser = etree.XMLParser(recover=True)
tree = etree.parse('uca.xml', parser)
</code>```

See http://lxml.de/api/lxml.etree.XMLParser-class.html

Body:
I am trying to parse the file browser Thunar's custom actions files (~/.config/Thunar/uca.xml) with the lxml Python module.

For some reason, Thunar obviously writes a malformed declaration into these files:

<?xml encoding="UTF-8" version="1.0"?>

Obviously, the version is expected to appear as the first "attribute" in the declaration. lxml raises an XMLSyntaxError if I try to parse the file.

And no, I cannot simply correct the declaration, becaue Thunar keeps overwriting it with the bogus one.

This might very likely be a bug in Thunar.

Nevertheless, I would like to know how to ignore the XML declaration with lxml.

I know that I could pre-process the XML document to filter out the XML declaration. But this doesn't seem very elegant. Since XML seems to default to version 1.0 and UTF-8 encoding, there surely is a possibility to just ignore the declaration and assume that in lxml. I didn't find anything in the documentation or on google, I might have overlooked something.

Body:
I know very little about Thunar, but if it produces the XML declaration in the question, then that is a bug. Having an incorrect XML declaration makes the document ill-formed.

The XML grammar specifies one correct order for the items in the XML declaration. version must come first and encoding second. See http://w3.org/TR/xml/#NT-XMLDecl.

However, with lxml you can parse using a parser instance that has the recover option set to True. It works in this case. The bad XML declaration is ignored.

from lxml import etree

parser = etree.XMLParser(recover=True)
tree = etree.parse('uca.xml', parser)

See http://lxml.de/api/lxml.etree.XMLParser-class.html


问:
lodash _.get function in typescript
I get the feeling after some googling that a lot of lodash's functions can be achieved with native typescript but i cannot find a straightforward answer for the _.get function...

In lodash the following, using the _.get function alerts 1

```<code>let obj = {a:{b:1}};
let a = _.get(obj, 'a.b');
alert(a);
</code>```

Is there a way of achieving the same result with only typescript?

答:
```<code>/**
 * Get value of a property from a nested object.
 * Example:
 * var x = { a: {b: "c"} };
 * var valueOf_b = getDeepValue(x, ["a", "b"]);
 *
 * @param  {object}     Object           The Object to get value from
 * @param  {KeyArray}   Array[String]    An array of nested properties. ex. ["property", "childProperty"]
 */
const getDeepValue = (object, keyArray) => {
    const extractValue = (obj, kArray) => {
        const objProperty = obj[kArray[0]];
        if (kArray.length >= 1) {
            const newKeyArray = kArray.splice(1, kArray.length);
            if (newKeyArray.length === 0) return objProperty;
            return extractValue(objProperty, newKeyArray);
        }
        return objProperty;
    };

    try {
        const value = extractValue(object, keyArray.slice());
        if (value === undefined || typeof value === 'object') {
            console.warn("Unable to retrieve value from object for key ", keyArray);
            return '';
        } else {
            return value;
        }
    } catch (e) {
        console.warn("Exception: Unable to retrieve value from object for key ", keyArray);
        return '';
    }
};
</code>```

Title: lodash _.get function in typescript

Body:
I get the feeling after some googling that a lot of lodash's functions can be achieved with native typescript but i cannot find a straightforward answer for the _.get function...

In lodash the following, using the _.get function alerts 1

let obj = {a:{b:1}};
let a = _.get(obj, 'a.b');
alert(a);

Is there a way of achieving the same result with only typescript?


问:
Find strings with maximum vowels
I want to find strings with maximum vowels in Python, but I don't know how.

Examples

Input

```<code>['Zak6aa','kak','ll','ak']
</code>```

Output:

```<code>['Zak6aa']
</code>```

Another if two or more strings tie for max vowels:

```<code>['Zaa', 'bii','ak']
</code>```

output is:

```<code>['Zaa', 'bii']
</code>```

My try:

```<code>def maxv(string):
    sam=0
    seq=[]
    for i in range(len(string)):
        k=0
        v=0
        for char in string[i]:
             if char in "aeiouy":
                v = v+1
        k=(len(string[i]))-v
        if (v >=k):
            seq=seq+[string[i]]
    return seq
</code>```

答:
One Solution using loops.

```<code>l=['Zak6aa','kak','ll','ak']
L={}
for x in l:
  cnt=x.count('a')+x.count('e')+x.count('i')+x.count('e')+x.count('u')
  if cnt not in L.keys():
    L[cnt]=[]
  L[cnt].append(x)
print(L[max(L.keys())])
</code>```

You can count the number of occurrences of vowels using re

```<code>import re
cnt=len(re.findall(r'[aeiou]{1}',x))
</code>```

Title: Find strings with maximum vowels

Body:
I want to find strings with maximum vowels in Python, but I don't know how.

Examples

Input

['Zak6aa','kak','ll','ak']

Output:

['Zak6aa']

Another if two or more strings tie for max vowels:

['Zaa', 'bii','ak']

output is:

['Zaa', 'bii']

My try:

def maxv(string):
    sam=0
    seq=[]
    for i in range(len(string)):
        k=0
        v=0
        for char in string[i]:
             if char in "aeiouy":
                v = v+1
        k=(len(string[i]))-v
        if (v >=k):
            seq=seq+[string[i]]
    return seq

Body:
One Solution using loops.

l=['Zak6aa','kak','ll','ak']
L={}
for x in l:
  cnt=x.count('a')+x.count('e')+x.count('i')+x.count('e')+x.count('u')
  if cnt not in L.keys():
    L[cnt]=[]
  L[cnt].append(x)
print(L[max(L.keys())])

You can count the number of occurrences of vowels using re

import re
cnt=len(re.findall(r'[aeiou]{1}',x))


问:
What is the point of 'git submodule init'?

Background

To populate a repository's submodules, one typically invokes:

```<code>git submodule init
git submodule update
</code>```

In this usage, git submodule init seems to do only one thing: populate .git/config with information that is already in .gitmodules.

What is the point of that?

Couldn't git submodule update simply use the information from .gitmodules? This would avoid both:

an unnecessary command (git submodule init); and

an unnecessary duplication of data (.gitmodules content into .git/config).

Question

Either:

there are use-cases for git submodule init that I do not know (in which case, please enlighten me!); or else

git submodule init is cruft that could be deprecated in Git without any harm.

Which of these is true?

答:
Reading the git submodule documentation, there is a use-case that ostensibly justifies the existence of git submodule init as a standalone command.

If a user who has cloned a repository wishes to use a different URL for a submodule than is specified by the upstream repository, then that user can:

```<code>git submodule init
vim .git/config # Alter submodule URL as desired, without changing .gitmodules
                # or polluting history.
git submodule update
</code>```

Body:
Background

To populate a repository's submodules, one typically invokes:

git submodule init
git submodule update

In this usage, git submodule init seems to do only one thing: populate .git/config with information that is already in .gitmodules.

What is the point of that?

Couldn't git submodule update simply use the information from .gitmodules? This would avoid both:

an unnecessary command (git submodule init); and

an unnecessary duplication of data (.gitmodules content into .git/config).

Question

Either:

there are use-cases for git submodule init that I do not know (in which case, please enlighten me!); or else

git submodule init is cruft that could be deprecated in Git without any harm.

Which of these is true?

Body:
Reading the git submodule documentation, there is a use-case that ostensibly justifies the existence of git submodule init as a standalone command.

If a user who has cloned a repository wishes to use a different URL for a submodule than is specified by the upstream repository, then that user can:

git submodule init
vim .git/config # Alter submodule URL as desired, without changing .gitmodules
                # or polluting history.
git submodule update


问:
Split a Sentences String into sentence per line in Java
I want to split the sentences into one sentence per line in Java.

Input String:
"Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates. The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund. (See pages 4 through 10 for fund specific results and information.)"

Output:

Sentence1: Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates.

Sentence2: The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund.

Sentence3:(See pages 4 through 10 for fund specific results and information.

I have written a java code to split the Sentences when .('Full stop') occurs, A new line has been coming after U.S.

string = string.replace(". ", ".\n")

答:
You could use String::split with regex to accomplish this like so:

```<code>String[] sentences = paragraph.split("(?<=[^ ]\\.) (?=[^a-z])");
int count = 0;
for(String str:sentences)
    System.out.println("Sentence " + (++count) + ":" + str);
</code>```

This uses advanced regex techniques called look ahead and look behind to retain the delimiters upon matching.

Body:
You could use String::split with regex to accomplish this like so:

String[] sentences = paragraph.split("(?<=[^ ]\\.) (?=[^a-z])");
int count = 0;
for(String str:sentences)
    System.out.println("Sentence " + (++count) + ":" + str);

This uses advanced regex techniques called look ahead and look behind to retain the delimiters upon matching.


问:
UITableViewCell shadows
I'm trying to implement this design but all solutions I have browsed won't work and from what I understand it could be because of the spacing between the cells and the UITableView.

Here's the design:

So basically what I'm trying to achieve is to have shadows from all 4 sides as well as some spacing between each cell and the following cell.
Thanks

Edit:
Here's the code I tried.

```<code>let shadowSize : CGFloat = 5.0
let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                           y: -shadowSize / 2,
                                           width: self.avatarImageView.frame.size.width + shadowSize,
                                           height: self.avatarImageView.frame.size.height + shadowSize))
self.avatarImageView.layer.masksToBounds = false
self.avatarImageView.layer.shadowColor = UIColor.black.cgColor
self.avatarImageView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.avatarImageView.layer.shadowOpacity = 0.5
self.avatarImageView.layer.shadowPath = shadowPath.cgPath
</code>```

Edit 2:
I'd like to point out that all my cell's objects are inside a container UIView. All the above code is applied to this UIView.

答:
You have to make a UIView inside UITableViewCell and work on that view.

FOR SHADOW I AM USING THIS IN UITableViewCell CLASS:-

```<code>viewDummy.addShadow() //use from any view

extension UIView {
    func addShadow(){
        self.layer.shadowColor = UIColor.blackColor().CGColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowRadius = 2.0
        self.layer.shadowOffset = CGSizeMake(1.0, 1.0)
    }
}
</code>```

Title: UITableViewCell shadows

Body:
I'm trying to implement this design but all solutions I have browsed won't work and from what I understand it could be because of the spacing between the cells and the UITableView.

Here's the design:

So basically what I'm trying to achieve is to have shadows from all 4 sides as well as some spacing between each cell and the following cell.
Thanks

Edit:
Here's the code I tried.

let shadowSize : CGFloat = 5.0
let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
                                           y: -shadowSize / 2,
                                           width: self.avatarImageView.frame.size.width + shadowSize,
                                           height: self.avatarImageView.frame.size.height + shadowSize))
self.avatarImageView.layer.masksToBounds = false
self.avatarImageView.layer.shadowColor = UIColor.black.cgColor
self.avatarImageView.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.avatarImageView.layer.shadowOpacity = 0.5
self.avatarImageView.layer.shadowPath = shadowPath.cgPath

Edit 2:
I'd like to point out that all my cell's objects are inside a container UIView. All the above code is applied to this UIView.

Body:
You have to make a UIView inside UITableViewCell and work on that view.

FOR SHADOW I AM USING THIS IN UITableViewCell CLASS:-

viewDummy.addShadow() //use from any view

extension UIView {
    func addShadow(){
        self.layer.shadowColor = UIColor.blackColor().CGColor
        self.layer.shadowOpacity = 0.5
        self.layer.shadowRadius = 2.0
        self.layer.shadowOffset = CGSizeMake(1.0, 1.0)
    }
}


问:
How to convert a string to date/time stamp in PHP
I have a string which has the value '2015-06-04 00:00:00'

How can I convert this to a date/time stamp using PHP?

Many thanks,

Alec

答:
Try this code</p>

```<code>$time = strtotime('2015-06-04 00:00:00'); // convert to datetime
$date = date('Y-m-d H:i:s',$time);        // change format
</code>```

Body:
Try this code

$time = strtotime('2015-06-04 00:00:00'); // convert to datetime
$date = date('Y-m-d H:i:s',$time);        // change format


问:
Connect SpringBoot to MySQL hosted in the cloud requires SSL
I am successful using MySQL Workbench to do full crud on a Bluemix hosted MySQL Compose service.

I then built a simple Microservice with SpringBoot on my local laptop with Apache Derby... successful.

My next step was to use the MySQL Compose hosted in Bluemix.

I edited application.properties and ran into this error
"PKIX path building failed: ...."
"SunCertPathBuilderException: unable to find valid certification path to request target"

```<code>application.properties file
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://somedomain:port/compose?useSSL=true?requireSSL=true
spring.datasource.username=myname
spring.datasource.password=mypassword
</code>```

Bluemix provided me these credentials in json:

```<code>{
  "db_type": "mysql",
  "name": "bmix-dal-yp-xxxxxxx-",
  "uri_cli": "mysql -u myname -p --host somedomain.com --port 5555 --ssl-mode=REQUIRED",
  "ca_certificate_base64": "LS0tLS1CRUd......",
  "deployment_id": "58fexxxxxxxxxxx",
  "uri": "mysql://myname:mypassword@somedomain.com:55555/compose"
}
</code>```

Am I supposed to use the ca certificate somewhere in my application.properties?

Do I need to enable ssl on my embedded tomcat server running by default with springBoot?

How can I configure my springBoot application to connect to my cloud providers MySQL instance with SSL with the json they provided?

```<code>Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
</code>```

答:
Add the following to your pom.xml (or equivalent):

```<code>...
<repositories>
   <repository>
      <id>jcenter</id>
      <url>http://jcenter.bintray.com </url>
      <snapshots>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
        <checksumPolicy>warn</checksumPolicy>
      </snapshots>
       <releases>
         <enabled>true</enabled>
         <checksumPolicy>warn</checksumPolicy>
      </releases>
   </repository>
</repositories>
...
<dependency>
   <groupId>com.orange.clara.cloud.boot.ssl-truststore-gen</groupId>
   <artifactId>spring-boot-ssl-truststore-gen</artifactId>
   <version>2.0.21</version>
</dependency>
...
</code>```

Add the following to your manifest.yml

```<code>env:
    # Add the certificate from VCAP_SERVICES ca_certificate_base64
    # You need to base64 decode the certificate and add it below
    # E.g. echo '<<ca_certificate_base64>>' | base64 -D

    TRUSTED_CA_CERTIFICATE: |-
        -----BEGIN CERTIFICATE-----
        ...
        -----END CERTIFICATE-----
</code>```

For more information, see https://github.com/orange-cloudfoundry/spring-boot-ssl-truststore-gen

Also see a minimal app here: https://github.com/snowch/hello-spring-cloud/tree/8b9728a826dcc1995a7ccb19a852ac8face21147

This is my first answer - this did not work.  Ignore this section.

One option is:

Import the cert to Java truststore file, pack the file into Java
  application and specify its path via JAVA_OPTS environment variable;
  the truststore file can be placed under resource directory. This can
  be used for single applications:

By using the 'cf set-env' command:

```<code>cf set-env <app> JAVA_OPTS '-Djavax.net.ssl.TrustStore=classpath:resources/config/truststore -Djavax.net.ssl.trustStorePassword=changeit'
</code>```

or, by using manifest.yml

```<code>applications:
- name: java-app
  ...
  env:
      JAVA_OPTS: '-Djavax.net.ssl.TrustStore=classpath:resources/config/truststore -Djavax.net.ssl.trustStorePassword=changeit'
</code>```

Note that the certificate in the field ca_certificate_base64 is base64 encoded so you will need to decode it before adding it to your truststore, e.g.

Decode the certificate:

```<code>echo '<<ca_certificate_base64>>' | base64 -D  > ca_certificate.pem
</code>```

Create a truststore:

```<code>keytool -import -trustcacerts -file ca_certificate.pem -alias compose_cert -keystore resources/config/truststore -storepass changeit -noprompt
</code>```

Note that the keystore location (resources/config/truststore) and the storepass (changeit) are set in the JAVA_OPTS.

There are a few different options you can try.  See this documentation for more information: https://discuss.pivotal.io/hc/en-us/articles/223454928-How-to-tell-application-containers-running-Java-apps-to-trust-self-signed-certs-or-a-private-or-internal-CA

Body:
I am successful using MySQL Workbench to do full crud on a Bluemix hosted MySQL Compose service.

I then built a simple Microservice with SpringBoot on my local laptop with Apache Derby... successful.

My next step was to use the MySQL Compose hosted in Bluemix.

I edited application.properties and ran into this error
"PKIX path building failed: ...."
"SunCertPathBuilderException: unable to find valid certification path to request target"

application.properties file
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://somedomain:port/compose?useSSL=true?requireSSL=true
spring.datasource.username=myname
spring.datasource.password=mypassword

Bluemix provided me these credentials in json:

{
  "db_type": "mysql",
  "name": "bmix-dal-yp-xxxxxxx-",
  "uri_cli": "mysql -u myname -p --host somedomain.com --port 5555 --ssl-mode=REQUIRED",
  "ca_certificate_base64": "LS0tLS1CRUd......",
  "deployment_id": "58fexxxxxxxxxxx",
  "uri": "mysql://myname:mypassword@somedomain.com:55555/compose"
}

Am I supposed to use the ca certificate somewhere in my application.properties?

Do I need to enable ssl on my embedded tomcat server running by default with springBoot?

How can I configure my springBoot application to connect to my cloud providers MySQL instance with SSL with the json they provided?

Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Body:
Add the following to your pom.xml (or equivalent):

...
<repositories>
   <repository>
      <id>jcenter</id>
      <url>http://jcenter.bintray.com </url>
      <snapshots>
        <enabled>true</enabled>
        <updatePolicy>never</updatePolicy>
        <checksumPolicy>warn</checksumPolicy>
      </snapshots>
       <releases>
         <enabled>true</enabled>
         <checksumPolicy>warn</checksumPolicy>
      </releases>
   </repository>
</repositories>
...
<dependency>
   <groupId>com.orange.clara.cloud.boot.ssl-truststore-gen</groupId>
   <artifactId>spring-boot-ssl-truststore-gen</artifactId>
   <version>2.0.21</version>
</dependency>
...

Add the following to your manifest.yml

env:
    # Add the certificate from VCAP_SERVICES ca_certificate_base64
    # You need to base64 decode the certificate and add it below
    # E.g. echo '<<ca_certificate_base64>>' | base64 -D

    TRUSTED_CA_CERTIFICATE: |-
        -----BEGIN CERTIFICATE-----
        ...
        -----END CERTIFICATE-----

For more information, see https://github.com/orange-cloudfoundry/spring-boot-ssl-truststore-gen

Also see a minimal app here: https://github.com/snowch/hello-spring-cloud/tree/8b9728a826dcc1995a7ccb19a852ac8face21147

This is my first answer - this did not work.  Ignore this section.

One option is:

Import the cert to Java truststore file, pack the file into Java
  application and specify its path via JAVA_OPTS environment variable;
  the truststore file can be placed under resource directory. This can
  be used for single applications:

By using the 'cf set-env' command:

cf set-env <app> JAVA_OPTS '-Djavax.net.ssl.TrustStore=classpath:resources/config/truststore -Djavax.net.ssl.trustStorePassword=changeit'

or, by using manifest.yml

applications:
- name: java-app
  ...
  env:
      JAVA_OPTS: '-Djavax.net.ssl.TrustStore=classpath:resources/config/truststore -Djavax.net.ssl.trustStorePassword=changeit'

Note that the certificate in the field ca_certificate_base64 is base64 encoded so you will need to decode it before adding it to your truststore, e.g.

Decode the certificate:

echo '<<ca_certificate_base64>>' | base64 -D  > ca_certificate.pem

Create a truststore:

keytool -import -trustcacerts -file ca_certificate.pem -alias compose_cert -keystore resources/config/truststore -storepass changeit -noprompt

Note that the keystore location (resources/config/truststore) and the storepass (changeit) are set in the JAVA_OPTS.

There are a few different options you can try.  See this documentation for more information: https://discuss.pivotal.io/hc/en-us/articles/223454928-How-to-tell-application-containers-running-Java-apps-to-trust-self-signed-certs-or-a-private-or-internal-CA


问:
How to count duplicate elements in ArrayList?
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I've got an arraylist called digits :

```<code> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
</code>```

I created a method which separates each value and saves it to a new array.

```<code>public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}
</code>```

After this I've got a new array called numbers. I'm using sort on this array

```<code>Collections.sort(numbers);
</code>```

and my ArrayList looks like this:

```<code>[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]
</code>```

It has:

```<code>2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;
</code>```

I need to print out the string of numbers depend on how many are they
So it suppose to look like this :
1354678290

答:
By using the Stream API for example.</p>

```<code>package tests;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Duplicates {

    @Test
    public void duplicates() throws Exception {
        List<Integer> items = Arrays.asList(1, 1, 2, 2, 2, 2);

        Map<Integer, Long> result = items.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        Assert.assertEquals(Long.valueOf(2), result.get(1));
        Assert.assertEquals(Long.valueOf(4), result.get(2));
    }
}
</code>```

Body:
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.

I've got an arraylist called digits :

 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]

I created a method which separates each value and saves it to a new array.

public static ArrayList<Integer> myNumbers(int z) {

    ArrayList<Integer> digits = new ArrayList<Integer>();
    String number = String.valueOf(z);
    for (int a = 0; a < number.length(); a++) {
        int j = Character.digit(number.charAt(a), 10);
        digits.add(j);
    }
    return digits;

}

After this I've got a new array called numbers. I'm using sort on this array

Collections.sort(numbers);

and my ArrayList looks like this:

[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]

It has:

2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;

I need to print out the string of numbers depend on how many are they
So it suppose to look like this :
1354678290

Body:
By using the Stream API for example.

package tests;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Duplicates {

    @Test
    public void duplicates() throws Exception {
        List<Integer> items = Arrays.asList(1, 1, 2, 2, 2, 2);

        Map<Integer, Long> result = items.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        Assert.assertEquals(Long.valueOf(2), result.get(1));
        Assert.assertEquals(Long.valueOf(4), result.get(2));
    }
}


答: String#split() takes a regex. In regex, . means anything other than \n. Escape the dot using \, so the resulting parameter becomes \\.

Title: Split a Sentences String into sentence per line in Java

Body:
I want to split the sentences into one sentence per line in Java.

Input String:
"Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates. The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund. (See pages 4 through 10 for fund specific results and information.)"

Output:

Sentence1: Volatility returned to the municipal bond market during the first half of the funds’ fiscal year as investors weighed the potential impact of the U.S. presidential election, strengthening economic conditions and rising interest rates.

Sentence2: The market was further pressured by a record level of municipal bond issuance in 2016. Against this backdrop, all six funds registered declines, ranging from –0.92% for American Funds Short-Term Tax-Exempt Bond Fund to –3.77% for American High-Income Municipal Bond Fund.

Sentence3:(See pages 4 through 10 for fund specific results and information.

I have written a java code to split the Sentences when .('Full stop') occurs, A new line has been coming after U.S.

string = string.replace(". ", ".\n")


问:
Nativescript using custom icons on NavigationButton
I'm trying to add a button with custom fonts on the ActionBar on a NativeScript Angular app. This is what I tried so far:

```<code><ActionBar class="cp-icon">
    <NavigationButton text="" (tap)="goBack()"></NavigationButton>
    <Image src="res://logo_h_white"></Image>
</ActionBar>

// Or one of these optio
<ActionItem text="" (tap)="goBack()"></ActionItem>
<Label text=""></Label>
<Button text=""></Button>
</code>```

But none of them seems to be working. I do have the font instaled because I can use in the view. Also, if I just change the text attribute to be a string instead of an icon, it also doesn't show nothing.

Is there a way to do this?

答:
Your best bet is using the nativescript-ngx-fonticon plugin: https://github.com/NathanWalker/nativescript-ngx-fonticon

Avoid a few common pitfals by also checking this SO answer: https://stackoverflow.com/a/41861624/2596974

Body:
I'm trying to add a button with custom fonts on the ActionBar on a NativeScript Angular app. This is what I tried so far:

<ActionBar class="cp-icon">
    <NavigationButton text="" (tap)="goBack()"></NavigationButton>
    <Image src="res://logo_h_white"></Image>
</ActionBar>

// Or one of these optio
<ActionItem text="" (tap)="goBack()"></ActionItem>

<Button text=""></Button>

But none of them seems to be working. I do have the font instaled because I can use in the view. Also, if I just change the text attribute to be a string instead of an icon, it also doesn't show nothing.

Is there a way to do this?


问:
How to connect via SSL to sequelize DB
I can't seem to find any documentation for SEQUELIZE.JS on how to use a CA.crt in order to enable connection to my database sitting on a remote server.

I figure its something in the options but I can't seem to figure it out

I have tried

```<code>{
 'ssl': true
 'dialectOptions':{
   ssl: {
     ca: 'path/to/ca'
   }
 }
}
</code>```

and a few other things but nothing seem to work for me.

Can anybody help me?

Edit:

Here is an error i get when using the ca thing

```<code>error connecting to db { Error: unable to verify the first certificate
at TLSSocket.<anonymous>
</code>```

答:
As you don't mention the backend DB of choice, I'll give a mysql sample and how I'd suggest you go about it.

First, confirm the connection using the dialect directly, so for mysql2 supplying variables as necessary:

```<code>const connection = mysql.createConnection({
  host: dbVars.host,
  user: dbVars.user,
  database: dbVars.database,
  password: dbVars.password,
  ssl: {
    key: cKey,
    cert: cCert,
    ca: cCA
  }
});
</code>```

Once that connection is confirmed, move it to Sequelize as:

```<code>const sequelize = new Sequelize(dbVars.database, dbVars.user, dbVars.password, {
  host: dbVars.host,
  dialect: 'mysql',
  dialectOptions: {
    ssl: {
      key: cKey,
      cert: cCert,
      ca: cCA
    }
  }
});
</code>```

Note: loading the certs properly was a learning curve and required a direct import using a raw-loader. Example:

```<code>import cKey from 'raw-loader!../certs/client-key.pem';
</code>```

Title: How to connect via SSL to sequelize DB

Body:
I can't seem to find any documentation for SEQUELIZE.JS on how to use a CA.crt in order to enable connection to my database sitting on a remote server.

I figure its something in the options but I can't seem to figure it out

I have tried

{
 'ssl': true
 'dialectOptions':{
   ssl: {
     ca: 'path/to/ca'
   }
 }
}

and a few other things but nothing seem to work for me.

Can anybody help me?

Edit:

Here is an error i get when using the ca thing

error connecting to db { Error: unable to verify the first certificate
at TLSSocket.<anonymous>

Body:
As you don't mention the backend DB of choice, I'll give a mysql sample and how I'd suggest you go about it.

First, confirm the connection using the dialect directly, so for mysql2 supplying variables as necessary:

const connection = mysql.createConnection({
  host: dbVars.host,
  user: dbVars.user,
  database: dbVars.database,
  password: dbVars.password,
  ssl: {
    key: cKey,
    cert: cCert,
    ca: cCA
  }
});

Once that connection is confirmed, move it to Sequelize as:

const sequelize = new Sequelize(dbVars.database, dbVars.user, dbVars.password, {
  host: dbVars.host,
  dialect: 'mysql',
  dialectOptions: {
    ssl: {
      key: cKey,
      cert: cCert,
      ca: cCA
    }
  }
});

Note: loading the certs properly was a learning curve and required a direct import using a raw-loader. Example:

import cKey from 'raw-loader!../certs/client-key.pem';


问:
Oracle SQL multiple tables
I'm still pretty fresh with SQL in general so this is probably not the best worded question. I want to get columns from different tables. They don't have any common column but there's 3rd table that has information that's able to link them together.

This is how I've tried to go about it:

```<code>SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17',
    CI_SP.SP_TYPE_CD WHERE SP_TYPE_CD='G-RES'
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID
</code>```

And this is the error that I receive in return:
    ORA-00923: FROM keyword not found where expected
    00923. 00000 -  "FROM keyword not found where expected"
    *Cause:

    *Action:
    Error at Line: 3 Column: 18

Anyone would be able to point me where I've got it wrong?

答:
the where condition should be after from table
for example select * from tab1 where ....

try it like this :

```<code>SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT ,
    CI_SP.SP_TYPE_CD
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID
WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17'
and SP_TYPE_CD='G-RES'
</code>```

also as user artur notices , are you joinin on CI_SA ? or CI_SA_SP ? if CI_SA you have too add alias like the below:

INNER JOIN CI_SA CI_SA_SP...

Title: Oracle SQL multiple tables

Body:
I'm still pretty fresh with SQL in general so this is probably not the best worded question. I want to get columns from different tables. They don't have any common column but there's 3rd table that has information that's able to link them together.

This is how I've tried to go about it:

SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17',
    CI_SP.SP_TYPE_CD WHERE SP_TYPE_CD='G-RES'
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID

And this is the error that I receive in return:
    ORA-00923: FROM keyword not found where expected
    00923. 00000 -  "FROM keyword not found where expected"
    *Cause:

    *Action:
    Error at Line: 3 Column: 18

Anyone would be able to point me where I've got it wrong?

Body:
the where condition should be after from table
for example select * from tab1 where ....

try it like this :

SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT ,
    CI_SP.SP_TYPE_CD
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID
WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17'
and SP_TYPE_CD='G-RES'

also as user artur notices , are you joinin on CI_SA ? or CI_SA_SP ? if CI_SA you have too add alias like the below:

INNER JOIN CI_SA CI_SA_SP...


问:
Powershell: A positional parameter cannot be found that accepts argument “test”
I'm trying to execute the following command via command line

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  Send-MailMessage -from "mail.me" -to "mail.me" -Subject "PS test !" -Body "Hi this is a power shell mail test" -SmtpServer "mail.domain.com"
</code>```

But I'm getting the following error :

Send-MailMessage: A positional parameter cannot be found that accepts argument  « test ».

Au niveau de ligne : 1 Caractère : 17

Send-MailMessage <<<<  -from mail.me -to mail.me -Subject PS test ! -Body Hi this is a power shell mail test -SmtpServer mail.domain.com

CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException

FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell

.Commands.SendMailMessage

The problem is that the same command works well when directly executed in Power Shell, but without the path.

What could be the problem generating this exception ?

答:
Use -commandand braces. Currently, you are launching powershell and passing it multiple arguments instead of asking it to execute your code.

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -command "& {Send-MailMessage -from "mail.me" -to "mail.me" -Subject "PS test !" -Body "Hi this is a power shell mail test" -SmtpServer "mail.domain.com"}"
</code>```

I'm getting errors for the some of values you have set (characters that need to be escaped, invalid emails etc), so replaced and got this to run:

```<code>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -Command "& {Send-MailMessage -From test@test.com -To othertest@test.com -Subject "whatevs" -SmtpServer "localhost" -Body "whatevs"}"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to execute the following command via command line

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  Send-MailMessage -from "mail.me" -to "mail.me" -Subject "PS test !" -Body "Hi this is a power shell mail test" -SmtpServer "mail.domain.com"

But I'm getting the following error :

Send-MailMessage: A positional parameter cannot be found that accepts argument  « test ».

Au niveau de ligne : 1 Caractère : 17

Send-MailMessage <<<<  -from mail.me -to mail.me -Subject PS test ! -Body Hi this is a power shell mail test -SmtpServer mail.domain.com

CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException

FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell

.Commands.SendMailMessage

The problem is that the same command works well when directly executed in Power Shell, but without the path.

What could be the problem generating this exception ?

Body:
Use -commandand braces. Currently, you are launching powershell and passing it multiple arguments instead of asking it to execute your code.

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -command "& {Send-MailMessage -from "mail.me" -to "mail.me" -Subject "PS test !" -Body "Hi this is a power shell mail test" -SmtpServer "mail.domain.com"}"

I'm getting errors for the some of values you have set (characters that need to be escaped, invalid emails etc), so replaced and got this to run:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe  -Command "& {Send-MailMessage -From test@test.com -To othertest@test.com -Subject "whatevs" -SmtpServer "localhost" -Body "whatevs"}"


问:
search tweet from tweet id in elasticsearch by custom id
I have been trying to search for the particular tweet through custom id in Kibana, my elasticsearch repo has the timeline json of a multiple accounts. I have tried so much formats but could not get it.

```<code>GET twitter/tweet/_search
{
   "query":{
      "term":{"id":"850330838709489700"}
   }
}
</code>```

following is the document sample.

```<code>{
        "_index": "twitter",
        "_type": "tweet",
        "_id": "AVwvzcZROQ98HXQdQAPR",
        "_score": 0,
        "_source": {
          "contributors": null,
          "truncated": false,
          "text": """"@zee_alam: Jiyoo. https://.../5qojZMzt4t"
Don't mind but this is bullshit """,
          "is_quote_status": false,
          "in_reply_to_status_id": 833583764513181700,
          "id": 833609664973635600,
          "favorite_count": 1,
          "source": """<a href="http://www.twitter.com" rel="nofollow">Twitter for Windows Phone</a>""",
          "retweeted": false,
          "coordinates": {
            "type": "Point",
            "coordinates": [
              73.07080201,
              33.64006041
            ]
          },
          "entities": {
            "symbols": [],
            "user_mentions": [
              {
                "id": 263167083,
                "indices": [
                  1,
                  10
                ],
                "id_str": "263167083",
                "screen_name": "zee_alam",
                "name": "Zee Shan Alam"
              }
            ],
            "hashtags": [],
            "urls": [
              {
                "url": "https://xxxxqojZMzt4t",
                "indices": [
                  19,
                  42
                ],
                "expanded_url": "http://xxxxme/6AFOzdQj2",
                "display_url": "fb.me/6AFOzdQj2"
              }
            ]
          },
          "in_reply_to_screen_name": "zee_alam",
          "in_reply_to_user_id": 263167083,
          "retweet_count": 0,
          "id_str": "833609664973635584",
          "favorited": false,
          "user": {
            "follow_request_sent": false,
            "has_extended_profile": true,
            "profile_use_background_image": false,
            "default_profile_image": false,
            "id": 1217815686,
            "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme8/bg.gif",
            "verified": false,
            "translator_type": "none",
            "profile_text_color": "000000",
            "profile_image_url_https": "https://pbs.twimg.com/profile_images/838740477230911488/B5ynFwDD_normal.jpg",
            "profile_sidebar_fill_color": "000000",
            "entities": {
              "url": {
                "urls": [
                  {
                    "url": "https://xxxxbQ6KljtBK",
                    "indices": [
                      0,
                      23
                    ],
                    "expanded_url": "https://etabz.blogspot.com",
                    "display_url": "etabz.blogspot.com"
                  }
                ]
              },
              "description": {
                "urls": []
              }
            },
            "followers_count": 88,
            "profile_sidebar_border_color": "000000",
            "id_str": "1217815686",
            "profile_background_color": "000000",
            "listed_count": 1,
            "is_translation_enabled": false,
            "utc_offset": 18000,
            "statuses_count": 295,
            "description": "Bi-Tri- quardi | Taekwando & Parkour freak && Climber | Sagittarius 10 |  Lucky  13 | Future is just Unexpected so cheers | Stay happy",
            "friends_count": 157,
            "location": "Islamabd, Pakistan.",
            "profile_link_color": "1B95E0",
            "profile_image_url": "http://pbs.twimg.com/profile_images/838740477230911488/B5ynFwDD_normal.jpg",
            "following": true,
            "geo_enabled": true,
            "profile_banner_url": "https://pbs.twimg.com/profile_banners/1217815686/1468083529",
            "profile_background_image_url": "http://abs.twimg.com/images/themes/theme8/bg.gif",
            "screen_name": "shaamuji",
            "lang": "en",
            "profile_background_tile": false,
            "favourites_count": 169,
            "name": "Ehtisham ullah",
            "notifications": false,
            "url": "https:/xxxxbQ6KljtBK",
            "created_at": "Mon Feb 25 10:08:09 +0000 2013",
            "contributors_enabled": false,
            "time_zone": "Karachi",
            "protected": false,
            "default_profile": false,
            "is_translator": false
          },
          "geo": {
            "type": "Point",
            "coordinates": [
              33.64006041,
              73.07080201
            ]
          },
          "in_reply_to_user_id_str": "263167083",
          "possibly_sensitive": false,
          "lang": "en",
          "created_at": "Mon Feb 20 09:30:06 +0000 2017",
          "in_reply_to_status_id_str": "833583764513181697",
          "place": {
            "country_code": "PK",
            "url": "https://api.twitter.com/1.1/geo/id/008a844c675a661b.json",
            "country": "Pakistan",
            "place_type": "city",
            "bounding_box": {
              "type": "Polygon",
              "coordinates": [
                [
                  [
                    72.952919,
                    33.53611
                  ],
                  [
                    73.122971,
                    33.53611
                  ],
                  [
                    73.122971,
                    33.670082
                  ],
                  [
                    72.952919,
                    33.670082
                  ]
                ]
              ]
            },
            "contained_within": [],
            "full_name": "Rawalpindi, Pakistan",
            "attributes": {},
            "id": "008a844c675a661b",
            "name": "Rawalpindi"
          }
        }
      }
</code>```

see the result displayed

答: Issue is solved as the problem was with the representation of the id in kibana. I was comparing with the values that was rounded off where as the original value in elasticsearch was different. here is the detail</p>

Body:
I have been trying to search for the particular tweet through custom id in Kibana, my elasticsearch repo has the timeline json of a multiple accounts. I have tried so much formats but could not get it.

GET twitter/tweet/_search
{
   "query":{
      "term":{"id":"850330838709489700"}
   }
}

following is the document sample.

{
        "_index": "twitter",
        "_type": "tweet",
        "_id": "AVwvzcZROQ98HXQdQAPR",
        "_score": 0,
        "_source": {
          "contributors": null,
          "truncated": false,
          "text": """"@zee_alam: Jiyoo. https://.../5qojZMzt4t"
Don't mind but this is bullshit """,
          "is_quote_status": false,
          "in_reply_to_status_id": 833583764513181700,
          "id": 833609664973635600,
          "favorite_count": 1,
          "source": """Twitter for Windows Phone""",
          "retweeted": false,
          "coordinates": {
            "type": "Point",
            "coordinates": [
              73.07080201,
              33.64006041
            ]
          },
          "entities": {
            "symbols": [],
            "user_mentions": [
              {
                "id": 263167083,
                "indices": [
                  1,
                  10
                ],
                "id_str": "263167083",
                "screen_name": "zee_alam",
                "name": "Zee Shan Alam"
              }
            ],
            "hashtags": [],
            "urls": [
              {
                "url": "https://xxxxqojZMzt4t",
                "indices": [
                  19,
                  42
                ],
                "expanded_url": "http://xxxxme/6AFOzdQj2",
                "display_url": "fb.me/6AFOzdQj2"
              }
            ]
          },
          "in_reply_to_screen_name": "zee_alam",
          "in_reply_to_user_id": 263167083,
          "retweet_count": 0,
          "id_str": "833609664973635584",
          "favorited": false,
          "user": {
            "follow_request_sent": false,
            "has_extended_profile": true,
            "profile_use_background_image": false,
            "default_profile_image": false,
            "id": 1217815686,
            "profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme8/bg.gif",
            "verified": false,
            "translator_type": "none",
            "profile_text_color": "000000",
            "profile_image_url_https": "https://pbs.twimg.com/profile_images/838740477230911488/B5ynFwDD_normal.jpg",
            "profile_sidebar_fill_color": "000000",
            "entities": {
              "url": {
                "urls": [
                  {
                    "url": "https://xxxxbQ6KljtBK",
                    "indices": [
                      0,
                      23
                    ],
                    "expanded_url": "https://etabz.blogspot.com",
                    "display_url": "etabz.blogspot.com"
                  }
                ]
              },
              "description": {
                "urls": []
              }
            },
            "followers_count": 88,
            "profile_sidebar_border_color": "000000",
            "id_str": "1217815686",
            "profile_background_color": "000000",
            "listed_count": 1,
            "is_translation_enabled": false,
            "utc_offset": 18000,
            "statuses_count": 295,
            "description": "Bi-Tri- quardi | Taekwando & Parkour freak && Climber | Sagittarius 10 |  Lucky  13 | Future is just Unexpected so cheers | Stay happy",
            "friends_count": 157,
            "location": "Islamabd, Pakistan.",
            "profile_link_color": "1B95E0",
            "profile_image_url": "http://pbs.twimg.com/profile_images/838740477230911488/B5ynFwDD_normal.jpg",
            "following": true,
            "geo_enabled": true,
            "profile_banner_url": "https://pbs.twimg.com/profile_banners/1217815686/1468083529",
            "profile_background_image_url": "http://abs.twimg.com/images/themes/theme8/bg.gif",
            "screen_name": "shaamuji",
            "lang": "en",
            "profile_background_tile": false,
            "favourites_count": 169,
            "name": "Ehtisham ullah",
            "notifications": false,
            "url": "https:/xxxxbQ6KljtBK",
            "created_at": "Mon Feb 25 10:08:09 +0000 2013",
            "contributors_enabled": false,
            "time_zone": "Karachi",
            "protected": false,
            "default_profile": false,
            "is_translator": false
          },
          "geo": {
            "type": "Point",
            "coordinates": [
              33.64006041,
              73.07080201
            ]
          },
          "in_reply_to_user_id_str": "263167083",
          "possibly_sensitive": false,
          "lang": "en",
          "created_at": "Mon Feb 20 09:30:06 +0000 2017",
          "in_reply_to_status_id_str": "833583764513181697",
          "place": {
            "country_code": "PK",
            "url": "https://api.twitter.com/1.1/geo/id/008a844c675a661b.json",
            "country": "Pakistan",
            "place_type": "city",
            "bounding_box": {
              "type": "Polygon",
              "coordinates": [
                [
                  [
                    72.952919,
                    33.53611
                  ],
                  [
                    73.122971,
                    33.53611
                  ],
                  [
                    73.122971,
                    33.670082
                  ],
                  [
                    72.952919,
                    33.670082
                  ]
                ]
              ]
            },
            "contained_within": [],
            "full_name": "Rawalpindi, Pakistan",
            "attributes": {},
            "id": "008a844c675a661b",
            "name": "Rawalpindi"
          }
        }
      }

see the result displayed


问:
How to read in existing data into Quill JS
I am having real trouble understanding how to work with quill...

Saving the data is not a problem as that pretty straight forward :)

I am a little stuck on two points

How to edit the saved data in quill

How to parse the saved data to create a static page

can anyone offer any advice how to load the delta

```<code>{"ops":[{"insert":"this is a test bit of text\n"}]}
</code>```

back into the quill editor and how to parse the output to create a page?

Thanks in advance for any replies!

答:
This works for me. May it will helps some one.

```<code>editor.root.innerHTML = "<p><strong class=\"ql-size-large\"><em><s><u>This would be the text that we are going to show in the editor with pre-formatting.<\/u><\/s><\/em><\/strong><\/p>";
</code>```

Here editor will be your quill instance.

Thanks to this LINK

Body:
I am having real trouble understanding how to work with quill...

Saving the data is not a problem as that pretty straight forward :)

I am a little stuck on two points

How to edit the saved data in quill

How to parse the saved data to create a static page

can anyone offer any advice how to load the delta

{"ops":[{"insert":"this is a test bit of text\n"}]}

back into the quill editor and how to parse the output to create a page?

Thanks in advance for any replies!

Body:
This works for me. May it will helps some one.

editor.root.innerHTML = "<p><strong class=\"ql-size-large\"><em><s><u>This would be the text that we are going to show in the editor with pre-formatting.<\/u><\/s><\/em><\/strong><\/p>";

Here editor will be your quill instance.

Thanks to this LINK


答:
The following worked properly. </p>

```<code>a=Array.new(4){ Array.new(5) { Array.new(6,0) }}
</code>```

Title: How to initialise a three dimensional ruby array

Body:
I want to initialise a three dimensional ruby array. For a two-dimensional array, I can do

a = Array.new(4){ Array.new(5, 0) }

so I have tried

a = Array.new(4) { Array.new(5, Array.new(6, 0)) }

but if I do a[1][2][3] = 5, it not only sets that element to 5, it sets the corresponding element to 5 in other sub arrays i.e.

[[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0], [0, 0, 0, 5, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]],
 [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]]

Body:
The following worked properly.

a=Array.new(4){ Array.new(5) { Array.new(6,0) }}


答:
The where clauses should be at the end:</p>

```<code>SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT ,
    CI_SP.SP_TYPE_CD
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID
WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17' and SP_TYPE_CD='G-RES'
</code>```

Title: Oracle SQL multiple tables

Body:
The where clauses should be at the end:

SELECT
    CI_SA.ACCT_ID,
    CI_SA.EXPIRE_DT ,
    CI_SP.SP_TYPE_CD
FROM CI_SA
INNER JOIN CI_SA ON CI_SA.SA_ID = CI_SA_SP.SA_ID AND CI_SP.SP_ID =
CI_SA_SP.SP_ID
WHERE EXPIRE_DT BETWEEN '15-APR-17' AND '30-APR-17' and SP_TYPE_CD='G-RES'


问:
Why am I receiving this IO exception when querying a Hive table using SparkSQL in Zeppelin?
I followed the first part of this tutorial to create an external Hive table and point it towards a specific S3 Bucket. In the Hue interface, I can browse a sample of the data after a successful creation. If I switch over to Zeppelin and run the following command: %sql show tables I can see my table listed next to the default database.

Now, if I actually try and query the table, I get a java.io.IOException: Not a file: s3://my-bucket/my-subdirectory error. The error makes sense, but Hive makes you specify an S3 bucket and not an actual S3 file, so I'm not sure how to make both happy!

Note, there is only 1 file in this directory and I'm not attempting any partitioning. The file is compressed and named foo.txt.gz and was generated using psql and dumping a postgres table.

Edit: showing code

Create Script

```<code>CREATE TABLE IF NOT EXISTS foo (
  name STRING,
  age INT
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION 's3://my-bucket/my-directory/'
</code>```

Querying In Zeppelin

```<code>%sql SELECT * FROM foo LIMIT 100

java.io.IOException: Not a file: s3://my-bucket/my-directory
at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:288)
at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:202)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:311)
at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2371)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2370)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2377)
at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2113)
at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2112)
at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2795)
at org.apache.spark.sql.Dataset.head(Dataset.scala:2112)
at org.apache.spark.sql.Dataset.take(Dataset.scala:2327)
at sun.reflect.GeneratedMethodAccessor114.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.zeppelin.spark.ZeppelinContext.showDF(ZeppelinContext.java:235)
at org.apache.zeppelin.spark.SparkSqlInterpreter.interpret(SparkSqlInterpreter.java:130)
at org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:95)
at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:490)
at org.apache.zeppelin.scheduler.Job.run(Job.java:175)
at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
</code>```

答:
There is potentially some listing confusion here related to the fake directory markers that the blobstore clients put in after a mkdir() call, markers they are meant to remove after actually creating files there.

that may be creating confusion

Have a look in the S3 browser in the AWS web pages, and look for a blob "my-directory/". If it is there, delete it

Body:
I followed the first part of this tutorial to create an external Hive table and point it towards a specific S3 Bucket. In the Hue interface, I can browse a sample of the data after a successful creation. If I switch over to Zeppelin and run the following command: %sql show tables I can see my table listed next to the default database.

Now, if I actually try and query the table, I get a java.io.IOException: Not a file: s3://my-bucket/my-subdirectory error. The error makes sense, but Hive makes you specify an S3 bucket and not an actual S3 file, so I'm not sure how to make both happy!

Note, there is only 1 file in this directory and I'm not attempting any partitioning. The file is compressed and named foo.txt.gz and was generated using psql and dumping a postgres table.

Edit: showing code

Create Script

CREATE TABLE IF NOT EXISTS foo (
  name STRING,
  age INT
)
ROW FORMAT DELIMITED FIELDS TERMINATED BY ','
STORED AS TEXTFILE
LOCATION 's3://my-bucket/my-directory/'

Querying In Zeppelin

%sql SELECT * FROM foo LIMIT 100

java.io.IOException: Not a file: s3://my-bucket/my-directory
at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:288)
at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:202)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:252)
at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:250)
at scala.Option.getOrElse(Option.scala:121)
at org.apache.spark.rdd.RDD.partitions(RDD.scala:250)
at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:311)
at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2371)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2370)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2377)
at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2113)
at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:2112)
at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2795)
at org.apache.spark.sql.Dataset.head(Dataset.scala:2112)
at org.apache.spark.sql.Dataset.take(Dataset.scala:2327)
at sun.reflect.GeneratedMethodAccessor114.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.zeppelin.spark.ZeppelinContext.showDF(ZeppelinContext.java:235)
at org.apache.zeppelin.spark.SparkSqlInterpreter.interpret(SparkSqlInterpreter.java:130)
at org.apache.zeppelin.interpreter.LazyOpenInterpreter.interpret(LazyOpenInterpreter.java:95)
at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:490)
at org.apache.zeppelin.scheduler.Job.run(Job.java:175)
at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)