text:
Q: How can I make use of promises more readable? I have the following code. Is there a better way to write it. It feels like when conditions and promises and querying from multiple tables are involved, the code becomes harder to read. Any help would be appreciated. Thanks!
fetchUserById = function (id) {
    var user = {};

    return knex_instance('user_info')
      .where('id', id)
      .first()
      .then(function (data) {
        if (!data) {
          return null;
        } else {
          user.info = data;
          return knex_instance('user_table')
            .where('id', id)
            .first()
            .then(function (values) {
              user.values = values;
              return user;
            });
        }
      })
      .catch(errorHandler('fetchUserById', id));
  }

A: Instead of increasing the indentation level with each request, you can return the request to the original promise chain and add a then there. Like this:
fetchUserById = function(id) {
  var user = {};

  return knex_instance('user_info').where('id', id).first()
    .then(function(data) {
      if (!data)
        return null;
      user.info = data;
      return knex_instance('user_table').where('id', id).first();
    })
    .then(function(values) {
      if (!values)
        return null;
      user.values = values;
      return user;
    });
    .catch(errorHandler('fetchUserById', id));
}

Problem with this approach, the null that can be returned by the first then must be passed through the second one (and the third, fourth, etc, if you had some). An alternate method would have been to use exceptions instead of returning null:
fetchUserById = function(id) {
  var user = {};

  return knex_instance('user_info').where('id', id).first()
    .then(function(data) {
      if (!data)
        throw "NO_USER_INFO";
      user.info = data;
      return knex_instance('user_table').where('id', id).first();
    })
    .then(function(values) {
      user.values = values;
      return user;
    });
    .catch(function(err) {
      if (err==="NO_USER_INFO")
        return null;
      else
        return errorHandler('fetchUserById', id);
    }
}

A: One way to increase readability is to separate part of the code into its own function.
I don't know what this function does, so I'm just going to call it doSomething. If you replace that with something descriptive it's easier to read in two places: The function itself describes the code it contains, and the call to the function indicates what's happening at that step in the calling code.
function doSomething(data)
{
    if (!data) {
        return null;
      } else {
        user.info = data;
        return knex_instance('user_table')
          .where('id', id)
          .first()
          .then(function (values) {
            user.values = values;
            return user;
      }
}

fetchUserById = function (id) {
  var user = {};

  return knex_instance('user_info')
    .where('id', id)
    .first()
    .then(doSomething)
    .catch(errorHandler('fetchUserById', id));
}


text:
Q: How to submit the same form multiple times on same page and also process them on that page in php I am trying to display a form and process data on same page multiple times.
This is my code:
<?php
function display($q) {
    $que=mysqli_fetch_row($q);
    $_SESSION['qid']=$que[0];
    ob_start ();
?>

<form method="post" action="">

 <?php echo $que[0]." . ".$que[2]; ?>

    <input type="radio" name="ans" value="<?php echo $que[3]; ?>"> <?php echo $que[3]; ?>

    <input type="radio" name="ans" value="<?php echo $que[4]; ?>"> <?php echo $que[4]; ?>

    <input type="submit" name="next" value="next" >
</form>

<?php
    $_SESSION['qid']=$que[0];
    echo $_SESSION['qid'];
    if(isset($_POST['next'])) {
        if(array_key_exists('next',$_POST)){
            next_que();
        }
    }
}

function next_que() {
    //some code
    // calling display function
}
?>

When I run this code, the display and next_que functions are working properly the first time, but on the next call only the display function is called displaying the form, and clicking the button doesn't turn the isset($_POST['next']) condition to true.
How can I get this to work?

A: Yes, prevent the form from submit via prevent default in your javascript. Then you can call your javascript functions / code on any button click and use the data in the same page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create multiple groups of clusters of different colors It is necessary that several clusters of groups of markers have different colors. For example, the gray markers are combined in grey circle - cluster, yellow - in yellow, and so on.
Here
.marker-cluster-small {
background-color: rgba(181, 226, 140, 0.6);
}
.marker-cluster-small div {
background-color: rgba(110, 204, 57, 0.6);
}

.marker-cluster-medium {
background-color: rgba(241, 211, 87, 0.6);
}
.marker-cluster-medium div {
background-color: rgba(240, 194, 12, 0.6);
}

.marker-cluster-large {
background-color: rgba(253, 156, 115, 0.6);
}
.marker-cluster-large div {
background-color: rgba(241, 128, 23, 0.6);
}

Specifies the colors for all the clusters. But how to make different colors for different clusters?
For example,
var groupGrey = new L.MarkerClusterGroup();
var groupRed = new L.MarkerClusterGroup();
var groupYellow = new L.MarkerClusterGroup();
var groupBlue = new L.MarkerClusterGroup();

A: See the iconCreateFunction option and its default implementation.


text:
Q: How to delete all rows from all tables in Azure SQL Database? I tried to use the answer given Here. But Azure SQL does not have 'sp_MSForEachTable'.
Any help would be appreciated

A: sp_MSForEachTable is a not documented stored procedure.
We can manually create it in Azure SQL database.
Bellow is the whole statement of the full sp_MSForEachTable:
Step 1: create [dbo].[sp_MSforeach_worker]:
CREATE proc [dbo].[sp_MSforeach_worker]
        @command1 nvarchar(2000), @replacechar nchar(1) = N'?', @command2 nvarchar(2000) = null, @command3 nvarchar(2000) = null, @worker_type int =1
    as

    create table #qtemp (   /* Temp command storage */
        qnum                int             NOT NULL,
        qchar               nvarchar(2000)  COLLATE database_default NULL
    )

    set nocount on
    declare @name nvarchar(517), @namelen int, @q1 nvarchar(2000), @q2 nvarchar(2000)
   declare @q3 nvarchar(2000), @q4 nvarchar(2000), @q5 nvarchar(2000)
    declare @q6 nvarchar(2000), @q7 nvarchar(2000), @q8 nvarchar(2000), @q9 nvarchar(2000), @q10 nvarchar(2000)
    declare @cmd nvarchar(2000), @replacecharindex int, @useq tinyint, @usecmd tinyint, @nextcmd nvarchar(2000)
   declare @namesave nvarchar(517), @nametmp nvarchar(517), @nametmp2 nvarchar(258)

    declare @local_cursor cursor
    if @worker_type=1
        set @local_cursor = hCForEachDatabase
    else
        set @local_cursor = hCForEachTable

    open @local_cursor
    fetch @local_cursor into @name

    while (@@fetch_status >= 0) begin

      select @namesave = @name
        select @useq = 1, @usecmd = 1, @cmd = @command1, @namelen = datalength(@name)
        while (@cmd is not null) begin      /* Generate @q* for exec() */
            select @replacecharindex = charindex(@replacechar, @cmd)
            while (@replacecharindex <> 0) begin

            /* 7.0, if name contains ' character, and the name has been single quoted in command, double all of them in dbname */
            /* if the name has not been single quoted in command, do not doulbe them */
            /* if name contains ] character, and the name has been [] quoted in command, double all of ] in dbname */
            select @name = @namesave
            select @namelen = datalength(@name)
            declare @tempindex int
            if (substring(@cmd, @replacecharindex - 1, 1) = N'''') begin
               /* if ? is inside of '', we need to double all the ' in name */
               select @name = REPLACE(@name, N'''', N'''''')
            end else if (substring(@cmd, @replacecharindex - 1, 1) = N'[') begin
               /* if ? is inside of [], we need to double all the ] in name */
               select @name = REPLACE(@name, N']', N']]')
            end else if ((@name LIKE N'%].%]') and (substring(@name, 1, 1) = N'[')) begin
               /* ? is NOT inside of [] nor '', and the name is in [owner].[name] format, handle it */
               /* !!! work around, when using LIKE to find string pattern, can't use '[', since LIKE operator is treating '[' as a wide char */
               select @tempindex = charindex(N'].[', @name)
               select @nametmp  = substring(@name, 2, @tempindex-2 )
               select @nametmp2 = substring(@name, @tempindex+3, len(@name)-@tempindex-3 )
               select @nametmp  = REPLACE(@nametmp, N']', N']]')
               select @nametmp2 = REPLACE(@nametmp2, N']', N']]')
               select @name = N'[' + @nametmp + N'].[' + @nametmp2 + ']'
            end else if ((@name LIKE N'%]') and (substring(@name, 1, 1) = N'[')) begin
               /* ? is NOT inside of [] nor '', and the name is in [name] format, handle it */
               /* j.i.c., since we should not fall into this case */
               /* !!! work around, when using LIKE to find string pattern, can't use '[', since LIKE operator is treating '[' as a wide char */
               select @nametmp = substring(@name, 2, len(@name)-2 )
               select @nametmp = REPLACE(@nametmp, N']', N']]')
               select @name = N'[' + @nametmp + N']'
            end
            /* Get the new length */
            select @namelen = datalength(@name)

            /* start normal process */
                if (datalength(@cmd) + @namelen - 1 > 2000) begin
                    /* Overflow; put preceding stuff into the temp table */
                    if (@useq > 9) begin
                        close @local_cursor
                        if @worker_type=1
                            deallocate hCForEachDatabase
                        else
                            deallocate hCForEachTable
                        return 1
                    end
                    if (@replacecharindex < @namelen) begin
                        /* If this happened close to beginning, make sure expansion has enough room. */
                        /* In this case no trailing space can occur as the row ends with @name. */
                        select @nextcmd = substring(@cmd, 1, @replacecharindex)
                        select @cmd = substring(@cmd, @replacecharindex + 1, 2000)
                        select @nextcmd = stuff(@nextcmd, @replacecharindex, 1, @name)
                        select @replacecharindex = charindex(@replacechar, @cmd)
                        insert #qtemp values (@useq, @nextcmd)
                        select @useq = @useq + 1
                        continue
                    end
                    /* Move the string down and stuff() in-place. */
                    /* Because varchar columns trim trailing spaces, we may need to prepend one to the following string. */
                    /* In this case, the char to be replaced is moved over by one. */
                    insert #qtemp values (@useq, substring(@cmd, 1, @replacecharindex - 1))
                    if (substring(@cmd, @replacecharindex - 1, 1) = N' ') begin
                        select @cmd = N' ' + substring(@cmd, @replacecharindex, 2000)
                        select @replacecharindex = 2
                    end else begin
                        select @cmd = substring(@cmd, @replacecharindex, 2000)
                        select @replacecharindex = 1
                    end
                    select @useq = @useq + 1
                end
                select @cmd = stuff(@cmd, @replacecharindex, 1, @name)
                select @replacecharindex = charindex(@replacechar, @cmd)
            end

            /* Done replacing for current @cmd.  Get the next one and see if it's to be appended. */
            select @usecmd = @usecmd + 1
            select @nextcmd = case (@usecmd) when 2 then @command2 when 3 then @command3 else null end
            if (@nextcmd is not null and substring(@nextcmd, 1, 2) = N'++') begin
                insert #qtemp values (@useq, @cmd)
                select @cmd = substring(@nextcmd, 3, 2000), @useq = @useq + 1
                continue
            end

            /* Now exec() the generated @q*, and see if we had more commands to exec().  Continue even if errors. */
            /* Null them first as the no-result-set case won't. */
            select @q1 = null, @q2 = null, @q3 = null, @q4 = null, @q5 = null, @q6 = null, @q7 = null, @q8 = null, @q9 = null, @q10 = null
            select @q1 = qchar from #qtemp where qnum = 1
            select @q2 = qchar from #qtemp where qnum = 2
            select @q3 = qchar from #qtemp where qnum = 3
            select @q4 = qchar from #qtemp where qnum = 4
            select @q5 = qchar from #qtemp where qnum = 5
            select @q6 = qchar from #qtemp where qnum = 6
            select @q7 = qchar from #qtemp where qnum = 7
            select @q8 = qchar from #qtemp where qnum = 8
            select @q9 = qchar from #qtemp where qnum = 9
            select @q10 = qchar from #qtemp where qnum = 10
            truncate table #qtemp
            exec (@q1 + @q2 + @q3 + @q4 + @q5 + @q6 + @q7 + @q8 + @q9 + @q10 + @cmd)
            select @cmd = @nextcmd, @useq = 1
        end
    fetch @local_cursor into @name
    end /* while FETCH_SUCCESS */
    close @local_cursor
    if @worker_type=1
        deallocate hCForEachDatabase
    else
        deallocate hCForEachTable

    return 0
  GO

Step 2: Create proc [dbo].[sp_MSforeachtable]
CREATE proc [dbo].[sp_MSforeachtable]
    @command1 nvarchar(2000), @replacechar nchar(1) = N'?', @command2 nvarchar(2000) = null,
  @command3 nvarchar(2000) = null, @whereand nvarchar(2000) = null,
    @precommand nvarchar(2000) = null, @postcommand nvarchar(2000) = null
AS
    declare @mscat nvarchar(12)
    select @mscat = ltrim(str(convert(int, 0x0002)))
    if (@precommand is not null)
        exec(@precommand)
   exec(N'declare hCForEachTable cursor global for select ''['' + REPLACE(schema_name(syso.schema_id), N'']'', N'']]'') + '']'' + ''.'' + ''['' + REPLACE(object_name(o.id), N'']'', N'']]'') + '']'' from dbo.sysobjects o join sys.all_objects syso on o.id = syso.object_id '
         + N' where OBJECTPROPERTY(o.id, N''IsUserTable'') = 1 ' + N' and o.category & ' + @mscat + N' = 0 '
         + @whereand)
    declare @retval int
    select @retval = @@error
    if (@retval = 0)
        exec @retval = dbo.sp_MSforeach_worker @command1, @replacechar, @command2, @command3, 0
    if (@retval = 0 and @postcommand is not null)
        exec(@postcommand)
    return @retval
GO

Then you won't get the message:  "The module 'sp_MSforeachtable' depends on the missing object 'dbo.sp_MSforeach_worker'. The module will still be created; however, it cannot run successfully until the object exists".
Ref: A Copy Of sp_MSforeachtable Stored Procedure For Azure, Uses sp_MSforeach_worker
I tested and it works in Azure SQL database:
Delete all the table data:
--Delete all the table data.
EXEC sp_msforeachtable 'DELETE FROM ?'

Data check:

Hope this helps.


text:
Q: Interoperate between C# and Java using web services without a Java EE application server? I'm in a difficult position:  We have a 3rd party enterprise system that exposes a Java-based API.  However, we are a 100% .Net oriented development team.  Essentially, I need to wrap the Java API with something that C# code can call.
Web services would be great, but the only Java application server supported on our infrastructure is WebSphere 6.1.  This means the ancient (and deprecated) JAX-RPC web service framework is the only way for us to expose web services.  Just getting a simple proof-of-concept working here has been a nightmare (because of Java inexperience, WebSphere being awful, JAX-RPC being clunky, and lots of JAR hell).
The new JAX-WS 2.0 web service framework in JAVA EE 5 looks great-- is there any way to run this without an entire Java application server?  For example, in .Net's WCF (Windows Communication Framework), you can host services pretty much anywhere you want (in-process, Windows Service, IIS 6/7 etc).
What is the most lightweight way to wrap this library with some web services?

A: Yes.
If you can create a Java method which is 1) annotated with @WebMetod and 2) takes the needed parameters and call into your 3'rd party code, and wrap it up as a web application you can use the Metro stack - https://metro.dev.java.net/ -  with any Servlet 2.5 web container (put it in the web containers global lib folder) to expose the above method as a web service.  We are using an embedded Jetty, but I've verified this works with Tomcat.
I wrote up my findings in http://archive.midrange.com/java400-l/200904/msg00071.html

I downloaded Metro 1.4 from https://metro.dev.java.net/1.4/ (version 1.5 is very new and I haven't looked at it), which eventually unpacks to several jar files.
Copy webservices-api.jar, webservices-rt.jar, webservices-extra-api.jar and webservices-extra.jar (four files) to the folder containing "blessed" jarfiles common to all of tomcat - I believe it is ${TOMCAT}/lib for Tomcat 6.[1]
In your Eclipse project eventually ending up to be a WAR file:

*

*If your workspace JRE is Java 5, you must add webservices-api.jar to the classpath (it should not be deployed in the end). If it is Java 6 you should be able to skip this step.

*Create a class foo.Ping looking like:

package foo;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 Ping is a simple web service class providing a "yes, we have contact" class.
 Currently the doPing() method provides a response with the host name and
 address (if available) and the current server time.

*/
@javax.jws.WebService
public class Ping {

@javax.jws.WebMethod(action = "doPing")
public String doPing() {
System.out.println("Ping.doPing() called.");

String hostName;
try {
  hostName = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
  hostName = "unknown (" + e.getMessage() + ")";
}

String hostAddress;
try {
  hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
  hostAddress = "unknown (" + e.getMessage() + ")";
}

return "Reached '" + hostName + "' (" + hostAddress + ") at "
    + new java.util.Date() + " java.version="
    + System.getProperty("java.version", "(not set)");
  }
}

*

*In your WEB-INF/web.xml add this snippet:

    <listener>
    <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
    </listener>
    <servlet>
    <description>JAX-WS endpoint - this servlet must handle all endpoints</description>
    <display-name>webservice</display-name>
    <servlet-name>webservice</servlet-name>
    <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- each endpoint must have a mapping to the JAX-WS endpoint servlet -->

    <servlet-mapping>
    <servlet-name>webservice</servlet-name>
    <url-pattern>/ws</url-pattern>
    </servlet-mapping>

*

*Create a NEW file WEB-INF/sun-jaxws.xml:

    <endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>
        <endpoint name='ping' implementation='foo.Ping'url-pattern='/ws'>
        </endpoint
    </endpoints>

*

*Ensure that both web.xml and sun-jaxws.xml are included in the deployment!

*Done!
Now deploy your war file to the Tomcat prepared above, and open "/ws" under your deployed web application. This might be http://localhost:8080/foo/ws;. This will give you a page with information including a link to WSDL for all web services, including the Ping. This link can be used directly in any WSDL processing tool, including the web service tool in Eclipse IDE for Java EE Developers and WSDCi.
Hope this helps you :)
[1] Not making them global WILL give you classloader problems!

A: I don't quite understand your statement "the only Java application server supported on our infrastructure is WebSphere 6.1" with respect to the question about how to run other stuff. But no, you don't need a full App Server just to expose a web service.
I think this is a good starting point for you: http://docs.codehaus.org/display/JETTY/J2se6HttpServerSPI

A: I ended up finding a solution that was far easier than any of the above.  We created some simple classes (like the doPing() method in @Thorbjørn Ravn Andersen's answer) with the @javax.jws.WebService and @javax.jws.WebMethod annotations, then deployed them using:
string url = "http://localhost:8282/MyService"
MyService serviceInstance = new MyService();
Endpoint svc = Endpoint.publish(url, serviceInstance);

I was then able to point Visual Studio at http://localhost:8282/MyService?wsdl and generate a client.  Easy as pie.
We have run a lot of requests through this service over a large span of time and have not noticed any problems.  We wrapped this with the Java Service Wrapper so that it comes back up across reboots/JVM crashes, etc.  A poor man's application server.
I hope this might help any other .NET developer looking to interoperate with Java without having to remap your brain to do it.

A: Since you can't update your version of the JDK, as I expect you are tied to what WebSphere needs, you may want to look at trying the axis famework, from apache.
This would require you to write a webservice that would just pass calls to the java code, but it should provide you the tools to get online, and it works well with older versions of java.
I expect that Jax-WS would be a problem unless by some miracle you are on JDK5 at least, then JAX-WS would be helpful, as the annotations makes the development more like the webservice model under .NET 2.0.


text:
Q: Javascript focus remove text highlight I have an input (text field) in update panel, and it autopostbacks after each change of text. I can keep focus on the same text field, but i can't get rid of text higlight which appears after calling document.getElementById('myTextField').focus().
This solution seemed to be the most accurate:
if (window.getSelection) {
    window.getSelection().removeAllRanges();
} else if (document.selection) {
    document.selection.empty();
}

But it has one problem. Input remains focused, but i can't write text. I have to click on it before writing.

A: You can  do it if you reset your value after focus, i.e.
HTML
<input id="myTextField" type="text" value="SomeValue" />

JS
var myInput=document.getElementById('myTextField');
var myInput_value=myInput.value;
myInput.focus();
myInput.value=myInput_value;

Working Example.

A: I'd argue that an ideal solution wouldn't involve unsetting and resetting the value of the input. This could have unwanted side-effects. Here's the proper way to move the caret in my opinion:
var input = document.getElementById('inputElement');
input.focus();
if(input.setSelectionRange) {
  input.setSelectionRange(input.value.length, input.value.length);
} else {
  var range = input.createTextRange();
  range.moveStart('character', input.value.length);
  range.moveEnd('character', input.value.length);
  range.select();
}


text:
Q: Hamiltonian and Supercharges Mirror Symmetry p.188
Eq. 10.109 states that
$$H \left\vert \alpha\right> = 0 \Longleftrightarrow Q \left\vert\alpha\right> = \overline{Q} \left\vert\alpha\right> =0. \tag{10.109}$$
I dont see why this is true, should not just
$$Q\overline{Q}\left\vert \alpha\right> = - \overline{Q} Q  \left\vert \alpha\right>$$ be true?

A: Suppose that $H = A^\dagger A$ for some matrix $A$ and assume that $H | v \rangle = 0$. Then
$$\langle v | H | v \rangle = 0.$$
So the norm of the vector $| v' \rangle \equiv A | v \rangle$ vanishes. But in a Hilbert space$\ldots$ (finish the argument yourself).

A: The book states on top of p. 188 that $\overline{Q}$ is the Hermitian adjoint operator $Q^{\dagger}$. Recall that a supernumber consists of body and soul. If $$0~=~2\langle \alpha|H|\alpha \rangle ~\equiv~ \langle \alpha|Q^{\dagger}Q|\alpha \rangle+\langle \alpha|QQ^{\dagger}|\alpha \rangle~\equiv~\underbrace{||Q|\alpha \rangle||^2}_{\geq 0}+\underbrace{||Q^{\dagger}|\alpha \rangle||^2}_{\geq 0},$$ then we must have both $Q|\alpha \rangle = 0$ and $Q^{\dagger}|\alpha \rangle = 0$.


text:
Q: Matplotlib Bar Customization This part of my code produces the bar chart in figure (1). I wonder how to modify it to produce the bar chart in figure (2) which is way more readable.
axs[4].set_xticks(range(N))
axs[4].set_xticklabels(words[inds],rotation = 'vertical')
axs[4].set_xlabel('word')
axs[4].set_yscale('log')
axs[4].set_ylabel('pagerank')
axs[4].set_title('Sorted PageRank biased by total word frequencies (c = '+str(c4)+')')
axs[4].bar(range(N),p4[inds],lw=2.5, align='center')

plt.subplots_adjust(hspace=.5)

plt.savefig('./figures/pageranks.pdf')

A: Using pylab.step instead of pylab.bar gives something a little closer to what you want. It takes the same arguments as bars but plots "steps" instead of "bars".
import pylab as p
ax = p.gca()
xbins = p.linspace(0.,10.,10)
step_heights = [10, 9, 9, 9, 7, 6, 6, 5, 4, 3]
ax.step(xbins, step_heights, linewidth=2.5, color="k",where="mid")
ax.set_ylim(0.,11.)

You may also want to look at the somewhat more complete pylab.hist documentation.

A: You can define your own function, and use plt.hlines to plot the horizontal lines. If you want to plot this in a certain axes, simply provide this axes as the argument to the ax parameter.
import matplotlib.pyplot as plt
import numpy as np

def bar_tops(x, y, width=0.8, align='center', ax=None, **kwargs):
    x = np.array(x)
    y = np.array(y)
    if align == 'center':
        left = x - 0.5 * width
        right = x + 0.5 * width
    elif align == 'edge':
        left = x
        right = x + width
    if ax == None:
        ax = plt.gca()
    ax.hlines(y, left, right, **kwargs)

Example usage:
bar_tops(np.arange(10), np.sort(np.random.rand(10)), lw=2)
plt.show()


text:
Q: Inhomogeneous Airy equation $y'' + t y = \cos(t) $ So, given the initial equation as $y'' + t y = \cos(t) $, I've got no clue as to how to handle this one.
I did some research into it, $y'' + xy =0 $ is an Airy equation that can be perfectly solved by different methods, i.e. series, Airy functions etc. Still, when it comes to an inhomogeneous guy, I am baffled.
What do I do?
I tried to utilize a series approach, but got stuck with the cosine $ t^{2n}$ part of the series
$$
2a_2 -1 +\sum_{n=1}^{\infty} t^n \left( \left(n+2\right)\left(n+1\right)a_{n+2}+a_{n-1} - \frac{\left(-1\right)^n t^n} {(2n)!}\right) = 0
$$
So it's of no use to me here.

A: Where did your last expression come from? When searching for a series solution you are supposed to explicitly write power series on both sides and carefully match coefficients.
Let's assume, for small $t$, the function can be written as:
$$y(t)=a_0+a_1t+a_2 t^2+ \cdots$$
Now we substitute this into the equation.
Up to first order we have: $$2a_2+6 a_3 t+a_0 t=1$$ Up to second order: $$2a_2+6 a_3 t+12 a_4 t^2+a_0 t+a_1 t^2=1-\frac{1}{2} t^2$$ and so on. Now we match the coefficients for the same powers of $t$. We can see here that: $$2a_2=1 \\ 6a_3+a_0=0 \\ 12 a_4+a_1=-\frac{1}{2}$$
If there's a general pattern, we can try to derive it. It's not always clear from the start, which is why I prefer writing down the first few terms explicitly.
In any case, I don't see what kind of trouble you had with your general expression? Yes, series for $\cos$ have only even powers. That just makes the equations easier to solve.
Note that we can write the cosine series as:
$$\cos t=\sum_{n=0}^\infty \frac{(-1)^n t^{2n}}{(2n)!}=\sum_{n=0}^\infty \frac{c_n t^n}{n!}$$
Where $c_{2k}=(-1)^k$ and $c_{2k+1}=0$, for $n=2k$ or $n=2k+1$.
Can you match the coefficients for your equation now?

Update
Another way would be to use the standard methods of solving inhomogeneous linear ODEs.
We search for a particular solution $y_p$, and write the general solution as a sum of the general solution of homogeneous equation $y_h$ and $y_p$.
$$y(t)=y_h(t)+y_p(t)$$
$$y_h(t)=C_1 \text{Ai} (-t)+C_2 \text{Bi} (-t)$$
Searching for $y_p$ might be done in various ways, for example, search in the form:
$$y_p(t)=C(t) \text{Ai} (-t)$$
Then:
$$C''\text{Ai} (-t) -2 C' \text{Ai}' (-t)= \cos t$$
Set:
$$C'(t)=f(t)$$
$$\text{Ai} (-t) f'-2 \text{Ai}' (-t) f= \cos t$$
This is a first order linear equation and can be solved in the usual way.
Of course, this method leads to some very awkward integrals, but it gives exact general solution in a manner of speaking.


text:
Q: how can I convert a date string in the format "1969-03-07T05:00:00.000Z" to the output normally provided by new Date() I am using mongodb to save my dates, and I do it by doing new Date()
how can I convert my date to string to the output of new Date()?

let date="1969-03-07T05:00:00.000Z";
let new_date=new Date(date); //in my code it returns "Invalid date"
console.log(new_date);
console.log(new Date());

A: You might use Date.parse() like:

let date = "1969-03-07T05:00:00.000Z";
let new_date = new Date(Date.parse(date));
console.log(new_date);
console.log(new Date());


text:
Q: am getting this error, can any one help? "Column count doesn't match value count at row 1" what i am trying to do is registering a new student to my database, hence storing it to the table student.
my php code, i dont know where is the error, though am not a pro in php language. here is all my php codes.
getting this error while trying to add records.
public function form(){
    $html = new Html();

    $html->div("row");
    $html->alert("message","Add New Student");

    $html->form("processstudent.php");

    $html->table("table table-bordered", "width:500px; margin:0 auto;");

    $html->input("", "hidden", "studentid", "");

    $html->row();
    $html->column(); echo "Firstname"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "firstname", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Lastname"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "lastname", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Emailaddress"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "emailaddress", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Password"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "password", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Dateofbirth"; $html->closecolumn();
    $html->column(); $html->input("form-control", "date", "dateofbirth", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Contact Number"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "contactnumber", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Address"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "address", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Gender"; $html->closecolumn();
    $html->column(); $html->input("form-control", "text", "gender", null); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Program"; $html->closecolumn();
    $html->column(); $html->selectprogram(); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Cohort"; $html->closecolumn();
    $html->column(); $html->selectcohort(); $html->closecolumn();
    $html->closerow();

    $html->row();
    $html->column(); echo "Department"; $html->closecolumn();
    $html->column(); $html->selectdepartment(); $html->closecolumn();
    $html->closerow();

    $html->row();

    $html->column(); $html->closecolumn(); $html->column(); $html->input("btn btn-primary", "submit", "addstudent", "Add"); $html->closecolumn();
    $html->closerow();

    $html->closetable();

    $html->closeform();
    $html->closediv();
}

///////// Add Student

public function add(){
    $mysql = new Mysql();
    $query = "insert into student VALUES ('','$this->firstname','$this->lastname','$this->emailaddress','$this->password','$this->dateofbirth','$this->contactnumber','$this->address','$this->gender','$this->cohort','$this->program','$this->department'); ";

    $mysql->execute($query);
    if($mysql->result)
        $mysql->successMessage ("Successfully inserted data");
}

}

?>

A: It means you're trying to insert an incorrect number of values in relation to the number of columns in the database.
It's better for readability to do it like this:
INSERT INTO table (column1, column2, column3) VALUES ($value1,$value2,$value3)

then you'll know your columns and values match properly.


text:
Q: Group custom fields in a Wordpress query I have a custom post type on a band site for displaying lyrics. This custom post type has custom fields like for example band. Naturally I'm able to retrieve all lyrics listed, but now I want to make a sorting functions. I want to have a drop down with the band names that has lyrics.
Therefore I want to get all band names from custom post-type lyrics, and group them (like in a MySQL group).
My code so far (this display all bands ungrouped):
<?php $bandQuery = new WP_Query(array('post_type' => 'lyrics', 'meta_key' => 'band', 'orderby' => 'meta_value', 'order' => 'ASC', 'posts_per_page' => '-1')); ?>
            <?php if(have_posts()) { while ( $bandQuery->have_posts() ) { $bandQuery->the_post(); ?>
                <?php $band = get_post_meta($post->ID, 'band', true); ?>

<?php echo get_the_title($band); ?>

        <?php }} // End the loop. ?>


text:
Q: Is there a "finitary" solution to the Basel problem? Gabor Toth's Glimpses of Algebra and Geometry contains the following beautiful proof (perhaps I should say "interpretation") of the formula $\displaystyle \frac{\pi}{4} = 1 - \frac{1}{3} + \frac{1}{5} \mp ...$, which I don't think I've ever seen before.  Given a non-negative integer $r$, let $N(r)$ be the number of ordered pairs $(a, b) \in \mathbb{Z}^2$ such that $a^2 + b^2 \le r^2$, i.e. the number of lattice points in the ball of radius $r$.  Then if $r_2(n)$ is the number of ordered pairs $(a, b) \in \mathbb{Z}^2$ such that $a^2 + b^2 = n$, it follows that $N(r^2) = 1 + r_2(1) + ... + r_2(r^2)$.
On the other hand, once one has characterized the primes which are a sums of squares, it's not hard to show that $r_2(n) = 4(d_1(n) - d_3(n))$ where $d_i(n)$ is the number of divisors of $n$ congruent to $i \bmod 4$.  So we want to count the number of divisors of numbers less than or equal to $r^2$ congruent to $i \bmod 4$ for $i = 1, 3$ and take the difference.  This gives
$\displaystyle \frac{N(r^2) - 1}{4} = \left\lfloor r^2 \right\rfloor - \left\lfloor \frac{r^2}{3} \right\rfloor + \left\lfloor \frac{r^2}{5} \right\rfloor \mp ...$
and now the desired result follows by dividing by $r^2$ and taking the limit.
Question:  Does a similar proof exist of the formula $\displaystyle \frac{\pi^2}{6} = 1 + \frac{1}{2^2} + \frac{1}{3^2} + ...$?
By "similar" I mean one first establishes a finitary result with a clear number-theoretic or combinatorial meaning and then takes a limit.

A: A somewhat different perspective to the Basel problem relates $\zeta(2)$ to the volume of $SL_2(\mathbb{R})/SL_2(\mathbb{Z})=\zeta(2)/2$. They compute this volume via a count of lattice points. One can also compute this via Gauss-Bonnet as a circle bundle over the modular curve $\mathbb{H}^2/PSL_2(\mathbb{Z})$ and deduce the Basel identity. There is some subtlety here about how the volume forms are defined in the comparison, but I think that this can be made into a proof.

A: I think that the 14th and last proof in Robin Chapman's collection is just that. It relies on the formula for the number of representations of an integer as a sum of four squares, which is kind of overkill, but anyway.


text:
Q: List is unchanged ever after element is changed While trying to implement an algorithm, I couldn't get python lists to mutate via a function. After reading up on the issue I was suggested by this StackOverflow answer to use [:] in order to mutate the array passed in the function argumemt.
However, as seen in the following code snippet, the issue still persists when trying to mutate the list l. I am expecting the output to be Before: [1,2,3,4]
After: [69, 69, 69, 69], but instead I get back the original value of l as shown below.
def mutate_list(a, b):
    c = [69] * 4
    a[:] = c[:2]  # changed the elements, but array's still unchanged outside function
    b[:] = c[2:]

if __name__ == '__main__':
    l = [1, 2, 3, 4]
    print("Before: {}" .format(l))
    mutate_list(l[:2], l[2:])
    print("After: {}" .format(l))

Output:
Before: [1, 2, 3, 4]
After : [1, 2, 3, 4]

Any insights into why this is happening?

A: The error is that you not pass actually the l but two slices of it. You should change it, for example:
def mutate_list(a):
    c = [69] * 4
    a[:2] = c[:2]
    a[2:] = c[2:]

if __name__ == '__main__':
    l = [1, 2, 3, 4]
    print("Before: {}" .format(l))
    mutate_list(l)
    print("After: {}" .format(l))

A: *

*its all about the scope, mutable concept is applicable on list but not to reference variable.

The variables a,b are local variables, hence the scope of the variable will be always function scope.

*The operations which you have performed :
a[:]=c[:2]
b[:]=c[2:]
Note: a and b both are list now so you will get following output in the function:
[69,69],[69,69]
but if you use + operator which is use for adding operations then the out out will be like:
[69,69,69,69]
Now whatever I told you that will be a local scope, if you want that the list should be mutable across the program then you have to specify the scope of the list as global inside function and on that variable you can do changes. in this case you also dont need to pass any arguments:
def mutate_list():
global l # telling python to use this global variable in a local function

c = [69] * 4

l=c      # assigning new values to actual list i.e l

Now before output will be [1,2,3,4]
and after will be [69,69,69,69]

A: As pointed out by others, the issue arose from the fact that the function parameters were slices of the original array and as such, the parameters were being passed by value (instead of being passed by reference).
According to @Selcuk 's suggestion, the correct way of doing such an operation would be to pass the original array along with its indices to the function and then perform any slicing inside the function.
NOTE: This concept comes in handy for (recursive) divide-and-conquer algorithms where subarrays must be mutated and combined to form the solution.


text:
Q: Extension can't access generic parameters at runtime I´m using AWS Cognito, in the doc it says I have to add this function.
But I´m getting this error:
Extension of a generic Objective-C class cannot access the class's generic parameters at runtime
extension AWSTask {
    public func continueWithExceptionCheckingBlock(completionBlock:@escaping (_ result: Any?, _ error: Error?) -> Void) {
        self.continue({(task: AWSTask) -> Any? in
            if let exception = task.exception {
                print("Fatal exception: \(exception)")
                kill(getpid(), SIGKILL);
            }
            let result: AnyObject? = task.result
            let error: NSError? = task.error as NSError?
            completionBlock(result, error)
            return nil
        })

    }
}

A: Without context I can't say if you are actually doing what the error message prompts you with, but there is an open bug report describing this issue (where no offending code is actually used):

*

*SR-2708: Extending ObjC generics in Swift 3 does not compile

ObjC:
@interface MySet<T : id<NSCopying>> : NSObject
@end

Swift:
class Foo { }
struct Bar { }

extension MySet {
    func foo() -> Foo { return Foo() }
    func bar() -> Bar { return Bar() }
}

Both of the extension methods result in "Extension of a generic Objective-C class cannot access the class's generic parameters at
runtime". However, neither really does anything like that (at least
not explicitly).

If you read the comments to the bug report, you'll see that a user named 'Vasili Silin' describes having this issue when attempting to extend AWSTask, so you might have to consider alternative approaches until this bug is resolved.

A: I just got the same error and solve it this way :

extension yourClass where T == yourType {}

A: For those who have this issue in Swift 5, try adding @objc modifier to the method. Please find the example below:
extension NSLayoutAnchor {

    @objc func constrainEqual(_ anchor: NSLayoutAnchor<AnchorType>, constant: CGFloat = 0) {
        let constraint = self.constraint(equalTo: anchor, constant: constant)
        constraint.isActive = true
    }
}


text:
Q: Is there a way to get a JSON value from under multiple keys and store it as a PHP value? I am new to the coding scene and am attempting to retrieve a particular value from a given JSON file and store it as a PHP variable to then add it to an SQL database.
I have gone through about half a dozen tutorials and they only seem to go 1 layer deep and get a value from their is that makes sense.
I am trying to get to the bolded values in php.
features{"attributes":{"Master_Incident_Number":"QF2-19-097369","IncidentType":"Vegetation Fire" ....
Full JSON file here
Is this possible, if so can someone please help point me in the path to do so.
Thank you

A: Use map to iterate over features.attributes to access keys Master_Incident_Number and IncidentType.

const input = {
  "features": [{
      "attributes": {
        "Master_Incident_Number": "QF4-20-011913",
        "IncidentType": "Vegetation Fire",
        "ResponseDate": 1580279411000,
        "LastUpdate": 1580357356000,
        "Location": "457 Ten Chain Rd, Kinleymore",
        "Region": "4 North Coast Region",
        "Latitude": -26.208141,
        "Longitude": 151.672965,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 1,
        "VehiclesOnScene": 0,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4726048",
        "OBJECTID": 1,
        "GlobalID": "5c6e0a07-aa7d-4e80-a44e-b652d2f0f18b",
        "Link": "https://"
      },
      "geometry": {
        "x": 151.672965,
        "y": -26.208141
      }
    },
    {
      "attributes": {
        "Master_Incident_Number": "QF4-20-012241",
        "IncidentType": "Permitted Burn (Attendance)",
        "ResponseDate": 1580353993000,
        "LastUpdate": 1580356129000,
        "Location": "22 Almond Rd, Benarkin North",
        "Region": "4 North Coast Region",
        "Latitude": -26.832734,
        "Longitude": 152.156489,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 0,
        "VehiclesOnScene": 4,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4798706",
        "OBJECTID": 2,
        "GlobalID": "2726c898-a6f4-4906-804f-d3f2e6c8a087",
        "Link": "https://"
      },
      "geometry": {
        "x": 152.156489,
        "y": -26.832734
      }
    },
    {
      "attributes": {
        "Master_Incident_Number": "QF6-20-012251",
        "IncidentType": "Vegetation Fire",
        "ResponseDate": 1580354969000,
        "LastUpdate": 1580358095000,
        "Location": "386 Main Western Rd, Tamborine Mountain",
        "Region": "6 South Eastern Region",
        "Latitude": -27.955333,
        "Longitude": 153.182491,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 2,
        "VehiclesOnScene": 1,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4813494",
        "OBJECTID": 3,
        "GlobalID": "e310dc73-695c-4466-8dc4-e6eb5344b406",
        "Link": "https://"
      },
      "geometry": {
        "x": 153.182491,
        "y": -27.955333
      }
    },
    {
      "attributes": {
        "Master_Incident_Number": "QF4-20-012274",
        "IncidentType": "Vegetation Fire",
        "ResponseDate": 1580357366000,
        "LastUpdate": 1580357666000,
        "Location": "2-21 Steindl St, Bundaberg East",
        "Region": "4 North Coast Region",
        "Latitude": -24.865996,
        "Longitude": 152.37337,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 1,
        "VehiclesOnScene": 0,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4828626",
        "OBJECTID": 4,
        "GlobalID": "a37695bd-ef88-49bd-813a-ca3133d42d83",
        "Link": "https://"
      },
      "geometry": {
        "x": 152.37337,
        "y": -24.865996
      }
    }
  ]
};

const output = input.features.map(({
  attributes: {
    Master_Incident_Number,
    IncidentType
  }
}) => console.log(Master_Incident_Number, IncidentType));

-- Edit --

const input = {
  "features": [{
      "attributes": {
        "Master_Incident_Number": "QF4-20-011913",
        "IncidentType": "Vegetation Fire",
        "ResponseDate": 1580279411000,
        "LastUpdate": 1580357356000,
        "Location": "457 Ten Chain Rd, Kinleymore",
        "Region": "4 North Coast Region",
        "Latitude": -26.208141,
        "Longitude": 151.672965,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 1,
        "VehiclesOnScene": 0,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4726048",
        "OBJECTID": 1,
        "GlobalID": "5c6e0a07-aa7d-4e80-a44e-b652d2f0f18b",
        "Link": "https://"
      },
      "geometry": {
        "x": 151.672965,
        "y": -26.208141
      }
    },
    {
      "attributes": {
        "Master_Incident_Number": "QF4-20-012241",
        "IncidentType": "Permitted Burn (Attendance)",
        "ResponseDate": 1580353993000,
        "LastUpdate": 1580356129000,
        "Location": "22 Almond Rd, Benarkin North",
        "Region": "4 North Coast Region",
        "Latitude": -26.832734,
        "Longitude": 152.156489,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 0,
        "VehiclesOnScene": 4,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4798706",
        "OBJECTID": 2,
        "GlobalID": "2726c898-a6f4-4906-804f-d3f2e6c8a087",
        "Link": "https://"
      },
      "geometry": {
        "x": 152.156489,
        "y": -26.832734
      }
    },
    {
      "attributes": {
        "Master_Incident_Number": "QF6-20-012251",
        "IncidentType": "Vegetation Fire",
        "ResponseDate": 1580354969000,
        "LastUpdate": 1580358095000,
        "Location": "386 Main Western Rd, Tamborine Mountain",
        "Region": "6 South Eastern Region",
        "Latitude": -27.955333,
        "Longitude": 153.182491,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 2,
        "VehiclesOnScene": 1,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4813494",
        "OBJECTID": 3,
        "GlobalID": "e310dc73-695c-4466-8dc4-e6eb5344b406",
        "Link": "https://"
      },
      "geometry": {
        "x": 153.182491,
        "y": -27.955333
      }
    },
    {
      "attributes": {
        "Master_Incident_Number": "QF4-20-012274",
        "IncidentType": "Vegetation Fire",
        "ResponseDate": 1580357366000,
        "LastUpdate": 1580357666000,
        "Location": "2-21 Steindl St, Bundaberg East",
        "Region": "4 North Coast Region",
        "Latitude": -24.865996,
        "Longitude": 152.37337,
        "CurrentStatus": "Going",
        "VehiclesOnRoute": 1,
        "VehiclesOnScene": 0,
        "CurrentWarning": "Information",
        "MediaMessage": "There is a vegetation fire at this location. Smoke may affect residents and motorists in the area. Residents should close their doors and windows and keep medication close by if suffering from a respiratory condition. Motorists should use caution and drive to conditions. If you believe your property is under threat, you should call Triple Zero (000) immediately.",
        "FMETimestamp": "20200130142217.4828626",
        "OBJECTID": 4,
        "GlobalID": "a37695bd-ef88-49bd-813a-ca3133d42d83",
        "Link": "https://"
      },
      "geometry": {
        "x": 152.37337,
        "y": -24.865996
      }
    }
  ]
};

const output = input.features.map((obj) => console.log(obj.attributes.Master_Incident_Number, obj.attributes.IncidentType));


text:
Q: Down arrow key won't work after using the Hyperlink button I found another odd bug... but I can only repro it in Firefox (40.0.2 for OSX). It doesn't occur in Chrome or Safari. I understand that, if it is a FF only thing, there's possibly nothing you guys can do about it, but I thought I'd put this out here anyway.
I use the magic hyperlink button to create links because they're pretty. Recently I've been noticing that, when I use it, I can't use ↓ until I click outside the text area.
The process is pretty simple:

*

*Write two lines of text (to make sure you have a "down" to go to).

*Highlight some of the text on the upper line.

*Click the hyperlink button or use Ctrl + L.

*Paste the link into the text area.

*Hit Enter/Return to close the dialogue. (Hitting the OK button will not repro the issue.)

*Try to use the down arrow….

*No response.

As long as you don't click out of the text input area, you will not be able to use the down button. Even using your mouse to move the cursor to another spot doesn't make it work. The other three direction arrows work fine.
This may or may not be related to this previous issue... I don't remember running into this issue until the last week or so.

A: Well, the bad news is that I suspect this is a Firefox bug.  The good news is, I figured out what's causing it and how to work around it.
Basically, if you remove an <input> element from the DOM while it has the focus, then no focusout event will be sent for that element, and I suspect that some internal focus-related code also fails to run.  In particular, if you then immediately call .focus() on a <textarea> (as the Markdown editor code does) it seems as if Firefox gets confused about what kind of an element has the focus and still thinks we're editing a single-line <input> where the up and down arrow keys don't work.
Or I might be wrong, and it might be some weird keypress event handler in SE code that gets confused.  But I suspect Firefox here, since 1) this bug does not occur on Chrome, and 2) I've looked very hard for that keypress handler, and I just can't find one.
In any case, explicitly calling .blur() on the URL input box before removing the dialog from the DOM fixes this bug.
Here's a single-line patch against Markdown.Editor.js that should solve this:
--- Markdown.Editor.js  2015-09-19 00:02:09.762614897 +0300
+++ Markdown.Editor.new.js  2015-09-19 00:01:19.362615469 +0300
@@ -1102,6 +1102,7 @@
                     text = 'http://' + text;
             }

+            input.blur();  // work around Firefox bug, see https://meta.stackexchange.com/q/264307
             dialog.parentNode.removeChild(dialog);

             callback(text);

I'd submit this directly to the Pagedown project, but the Google Code project is frozen, and AFAIK there isn't an official GitHub repo yet.  Hopefully balpha or someone will see this here and can apply it.

Ps. The way I ended up fixing this in SOUP is a bit more thorough:
var proto = document.body;
while ( proto && proto.removeChild && !proto.hasOwnProperty('removeChild') ) {
    proto = Object.getPrototypeOf( proto );
}
if ( !proto || !proto.removeChild ) return;

var oldRemoveChild = proto.removeChild;
proto.removeChild = function ( removed ) {
    var active = document.activeElement, node = active;
    while ( node && node !== removed ) node = node.parentNode;
    if ( node ) active.blur();
    return oldRemoveChild.apply( this, arguments );
};

Basically, this patches Node.removeChild() so that, if the currently focused element is a child of the element being removed, it will be properly defocused before it gets removed from the DOM.  This seems to fix the problem, and hopefully may also proactively fix similar bugs lurking in other parts of the SE interface.


text: Q: Example of compactly supported, closed, smooth $2$-form in $\mathbb{R}^3$ I want to find an example of compactly supported closed, smooth $2$-form in $\mathbb{R}^3$. I know that for a $2$-form $$w = a dx\wedge dy + b dx\wedge dz + c dy\wedge dz$$ and its exterior derivative is $$dw= (\frac{\partial a}{\partial z}-\frac{\partial b}{\partial y}+\frac{\partial c}{\partial x})dx\wedge dy\wedge dz$$ So I want to pick a compact supported, smooth function $\phi:\mathbb{R}^3 \to \mathbb{R}$ that is symmetric across $x,y,z$ and choose $\psi(x,y,z)=\phi(x,2y,z)$ such that $2\partial_x\psi= 2\partial_z\psi = \partial_y\psi$. Then choose $$w(p) = \psi(p) dx\wedge dy + \psi(p)  dx\wedge dz + \psi(p)  dy\wedge dz$$ and by equation above $dw = 0$ so $w$ is closed. I wonder if this is legitimate. The question is that the solution is not symmetric and there is $2y$ for seemingly no reason, so I think I probably did something wrong.


text:
Q: Unity Error CS1520: Method must have a return type I'm trying to trigger the transition from an idle animation to a running animation when the "d" button is being pressed.
(A link to a tutorial covering a transition like this could also work).
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

        public class IdleToJump : MonoBehaviour
    {
        bool keyHold = false;
        public Form1()
        {
        InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
        if (keyHold == true)
        {
            anim.Play("Run_Anim");
        }
    }

    private void Key_up(object sender, KeyEventArgs e)
    {
        Key key = (Key)sender;
        if (key == "d") {
            keyHold = false;
        }
        }

        private void Key_down(object sender, KeyEventArgs e)
        {
            Key key = (Key)sender;
            if (key == "d")
            {
                keyHold = true;
            }
        }
    }

A: Cross-check, you're code with this.
Form1 looks like a constructor that somehow got autogenerated. Just comment it out, and add the last two methods inside the class not outside.
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class IdleToJump : MonoBehaviour
    {
        bool keyHold = false;
        //public Form1()//Not sure this constructor is relevant in class, so just comment it
        //{
          //InitializeComponent();
        //}

        private void timer1_Tick(object sender, EventArgs e)
        {
         if (keyHold == true)
         {
            anim.Play("Run_Anim");
         }

    private void Key_up(object sender, KeyEventArgs e)
    {
        Key key = (Key)sender;
        if (key == "d") {
            keyHold = false;
        }
    }

    private void Key_down(object sender, KeyEventArgs e)
    {
            Key key = (Key)sender;
            if (key == "d")
            {
                keyHold = true;
            }
        }
    }
}


text:
Q: Is there a way to convert scientific notation to just the first few decimal places in Python? I have a list of 1111 values in scientific notation. Here are a few examples:
6.042968853864891e-12, 6.042894605467602e-12, 6.042777396826408e-12, 6.042616263531836e-12, 6.042410211830538e-12, 6.042158216350682e-12,

Is there a way I can convert this to just a list of 6.0429885, 6.04289460, 6.04277739,  6.04261626, 6.04241021, 6.04215821 (8 decimal places)? I don't want the scientific notation part (e-12).
I am ultimately trying to plot longitude on the x axis, latitude on the y-axis and have the points different sizes or colors based on density values (the density values are the numbers above in scientific notation). Here is a plot I have of just the longitude and latitude. I want to have this and each point be varying size depending on what the density is at that location.

A: Seems like you just need to multipy these numbers by 1e12 then round to 8 decimal places, right?
a = [6.042968853864891e-12, 6.042894605467602e-12, 6.042777396826408e-12, 6.042616263531836e-12, 6.042410211830538e-12, 6.042158216350682e-12,
]

b = [round(i*1e12,8) for i in a]

# if you want to scale your plot, then you shouldn't need to change the list itself, rather do this to your plot:

# if you have an ax, do:
ax.set_ylim([0,1e-11])
# this will give you a fixed y axis limit between 0 and 1e-11.


text:
Q: Live Server is Working but button is not showing on vscode? Earlier Live Server Button (Go Live) was easily visible but now it no more visible.
P.S.- It works with Cmd + L -> Cmd + O, but button in not visible.
What could be the possible reason behind this?????
Following is the setting (json of it)

A: Right click on the status bar at the bottom and make sure the Live Server (Extension) is selected. That will hide/unhide the 'Go Live' button on status bar.

A: you can also active your server by alt + L + O
keep in mind that you have to open with any folder either it have files or empty

A: In the case when you only open the file, not the the folder, not only Go Live icon will not be appeared in status bar but also even Live Server (Extension) will not be listed by right clicking on status bar.
So you have to open folder not just the file.

A: *

*Go to live-server > config tab in extension settings.

*Look for > Advance Custom Browser Cmd Line

*tap on Edit settings.json

*on 4th line you may find it...
"liveServer.settings.showOnStatusbar": false,

*In my case it was false and i changed it to 'true'

*Restart vscode and Enjoy...

Screenshot

A: @SomeEarth - Just to trump your dumbness I offer you, and any poor unfortunates who arrive here via google, this observation...
When the server is already active it displays Port: 5500 not Go Live
I know. I'll show myself out!

A: this guy explains it really well in his youtube channel, somewhere around 4:25 installing an extension called "live server" by Ritwick Dey https://www.youtube.com/watch?v=Du9mlokcHnI

A: Go to VSCode-> Extention-> Install "Live Server" , Restart VS Code
Then Right Click on Status Bar and Enable "Liver Server(Extension)"
Done. You will see "Go Live"

A: If Enabling the App in the taskbar, did not work for you:
Are you being asked to update your VS Code extensions?
Check the Cog icon in the bottom left of your window:

If a blue notification symbol is present:

*

*Click on the cog

*Scroll to the bottom of the menu

*Select Restart to Upgrade

Your app will reboot, and the Go Live option will repopulate.
Side note: I found this to be especially confusing, as it is possible to right click on your HTML file, while Go Live is not present, and Stop/Start your local server. This process has no visual affect, and the server does not load up.
Hope that this helps somebody out. Best of luck.

A: Just install/re-install the extension Live server from the settings -> extension. Then the button for Go Live will be available


text:
Q: Angular 14 application crashes when using ng2-charts upon loading     I saw a similiar problem but it was not with ng2-charts. I already spent more the 1
    day on what I believe is an environment issue. I need help big time.

    Crash Message:
    Error: NG0203: inject() must be called from an injection context (a constructor, a
    factory function or a field initializer). Find more at
    https://angular.io/errors/NG0203
at injectInjectorOnly (core.mjs:4751:15)
at Module.ɵɵinject (core.mjs:4762:12)
at Object.NgChartsModule_Factory [as useFactory] (ng2-charts.mjs:274:1)
at Object.factory (core.mjs:9324:38)
at R3Injector.hydrate (core.mjs:9237:35)
at R3Injector.get (core.mjs:9131:33)
at injectInjectorOnly (core.mjs:4757:33)
at ɵɵinject (core.mjs:4761:12)
at useValue (core.mjs:8897:65)
at R3Injector.resolveInjectorInitializers (core.mjs:9174:17)

index.js:551 [webpack-dev-server] Live Reloading enabled.
Code added to app-module.ts:
import { NgChartsModule }                        from 'ng2-charts';

@NgModule({  NgChartsModule, .......

Package.json
"dependencies": {
"@angular/animations": "14.1.0",
"@angular/common": "14.1.0",
"@angular/compiler": "14.1.0",
"@angular/core": "14.1.0",
"@angular/forms": "14.1.0",
"@angular/material": "14.1.0",
"@angular/material-moment-adapter": "14.1.0",
"material-design-icons": "3.0.1",
"@angular/platform-browser": "14.1.0",
"@angular/platform-browser-dynamic": "14.1.0",
"@angular/router": "14.1.0",
"@types/file-saver": "^2.0.5",
"core-js": "3.24.0",
"chart.js": "3.8.2",
"ng2-charts": "4.0.0",
"rxjs": "7.5.6",
"rxjs-compat": "6.6.7",
"tslib": "2.4.0",
"zone.js": "0.11.7",

Installation:
npm install --g @angular/cli@14.1.0
npm i --unsafe-perm --verbose
npm i @types/chart.js


text:
Q: DbComparisonExpression requires arguments with comparable types entity y c# Tengo un problema para poder realizar una query de entity, la cual le agregue una condicion de tipo contains para buscar los registros especificos que ingreso a traves de un textbox multiline y que separo mediante coma a traves de un método que me regresa una cadena, esto con el fin de poder buscarlos, pero me genera un error en la query que no he podido resolver

System.ArgumentException: 'DbComparisonExpression requires arguments with comparable types.'

public List<CambioEstatus> QueryResultados()
    {
        string situacion;
        if (RadCmbAccion.SelectedValue == "1")
        {
            situacion = "4";
        }
        else
        {
            situacion = "3";
        }
        string valoresCtas = regresa_info();

        CatalogoContainer entidad = new CatalogoContainer();
        List<CambioEstatus> query = (from c in entidad.CUENTA
                                     join ct in entidad.CUENTA_TIPO
                                     on c.id_CUENTA_TIPO equals ct.id_CUENTA_TIPO
                                     join ffp in entidad.FACTURA_FORMA_PAGO
                                     on c.id_FORMA_PAGO equals ffp.id_FORMA_PAGO
                                     join cs in entidad.CUENTA_SITUACION
                                     on c.id_CUENTA_SITUACION equals cs.id_CUENTA_SITUACION
                                     where c.id_CUENTA_SITUACION.Equals(situacion) && valoresCtas.Contains(Convert.ToString(c.id_CUENTA))
                                     select new CambioEstatus()
                                     {
                                         IDCUENTA=c.id_CUENTA.ToString()
                                     }).ToList();

      return query;
    }

en este metodo separo la informacion a traves de coma

public string regresa_info()
    {
        string todos = "";
        string todos_1 = "";
        string[] ar = RadTxtBuscar.Text.Split('\n');
        int g = ar.Length;
        string valor = "";

        int cont = 0;
        for (int i = 0; i < ar.Length; i++)
        {
            cont++;
            if (cont == g)
            {
                valor = ar[i].ToString().Replace('\r', ' ').Trim();
                todos_1 = "'" + valor + "'";
            }
            else
            {
                valor = ar[i].ToString().Replace('\r', ' ').Trim();
                todos_1 = "'" + valor + "',";
            }

            todos += "" + todos_1 + "";

        }
        return todos;
    }

esta clase son las propiedades para poder crear la lista generica

public class CambioEstatus
{
    public string IDCUENTA { get; set; }
    public string RFC { get; set; }
    public string RAZONSOCIAL { get; set; }
    public string TIPO { get; set; }
    public string FORMAPAGO { get; set; }
    public string ESTATUS { get; set; }
}

A: El problema esta en la traducción que intenta realizar Entity Framework  al convertir los tipos, ya que esto no puede ser transformado a SQL, por lo que deberías de intentar con esto:
List<CambioEstatus> query = (from c in entidad.CUENTA
                join ct in entidad.CUENTA_TIPO
                    on c.id_CUENTA_TIPO equals ct.id_CUENTA_TIPO
                join ffp in entidad.FACTURA_FORMA_PAGO
                    on c.id_FORMA_PAGO equals ffp.id_FORMA_PAGO
                join cs in entidad.CUENTA_SITUACION
                    on c.id_CUENTA_SITUACION equals cs.id_CUENTA_SITUACION
                where c.id_CUENTA_SITUACION.Equals(situacion)
                select new CambioEstatus()
                {
                    IDCUENTA=c.id_CUENTA.ToString()
                }).ToList();

query = query.Where(c=>valoresCtas.Contains(Convert.ToString(c.id_CUENTA))).ToList();


text:
Q: support v4 arraymap crashes in kitkat devices only Android app crashing with error class def not found: support v4 arraymap in kitkat devices only.
Gradle Dependencies:
compile files('libs/cometchat-sdk.jar')
compile files('libs/jsoup-1.7.3.jar')
compile files('libs/picasso-2.5.2.jar')
compile files('libs/volley.jar')
// compile files('libs/android-support-v4.jar')
compile 'com.paypal.sdk:paypal-android-sdk:2.12.4'
compile files('libs/gcm.jar')
compile 'com.parse.bolts:bolts-android:1.+'
compile 'com.parse:parse-android:1.+'
compile 'info.hoang8f:android-segmented:1.0.6'
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.prolificinteractive:material-calendarview:0.8.1'
compile 'com.android.support:gridlayout-v7:22.0.0'
compile 'com.android.support:cardview-v7:22.0.0'
compile 'com.melnykov:floatingactionbutton:1.3.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.google.android.gms:play-services-base:8.3.0'
compile 'com.google.android.gms:play-services-maps:8.3.0'
// compile 'com.facebook.android:facebook-android-sdk:4.6.0'
// compile 'com.google.android.gms:play-services-plus:8.3.0'
// compile 'com.google.android.gms:play-services-identity:8.3.0'
compile('com.google.android.gms:play-services:8.3.0')
compile('com.twitter.sdk.android:twitter:1.8.0@aar') {
    transitive = true;
}

Log cat:
Process: java.lang.NoClassDefFoundError: android.support.v4.util.ArrayMap at
com.google.android.gms.measurement.internal.zzd.(Unknown Source) at
com.google.android.gms.measurement.internal.zzx.zzh(Unknown Source) at
com.google.android.gms.measurement.internal.zzt.(Unknown Source) at
com.google.android.gms.measurement.internal.zzx.zzBQ(Unknown Source) at
com.google.android.gms.measurement.internal.zzt.zzaU(Unknown Source) at
com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source) at
android.content.ContentProvider.attachInfo(ContentProvider.java:1591) at
android.content.ContentProvider.attachInfo(ContentProvider.java:1562) at
android.app.ActivityThread.installProvider(ActivityThread.java:4774) at
android.app.ActivityThread.installContentProviders(ActivityThread.java:4369) at
android.app.ActivityThread.handleBindApplication(ActivityThread.java:4309) at
de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method) at
de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631) at
android.app.ActivityThread.handleBindApplication(Native Method) at
android.app.ActivityThread.access$1500(ActivityThread.java:135) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) at
android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:136) at
android.app.ActivityThread.main(ActivityThread.java:5001) at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:515) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at
de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132) at
dalvik.system.NativeStart.main(Native Method)

A: You are getting

Log cat: Process: java.lang.NoClassDefFoundError:
  android.support.v4.util.ArrayMap at
  com.google.android.gms.measurement.internal.zzd.(Unknown Source) at
  com.google.android.gms.measurement.internal.zzx.zzh(Unknown Source) at
  com.google.android.gms.measurement.internal.zzt.(Unknown Source) at
  com.google.android.gms.measurement.internal.zzx.zzBQ(Unknown Source)
  at com.google.android.gms.measurement.internal.zzt.zzaU(Unknown
  Source)

NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.
So import android.support.v4.util.ArrayMap instead of android.util.ArrayMap
Courtesy goes to Crash with Android 4.1 with ArrayMap #Blackbelt's Sir Answer .


text:
Q: InvalidOperationException in release-mode of visual studio since using .Net 4.0 I have some trouble to port an existing .NET 3.5 Application to .NET 4.0. The Code isn't written by myself so I didn´t know in detail why the things are as they are.
This is the Situation:
Code works fine if the application is started from Visual Studio (Release or Debug-Mode doesn't matter) and also if the application is started form Debug-folder
The Problem is the Release-deploy, because is doesn't work well since 4.0 (and also in 4.5) :-/
This is the initial call:
someObject.Text = Elements.GetElement(Int16.Parse(cb1.Text));

And Here is the code:
public class Elements : EnumBase<int, Elements>
{
    public static readonly Elements Element1 = Create("Number 0", 0);
    public static readonly Elements Element2 = Create("Number 1", 1);

    private static Elements Create(string text, int value)
    {
        return new Elements() { text = text, value = value };
    }

    public static String GetElement(int id)
    {

        // The Following Code safes the day and let the release deploy work fine.
        // It doesn´t matter if the condition becomes true or not to runtime.
        /*
        if (id == 999999999)
        {
            Elements el = Element1;
        }
        */

        // Release deploy works also fine if you do the following line in a loop instead of linq.
        return BaseItemList.Single(v => v.Value == id).Text;
    }
}

[Serializable()]
public class EnumBase<T, E> :  IEqualityComparer<E>
        where E : EnumBase<T, E>
{
    private static readonly List<E> list = new List<E>();
    protected string text;
    protected T value;

    protected static IList<E> BaseItemList
    {
        get
        {
            return list.Distinct(new EnumBase<T, E>(false)).ToList();
        }
    }

    protected EnumBase()
    {
        list.Add(this as E);
    }

    /// <summary>
    /// Constructor for distinct to avoid empty elements in the list
    /// </summary>
    private EnumBase(bool egal) {}

    public string Text
    {
        get { return text; }
    }

    public T Value
    {
        get { return value; }
    }

    #region IEqualityComparer<E> Member

    // ...

    #endregion
}

The key is return BaseItemList.Single(v => v.Value == id).Text;. It throws a InvalidOperationException, because in Release
public static readonly Elements Element1 = Create("Number 0", 0); and public static readonly Elements Element2 = Create("Number 1", 1); aren't ready. In the moment of the Exception is BaseItemList empty (BaseItemList.Count = 0).
I am not sure why this happened in release form bin-folder and not in release out of visual studio.
For tests I deactivated "Optimize code" in project-properties but it doesn't help.
Surely the construct isn't the best, but I want to know what is different in .Net 4.0 that bring the code to flatter.
Thanks for help

A: I believe the problem is that you're relying on the static initializer for Elements having run, despite the fact that you haven't referred to any fields within it. The type initializer in a type which doesn't have a static constructor is only guaranteed to run before the first static field access. Section 10.5.5.1 of the C# 5 specification:

If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

And section 10.12 has:

The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

*

*An instance of the class type is created.

*Any of the static members of the class type are referenced.

The implementation of type initialization changed in .NET 4, but it was only an implementation detail - your code was broken before, you just didn't know it.
If you change your code to have:
static Elements() {}

in the Elements class, then I believe it will work - because static constructors force type initialization to occur before immediately the first member access, rather than just "at some point before the first field access".
Personally I'm dubious about the general pattern, but that's a slightly different matter.


text:
Q: ASPNET Core 3.0 Model validation error with Inheritance I just moved to ASP.NET Core 3.0 and it seems that either model validation with inheritance is broken, or I am missing something. When I post the following model with IlVal00 = null, it says:

title=One or more validation errors occurred. status=400, The IlVal00 field is required.

public class Stock : BaseClass
{
    [Required]
    public string Ref { get; set; } = default!;
}

public class BaseClass
{
    public string? IlVal00 { get; set; }
}

But if I change my model to the following, it works:
public class Stock : BaseClass
{
     [Required]
     public string Ref { get; set; } = default!;

     public new string? IlVal00 { get; set; }
}

public class BaseClass
{
     public string? IlVal00 { get; set; }
}

But I need this to support inheritance. Does anyone have an idea for how to make this work?
Thanks.

A: As I went through a very close scenario, I will add here an answer just in case others run into the same or similar issues:
In my case, the problem involved a project with .NET Core 3.1 as Target Framework and inheritance was not part of the problem. My project had a NuGet package dll as one of its dependencies and such package had several models. Our controller endpoints had these models as parameters. However, requests sent to any of these endpoints (with any of those models as body) were giving rise to validation errors for non-nullable reference type properties.
The workaround to solve it was similar to the one suggested here:
https://github.com/dotnet/aspnetcore/issues/14812. I added the following option to AddControllers method, from Startup's ConfigureServices method:
services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

Note that, by using this workaround, it will be necessary to manually add [Required] attributes for nullable reference type properties around your application.
I also opened an issue on their repository:
https://github.com/dotnet/aspnetcore/issues/27448

A: try to use virtual like this:
public virtual string? IlVal00 { get; set; }


text:
Q: Problem storing the right value while simulating So I am simulating different random phone calls according a Poisson distribution. I'm checking every minute if there is a call or not and storing it in a dictionary.
This is an example of how my calls dictionary looks like:
{0: 0, 1: 0, 2: 1, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 2,
 10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0, 17: 0, ......

What I want to do, is if there have been calls that minute (value > 0) to store the time in a class instance. Each dictionary key corresponds to a minute .
Currently, this is the code I am using:
import numpy as np
import datetime as dt

# initial day and time of simulation
numberOfSimulationDays = 28
currentDay = 1
currentTime = 0

# 2. Timeslots & availability
hours = []
free = []
start_time = 0
end_time = 480
time = start_time
end = end_time

while time <= end:
    hours.append(time)
    free.append(True)
    time += 15

class Slot:
    def __init__(self, slot, available):
        self.slot = slot
        self.available = available

timeSlots = {}
rangeHours = np.size(hours)

for i in range(rangeHours):
    timeSlots[i] = Slot(hours[i],free[i])

# 2. Simualte calls
patient = {}
class Patient:
    def __init__(self, calltime, slot):
        self.calltime = calltime
        self.slot = slot
        self.arrivalTime = slot + np.random.normal(loc=0, scale=2.5,size=None)
        self.AppointmentWaitingTime = self.arrivalTime - calltime

class Schedule:
    @staticmethod
    def get_number_of_calls_in_minute():
        number_of_calls_in_minute =
            np.random.poisson(lam=28.345 / (9 * 24), size=None)
        return number_of_calls_in_minute

class SimulationEveryMinute:
    while currentDay <= numberOfSimulationDays:
        calls = {}
        currentTime = 0
        endOfDayTime = 540

        while currentTime < endOfDayTime:

            for i in range(endOfDayTime):
                calls[i] = Schedule.get_number_of_calls_in_minute()

            for call in calls:
                if call == 1:
                    for slot_index, Slot in timeSlots.items():
                        if timeSlots[slot_index].available == True:
                             patient[slot_index] =
                                 Patient(currentTime, Slot.slot)
                             timeSlots[slot_index].available = False
                        currentTime += 1
        currentDay = currentDay + 1

print(SimulationEveryMinute.calls)
print("Number of calls:", sum(SimulationEveryMinute.calls.values()))
print("Number of scheduled patients:", len(patient))
for i in patient:
    print("Calltime:", patient[i].calltime, "Slottime:",
          patient[i].slot, "Appointment waiting time:",
          patient[i].AppointmentWaitingTime)

The problem with this is that it just increments currentTime from 1 to 32 (I have 32 timeSlots) instead of storing the minute on which the call has been made.
Example of the output:
('Calltime:', 0, 'Slottime:', 0, 'Appointment waiting time:', 0.4138422146210218)
('Calltime:', 1, 'Slottime:', 15, 'Appointment waiting time:', 11.162701908696011)
('Calltime:', 2, 'Slottime:', 30, 'Appointment waiting time:', 27.40165239831842)
('Calltime:', 3, 'Slottime:', 45, 'Appointment waiting time:', 41.696420163160745)

Instead, it should give
('Calltime:', 2, 'Slottime:', 0, 'Appointment waiting time:', 0.4138422146210218)
('Calltime:', 9, 'Slottime:', 15, 'Appointment waiting time:', 11.162701908696011)
('Calltime:', 9, 'Slottime:', 30, 'Appointment waiting time:', 27.40165239831842)

Could anyone help me see what I am doing wrong?
Thank you

A: First of all, it appears that this is simply a matter of printing that call time from the Patient object, instead of the slot number:
print("Calltime:", ceil(patient[i].arrivalTime),
    "Slottime:",patient[i].slot, "Appointment waiting time:",
    patient[i].AppointmentWaitingTime)

Second, I don't understand the dict you're using.  If this is simply calls in any given minute, then use a list.  The list index is the minute number:
[0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, ...]

You can simplify several of your loops with better logic application and the occasional enumerate call -- that's an iterator that steps through both the index and value, such as
for slot_num, freq in enumerate(calls):

I suggest that you simplify your coding somewhat.  For starters, use incremental programming: write a block of code and make sure that the results are exactly what you want.  Don't write more code until you've debugged that one.
Second, do not use a class until you know that you require the additional features.  The posted code uses some classes that don't add anything to the simpler code within.

Your call generation code runs for every minute of the day, overwriting the original call frequencies.
    currentTime = 0

    while currentTime < endOfDayTime:

        # This generates a call frequency for every minute of the day.
        for i in range(endOfDayTime):
            calls[i] = Schedule.get_number_of_calls_in_minute()

        for call in calls:
            if call == 1:    # Should this be call >= 1 ??
                ...
                    currentTime += 1


text:
Q: VSCode can't find header files when they are in different folders I have a problem with VSC. I started to use it recently and well I have 1 issue with it. My project has multiple folders, those folder just contain .h and .c files, but sometimes I need that .c file from one folder would read functions from .h file from another folder, and well when I include .h file, compiler can't find it. example bellow:

the only thing that works is by including full path to that file:
#include "C:/Users/Name/Desktop/Project/Project_dir/components/configurations/I2C_master.h"
Is this normal for VSC or I don't know how to use linker?

A: I think your problem here is that you're writing the file path as if the two were located in the same directory.
If you are referencing a file from another directory you should write the relative path like this:
#include "../configurations/I2C_master.h"


text:
Q: time step for Brownian motion Given a stochastic differential equation:
$$
dx=a(x,t)dt+b(x,t)dW(t)
$$
where $x$ is a random variable, $a(x,t)$ is a function of $x$ and $t$; called drift term, and $b(x,t)$ is the diffusion term. Brownian motion is $dW(t)$.
Is there a relationship between the time increment $dt$ and the time step for Brownian motion? In another way is it correct that:
$$
\delta t=\sqrt dt
$$
where $\delta t$ is Brownian motion time step.

A: In rough words, so you can confirm your intuition, if you were asked to simulate the process on a timegrid (a bunch of "dt"), you will simulate $dW_t$ using $dW_t=\sqrt{dt}Y$ where Y is normally distributed (mean 0, variance 1).


text:
Q: Room - RxJava : getByName() query not working I'm using Room for persistence in my app. I have a Player table, which has a name and matchesPlayed column.
When a match is played by a Player, I would like to increment matchesPlayed if it was played by an existing Player, or create a new Player otherwise. In order to determine this, I created a SQL query getPlayerByName(name: String) which should return us the Player if it exists. When I run the query in the Database Inspector in Android Studio, everything works fine. However, when I run the same query in the app, it fails. Does anybody know what I'm doing wrong?
 Player.kt
@Entity(tableName = "players")
data class Player(
    @PrimaryKey val id: String,
    val name: String,
    @ColumnInfo(name = "matches_played") val matchesPlayed: String,
    @ColumnInfo(name = "matches_won") val matchesWon: String
)

 PlayerDao.kt
@Dao
interface PlayerDao {
    @Query("SELECT * FROM $PLAYER_TABLE_NAME")
    fun getAll(): Single<List<Player>>

    @Query("SELECT * FROM $PLAYER_TABLE_NAME WHERE name = :name LIMIT 1")
    fun getPlayerByName(name: String): Maybe<Player>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(player: Player): Completable
}

 PlayerViewModel.kt
@HiltViewModel
class PlayerViewModel @Inject constructor(
    private val playerRepository: PlayerRepositoryImpl
) : ViewModel() {

    ...

    private fun findAndInsertPlayer(
        playerName: String,
        playerWon: Boolean
    ) {
        viewModelScope.launch {
            val increment = if (playerWon) 1 else 0
            playerRepository.getPlayerByName(playerName)
                .subscribe(
                    { player ->
                        // Handle Success
                    },
                    {
                        // Somehow, this block always gets called
                    }
                )
        }
    )
}


text:
Q: How can you create an API Health check in azure? What is the best way to test API endpoints within azure? I am looking to get alerted if an endpoint is not working.

A: Take a look at webtest feature in Application Insights.
https://learn.microsoft.com/en-us/azure/application-insights/app-insights-monitor-web-app-availability

A: I suggest you create a WebJob to test your API endpoints. In your WebJob, you could use a TimerTrigger to run the test function timely(For example, every 2 minutes).
To use TimerTrigger, you need to install Microsoft.Azure.WebJobs.Extensions package using NuGet. After that, you could configure the WebJob to use the timer extension using following code.
static void Main()
{
    var config = new JobHostConfiguration();
    //Configure WebJob to use TimerTrigger
    config.UseTimers();
    var host = new JobHost(config);
    // The following code ensures that the WebJob will be running continuously
    host.RunAndBlock();
}

In the function, you could send a request to your Web API. If you can't get the response from the server or the response status is not equal to 200 OK, it means that the Web API is not useable.
public static void StartupJob([TimerTrigger("0 */2 * * * *", RunOnStartup = true)] TimerInfo timerInfo)
{
    WebRequest request = WebRequest.Create("URL of your api");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response == null || response.StatusCode != HttpStatusCode.OK)
    {
        //API is not useable
    }
}

A: you can write a custom Azure Function to report Telemetry to Application Insight. See:
https://github.com/rbickel/Azure.Function.AppInsightAvailabilityTest


text:
Q: Convert datetime column in seconds (?) to pandas date time I have the following:
import pandas as pd
import io
s = pd.read_csv(
    io.StringIO(",Unnamed: 0,date\n0,0,13837781820.0\n1,1,13837781880.0\n")
)["date"]

I don't know what the date should be other than

*

*it certainly isn't 1970.

*it certainly isn't in the future

*it certainly is within the last year.

pd.to_datetime(s)

returns
0   1970-01-01 00:00:13.837781820
1   1970-01-01 00:00:13.837781880
Name: date, dtype: datetime64[ns]

which is wrong.
from datetime import datetime

datetime.fromtimestamp(s[0])

returns
datetime.datetime(2408, 7, 2, 13, 17)

which is wrong.
Edit
Adding something which is a bit more concrete -
I would expect:
13838574120.0

to convert to
2021-04-23 16:22:00

A: If my guess is correct, then what you have is seconds from 14. October 1582. A common way of representing dates in the Unix world is seconds from 1. January 1970, so if we can find the difference between those dates in seconds, we can subtract that number from what you have, and take it from there.
To find the difference, we could sit down with pencil and paper and think really hard about leap year rules, or we could let the computer do the work for us:
import datetime

# This really should be zero, but just for good measure...
unix_epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
assert unix_epoch.timestamp() == 0

lilian_epoch = datetime.datetime(1582, 10, 14, tzinfo=datetime.timezone.utc)
delta = unix_epoch.timestamp() - lilian_epoch.timestamp()

Now let's try it with your sample date
print(datetime.datetime.fromtimestamp(13838574120.0 - delta))
# prints 2021-04-23 18:22:00

Why is it two hours off? I'm in Stockholm, and fromtimestamp gives local time, but timestamp values are supposed to be UTC. You'll have to adjust for timezone, somehow.

A: Seems like an issue in number of digits because 10 digit epoch time is required if you want your datetime in seconds and 13 digit epoch time is required for the resulting time to be in miliseconds. I just removed the last digit and it worked.
pd.to_datetime(s//10, unit = "s")


text:
Q: How do I make a username-checker in Python using status-codes? I'm trying to make a program that checks username availability on Ubisoft.com.
I tried to do this by entering a profile URL letting the code check whether the site gives a 200- or a 404 status code, with 404 being a Taken username and 200 an Available username.
The problem with using a 200 status code for this is that the page that says it's a 404 is in fact a 200 status code.
Does anyone know a way to make it print ("AVAILABLE") if an username exists (like https://ubisoftconnect.com/en-US/profile/test) and print ("TAKEN") if an username is taken (like https://ubisoftconnect.com/en-US/profile/test1241924)
The code I currently have and used for the 200 and 404 source code:
(urllib.request.urlopen("https://ubisoftconnect.com/en-US/profile/test1241924").getcode())

if (urllib.request.urlopen("https://ubisoftconnect.com/en-US/profile/test1241924").getcode()) == 200:
    print ("TAKEN")
if (urllib.request.urlopen("https://ubisoftconnect.com/en-US/profile/test1241924").getcode()) == 404:
    print ("AVAILABLE!")

A: Well first of all I'd recommend using the python requests module for this. You can implement something similar to this in urlib3 as well:
import requests

r = requests.get('https://ubisoftconnect.com/en-US/profile/test1241924')

text = r.text

if 'Nothing is broken' in text:
    print('taken')
else:
    print('available')

This is one way of doing it

A: urlib is a good choice but for more simple code use requests
example:
import requests
r = requests.get("https://ubisoftconnect.com/en-US/profile/test1241924")
if r.status_code == 404:
   print("Available"}
elif r.status_code == 200:
    print("Taken")

i also recommend using headers!


text:
Q: How to get .bench file from verilog file Test.v is here:
module test(input A, B, C, D, E, output Y);
    assign Y = ((A^B)&C)^(D&E);
endmodule

Firstly I get .blif file by yosys (I use mycells.lib because I want only simple gates in bench file):
read_verilog test.v
hierarchy -check -top test
proc; opt; memory; opt;
techmap; opt
dfflibmap -liberty ../yosys/manual/PRESENTATION_Intro/mycells.lib
abc -liberty ../yosys/manual/PRESENTATION_Intro/mycells.lib
write_blif test.blif

I get the following test.blif file:
# Generated by Yosys 0.9+3746 (git sha1 ec410c9b, gcc 9.3.0-17ubuntu1~20.04 -fPIC -Os)

.model test
.inputs A B C D E
.outputs Y
.names $false
.names $true
1
.names $undef
.subckt NAND A=D B=E Y=$abc$80$new_n7_
.subckt NOR A=A B=B Y=$abc$80$new_n8_
.subckt NAND A=A B=B Y=$abc$80$new_n9_
.subckt NAND A=C B=$abc$80$new_n9_ Y=$abc$80$new_n10_
.subckt NOR A=$abc$80$new_n8_ B=$abc$80$new_n10_ Y=$abc$80$new_n11_
.subckt NAND A=$abc$80$new_n7_ B=$abc$80$new_n11_ Y=$abc$80$new_n12_
.subckt NOR A=$abc$80$new_n7_ B=$abc$80$new_n11_ Y=$abc$80$new_n13_
.subckt NOT A=$abc$80$new_n13_ Y=$abc$80$new_n14_
.subckt NAND A=$abc$80$new_n12_ B=$abc$80$new_n14_ Y=Y
.end

I exit "yosys" and enter "yosys-abc" to generate .bench file. But I got the model error below:
abc 01> read_blif test.blif
Line 10: Cannot find the model for subcircuit NAND.
Reading network from file has failed.
abc 01>

How can I get test.bench file? Thanks..

A: It's related to your library (mycells.lib) and generating blif file. Your blif file should have ".gate" instead of ".subckt".
You can use this command:

write_blif -gates test.blif


text:
Q: Find all positions of a value in a list in Prolog My assignment is this: Write a program that reads an integer x and a list of integers L; then locate the list of all positions of x into L, and return the resulting list. For example, for x=2 and L=[1,2,3,4,2,5,2,6] the program should return the list R=[2,5,7].
So far, I've been able to write an indexOf predicate:
indexOf([E|_], E, 1).
indexOf([_|T], E, I) :- indexOf(T, E, I2), I is I2 + 1.

However, this doesn't "return" a list. So:
indexOf([a,b,c,a,d], a, R).
R = 1;
R = 4

I'd like to do something like this:
findAll([a,b,c,a,d], a, R).
R = [1, 4]

But I'm not sure how to collect the values into a list.
This is a school assignment, so I'd appreciate just a nudge in the right direction.

A: A nudge: you find the indices, but you don't collect them.
indices(List, E, Is) :-
    indices_1(List, E, Is, 1).

For an empty list, the list of indices is empty,
and the element doesn't matter
indices_1([], _, [], _).

If the element is like the head, collect the index.
indices_1([E|Xs], E, [I|Is], I) :-
    I1 is I + 1,
    indices_1(Xs, E, Is, I1).

This needs another clause to work properly.
EDIT:
One way to do it would be:
indices_1([X|Xs], E, Is, I) :- dif(X, E),
    I1 is I + 1,
    indices_1(Xs, E, Is, I1).

In the previous clause, the head of the list and the Element are unified. In this clause, they are explicitly different. This means that only one of the two clauses can be true for an element of the list in the first arguemnt.
EDIT:
Another way to do that is to use findall and nth1:
indices(List, E, Is) :-
    findall(N, nth1(N, List, E), Is).


text:
Q: jquery passing single value arrays via ajax I've seen a lot of posts about how to pass arrays via ajax in jquery.  This is not exactly about those questions.  Is the following reasonable behaviour or am I doing something wrong?
I have some simple jquery ...
var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
    url: url,
    data: {
        ids: changedIds
    },
    dataType: "json",
    traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
    window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
    console.log("Submit Fail: ");
});

The changedIds array will end up with 0-N integers in it.  I check the .length before the POST so a zero length array is not sent.  My question is about what happens when there is only ONE value.
It appears that having a single value array treats the "array" like a plain variable.  The HTTP request lists the data as:
ids=123

The target of this ajax call is a .Net ActionResult method that wants an array value.  It pouts and throws an exception if it is handed what looks like a plain variable.
I have started checking the array .length and if it is 1 then pushing in a known dummy value so that there are two values for the array.  This seems to work -- but is this correct behaviour?  Is this the best work-around?

A: Try serializing your data parameter using JSON.stringify and specifying a contentType of application/json as follows:
var changedIds = new Array();
...
changedIds.push(123);
...
$.post({
    url: url,
    data: JSON.stringify({
        ids: changedIds
    }),
    contentType: "application/json",
    dataType: "json",
    traditional: true
}).done(function(ajaxData, textStatus, jqXhr) {
    window.location.reload();
}).fail(function(jqXhr, textStatus, errorThrown) {
    console.log("Submit Fail: ");
});

That should convert the JavaScript object into valid JSON and tell the server the type of data that you are sending.


text:
Q: VisualStudios ERROR MainViewModel doesnt exist Hy Guys i installed VS three times and everytime the same Error
I installed MVVM Light in the NUGET Manager for the MVVM
After installing i set the DataContext in the Main.Window on MainViewModel
That works now. But in my App.xaml is it not possible to get the Resource Dictonary in it. In attachment screenshots of my problem.
appxaml ( <= Full size image)

and...

A: Try to declare 'vm' namespace before usage, put it in Application tag.

A: Replace <vm: with <local: as the "local" namespace is aleady mapped at the root element in App.xaml:
<Application x:Class="testapp.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:testapp.ViewModel"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <local:ViewModelLocator x:Key="Locator" />
    </Application.Resources>
</Application>