text:
Q: How to access the calendar of a Microsoft Exchange on-premise installation With EWS being deprecated, what is a currently working and future-proof way to create applications that interact with the Exchange calendar without using a hybrid deployment?
MS is obviously heavily pushing the Graph API, but it only seems to work when Exchange is connected to the cloud in one way or another (hybrid deployment, O365, Exchange online). Older answers to similar questions point to the REST API, which also is deprecated.

A: Good question.  In order to support Graph on-prem Windows AD would need to support OAuth.  I thought I had read something about that being supported in E2019 (at least for EWS), but frankly, I've not really looked into it.  EWS will likely have to be fully supported, albeit stabilized, indefinitely until Graph can run on-prem.  Suggest you search thru MS Graph blogosphere for more concrete info, because that seems to be where everything in the Office world is converging.


text:
Q: Run supervisor outside docker whereas nimbus runs as a docker container I'm trying to run nimbus as container in docker and trying to use my machine as supervisor. I've tried the following. I've a docker compose that sets up nimbus and zookeeper containers
  nimbus:
    image: storm:2.4.0
    platform: linux/x86_64
    container_name: nimbus
    command: storm nimbus
    depends_on:
      - zookeeper
    links:
      - zookeeper
    restart: always
    ports:
      - '6627:6627'

    networks:
      - storm

  zookeeper:
    image: bitnami/zookeeper:3.6.2
    container_name: zookeeper
    ports:
      - '2181'
    volumes:
      - ~/data/zookeeper:/bitnami/zookeeper
    environment:
      - ALLOW_ANONYMOUS_LOGIN=yes
    networks:
      - storm

  ui:
    platform: linux/x86_64
    image: storm:2.4.0
    container_name: ui
    command: storm ui
    links:
      - nimbus
      - zookeeper
    restart: always
    ports:
      - "9090:8080"

    networks:
      - storm

I've exposed the two with ports. When I try to run storm supervisor from terminal, with localhost as nimbus seed and zookeeper server in storm.yaml, I get the following log and am not able to start the supervisor.
2022-11-03 19:15:55.866 o.a.s.s.o.a.z.ClientCnxn main-SendThread(localhost:2181) [INFO] Socket error occurred: localhost/127.0.0.1:2181: Connection refused
2022-11-03 19:15:55.971 o.a.s.d.s.Supervisor main [ERROR] supervisor can't create stormClusterState
2022-11-03 19:15:55.975 o.a.s.u.Utils main [ERROR] Received error in thread main.. terminating server...
java.lang.Error: java.lang.RuntimeException: org.apache.storm.shade.org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /storm
    at org.apache.storm.utils.Utils.handleUncaughtException(Utils.java:663) ~[storm-client-2.3.0.jar:2.3.0]
    at org.apache.storm.utils.Utils.handleUncaughtException(Utils.java:667) ~[storm-client-2.3.0.jar:2.3.0]
    at org.apache.storm.utils.Utils.lambda$createDefaultUncaughtExceptionHandler$2(Utils.java:1047) ~[storm-client-2.3.0.jar:2.3.0]
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1055) [?:?]
    at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:1050) [?:?]
    at java.lang.Thread.dispatchUncaughtException(Thread.java:1997) [?:?]

I'm able to access the ui as localhost:9090. Can someone please tell me how to resolve this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connecting to SQL Server Named Instance from Windows 64bit I have both java and .net applications running on an app server using Microsoft Windows Server 2003, Enterprise Edition.  These are being migrated to another app server Windows 2008 64-bit machine.
All applications connect to the same SQL Server 2005 database, on a named instance.
So far I have tried to move the applications exactly as they are, with no changes in the configuration files, from the old box to the new box.
On the new app server, neither the java nor the .net applications connect to the database (named instance).

JDBC error message: "The connection to the named instance has failed. Error: java.net.SocketTimeoutException: Receive timed out."
The .net error message: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible."

If I change the DB config to one that is not on a named instance it works on the new app server.
The database is setup correctly, because we were able to connect on the old app server.  I can ping the database server from the new app server.
Is there any reason this won't work on the new app server?

java connection string: "jdbc:microsoft:sqlserver://[dbservername];SelectMethod=Cursor;instanceName=[dbinstance]"
.net connection string: "Server=[dbservername]\[dbinstance];Database=Risk_DB;Uid=[user];Pwd=[pwd];"

UPDATE
Per suggestions in the answers, I got the instance port number.  I also installed SQL Server Management Studio so I can eliminate my apps as the problem points.  From Management Studio, if I use [servername][instancename], I get the message "a network-related or instance-specific error while establishing a connection to SQL Server..."  But it works when i use [servername],[port].  Not sure if there's anyway to work around this?
UPDATE #2 Escalated the issue to the infrastructure/server/network team. They disabled windows firewall on the new app server.  Presto, now I can connect to [dbservername]\[dbinstance] in Management Studio, and all apps are working using existing configuration files.

A: Your named instance is going to be running on a different port. Port 1433 (the default for a default instance) is probably open, and the port that the named instance is running on is probably blocked. You can check the port in the error log for the named instance (assuming you can connect locally, in Object Explorer, expand the server, expand Management, expand SQL Server Logs, right-click current, and choose "View SQL Server Log" IIRC), it will say something like this on startup:
Server is listening on [ 127.0.0.1 <ipv4> 3587 ].

That last number is the port number that needs to be accessible from your remote machine and whatever network devices and services it has to go through to get there. If you don't find a line like that, it's possible that TCP/IP is not enabled for the named instance. On that server, go to SQL Server Configuration Manager, expand SQL Server Network Configuration, click on "Protocols for " and make sure TCP/IP is enabled in the right pane. If you have to enable this you'll need to restart SQL Server for it to take effect.
If it is already enabled (or once you enable it and restart the service), you should be able to refresh this view and validate the port that is being used if you right-click TCP/IP, hit properties, and move to the IP Addresses tab. You can see the ports currently being for each IP. Here there will be multiple IPn sections and an IPAll section. For each IP, you can change the "TCP Port" box to a port you want to use (and delete any values in all the "Dynamic TCP Ports" box to 0). Hit Apply and restart the service. This will again require a restart of the service but will allow you to specify a specific port so you can add an exclusion to your firewall (or make use of one that already exists, assuming this server isn't already using that port).

A: Possible issues:

*

*Firewall maybe blocking connections.

*The instance name is not the same as specified in the connection string.

*The connection string specifies a different port or SQL Server is running on a different port rather than the default 1433


text:
Q: ASP.NET MVC Signalr reconnect and negotiate throwing a System.OutOfMemoryException I have an ASP.NET MVC application working on a Web Garden configuration. The application pool identity is set to a custom domain account (with local administator permissions). Application pool has 4 worker processes. Session state mode is set to serverState using the ASP.NET State service which runs on the same machine (not remote one).
Regarding to signalr I have noticed an OutOfMemoryException in the event log when trying to reconnect and negotiate and I am not being able to detect what is happening. Any help will be highly appreciated.
Some texts below in the errors are in Spanish (Sorry).
Below the reconnect error:
Event code: 3005
Event message: Excepción no controlada.
Event time: 05/11/2020 13:28:04
Event time (UTC): 05/11/2020 12:28:04
Event ID: 447eb425512c433387a36b70af64f768
Event sequence: 1
Event occurrence: 1
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/2/ROOT-2-132490528843179653
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\inetpub\wwwroot\MyMVCApp\
    Machine name: MyServer

Process information:
    Process ID: 1668
    Process name: w3wp.exe
    Account name: MyDomain\MyAppPoolCustomIdentity

Exception information:
    Exception type: InvalidOperationException
    Exception message: El método de inicialización Run previo al inicio de la aplicación del tipo WebActivatorEx.ActivationManager produjo una excepción con el siguiente mensaje de error: Se produjo una excepción de tipo 'System.OutOfMemoryException'..
   en System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures)
   en System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods)
   en System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded)
   en System.Web.Compilation.BuildManager.ExecutePreAppStart()
   en System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)

Se produjo una excepción de tipo 'System.OutOfMemoryException'.
   en System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   en System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   en System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   en System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   en System.Reflection.Assembly.LoadFrom(String assemblyFile)
   en WebActivatorEx.ActivationManager.get_Assemblies()
   en WebActivatorEx.ActivationManager.RunActivationMethods[T](Boolean designerMode)
   en WebActivatorEx.ActivationManager.Run()

Request information:
    Request URL: http://my.mvcapp.com/signalr/reconnect?transport=longPolling&clientProtocol=1.5&connectionToken=6Avu6HS5DNT2tKAPHT90nO3u8M2arqOCtaMVIGGiEi/ZsxSM3axZQUBukhn1C0p14qGfoIxy722kR3LhvsZb5Qq6ERwk8z9GA6DI4VGJ8fm8onV8pM79bGp2BTIwaareiiXFYGIWDJxWL7LKux6TwA==&connectionData=[{"name":"wstimerhub"}]
    Request path: /signalr/reconnect
    User host address: XXX.XX.X.XX
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: MyDomain\MyAppPoolCustomIdentity

Thread information:
    Thread ID: 51
    Thread account name: MyDomain\MyAppPoolCustomIdentity
    Is impersonating: False
    Stack trace:    en System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures)
   en System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods)
   en System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded)
   en System.Web.Compilation.BuildManager.ExecutePreAppStart()
   en System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException)

Custom event details:

And below the signalr negotitate error (Event id 1309):
Event code: 3005
Event message: Excepción no controlada.
Event time: 05/11/2020 18:09:47
Event time (UTC): 05/11/2020 17:09:47
Event ID: c19a08970c4c44abb969098d601bc6e1
Event sequence: 13649
Event occurrence: 2
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/2/ROOT-4-132490644058804577
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\inetpub\wwwroot\MyMVCApp\
    Machine name: MyServer

Process information:
    Process ID: 6936
    Process name: w3wp.exe
    Account name: MyDomain\MyAppPoolCustomIdentity

Exception information:
    Exception type: OutOfMemoryException
    Exception message: Se produjo una excepción de tipo 'System.OutOfMemoryException'.
   en System.Web.Hosting.IIS7WorkerRequest.ReadRequestHeaders()
   en System.Web.Hosting.IIS7WorkerRequest.GetKnownRequestHeader(Int32 index)
   en System.Web.HttpWorkerRequest.HasEntityBody()
   en System.Web.HttpRequest.GetEncodingFromHeaders()
   en System.Web.HttpRequest.get_ContentEncoding()
   en System.Web.HttpRequest.get_QueryStringEncoding()
   en System.Web.HttpRequest.get_QueryStringText()
   en System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
   en System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

Request information:
    Request URL: http://my.mvcapp.com/signalr/negotiate?clientProtocol=1.5&connectionData=[{"name":"wstimerhub"}]&_=1604596208232
    Request path: /signalr/negotiate
    User host address: XXX.XX.XXX.XX
    User: MyDomain\OneUser
    Is authenticated: True
    Authentication Type: Negotiate
    Thread account name: MyDomain\MyAppPoolCustomIdentity

Thread information:
    Thread ID: 86
    Thread account name: MyDomain\MyAppPoolCustomIdentity
    Is impersonating: False
    Stack trace:    en System.Web.Hosting.IIS7WorkerRequest.ReadRequestHeaders()
   en System.Web.Hosting.IIS7WorkerRequest.GetKnownRequestHeader(Int32 index)
   en System.Web.HttpWorkerRequest.HasEntityBody()
   en System.Web.HttpRequest.GetEncodingFromHeaders()
   en System.Web.HttpRequest.get_ContentEncoding()
   en System.Web.HttpRequest.get_QueryStringEncoding()
   en System.Web.HttpRequest.get_QueryStringText()
   en System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
   en System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

Custom event details:


text:
Q: 2 way to write Plotly.newPlot : is there a difference? Can someone explain to me the difference between the following:

*

*Plotly.newPlot(graphDiv, data, layout, config)

*Plotly.newPlot(graphDiv, obj)
I thought it the two were the same but I get errors with the former on resize, which I do not encounterwhen using the latter.
Maybe the way the div is declared..?

A: There is not meant to be a difference between the two: https://plot.ly/javascript/plotlyjs-function-reference/#plotlynewplot


text:
Q: AWS Lambda Execution result: failed I've written a lambda function in the AWS Lambda GUI. The program I've written will send me an email, the program appears to work but there is error in my logs and I cannot even begin to understand those errors. I like to seek help on how to resolve the error.
This is the error I've gotten:
{
  "errorMessage": "2020-04-27T07:22:08.185Z b6ec9468-75c2-4e39-aeeb-bd0085758fb8 Task timed out after 3.00 seconds"
}

This is the log output
START RequestId: b6ec9468-75c2-4e39-aeeb-bd0085758fb8 Version: $LATEST
END RequestId: b6ec9468-75c2-4e39-aeeb-bd0085758fb8
REPORT RequestId: b6ec9468-75c2-4e39-aeeb-bd0085758fb8  Duration: 3003.16 ms    Billed Duration: 3000 ms    Memory Size: 128 MB Max Memory Used: 50 MB  Init Duration: 122.21 ms
2020-04-27T07:22:08.185Z b6ec9468-75c2-4e39-aeeb-bd0085758fb8 Task timed out after 3.00 seconds

And my code is below (mail-demo.py)
import os
import smtplib

def main(event, context):
    # TODO implement
    EMAIL_ADDRESS = os.environ['EMAIL_ADD']
    EMAIL_PASSWORD = os.environ['EMAIL_PWD']

    with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
        smtp.ehlo()
        smtp.starttls()
        smtp.ehlo()

        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

        subject = 'Wassup!'
        body = 'Testing some lambda function at don\'t know what time'

        msg = f'Subject: {subject}\n\n{body}'

        smtp.sendmail(EMAIL_ADDRESS, EMAIL_ADDRESS, msg)

    return 'email sent success'

A: You have to increase your functions execution timeout:

Timeout – The amount of time that Lambda allows a function to run before stopping it. The default is 3 seconds. The maximum allowed value is 900 seconds.


text:
Q: Can not POST JSON with embedded objects - It reads and stores everything except the list of objects (OneToMany) - Spring Boot API (+ hibernate) So I have this problem, when I try to post a JSON to the database using Postman it uploads it perfectly but it does not upload the embedded objects (which are in a list), I am using Spring Boot with JPA and hibernate, I am trying to create an API to make a CRUD with json files that all have the same structure.
In my case, I have Compania which is the main class and it has two Lists of objects, one being default_group, and the other one being Office.
Here is my controller(the POST method):
@PostMapping()
    public void createCompania(@RequestBody Compania compania) {
        companiaService.addCompania(compania);
    }

Here is my save method in my repository:
public void addCompania(Compania compania) {
        companiaRepository.save(compania);
        companiaRepository.flush();
    }

Here is my main entity(Compania) that has two OneToMany variables:
@Entity(name = "Compania")
@Table(
        name = "compania"
)
public class Compania {
    @Id
    @SequenceGenerator(
            name = "compania_sequence",
            sequenceName = "compania_sequence",
            allocationSize = 1
    )
    @GeneratedValue (
            strategy = GenerationType.SEQUENCE,
            generator = "compania_sequence"
    )
    @Column(
            nullable = false
    )
    private Long id;
    private String name;
    private String dominio;
    private String altas;
    private String bajas;
    @OneToMany(
            cascade = CascadeType.ALL,
            fetch = FetchType.LAZY,
            orphanRemoval = true
    )
    private List<DefaultGroup> default_group;
    @OneToMany(
            cascade = CascadeType.ALL,
            fetch = FetchType.LAZY
    )
    private List<Office> office;

Here is one of the other entities (default_group):
@Entity
@Table
public class DefaultGroup {
    @Id
    @SequenceGenerator(
            name = "defaultGroup_sequence",
            sequenceName = "defaultGroup_sequence",
            allocationSize = 1
    )
    @GeneratedValue(
            strategy = GenerationType.SEQUENCE,
            generator = "defaultGroup_sequence"
    )
    @Column(
            nullable = false
    )
    private Long id;
    private String name;
    private String path;
}

Here is the POST JSON I send with Postman:
{
"name": "name",
"dominio": "domain",
"altas": "xxxx",
"bajas": "yyyy",
"default_group":[
    {
        "name":"Users",
        "path":"pathExample"

    }
]
}

Here is the GET METHOD with the results
{
        "id": 3,
        "name": "name",
        "dominio": "domain",
        "altas": "xxxx",
        "bajas": "yyyy",
        "default_group": [
            {}
        ],
        "office": []
    }

As you can see, I'm not getting the default_group data, like if it wasn't parsing it correctly. Do you know what could be the problem? Or where could it be?
Thanks!

A: The problem was that I didn't add the getters and setters for the other entities (Default_group and office) so it couldn't set the different parameters into the objects.


text:
Q: How to call a stored proc in db2 database from spark scala I have to call a stored proc in db2 that takes 3 arguments and return an integer . Can anyone help me to call this sp from spark Scala code.
Below is the stored proc in db2.
CREATE PROCEDURE TEST_PROC(IN V_DATE DATE,IN V_GROUP VARCHAR(20),IN V_FREQ
VARCHAR(20),IN V_RULE VARCHAR(20), OUT ID INTEGER)
LANGUAGE SQL
MODIFIES SQL DATA
BEGIN
LOCK TABLE CAL_LOG IN EXCLUSIVE MODE;
SET ID = (10+ COALESENCE((SELECT MAX(ID) FROM CAL_LOG WITH UR),0));
INSERT INTO CAL_RESULT(ID,P_DATE,GROUP,FREQ,RULE)
VALUES(ID,V-DATE,V_GROUP,V_FREQ,V_RULE);
COMMIT:
END;

PROC is created and it is working as expected.
Now i want to call this proc from spark scala code.
I am trying the below code
val result = spark.read.format("jdbc")
.options(Map(
"url"-> //the db2 url
"driver" - > // my db2 driver
"user name" - > // username
"password" -> // password
""dbtable" -> "(CALL TEST_PROC('2020-07-08','TEST',''TEST','TEST,?)) as proc_result;"
)).load()

but the code snippet is giving below error
DB@ SQL Error: SQLCODE=-104, SQLSTATE=42601
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601

A: I think you should use JDBC connection directly instead of Spark, as your stored procedure only returns an integer. If you need that value you can retrieve that from the call to the stored procedure, but using Scala without using Spark.
You can find a sample at https://www.ibm.com/support/knowledgecenter/SSEPEK_12.0.0/java/src/tpc/imjcc_tjvcscsp.html
That's the standard way to call it on any language:

*

*If you need to replace parameters, you can use the prepareCall as described on the link above

*assign the parameters values with the registerParameter (In or Out)

*run the executeQuery as your sp returns an integer

*close the connection

A: I recommend ScalikeJDBC
Maven coordinates (Scala 2.11): org.scalikejdbc:scalikejdbc_2.11:3.4.1
import scalikejdbc._

// Initialize JDBC driver & connection pool
Class.forName(<db2 driver>)
ConnectionPool.singleton(<url>, <user>, <password>)

// ad-hoc session provider on the REPL
implicit val session = AutoSession

// Now you can run anything you want
sql"""
CREATE PROCEDURE TEST_PROC(IN V_DATE DATE,IN V_GROUP VARCHAR(20),IN V_FREQ
VARCHAR(20),IN V_RULE VARCHAR(20), OUT ID INTEGER)
LANGUAGE SQL
MODIFIES SQL DATA
BEGIN
LOCK TABLE CAL_LOG IN EXCLUSIVE MODE;
SET ID = (10+ COALESENCE((SELECT MAX(ID) FROM CAL_LOG WITH UR),0));
INSERT INTO CAL_RESULT(ID,P_DATE,GROUP,FREQ,RULE)
VALUES(ID,V-DATE,V_GROUP,V_FREQ,V_RULE);
COMMIT:
END;""".execute.apply()

Fetch data as follows
sql"""(CALL TEST_PROC('2020-07-08','TEST',''TEST','TEST,?))
as proc_result;""".execute.apply()

The result can be turned into a dataframe again if needed.

A: You cannot call stored procedure using Apache Spark though load same data using Spark load
Load fron db2
val sqlContext = new org.apache.spark.sql.SQLContext(sc)

val df= sqlContext.load("jdbc", Map(
                       "url" -> "jdbc:db2://xx.xx.xx.xx:50000/SQLDB:securityMechanism=9;currentSchema=vaquarkhan;user=<ur-username>;password=xxxxx;",
        "driver" -> "com.ibm.db2.jcc.DB2Driver",
        "dbtable" -> "scheam.TableName"))

Create temp table/df and add filters to get required response.


text:
Q: Asymmetric delta potential well modelling wave function I'm trying to model the wave function for an asymmetric delta function potential well, in which the left side of the well is at a potential of $0$, however the right side of the well has been moved down to $-5U$. Considering free particles of energy  $E_1 = -2U$ and $E_2 = -6U$, what would their wave functions look like? Obviously to the left of the well for $E_1$ it is a positive exponential curve up to $0$, then on the right I would expect it to have a sinusoidal wave function as $E_1 > -5U$, so the particle can be found here. For $E_2$ I would expect the wave function to the left to be a positive exponential curve and the right to be an exponential decay curve down. Here is a quick sketch I mocked up on what I think is going on, please note that the wave function $\Psi(X)$ is superimposed on to the energy diagram.
[![Asymmetric delta poential well][1]][1]
I am also trying to find out how much more likely it is for the particle of energy $E_2$ to be found to the right of the well than to the left of the well. I presume this has to do with the pre-exponential constant A on each side being different.
Any help is much appreciated, I haven't seen an example like this before and it's stumped me!
Thanks.


text:
Q: Problems with Spring Security 4 and REST, does not display HTML files I have a problem with my proyect, I've tried to configure Spring Security 4 with Spring REST, but there is a problem when I try to access with any context.
Here  is my project structure:

Inside of "views" are my html pages.
And here is my spring configuration.
<import resource="classpath:applicationContext-business.xml"/>
<mvc:annotation-driven />

<security:http auto-config="true" >

    <security:intercept-url pattern="/" access="permitAll" />
    <security:intercept-url pattern="/home" access="permitAll" />

    <security:form-login  login-page="/iniciar_sesion"
                 username-parameter="email"
                 password-parameter="password"
                 authentication-failure-url="/Access_Denied" />
    <security:csrf/>

</security:http>
<context:component-scan base-package="turing.solutions.dy.web" >
    <context:include-filter type="regex" expression=".*\.(.)*"/>
    <context:exclude-filter type="regex" expression="security"/>
</context:component-scan>

<bean id="customUserDetailsService" class="turing.solutions.dy.web.security.CustomUserDetailService" />

<security:authentication-manager>
    <security:authentication-provider user-service-ref="customUserDetailsService"/>
</security:authentication-manager>

And my web.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
    <servlet-name>dy</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dy</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
    <session-timeout>
        10
    </session-timeout>
</session-config>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

And this is my RestController:
@RestController
public class LoginController {

@RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage() {
    System.out.println("Redirect");
    return "index";
}

@RequestMapping(value="iniciar_sesion",method = RequestMethod.GET)
public String iniciarSession(ModelMap model){
    model.put("login", "log");
    return "iniciar_sesion";
}

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
public Map<String, Object> login() {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("login", "ok");
    return map;
}

@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
    model.addAttribute("user", getPrincipal());
    return "accessDenied";
}

private String getPrincipal() {
    String userName = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
        userName = ((UserDetails) principal).getUsername();
    } else {
        userName = principal.toString();
    }
    return userName;
}

}

Ant this is my CustomUserDetailService
@Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService {

@Autowired
private UsuariosService usuariosService;

@Override
public UserDetails loadUserByUsername(String correo) throws UsernameNotFoundException {
    Usuarios usuario = this.usuariosService.findByCorreo(correo);
    if (usuario == null) {
        throw new UsernameNotFoundException("El usuairo " + correo + " no existe, favor de verificar");
    }
    return new User(usuario.getEmail(), usuario.getPassword(), usuario.getActivo(), true, true, true, getGrantedAuthorities(usuario));
}

private List<GrantedAuthority> getGrantedAuthorities(Usuarios usuario) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (Roles rol : usuario.getRolesList()) {
        System.out.println("Usuario " + usuario.getEmail() + " ROl" + rol.getDescRol().toUpperCase());
        authorities.add(new SimpleGrantedAuthority("ROLE_" + rol.getDescRol().toUpperCase()));
    }
    return authorities;
}
}

When I try to access to the URL "http://localhost:9080/DespreocupateYA/home" I see this

But I should see this

So,my question is: Why i can't see the html pages in my project? I've searched and I found many Spring configurations, but I've not been able to solve the problem.
My Server is an Apache Tomcat 8.0.28.
I hope you can help me, Thanks.

A: Change your @RestController annotation to @Controller and it will work properly.
Here  are docs explaining the difference between this two annotations
Morover when you say RestController you mean a Controller wich  handle some data like JSON objects. Here you need a simple Controller to handle html views.
EDIT
You didn't mention what kind of view rendering engine you are using, this is example configuration for jsp
<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

And this to your spring conifguration file, make sure you declare "http://www.springframework.org/schema/beans" name space so you can use bean definition


text:
Q: Make can't do this harmless command I am using make on linux. I downloaded the GCC source code from
svn checkout svn://gcc.gnu.org/svn/gcc/trunk
and I got gcc version 4.6.0. I then typed in:
./configure --build=x86_64-fedora-linux-gnu --target=arm-apple-darwin --with-ecj-jar
I'm running fedora 12 linux. I typed in --build because otherwise it configures it under x86_64-unknown-linux-gnu.
My default build directory is /home/Leo/Documents/gcc-cross-iphone-4.6.0/
I then typed in make, and somewhere near the beginning I got error 2. I know that error 2 means that the program within make returned error 2. However, nothing appeared to have gone wrong. It just executed a bunch of commands, and make returned error 2. There was no echoed output that said foo happened it just said make ********* error 2.
This is the error message: (skip to the end for the actual message.)
gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic   ../.././libiberty/physmem.c -o pic/physmem.o; \
    else true; fi
gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic  ../.././libiberty/physmem.c -o physmem.o
if [ x"" != x ]; then \
      gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic   ../.././libiberty/pex-common.c -o pic/pex-common.o; \
    else true; fi
yes
gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic  ../.././libiberty/pex-common.c -o pex-common.o
checking for sys/stat.h... if [ x"" != x ]; then \
      gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic   ../.././libiberty/pex-one.c -o pic/pex-one.o; \
    else true; fi
gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic  ../.././libiberty/pex-one.c -o pex-one.o
if [ x"" != x ]; then \
      gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic   ../.././libiberty/pex-unix.c -o pic/pex-unix.o; \
    else true; fi
gcc -c -DHAVE_CONFIG_H -g -O2  -I. -I../.././libiberty/../include  -W -Wall -Wwrite-strings -Wc++-compat -Wstrict-prototypes -pedantic  ../.././libiberty/pex-unix.c -o pex-unix.o
yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... rm -f ./libiberty.a pic/./libiberty.a
ar rc ./libiberty.a \
      ./regex.o ./cplus-dem.o ./cp-demangle.o ./md5.o ./sha1.o ./alloca.o ./argv.o ./choose-temp.o ./concat.o ./cp-demint.o ./crc32.o ./dyn-string.o ./fdmatch.o ./fibheap.o ./filename_cmp.o ./floatformat.o ./fnmatch.o ./fopen_unlocked.o ./getopt.o ./getopt1.o ./getpwd.o ./getruntime.o ./hashtab.o ./hex.o ./lbasename.o ./lrealpath.o ./make-relative-prefix.o ./make-temp-file.o ./objalloc.o ./obstack.o ./partition.o ./pexecute.o ./physmem.o ./pex-common.o ./pex-one.o ./pex-unix.o ./safe-ctype.o ./sort.o ./spaces.o ./splay-tree.o ./strerror.o ./strsignal.o ./unlink-if-ordinary.o ./xatexit.o ./xexit.o ./xmalloc.o ./xmemdup.o ./xstrdup.o ./xstrerror.o ./xstrndup.o
ranlib ./libiberty.a
yes
checking for unistd.h... if [ x"" != x ]; then \
      cd pic; \
      ar rc ./libiberty.a \
        ./regex.o ./cplus-dem.o ./cp-demangle.o ./md5.o ./sha1.o ./alloca.o ./argv.o ./choose-temp.o ./concat.o ./cp-demint.o ./crc32.o ./dyn-string.o ./fdmatch.o ./fibheap.o ./filename_cmp.o ./floatformat.o ./fnmatch.o ./fopen_unlocked.o ./getopt.o ./getopt1.o ./getpwd.o ./getruntime.o ./hashtab.o ./hex.o ./lbasename.o ./lrealpath.o ./make-relative-prefix.o ./make-temp-file.o ./objalloc.o ./obstack.o ./partition.o ./pexecute.o ./physmem.o ./pex-common.o ./pex-one.o ./pex-unix.o ./safe-ctype.o ./sort.o ./spaces.o ./splay-tree.o ./strerror.o ./strsignal.o ./unlink-if-ordinary.o ./xatexit.o ./xexit.o ./xmalloc.o ./xmemdup.o ./xstrdup.o ./xstrerror.o ./xstrndup.o  ; \
      ranlib ./libiberty.a; \
      cd ..; \
    else true; fi
make[2]: Leaving directory `/home/Leo/Documents/gcc-cross-iphone-4.6.0/build-x86_64-fedora-linux-gnu/libiberty'
yes
checking locale.h usability... yes
checking locale.h presence... yes
checking for locale.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking limits.h usability... yes
checking limits.h presence... yes
checking for limits.h... yes
checking stddef.h usability... yes
checking stddef.h presence... yes
checking for stddef.h... yes
checking for stdlib.h... (cached) yes
checking for strings.h... (cached) yes
checking for string.h... (cached) yes
checking sys/file.h usability... yes
checking sys/file.h presence... yes
checking for sys/file.h... yes
checking for unistd.h... (cached) yes
checking whether byte ordering is bigendian... no
checking for an ANSI C-conforming const... yes
checking for inline... inline
checking for obstacks... yes
checking for off_t... yes
checking for size_t... yes
checking for ssize_t... yes
checking for uintptr_t... yes
checking for ptrdiff_t... yes
checking whether struct tm is in sys/time.h or time.h... time.h
checking size of int... 4
checking size of long... 8
checking for clearerr_unlocked... yes
checking for feof_unlocked... yes
checking for ferror_unlocked... yes
checking for fflush_unlocked... yes
checking for fgetc_unlocked... yes
checking for fgets_unlocked... yes
checking for fileno_unlocked... yes
checking for fprintf_unlocked... no
checking for fputc_unlocked... yes
checking for fputs_unlocked... yes
checking for fread_unlocked... yes
checking for fwrite_unlocked... yes
checking for getchar_unlocked... yes
checking for getc_unlocked... yes
checking for putchar_unlocked... yes
checking for putc_unlocked... yes
checking whether abort is declared... yes
checking whether asprintf is declared... no
checking whether basename is declared... no
checking whether errno is declared... no
checking whether getopt is declared... yes
checking whether vasprintf is declared... no
checking whether clearerr_unlocked is declared... yes
checking whether feof_unlocked is declared... yes
checking whether ferror_unlocked is declared... yes
checking whether fflush_unlocked is declared... yes
checking whether fgetc_unlocked is declared... yes
checking whether fgets_unlocked is declared... no
checking whether fileno_unlocked is declared... yes
checking whether fprintf_unlocked is declared... no
checking whether fputc_unlocked is declared... yes
checking whether fputs_unlocked is declared... no
checking whether fread_unlocked is declared... yes
checking whether fwrite_unlocked is declared... yes
checking whether getchar_unlocked is declared... yes
checking whether getc_unlocked is declared... yes
checking whether putchar_unlocked is declared... yes
checking whether putc_unlocked is declared... yes
checking for working alloca.h... yes
checking for alloca... yes
checking for ANSI C header files... (cached) yes
checking for nl_langinfo and CODESET... yes
checking whether NLS is requested... yes
checking for catalogs to be installed...  be ca da de el es fi fr id ja nl sv tr uk vi zh_CN zh_TW
checking for uchar...
checking for ld used by GCC... ld
checking if the linker (ld) is GNU ld... yes
checking for shared library run path origin... done
checking for iconv... yes
checking for iconv declaration... install-shextern size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
configure: updating cache ./config.cache
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: executing depdir commands
mkdir -p -- .deps
make[1]: Leaving directory `/home/Leo/Documents/gcc-cross-iphone-4.6.0'
make: *** [all] Error 2

Can someone help me with this? Thanx!

A: Never Mind. I tried it again, and I got configuration arm-apple-darwin not supported. oh well.


text:
Q: File permissions: kernel or file system? When we say "file permissions" are we referring to something that's inside the kernel, or a function of the file system? What layer determines where those permissions are stored. I'm confused at what level file permissions exist. Can someone help clarify the boundary?
I know how chown chmod work from the User-Perspective, but I don't know how they're implemented, or what actually throws the "Permission denied" error
touch foo
chmod 000 foo
cat foo
cat: foo: Permission denied

Can someone take me through the process of how the kernel, file system, io, and bits fit into that sequence above.

A: The best one-word answer to this question is either both or mu.
In the Unix operating system design, the filesystem functionality is provided by the kernel. So file permissions come from the kernel, and are enforced by the kernel.
Inside the kernel, there's a subsystem that handles accesses to files. Permissions are enforced by that subsystem. Subsystems don't have a clearly defined boundary, they're a human construction to understand the structure of the system. It is actually useful to separate the part of the kernel that handles accesses to files into two parts:

*

*the virtual filesystem (VFS), which handles accesses from application and parses paths;

*individual filesystem drivers, which manage access to specific filesystems that store information in a particular format.

Each filesystem driver decides how it stores and retrieves permissions. The VFS layer doesn't care: its job is to dispatch requests to the correct drivers. Filesystems for disk files store the permissions somewhere on the disk, if they support them at all. Filesystems for disk files that follow a traditional Unix design store permissions with other metadata in a file's inode. Network filesystems ask the server what the permissions are, if the protocol supports permissions. If the format or protocol doesn't support Unix permissions, it's up to the driver to make up something, for example by reporting the same permissions for all files. In-memory filesystems such as procfs and sysfs store permissions in a data structure in memory or calculate them on the fly. FUSE calls a function in the program that implements the filesystem, and so on.
Note that both the VFS layer and the filesystem driver contribute to determining whether an access request is granted. A request may even involve multiple filesystem drivers if it involves a path that traverses mount points (e.g. if /foo/bar is a mount point, then an access to /foo/bar/qux requires querying one filesystem for the traversal of / and /foo and another for the traversal of /foo/bar and /foo/bar/qux). The details of the split can vary depending on the Unix variant, but typically the VFS layer relates the file permissions with the calling context and may apply other restrictions (read-only mount, frameworks such as SELinux, etc.), and the individual filesystem may apply additional restrictions (e.g. for a network filesystem, the server can always say no).


text:
Q: validation using jQuery plugin not working properly Whatever I enter the response is "enter correct email" or "correct name" but when I click save a new user is always created.
<form id="dialogform" title="Edit User" action="">

Name

        <input class="name input" type="text" name="name" minlength="2" type="text" required aria-required="true">

Email

        <input class="mail input" type="email" name="email" required aria-required="true">

</form>
<form id="dialogNewUser" title="New User" action="">

         Name
        <input class="name input" name="name" minlength="2" type="text" required aria-required="true">
        Email
        <input class="mail input" type="email" name="email" required aria-required="true">

</form>

http://jsfiddle.net/RobDee/rvpvwgza/4

A: You need to use if($('#dialogNewUser').valid()){ /*code which need to be executed after validatin */
}
check below function.
Hope this helps
    function saveNew() {
  if($('#dialogNewUser').valid()){
  var n = $('#dataNew');
  var nn = n.find('.name').val();
  var mn = n.find('.mail').val();
  var row = $('#mylist').data('currentrow');
  row = row === "" || row === undefined ? "" : row;
  if (row === "") {
    addRow(nn, mn, "");

  } else {
    var r = $('#mylist').find('tbody').find('tr').eq(row);
    var name = r.find('.name');
    var mail = r.find('.mail');
    name.text(nn);
    mail.text(mn);

  }
  NewUser.dialog("close");
  }
}

'use strict';

var myajax = $.ajax({
  type: 'GET',
  url: 'people.json',
  datatype: 'json'
});
myajax.done(function(data) {
  for (var i in data.people) {
    var name = data.people[i].imię + " " + data.people[i].nazwisko;
    var mail = data.people[i].mail;
    var ico = data.people[i].ico;
    addRow(name, mail, ico);
  }
});
$('#mylist').on('click', '.ddledit', function() {
  var r = $(this).parents('tr');
  $('#mylist').data('currentrow', r.index());
  var n = r.find('.name').text();
  var m = r.find('.mail').text();
  var d = $('#dataEdit');
  d.find('.name').val(n);
  d.find('.mail').val(m);
  dialog.dialog("open");
});

function addRow(name, mail, ico) {
  var tr = "

";
  var ddl = '
<button class="btn btn-default dropdown-toggle" ' +
    'type="button"  data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">' +
    '</button>

Edit

Remove' +
    '

	';

  var pn = "";
  var pm = "";
  var $tr = $(tr);
  pn += '' + name + '	';
  pm += '' + mail + '	';
  var z = $(ddl);
  z.find('.ico').html(ico);
  $tr.append(pn + pm);
  z.appendTo($tr);
  $tr.appendTo('tbody');
}

var dialog;
var NewUser;
$(function() {
  dialog = $("#dialogform").dialog({
    autoOpen: false,
    width: 350,
    position: {
      my: "center top",
      at: "center top ",
      of: window
    },

    modal: true, //disable other items on the page
    buttons: {
      "Save": saveEdit,
      "Cancel": function() {
        dialog.dialog("close");
      }
    },
    close: function() {
      $('#dialogform')[0].reset();
      $('#mylist').data('currentrow', "");

    }
  });

  NewUser = $("#dialogNewUser").dialog({
    autoOpen: false,
    width: 350,
    position: {
      my: "center top",
      at: "center top ",
      of: window
    },

    modal: true,
    buttons: {
      "Save": saveNew,
      "Cancel": function() {
        NewUser.dialog("close");
      }
    },
    close: function() {
      $('#dialogNewUser')[0].reset();
      $('#mylist').data('currentrow', "");

    }
  });
});

function saveEdit() {
  var d = $('#dataEdit');
  var nd = d.find('.name').val();
  var md = d.find('.mail').val();

  var row = $('#mylist').data('currentrow');
  row = row === "" || row === undefined ? "" : row;
  if (row === "") {
    addRow(nd, md, "");
  } else {
    var r = $('#mylist').find('tbody').find('tr').eq(row);
    var n = r.find('.name');
    var m = r.find('.mail');
    n.text(nd);
    m.text(md);
  }
  dialog.dialog("close");
}

$(function() {
  $("#createnew").button().on("click", function() {
    NewUser.dialog("open");
  })

});

function saveNew() {

if($('#dialogNewUser').valid()){
  var n = $('#dataNew');
  var nn = n.find('.name').val();
  var mn = n.find('.mail').val();
  var row = $('#mylist').data('currentrow');
  row = row === "" || row === undefined ? "" : row;
  if (row === "") {
    addRow(nn, mn, "");

  } else {
    var r = $('#mylist').find('tbody').find('tr').eq(row);
    var name = r.find('.name');
    var mail = r.find('.mail');
    name.text(nn);
    mail.text(mn);

  }
  NewUser.dialog("close");
  }
}

$(function() {
  $("#dialogNewUser").validate();
  $("#dialogform").validate();
});

           Name

           Email

           Actions

  <button id="createnew" type="button" class="mybutton">Create New</button>
  <form id="dialogform" title="Edit User" action="">

Name

          <input class="name input" type="text" name="name" minlength="2" type="text" required aria-required="true">

Email

          <input class="mail input" type="email" name="email" required aria-required="true">

  </form>
  <form id="dialogNewUser" title="New User" action="">

          Name
          <input class="name input" name="name" minlength="2" type="text" required aria-required="true" >
          Email
          <input class="mail input" type="email" name="email" required aria-required="true">

  </form>


text:
Q: Show / hide base on input file value I have got an input file
 <input type="file" name="image" id="file">

and a button that save this file
 <input type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />

I need a JavaScript that will hide button if file was not choosen = 0, else show button if file choosen.

A:  <input type="file" name="image" id="file">

 <input type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />

<script>
$(function(){
   $("#upload_picture").hide();
   $("#file").change(function(){
        if ($("#file").val() != ""){
             $("#upload_picture").show();
        }
        else{
             $("#upload_picture").hide();
        }
   });
});
</script>

http://sandbox.phpcode.eu/g/6d8cd.php

A: $('#file').change(function(){
    $('#upload_picture').show();
});

and fiddle: http://jsfiddle.net/xGAVj/

A: HTML:
<input id="fld" type="file" name="image" id="file">

<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />

Javascript:
$("#fld").change(function(){
      if($(this).val() != "")
      {
           $("#btn").toggle();
      } else{
           $("#btn").toggle();
      }
});

Working Example: http://jsfiddle.net/saDFC/

A: Try this
$("#file").change(function(){
  if(!$(this).val()){
      $("#upload_picture").hide();
  }
  else{
      $("#upload_picture").show();
  }
});


text:
Q: Report Builder - Check condition with multiple values using switch Is there a way to use switch , in report builder, to check for multiple values?
`I can do :
Switch(
       Fields!parentclass.Value = 522,(Fields!Score.Value/21),
       Fields!parentclass.Value =4602,(Fields!Score.Value/2)
)

I want to do
Switch(
       Fields!parentclass.Value = 522,(Fields!Score.Value/21),
       Fields!parentclass.Value =4602,(Fields!Score.Value/2),
       Fields!parentclass.Value ="3969,3967,586,3968",(Fields!Score.Value/22)
)

Is it even possible to do so without using multiple "OR".
Thanks in advance

A: Try this:
=Switch(
Fields!parentclass.Value = 522,(Fields!Score.Value/21),
Fields!parentclass.Value =4602,(Fields!Score.Value/2),
Array.IndexOf(Split("3969,3967,586,3968",","),CStr(Fields!parentclass.Value))>=0,(Fields!Score.Value/22)
)

Let me know if this helps you.


text:
Q: Rails: form generation based on conditions I've got a form to build a Document. That form needs adjusting depending on what type of Document a user has chosen. At this point I've got a deferring kind of method in new.html.erb that goes like this:
<%= render 'form_'+@template.label.downcase.parameterize.underscore %>

Which works fine but it's kinda difficult to manage though because when new types of documents are added I need to create actual HTML files and upload them.
Is there a better way to manage this kind of form generation? A view with hundreds of if statements in it feels cumbersome too.

A: You can push it to document_helper or decorator like :
module DocumentHelper
  def form_render
    return 'form_#{type}'
  end
end


text:
Q: Насколько корректно так делать внутренние объекты в javascript Вопрос к почтенной публике, мне нужен внутренний объект, и сейчас я делаю так:
function FooList () {
    this.id = 0;
    this.list = {};
}
FooList.prototype = {
    add: function () {
        var item = new this.foo(this.id++, this);

        this.list[item.id] = item;
        return item;
    },
    get: function (id) {
        return this.list[id];
    },
    foo: function (id, parent) {
        this.id = id;
        this.parent = parent;
    }
};
FooList.prototype.foo.prototype = {
    set: function (name) {
        this.name = name;
    },
    get: function () {
        return this.name;
    }
};

// Test
var list = new FooList;
var foo = list.add();
foo.set("name");
console.log(foo);

Насколько это корректно (совместимо с разными броузерами)


text:
Q: How to create an array of unicode values of currency symbols in Swift? Unicode values are:
U+20A0 to U+20AF

All these values represent currency symbol. Check the following link for reference: https://en.wikipedia.org/wiki/Currency_Symbols_(Unicode_block)
In swift, I can print the currency symbol associated with a unicode with the following code:
let rupee = "\u{20B9}"    //Its currency symbol "₹"

My goel is to show all currency symbols in a table and for this purpose, I want to create an array of unicode values whose range I have mentioned above. I have used the following code to create an array, but there is problem in the step in which I am creating the unicode :
var unicodeArray:[String] = [String]()
for var decNumber=0; decNumber < 16; decNumber++ {
    let hexVal = String(decNumber, radix: 16)
    let unicode = "{20A\(hexVal)}"  \\u is missing in the string, writing \u gives error"
    unicodeArray.append(unicode)
}

After the for loop, array would have values between {20A0} to {20AF}, But I need the values from "\u{20A0}" to "\u{20AF}". How can I fix this. Or Is there any other way of doing what I am trying?

A: Edited: Used swift style loop as per suggestion @Grimxn
Try this:
var unicodeArray:[String] = [String]()
for decNumber in 0..<16 {
    let hexVal = String(decNumber, radix: 16)
    let integer = Int(strtoul("20A\(hexVal)", nil, 16))
    let unicode = UnicodeScalar(integer)

    unicodeArray.append(String(unicode))
}

Basically it prepares the hex values as Int. Then UnicodeScalar converts them to unicode. Which you can then convert into a String.

A: With Swift 5, you can use the following Playground sample code in order to get an array of all currency symbols as they are defined in Currency Symbols Unicode block:
//1.
let scalarRange: ClosedRange<Unicode.Scalar> = "\u{20A0}" ... "\u{20BF}"
//2.
let scalarValueRange = scalarRange.lowerBound.value ... scalarRange.upperBound.value

//3.
let currencySymbolArray = scalarValueRange.compactMap({ (scalarValue: UInt32) -> String? in
    guard let scalar = Unicode.Scalar(scalarValue) else { return nil }
    return String(scalar)
})

print(currencySymbolArray)
/*
 prints: ["₠", "₡", "₢", "₣", "₤", "₥", "₦", "₧", "₨", "₩", "₪", "₫", "€", "₭", "₮", "₯", "₰", "₱", "₲", "₳", "₴", "₵", "₶", "₷", "₸", "₹", "₺", "₻", "₼", "₽", "₾", "₿"]
 */

*

*You first create a range of Unicode scalars that match the code points for Currency Symbols.

*Because this first range is not strideable (you can't iterate on it), convert it to a range of Unicode scalar numeric representations using Unicode.Scalar's value property.

*Iterate over your range in order to create a String from each Unicode scalar numeric representation so that you can get an array of Currency Symbols.

If needed, the following code uses Unicode.Scalar's escaped(asASCII:) in order to get an array of Currency Symbols represented as ASCII escaped numeric values:
let scalarRange: ClosedRange<Unicode.Scalar> = "\u{20A0}" ... "\u{20BF}"
let scalarValueRange = scalarRange.lowerBound.value ... scalarRange.upperBound.value

let currencySymbolArray = scalarValueRange.compactMap({ (scalarValue: UInt32) -> String? in
    guard let scalar = Unicode.Scalar(scalarValue) else { return nil}
    let ascii = scalar.escaped(asASCII: true)
    return ascii
})

print(currencySymbolArray)
/*
 prints: ["\\u{20A0}", "\\u{20A1}", "\\u{20A2}", "\\u{20A3}", "\\u{20A4}", "\\u{20A5}", "\\u{20A6}", "\\u{20A7}", "\\u{20A8}", "\\u{20A9}", "\\u{20AA}", "\\u{20AB}", "\\u{20AC}", "\\u{20AD}", "\\u{20AE}", "\\u{20AF}", "\\u{20B0}", "\\u{20B1}", "\\u{20B2}", "\\u{20B3}", "\\u{20B4}", "\\u{20B5}", "\\u{20B6}", "\\u{20B7}", "\\u{20B8}", "\\u{20B9}", "\\u{20BA}", "\\u{20BB}", "\\u{20BC}", "\\u{20BD}", "\\u{20BE}", "\\u{20BF}"]
 */

As an alternative, you can use String's init(_:radix:uppercase:) to convert the scalar value to an hexadecimal value:
let scalarRange: ClosedRange<Unicode.Scalar> = "\u{20A0}" ... "\u{20BF}"
let scalarValueRange = scalarRange.lowerBound.value ... scalarRange.upperBound.value

let currencySymbolArray = scalarValueRange.map({ (scalarValue: UInt32) -> String in
    return String(scalarValue, radix: 16, uppercase: true)
})

print(currencySymbolArray)
/*
 prints: ["20A0", "20A1", "20A2", "20A3", "20A4", "20A5", "20A6", "20A7", "20A8", "20A9", "20AA", "20AB", "20AC", "20AD", "20AE", "20AF", "20B0", "20B1", "20B2", "20B3", "20B4", "20B5", "20B6", "20B7", "20B8", "20B9", "20BA", "20BB", "20BC", "20BD", "20BE", "20BF"]
 */


text:
Q: Stopping a PowerShell command How do I stop a PowerShell command when it has started executing?
E.g. How do I stop a command like this
Select-String -Path c:\*.* "Cat"

without having to kill my PowerShell terminal?
Ctrl-C or Break does not work.

A: While the script runs type Ctrl+Break.


text:
Q: Checking two node chains and calculate whether they have same data I have a function, which checks given two node chains and determines whether those two node chains contain same data values in same order. Function returns True if they do and returns False otherwise. I need to write this function using recursion.
Here's my attempt:
def check_chains(chain1, chain2):
    if chain1 is None or chain2 is None:
        return False
    else:
        if chain1.get_data() == chain2.get_data():
            check_chains(chain1.get_next(), chain2.get_next())
            return True
        else:
            return False

This one returns True even if node chains have different data values in them.
Below are some test cases:
1. Test case 1 (test passed)

    chain1 = N.node(5 ,N.node(10,N.node(-15, N.node(1))))
    chain2 = N.node(5 ,N.node(10,N.node(-15, N.node(1))))
    expected = True

    result = a7q8.check_chains(chain1, chain2)

    if result!=expected:
        print('Test failed')

2. test 2 (test failed, expected false but returned True)

    chain1 = N.node(5 ,N.node(10,N.node(-15, N.node(1))))
    chain2 = N.node(5 ,N.node(10,N.node(7, N.node(1))))
    expected = True

    result = a7q8.check_chains(chain1, chain2)

    if result!=expected:
        print('Test failed')

A: Your logic was a little bit flawed in two places:
def check_chains(chain1, chain2):
    # base case for equality was missing!
    if chain1 is chain2 is None:
        return True
    if None in (chain1, chain2):  # rewrote your condition less verbosely
        return False
    if chain1.get_data() == chain2.get_data():
        # recursive result was never used!
        return check_chains(chain1.get_next(), chain2.get_next())
    return False

I also removed some spurious else, as you return from every if-block.

A: def check_chains(chain1, chain2):
    if chain1 is None and chain2 is None:
        return True
    if chain1 is None or chain2 is None:
        return False
    else:
        if chain1.get_data() == chain2.get_data():
            return check_chains(chain1.get_next(), chain2.get_next())

        else:
            return False


text:
Q: Disable Persistent Database Connections on HHVM running as FastCGI I'm running HHVM version 3.0 as FastCGI whith NGINX.
I would like to know where disable php MySQL persistent connections.
In traditional php is on the php.ini file as follows:
[MySQL]
mysql.allow_persistent = Off

It's not clear in the HHVM documentation how to do this.
When a I try the code below:
<?php
echo "Display erros: " . ini_get('display_errors') . "
"; // Only for test
ini_set('mysql.allow_persistent', '0');
echo "Mysql persistent: " . ini_get('mysql.allow_persistent') . "
";
?>

I get the output below:
Display erros: 1
Mysql persistent:

How to disable persistent connections in HHVM?

A: mysql.allow_persistent is changeable as PHP_INI_SYSTEM, which means only in php.ini or your server config. As a result, you can't use ini_set to change it.
var_dump(ini_set('mysql.allow_persistent', '0')); will indicate to you that your call is returning FALSE, indicating a failure to change the value.
HHVM uses php.ini just like other methods of running PHP. Depending on your install, it may use one in a different location. Check phpinfo()'s output for the location - it may be in /etc/hhvm somewhere.


text:
Q: Generating a number between 1 and 2 java Math.random() with a probability set for each number I'm trying to generate a random numbers between 1 and 2 using the imported math.random() class and set the probability for each number.
The code below set the probability to be 1/2 for the two number each 1/2
int randomInt = (Math.random() <= 0.5) ? 1 : 2;

I want to be able to set the probability for each individual numbers, for example number 1 (20% probability) and number 2 (80% probability) or the ratio of 20:80. any solution?
Edit : The program I need to make is able to set the probability for number 1 and number 2 separately. like asking the user to input the probability for number 1 and 2

A: I think you can do in many ways.
Option 1: Simplest
int randomInt = (Math.random() <= 0.2) ? 1 : 2;

Option 2: Slightly intresting
// 20:80
final int seedList[] =  {
        1, //20%
        2,2,2,2//80%
};
for (int i =0; i < 10; i++) {
        int position = (int) (Math.random() * seedList.length);
        System.out.println(seedList[position]);
}

Any many more ways. I think you can be creative about solving this.

A: This method will take an arbitrary number of numbers to be used as weighting the result. There is no check in the code but for correctness the sum of them should be 100.
public static int randomInt(int... ratios) {
    int randomInt = ThreadLocalRandom.current().nextInt(1, 101);
    int previous = 0;
    for (int i = 0; i < ratios.length; i++) {
        if (randomInt < (ratios[i] + previous)) {
            return i + 1;
        }
        previous += ratios[i];
    }
    return 0;
}

Example, the following call would give 1 10%, 2 40%, 3 20% and 4 30% probability.
randomInt(10, 40, 20, 30)

A: Since your selection set contains only two items (1,2) you can infer the probability of 1 when the user enters the probability of 2.
public class OneOrTwo {
  public double probability1 = 0.2;
  public int next() {
    return (Math.random() <= probability1 ? 1 : 2);
  }
  public void setProbabilityOne(double p1) {
    probability1 = p1;
  }
  public void setProbabilityTwo(double p2) {
    probability1 = 1.0 - p2;
  }
  ... driver method, get user input, all that stuff ...
}

A: All you need to do is make it possible to parametrize the "0.5" in your code. For example, use a variable for it:
static int randomOneOrTwo(double probabilityOfOne) {
    return (Math.random() < probabilityOfOne) ? 1 : 2;
}

Now randomOneOrTwo(0.20) will return 1 with 20% probability, 2 with 80% probability.


text:
Q: Safari Services crash [SFAuthenticationViewController dismissViewControllerAnimated:completion:] I'm having a crash very often in my app. It seems a crash from iOS system only happening in the latest iOS 11.
This is the crash
Crashed: com.apple.main-thread
0  libobjc.A.dylib                0x18439d7ec objc_object::release() + 8
1  SafariServices                 0x1995d471c __75-[SFAuthenticationViewController dismissViewControllerAnimated:completion:]_block_invoke + 32
2  UIKit                          0x18e5bf030 -[UIPresentationController transitionDidFinish:] + 1320
3  UIKit                          0x18e79e760 -[_UICurrentContextPresentationController transitionDidFinish:] + 44
4  UIKit                          0x18e5c2a20 __56-[UIPresentationController runTransitionForCurrentState]_block_invoke_2 + 188
5  UIKit                          0x18e38e9d8 -[_UIViewControllerTransitionContext completeTransition:] + 116
6  UIKit                          0x18e38e7c8 -[UITransitionView notifyDidCompleteTransition:] + 252
7  UIKit                          0x18e38e260 -[UITransitionView _didCompleteTransition:] + 1128
8  UIKit                          0x18e38dde4 -[UITransitionView _transitionDidStop:finished:] + 120
9  UIKit                          0x18e2b370c -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 312
10 UIKit                          0x18e2b3418 -[UIViewAnimationState animationDidStop:finished:] + 296
11 UIKit                          0x18e2b34b8 -[UIViewAnimationState animationDidStop:finished:] + 456
12 QuartzCore                     0x188e57d6c CA::Layer::run_animation_callbacks(void*) + 284
13 libdispatch.dylib              0x1847f1048 _dispatch_client_callout + 16
14 libdispatch.dylib              0x1847fdb74 _dispatch_main_queue_callback_4CF$VARIANT$mp + 1016
15 CoreFoundation                 0x184e13f20 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 12
16 CoreFoundation                 0x184e11afc __CFRunLoopRun + 2012
17 CoreFoundation                 0x184d322d8 CFRunLoopRunSpecific + 436
18 GraphicsServices               0x186bc3f84 GSEventRunModal + 100
19 UIKit                          0x18e2df880 UIApplicationMain + 208
20 Jaumo                          0x1005674b4 main (main.m:20)
21 libdyld.dylib                  0x18485656c start + 4

Not sure what is this crash. anyone can help with this issue?

A: We had the same issue after we updated to the latest Facebook SDK (from a quite old version 4.11 to 4.27.1). Actually we had some calls initiated from applicationDidBecomeActive event which triggered the Facebook login (so opening a SFAuthenticationSession which opens the SFAuthenticationViewController the prompt that asks the user to continue authentication with Facebook or other 3rd party). Once the user tapped on "Continue" it triggered the applicationDidBecomeActive event again. This caused an endless loop of starting new SFAuthenticaionSessions which resulted in a crash. So we decided not to call Facebook login from this event at all. To summarize how to avoid this crash: you have to make sure that you call Facebook login (or SFAuthenticationSession start() method) only once at the same time.

A: As @Zoltán Homoki and @Jelly said, we should call logInWithReadPermissions only once.
For this purpose a common implementation (that was ok before) is to set a flag in the appDelegate like :
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([[url.scheme substringToIndex:2] isEqualToString:@"fb"]) {
        _fromFbConnect = YES; // <- This flag
        returnValue = [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    }
    // Manage app deep links here
}

Then use it to prevent multiple call to the Facebook login :
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [FBSDKAppEvents activateApp];

    if (_fromFbConnect == NO) { // <- Always `YES` on iOS11 with FB SDK 4.27
        // Refresh the facebook token
        if ([FBSDKAccessToken currentAccessToken] != nil) {
            [[FBSDKLoginManager new] logInWithReadPermissions: // ...
        }
        _fromFbConnect = NO;
    }
}

The issue is that on iOS11 with FBSDKLoginKit >= 4.27 application:openURL:sourceApplication:annotation: is not called (nor application:openURL:option) so the flag is not set. That create multiple calls to the login (applicationDidBecomeActive being called when the user close the first popup)
The solution I found is to setup a flag before any call to FBSDKLoginManager and stop any other call until the process is done.
@property (assign, nonatomic) BOOL fbRequesting;

// ...

if(_fbRequesting == YES) {
    NSLog(@"Facebook login already in progress");
    return;
}

if ([FBSDKAccessToken currentAccessToken] != nil) {
    return;
}

_fbRequesting = YES;
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];

NSLog(@"Logging in to Facebook...");

@weakify(self);
[[FBSDKLoginManager new] logInWithReadPermissions:... fromViewController:... handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    @strongify(self);

    // Handle login

    _fbRequesting = NO;
    })
];

This seems to work with versions 4.22 to 4.28 of FBSDKLoginKit.

A: Just faced this crash in FB SDK 4.31.1, and that's how I solved it.
In my case Crash happens, only when I trying to start login into FB, when FB Login already started(there is a Safari Web view on screen).
So I just check:
UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (topController.presentedViewController) {
       topController = topController.presentedViewController;
    }

if ([topController isKindOfClass:[MyViewController class]])
{
     // If that's my view controller, we can start FB Login
}


text:
Q: Importing an upgraded version of ExtJS into an existing project I have an existing Java 1.8 web application that uses ExtJS 3.  I need to upgrade to ExtJS 6 - but I can't figure out how to do this.
All the documentation I've come up so far explains how to do it with an entirely new project.
So after downloading and installing Sencha Cmd 6 and downloading and unzipping ExtJS 6, the documentation says to run the following from the command line:
sencha -sdk /path/to/extjs/framework generate app AppName path/to/app
cd /path/to/app
sencha app watch

Only problem is this assumes I want to do a new app - and also because it seems to lock everything into that particular new project.
Can someone point me to some documentation on how to do this?
Thanks!

A: Unfortunately, there is no automatic means of directly upgrading an ExtJS 3 app to ExtJS 6. The Sencha Cmd (the command line tool that you used to generate app) supports only ExtJS 4.1.1a and above (citation).
Most legacy applications written with ExtJS 3 and below are unstructured and did not have a framework-driven MVC. Depending on how big and complex your application is, an upgrade to ExtJS 6 can be as difficult as re-writing the application. The best approach is to start with a new ExtJS 6 application and migrate your existing application into the new one piece-by-piece, Here is the
Sencha Documentation that shows an example of how to do it.


text:
Q: Foundation exception found when running HMS Map demo code I'm trying to run the HMS map demo on my device and it is not working. I'm using a Honor v30. I'm getting errors in the log:
2021-03-25 17:50:04.567 22644-22644/com.huawei.hms.maps.sample E/hms.maps.sampl: Unknown bits set in runtime_flags: 0x8000
2021-03-25 17:50:04.664 22644-23636/com.huawei.hms.maps.sample E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@562ee
2021-03-25 17:50:20.861 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_PresentationLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.861 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_PresentationLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.862 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_PresentationLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.862 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_PresentationLogPusher_10: analyticsInstance is null
2021-03-25 17:50:20.869 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.870 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.870 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.871 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.872 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.872 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.873 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.874 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.874 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.875 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.875 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.876 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.877 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.877 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.878 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:20.879 22644-22644/com.huawei.hms.maps.sample E/HmsMapKit_AccessTraceLogPusher_73: analyticsInstance is null.
2021-03-25 17:50:21.021 22644-22644/com.huawei.hms.maps.sample E/HMSSDK_AGCUtils: Get client/cp_id failed: java.io.FileNotFoundException: agconnect-services.json
2021-03-25 17:50:21.021 22644-22644/com.huawei.hms.maps.sample E/HMSSDK_AGCUtils: The client/cp_id is null.
2021-03-25 17:50:21.718 22644-23809/com.huawei.hms.maps.sample E/HmsMapKit_TileClient_23: Exception occur
    com.huawei.hms.maps.foundation.client.mac: * * *E*U*S*_*E*I*D
        at com.huawei.hms.maps.foundation.client.mac$maa.b(Unknown Source:25)
        at com.huawei.hms.maps.foundation.client.mab.a(Unknown Source:20)
        at com.huawei.hms.maps.foundation.client.mab.a(Unknown Source:159)
        at com.huawei.hms.maps.provider.client.tile.maa.a(Unknown Source:1)
        at com.huawei.hms.maps.provider.client.tile.maa.lambda$gI3f4RyIuh0G4Qoia5V0XosFnEE(Unknown Source:0)
        at com.huawei.hms.maps.provider.client.tile.-$$Lambda$maa$gI3f4RyIuh0G4Qoia5V0XosFnEE.call(Unknown Source:6)
        at com.huawei.hms.maps.foundation.client.mab$maa.a(Unknown Source:3)
        at com.huawei.hms.maps.provider.client.tile.maa.c(Unknown Source:23)
        at com.huawei.hms.maps.provider.client.tile.maa.a(Unknown Source:4)
        at com.huawei.hms.maps.provider.cache.mad.a(Unknown Source:63)
        at com.huawei.hms.maps.provider.cache.mad$mac.startUrlRequest(Unknown Source:2)
        at com.huawei.map.MapController.startUrlRequest(Unknown Source:28)

A: It looks like that you are missing your agconnect-services.json. You need to connect your app with your developer console and download the agconnect-services.json and place it in app level directory.
Follow the guide here for the full instructions: Link


text:
Q: html5 video m3u8: How to auto play the video? <video id="videoHTML5" class="video" width="100%" height="400" poster="img/poster.png" autoplay controls>
   <source src="http://IP/live/stage.stream/playlist.m3u8" >
</video>

<script>
    var vdo = document.getElementById('videoHTML5');
    vdo.src = 'http://IP/live/stage.stream/playlist.m3u8';
    vdo.load();
    vdo.play();
</script>

NEVER starts ! I need to press the PLAY button on ipad and adroid !
Any idea on how to autostart an m3u8 video ?
reagards

A: you can try autoplay="true" in your  code


text:
Q: How does ILogger logs to Azure Application Insights? In an Azure Function, when you enable telemetry to Application Insight and fire a (for example) logger.LogInformation call (where logger is an ILogger instance), does it send it to the Application Insight instance asynchronously (ie non-blocking), synchronously (blocking), or through a local log that gets drained asynchronously?

A: Generally, the logger would be hooked up to turn log calls into the various trackMessage or related calls in the Application Insights SDK.  those messages get batched up in the AI side, and then sent after a threshold count of messages has been met, or after a certain amount of time has elapsed.  the calls into application insights are all non-blocking, and will not throw exceptions (you don't want telemetry to negatively affect your real app!)
the c# sdks that azure functions would use would be here: https://github.com/Microsoft/ApplicationInsights-dotnet/
I said generally at the top, because all this depends on how the SDK is configured, and that would be up to the Azure functions underlying code.  The GitHub with their info is here: https://github.com/Azure/Azure-Functions, and they have a specific wiki set up with AI info as well, here: https://github.com/Azure/Azure-Functions/wiki/App-Insights

A: This appears the be the relevant code for specifically how data is sent to Application Insights:
https://github.com/Microsoft/ApplicationInsights-dotnet/tree/develop/src/Microsoft.ApplicationInsights/Channel
The ILogger wraps a TelemetryClient, which sends data to an ITelemetryChannel.
The InMemoryTelemetryChannel contains the logic for how data is pooled and sent to Application Insights.  As John mentioned, the channel uses a "buffer" for storing data that hasn't been sent.  The buffer is flushed and the data sent asynchronously to Azure Portal when either the buffer is full or at a specific time internal (30 seconds).


text:
Q: #pragma for GNU ARM I want to enclose an entire C file in a output section,
Here is the example code I am trying:
#include<stdio.h>
#pragma arm section code = ".sec_ro"
int main(void)
{
printf("Hi\n");
}
#pragma arm section

I used :
arm-none-linux-gnueabi-gcc -S hello.c

to get the .S file.
But it looks like the sec_ro section is not present in the .S file.
EDIT/UPDATE :
Attaching the .s file contents :
.arch armv5te
.fpu softvfp
.eabi_attribute 20, 1
.eabi_attribute 21, 1
.eabi_attribute 23, 3
.eabi_attribute 24, 1
.eabi_attribute 25, 1
.eabi_attribute 26, 2
.eabi_attribute 30, 6
.eabi_attribute 18, 4
.file   "hello.c"
.section    .rodata
.align  2
.LC0:
    .ascii  "Hi\000"
    .text
    .align  2
    .global main
    .type   main, %function
main:
    .fnstart
.LFB0:
    @ args = 0, pretend = 0, frame = 0
    @ frame_needed = 1, uses_anonymous_args = 0
    stmfd   sp!, {fp, lr}
    .save {fp, lr}
    .setfp fp, sp, #4
    add fp, sp, #4
    ldr r0, .L2
    bl  puts
    mov r0, r3
    ldmfd   sp!, {fp, pc}

I want to enclose an entire C file to create an output section , I am using GNU ARM tool chain, Am I missing something ?

A: '#pragma arm' directives are only supported with the ARM toolchain (RVCT or DS-5). For GCC you'll need to use a linker script or '_attribute(section)' style syntax. This is supported by both armcc and GCC:
http://www.keil.com/support/man/docs/armccref/armccref_Cacbgief.htm

A: Does that say if use gcc, there is no way to specify entire file session by something like progma?
It is important to allow the progma syntax from source code level, as in many cases, the linker doesnot really know what files are going to be included, especially in a large scale project shares same link script.


text:
Q: Usage of case clause in where clause I need to add a filter to a stored procedure depending on a dropdowns value
Available values are 0,1,2,3,4,5. @TescilDurum is my parameter.
0 = ALL
1 = TescilDurumId IN 4 OR 5
2 = t.ID IS NULL
3 = dncts.RegistrationCode IS NULL
4 = hsm.ID IS NULL AND dncts.RegistrationCode IS NULL IS NOT NULL
5 = hsm.ENSMRN IS NULL

So far I tried this from a similar question answer on internet but I'm not sure if it is right thing to do. I'm not sure if this "reverse logic" is correct way to do this. And the order by after it gives an error too...
AND 1 =
    CASE WHEN @TescilDurum = 1 AND t.TescilDurumId NOT IN (4,5) THEN 0
    ELSE CASE WHEN @TescilDurum = 2 AND t.Id IS NOT NULL THEN 0
    ELSE CASE WHEN @TescilDurum = 3 AND hsm.EnsMRN IS NOT NULL THEN 0
    ELSE CASE WHEN @TescilDurum = 4 AND hsm.Id IS NOT NULL AND dncts.RegistrationCode IS NULL THEN 0
    ELSE CASE WHEN @TescilDurum = 5 AND hsm.EnsMRN IS NOT NULL THEN 0
    ELSE 1 END

A: You can simplify it:
WHERE
  (CASE
       WHEN @TescilDurum = 0 THEN 1
       WHEN @TescilDurum = 1 AND TescilDurumId IN (4,5) THEN 1
       WHEN @TescilDurum = 2 AND t.ID IS NULL THEN 1
       WHEN @TescilDurum = 3 AND dncts.RegistrationCode IS NULL THEN 1
       WHEN @TescilDurum = 4 AND hsm.ID IS NULL AND dncts.RegistrationCode IS NOT NULL THEN 1
       WHEN @TescilDurum = 5 AND hsm.ENSMRN IS NULL THEN 1
       ELSE NULL    -- this is default and can be skipped if needed
  END) = 1

EDIT:
For anyone who is afraid that query above is always 1 = 1:
CASE has default ELSE NULL clause so when there is no match before entire statement will return NULL and NULL = 1 => NULL.
DECLARE @v INT = 4;

SELECT 1
WHERE(CASE WHEN @v = 1 THEN 1
           WHEN @v = 2 THEN 1
           WHEN @v = 3 THEN 1
           ELSE NULL    -- this is default and can be skipped if needed
      END) = 1
 -- empty resultset

and:
CREATE TABLE #tab(ID INT, col VARCHAR(100));

INSERT INTO #tab
VALUES (1, 'aa'), (2, 'bbb'), (3, NULL), (4, 'aa');

-- DROP DOWN MENU
-- 1 all records
-- 2 only those which ID is in (2,3)
-- 3 only those which has col = 'aa'
-- 4 only those which has NULL value in col

DECLARE @variable INT = 3;

SELECT *
FROM #tab
WHERE
(
  CASE WHEN @variable = 1 THEN 1
       WHEN @variable = 2 AND ID IN (2,3) THEN 1
       WHEN @variable = 3 AND col = 'aa'  THEN 1
       WHEN @variable = 4 AND col IS NULL THEN 1
       ELSE NULL    -- this is default and can be skipped if needed
 END
) = 1

Keep in mind that that there is compound condition with AND so correct rows will be returned.
LiveDemo


text:
Q: Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'String' I been getting errors on the snippet of code below. Every time I try to build it, the compiler complains:

Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'String'

Here is the code, in all of its glory:
import Foundation
import MapKit

enum LocationKey: String {
    case Latitude = "lat"
    case Longitude = "long"
    case Title = "title"
}

extension MKPointAnnotation {
    var propertyState: [NSObject: AnyObject] {
        get {
            return [ LocationKey.Longitude.rawValue as NSObject: NSNumber(value: coordinate.latitude),
                     LocationKey.Longitude.rawValue as NSObject: NSNumber(value: coordinate.longitude),
                     LocationKey.Title.rawValue as NSObject: title as AnyObject]
        }
        set {
            let lat = (newValue[LocationKey.Latitude.rawValue] as NSNumber).doubleValue
            let long = (newValue[LocationKey.Longitude.rawValue] as NSNumber).doubleValue
            coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
            title = newValue[LocationKey.Title.rawValue] as NSString
        }
    }
}

The lines of code that I really have trouble with are:
let lat = (newValue[LocationKey.Latitude.rawValue] as NSNumber).doubleValue
let long = (newValue[LocationKey.Longitude.rawValue] as NSNumber).doubleValue
title = newValue[LocationKey.Title.rawValue] as NSString

Thanks a bunch!

A: var propertyState: [NSObject: AnyObject] is a Dictionary which has keys of type NSObject. Try changing that to type String and see if that works.

A: It's because you're creating a Dictionary with NSObject key.
Try this:
import Foundation
import MapKit

enum LocationKey: String {
    case Latitude = "lat"
    case Longitude = "long"
    case Title = "title"
}

extension MKPointAnnotation {
    var propertyState: [String: AnyObject] {
        get {
            return [ LocationKey.Longitude.rawValue: NSNumber(value: coordinate.latitude),
                     LocationKey.Longitude.rawValue: NSNumber(value: coordinate.longitude),
                     LocationKey.Title.rawValue: title as AnyObject]
        }
        set {
            guard let lat = (newValue[LocationKey.Latitude.rawValue] as? NSNumber)?.doubleValue,
                let long = (newValue[LocationKey.Longitude.rawValue] as? NSNumber)?.doubleValue else {
                return
            }
            coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
            title = newValue[LocationKey.Title.rawValue] as? String
        }
    }
}

In code you've seen сonditionally unwrapped optionals in properyState setter because it's good a practice not to use force unwrapping.

A: Your code is too complicated. All values are value type so declare the dictionary as [String:Any] – which solves the error by the way – and get rid of all ugly type casts to NSNumber and AnyObject.
import Foundation
import MapKit

enum LocationKey: String {
    case latitude = "lat"
    case longitude = "long"
    case title = "title"
}

extension MKPointAnnotation {
    var propertyState: [String: Any] {
        get {
            return [ LocationKey.latitude.rawValue: coordinate.latitude,
                     LocationKey.longitude.rawValue: coordinate.longitude,
                     LocationKey.title.rawValue: title ?? ""]
        }
        set {
            guard let lat = newValue[LocationKey.latitude.rawValue] as? CLLocationDegrees,
            let long = newValue[LocationKey.longitude.rawValue] as? CLLocationDegrees else { return }
            coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
            title = newValue[LocationKey.title.rawValue] as? String
        }
    }
}

You can even use the enum as key
extension MKPointAnnotation {
    var propertyState: [LocationKey: Any] {
        get {
            return [ .latitude: coordinate.latitude,
                     .longitude: coordinate.longitude,
                     .title: title ?? ""]
        }
        set {
            guard let lat = newValue[.latitude] as? CLLocationDegrees,
            let long = newValue[.longitude] as? CLLocationDegrees else { return }
            coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
            title = newValue[.title] as? String
        }
    }
}

Note: Your getter uses LocationKey.Longitude twice which will cause a compiler error.


text:
Q: Как запустить сайт на Django в подпути? Появилась задача запустить сайт на Django не на всём домене, а внутри подпути, то есть чтобы по адресу типа http://example.com/subpath/ открывалась главная, по адресу http://example.com/subpath/admin/ админка и так далее. Как это сделать, не переписывая вручную абсолютно все ссылки в urls.py? Иначе говоря, как добавить префикс ко всем URL в Django?

A: Для случая, когда перед Django стоит nginx (а именно так и должно быть на продакшене) enSO предлагает прописать FORCE_SCRIPT_NAME в settings.py (или ином DJANGO_SETTINGS_MODULE):
FORCE_SCRIPT_NAME = '/subpath'

Тогда настройка nginx может выглядеть примерно так:
server_name example.com;
# ...
location /subpath/ {
    proxy_pass http://localhost:8000/;  # внимание: есть слэш в конце
    include proxy_params;
    # ...
}

В таком случае запросы на nginx будут поступать в виде http://example.com/subpath/admin/ и перенаправляться в Django в виде http://localhost:8000/admin/. В ответе Django будет приписывать /subpath ко всем ссылкам на странице (при использовании reverse или {% url %}, разумеется).

Эта настройка может быть неудобна тем, что Django принимает ссылки строго без /subpath, что не очень удобно при разработке. Поэтому я предпочитаю прописывать префикс в urls.py явно. Это можно сделать ровно один раз в root urlconf:
from django.conf import settings
from django.conf.urls import include, url
# ... прочие импорты

urlpatterns = [url(settings.URL_PREFIX, include([
    url(r'^$',views.index, name='index'),
    url(r'^admin/', admin.site.urls),
    # ... и так далее
]))]

И, соответственно, прописываем в settings.py:
URL_PREFIX = 'subpath/'

Чтобы префикс не использовался, пишем URL_PREFIX = ''.
Тогда настройка nginx будет немного отличаться:
server_name example.com;
# ...
location /subpath/ {
    proxy_pass http://localhost:8000;  # внимание: слэш в конце пропал
    include proxy_params;
    # ...
}

Таким образом Django принимает запросы вида http://localhost:8000/subpath/admin/, и это нормально работает на dev-сервере совсем без nginx, что удобно для тестирования.
Ну и ещё STATIC_ROOT = '/subpath/static/' и MEDIA_ROOT = '/subpath/media/' по вкусу.

Про влияние слэша и других URI в конце proxy_pass читайте в документации nginx.
(И не забывайте, что ни в коем случае нельзя запускать встроенный dev-сервер Django на продакшене, потому что он небезопасен. Используйте uwsgi, gunicorn или другие серьёзные wsgi-серверы.)


text:
Q: Python "while" loop will not terminate I am currently working on a project where we have to check password strength and generate a strong password, but In the task of making a way for the program to exit I've hit a block, and am unable to find ways to progress. Ive tried break and sys.exit() but neither seem to work.
I would like to, when they enter [3] then ['yes'], for the program to end, but it just returns to the first question.
I have also attempted the while = True: , but that had even less success.
count = 0
while (count < 1):

    while True:
        choice = input ("Do you want to: 1) Check a password 2) Generate a Password, or 3) Quit? . [1/2/3]? : ")
        if choice in ['1', '2', '3']:
            break
    if choice == "1":
        while True:
            checkyes = input ("you want to check a password, correct? [yes/no]")
            if checkyes in ['yes', 'no']:
               break
    elif choice == "2":
        while True:
            genyes = input ("you want to generate a password, correct? [yes/no]")
            if genyes in ['yes', 'no']:
                break
    else:
        while True:
            quityes = input ("you want to quit, correct? [yes/no]")
            if quityes in ['yes', 'no']:
                break
                if choice == "yes":
                    count = count + 1
                else:
                    pass

A: You are checking the wrong variable for the exit condition. You need to check with quityes:
count = 0
while (count < 1):

    while True:
        choice = input ("Do you want to: 1) Check a password 2) Generate a Password, or 3) Quit? . [1/2/3]? : ")
        if choice in ['1', '2', '3']:
            break
    if choice == "1":
        while True:
            checkyes = input ("you want to check a password, correct? [yes/no]")
            if checkyes in ['yes', 'no']:
               break
    elif choice == "2":
        while True:
            genyes = input ("you want to generate a password, correct? [yes/no]")
            if genyes in ['yes', 'no']:
                break
    else:
        while True:
            quityes = input ("you want to quit, correct? [yes/no]")
            if quityes in ['yes', 'no']:
               if quityes == 'yes'
                    count += 1
                    break
               else:
                   pass

Output:
Do you want to: 1) Check a password 2) Generate a Password, or 3) Quit? . [1/2/3]? : 3
you want to quit, correct? [yes/no]yes

Process finished with exit code 0

A: 2 problems:

*

*the break statement is executed before count in incremented

*you check choice instead quityes against 'yes'
if quityes in ['yes', 'no']:
    if quityes == "yes":
        count = count + 1
    else:
         pass
    break

A: You can try to import sys and replace the break with sys.exit().
Think the reason why the break didnt work is because its breaking out of first loop but not out of the bigger loop.


text:
Q: Interpretation of an 'Empty' C Array (int a = {};) I have a snippet of code that defines (what I believe to be) an empty array, i.e. an array containing no elements:
int a[] = {};

I compiled the snippet with gcc with no problem
A colleague attempting to get that same code to compile under MSVS made the modification:
int* a = NULL;

No he obviously thought that was an equivalent statemnent that would be acceptable to the MSVS compiler.
However, later in the code I retrieve the no. of elements in the array using the following macro:
#define sizearray(a)  (sizeof(a) / sizeof((a)[0]))

when doing so:
sizearray({}) returns 0

this is as I would expect for what I believe to be a definition of an empty array
sizearray(NULL) returns 1

I'm thinking that sizeof(NULL)/sizeof((NULL)[0])) is actually 4/4 == 1
as NULL == (void*)0
My question is whether:
int a[] = {};

is a valid way of expressing an empty array, or whether its poor programming practice.
Also, is it the case that you can't use such an expression with the MSVS compiler, i.e. is this some sort of C99 compatibility issue?
UPDATE:
Just compiled this:
#include <stdio.h>

#define sizearray(a)  (sizeof(a) / sizeof((a)[0]))

int main()
{
    int a[] = {};
    int b[] = {0};
    int c[] = {0,1};

    printf("sizearray a = %lu\n", sizearray(a));
    printf("sizearray b = %lu\n", sizearray(b));
    printf("sizearray c = %lu\n", sizearray(c));

    return 0;
}

using this Makefile:
array: array.c
    gcc -g -o array array.c

My compiler is:
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.9)

compiles without any complaint, output looks like this:
bph@marvin:~/projects/scratch/c/array$ ./array
sizearray a = 0
sizearray b = 1
sizearray c = 2

very curious? could it secretly be a C++ compiler, not a C compiler?
Tried John Bodes suggestion of additional compiler flags and can confirm that the compilation does then fail:
gcc --std=c11 --pedantic -Wall -g -o array array.c
array.c: In function 'main':
array.c:7:15: warning: ISO C forbids empty initializer braces [-Wpedantic]
     int a[] = {};
               ^
array.c:7:9: error: zero or negative size array 'a'
     int a[] = {};
         ^
Makefile:2: recipe for target 'array' failed
make: *** [array] Error 1

A: Empty initializers are invalid in C. So
int a = {};

is ill-formed. See 6.7.9 Initialization.
sizearray(NULL) is not valid either. Because the sizearray macro would expand to:
sizeof 0 /sizeof 0[0])

If NULL is defined as 0. This is not valid because the 0[0] isn't valid because of there's no pointer or array involved (as required for pointer arithmetic - remember a[b] is equivalent to *(a + b)).
Or, it would expand to:
(sizeof(((void *)0)) / sizeof((((void *)0))[0]))

if NULL was as ((void*)0). This is not valid because pointer arithmetic is not allowed on void pointers. See 6.5.6, 2 and void* is an incomplete type. Similar issue be present for whatever the definition of NULL is in an implementation (C standard is flexible with the definition of null pointer constant i.e., NULL. See 7.19, 3).
So in both cases, what you see is compiler specific behaviours for non-standard code.

A: This is not an array, but it's not a scalar either: it's a syntax error.
The C11 draft says, in §6.7.9.11 (Initialization Semantics):

The initializer for a scalar shall be a single expression, optionally
  enclosed in braces. The initial value of the object is that of the
  expression (after conversion); the same type constraints and conversions as
  for simple assignment apply, taking the type of the scalar to be the
  unqualified version of its declared type.

But there has to be something between the braces, it can't be empty.
So I'd argue that the question is missing something, and this was not the actual code.

A: It's not an array, it's the brace initialization syntax.
Short word, you can write this:
int a = {1234};

It does not initialize a with an array, it just assigns 1234. If there are 2 or more values, that's be an error.
Brace initialization disables value truncating, so:
char b = 258; // Valid, same as b = 2
char b = {258}; // Wrong, can't truncate value in braces

And empty braces are just zero-initializers, so int a = {} is equivalent to int a = {0}


text:
Q: SQL Eliminate Duplicates with NO ID I have a table with the following Columns...
Node, Date_Time, Market, Price
I would like to delete all but 1 record for each Node, Date time.
SELECT Node, Date_Time, MAX(Price)
FROM Hourly_Data
Group BY Node, Date_Time

That gets the results I would like to see but cant figure out how to remove the other records.
Note - There is no ID for this table

A: Here are steps that are rather workaround than a simple one-command which will work in any relational database:

*

*Create new table that looks just like the one you already have

*Insert the data computed by your group-by query to newly created table

*Drop the old table

*Rename new table to the name the old one used to have

Just remember that locking takes place and you need to have some maintenance time to perform this action.
There are simpler ways to achieve this, but they are DBMS specific.

A: here is an easy sql-server method that creates a Row Number within a cte and deletes from it.  I believe this method also works for most RDBMS that support window functions and Common Table Expressions.
;WITH cte AS (
    SELECT
       *
       ,RowNum = ROW_NUMBER() OVER (PARTITION BY Node, Date_Time ORDER BY Price DESC)
    FROM
       Hourly_Data
)

DELETE
FROM
    cte
WHERE
    RowNum > 1


text:
Q: $\nabla U=0 \implies U=\mathrm{constant}$ with $A$ connected and $U$ continuous? I'm looking for suggestions on how to prove that

Given a function $U: A \subset \mathbb{R}^n \to \mathbb{R}$ with $U \in C^1 $ (therefore continuous) and $A$ a
  connected set, $$\nabla U=\bar{0} \,\,\,\,\,\,\, \forall \bar{x} \in A\implies U=\mathrm{constant} \,\,\,\,\,\,\, \forall \bar{x} \in
A$$

In particular, how is the condition of $A$ as a connected necessary?


text:
Q: Solving RSA cipher without calculator I have a question: Encrypt the message UPLOAD using RSA with $n=3\cdot 31$ and $e =17$.
My question is, how can I solve this with a calculator and in an efficient manner due to being in an exam environment?
For example, for $U$ I got $C= 21^{17}\pmod{93}$. Is there any shortcut I can use?