问:
How to convert this Octave/Matlab code to Python 3.7.4?
I have some working Octave/Matlab code that I'm trying to get working / converted to Python 3.7.4, so I can use it in Blender 2.82 which uses Python 3.7.4.

The working Octave/Matlab code is:

c=[7,-2,-4,-8]

[rw col]= size(c); %get size a array

num_of_loops=5 %number of loops to iterate
a= zeros(num_of_loops,col); %allocate memory to array
b= zeros(1,(rw*col)); %allocate memory to array

a(1,:)=c; %add c array to 1st row in array

for n=1:num_of_loops
  n
  a = c .+ [c(end).*(0:4)].';
  b = vec (a.', 2);
endfor

b=reshape(a',1,[]);
```

<p>Which gives me the correct output of:</p>

```c=
7   -2  -4  -8

a=
 7  -2  -4  -8
-1  -10 -12 -16
-9  -18 -20 -24
-17 -26 -28 -32
-25 -34 -36 -40

b=
7   -2  -4  -8  -1  -10 -12 -16 -9  -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40
```

<p>(<strong>If you need the if / then / else commands</strong> here's the original question.)</p>

<p>I tried the online convert octave/matlab to python converter and it gives me the code below (which doesn't fully work). How can I fix the Python 3.x code to get it to work in Blender 2.82 which uses Python 3.7.4?</p>

<pre class="lang-py prettyprint-override"><code>c = mcat([7, -2, -4, -8]); print c

[rw, col] = size(c)#get size a array

num_of_loops = 5; print num_of_loops#number of loops to iterate
a = zeros(num_of_loops, col)#allocate memory to array
b = zeros(1, (rw * col))#allocate memory to array

a(1, mslice[:]).lvalue = c#add c array to 1st row in array

for n in mslice[1:num_of_loops]:
    n()
    mcat([c(end) *elmul* (mslice[0:4])]).T
    b = vec(a.T, 2)
    end

    b = reshape(a.cT, 1, mcat([]))
</code>```

答:
The given MATLAB/Octave code can be minimized (see also the comment on your previous question) to:

c = [7, -2, -4, -8]
a = c .+ [c(end).*(0:4)].'
b = vec(a.', 2)
```

<p>The corresponding output is:</p>

<pre class="lang-none prettyprint-override"><code>c =
   7  -2  -4  -8

a =
    7   -2   -4   -8
   -1  -10  -12  -16
   -9  -18  -20  -24
  -17  -26  -28  -32
  -25  -34  -36  -40

b =
    7 -2 -4 -8 -1 -10 -12 -16 -9 -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40
</code>```

The MATLAB/Octave code can be easily transferred to Python using NumPy. There are a lot of resources on "NumPy for MATLAB users" which can be found online, e.g. this one from the developers themselves.

My solution would look like this:

import numpy as np

c = np.array([[7, -2, -4, -8]])
a = c + (np.expand_dims(c[0][-1] * np.arange(5), 1))
b = a.reshape(1, np.prod(a.shape))

# Just for console output
print('c = ')
print(c, '\n')
print('a = ')
print(a, '\n')
print('b = ')
print(b, '\n')
```

<p>The output of that code is:</p>

<pre class="lang-none prettyprint-override"><code>c =
[[ 7 -2 -4 -8]]

a =
[[  7  -2  -4  -8]
 [ -1 -10 -12 -16]
 [ -9 -18 -20 -24]
 [-17 -26 -28 -32]
 [-25 -34 -36 -40]]

b =
[[  7 -2 -4 -8 -1 -10 -12 -16 -9 -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40]]
</code>```

It's up to you to check, if NumPy is supported in your environment. If not, I'd assume, a solution might get a lot more complicated.

Hope that helps.

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
Octave:      5.1.0
----------------------------------------
```

Body:
I have some working Octave/Matlab code that I'm trying to get working / converted to Python 3.7.4, so I can use it in Blender 2.82 which uses Python 3.7.4.

The working Octave/Matlab code is:

c=[7,-2,-4,-8]

[rw col]= size(c); %get size a array

num_of_loops=5 %number of loops to iterate
a= zeros(num_of_loops,col); %allocate memory to array
b= zeros(1,(rw*col)); %allocate memory to array

a(1,:)=c; %add c array to 1st row in array

for n=1:num_of_loops
  n
  a = c .+ [c(end).*(0:4)].';
  b = vec (a.', 2);
endfor

b=reshape(a',1,[]);

Which gives me the correct output of:

c=
7   -2  -4  -8

a=
 7  -2  -4  -8
-1  -10 -12 -16
-9  -18 -20 -24
-17 -26 -28 -32
-25 -34 -36 -40

b=
7   -2  -4  -8  -1  -10 -12 -16 -9  -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40

(If you need the if / then / else commands here's the original question.)

I tried the online convert octave/matlab to python converter and it gives me the code below (which doesn't fully work). How can I fix the Python 3.x code to get it to work in Blender 2.82 which uses Python 3.7.4?

c = mcat([7, -2, -4, -8]); print c

[rw, col] = size(c)#get size a array

num_of_loops = 5; print num_of_loops#number of loops to iterate
a = zeros(num_of_loops, col)#allocate memory to array
b = zeros(1, (rw * col))#allocate memory to array

a(1, mslice[:]).lvalue = c#add c array to 1st row in array

for n in mslice[1:num_of_loops]:
    n()
    mcat([c(end) *elmul* (mslice[0:4])]).T
    b = vec(a.T, 2)
    end

    b = reshape(a.cT, 1, mcat([]))

Body:
The given MATLAB/Octave code can be minimized (see also the comment on your previous question) to:

c = [7, -2, -4, -8]
a = c .+ [c(end).*(0:4)].'
b = vec(a.', 2)

The corresponding output is:

c =
   7  -2  -4  -8

a =
    7   -2   -4   -8
   -1  -10  -12  -16
   -9  -18  -20  -24
  -17  -26  -28  -32
  -25  -34  -36  -40

b =
    7 -2 -4 -8 -1 -10 -12 -16 -9 -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40

The MATLAB/Octave code can be easily transferred to Python using NumPy. There are a lot of resources on "NumPy for MATLAB users" which can be found online, e.g. this one from the developers themselves.

My solution would look like this:

import numpy as np

c = np.array([[7, -2, -4, -8]])
a = c + (np.expand_dims(c[0][-1] * np.arange(5), 1))
b = a.reshape(1, np.prod(a.shape))

# Just for console output
print('c = ')
print(c, '\n')
print('a = ')
print(a, '\n')
print('b = ')
print(b, '\n')

The output of that code is:

c =
[[ 7 -2 -4 -8]]

a =
[[  7  -2  -4  -8]
 [ -1 -10 -12 -16]
 [ -9 -18 -20 -24]
 [-17 -26 -28 -32]
 [-25 -34 -36 -40]]

b =
[[  7 -2 -4 -8 -1 -10 -12 -16 -9 -18 -20 -24 -17 -26 -28 -32 -25 -34 -36 -40]]

It's up to you to check, if NumPy is supported in your environment. If not, I'd assume, a solution might get a lot more complicated.

Hope that helps.

----------------------------------------
System information
----------------------------------------
Platform:    Windows-10-10.0.16299-SP0
Python:      3.8.1
NumPy:       1.18.1
Octave:      5.1.0
----------------------------------------


来源: stackexchange

问:
Javascript: Is there a way to get the filename of the dragged-in file?
When user drags in a file, is there a way in Javascript to detect its filename onDragEnter (not after it's uploaded)?</p>

答:
Not every browser supports dragging files to a file input (FF4 on OS X certainly doesn't), but you can check the value of the file input on change event, which should provide a uniform result across browsers.

Depending on the browser, you can check the value of

```<code><input type="file" id="foo" />
</code>```

like so:

```<code>// vanilla JS
var filename = document.getElementById('foo').value;

// jQuery
var filename = $('#foo').val();
</code>```

You'd do this inside of a change listener, like so (example for jQuery in jsFiddle below):

```<code>function alertFileName()
{
    alert(this.value);
}

var input = document.getElementById('foo');

// not IE friendly; use `attachEvent` instead
input.addEventListener('change', alertFilename, false);
</code>```

If you upload a file named bar.txt, filename will be:

'C:\fakepath\bar.txt' (Chrome)

'bar.txt' (Firefox 4, Safari)

??? (IE)

I am not set up to test IE at present; feel free to try it yourself.

ContentLicense: CC BY-SA 3.0

Body:
Not every browser supports dragging files to a file input (FF4 on OS X certainly doesn't), but you can check the value of the file input on change event, which should provide a uniform result across browsers.

Depending on the browser, you can check the value of

<input type="file" id="foo" />

like so:

// vanilla JS
var filename = document.getElementById('foo').value;

// jQuery
var filename = $('#foo').val();

You'd do this inside of a change listener, like so (example for jQuery in jsFiddle below):

function alertFileName()
{
    alert(this.value);
}

var input = document.getElementById('foo');

// not IE friendly; use `attachEvent` instead
input.addEventListener('change', alertFilename, false);

If you upload a file named bar.txt, filename will be:

'C:\fakepath\bar.txt' (Chrome)

'bar.txt' (Firefox 4, Safari)

??? (IE)

I am not set up to test IE at present; feel free to try it yourself.


问:
Angular 8: access the assets folder when running ng build --prod --base-href './project1'
My client want me to deploy multiple projects on the same ngnix server with the following configuration.

```<code>location /project1/ {
    alias /usr/local/var/www/project1/;
    try_files $uri$args $uri$args/ /project1/index.html;
}
</code>```

In the above configuration I could not access the assets folder as it's in the project1 folder and I try to access it from the root of the domain example src:

url('/assets/fonts/texta/Texta-Regular/Texta-Regular.eot')

When I change the path with src: url('./assets/fonts/texta/Texta-Regular/Texta-Regular.eot') I'm getting following problem when building the production build

ERROR in ./src/styles.scss Module build failed (from
  ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleError:
  Module Error (from ./node_modules/postcss-loader/src/index.js):
  (Emitted value instead of an instance of Error) CssSyntaxError:
  /Users/Desktop/personal/projects/example/src/styles.scss:10115:13:
  Can't resolve
  './assets/fonts/texta/Texta-Regular/Texta-Regular.eot%3F' in
  '/Users/Desktop/personal/projects/example/src'

答:
I have not problem to compile url('./assets/fonts/texta/Texta-Regular/Texta-Regular.eot').
Please check the Texta-Regular.eot presence.</p>

ContentLicense: CC BY-SA 4.0

Body:
My client want me to deploy multiple projects on the same ngnix server with the following configuration.

location /project1/ {
    alias /usr/local/var/www/project1/;
    try_files $uri$args $uri$args/ /project1/index.html;
}

In the above configuration I could not access the assets folder as it's in the project1 folder and I try to access it from the root of the domain example src:

url('/assets/fonts/texta/Texta-Regular/Texta-Regular.eot')

When I change the path with src: url('./assets/fonts/texta/Texta-Regular/Texta-Regular.eot') I'm getting following problem when building the production build

ERROR in ./src/styles.scss Module build failed (from
  ./node_modules/mini-css-extract-plugin/dist/loader.js): ModuleError:
  Module Error (from ./node_modules/postcss-loader/src/index.js):
  (Emitted value instead of an instance of Error) CssSyntaxError:
  /Users/Desktop/personal/projects/example/src/styles.scss:10115:13:
  Can't resolve
  './assets/fonts/texta/Texta-Regular/Texta-Regular.eot%3F' in
  '/Users/Desktop/personal/projects/example/src'


问:
How to get Log with Stackdriver Logging API
I'm developing a chatbot using Dialogflow and I need to get full conversation log from it.

I checked this page and I guessed it is able to achieve it by using Stackdriver Logging api.

I referred below page and I tried, however using this api, it occurs 403 error.
https://cloud.google.com/logging/docs/reference/v2/rest/v2/logs/list

Did I use this in a wrong way?

How can I resolve this problem?

This is the error message.

```<code>{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}
</code>```

This is my code where calling the api.
I used Google Apps Script.

```<code>function getLogs() {
  //XXXXXXXX is my project_id
  var output = UrlFetchApp.fetch('https://logging.googleapis.com/v2/projects/XXXXXXXX/logs');
  Logger.log(output)
}
</code>```

答:
I've resolved this way.

Add my api key to http request.

```<code>var options = {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
var logs = UrlFetchApp.fetch("https://logging.googleapis.com/v2/projects/XXXXXXXX/logs?key=my_api_key", options)
</code>```

Add scope to appscript.json.

```<code>"oauthScopes": ["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/script.external_request"]
</code>```

Then I found logs.list methond is not appropriate for my goal so I need to change to v2.entries method.

```<code>function getLogs(){
var options = {
    method: "post",
    contentType: "application/json",
    headers: {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: JSON.stringify({
      resourceNames: ['projects/XXXXXXX'],
      filter: "timestamp >= searchdate",
      orderBy: "timestamp desc",
      pageSize: 1,
    }),
  }

  var logs = UrlFetchApp.fetch("https://logging.googleapis.com/v2/entries:list?key=my_api_key", options);
  Logger.log(logs);

}
</code>```

Body:
I'm developing a chatbot using Dialogflow and I need to get full conversation log from it.

I checked this page and I guessed it is able to achieve it by using Stackdriver Logging api.

I referred below page and I tried, however using this api, it occurs 403 error.
https://cloud.google.com/logging/docs/reference/v2/rest/v2/logs/list

Did I use this in a wrong way?

How can I resolve this problem?

This is the error message.

{
  "error": {
    "code": 403,
    "message": "The request is missing a valid API key.",
    "status": "PERMISSION_DENIED"
  }
}

This is my code where calling the api.
I used Google Apps Script.

function getLogs() {
  //XXXXXXXX is my project_id
  var output = UrlFetchApp.fetch('https://logging.googleapis.com/v2/projects/XXXXXXXX/logs');
  Logger.log(output)
}

Body:
I've resolved this way.

Add my api key to http request.

var options = {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}};
var logs = UrlFetchApp.fetch("https://logging.googleapis.com/v2/projects/XXXXXXXX/logs?key=my_api_key", options)

Add scope to appscript.json.

"oauthScopes": ["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/script.external_request"]

Then I found logs.list methond is not appropriate for my goal so I need to change to v2.entries method.

function getLogs(){
var options = {
    method: "post",
    contentType: "application/json",
    headers: {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
    payload: JSON.stringify({
      resourceNames: ['projects/XXXXXXX'],
      filter: "timestamp >= searchdate",
      orderBy: "timestamp desc",
      pageSize: 1,
    }),
  }

  var logs = UrlFetchApp.fetch("https://logging.googleapis.com/v2/entries:list?key=my_api_key", options);
  Logger.log(logs);

}


问:
When I am running this query from back end, getting error
```<code>SQL> select
  2  DECODE (TNOT_NOTICE_TYPE,
  3      '1200', 'Duration Challenge ',
  4      '1400', 'Informal Overrun Warning ',
  5      '1500', 'Works Comments ',
  6      '1600', 'Direction on Timing ',
  7      '1601', 'Direction on Placing Apparatus ',
  8      '1602', 'Undue Delay ',
  9      '1611', 'Grant Permit ',
 10      '1613', 'Refuse Permit ',
 11      '2100', 'FPN Notice ',
 12      '2101', 'FPN Withdrawal ',
 13      '2200', 'FPN Comments ',
 14      '2600', 'Inspection ',
 15      '2800', 'Temporary Traffic Signal Application Responses '
 16      ) || 'Received' AS "Subject",
 17  DECODE (TNOT_NOTICE_TYPE,
 18      '1200', 'Duration Challenge - ',
 19      '1400', 'Informal Overrun Warning - ',
 20      '1500', 'Works Comments - ',
 21      '1600', 'Direction on Timing - ',
 22      '1601', 'Direction on Placing Apparatus - ',
 23      '1602', 'Undue Delay - ',
 24      '1611', 'Grant Permit - ',
 25      '1613', 'Refuse Permit - ',
 26      '2100', 'FPN Notice - ',
 27      '2101', 'FPN Withdrawal - ',
 28      '2200', 'FPN Comments - ',
 29      '2600', 'Inspection - ',
 30      '2800', 'Temporary Traffic Signal Application Responses - '
 31      ) || SUBSTR(TNOT_WORKS_REF, 3, 3) AS "Alert Description",
 32  SUBSTR(TNOT_WORKS_REF, 3, 3) AS "District"    ,
 33  TNOT_SENDER_ORG_REF as "Org Ref",
 34  TNOT_SENDER_DIST_REF as "Dist Ref",
 35  TNOT_DATE_MODIFIED as "Date Modified",
 36  TNOT_DATE_MODIFIED as "Date Modified",
 37  TNOT_WORKS_REF as "Works Ref",
 38  TNOT_COMMENTS as "Comments",
 39  TNOT_WORKS_DESCRIPTION AS "Works Description",
 40  TNOT_LOC_DESCRIPTION AS "Location Description",
 41  TNOT_NOTICE_TYPE ,
 42  TNOT_CREATED_DATIM
 43  from TMA_NOTICES
 44  where
 45  TNOT_SENT_RECEIVED = 'R'
 46  AND TNOT_WORKS_REF LIKE 'AY009%'
 47  AND TNOT_NOTICE_TYPE IN ('1200','1400', '1500', '1600', '1601', '1602', '16
11', '1613', '2100', '2101', '2200','2600', '2800')
 48  AND TNOT_CREATED_DATIM BETWEEN '01-OCT-19 00:00:00' and SYSDATE
 49  ORDER BY TNOT_NOTICE_TYPE, TNOT_CREATED_DATIM DESC;
AND TNOT_CREATED_DATIM BETWEEN '01-OCT-19 00:00:00' and SYSDATE
                               *
</code>```

****ERROR at line 48:

ORA-01830: date format picture ends before converting entire input
  string****

SQL>

答:
You are facing the issue when your input string '01-OCT-19 00:00:00' is converted to a date. By default, It uses NLS_DATE_FORMAT of your session to convert the string to date and if provided string and NLS_DATE_FORMAT do not match then this error is thrown.

So better is to convert the string to date using TO_DATE function or DATE literal as follows:

```<code>Replace '01-OCT-19 00:00:00' with -> DATE '2019-10-01'
-- OR --
Replace '01-OCT-19 00:00:00' with -> TO_DATE('01-OCT-19 00:00:00','DD-MON-RR HH24:MI:SS')
</code>```

Cheers!!

Body:
SQL> select
  2  DECODE (TNOT_NOTICE_TYPE,
  3      '1200', 'Duration Challenge ',
  4      '1400', 'Informal Overrun Warning ',
  5      '1500', 'Works Comments ',
  6      '1600', 'Direction on Timing ',
  7      '1601', 'Direction on Placing Apparatus ',
  8      '1602', 'Undue Delay ',
  9      '1611', 'Grant Permit ',
 10      '1613', 'Refuse Permit ',
 11      '2100', 'FPN Notice ',
 12      '2101', 'FPN Withdrawal ',
 13      '2200', 'FPN Comments ',
 14      '2600', 'Inspection ',
 15      '2800', 'Temporary Traffic Signal Application Responses '
 16      ) || 'Received' AS "Subject",
 17  DECODE (TNOT_NOTICE_TYPE,
 18      '1200', 'Duration Challenge - ',
 19      '1400', 'Informal Overrun Warning - ',
 20      '1500', 'Works Comments - ',
 21      '1600', 'Direction on Timing - ',
 22      '1601', 'Direction on Placing Apparatus - ',
 23      '1602', 'Undue Delay - ',
 24      '1611', 'Grant Permit - ',
 25      '1613', 'Refuse Permit - ',
 26      '2100', 'FPN Notice - ',
 27      '2101', 'FPN Withdrawal - ',
 28      '2200', 'FPN Comments - ',
 29      '2600', 'Inspection - ',
 30      '2800', 'Temporary Traffic Signal Application Responses - '
 31      ) || SUBSTR(TNOT_WORKS_REF, 3, 3) AS "Alert Description",
 32  SUBSTR(TNOT_WORKS_REF, 3, 3) AS "District"    ,
 33  TNOT_SENDER_ORG_REF as "Org Ref",
 34  TNOT_SENDER_DIST_REF as "Dist Ref",
 35  TNOT_DATE_MODIFIED as "Date Modified",
 36  TNOT_DATE_MODIFIED as "Date Modified",
 37  TNOT_WORKS_REF as "Works Ref",
 38  TNOT_COMMENTS as "Comments",
 39  TNOT_WORKS_DESCRIPTION AS "Works Description",
 40  TNOT_LOC_DESCRIPTION AS "Location Description",
 41  TNOT_NOTICE_TYPE ,
 42  TNOT_CREATED_DATIM
 43  from TMA_NOTICES
 44  where
 45  TNOT_SENT_RECEIVED = 'R'
 46  AND TNOT_WORKS_REF LIKE 'AY009%'
 47  AND TNOT_NOTICE_TYPE IN ('1200','1400', '1500', '1600', '1601', '1602', '16
11', '1613', '2100', '2101', '2200','2600', '2800')
 48  AND TNOT_CREATED_DATIM BETWEEN '01-OCT-19 00:00:00' and SYSDATE
 49  ORDER BY TNOT_NOTICE_TYPE, TNOT_CREATED_DATIM DESC;
AND TNOT_CREATED_DATIM BETWEEN '01-OCT-19 00:00:00' and SYSDATE
                               *

****ERROR at line 48:

ORA-01830: date format picture ends before converting entire input
  string****

SQL>

Body:
You are facing the issue when your input string '01-OCT-19 00:00:00' is converted to a date. By default, It uses NLS_DATE_FORMAT of your session to convert the string to date and if provided string and NLS_DATE_FORMAT do not match then this error is thrown.

So better is to convert the string to date using TO_DATE function or DATE literal as follows:

Replace '01-OCT-19 00:00:00' with -> DATE '2019-10-01'
-- OR --
Replace '01-OCT-19 00:00:00' with -> TO_DATE('01-OCT-19 00:00:00','DD-MON-RR HH24:MI:SS')

Cheers!!


问:
Overlapping R ggplots with two different y axis (different time period) and x axis (different scale)
I currently have two different data sets, with two columns each (date and value). Basically, these two data sets differ in that they occur in different time periods (y axis), I would say roughly twenty years apart and as for the x axis (value) the ratio is about 1:10. The aim here is that since they occur in different time periods, is there a way for me to overlay these two plots using ggplot and have the two different y axes (different time periods) placed one above and the other below i.e. to say one of the dataset is from 1994-2002 and second dataset is 2017-2020. Reason is because they both exhibit the same pattern and i would like them to be placed together to exhibit the pattern clearly.
Example of such a chart is as attached.

答:
It's very doable. For ggplot2, you can easily add a secondary axis, with a simple transform. I'll use the EuStockMarkets data as an example.

```<code>library(ggplot2)
library(dplyr)
library(tidyr)

rm(list=ls())
data(EuStockMarkets)
StockMarkets <- EuStockMarkets[, c("DAX","FTSE")]

plot(StockMarkets, plot.type="single", col=c(2,3),
     main="European Stock Markets (1991 - 1998)",
     ylab="Closing price (value)")
legend("topleft", inset=0.02,  legend=colnames(StockMarkets),
         lwd=2, lty=1, col=c(2,3))
</code>```

You'll get a nice plot like this:

The ggplot2 version is also quite simple:

```<code>StockMarkets %>%
  as.data.frame() %>%
  mutate(sDate=as.Date(seq(1,1860,1), origin="1991-05-10")) %>%
  pivot_longer(-sDate) %>%
  ggplot(aes(x=sDate, y=value, color=name)) +
  geom_line()
</code>```

Now suppose FTSE is 20 years ago. I will change the date manually, so you can see the results.

```<code>DAX <- tibble(Stock=as.vector(EuStockMarkets[,c("DAX")])) %>%
   mutate(stDate=as.Date(seq(1,1860,1), origin="1991-05-10"), name="DAX")

FTSE <- tibble(Stock=as.vector(EuStockMarkets[,c("FTSE")])) %>%
  mutate(stDate=as.Date(seq(1,1860,1), origin="1971-05-10"), name="FTSE")
</code>```

Now combine them into one data frame. Imagine you start with this data. And imagine it has NASDAQ and Bitcoin instead of FTSE and DAX.

```<code>DAX_FTSE <- bind_rows(DAX, FTSE)
</code>```

If you try to plot this data, you get the following, which is correct, but not what the OP wanted:

```<code>DAX_FTSE %>%
  ggplot(aes(x=stDate, y=Stock, color=name)) +
  geom_line()
</code>```

The trick here is to add a secondary axis with a simple transform:

```<code>DAX_FTSE %>%
  mutate(st2Date=if_else(name=="FTSE", stDate+20*365.25, stDate)) %>%
  ggplot(aes(x=st2Date, y=Stock, color=name)) +
  geom_line() + xlab(label="DAX") +
  scale_x_date("DAX", sec.axis=sec_axis(~ . -20*365.25, name="FTSE"))
</code>```

Body:
It's very doable. For ggplot2, you can easily add a secondary axis, with a simple transform. I'll use the EuStockMarkets data as an example.

library(ggplot2)
library(dplyr)
library(tidyr)

rm(list=ls())
data(EuStockMarkets)
StockMarkets <- EuStockMarkets[, c("DAX","FTSE")]

plot(StockMarkets, plot.type="single", col=c(2,3),
     main="European Stock Markets (1991 - 1998)",
     ylab="Closing price (value)")
legend("topleft", inset=0.02,  legend=colnames(StockMarkets),
         lwd=2, lty=1, col=c(2,3))

You'll get a nice plot like this:

The ggplot2 version is also quite simple:

StockMarkets %>%
  as.data.frame() %>%
  mutate(sDate=as.Date(seq(1,1860,1), origin="1991-05-10")) %>%
  pivot_longer(-sDate) %>%
  ggplot(aes(x=sDate, y=value, color=name)) +
  geom_line()

Now suppose FTSE is 20 years ago. I will change the date manually, so you can see the results.

DAX <- tibble(Stock=as.vector(EuStockMarkets[,c("DAX")])) %>%
   mutate(stDate=as.Date(seq(1,1860,1), origin="1991-05-10"), name="DAX")

FTSE <- tibble(Stock=as.vector(EuStockMarkets[,c("FTSE")])) %>%
  mutate(stDate=as.Date(seq(1,1860,1), origin="1971-05-10"), name="FTSE")

Now combine them into one data frame. Imagine you start with this data. And imagine it has NASDAQ and Bitcoin instead of FTSE and DAX.

DAX_FTSE <- bind_rows(DAX, FTSE)

If you try to plot this data, you get the following, which is correct, but not what the OP wanted:

DAX_FTSE %>%
  ggplot(aes(x=stDate, y=Stock, color=name)) +
  geom_line()

The trick here is to add a secondary axis with a simple transform:

DAX_FTSE %>%
  mutate(st2Date=if_else(name=="FTSE", stDate+20*365.25, stDate)) %>%
  ggplot(aes(x=st2Date, y=Stock, color=name)) +
  geom_line() + xlab(label="DAX") +
  scale_x_date("DAX", sec.axis=sec_axis(~ . -20*365.25, name="FTSE"))


问:
Writing to socket fails after X bytes
I'm attempting to write song data to a socket however after approximately 66338 bytes the following exception is thrown:

```<code>    E/        ( 1016): Connection reset by peer
    E/        ( 1016): java.net.SocketException: Connection reset by peer
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.writeSocketImpl(Native Method)
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.write(OSNetworkSystem.java:723)
    E/        ( 1016):  at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:578)
    E/        ( 1016):  at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
    E/        ( 1016):  at com.myprogram.StreamProxy.processRequest(StreamProxy.java:307)
    E/        ( 1016):  at com.myprogram.StreamProxy.run(StreamProxy.java:145)
    E/        ( 1016):  at java.lang.Thread.run(Thread.java:1096)
</code>```

This only happens with certain songs and if one song does it all of the songs in the entire album do the same thing.  I'm wondering if it has something to do with the header information for the song?

Any suggestions on how to debug or fix this would be greatly appreciated.  Thanks.

EDIT:  Here's the code that is reading from an InputStream and writing back out to a socket.  The code is pretty straight forward so I'm not really sure why it would be crashing unless the connection is being closed on the receiving end.  (Note: this is only psuedocode, but gives the general idea)

```<code>    InputStream data = realResponse.getEntity().getContent();
    Socket socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
    socket.setSoTimeout(5000);
    port = socket.getLocalPort();
    Socket client = socket.accept();

    ...some code...

    byte[] buff = new byte[1024 * 50];
    while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
      client.getOutputStream().write(buff, 0, readBytes);
    }
</code>```

Also, could this have anything to do with the socket buffer filling up? Especially since it seems to crash at 64k every time.

答:
Most probably the bug is in your code. If you could attach the code it will be helpful to narrow down the error. If you feel it has something to do with header use wireshark to see when that happens.

EDIT: I feel it has something to do with setSoTimeout(milliseconds) this will timeout after 5 seconds of inactivity as you have written in the code. This i guess should be the reason for the following statement of yours "if one song does it all of the songs in the entire album do the same thing".

Try increasing the timeout value.

Title: Writing to socket fails after X bytes

Body:
I'm attempting to write song data to a socket however after approximately 66338 bytes the following exception is thrown:

    E/        ( 1016): Connection reset by peer
    E/        ( 1016): java.net.SocketException: Connection reset by peer
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.writeSocketImpl(Native Method)
    E/        ( 1016):  at org.apache.harmony.luni.platform.OSNetworkSystem.write(OSNetworkSystem.java:723)
    E/        ( 1016):  at org.apache.harmony.luni.net.PlainSocketImpl.write(PlainSocketImpl.java:578)
    E/        ( 1016):  at org.apache.harmony.luni.net.SocketOutputStream.write(SocketOutputStream.java:59)
    E/        ( 1016):  at com.myprogram.StreamProxy.processRequest(StreamProxy.java:307)
    E/        ( 1016):  at com.myprogram.StreamProxy.run(StreamProxy.java:145)
    E/        ( 1016):  at java.lang.Thread.run(Thread.java:1096)

This only happens with certain songs and if one song does it all of the songs in the entire album do the same thing.  I'm wondering if it has something to do with the header information for the song?

Any suggestions on how to debug or fix this would be greatly appreciated.  Thanks.

EDIT:  Here's the code that is reading from an InputStream and writing back out to a socket.  The code is pretty straight forward so I'm not really sure why it would be crashing unless the connection is being closed on the receiving end.  (Note: this is only psuedocode, but gives the general idea)

    InputStream data = realResponse.getEntity().getContent();
    Socket socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
    socket.setSoTimeout(5000);
    port = socket.getLocalPort();
    Socket client = socket.accept();

    ...some code...

    byte[] buff = new byte[1024 * 50];
    while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
      client.getOutputStream().write(buff, 0, readBytes);
    }

Also, could this have anything to do with the socket buffer filling up? Especially since it seems to crash at 64k every time.


问:
Expand Searchbar with Search icon as well as show close icon onclick using Javascript
I am trying to open the expanded search bar with a search icon as well as a close icon on click using javascript. Here I am attaching my code. Your help will be appreciated in advance. I am also attaching the image so it can be understood very well. My code is on hover but I want to make it on click.

//Search Bar
        var searchBar = document.getElementById("express-form-typeahead");
        searchBar.addEventListener('click' , function(){
            var closeSearch = document.getElementById("closeSearch");
            closeSearch.style.display = "block";
        });
        window.addEventListener('mouseup', e =>{
            //alert(e);
                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    var closeSearch = document.getElementById("closeSearch");
                    closeSearch.style.display = "";
                }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.custom-search{position: relative;right:-12px;}
    #express-form-typeahead{background-color:transparent;background-image:url('../images/search.svg');background-position:5px center;background-repeat:no-repeat;background-size:15px;border:none;cursor:pointer;height:30px;padding:0 0 0 34px;position:relative;-webkit-transition:width 1.1s ease, background 1.1s ease;transition:width 1.1s ease, background 1.1s ease;width:0;}
    .close-search{display:none;-webkit-animation: fadeEffect1 2s;animation: fadeEffect1 2s;
    position: absolute;top:9px;right:9px;background-image: url('../images/close-icon-grey.png');width: 15px;
    height: 15px;background-repeat: no-repeat;background-size: 15px;}
    #express-form-typeahead:focus{background-color:#fff;border-bottom:1px solid #e7e7e7;cursor:text;outline:0;width:200px;border-radius: 0;}
    .search-btn{display:none;}
    input[type="search"]{-webkit-appearance:textfield;}
   /* Fade in tabs */
    @-webkit-keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }</code>```

                                <input required="" name="q" placeholder="Blue Book" class="form-control" id="express-form-typeahead"  type="search">
                                <button class="search-btn" type="submit"></button>

```

答:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("searchBox").addEventListener("click", function(event) {
    arr = this.className.split(" ");
    if (arr.indexOf("active") == -1) {
      this.className += " active";
    }
    this.getElementsByTagName("INPUT")[0].focus();
  });

  document.getElementById("searchBox").getElementsByClassName("search")[0].addEventListener("click", function(event) {
    var parent = this.parentElement; //searchBox element;
    var arr = parent.className.split(" ");
    if (arr.indexOf("active") != -1) {
      var input = parent.getElementsByTagName("INPUT")[0];
      input.value = "";
      var classList = parent.className;
      classList = classList.replace(/\bactive\b/g, "").trim();
      parent.className = classList;
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
    }
  });
}, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.search-container {
  position: absolute;
  top: 25px;
  right: 25px;
  display: inline-block;
}

.search-container .search {
  transition: all 1s;
  z-index: 4;
  position: relative;
  display: inline-block;
  height: 50px;
  width: 50px;
  vertical-align: middle;
  right: -55px;
}

.search-container .search:hover {
  cursor: pointer;
}

.search-container .search::before {
  content: "";
  position: absolute;
  top: 36px;
  right: 0;
  bottom: 0;
  left: 28px;
  width: 12px;
  height: 2px;
  background: #ccc;
  transform: rotate(45deg);
  transition: all .5s;
}

.search-container .search::after {
  content: "";
  position: absolute;
  top: 8px;
  right: 0;
  bottom: 0;
  left: 8px;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  border: 2px solid #ccc;
  transition: all .5s;
}

.search-container input {
  width: 50px;
  height: 50px;
  outline: none;
  border-bottom: 1px solid #ccc;
  color: #ccc;
  padding: 0;
  border-top: 0;
  border-right: 0;
  border-left: 0;
  transition: all 1s;
  opacity: 0;
  z-index: 5;
  font-weight: bolder;
  letter-spacing: 0.1em;
  box-sizing: border-box;
}

.search-container input:hover {
  cursor: pointer;
}

.search-container.active input {
  width: 300px;
  opacity: 1;
  cursor: text;
  padding: 0 0 0 50px;
}

.search-container .close {
  transition: all 1s;
  z-index: 4;
  position: relative;
  display: inline-block;
  height: 50px;
  width: 50px;
  vertical-align: middle;
  right: 55px;
  visibility: hidden;
}

.search-container.active input~.close {
  right: 55px;
  z-index: 6;
  visibility: visible;
}

.search-container.active input~.close::before {
  content: "";
  top: 25px;
  left: 15px;
  width: 20px;
  position: absolute;
  height: 2px;
  background: #ccc;
  transform: rotate(45deg);
  transition: all .5s;
}

.search-container.active input~.close::after {
  content: "";
  top: 25px;
  left: 15px;
  width: 20px;
  height: 2px;
  background: #ccc;
  transform: rotate(-45deg);
  position: absolute;
  transition: all .5s;
}

.search-container input::placeholder {
  color: #898989;
  opacity: 0.5;
  font-weight: bolder;
}

.search-container .input-box {
  vertical-align: middle;
  display: inline-block;
}</code>```

    <input type="text" placeholder="Search...">

```

Body:
I am trying to open the expanded search bar with a search icon as well as a close icon on click using javascript. Here I am attaching my code. Your help will be appreciated in advance. I am also attaching the image so it can be understood very well. My code is on hover but I want to make it on click.

//Search Bar
        var searchBar = document.getElementById("express-form-typeahead");
        searchBar.addEventListener('click' , function(){
            var closeSearch = document.getElementById("closeSearch");
            closeSearch.style.display = "block";
        });
        window.addEventListener('mouseup', e =>{
            //alert(e);
                if(e.target != searchBar && e.target.parentNode != searchBar )
                {
                    var closeSearch = document.getElementById("closeSearch");
                    closeSearch.style.display = "";
                }
        });

.custom-search{position: relative;right:-12px;}
    #express-form-typeahead{background-color:transparent;background-image:url('../images/search.svg');background-position:5px center;background-repeat:no-repeat;background-size:15px;border:none;cursor:pointer;height:30px;padding:0 0 0 34px;position:relative;-webkit-transition:width 1.1s ease, background 1.1s ease;transition:width 1.1s ease, background 1.1s ease;width:0;}
    .close-search{display:none;-webkit-animation: fadeEffect1 2s;animation: fadeEffect1 2s;
    position: absolute;top:9px;right:9px;background-image: url('../images/close-icon-grey.png');width: 15px;
    height: 15px;background-repeat: no-repeat;background-size: 15px;}
    #express-form-typeahead:focus{background-color:#fff;border-bottom:1px solid #e7e7e7;cursor:text;outline:0;width:200px;border-radius: 0;}
    .search-btn{display:none;}
    input[type="search"]{-webkit-appearance:textfield;}
   /* Fade in tabs */
    @-webkit-keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }
    @keyframes fadeEffect1 {
        from {opacity: 0;}
        to {opacity: 1;}
    }

                                <input required="" name="q" placeholder="Blue Book" class="form-control" id="express-form-typeahead"  type="search">
                                <button class="search-btn" type="submit"></button>

Body:
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById("searchBox").addEventListener("click", function(event) {
    arr = this.className.split(" ");
    if (arr.indexOf("active") == -1) {
      this.className += " active";
    }
    this.getElementsByTagName("INPUT")[0].focus();
  });

  document.getElementById("searchBox").getElementsByClassName("search")[0].addEventListener("click", function(event) {
    var parent = this.parentElement; //searchBox element;
    var arr = parent.className.split(" ");
    if (arr.indexOf("active") != -1) {
      var input = parent.getElementsByTagName("INPUT")[0];
      input.value = "";
      var classList = parent.className;
      classList = classList.replace(/\bactive\b/g, "").trim();
      parent.className = classList;
      event.preventDefault();
      event.stopPropagation();
      event.stopImmediatePropagation();
    }
  });
}, false);

.search-container {
  position: absolute;
  top: 25px;
  right: 25px;
  display: inline-block;
}

.search-container .search {
  transition: all 1s;
  z-index: 4;
  position: relative;
  display: inline-block;
  height: 50px;
  width: 50px;
  vertical-align: middle;
  right: -55px;
}

.search-container .search:hover {
  cursor: pointer;
}

.search-container .search::before {
  content: "";
  position: absolute;
  top: 36px;
  right: 0;
  bottom: 0;
  left: 28px;
  width: 12px;
  height: 2px;
  background: #ccc;
  transform: rotate(45deg);
  transition: all .5s;
}

.search-container .search::after {
  content: "";
  position: absolute;
  top: 8px;
  right: 0;
  bottom: 0;
  left: 8px;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  border: 2px solid #ccc;
  transition: all .5s;
}

.search-container input {
  width: 50px;
  height: 50px;
  outline: none;
  border-bottom: 1px solid #ccc;
  color: #ccc;
  padding: 0;
  border-top: 0;
  border-right: 0;
  border-left: 0;
  transition: all 1s;
  opacity: 0;
  z-index: 5;
  font-weight: bolder;
  letter-spacing: 0.1em;
  box-sizing: border-box;
}

.search-container input:hover {
  cursor: pointer;
}

.search-container.active input {
  width: 300px;
  opacity: 1;
  cursor: text;
  padding: 0 0 0 50px;
}

.search-container .close {
  transition: all 1s;
  z-index: 4;
  position: relative;
  display: inline-block;
  height: 50px;
  width: 50px;
  vertical-align: middle;
  right: 55px;
  visibility: hidden;
}

.search-container.active input~.close {
  right: 55px;
  z-index: 6;
  visibility: visible;
}

.search-container.active input~.close::before {
  content: "";
  top: 25px;
  left: 15px;
  width: 20px;
  position: absolute;
  height: 2px;
  background: #ccc;
  transform: rotate(45deg);
  transition: all .5s;
}

.search-container.active input~.close::after {
  content: "";
  top: 25px;
  left: 15px;
  width: 20px;
  height: 2px;
  background: #ccc;
  transform: rotate(-45deg);
  position: absolute;
  transition: all .5s;
}

.search-container input::placeholder {
  color: #898989;
  opacity: 0.5;
  font-weight: bolder;
}

.search-container .input-box {
  vertical-align: middle;
  display: inline-block;
}

<div id="searchBox" class="search-container">
  <div class="search"></div>
  <div class="input-box">
    <input type="text" placeholder="Search...">
    <div class="close"></div>
  </div>
</div>


问:
Reading a TensorArray in Tensorflow always returns zeroes
I am using Tensorflow v1.15. I have a very basic implementation of the TensorArray given in the following example:

import tensorflow as tf

an_array = tf.TensorArray(dtype=tf.float32, size=5, dynamic_size=True, clear_after_read=False, element_shape=(16, 7, 2))
for i in range(5):
    val = tf.random.normal(shape=(16, 7, 2))
    an_array.write(i, val)
    print(tf.Session().run(val))
tensors = [an_array.read(j) for j in range(5)]
print(tf.Session().run(tensors))
```

The print in the for loop does not print all zeros, while the last print statement does. Why is this happening? Thanks.

答:
tf.TensorArray.write returns a new tf.TensorArray  where the writing operation has taken place. In general, the output of this function should replace the previous reference to the array:

import tensorflow as tf

an_array = tf.TensorArray(dtype=tf.float32, size=5, dynamic_size=True,
                          clear_after_read=False, element_shape=(16, 7, 2))
for i in range(5):
    val = tf.random.normal(shape=(16, 7, 2))
    # Replace tensor array reference with the written one
    an_array = an_array.write(i, val)
    print(tf.Session().run(val))
tensors = [an_array.read(j) for j in range(5)]
print(tf.Session().run(tensors))
```

Body:
I am using Tensorflow v1.15. I have a very basic implementation of the TensorArray given in the following example:

import tensorflow as tf

an_array = tf.TensorArray(dtype=tf.float32, size=5, dynamic_size=True, clear_after_read=False, element_shape=(16, 7, 2))
for i in range(5):
    val = tf.random.normal(shape=(16, 7, 2))
    an_array.write(i, val)
    print(tf.Session().run(val))
tensors = [an_array.read(j) for j in range(5)]
print(tf.Session().run(tensors))

The print in the for loop does not print all zeros, while the last print statement does. Why is this happening? Thanks.


问:
angular convert number to persian
I want to convert English numbers to Persian number in angular 4:

```<code>persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
price="1000$";
price= this.fixnumber(price,this.persianNumbers,this.englishNumbers);

fixnumber(src,persian,english){
   for(var i=0; i<10; i++)
      {
        var str = /english[i]/gi;
        src = src.replace(str, persian[i]);
      }
    return src;
}
</code>```

It doesn't work.

答:
You can use this function :

function ConvertToPr(str) {
    return str.replace(/0/g,'٠').replace(/1/g,'١').replace(/2/g,'٢').replace(/3/g,'٣').replace(/4/g,'٤')
        .replace(/5/g,'٥').replace(/6/g,'٦').replace(/7/g,'٧').replace(/8/g,'٨').replace(/9/g,'٩')
        .replace(/۰/g,'٠').replace(/۱/g,'١').replace(/۲/g,'٢').replace(/۳/g,'٣').replace(/۴/g,'٤')
        .replace(/۵/g,'٥').replace(/۶/g,'٦').replace(/۷/g,'٧').replace(/۸/g,'٨').replace(/۹/g,'٩');
}

console.log(ConvertToPr("1000$")) //print ١٠٠٠$```

Title: angular convert number to persian

Body:
I want to convert English numbers to Persian number in angular 4:

persianNumbers = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
englishNumbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
price="1000$";
price= this.fixnumber(price,this.persianNumbers,this.englishNumbers);

fixnumber(src,persian,english){
   for(var i=0; i<10; i++)
      {
        var str = /english[i]/gi;
        src = src.replace(str, persian[i]);
      }
    return src;
}

It doesn't work.


问:
Interacting with Metamask web3.js
I am facing a problem when I am creating a contract on my local ethereum blockchain. I have a basic contract to register a doc on blockchain.

So, when a run my contract in truffle console I can call all my functions perfectly, but, when I create a webpage with a front end interface, I can't open metamask to pay a fee.
My contract has basicly 2 functions: addDoc and FindDoc. I did a test creating a transaction using remix website and it worked normal. At my page, I still can call a findDoc and get answer with the correct informations, but when I try creating a transaction and pay a fee, the metamask doesn't show me.

My project is just 4 files:

index.html

app.js

notaryWebApp.js

sha256

The codes can be found here: https://github.com/ffelipesimoes/solidity/tree/master/webapp

The main interact with blockchain is notaryWebApp.js file:

```<code>var contract = undefined;
var customProvider = undefined;
var address = "0x6A4494ed32ce0Ab8004fbEAdac534916f88C8d3E";
var abi = undefined;

function notary_init() {
    // Check if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
        // Use existing gateway
        window.web3 = new Web3(web3.currentProvider);
    } else {
        alert("No Ethereum interface injected into browser. Read-only access");
    }
    //contract abi
    abi = [...]
    contract = new web3.eth.Contract(abi, address);
};

//sends a hash to the blockchain
function notary_send(hash, callback) {
    web3.eth.getAccounts(function (error, accounts) {
        contract.methods.addDocHash(hash).send({
            from: accounts[0]
        }, function (error, tx) {
            if (error) callback(error, null);
            else callback(null, tx);
        });
    });
};

//looks up a hash on the blockchain
function notary_find(hash, callback) {
    contract.methods.findDocHash(hash).call(function (error, result) {
        if (error) callback(error, null);
        else {
            let resultObj = {
                mineTime: new Date(result[0] * 1000),
                blockNumber: result[1]
            }
            callback(null, resultObj);
        }
    });
};
</code>```

since now, thank you all!

答: Prefer using direct connection interface and predesigned scripts to solve this problem. You could find a package named Blockchain itself in pypi this could solve your problems and make sure that you are on the right folder ad=nd address</p>

Title: Interacting with Metamask web3.js

Body:
I am facing a problem when I am creating a contract on my local ethereum blockchain. I have a basic contract to register a doc on blockchain.

So, when a run my contract in truffle console I can call all my functions perfectly, but, when I create a webpage with a front end interface, I can't open metamask to pay a fee.
My contract has basicly 2 functions: addDoc and FindDoc. I did a test creating a transaction using remix website and it worked normal. At my page, I still can call a findDoc and get answer with the correct informations, but when I try creating a transaction and pay a fee, the metamask doesn't show me.

My project is just 4 files:

index.html

app.js

notaryWebApp.js

sha256

The codes can be found here: https://github.com/ffelipesimoes/solidity/tree/master/webapp

The main interact with blockchain is notaryWebApp.js file:

var contract = undefined;
var customProvider = undefined;
var address = "0x6A4494ed32ce0Ab8004fbEAdac534916f88C8d3E";
var abi = undefined;

function notary_init() {
    // Check if Web3 has been injected by the browser (Mist/MetaMask)
    if (typeof web3 !== 'undefined') {
        // Use existing gateway
        window.web3 = new Web3(web3.currentProvider);
    } else {
        alert("No Ethereum interface injected into browser. Read-only access");
    }
    //contract abi
    abi = [...]
    contract = new web3.eth.Contract(abi, address);
};

//sends a hash to the blockchain
function notary_send(hash, callback) {
    web3.eth.getAccounts(function (error, accounts) {
        contract.methods.addDocHash(hash).send({
            from: accounts[0]
        }, function (error, tx) {
            if (error) callback(error, null);
            else callback(null, tx);
        });
    });
};

//looks up a hash on the blockchain
function notary_find(hash, callback) {
    contract.methods.findDocHash(hash).call(function (error, result) {
        if (error) callback(error, null);
        else {
            let resultObj = {
                mineTime: new Date(result[0] * 1000),
                blockNumber: result[1]
            }
            callback(null, resultObj);
        }
    });
};

since now, thank you all!


问:
Is my for loop not looping though all data?
I am trying to populate database using for loop. While submitting the form I am getting the following data:

```<code>"name" => "This is a product title"
  "slug" => "this-is-a-product-title"
  "category_id" => "1"
  "brand_id" => "1"
  "description" => "<p>This is a product description</p>"
  "video" => "https://www.youtube.com/watch?v=kY1F_Y0GniQ"
  "imageColor" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "image" => array:2 [▼
    0 => "["http://ecom.local/uploads/product-1.jpg","http://ecom.local/uploads/product-2.jpg"]"
    1 => "["http://ecom.local/uploads/product-4.jpg","http://ecom.local/uploads/product-3.jpg"]"
  ]
  "color" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "size" => array:2 [▼
    0 => "11"
    1 => "9"
  ]
  "stock" => "2"
  "price" => array:2 [▼
    0 => "4000"
    1 => "3000"
  ]
  "discount" => array:2 [▼
    0 => "0"
    1 => "0"
  ]
  "status" => "active"
</code>```

In order to populate data I have written the following code:

```<code>public function store(Request $request)
{
    $rules = $this->product->getRules();
    $request->validate($rules);
    $data = $request->all();
    $data['name'] = $request->name;
    $data['slug'] = $request->slug;
    $data['category_id'] = $request->category_id;
    $data['brand_id'] = $request->brand_id;
    $data['video'] = $request->video;
    $data['status'] = $request->status;
    $this->product->fill($data);
    $status = $this->product->save();
    $product_id = $this->product->id;
    if($status){
        if(!empty($request->image)){
            for($i = 0; $i < count($request->image);){
                    $images = $request->image[$i];
                    $images = str_replace('"', '', $images);
                    $images = str_replace(array('[',']'),'',$images);
                    $images = explode(',', $images);
                for($j = 0; $j < count($images[$i]);){
                    $image_data['product_id'] = $product_id;
                    $image_data['color_id'] = $request->imageColor[$i];
                    $image_data['image'] = $images[$j];
                    $this->product_image->fill($image_data);
                    $this->product_image->save();
                    $j++;
                }
                $i++;
            }
        }
        if(!empty($request->size)){
            for($i = 0; $i < count($request->size); $i++){
                $size_data['product_id'] = $product_id;
                $size_data['size_id'] = $request->size[$i];
                $this->product_size->fill($size_data);
                $this->product_size->save();
            }
        }
        $request->session()->flash('success','Product created successfully.');
    } else {
        $request->session()->flash('error','Problem while adding product.');
    }
    return redirect()->route('products.index');
}
</code>```

But, every time I insert a product I only get single row being populated in product_images and product_sizes table. Is my for loop not working or there is a bug in my code?
For now I am getting this result with my code:

My expected answer would look like the following in product images tabel

答:
You have to create new Images like this example below:

```<code>[...]
$product_image = new Image;
$image_data['product_id'] = $product_id;
$image_data['color_id'] = $request->imageColor[$i];
$image_data['image'] = $images[$j];
$product_image->fill($image_data);
$product_image->product_id = $this->id;
$product_image->save();
[...]
</code>```

Otherwise it will only create a single one.

I think the for loop is wrong too:

```<code>for($j = 0; $j < count($images[$i]);){
</code>```

change it into:

```<code>for($j = 0; $j < count($images);){
</code>```

Body:
I am trying to populate database using for loop. While submitting the form I am getting the following data:

"name" => "This is a product title"
  "slug" => "this-is-a-product-title"
  "category_id" => "1"
  "brand_id" => "1"
  "description" => "
This is a product description
"
  "video" => "https://www.youtube.com/watch?v=kY1F_Y0GniQ"
  "imageColor" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "image" => array:2 [▼
    0 => "["http://ecom.local/uploads/product-1.jpg","http://ecom.local/uploads/product-2.jpg"]"
    1 => "["http://ecom.local/uploads/product-4.jpg","http://ecom.local/uploads/product-3.jpg"]"
  ]
  "color" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "size" => array:2 [▼
    0 => "11"
    1 => "9"
  ]
  "stock" => "2"
  "price" => array:2 [▼
    0 => "4000"
    1 => "3000"
  ]
  "discount" => array:2 [▼
    0 => "0"
    1 => "0"
  ]
  "status" => "active"

In order to populate data I have written the following code:

public function store(Request $request)
{
    $rules = $this->product->getRules();
    $request->validate($rules);
    $data = $request->all();
    $data['name'] = $request->name;
    $data['slug'] = $request->slug;
    $data['category_id'] = $request->category_id;
    $data['brand_id'] = $request->brand_id;
    $data['video'] = $request->video;
    $data['status'] = $request->status;
    $this->product->fill($data);
    $status = $this->product->save();
    $product_id = $this->product->id;
    if($status){
        if(!empty($request->image)){
            for($i = 0; $i < count($request->image);){
                    $images = $request->image[$i];
                    $images = str_replace('"', '', $images);
                    $images = str_replace(array('[',']'),'',$images);
                    $images = explode(',', $images);
                for($j = 0; $j < count($images[$i]);){
                    $image_data['product_id'] = $product_id;
                    $image_data['color_id'] = $request->imageColor[$i];
                    $image_data['image'] = $images[$j];
                    $this->product_image->fill($image_data);
                    $this->product_image->save();
                    $j++;
                }
                $i++;
            }
        }
        if(!empty($request->size)){
            for($i = 0; $i < count($request->size); $i++){
                $size_data['product_id'] = $product_id;
                $size_data['size_id'] = $request->size[$i];
                $this->product_size->fill($size_data);
                $this->product_size->save();
            }
        }
        $request->session()->flash('success','Product created successfully.');
    } else {
        $request->session()->flash('error','Problem while adding product.');
    }
    return redirect()->route('products.index');
}

But, every time I insert a product I only get single row being populated in product_images and product_sizes table. Is my for loop not working or there is a bug in my code?
For now I am getting this result with my code:

My expected answer would look like the following in product images tabel

Body:
You have to create new Images like this example below:

[...]
$product_image = new Image;
$image_data['product_id'] = $product_id;
$image_data['color_id'] = $request->imageColor[$i];
$image_data['image'] = $images[$j];
$product_image->fill($image_data);
$product_image->product_id = $this->id;
$product_image->save();
[...]

Otherwise it will only create a single one.

I think the for loop is wrong too:

for($j = 0; $j < count($images[$i]);){

change it into:

for($j = 0; $j < count($images);){


问:
Split the string '1/10/2/20/3/30/4/40' into two columns check body for more details
```<code>string = '1/10/2/20/3/30/4/40'
output = col1  |   col2
           1   |    10
           2   |    20
           3   |    30
           4   |    40
</code>```

I tried below code:

```<code>DECLARE @TEXT VARCHAR(60) = '1/10/2/20/3/30/4/40', @POSITION INT=1
CREATE TABLE #TEMP(VAL1 INT,VAL2 INT)
WHILE (LEN(@TEXT) >= @POSITION)
BEGIN
  INSERT INTO #TEMP VALUES(SUBSTRING(@TEXT,@POSITION,1),SUBSTRING(@TEXT,@POSITION+2,2))
  SET @POSITION = @POSITION+5
END

SELECT * FROM #TEMP
</code>```

this is giving the output but this is more like hard coded.

答:
I tried by creating temporory tables. And adding single digit into one temp table, and non-single digit into another temp table. And putting values of both table into another temp table.

Code:

     Note: @series is string I passed.

```<code>select value into #value from string_split(@series,'/')

create table #position(var int identity(1,1),var1 int)

insert into #position(var1)
select value from #value    where value like '_'

create table #position2(var int,var2 int)

insert into #position2(var2)
select value from #value where value not like '_'

create table #final(var1 int,var2 int)

insert into #final(var1,var2)
select p1.var1,p2.var2 from #position p1
      join #position2 p2 on p1.var=p2.var

select * from #final
</code>```

Body:
string = '1/10/2/20/3/30/4/40'
output = col1  |   col2
           1   |    10
           2   |    20
           3   |    30
           4   |    40

I tried below code:

DECLARE @TEXT VARCHAR(60) = '1/10/2/20/3/30/4/40', @POSITION INT=1
CREATE TABLE #TEMP(VAL1 INT,VAL2 INT)
WHILE (LEN(@TEXT) >= @POSITION)
BEGIN
  INSERT INTO #TEMP VALUES(SUBSTRING(@TEXT,@POSITION,1),SUBSTRING(@TEXT,@POSITION+2,2))
  SET @POSITION = @POSITION+5
END

SELECT * FROM #TEMP

this is giving the output but this is more like hard coded.

Body:
I tried by creating temporory tables. And adding single digit into one temp table, and non-single digit into another temp table. And putting values of both table into another temp table.

Code:

     Note: @series is string I passed.

select value into #value from string_split(@series,'/')

create table #position(var int identity(1,1),var1 int)

insert into #position(var1)
select value from #value    where value like '_'

create table #position2(var int,var2 int)

insert into #position2(var2)
select value from #value where value not like '_'

create table #final(var1 int,var2 int)

insert into #final(var1,var2)
select p1.var1,p2.var2 from #position p1
      join #position2 p2 on p1.var=p2.var

select * from #final


问:
Switch case statements causes fatal error in my Android App
I am building an Android app using a pile of switch statements to switch between views. Everything was going fine until I added a block of cases that cause a fatal error when the app is starting up. The cases are called by onClick statements in the XML. The offending block of cases is actually part of a block of statements that work fine. Can anyone see what I'm missing? What's causing the fatal error? I'm including snippets of the broken code and working code along with the logCat file.

```<code>05-17 01:48:01.931: INFO/System.out(270): debugger has settled (1381)
05-17 01:48:02.341: WARN/dalvikvm(270): VFY: invalid switch target 7170 (-> 0x1c0b) at 0x9[0]
05-17 01:48:02.351: WARN/dalvikvm(270): VFY:  rejected Lcom/findthway/main;.nextLayout (Landroid/view/View;)V
05-17 01:48:02.351: WARN/dalvikvm(270): Verifier rejected class Lcom/findthway/main;
05-17 01:48:02.351: WARN/dalvikvm(270): Class init failed in newInstance call (Lcom/findthway/main;)
05-17 01:48:03.031: INFO/ActivityManager(67): Displayed activity com.android.launcher/com.android.launcher2.Launcher: 50893 ms (total 50893 ms)
05-17 01:48:08.001: WARN/ActivityManager(67): Launch timeout has expired, giving up wake lock!
05-17 01:48:08.751: WARN/ActivityManager(67): Activity idle timeout for HistoryRecord{43eda500 com.findthway/.main}
05-17 01:52:41.531: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 01:57:41.551: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:02:41.576: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:07:41.641: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:08:45.831: DEBUG/dalvikvm(67): GC_FOR_MALLOC freed 15592 objects / 665856 bytes in 160ms
05-17 02:12:41.695: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:16:30.392: DEBUG/dalvikvm(67): GC_FOR_MALLOC freed 4697 objects / 200928 bytes in 108ms
05-17 02:17:41.716: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:22:41.745: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:27:41.801: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:32:41.812: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:37:41.851: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:41:00.341: DEBUG/dalvikvm(67): GC_FOR_MALLOC freed 12690 objects / 520224 bytes in 235ms
</code>```

Example of the XML that would be calling the broken switch cases:

```<code><RelativeLayout android:id="@+id/level07_layout00"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/vlayoutup"
android:visibility="gone">
    <ImageButton android:id="@+id/level07_closeButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/close"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="10dp"
    android:layout_marginBottom="10dp"
    android:onClick="closetomain">
    </ImageButton>
    <ImageButton android:id="@+id/level07_leftButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="135dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageButton android:id="@+id/level07_rightButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="340dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageView android:id="@+id/level07_beginButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/beginbutton"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="2dp"
    android:layout_marginLeft="235dp">
    </ImageView>
    <ImageView android:id="@+id/level07_ImageView00"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="325dp"
    android:background="@drawable/rocket">
    </ImageView>
</RelativeLayout>

<RelativeLayout android:id="@+id/level07_layout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/vlayoutup"
android:visibility="gone">
    <ImageButton android:id="@+id/level07_closeButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/close"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="10dp"
    android:layout_marginBottom="10dp"
    android:onClick="closetomain">
    </ImageButton>
    <ImageButton android:id="@+id/level07_leftButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="135dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageButton android:id="@+id/level07_rightButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="340dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageButton android:id="@+id/level07_backButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/backlevel"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="2dp"
    android:layout_marginLeft="235dp"
    android:onClick="prevLayout">
    </ImageButton>
</RelativeLayout>
</code>```

Here's a snippet of the broken java:

```<code>    case R.id.level07_backButton01:
        RelativeLayout bB017 = (RelativeLayout)findViewById(R.id.level07_layout00);
        bB017.setVisibility(View.VISIBLE);
        RelativeLayout bB017b = (RelativeLayout)findViewById(R.id.level07_layout01);
        bB017b.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton02:
        RelativeLayout bB027b = (RelativeLayout)findViewById(R.id.level07_layout01);
        bB027b.setVisibility(View.VISIBLE);
        RelativeLayout bB027 = (RelativeLayout)findViewById(R.id.level07_layout02);
        bB027.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton03:
        RelativeLayout bB037 = (RelativeLayout)findViewById(R.id.level07_layout02);
        bB037.setVisibility(View.VISIBLE);
        RelativeLayout bB037b = (RelativeLayout)findViewById(R.id.level07_layout03);
        bB037b.setVisibility(View.GONE);
        break;
</code>```

Here's a snippet of the code that works from the same block:

```<code>case R.id.level07_backButton16:
        RelativeLayout bB167 = (RelativeLayout)findViewById(R.id.level07_layout15);
        bB167.setVisibility(View.VISIBLE);
        RelativeLayout bB167b = (RelativeLayout)findViewById(R.id.level07_layout16);
        bB167b.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton17:
        RelativeLayout bB177 = (RelativeLayout)findViewById(R.id.level07_layout13);
        bB177.setVisibility(View.VISIBLE);
        RelativeLayout bB177b = (RelativeLayout)findViewById(R.id.level07_layout17);
        bB177b.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton18:
        RelativeLayout bB187 = (RelativeLayout)findViewById(R.id.level07_layout17);
        bB187.setVisibility(View.VISIBLE);
        RelativeLayout bB187b = (RelativeLayout)findViewById(R.id.level07_layout18);
        bB187b.setVisibility(View.GONE);
        break;
</code>```

As you can see, I think, the two blocks of switch cases are the same. The part that I think is the important clue is in the logCat: VFY: invalid switch target.

If you need more information please let me know. Thanks in advance for the help!

答:
Use a default case to trap unspecified cases, however it's not required.

Check the switch statement.

Body:
I am building an Android app using a pile of switch statements to switch between views. Everything was going fine until I added a block of cases that cause a fatal error when the app is starting up. The cases are called by onClick statements in the XML. The offending block of cases is actually part of a block of statements that work fine. Can anyone see what I'm missing? What's causing the fatal error? I'm including snippets of the broken code and working code along with the logCat file.

05-17 01:48:01.931: INFO/System.out(270): debugger has settled (1381)
05-17 01:48:02.341: WARN/dalvikvm(270): VFY: invalid switch target 7170 (-> 0x1c0b) at 0x9[0]
05-17 01:48:02.351: WARN/dalvikvm(270): VFY:  rejected Lcom/findthway/main;.nextLayout (Landroid/view/View;)V
05-17 01:48:02.351: WARN/dalvikvm(270): Verifier rejected class Lcom/findthway/main;
05-17 01:48:02.351: WARN/dalvikvm(270): Class init failed in newInstance call (Lcom/findthway/main;)
05-17 01:48:03.031: INFO/ActivityManager(67): Displayed activity com.android.launcher/com.android.launcher2.Launcher: 50893 ms (total 50893 ms)
05-17 01:48:08.001: WARN/ActivityManager(67): Launch timeout has expired, giving up wake lock!
05-17 01:48:08.751: WARN/ActivityManager(67): Activity idle timeout for HistoryRecord{43eda500 com.findthway/.main}
05-17 01:52:41.531: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 01:57:41.551: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:02:41.576: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:07:41.641: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:08:45.831: DEBUG/dalvikvm(67): GC_FOR_MALLOC freed 15592 objects / 665856 bytes in 160ms
05-17 02:12:41.695: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:16:30.392: DEBUG/dalvikvm(67): GC_FOR_MALLOC freed 4697 objects / 200928 bytes in 108ms
05-17 02:17:41.716: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:22:41.745: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:27:41.801: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:32:41.812: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:37:41.851: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
05-17 02:41:00.341: DEBUG/dalvikvm(67): GC_FOR_MALLOC freed 12690 objects / 520224 bytes in 235ms

Example of the XML that would be calling the broken switch cases:

<RelativeLayout android:id="@+id/level07_layout00"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/vlayoutup"
android:visibility="gone">
    <ImageButton android:id="@+id/level07_closeButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/close"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="10dp"
    android:layout_marginBottom="10dp"
    android:onClick="closetomain">
    </ImageButton>
    <ImageButton android:id="@+id/level07_leftButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="135dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageButton android:id="@+id/level07_rightButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="340dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageView android:id="@+id/level07_beginButton00"
    android:layout_height="wrap_content"
    android:background="@drawable/beginbutton"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="2dp"
    android:layout_marginLeft="235dp">
    </ImageView>
    <ImageView android:id="@+id/level07_ImageView00"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="325dp"
    android:background="@drawable/rocket">
    </ImageView>
</RelativeLayout>

<RelativeLayout android:id="@+id/level07_layout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/vlayoutup"
android:visibility="gone">
    <ImageButton android:id="@+id/level07_closeButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/close"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginLeft="10dp"
    android:layout_marginBottom="10dp"
    android:onClick="closetomain">
    </ImageButton>
    <ImageButton android:id="@+id/level07_leftButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="135dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageButton android:id="@+id/level07_rightButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/node"
    android:layout_width="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="2dp"
    android:layout_marginLeft="340dp"
    android:onClick="nextLayout">
    </ImageButton>
    <ImageButton android:id="@+id/level07_backButton01"
    android:layout_height="wrap_content"
    android:background="@drawable/backlevel"
    android:layout_width="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="2dp"
    android:layout_marginLeft="235dp"
    android:onClick="prevLayout">
    </ImageButton>
</RelativeLayout>

Here's a snippet of the broken java:

    case R.id.level07_backButton01:
        RelativeLayout bB017 = (RelativeLayout)findViewById(R.id.level07_layout00);
        bB017.setVisibility(View.VISIBLE);
        RelativeLayout bB017b = (RelativeLayout)findViewById(R.id.level07_layout01);
        bB017b.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton02:
        RelativeLayout bB027b = (RelativeLayout)findViewById(R.id.level07_layout01);
        bB027b.setVisibility(View.VISIBLE);
        RelativeLayout bB027 = (RelativeLayout)findViewById(R.id.level07_layout02);
        bB027.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton03:
        RelativeLayout bB037 = (RelativeLayout)findViewById(R.id.level07_layout02);
        bB037.setVisibility(View.VISIBLE);
        RelativeLayout bB037b = (RelativeLayout)findViewById(R.id.level07_layout03);
        bB037b.setVisibility(View.GONE);
        break;

Here's a snippet of the code that works from the same block:

case R.id.level07_backButton16:
        RelativeLayout bB167 = (RelativeLayout)findViewById(R.id.level07_layout15);
        bB167.setVisibility(View.VISIBLE);
        RelativeLayout bB167b = (RelativeLayout)findViewById(R.id.level07_layout16);
        bB167b.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton17:
        RelativeLayout bB177 = (RelativeLayout)findViewById(R.id.level07_layout13);
        bB177.setVisibility(View.VISIBLE);
        RelativeLayout bB177b = (RelativeLayout)findViewById(R.id.level07_layout17);
        bB177b.setVisibility(View.GONE);
        break;
    case R.id.level07_backButton18:
        RelativeLayout bB187 = (RelativeLayout)findViewById(R.id.level07_layout17);
        bB187.setVisibility(View.VISIBLE);
        RelativeLayout bB187b = (RelativeLayout)findViewById(R.id.level07_layout18);
        bB187b.setVisibility(View.GONE);
        break;

As you can see, I think, the two blocks of switch cases are the same. The part that I think is the important clue is in the logCat: VFY: invalid switch target.

If you need more information please let me know. Thanks in advance for the help!


问:
Skip the filenames whch do not have contents while doing a for loop
I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

```<code>for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done
</code>```

Output

```<code>-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)
</code>```

Desired output..

```<code>-- file6 --
some output
-- file9 --
some output
</code>```

答:
try:</p>

```<code>grep -rin path/to/dir -e string_to_search
</code>```

Body:
I'm grepping a string in files under a directory as i don't know in which file the string_something exits thus I'm listing all the files and doing grep on then to identify, this works however in the echo statement i only want the the Files which have the string value found rest skip the filename in the output.

for i in `ls -Xl| awk '{print $NF}'`;do echo "-- $i --"; grep string "$i";done

Output

-- file1 --
-- file2 --
-- file3 --
-- file4 --
-- file5 --
-- file6 --
some output   ( all the output matching to the `string` matched)
-- file7 --
-- file8 --
-- file9 --
some output   ( all the output matching to the `string` matched)

Desired output..

-- file6 --
some output
-- file9 --
some output

Body:
try:

grep -rin path/to/dir -e string_to_search


问:
Allow cloud functions ip from app engine firewall rules
We have created an app engine instance to work as backend and another one is from cloud function.
Now cloud functions needs to access the api from app engine within the same google project this works fine if the firewall from app engine allows everyone to access. But in our case we need to restrict the access from cloud function only.

I'm new to GCP I would higly appreciate your suggestions. Thanks in advance.

答:
The best solution would be to activate the IAP for App Engine ( Identity aware proxy ). Here you can find a guide on how to activate your IAP on App Engine.

IAP will interdict the acces of anyone, any application to access your App Engine instance, but the one you will allow manually. In your situation you will need to allow the Cloud Functions service account to access your application. You can check on this guide on how to achieve that programmatically from Cloud Functions. You have examples for C#, Python, Java and PHP.

eg Python :

```<code>import google.auth
import google.auth.app_engine
import google.auth.compute_engine.credentials
import google.auth.iam
from google.auth.transport.requests import Request
import google.oauth2.credentials
import google.oauth2.service_account
import requests
import requests_toolbelt.adapters.appengine

IAM_SCOPE = 'https://www.googleapis.com/auth/iam'
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'

def make_iap_request(url, client_id, method='GET', **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.
Args:
  url: The Identity-Aware Proxy-protected URL to fetch.
  client_id: The client ID used by Identity-Aware Proxy.
  method: The request method to use
          ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
  **kwargs: Any of the parameters defined for the request function:
            https://github.com/requests/requests/blob/master/requests/api.py
            If no timeout is provided, it is set to 90 by default.

Returns:
  The page body, or raises an exception if the page couldn't be retrieved.
"""
# Set the default timeout, if missing
if 'timeout' not in kwargs:
    kwargs['timeout'] = 90

# Figure out what environment we're running in and get some preliminary
# information about the service account.
bootstrap_credentials, _ = google.auth.default(
    scopes=[IAM_SCOPE])
if isinstance(bootstrap_credentials,
              google.oauth2.credentials.Credentials):
    raise Exception('make_iap_request is only supported for service '
                    'accounts.')
elif isinstance(bootstrap_credentials,
                google.auth.app_engine.Credentials):
    requests_toolbelt.adapters.appengine.monkeypatch()

# For service account's using the Compute Engine metadata service,
# service_account_email isn't available until refresh is called.
bootstrap_credentials.refresh(Request())

signer_email = bootstrap_credentials.service_account_email
if isinstance(bootstrap_credentials,
              google.auth.compute_engine.credentials.Credentials):
    # Since the Compute Engine metadata service doesn't expose the service
    # account key, we use the IAM signBlob API to sign instead.
    # In order for this to work:
    #
    # 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
    #    You can specify this specific scope when creating a VM
    #    through the API or gcloud. When using Cloud Console,
    #    you'll need to specify the "full access to all Cloud APIs"
    #    scope. A VM's scopes can only be specified at creation time.
    #
    # 2. The VM's default service account needs the "Service Account Actor"
    #    role. This can be found under the "Project" category in Cloud
    #    Console, or roles/iam.serviceAccountActor in gcloud.
    signer = google.auth.iam.Signer(
        Request(), bootstrap_credentials, signer_email)
else:
    # A Signer object can sign a JWT using the service account's key.
    signer = bootstrap_credentials.signer

# Construct OAuth 2.0 service account credentials using the signer
# and email acquired from the bootstrap credentials.
service_account_credentials = google.oauth2.service_account.Credentials(
    signer, signer_email, token_uri=OAUTH_TOKEN_URI, additional_claims={
        'target_audience': client_id
    })

# service_account_credentials gives us a JWT signed by the service
# account. Next, we use that to obtain an OpenID Connect token,
# which is a JWT signed by Google.
google_open_id_connect_token = get_google_open_id_connect_token(
    service_account_credentials)

# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.request(
    method, url,
    headers={'Authorization': 'Bearer {}'.format(
        google_open_id_connect_token)}, **kwargs)
if resp.status_code == 403:
    raise Exception('Service account {} does not have permission to '
                    'access the IAP-protected application.'.format(
                        signer_email))
elif resp.status_code != 200:
    raise Exception(
        'Bad response from application: {!r} / {!r} / {!r}'.format(
            resp.status_code, resp.headers, resp.text))
else:
    return resp.text

def get_google_open_id_connect_token(service_account_credentials):
    """Get an OpenID Connect token issued by Google for the service account.

This function:

  1. Generates a JWT signed with the service account's private key
     containing a special "target_audience" claim.

  2. Sends it to the OAUTH_TOKEN_URI endpoint. Because the JWT in #1
     has a target_audience claim, that endpoint will respond with
     an OpenID Connect token for the service account -- in other words,
     a JWT signed by *Google*. The aud claim in this JWT will be
     set to the value from the target_audience claim in #1.

For more information, see
https://developers.google.com/identity/protocols/OAuth2ServiceAccount .
The HTTP/REST example on that page describes the JWT structure and
demonstrates how to call the token endpoint. (The example on that page
shows how to get an OAuth2 access token; this code is using a
modified version of it to get an OpenID Connect token.)
"""

service_account_jwt = (
    service_account_credentials._make_authorization_grant_assertion())
request = google.auth.transport.requests.Request()
body = {
    'assertion': service_account_jwt,
    'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
}
token_response = google.oauth2._client._token_endpoint_request(
    request, OAUTH_TOKEN_URI, body)
return token_response['id_token']
</code>```

In case you use a Cloud Function on Nodejs, a StackOverflow user created an example on how to achieve the same for Nodejs in this post.

Body:
The best solution would be to activate the IAP for App Engine ( Identity aware proxy ). Here you can find a guide on how to activate your IAP on App Engine.

IAP will interdict the acces of anyone, any application to access your App Engine instance, but the one you will allow manually. In your situation you will need to allow the Cloud Functions service account to access your application. You can check on this guide on how to achieve that programmatically from Cloud Functions. You have examples for C#, Python, Java and PHP.

eg Python :

import google.auth
import google.auth.app_engine
import google.auth.compute_engine.credentials
import google.auth.iam
from google.auth.transport.requests import Request
import google.oauth2.credentials
import google.oauth2.service_account
import requests
import requests_toolbelt.adapters.appengine

IAM_SCOPE = 'https://www.googleapis.com/auth/iam'
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'

def make_iap_request(url, client_id, method='GET', **kwargs):
    """Makes a request to an application protected by Identity-Aware Proxy.
Args:
  url: The Identity-Aware Proxy-protected URL to fetch.
  client_id: The client ID used by Identity-Aware Proxy.
  method: The request method to use
          ('GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE')
  **kwargs: Any of the parameters defined for the request function:
            https://github.com/requests/requests/blob/master/requests/api.py
            If no timeout is provided, it is set to 90 by default.

Returns:
  The page body, or raises an exception if the page couldn't be retrieved.
"""
# Set the default timeout, if missing
if 'timeout' not in kwargs:
    kwargs['timeout'] = 90

# Figure out what environment we're running in and get some preliminary
# information about the service account.
bootstrap_credentials, _ = google.auth.default(
    scopes=[IAM_SCOPE])
if isinstance(bootstrap_credentials,
              google.oauth2.credentials.Credentials):
    raise Exception('make_iap_request is only supported for service '
                    'accounts.')
elif isinstance(bootstrap_credentials,
                google.auth.app_engine.Credentials):
    requests_toolbelt.adapters.appengine.monkeypatch()

# For service account's using the Compute Engine metadata service,
# service_account_email isn't available until refresh is called.
bootstrap_credentials.refresh(Request())

signer_email = bootstrap_credentials.service_account_email
if isinstance(bootstrap_credentials,
              google.auth.compute_engine.credentials.Credentials):
    # Since the Compute Engine metadata service doesn't expose the service
    # account key, we use the IAM signBlob API to sign instead.
    # In order for this to work:
    #
    # 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
    #    You can specify this specific scope when creating a VM
    #    through the API or gcloud. When using Cloud Console,
    #    you'll need to specify the "full access to all Cloud APIs"
    #    scope. A VM's scopes can only be specified at creation time.
    #
    # 2. The VM's default service account needs the "Service Account Actor"
    #    role. This can be found under the "Project" category in Cloud
    #    Console, or roles/iam.serviceAccountActor in gcloud.
    signer = google.auth.iam.Signer(
        Request(), bootstrap_credentials, signer_email)
else:
    # A Signer object can sign a JWT using the service account's key.
    signer = bootstrap_credentials.signer

# Construct OAuth 2.0 service account credentials using the signer
# and email acquired from the bootstrap credentials.
service_account_credentials = google.oauth2.service_account.Credentials(
    signer, signer_email, token_uri=OAUTH_TOKEN_URI, additional_claims={
        'target_audience': client_id
    })

# service_account_credentials gives us a JWT signed by the service
# account. Next, we use that to obtain an OpenID Connect token,
# which is a JWT signed by Google.
google_open_id_connect_token = get_google_open_id_connect_token(
    service_account_credentials)

# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.request(
    method, url,
    headers={'Authorization': 'Bearer {}'.format(
        google_open_id_connect_token)}, **kwargs)
if resp.status_code == 403:
    raise Exception('Service account {} does not have permission to '
                    'access the IAP-protected application.'.format(
                        signer_email))
elif resp.status_code != 200:
    raise Exception(
        'Bad response from application: {!r} / {!r} / {!r}'.format(
            resp.status_code, resp.headers, resp.text))
else:
    return resp.text

def get_google_open_id_connect_token(service_account_credentials):
    """Get an OpenID Connect token issued by Google for the service account.

This function:

  1. Generates a JWT signed with the service account's private key
     containing a special "target_audience" claim.

  2. Sends it to the OAUTH_TOKEN_URI endpoint. Because the JWT in #1
     has a target_audience claim, that endpoint will respond with
     an OpenID Connect token for the service account -- in other words,
     a JWT signed by *Google*. The aud claim in this JWT will be
     set to the value from the target_audience claim in #1.

For more information, see
https://developers.google.com/identity/protocols/OAuth2ServiceAccount .
The HTTP/REST example on that page describes the JWT structure and
demonstrates how to call the token endpoint. (The example on that page
shows how to get an OAuth2 access token; this code is using a
modified version of it to get an OpenID Connect token.)
"""

service_account_jwt = (
    service_account_credentials._make_authorization_grant_assertion())
request = google.auth.transport.requests.Request()
body = {
    'assertion': service_account_jwt,
    'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
}
token_response = google.oauth2._client._token_endpoint_request(
    request, OAUTH_TOKEN_URI, body)
return token_response['id_token']

In case you use a Cloud Function on Nodejs, a StackOverflow user created an example on how to achieve the same for Nodejs in this post.


问:
How to search and modify floating values that follow a string in a file using Perl
Lets say we have "abc {{1.1 2.2}}" occurring multiple times in a file and I want to modify it to "xyz {{2.2 4.4}}" which is basically:

Change abc to xyz.

And multiply the floating values by 2 that appear in the curly braces (always preceded by abc keyword).

```<code>abc {{1.1 2.2}} ----------> xyz {{2.2 4.4}}
</code>```

This modification must be done to all instances of the file.
Here's the code that I tried but was able to replace only abc to xyz and couldn't figure out how to do the operations by extracting those floating values.

```<code>#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/abc/xyz/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);
</code>```

Any sort of help is highly appreciated.

答:
No sample of input file was provide by OP and due this reason the following code may not reflect proper solution.

It was assumed that the pattern abc {{x.x x.x}} will not present more than once on the line.

```<code>use strict;
use warnings;
use feature 'say';

my $debug = 0;

for (<DATA>) {
    chomp;
    say $_ if $debug;
    if( /(.*)?abc\s*\{\{\s*([\d\.]+)\s*([\d\.]+)\s*\}\}(.*)/ ) {
        my($a,$b) = ($2,$3);
        $a *= 2;
        $b *= 2;
        say $1 . "xyz {{$a $b}}" . $4;
    } else {
        say $_;
    }
}

__DATA__
This an example data abc {{1.1 2.2}} which required some manipulation.

We should take abc {{1.1 2.2}} and replace 'abc' to 'xyz' take two
float numbers in curly brackets and multiply each by 2, write result
as xyz {{2.2 4.4}}.

Let's play with some numbers
        abc {{7.2 12.4}}
            boy {{0.5 8.2}}
        put {{2.3 8.6}}
            got {{4.1 2.3}}
        abc {{0.5 4.9}}

Note: numbers can have values different from provided sample
</code>```

Output

```<code>This an example data xyz {{2.2 4.4}} which required some manipulation.

We should take xyz {{2.2 4.4}} and replace 'abc' to 'xyz' take two
float numbers in curly brackets and multiply each by 2, write result
as xyz {{2.2 4.4}}.

Let's play with some numbers
                xyz {{14.4 24.8}}
                        boy {{0.5 8.2}}
                put {{2.3 8.6}}
                        got {{4.1 2.3}}
                xyz {{1 9.8}}

Note: numbers can have values different from provided sample
</code>```

Body:
Lets say we have "abc {{1.1 2.2}}" occurring multiple times in a file and I want to modify it to "xyz {{2.2 4.4}}" which is basically:

Change abc to xyz.

And multiply the floating values by 2 that appear in the curly braces (always preceded by abc keyword).

abc {{1.1 2.2}} ----------> xyz {{2.2 4.4}}

This modification must be done to all instances of the file.
Here's the code that I tried but was able to replace only abc to xyz and couldn't figure out how to do the operations by extracting those floating values.

#!/usr/bin/perl -w

use strict;

open(FILE, "</tmp/yourfile.txt") || die "File not found";
my @lines = <FILE>;
close(FILE);

foreach(@lines) {
   $_ =~ s/abc/xyz/g;
}

open(FILE, ">/tmp/yourfile.txt") || die "File not found";
print FILE @lines;
close(FILE);

Any sort of help is highly appreciated.

Body:
No sample of input file was provide by OP and due this reason the following code may not reflect proper solution.

It was assumed that the pattern abc {{x.x x.x}} will not present more than once on the line.

use strict;
use warnings;
use feature 'say';

my $debug = 0;

for (<DATA>) {
    chomp;
    say $_ if $debug;
    if( /(.*)?abc\s*\{\{\s*([\d\.]+)\s*([\d\.]+)\s*\}\}(.*)/ ) {
        my($a,$b) = ($2,$3);
        $a *= 2;
        $b *= 2;
        say $1 . "xyz {{$a $b}}" . $4;
    } else {
        say $_;
    }
}

__DATA__
This an example data abc {{1.1 2.2}} which required some manipulation.

We should take abc {{1.1 2.2}} and replace 'abc' to 'xyz' take two
float numbers in curly brackets and multiply each by 2, write result
as xyz {{2.2 4.4}}.

Let's play with some numbers
        abc {{7.2 12.4}}
            boy {{0.5 8.2}}
        put {{2.3 8.6}}
            got {{4.1 2.3}}
        abc {{0.5 4.9}}

Note: numbers can have values different from provided sample

Output

This an example data xyz {{2.2 4.4}} which required some manipulation.

We should take xyz {{2.2 4.4}} and replace 'abc' to 'xyz' take two
float numbers in curly brackets and multiply each by 2, write result
as xyz {{2.2 4.4}}.

Let's play with some numbers
                xyz {{14.4 24.8}}
                        boy {{0.5 8.2}}
                put {{2.3 8.6}}
                        got {{4.1 2.3}}
                xyz {{1 9.8}}

Note: numbers can have values different from provided sample