问:
Undefined method uploading apk with Fastlane
I'm getting an error on gitlab ci server deploying/uploading an apk to Fabric with Fastlane. The strange thing is that it is working if I run the task from my local. The Fastlane is the same version in both cases 2.123.0.

The method of the task that is failing is:

```<code>31 desc "Generate QA release notes"
32 private_lane :qa_release_notes do
33 commit = last_git_commit
34 short_hash = commit[:abbreviated_commit_hash]
35 author = commit[:author]
36 message = commit[:message]
37 "Release notes of commit " + short_hash + " by " + author +":\n " + message
38 end
</code>```

And the error printed in the ci log is:

```<code>[15:43:34]: Error in your Fastfile at line 34
[15:43:34]: 32:  private_lane :qa_release_notes do
[15:43:34]: 33:  commit = last_git_commit
[15:43:34]: => 34:   short_hash = commit[:abbreviated_commit_hash]
[15:43:34]: 35:  author = commit[:author]
[15:43:34]: 36:  message = commit[:message]
</code>```

(...)

```<code>Fastfile:34:in block (2 levels) in parsing_binding': [!] undefined method []' for nil:NilClass (NoMethodError)
    from /var/lib/gems/2.3.0/gems/fastlane-2.123.0/fastlane/lib/fastlane/lane.rb:33:in `call'
</code>```

It seems the problem is with the method commit[:abbreviated_commit_hash]
But I don't know what the problem is...Any idea?

答:
I think the error message tells you that commit = last_git_commit didn't actually set commit to anything, so using [...] on it raises [!] undefined method []' for nil:NilClass (NoMethodError).

You could try to debug by simply outputting commit between lines 33 and 34: puts(commit). Running the lane with --verbose might also give some additional, hopefully helpful output to understand what is going on.

The code being executed in the background is actually https://github.com/fastlane/fastlane/blob/4c468b9873f9a2bd68e8ef21b2502d32f2024d32/fastlane/lib/fastlane/helper/git_helper.rb#L53-L74, but I don't see an obvious way why this would be failing on gitlab CI.

Body:
I'm getting an error on gitlab ci server deploying/uploading an apk to Fabric with Fastlane. The strange thing is that it is working if I run the task from my local. The Fastlane is the same version in both cases 2.123.0.

The method of the task that is failing is:

31 desc "Generate QA release notes"
32 private_lane :qa_release_notes do
33 commit = last_git_commit
34 short_hash = commit[:abbreviated_commit_hash]
35 author = commit[:author]
36 message = commit[:message]
37 "Release notes of commit " + short_hash + " by " + author +":\n " + message
38 end

And the error printed in the ci log is:

[15:43:34]: Error in your Fastfile at line 34
[15:43:34]: 32:  private_lane :qa_release_notes do
[15:43:34]: 33:  commit = last_git_commit
[15:43:34]: => 34:   short_hash = commit[:abbreviated_commit_hash]
[15:43:34]: 35:  author = commit[:author]
[15:43:34]: 36:  message = commit[:message]

(...)

Fastfile:34:in block (2 levels) in parsing_binding': [!] undefined method []' for nil:NilClass (NoMethodError)
    from /var/lib/gems/2.3.0/gems/fastlane-2.123.0/fastlane/lib/fastlane/lane.rb:33:in `call'

It seems the problem is with the method commit[:abbreviated_commit_hash]
But I don't know what the problem is...Any idea?


来源: stackexchange

问:
Node.js: Regular expressions to get e-mail headers and body
I know very little about regular expressions and I'm having trouble getting the information I need from an e-mail so I'd like your help reading the fields: "status", "to", "from", "subject" and "body".

```<code>The e-mail has failed, details:

Action: failed
Status: 5.0.0 (permanent failure)

---------- Forwarded message ----------
From: exp@gmail.com
To: regular_exp@gmail.com
Date: Tue, 12 Apr 2011 13:55:23 +0000
Subject: test
hellloooooo
</code>```

What's the best way to do it using JavaScript?

Thanks

答:
Assuming that these fields are as simple and consistent as

[\n] From: [...][\n]

then an expression like

/[\n]( From: ).+[\n]/

Would work for you. Replace ( From: ) with ( Date: ) etc.

And use string.match(regExp)

Update:

```<code>var bodyRegex = /[\n] Subject: (.+)[\n](.+)/
var string = ...;
var result = string.match(bodyRegex);
result[1]; // Subject
result[2]; // Body
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know very little about regular expressions and I'm having trouble getting the information I need from an e-mail so I'd like your help reading the fields: "status", "to", "from", "subject" and "body".

The e-mail has failed, details:

Action: failed
Status: 5.0.0 (permanent failure)

---------- Forwarded message ----------
From: exp@gmail.com
To: regular_exp@gmail.com
Date: Tue, 12 Apr 2011 13:55:23 +0000
Subject: test
hellloooooo

What's the best way to do it using JavaScript?

Thanks

Body:
Assuming that these fields are as simple and consistent as

[\n] From: [...][\n]

then an expression like

/[\n]( From: ).+[\n]/

Would work for you. Replace ( From: ) with ( Date: ) etc.

And use string.match(regExp)

Update:

var bodyRegex = /[\n] Subject: (.+)[\n](.+)/
var string = ...;
var result = string.match(bodyRegex);
result[1]; // Subject
result[2]; // Body


问:
Chrome extension - retrieving global variable from webpage
I am working on an extension for Chrome. I wish parse the content of the "original" Gmail message (the currently viewed message).

I tried to utilize the jQuery.load() as follows

```<code>$(windows).load(function() { alert(GLOBALS); });
</code>```

and place it at the content script, but it does not work either. I am using Chrome's developer tools, which returns the following error on the invocation of the alert(GLOBALS);

Uncaught ReferenceError: GLOBALS is not defined

Although, when using the developers tools' console, typing into the console GLOBALS it returns an array.

Any clue how to access the GLOBALS from the content script?

答:
Add to your content script:

```<code>function executeOnPageSpace(code){

  // create a script tag
  var script = document.createElement('script')
  script.id = 'tmpScript'
  // place the code inside the script. later replace it with execution result.
  script.textContent =
  'document.getElementById("tmpScript").textContent = JSON.stringify(' + code + ')'
  // attach the script to page
  document.documentElement.appendChild(script)
  // collect execution results
  let result = document.getElementById("tmpScript").textContent
  // remove script from page
  script.remove()
  return JSON.parse(result)

}
</code>```

Now you can do:

```<code>let window = executeOnPageSpace('window')
</code>```

or even like this:

```<code>executeOnPageSpace('window.location.href = "http://stackoverflow.com"')
</code>```

NOTE: I have not tested this for long-running code.

Body:
I am working on an extension for Chrome. I wish parse the content of the "original" Gmail message (the currently viewed message).

I tried to utilize the jQuery.load() as follows

$(windows).load(function() { alert(GLOBALS); });

and place it at the content script, but it does not work either. I am using Chrome's developer tools, which returns the following error on the invocation of the alert(GLOBALS);

Uncaught ReferenceError: GLOBALS is not defined

Although, when using the developers tools' console, typing into the console GLOBALS it returns an array.

Any clue how to access the GLOBALS from the content script?

Body:
Add to your content script:

function executeOnPageSpace(code){

  // create a script tag
  var script = document.createElement('script')
  script.id = 'tmpScript'
  // place the code inside the script. later replace it with execution result.
  script.textContent =
  'document.getElementById("tmpScript").textContent = JSON.stringify(' + code + ')'
  // attach the script to page
  document.documentElement.appendChild(script)
  // collect execution results
  let result = document.getElementById("tmpScript").textContent
  // remove script from page
  script.remove()
  return JSON.parse(result)

}

Now you can do:

let window = executeOnPageSpace('window')

or even like this:

executeOnPageSpace('window.location.href = "http://stackoverflow.com"')

NOTE: I have not tested this for long-running code.

ContentLicense: CC BY-SA 4.0


问:
Concatenate a variable with an Id tag in Pug
I'm triyng to create dynamic variables using an Id and an incremental number.

```<code>ul
  - for(var i = 0; i < 3; i++)
    li#id#{i}
</code>```

I expected to get

```<code>li#id0
li#id1
...
</code>```

答:
Pug's id shorthand doesn't work well with dynamic values. Use the standard attribute syntax instead.

```<code>ul
  - for (var i = 0; i < 3; i++)
    li(id= 'id' + i)
</code>```

Or, if you like ES6 template strings:

```<code>ul
  - for (var i = 0; i < 3; i++)
    li(id=`id${i}`)
</code>```

Both compile to:

```<code><ul>
  <li id="id0"></li>
  <li id="id1"></li>
  <li id="id2"></li>
</ul>
</code>```

Body:
I'm triyng to create dynamic variables using an Id and an incremental number.

ul
  - for(var i = 0; i < 3; i++)
    li#id#{i}

I expected to get

li#id0
li#id1
...

Body:
Pug's id shorthand doesn't work well with dynamic values. Use the standard attribute syntax instead.

ul
  - for (var i = 0; i < 3; i++)
    li(id= 'id' + i)

Or, if you like ES6 template strings:

ul
  - for (var i = 0; i < 3; i++)
    li(id=`id${i}`)

Both compile to:

<ul>
  <li id="id0"></li>
  <li id="id1"></li>
  <li id="id2"></li>
</ul>


问:
How can Iconvert Matlab code into python :- For UT (Universal Time) to LST (Local Sidereal Time) time conversion with incrementing date time
I have a user defined function UT2LSTmine in matlab. I want to convert the same function into Python working in exact way as it does in matlab. I am new to python programming. I tried alot . I also used online conversion apps for Matlab to Python (OMPC). It is not working as per my requirement.

The function should take start universal time (UT) and convert into Local Sidereal time (LST) , taking incrementing date and time into consideration.

Function to convert the UT hours, min, sec to LST hours, min, sec at GBD
This fuction takes the input from the obsever such as yr,mn,dd,uth,htm,uts. Returns the converted lsth, lstm, lsts. This fuction also checks for 24 hours input and automatically increments the day.

```<code>function [t] = UT2LSTmine(varargin)

yr = varargin{1};
mn = varargin{2};
dd = varargin{3};
uth = varargin{4};
utm = varargin{5};
uts = varargin{6};

t=[yr,mn,dd,uth,utm,uts];

format long g ;

gbdlong = 5.06138;

%%% Compute Julian Date for the given date

x=[t(1,1), t(1,2), t(1,3), 0,0,0.5];
[~,indx]=ismember(x,t,'rows');%for 24 hours check
if(indx > 0)
t(indx:end,3)=t(indx:end,3)+1;%Incrementing the day manually commented                       for RTLSDR on 30th MA
x=[t(indx,1), t(indx,2), t(indx,3), 23,59,59];
end

%%% Compute Local time & UT for the given IST
utd = t(:,4) + (t(:,5)./60) + (t(:,6)/3600);

for i=1:1:length(t)

julday(i) = juliandate(t(i,1),t(i,2),t(i,3)) + 0.5000000;
jd(i) = julday(i) - 0.5; %%% JD @ 0h UT
T(i) = (jd(i) - 2451545.0)/36525;  %%% Time interval since 2000 jan 1
12h UT

%%% Compute Gmst @ 0h UT
gmst0(i) = 24110.54841 + (8640184.812866 * T(i)) + (0.093104 * T(i) *
T(i)) - (0.000006200 * T(i) * T(i) * T(i));

%%% Convert Gmst to Hours

gmst0(i) = gmst0(i) / (86400.0); %%% gmst0 in days
gmst0(i) = gmst0(i) - floor(gmst0(i)); %%% Get the fraction of the day
gmst0(i) =  gmst0(i) * 24.0;  %%% Convert into hours
if (gmst0(i) < -0.0000001);
gmst0(i) = gmst0(i) + 24;
end

%%% Compute equivalent of mean sidreal time interval from oh to UT of
%%% intrest

mst(i) = utd(i) * 1.0027379094;
if ( mst(i) - 24.0 > 0.000001);
mst(i) = mst(i) - 24.0;
end

%%% Greenwitch mean sidreal time @ required UT

gmst(i) = gmst0(i) + mst(i);
if ( gmst(i) - 24.0 > 0.000001);
gmst(i) =gmst(i) - 24.0;
end

%%% Local mean sidreal time

lst(i) = gmst(i) + gbdlong;
if ( lst(i) > 24.0);
lst(i) = lst(i) - 24.0;
else if ( lst(i) < 0);
lst(i) = lst(i) + 24.0;
else
lst(i) = lst(i);
end

lsth(i) = floor(lst(i));
lstm1(i) = (lst(i) - floor(lsth(i))) * 60.0;
lstm(i) = floor(lstm1(i));
lsts(i) = (lstm1(i) - floor(lstm(i))) * 60.0;

% IST corresponding to the given UT

istd(i) = utd(i) + 5.5;
if ( istd(i) > 24.0);
ist(i) = istd(i) - 24.0;
elseif ( istd(i) < 0);
ist(i) = istd(i) + 24.0;
else
ist(i) = istd(i);
end
isth(i) = floor(ist(i));
istm(i) = (ist(i) - floor(ist(i))) * 60;
ists(i) = (istm(i) - floor(istm(i))) * 60;
t(i,4)=lsth(i);t(i,5)=lstm(i);t(i,6)=lsts(i);

end

%%%%%%%%%%%%%%%%%%For checking 24hours condition for LST%%%%%

 [~,index]=ismember(x,t,'rows');%for 24 hours check

 if(indx > 0 & index == 0)

 t(indx:end,3)=t(indx:end,3)-1;%If LST not completed 24 hours then do 1
 day substraction do to the increment of UT

 end
</code>```

I have tried this -

```<code> import numpy as np
 def UT2LSTmine(*args):
#Function to convert the UT hours, min, sec to LST hours, min, sec at GBD
#  This fuction takes the input from the obsever such as
#  yr,mn,dd,uth,htm,uts. Returs the converted lsth, lstm, lsts
#This fuction also checks for 24 hours input and automatically increments
#the day
 yr = args[:,0]
 mn = args[:,1]
 dd = args[:,2]
 uth = args[:,3]
 utm = args[:,4]
 uts = args[:,5]

 t = [yr, mn, dd, uth, utm, uts]

 format('long', 'g')
 #gbdlong = 5.162351852;%for GBD

 gbdlong = 5.06138#for IIT Indore

 #########Compute Julian Date for the given date

 x = [t(1, 1), t(1, 2), t(1, 3), 0, 0, 0.5]
 ismember(x, t, 'rows')  #for 24 hours check
 for i in x:
    index = np.where(t==i)[0]
    if index.size == 0:
        yield 0
    else:
        yield index

    if (index > 0):
        t[slice[index:stop], 3]=  t(slice[index:end], 3) + 1           #Incrementing the day manually commented for
    #RTLSDR on 30th MA
     x = [t(index, 1), t(index, 2), t(index, 3), 23, 59, 59]

     ##### Compute Local time & UT for the given IST
     utd = t(slice[:], 4) + (t(slice[:], 5) / 60) + (t(slice[:], 6) / 3600)

     for i in slice[1:1:length(t)]:

        julday[i] = juliandate(t(i, 1), t(i, 2), t(i, 3)) + 0.5000000
        jd[i]= julday(i) - 0.5        #%% JD @ 0h UT
        T[i] = (jd(i) - 2451545.0) / 36525        #%% Time interval      since 2000 jan 1 12h UT

         ########Compute Gmst @ 0h UT
         gmst0[i] = 24110.54841 + (8640184.812866 * T(i)) + (0.093104 *     T(i) * T(i)) - (0.000006200 * T(i) * T(i) * T(i))

          ####Convert Gmst to Hours
         gmst0[i] = gmst0(i) / (86400.0)        #%% gmst0 in days
         gmst0[i]= gmst0(i) - floor(gmst0(i))        #%% Get the  fraction of the day
          gmst0[i]= gmst0(i) * 24.0        #%% Convert into hours
          if (gmst0(i) < -0.0000001):
            gmst0[i]= gmst0(i) + 24
         ###Compute equivalent of mean sidreal time interval from oh to  UT of intrest
            mst[i] = utd(i) * 1.0027379094
            if (mst(i) - 24.0 > 0.000001):
                mst[i] = mst(i) - 24.0
                end

        ###Greenwitch mean sidreal time @ required UT

                gmst[i] = gmst0(i) + mst(i)
                if (gmst(i) - 24.0 > 0.000001):
                    gmst[i] = gmst(i) - 24.0
           # ####Local mean sidreal time

                    lst[i] = gmst(i) + gbdlong
                    if (lst(i) > 24.0):
                        lst[i]= lst(i) - 24.0
                    elif (lst(i) < 0):
                        lst[i]= lst(i) + 24.0
                    else:
                        lst[i]= lst(i)

                        lsth[i]= floor(lst(i))
                        lstm1[i]= (lst(i) - floor(lsth(i))) * 60.0
                        lstm[i]= floor(lstm1(i))
                        lsts[i]= (lstm1(i) - floor(lstm(i))) * 60.0

                        # IST corresponding to the given UT

                        istd[i]= utd(i) + 5.5
                        if (istd(i) > 24.0):
                            ist[i]= istd(i) - 24.0
                        elif (istd(i) < 0):
                            ist[i] = istd(i) + 24.0
                        else:
                            ist[i]= istd(i)

                            isth[i] = floor(ist(i))
                            istm[i]= (ist(i) - floor(ist(i))) * 60
                            ists[i]= (istm(i) - floor(istm(i))) * 60
                            t[i, 4]= lsth(i)
                            t[i, 5] = lstm(i)
                            t[i, 6] = lsts(i)

          ############For checking 24hours condition for LST ###################

                            ismember(x, t,'rows')                                         #for 24 hours check

                            if (logical_and(indx > 0, index == 0)):

                                t[slice[indx:end], 3]=                                               t(slice[indx:end], 3) - 1                                #If LST not completed     24 hours then do 1 day substraction do to the increment of UT
</code>```

答:
Without thorough inspection I spot already multiple issues.
Looking at the programming style the Matlab-code is quite outdated; semi-columns after if-statements; and a function-statement without end-statement.

Furthermore, the function implements a juliandate() with doubles which is not supported (anymore?). Therefore, my matlab-version (R2018b) throws an error.
I see that the juliandate()-function is literally copied in to the python script, which is, as far as I know, not a function in python.

I do not have a lot of Python knowledge. But i know that the indenting is quite important. The following python code is:

```<code>if (true):
  doSomething()

  if (true):
    doSomethingElse()
</code>```

equivalent to this matlab code:

```<code>if true
  doSomething()
    if true
      doSomethingElse()
    end
end
</code>```

Which is clearly not the desired behavior.

It sounds like you found a matlab-function, that you needed in python.
But converting scripts with a online-tool sounds, for me, is a really big red flag.

So, I did some googling and found this:
Github: Sidereal-Time-Calculator.
Which sounds like what you need. It is not a function, but that is possible with not to much work.

Body:
I have a user defined function UT2LSTmine in matlab. I want to convert the same function into Python working in exact way as it does in matlab. I am new to python programming. I tried alot . I also used online conversion apps for Matlab to Python (OMPC). It is not working as per my requirement.

The function should take start universal time (UT) and convert into Local Sidereal time (LST) , taking incrementing date and time into consideration.

Function to convert the UT hours, min, sec to LST hours, min, sec at GBD
This fuction takes the input from the obsever such as yr,mn,dd,uth,htm,uts. Returns the converted lsth, lstm, lsts. This fuction also checks for 24 hours input and automatically increments the day.

function [t] = UT2LSTmine(varargin)

yr = varargin{1};
mn = varargin{2};
dd = varargin{3};
uth = varargin{4};
utm = varargin{5};
uts = varargin{6};

t=[yr,mn,dd,uth,utm,uts];

format long g ;

gbdlong = 5.06138;

%%% Compute Julian Date for the given date

x=[t(1,1), t(1,2), t(1,3), 0,0,0.5];
[~,indx]=ismember(x,t,'rows');%for 24 hours check
if(indx > 0)
t(indx:end,3)=t(indx:end,3)+1;%Incrementing the day manually commented                       for RTLSDR on 30th MA
x=[t(indx,1), t(indx,2), t(indx,3), 23,59,59];
end

%%% Compute Local time & UT for the given IST
utd = t(:,4) + (t(:,5)./60) + (t(:,6)/3600);

for i=1:1:length(t)

julday(i) = juliandate(t(i,1),t(i,2),t(i,3)) + 0.5000000;
jd(i) = julday(i) - 0.5; %%% JD @ 0h UT
T(i) = (jd(i) - 2451545.0)/36525;  %%% Time interval since 2000 jan 1
12h UT

%%% Compute Gmst @ 0h UT
gmst0(i) = 24110.54841 + (8640184.812866 * T(i)) + (0.093104 * T(i) *
T(i)) - (0.000006200 * T(i) * T(i) * T(i));

%%% Convert Gmst to Hours

gmst0(i) = gmst0(i) / (86400.0); %%% gmst0 in days
gmst0(i) = gmst0(i) - floor(gmst0(i)); %%% Get the fraction of the day
gmst0(i) =  gmst0(i) * 24.0;  %%% Convert into hours
if (gmst0(i) < -0.0000001);
gmst0(i) = gmst0(i) + 24;
end

%%% Compute equivalent of mean sidreal time interval from oh to UT of
%%% intrest

mst(i) = utd(i) * 1.0027379094;
if ( mst(i) - 24.0 > 0.000001);
mst(i) = mst(i) - 24.0;
end

%%% Greenwitch mean sidreal time @ required UT

gmst(i) = gmst0(i) + mst(i);
if ( gmst(i) - 24.0 > 0.000001);
gmst(i) =gmst(i) - 24.0;
end

%%% Local mean sidreal time

lst(i) = gmst(i) + gbdlong;
if ( lst(i) > 24.0);
lst(i) = lst(i) - 24.0;
else if ( lst(i) < 0);
lst(i) = lst(i) + 24.0;
else
lst(i) = lst(i);
end

lsth(i) = floor(lst(i));
lstm1(i) = (lst(i) - floor(lsth(i))) * 60.0;
lstm(i) = floor(lstm1(i));
lsts(i) = (lstm1(i) - floor(lstm(i))) * 60.0;

% IST corresponding to the given UT

istd(i) = utd(i) + 5.5;
if ( istd(i) > 24.0);
ist(i) = istd(i) - 24.0;
elseif ( istd(i) < 0);
ist(i) = istd(i) + 24.0;
else
ist(i) = istd(i);
end
isth(i) = floor(ist(i));
istm(i) = (ist(i) - floor(ist(i))) * 60;
ists(i) = (istm(i) - floor(istm(i))) * 60;
t(i,4)=lsth(i);t(i,5)=lstm(i);t(i,6)=lsts(i);

end

%%%%%%%%%%%%%%%%%%For checking 24hours condition for LST%%%%%

 [~,index]=ismember(x,t,'rows');%for 24 hours check

 if(indx > 0 & index == 0)

 t(indx:end,3)=t(indx:end,3)-1;%If LST not completed 24 hours then do 1
 day substraction do to the increment of UT

 end

I have tried this -

 import numpy as np
 def UT2LSTmine(*args):
#Function to convert the UT hours, min, sec to LST hours, min, sec at GBD
#  This fuction takes the input from the obsever such as
#  yr,mn,dd,uth,htm,uts. Returs the converted lsth, lstm, lsts
#This fuction also checks for 24 hours input and automatically increments
#the day
 yr = args[:,0]
 mn = args[:,1]
 dd = args[:,2]
 uth = args[:,3]
 utm = args[:,4]
 uts = args[:,5]

 t = [yr, mn, dd, uth, utm, uts]

 format('long', 'g')
 #gbdlong = 5.162351852;%for GBD

 gbdlong = 5.06138#for IIT Indore

 #########Compute Julian Date for the given date

 x = [t(1, 1), t(1, 2), t(1, 3), 0, 0, 0.5]
 ismember(x, t, 'rows')  #for 24 hours check
 for i in x:
    index = np.where(t==i)[0]
    if index.size == 0:
        yield 0
    else:
        yield index

    if (index > 0):
        t[slice[index:stop], 3]=  t(slice[index:end], 3) + 1           #Incrementing the day manually commented for
    #RTLSDR on 30th MA
     x = [t(index, 1), t(index, 2), t(index, 3), 23, 59, 59]

     ##### Compute Local time & UT for the given IST
     utd = t(slice[:], 4) + (t(slice[:], 5) / 60) + (t(slice[:], 6) / 3600)

     for i in slice[1:1:length(t)]:

        julday[i] = juliandate(t(i, 1), t(i, 2), t(i, 3)) + 0.5000000
        jd[i]= julday(i) - 0.5        #%% JD @ 0h UT
        T[i] = (jd(i) - 2451545.0) / 36525        #%% Time interval      since 2000 jan 1 12h UT

         ########Compute Gmst @ 0h UT
         gmst0[i] = 24110.54841 + (8640184.812866 * T(i)) + (0.093104 *     T(i) * T(i)) - (0.000006200 * T(i) * T(i) * T(i))

          ####Convert Gmst to Hours
         gmst0[i] = gmst0(i) / (86400.0)        #%% gmst0 in days
         gmst0[i]= gmst0(i) - floor(gmst0(i))        #%% Get the  fraction of the day
          gmst0[i]= gmst0(i) * 24.0        #%% Convert into hours
          if (gmst0(i) < -0.0000001):
            gmst0[i]= gmst0(i) + 24
         ###Compute equivalent of mean sidreal time interval from oh to  UT of intrest
            mst[i] = utd(i) * 1.0027379094
            if (mst(i) - 24.0 > 0.000001):
                mst[i] = mst(i) - 24.0
                end

        ###Greenwitch mean sidreal time @ required UT

                gmst[i] = gmst0(i) + mst(i)
                if (gmst(i) - 24.0 > 0.000001):
                    gmst[i] = gmst(i) - 24.0
           # ####Local mean sidreal time

                    lst[i] = gmst(i) + gbdlong
                    if (lst(i) > 24.0):
                        lst[i]= lst(i) - 24.0
                    elif (lst(i) < 0):
                        lst[i]= lst(i) + 24.0
                    else:
                        lst[i]= lst(i)

                        lsth[i]= floor(lst(i))
                        lstm1[i]= (lst(i) - floor(lsth(i))) * 60.0
                        lstm[i]= floor(lstm1(i))
                        lsts[i]= (lstm1(i) - floor(lstm(i))) * 60.0

                        # IST corresponding to the given UT

                        istd[i]= utd(i) + 5.5
                        if (istd(i) > 24.0):
                            ist[i]= istd(i) - 24.0
                        elif (istd(i) < 0):
                            ist[i] = istd(i) + 24.0
                        else:
                            ist[i]= istd(i)

                            isth[i] = floor(ist(i))
                            istm[i]= (ist(i) - floor(ist(i))) * 60
                            ists[i]= (istm(i) - floor(istm(i))) * 60
                            t[i, 4]= lsth(i)
                            t[i, 5] = lstm(i)
                            t[i, 6] = lsts(i)

          ############For checking 24hours condition for LST ###################

                            ismember(x, t,'rows')                                         #for 24 hours check

                            if (logical_and(indx > 0, index == 0)):

                                t[slice[indx:end], 3]=                                               t(slice[indx:end], 3) - 1                                #If LST not completed     24 hours then do 1 day substraction do to the increment of UT

Body:
Without thorough inspection I spot already multiple issues.
Looking at the programming style the Matlab-code is quite outdated; semi-columns after if-statements; and a function-statement without end-statement.

Furthermore, the function implements a juliandate() with doubles which is not supported (anymore?). Therefore, my matlab-version (R2018b) throws an error.
I see that the juliandate()-function is literally copied in to the python script, which is, as far as I know, not a function in python.

I do not have a lot of Python knowledge. But i know that the indenting is quite important. The following python code is:

if (true):
  doSomething()

  if (true):
    doSomethingElse()

equivalent to this matlab code:

if true
  doSomething()
    if true
      doSomethingElse()
    end
end

Which is clearly not the desired behavior.

It sounds like you found a matlab-function, that you needed in python.
But converting scripts with a online-tool sounds, for me, is a really big red flag.

So, I did some googling and found this:
Github: Sidereal-Time-Calculator.
Which sounds like what you need. It is not a function, but that is possible with not to much work.


问:
how to get descriptive error messages from embedded cassandra
I am using embedded cassandra to run unit tests. I notice that if any cql statements fail, then I don't see any descriptive reason for failure. For eg. I am running the following two statements which fails because I am trying to add a table without switching to a keyspace

```<code>val statement1 =
        """
          |CREATE KEYSPACE test
          |  WITH REPLICATION = {
          |   'class' : 'SimpleStrategy',
          |   'replication_factor' : 1
          |  };
        """.stripMargin

      val statement3 =
        """
            |CREATE TABLE users (
            |    bucket int,
            |    email text,
            |    firstname text,
            |    lastname text,
            |    authprovider text,
            |    password text,
            |    confirmed boolean,
            |    id UUID,
            |    hasher text,
            |    salt text,
            |    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        """.stripMargin

val cqlStatements:CqlStatements = new CqlStatements(statement1,statement3)

")
      val testCassandra = repoTestEnv.testCassandra

      try {
        testCassandra.start()
        testCassandra.executeScripts(cqlStatements)
      } finally testCassandra.stop()
</code>```

But I don't see correct error. I see the following which doesn't tell exactly what is the problem

```<code>[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is started
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is started (20811 ms)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Script: CqlStatements [
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };
        ,
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        ]
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };

[info] c.g.n.e.c.Cassandra - INFO  [Native-Transport-Requests-1] 2019-05-29 07:50:00,788 MigrationManager.java:310 - Create new Keyspace: KeyspaceMetadata{name=test, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=1}}, tables=[], views=[], functions=[], types=[]}
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )

[debug] c.g.n.e.c.t.TestCassandra - Stop TestCassandra 3.11.1
[info] c.g.n.e.c.l.LocalCassandraDatabase - Stop Apache Cassandra '3.11.1'
[debug] c.g.n.e.c.l.RunProcess - Execute 'powershell -ExecutionPolicy Unrestricted C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\bin\stop-server.ps1 -p C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\1da63488-2624-4141-a49e-174203b7edc4' within a directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32'
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,926 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,933 Server.java:176 - Stop listening for CQL clients
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,934 Gossiper.java:1532 - Announcing shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,938 StorageService.java:2268 - Node localhost/127.0.0.1 state jump to shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:05,941 MessagingService.java:984 - Waiting for messaging service to quiesce
[info] c.g.n.e.c.Cassandra - INFO  [ACCEPT-localhost/127.0.0.1] 2019-05-29 07:50:05,948 MessagingService.java:1338 - MessagingService has terminated the accept() thread
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:06,076 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.l.WindowsCassandraNode - Successfully sent ctrl+c to process with id: 7276.
[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is stopped
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is stopped (3490 ms)
[info] c.g.n.e.c.l.LocalCassandraDatabase - The working directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32' was deleted.
[debug] c.g.n.e.c.t.TestCassandra - TestCassandra 3.11.1 is stopped

Unable to start TestCassandra 3.11.1
com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.1
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:128)
    at UnitSpecs.RepositorySpecs.UsersRepositorySpecs.$anonfun$new$3(UsersRepositorySpecs.scala:146)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
</code>```

Ideally I should get the error similar to what I would get if I was using cqlsh

Is there a way to get more descriptive errors?

答:
I haven't been able to find my Caused isn't printed but I have found this workaround

```<code>  try {
    testCassandra.start()
    println(s"cassandra state is ${testCassandra.getState}")
    testCassandra.executeScripts(cqlStatements)
    //println(s"result of execution is ${result}")
    //val settings = testCassandra.getSettings
    //println(s"settings are ${settings}")
  } catch {
    case e:Exception => {
      println(s"exception ${e} caused by ${e.getCause}")
      //println(s"caused by ${e.getCause()}")
     fail( new Throwable(e.getCause))
    }
  }finally {
    testCassandra.stop()

  }
</code>```

the above prints

```<code>org.scalatest.exceptions.TestFailedException was thrown.
ScalaTestFailureLocation: UnitSpecs.RepositorySpecs.UsersRepositorySpecs at (UsersRepositorySpecs.scala:157)
...
Caused by: java.lang.Throwable: com.datastax.driver.core.exceptions.InvalidQueryException: No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename
</code>```

Body:
I am using embedded cassandra to run unit tests. I notice that if any cql statements fail, then I don't see any descriptive reason for failure. For eg. I am running the following two statements which fails because I am trying to add a table without switching to a keyspace

val statement1 =
        """
          |CREATE KEYSPACE test
          |  WITH REPLICATION = {
          |   'class' : 'SimpleStrategy',
          |   'replication_factor' : 1
          |  };
        """.stripMargin

      val statement3 =
        """
            |CREATE TABLE users (
            |    bucket int,
            |    email text,
            |    firstname text,
            |    lastname text,
            |    authprovider text,
            |    password text,
            |    confirmed boolean,
            |    id UUID,
            |    hasher text,
            |    salt text,
            |    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        """.stripMargin

val cqlStatements:CqlStatements = new CqlStatements(statement1,statement3)

")
      val testCassandra = repoTestEnv.testCassandra

      try {
        testCassandra.start()
        testCassandra.executeScripts(cqlStatements)
      } finally testCassandra.stop()

But I don't see correct error. I see the following which doesn't tell exactly what is the problem

[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is started
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is started (20811 ms)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[warn] c.d.d.c.Connection - /127.0.0.1:9042 did not send an authentication challenge; This is suspicious because the driver expects authentication (configured auth provider = com.datastax.driver.core.PlainTextAuthProvider)
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Script: CqlStatements [
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };
        ,
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )
        ]
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE KEYSPACE test
  WITH REPLICATION = {
   'class' : 'SimpleStrategy',
   'replication_factor' : 1
  };

[info] c.g.n.e.c.Cassandra - INFO  [Native-Transport-Requests-1] 2019-05-29 07:50:00,788 MigrationManager.java:310 - Create new Keyspace: KeyspaceMetadata{name=test, params=KeyspaceParams{durable_writes=true, replication=ReplicationParams{class=org.apache.cassandra.locator.SimpleStrategy, replication_factor=1}}, tables=[], views=[], functions=[], types=[]}
[debug] c.g.n.e.c.t.u.CqlUtils - Executing Statement:
CREATE TABLE users (
    bucket int,
    email text,
    firstname text,
    lastname text,
    authprovider text,
    password text,
    confirmed boolean,
    id UUID,
    hasher text,
    salt text,
    PRIMARY KEY ((bucket, email), authprovider,firstname, lastname) )

[debug] c.g.n.e.c.t.TestCassandra - Stop TestCassandra 3.11.1
[info] c.g.n.e.c.l.LocalCassandraDatabase - Stop Apache Cassandra '3.11.1'
[debug] c.g.n.e.c.l.RunProcess - Execute 'powershell -ExecutionPolicy Unrestricted C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\bin\stop-server.ps1 -p C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32\1da63488-2624-4141-a49e-174203b7edc4' within a directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32'
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,926 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,933 Server.java:176 - Stop listening for CQL clients
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,934 Gossiper.java:1532 - Announcing shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:03,938 StorageService.java:2268 - Node localhost/127.0.0.1 state jump to shutdown
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:05,941 MessagingService.java:984 - Waiting for messaging service to quiesce
[info] c.g.n.e.c.Cassandra - INFO  [ACCEPT-localhost/127.0.0.1] 2019-05-29 07:50:05,948 MessagingService.java:1338 - MessagingService has terminated the accept() thread
[info] c.g.n.e.c.Cassandra - INFO  [StorageServiceShutdownHook] 2019-05-29 07:50:06,076 HintsService.java:220 - Paused hints dispatch
[info] c.g.n.e.c.l.WindowsCassandraNode - Successfully sent ctrl+c to process with id: 7276.
[info] c.g.n.e.c.l.WindowsCassandraNode - Apache Cassandra Node '7276' is stopped
[info] c.g.n.e.c.l.LocalCassandraDatabase - Apache Cassandra '3.11.1' is stopped (3490 ms)
[info] c.g.n.e.c.l.LocalCassandraDatabase - The working directory 'C:\Users\manu\AppData\Local\Temp\embedded-cassandra\3.11.1\0d155e04-97d5-4927-87ac-d46824a77c32' was deleted.
[debug] c.g.n.e.c.t.TestCassandra - TestCassandra 3.11.1 is stopped

Unable to start TestCassandra 3.11.1
com.github.nosan.embedded.cassandra.CassandraException: Unable to start TestCassandra 3.11.1
    at com.github.nosan.embedded.cassandra.test.TestCassandra.start(TestCassandra.java:128)
    at UnitSpecs.RepositorySpecs.UsersRepositorySpecs.$anonfun$new$3(UsersRepositorySpecs.scala:146)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)

Ideally I should get the error similar to what I would get if I was using cqlsh

Is there a way to get more descriptive errors?

Body:
I haven't been able to find my Caused isn't printed but I have found this workaround

  try {
    testCassandra.start()
    println(s"cassandra state is ${testCassandra.getState}")
    testCassandra.executeScripts(cqlStatements)
    //println(s"result of execution is ${result}")
    //val settings = testCassandra.getSettings
    //println(s"settings are ${settings}")
  } catch {
    case e:Exception => {
      println(s"exception ${e} caused by ${e.getCause}")
      //println(s"caused by ${e.getCause()}")
     fail( new Throwable(e.getCause))
    }
  }finally {
    testCassandra.stop()

  }

the above prints

org.scalatest.exceptions.TestFailedException was thrown.
ScalaTestFailureLocation: UnitSpecs.RepositorySpecs.UsersRepositorySpecs at (UsersRepositorySpecs.scala:157)
...
Caused by: java.lang.Throwable: com.datastax.driver.core.exceptions.InvalidQueryException: No keyspace has been specified. USE a keyspace, or explicitly specify keyspace.tablename


问:
Error with RecyclerView: No adapter attached; skipping layout
I can't get my code work
I'm trying to get a list of my database activities.

A lot of research here and none of the answers helped me

My Adapter

```<code>public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {

    private Context mCtx;
    private List<Atividades> atividadesList;

    public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
        this.mCtx = mCtx;
        this.atividadesList = atividadesList;
    }

    @Override
    public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.atividades_lista, null);
        return new AtividadesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AtividadesViewHolder holder, int position) {
        Atividades atividades = atividadesList.get(position);
        holder.textViewAtividade.setText(atividades.getAtividade());
        holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
        holder.textViewHora.setText(String.valueOf(atividades.getHora()));
        holder.textViewDestinatarios.setText(atividades.getDestinatarios());
    }

    @Override
    public int getItemCount() {
        return atividadesList.size();
    }

    class AtividadesViewHolder extends RecyclerView.ViewHolder {

        TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;

        public AtividadesViewHolder(View itemView) {
            super(itemView);
            textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
            textViewData = itemView.findViewById(R.id.textViewData);
            textViewHora = itemView.findViewById(R.id.textViewHora);
            textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
        }
    }
}
</code>```

My activity

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

private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        loadAtividades();
    }

    private void loadAtividades() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject a = array.getJSONObject(i);
                                Log.d("Valores", a.getString("Atividade"));
                                atividadesList.add(new Atividades(
                                        a.getInt("idAtividade"),
                                        a.getString("Atividade"),
                                        java.sql.Date.valueOf(a.getString("dataPrevista")),
                                        java.sql.Time.valueOf(a.getString("hora")),
                                        a.getString("Destinatarios"),
                                        a.getString("Local")
                                ));
                            }
                            AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
                            recyclerView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        Volley.newRequestQueue(this).add(stringRequest);
    }
}
</code>```

Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.

答:
Please attach parent and the rest:</p>

```<code>@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new AtividadesViewHolder(LayoutInflater.from(mCtx).inflate(R.layout.atividades_lista, parent, false));
}
</code>```

Body:
I can't get my code work
I'm trying to get a list of my database activities.

A lot of research here and none of the answers helped me

My Adapter

public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {

    private Context mCtx;
    private List<Atividades> atividadesList;

    public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
        this.mCtx = mCtx;
        this.atividadesList = atividadesList;
    }

    @Override
    public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.atividades_lista, null);
        return new AtividadesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AtividadesViewHolder holder, int position) {
        Atividades atividades = atividadesList.get(position);
        holder.textViewAtividade.setText(atividades.getAtividade());
        holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
        holder.textViewHora.setText(String.valueOf(atividades.getHora()));
        holder.textViewDestinatarios.setText(atividades.getDestinatarios());
    }

    @Override
    public int getItemCount() {
        return atividadesList.size();
    }

    class AtividadesViewHolder extends RecyclerView.ViewHolder {

        TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;

        public AtividadesViewHolder(View itemView) {
            super(itemView);
            textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
            textViewData = itemView.findViewById(R.id.textViewData);
            textViewHora = itemView.findViewById(R.id.textViewHora);
            textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
        }
    }
}

My activity

public class AtividadesActivity extends AppCompatActivity {

private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        loadAtividades();
    }

    private void loadAtividades() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject a = array.getJSONObject(i);
                                Log.d("Valores", a.getString("Atividade"));
                                atividadesList.add(new Atividades(
                                        a.getInt("idAtividade"),
                                        a.getString("Atividade"),
                                        java.sql.Date.valueOf(a.getString("dataPrevista")),
                                        java.sql.Time.valueOf(a.getString("hora")),
                                        a.getString("Destinatarios"),
                                        a.getString("Local")
                                ));
                            }
                            AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
                            recyclerView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        Volley.newRequestQueue(this).add(stringRequest);
    }
}

Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.

Body:
Please attach parent and the rest:

@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
    return new AtividadesViewHolder(LayoutInflater.from(mCtx).inflate(R.layout.atividades_lista, parent, false));
}


问:
How to avoid StackOverflow Error in Recursive MazeSolver
Like many other java students in college, I need to develop a maze program that solves the maze. My solveMaze method that implements recursion returned a stackoverflow runtime error. How do I solve this problem please? Does this have to do with my algorithm? Thanks in advance.

A) I created a solution maze that array that's going to hold the path to the exit.

B) Then, I implemented a method solveMaze() that took a step toward the exit everytime it's called.

Note: The isWall() method checks if the position you're moving to is a wall or not.

  public void showPath() {
    int[][] sol = new int[m.length][m[0].length];
    for (int j = 0; j < sol.length; j++) {
      for (int i = 0; i < sol[0].length; i++) {
        sol[j][i] = m[j][i];
      }
    }
    if (solveMaze(sol, m.length - 1, 0, exitCords) == false)
      System.out.println("Solution doesn't exist");
    else {
      for (int y = 0; y < sol.length; y++) {
        for (int x = 0; x < sol[0].length; x++) {
          if (sol[y][x] == exitCords[0] && sol[y][x] == exitCords[1]) {
            System.out.print("E ");
          } else {
            if (sol[y][x] == 1) {
              System.out.print("  ");
            } else if (sol[y][x] == 3) {
              System.out.print("~");
            } else {
              System.out.print("# ");
            }
          }

        }
        System.out.println();
      }
    }
  }

  public boolean solveMaze(int[][] sol, int y, int x, int[] exitCords) {
    //exitCords[] is a one-dimensional array that holds the x and y coordinate of the exit point on a maze.
    if (y == exitCords[1] && x == exitCords[0]) {//Base Case
      return true;
    }
    //North
    if (!isWall(x, y - 1) && sol[y - 1][x] != 3) {
      sol[y][x] = 3;//3 is assigned to positions you already visited.
      y--;
      sol[y][x] = 3;
      //Implement recursion to call the solveMaze again on this line.
      solveMaze(sol, y, x, exitCords);
      return true;
    }

    //South
    else if (!isWall(x, y + 1) && sol[y + 1][x] != 3) {
      sol[y][x] = 3;
      y++;
      sol[y][x] = 3;
      solveMaze(sol, y, x, exitCords);
      return true;
    }
    //East
    else if (!isWall(x + 1, y) && sol[y][x + 1] != 3) {
      sol[y][x] = 3;
      x++;
      sol[y][x] = 3;
      solveMaze(sol, y, x, exitCords);
      return true;
    }
    //West
    else if (!isWall(x - 1, y) && sol[y][x - 1] != 3) {
      sol[y][x] = 3;
      x--;
      sol[y][x] = 3;
      solveMaze(sol, y, x, exitCords);
      return true;
    }
    /*The following line of code are to get out of dead ends and replace every position near a dead end with a wall*/
    else if ((isWall(x, y - 1) && isWall(x, y + 1) && isWall(x + 1, y)) || (isWall(x, y - 1) && isWall(x, y + 1) && isWall(x - 1, y))
        || (isWall(x - 1, y) && isWall(x, y + 1) && isWall(x + 1, y)) || (isWall(x - 1, y) && isWall(x, y - 1) && isWall(x + 1, y))) {

      if (isWall(x, y - 1) && isWall(x, y + 1) && isWall(x + 1, y)) {
        sol[y][x] = 0;
        solveMaze(sol, y, x - 1, exitCords);
        return true;
      }
      if (isWall(x, y - 1) && isWall(x, y + 1) && isWall(x - 1, y)) {
        sol[y][x] = 0;
        solveMaze(sol, y, x + 1, exitCords);
        return true;
      }
      if (isWall(x - 1, y) && isWall(x, y + 1) && isWall(x + 1, y)) {
        sol[y][x] = 0;
        solveMaze(sol, y - 1, x, exitCords);
        return true;
      }
      if (isWall(x - 1, y) && isWall(x, y - 1) && isWall(x + 1, y)) {
        sol[y][x] = 0;
        solveMaze(sol, y + 1, x, exitCords);
        return true;
      }
    }
    return false;
  }
```

答: A stack overflow error means that your recursion has gone deeper than the language allows.  For a small maze, this shouldn't happen, unless you are revisiting locations in the maze.  As your code does not seem to make any effort to avoid that, you might want to fix that.


问:
Java NullPointerException on BluetoothAdapter.isEnabled()
Hallo I have a problem with my code.
I want to check the app if it's enabled or not.
If bluetooth is enabled and a device is paired I want to connect to the device, if not I want to try to connect to it.

If my bluetooth device is on and I'm connected all works great and I'm getting the data, but if the device is off or not paired I'm getting this:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference.

hope you can help me.

Main Activity Fragment:

```<code>public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_wind, container, false);

........

   try
                {
                    findBT();
                    openBT();
                }
                catch (IOException ex) { }

        //Send Button

        //Close button
        closeButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    closeBT();
                }
                catch (IOException ex) { }
            }
        });
.........

void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null) {
            arduinodata.setText("Bluetooth Device not Found");
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth, 0);

        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("HC05"))
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        arduinodata.setText("Bluetooth Device Found");
    }

    void openBT() throws IOException
    {
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        arduinodata.setText("Bluetooth Opened");
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        final byte delimiter = 10; //This is the ASCII code for a newline character

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
                while(!Thread.currentThread().isInterrupted() && !stopWorker)
                {
                    try
                    {
                        int bytesAvailable = mmInputStream.available();
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == delimiter)
                                {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            arduinodata.setText(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }

    void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        arduinodata.setText("Bluetooth Closed");
    }
</code>```

答:
isEnabled() method of bluetooth adapter might be a Wrapper Boolean class which can have null value. If we check for true or false directly inside if condition, there is a possibility of null pointer exception as shown below:

Below code throws null pointer exception:

```<code>    Boolean val = null;

    if (val) {
        System.out.println("Will not work incase of null");
    }
</code>```

Below code works:

```<code>    if (null != val && val) {
        System.out.println("Works");
    }
</code>```

Body:
Hallo I have a problem with my code.
I want to check the app if it's enabled or not.
If bluetooth is enabled and a device is paired I want to connect to the device, if not I want to try to connect to it.

If my bluetooth device is on and I'm connected all works great and I'm getting the data, but if the device is off or not paired I'm getting this:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference.

hope you can help me.

Main Activity Fragment:

public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_wind, container, false);

........

   try
                {
                    findBT();
                    openBT();
                }
                catch (IOException ex) { }

        //Send Button

        //Close button
        closeButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                try
                {
                    closeBT();
                }
                catch (IOException ex) { }
            }
        });
.........

void findBT()
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null) {
            arduinodata.setText("Bluetooth Device not Found");
        }
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetooth, 0);

        }

        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("HC05"))
                {
                    mmDevice = device;
                    break;
                }
            }
        }
        arduinodata.setText("Bluetooth Device Found");
    }

    void openBT() throws IOException
    {
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        beginListenForData();

        arduinodata.setText("Bluetooth Opened");
    }

    void beginListenForData()
    {
        final Handler handler = new Handler();
        final byte delimiter = 10; //This is the ASCII code for a newline character

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
                while(!Thread.currentThread().isInterrupted() && !stopWorker)
                {
                    try
                    {
                        int bytesAvailable = mmInputStream.available();
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == delimiter)
                                {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            arduinodata.setText(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
                }
            }
        });

        workerThread.start();
    }

    void closeBT() throws IOException
    {
        stopWorker = true;
        mmOutputStream.close();
        mmInputStream.close();
        mmSocket.close();
        arduinodata.setText("Bluetooth Closed");
    }

Body:
isEnabled() method of bluetooth adapter might be a Wrapper Boolean class which can have null value. If we check for true or false directly inside if condition, there is a possibility of null pointer exception as shown below:

Below code throws null pointer exception:

    Boolean val = null;

    if (val) {
        System.out.println("Will not work incase of null");
    }

Below code works:

    if (null != val && val) {
        System.out.println("Works");
    }


问:
Unity 3D: what is the correct way to detect that the collision has already been processed for another collision participant?
I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.

In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.

```<code>private void OnCollisionEnter(Collision collision)
{
    // Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
    // ...

    // Play an impact sound and show a visual effect.
    if (thisObject.CollisionFrameId != Time.frameCount)
    {
        otherObject.CollisionFrameId = Time.frameCount;
        // play sound
        // show hit effect
    }
}
</code>```

Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.

Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.

答: Maybe you have 2 Colliders. If so you could check if boxcollider for example is colliding only. You could also try on Collision leave. Hope it helps.</p>

Body:
I have a class CollisionHandler which has the OnCollisionEnter method. Each collideable entity in the game has CollisionHandler as a component. So, when 2 objects collide the OnCollisionEnter method is called twice and it's ok because the damage and other things are processed as a result of touching object "B" by object "A" and vice versa.

In addition, each collision creates a flash effect and plays a sound of impact and of course, these effects are also played twice for each collision. Although it wouldn't be imperceptible to the player it doesn't seem to be correct anyway. In order to prevent it, I came up with the following solution: I save the current frame number in another collision participant so it will know that these effects have been played already by the first one.

private void OnCollisionEnter(Collision collision)
{
    // Calculate the damage caused by `this.gameObject` to `collision.gameObject`.
    // ...

    // Play an impact sound and show a visual effect.
    if (thisObject.CollisionFrameId != Time.frameCount)
    {
        otherObject.CollisionFrameId = Time.frameCount;
        // play sound
        // show hit effect
    }
}

Although it works I'm not sure (I'm a novice in Unity) that it's the best practice and if so please suggest other possible solutions.

Note that I didn't ask "Why is OnCollisionEnter getting called twice?". I know why it happens. My question is about the other, though it does mention the name of the same function it still doesn't asks the same.


问:
How to convert parts of a line to uppercase in a file
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

```<code>    # Queue name
    #
    queuename=sp00245b
</code>```

答:
```<code>awk '$1 == "queuename" {$2 = toupper($2)}1' FS== OFS== input-file
</code>```

Note that this will fail if there are 2 = in the line, and only the values between the first 2 = will be uppercased.  If that's an issue, it's an easy fix (left as an exercise for the reader).

Body:
I have a file file.txt and it has the lines below. I want the queuename to be converted to uppercase, like this: queuename=SP00245B

    # Queue name
    #
    queuename=sp00245b

Body:
awk '$1 == "queuename" {$2 = toupper($2)}1' FS== OFS== input-file

Note that this will fail if there are 2 = in the line, and only the values between the first 2 = will be uppercased.  If that's an issue, it's an easy fix (left as an exercise for the reader).


问:
Bit Difference between 2 binary numbers in MIPS Assembly
So I have to create an MIPS assembly program that reads 2 numbers out of 2 registers ($s0 & $s1) and calculates the number of bits that these 2 numbers differ by. And stores the result in the $s2 register.
I also have to fulfill all the above with the least amount of commands possible.
I have tried a few things on paper with XOR operations but I can't quite figure how to calculate the amount of different bits.

If anyone can help, you're more than welcome to.
Thanks in advance

答:
XOR the bits together and then count the number of bits in the resulting number. To do that, you can loop over each bit, check if it is set (by using a bitmask and bitshift), and then increment a counter.

I am purposefully leaving this vague as this is for you to figure out.


问:
Pass function parameter to then in Javascript
By default methodB takes text parameter. How do I pass title parameter as additional parameter from methodA to methodB ?

```<code>function methodA(link,title){
    return superagent.get(link).then(page => page.text).then(methodB); <== here
}

function methodB(text,title) {
    const promotions = [];
    const html = cheerio.load(text);

    html("#promolain > li > a > img").each((index, element) => {
        //console.log("scraping promo : "+element.attribs.title);
        promotions.push(element.attribs);
    });

    return promotions;
}
</code>```

答:
You can use a fat arrow function:</p>

```<code>function methodA(link,title){
    return superagent.get(link)
        .then(page => page.text)
        .then(text => methodB(text, title));
}
</code>```

Body:
By default methodB takes text parameter. How do I pass title parameter as additional parameter from methodA to methodB ?

function methodA(link,title){
    return superagent.get(link).then(page => page.text).then(methodB); <== here
}

function methodB(text,title) {
    const promotions = [];
    const html = cheerio.load(text);

    html("#promolain > li > a > img").each((index, element) => {
        //console.log("scraping promo : "+element.attribs.title);
        promotions.push(element.attribs);
    });

    return promotions;
}

Body:
You can use a fat arrow function:

function methodA(link,title){
    return superagent.get(link)
        .then(page => page.text)
        .then(text => methodB(text, title));
}


问:
Consultation python in csv .20 major movements by department
I need to get the 20 biggest 'MOV12' for 'DPTO', using python and pandas

I have a csv (.del) with the following fields

```<code>"CODCLI" "DPTO" "SEG" "TIPPER"  "MOV12"

11 20 "SEG1" "NAT" 6480.00
19 20 "SEG1" "NAT" 0.00
28 20 "SEG1" "NAT" 900.00
29 24 "SEG4" "NAT" 1800.00
31 20 "SEG1" "NAT" 3050.00
38 20 "SEG1" "NAT" 0.00
39 20 "SEG1" "NAT" 0.00
</code>```

I have a csv with the following fields, considering that the 'DPTO' is a total of 12 and I have thousands of data

for the moment and managed to obtain the moyor 'MOV12'

```<code>import pandas as pd

df = pd.read_csv("c.del", sep = ' ')
result=df.loc[df[['MOV12']].idxmax().unique()].groupby('DPTO')
print(result)
</code>```

I hope you give me suggestions to find the solution, thanks

答:
Use groupby and apply with nlargest

```<code>import pandas as pd
df = pd.read_csv("c.del", sep = ' ')
result=df.groupby('DPTO').apply(
    lambda x: x.nlargest(20,'MOV12')
)
</code>```

This will find the rows corresponding to the 20 largest values of 'MOV12' for every value of 'DPTO'.

Body:
I need to get the 20 biggest 'MOV12' for 'DPTO', using python and pandas

I have a csv (.del) with the following fields

"CODCLI" "DPTO" "SEG" "TIPPER"  "MOV12"

11 20 "SEG1" "NAT" 6480.00
19 20 "SEG1" "NAT" 0.00
28 20 "SEG1" "NAT" 900.00
29 24 "SEG4" "NAT" 1800.00
31 20 "SEG1" "NAT" 3050.00
38 20 "SEG1" "NAT" 0.00
39 20 "SEG1" "NAT" 0.00

I have a csv with the following fields, considering that the 'DPTO' is a total of 12 and I have thousands of data

for the moment and managed to obtain the moyor 'MOV12'

import pandas as pd

df = pd.read_csv("c.del", sep = ' ')
result=df.loc[df[['MOV12']].idxmax().unique()].groupby('DPTO')
print(result)

I hope you give me suggestions to find the solution, thanks

Body:
Use groupby and apply with nlargest

import pandas as pd
df = pd.read_csv("c.del", sep = ' ')
result=df.groupby('DPTO').apply(
    lambda x: x.nlargest(20,'MOV12')
)

This will find the rows corresponding to the 20 largest values of 'MOV12' for every value of 'DPTO'.


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答: I think the best way is to code a little, or as much as you can. Don't actually give them your code until you think you've got enough done. Sure its slow but its open source and doesn't actually have a deadline.</p>

OwnerDisplayName: Nikhil

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Lucas Aardvark


问:
Rails - How to do If and else statements in a text field
I am trying to do a if and else statement in this text field with the value:

```<code><%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>
</code>```

I get this error in view:

```<code>SyntaxError in Kategoris#show

Showing C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb where line #3 raised:

C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected keyword_else, expecting keyword_then or ';' or '\n'
...ue => if vind.ratings == 0 else vind.rating_score/vind.ratin...
...                               ^
C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected ',', expecting ')'
...vind.rating_score/vind.ratings, :type => 'range', :step => '...
...                               ^
</code>```

答:
I can do like this:

```<code><%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => "#{if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>
</code>```

or like above but in ():

```<code><%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => ((vind.ratings == 0) ? value_here : vind.rating_score/vind.ratings), :type => 'range', :step => '1', :id => "#{vind.id}" %>
</code>```

Body:
I am trying to do a if and else statement in this text field with the value:

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>

I get this error in view:

SyntaxError in Kategoris#show

Showing C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb where line #3 raised:

C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected keyword_else, expecting keyword_then or ';' or '\n'
...ue => if vind.ratings == 0 else vind.rating_score/vind.ratin...
...                               ^
C:/Rails/konkurranceportalen/app/views/kategoris/_rating.html.erb:3: syntax error, unexpected ',', expecting ')'
...vind.rating_score/vind.ratings, :type => 'range', :step => '...
...                               ^

Body:
I can do like this:

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => "#{if vind.ratings == 0 else vind.rating_score/vind.ratings, :type => 'range', :step => '1', :id => "#{vind.id}" %>

or like above but in ():

<%= f.text_field :rating, :size => 1, :min => 1, :max => 6, :value => ((vind.ratings == 0) ? value_here : vind.rating_score/vind.ratings), :type => 'range', :step => '1', :id => "#{vind.id}" %>


问:
How to fit a lot of header within cell width using VBA?
I have copied approximately 88 columns of content from another spreadsheet. The problem is the headers are too big and they are not showing in the column cell properly. So, I had to go to each cell and press Alt+Enter each time. I want to use a macro that will do it automatically.

I am using Microsoft Excel 2016 version.

```<code>Sub Fit_Headers()

   'Fit_Headers Macro

    Range("BI13").Select
    ActiveCell.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Range("BJ13").Select
End Sub
</code>```

I used "Record Macro" to record what I am doing in one cell. How can I modify it so I can use it for remaining cells?`

答:
Chr(10) is vbLf... and it doesn't quite play well with Range.AutoFit. vbNewLine (vbCrLf, i.e. Chr(10) & Chr(13)) works beautifully though; you don't need to Select anything, or to work off the ActiveCell at all - that's just macro-recorder junk begging to be cleaned up (recorder merely mimicks [most] user actions, including selecting cells: it doesn't care for redundant or efficient code):

```<code>Public Sub FitHeaders()
    With ActiveSheet.Range("BI13")
        .Value = "ACTUAL SAMPLE" & vbNewLine & "FABRIC INHOUSE DATE"
        .EntireColumn.AutoFit
    End With
End Sub
</code>```

Body:
I have copied approximately 88 columns of content from another spreadsheet. The problem is the headers are too big and they are not showing in the column cell properly. So, I had to go to each cell and press Alt+Enter each time. I want to use a macro that will do it automatically.

I am using Microsoft Excel 2016 version.

Sub Fit_Headers()

   'Fit_Headers Macro

    Range("BI13").Select
    ActiveCell.FormulaR1C1 = "ACTUAL SAMPLE " & Chr(10) & "FABRIC INHOUSE DATE"
    Range("BJ13").Select
End Sub

I used "Record Macro" to record what I am doing in one cell. How can I modify it so I can use it for remaining cells?`

Body:
Chr(10) is vbLf... and it doesn't quite play well with Range.AutoFit. vbNewLine (vbCrLf, i.e. Chr(10) & Chr(13)) works beautifully though; you don't need to Select anything, or to work off the ActiveCell at all - that's just macro-recorder junk begging to be cleaned up (recorder merely mimicks [most] user actions, including selecting cells: it doesn't care for redundant or efficient code):

Public Sub FitHeaders()
    With ActiveSheet.Range("BI13")
        .Value = "ACTUAL SAMPLE" & vbNewLine & "FABRIC INHOUSE DATE"
        .EntireColumn.AutoFit
    End With
End Sub


问:
Running Android emulator Hyper-V based on a Azure VM Windows Server 2016
Our goal is to run UI tests with Appium on our CI build. But it seems that running the Android emulator (Hyper-V based) within virtual build machine (Windows Server 2016) on Azure might not be supported.

So my question is, does Hyper-V based nested virtualization is supported from a Windows Server 2016 virtual machine on Azure ?

note: using a CPU Android emulation is not an option

答:
Yes, it is possible, you need to be on Dv3 or Ev3 SKU.

https://learn.microsoft.com/en-us/azure/virtual-machines/windows/nested-virtualization


问:
Matching an array/list of values in xpath expression
I am looking to match a list/array of values in my xpath expression and would like to know if that's possible.

My XML

```<code><Parent-tag>
        <Child-Tag>
            <status>Up</status>
            <prop-name>prop-1</prop-name>
        </Child-Tag>
        <Child-Tag>
            <status>Up</status>
            <prop-name>prop-2</prop-name>
        </Child-Tag>
        <Child-Tag>
            <status>Down</status>
            <prop-name>prop-3</prop-name>
        </Child-Tag>
        <Child-Tag>
            <status>Up</status>
            <prop-name>prop-4</prop-name>
        </Child-Tag>
</Parent-Tag>
</code>```

I would like an XPATH like below

```<code>/Parent-Tag/Child-Tag[prop-name=('prop-1', 'prop-2','prop-3')]/status
</code>```

I tried two xpath testers online:

(1) https://www.freeformatter.com/xpath-tester.html#xpath-examples

(2) https://www.webtoolkitonline.com/xml-xpath-tester.html

In (1), the above expression returned values, but in (2) it returned with a syntax error.

I am not sure if this is something to do with XPATH versions. Would you know if the latest XPATH supports this? If yes, is there an alternative to doing this in older XPATH versions?

This said, I understand this can be achieved like this (but not something I would like):

```<code>/Parent-Tag/Child-Tag[prop-name='prop-1' or prop-name='prop-2' or prop-name='prop-3')]/status
</code>```

答:
You can use contains as shown below. (Tested in chrome browser to make sure the xpath works in Xpath 1.0 as browser support xpath 1.0 only)

```<code>/Parent-Tag/Child-Tag[contains('prop-1, prop-2, prop-3',prop-name)]/status
</code>```

Evidence Browser Version:

Evidence XML Version:

Body:
I am looking to match a list/array of values in my xpath expression and would like to know if that's possible.

My XML

<Parent-tag>
        <Child-Tag>
            <status>Up</status>
            <prop-name>prop-1</prop-name>
        </Child-Tag>
        <Child-Tag>
            <status>Up</status>
            <prop-name>prop-2</prop-name>
        </Child-Tag>
        <Child-Tag>
            <status>Down</status>
            <prop-name>prop-3</prop-name>
        </Child-Tag>
        <Child-Tag>
            <status>Up</status>
            <prop-name>prop-4</prop-name>
        </Child-Tag>
</Parent-Tag>

I would like an XPATH like below

/Parent-Tag/Child-Tag[prop-name=('prop-1', 'prop-2','prop-3')]/status

I tried two xpath testers online:

(1) https://www.freeformatter.com/xpath-tester.html#xpath-examples

(2) https://www.webtoolkitonline.com/xml-xpath-tester.html

In (1), the above expression returned values, but in (2) it returned with a syntax error.

I am not sure if this is something to do with XPATH versions. Would you know if the latest XPATH supports this? If yes, is there an alternative to doing this in older XPATH versions?

This said, I understand this can be achieved like this (but not something I would like):

/Parent-Tag/Child-Tag[prop-name='prop-1' or prop-name='prop-2' or prop-name='prop-3')]/status

Body:
You can use contains as shown below. (Tested in chrome browser to make sure the xpath works in Xpath 1.0 as browser support xpath 1.0 only)

/Parent-Tag/Child-Tag[contains('prop-1, prop-2, prop-3',prop-name)]/status

Evidence Browser Version:

Evidence XML Version:


问:
Convert serialized() complex string to array of objects
I have a string:

```<code>"id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1"
</code>```

Now I want to get an array of objects to pass to controller via ajax like this:

```<code>[{"id":1, "lotcode"="ACB","location":"A1"},{"id":2, "lotcode"="CCC","location":"B1"}]
</code>```

I started by splitting the string

```<code>var string = data.split('&', 2);
</code>```

now I stuck here...

答:
You could split the string by & and then take the key/value pairs and assign them to an array with an incrementing index.

This solution assumes, that all keys have the same count.

var string = "id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1",
    result = [],
    indices = {};

string.split('&').forEach(s => {
    var [key, value] = s.split('='),
        index = (indices[key] || 0);

    result[index] = result[index] || {};
    result[index][key] = value;
    indices[key] = index + 1;
});

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a string:

"id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1"

Now I want to get an array of objects to pass to controller via ajax like this:

[{"id":1, "lotcode"="ACB","location":"A1"},{"id":2, "lotcode"="CCC","location":"B1"}]

I started by splitting the string

var string = data.split('&', 2);

now I stuck here...

Body:
You could split the string by & and then take the key/value pairs and assign them to an array with an incrementing index.

This solution assumes, that all keys have the same count.

var string = "id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1",
    result = [],
    indices = {};

string.split('&').forEach(s => {
    var [key, value] = s.split('='),
        index = (indices[key] || 0);

    result[index] = result[index] || {};
    result[index][key] = value;
    indices[key] = index + 1;
});

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Creating New Observations From Multiple Month Columns
I have a dataframe that does not have a single month column. It is divided into multiple month columns for each record, which prevents me from trending the data with a single month column and amount column. I have not been able to find any tips from the documentation or other questions as to how to accomplish this. Here is my code to create an example dataframe:

```<code> import pandas as pd

 data = [['tom', 1, 3, 4], ['nick', 5, 6, 7], ['juli', 6, 15, 10]]

 df = pd.DataFrame(data, columns = ['Name', 'mon1', 'mon2', 'mon3'])
</code>```

I want to have a data frame that has a single month column with mon1 as January mon2 as February and mon3 as March. I also would like the dataframe to have the numbers identified with a unique month to be put in an Amount column. I expect the number of observations to be 9 instead of three. For example Tom would have three unique observations because in January he would have an amount of 1 compared to 3 in February. Is it possible to write some kind of for loop to accomplish this?

Expected Example Dataframe:

```<code>  pd.DataFrame(data, columns=[‘Name’, ‘month’, ‘Amount’])
</code>```

Only with the previous data manipulated to fit the above format.

答:
IIUC, you can try with below:

```<code>import calendar
d={'mon'+str(e):i for e,i in enumerate(list(calendar.month_name))}
</code>```

```<code>df_new=df.rename(columns=d).melt('Name',var_name='Month',value_name='Amount')
print(df_new)
</code>```

```<code>   Name     Month  Amount
0   tom   January       1
1  nick   January       5
2  juli   January       6
3   tom  February       3
4  nick  February       6
5  juli  February      15
6   tom     March       4
7  nick     March       7
8  juli     March      10
</code>```

Note: print(d)

```<code>{'mon0': '',
 'mon1': 'January',
 'mon2': 'February',
 'mon3': 'March',
 'mon4': 'April',
 'mon5': 'May',
 'mon6': 'June',
 'mon7': 'July',
 'mon8': 'August',
 'mon9': 'September',
 'mon10': 'October',
 'mon11': 'November',
 'mon12': 'December'}
</code>```

Body:
I have a dataframe that does not have a single month column. It is divided into multiple month columns for each record, which prevents me from trending the data with a single month column and amount column. I have not been able to find any tips from the documentation or other questions as to how to accomplish this. Here is my code to create an example dataframe:

 import pandas as pd

 data = [['tom', 1, 3, 4], ['nick', 5, 6, 7], ['juli', 6, 15, 10]]

 df = pd.DataFrame(data, columns = ['Name', 'mon1', 'mon2', 'mon3'])

I want to have a data frame that has a single month column with mon1 as January mon2 as February and mon3 as March. I also would like the dataframe to have the numbers identified with a unique month to be put in an Amount column. I expect the number of observations to be 9 instead of three. For example Tom would have three unique observations because in January he would have an amount of 1 compared to 3 in February. Is it possible to write some kind of for loop to accomplish this?

Expected Example Dataframe:

  pd.DataFrame(data, columns=[‘Name’, ‘month’, ‘Amount’])

Only with the previous data manipulated to fit the above format.

Body:
IIUC, you can try with below:

import calendar
d={'mon'+str(e):i for e,i in enumerate(list(calendar.month_name))}

df_new=df.rename(columns=d).melt('Name',var_name='Month',value_name='Amount')
print(df_new)

   Name     Month  Amount
0   tom   January       1
1  nick   January       5
2  juli   January       6
3   tom  February       3
4  nick  February       6
5  juli  February      15
6   tom     March       4
7  nick     March       7
8  juli     March      10

Note: print(d)

{'mon0': '',
 'mon1': 'January',
 'mon2': 'February',
 'mon3': 'March',
 'mon4': 'April',
 'mon5': 'May',
 'mon6': 'June',
 'mon7': 'July',
 'mon8': 'August',
 'mon9': 'September',
 'mon10': 'October',
 'mon11': 'November',
 'mon12': 'December'}


问:
Connect to CRM and get data
I'm writing an ASP.NET app that should connect to dynamics CRM and fetch the contacts info. In the view it should return a list of the contacts with their info. There is some data in the testing CRM I'm provided with but I can't get the entities (e.g. table name and its columns), so I can't create my models in VS, since I don't know what props to put there.

Is there a way to get the entites with the code, or how can this problem be solved?

I've tried early-bound generator, and it won't work. I tried with ADO.NET entity data model but doesn't work either.

答:
In order to actually work with the CRM entities you're going to need to configure your project to work with an Organization Service (Might need a different tutorial depending on CRM version) that connects to your CRM instance.

Afterwards, like David Yenglin was explaining, you should be able to use methods like IOrganizationService.Retrieve(String, Guid, ColumnSet) which allows you to retrieve a record or IOrganizationService.RetrieveMultiple(QueryBase) which allows you to retrieve multiple records. In your case, I think you just need the Retrieve method.

Another way you can access the data is through the CRM Web API (which I have less experience with) which would allow you to query the data from CRM.

There's a ton of great examples of different scenarios over at Microsoft's github repo, PowerApps-Samples. I'd recommend checking it out later when you get your project configured.

Title: Connect to CRM and get data


问:
How to insert a list of values into a mysql database using python?
I don't know how to correctly insert values into a mysql database.

I think it's a pretty simple fix but I'm new to mysql.

...

```<code>sqllist = "INSERT INTO station_fenelon (date, time, outsidetemp, outsidehumidity) VALUES (%s, %s, %f, %f)"

record = [('2019-06-21', '12:12:11', '414.44', '42.4')]

cursor.execute(sqllist, record)
sql.commit()
</code>```

I get the error:
Not all parameters were used in the SQL statement

答:
I would recommend using an ORM (Object Relational Mapper) like SQLAlchemy. If you are writing to your database over a flask application, try using the flask_sqlalchemy extension to support your software. It's quite useful as it can be easily paired with the alembic library for database migrations.

If you use flask_sqlalchemy, then inserting into your database will become as simple as creating a new software object, and then adding it to your database session. Your database session I believe is a representation of your active connection, and adding to it is like writing to the log that is built on top of it. Then you would simply commit your changes to the log, and watch as they propagate into your database.

Body:
I don't know how to correctly insert values into a mysql database.

I think it's a pretty simple fix but I'm new to mysql.

...

sqllist = "INSERT INTO station_fenelon (date, time, outsidetemp, outsidehumidity) VALUES (%s, %s, %f, %f)"

record = [('2019-06-21', '12:12:11', '414.44', '42.4')]

cursor.execute(sqllist, record)
sql.commit()

I get the error:
Not all parameters were used in the SQL statement


问:
Configuration::get() returning empty value in Controller of PrestaShop 1.6
I am using PrestaShop 1.6.1.0

I have a field in my module supporting different languages, the postProcess() looks like this:

protected function postProcess()
{

  $languages = Language::getLanguages(false);
  $values = array();

  foreach ($languages as $lang)
  {
    $values['CUSTOMPAGECONFIGURATION_HEADING_TEXT'][$lang['id_lang']] = Tools::getValue('CUSTOMPAGECONFIGURATION_HEADING_TEXT_'.$lang['id_lang']);
  }
  Configuration::updateValue('CUSTOMPAGECONFIGURATION_HEADING_TEXT', $values['CUSTOMPAGECONFIGURATION_HEADING_TEXT'], true);
  return $this->displayConfirmation($this->l('The settings have been updated.'));
}
```

<p><strong>Problem:</strong></p>

<p>When I try to get this configuration variable value in a custom controller (path: <code>/controllers/front/CustomPageController.php</code>) like shown below, it is not fetching any results:</p>

<pre class="lang-php prettyprint-override"><code>$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT');
print_r($headtxt);
exit;
</code>```

It is not printing anything. I want to fetch this value in a controller, but it does not work and returns an empty string.

Site is using PrestaShop 1.6.1.0 and I tried many codes available. Am I missing something?

I am using this code in new controller created by me for custom page:

$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT');
print_r($headtxt);
exit;
```

I expect to output results of configuration variable which saved by the postProcess() method.

答:
Hi @Ankur and Welcome to SO!

In your postProcess() method, you are saving this Configuration value as a multilingual value.

However, while calling the Configuration::get() static method, it seems to me you forgot to mention the language ID, here's the function prototype:

```<code>public static function get($key, $idLang = null, $idShopGroup = null, $idShop = null, $default = false)
</code>```

This should work:

```<code>$id_lang = (int)$this->context->cookie->id_lang
$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT', $id_lang);
print_r($headtxt);
exit;
</code>```

Body:
I am using PrestaShop 1.6.1.0

I have a field in my module supporting different languages, the postProcess() looks like this:

protected function postProcess()
{

  $languages = Language::getLanguages(false);
  $values = array();

  foreach ($languages as $lang)
  {
    $values['CUSTOMPAGECONFIGURATION_HEADING_TEXT'][$lang['id_lang']] = Tools::getValue('CUSTOMPAGECONFIGURATION_HEADING_TEXT_'.$lang['id_lang']);
  }
  Configuration::updateValue('CUSTOMPAGECONFIGURATION_HEADING_TEXT', $values['CUSTOMPAGECONFIGURATION_HEADING_TEXT'], true);
  return $this->displayConfirmation($this->l('The settings have been updated.'));
}

Problem:

When I try to get this configuration variable value in a custom controller (path: /controllers/front/CustomPageController.php) like shown below, it is not fetching any results:

$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT');
print_r($headtxt);
exit;

It is not printing anything. I want to fetch this value in a controller, but it does not work and returns an empty string.

Site is using PrestaShop 1.6.1.0 and I tried many codes available. Am I missing something?

I am using this code in new controller created by me for custom page:

$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT');
print_r($headtxt);
exit;

I expect to output results of configuration variable which saved by the postProcess() method.

Body:
Hi @Ankur and Welcome to SO!

In your postProcess() method, you are saving this Configuration value as a multilingual value.

However, while calling the Configuration::get() static method, it seems to me you forgot to mention the language ID, here's the function prototype:

public static function get($key, $idLang = null, $idShopGroup = null, $idShop = null, $default = false)

This should work:

$id_lang = (int)$this->context->cookie->id_lang
$headtxt = Configuration::get('CUSTOMPAGECONFIGURATION_HEADING_TEXT', $id_lang);
print_r($headtxt);
exit;