text:
Q: Convert a Byte Array to an Image I am working on a utility that takes the JPEG byte message from ActiveMQ and convert it to byte array and sends it to other application in byte array.
I want to check if the particular byte message is in proper format and it can be converted to image format, When I am trying to convert it to image format it gives me null pointer exception always. Can any one help?
The code follows:
if (message instanceof BytesMessage) {
    BUSINESS_LOGGER.info("bytes message Recieved");
    BytesMessage bMessage = (BytesMessage) message;
    //BufferedImage imagebyte= null;
    byte[] imageinbytearray;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int n;
    byte[] bytemesage = new byte[message.toString().length()];

    while ((n = bMessage.readInt()) !=- 1) {
        out.write(bytemesage, 0, n);
    }

    imageinbytearray= out.toByteArray();
    itemDamage.setPicture(imageinbytearray);

    // itemDamage is a soap operation.
    try {
        BufferedImage imagebyte = ImageIO.read(new ByteArrayInputStream(imageinbytearray));
        File f = new File("c:/Image.jpeg");
        ImageIO.write(imagebyte, "JPEG", f);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
} else {
    BUSINESS_LOGGER.info("No message format Recieved");
}

The value imagebyte is always null.
java.lang.IllegalArgumentException: image == null!
    at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
    at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
    at javax.imageio.ImageIO.write(ImageIO.java:1520)
    at se.posten.loab.lisp.csp.core.serviceimpl.NovaItemDamageServiceBean.createItemDamage(NovaItemDamageServiceBean.java:114)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.delegateInterception(Jsr299BindingsInterceptor.java:74)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:84)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:97)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.sculptor.framework.persistence.JpaFlushEagerInterceptor.invoke(JpaFlushEagerInterceptor.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:89)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.sculptor.framework.errorhandling.ErrorHandlingInterceptor.invoke(ErrorHandlingInterceptor.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:89)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.jpa.interceptor.SBInvocationInterceptor.processInvocation(SBInvocationInterceptor.java:47)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:73)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:258)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:347)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:243)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor.processInvocation(WaitTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:55)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:185)
    at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:185)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73)
    at se.posten.loab.lisp.csp.core.serviceapi.NovaItemDamageServiceLocal$$$view148.createItemDamage(Unknown Source)
    at se.posten.loab.lisp.csp.core.consumer.NovaDamageItemConsumerBean.handleMessage(NovaDamageItemConsumerBean.java:63)
    at se.posten.loab.lisp.csp.core.consumer.NovaDamageItemConsumerBean.onMessage(NovaDamageItemConsumerBean.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:52)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.doMethodInterception(Jsr299BindingsInterceptor.java:86)
    at org.jboss.as.weld.ejb.Jsr299BindingsInterceptor.processInvocation(Jsr299BindingsInterceptor.java:97)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.sculptor.framework.persistence.JpaFlushEagerInterceptor.invoke(JpaFlushEagerInterceptor.java:41)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:89)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.sculptor.framework.errorhandling.ErrorHandlingInterceptor.invoke(ErrorHandlingInterceptor.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:89)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InterceptorContext$Invocation.proceed(InterceptorContext.java:374)
    at org.sculptor.framework.context.ServiceContextStoreInterceptor.invoke(ServiceContextStoreInterceptor.java:50)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ee.component.ManagedReferenceLifecycleMethodInterceptor.processInvocation(ManagedReferenceLifecycleMethodInterceptor.java:89)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.WeavedInterceptor.processInvocation(WeavedInterceptor.java:53)
    at org.jboss.as.ee.component.interceptors.UserInterceptorFactory$1.processInvocation(UserInterceptorFactory.java:63)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.invocationmetrics.ExecutionTimeInterceptor.processInvocation(ExecutionTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.weld.ejb.EjbRequestScopeActivationInterceptor.processInvocation(EjbRequestScopeActivationInterceptor.java:93)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.InitialInterceptor.processInvocation(InitialInterceptor.java:21)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.interceptors.ComponentDispatcherInterceptor.processInvocation(ComponentDispatcherInterceptor.java:53)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.pool.PooledInstanceInterceptor.processInvocation(PooledInstanceInterceptor.java:51)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:258)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:347)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:243)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.CurrentInvocationContextInterceptor.processInvocation(CurrentInvocationContextInterceptor.java:41)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.invocationmetrics.WaitTimeInterceptor.processInvocation(WaitTimeInterceptor.java:43)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.ShutDownInterceptorFactory$1.processInvocation(ShutDownInterceptorFactory.java:64)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.LoggingInterceptor.processInvocation(LoggingInterceptor.java:59)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ee.component.NamespaceContextInterceptor.processInvocation(NamespaceContextInterceptor.java:50)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.interceptors.AdditionalSetupInterceptor.processInvocation(AdditionalSetupInterceptor.java:55)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ejb3.component.messagedriven.MessageDrivenComponentDescription$5$1.processInvocation(MessageDrivenComponentDescription.java:203)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.as.ee.component.TCCLInterceptor.processInvocation(TCCLInterceptor.java:45)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.ViewService$View.invoke(ViewService.java:185)
    at org.jboss.as.ee.component.ViewDescription$1.processInvocation(ViewDescription.java:185)
    at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288)
    at org.jboss.invocation.ChainedInterceptor.processInvocation(ChainedInterceptor.java:61)
    at org.jboss.as.ee.component.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:73)
    at javax.jms.MessageListener$$$view102.onMessage(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.jboss.as.ejb3.inflow.MessageEndpointInvocationHandler.doInvoke(MessageEndpointInvocationHandler.java:140)
    at org.jboss.as.ejb3.inflow.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:73)
    at com.sun.proxy.$Proxy163.onMessage(Unknown Source)
    at org.apache.activemq.ra.MessageEndpointProxy$MessageEndpointAlive.onMessage(MessageEndpointProxy.java:123)
    at org.apache.activemq.ra.MessageEndpointProxy.onMessage(MessageEndpointProxy.java:64)
    at org.apache.activemq.ActiveMQSession.run(ActiveMQSession.java:916)
    at org.apache.activemq.ra.ServerSessionImpl.run(ServerSessionImpl.java:169)
    at org.jboss.jca.core.workmanager.WorkWrapper.run(WorkWrapper.java:218)
    at org.jboss.threads.SimpleDirectExecutor.execute(SimpleDirectExecutor.java:33)
    at org.jboss.threads.QueueExecutor.runTask(QueueExecutor.java:808)
    at org.jboss.threads.QueueExecutor.access$100(QueueExecutor.java:45)
    at org.jboss.threads.QueueExecutor$Worker.run(QueueExecutor.java:828)
    at java.lang.Thread.run(Thread.java:745)
    at org.jboss.threads.JBossThread.run(JBossThread.java:122)

This is the stack trace. The issue is not the null pointer here but issue is  BufferedImage imagebyte = ImageIO.read(new ByteArrayInputStream(imageinbytearray)); this line returns null value even if imageinbytearray is having byte arrays


text:
Q: Newtonsoft.Json.JsonReaderException when I use a string s Newtonsoft.Json.JsonReaderException:"After parsing a value an unexpected character was encountered:

Newtonsoft.Json version="11.0.2"
in c#4.5
JsonConvert.DeserializeObject<QueryModel>(Json);
  private class QueryModel
    {
        public Pagination pagination { get; set; }
        public string queryJson { get; set; }
    }

public class Pagination
{
    public int rows { get; set; }
    public int page { get; set; }
   }

when I use json
"{"pagination":{"rows":10,"page":1},"queryJson":"{}"}" is ok
but use
"{"pagination":{"rows":10,"page":1},"queryJson":\"{/\"keyword/\":/\"test/\"}\"}"
is error

A: Sub JsonStr use '' replace \"\"   like "{"pagination":{"rows":10,"page":1},"queryJson":\"{'keyword':'test'}\"}"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot load modules Mod_authz_svn.so & Mod_dav_svn.so on-apache-2.4.10 I  am using Subversion-1.8.14  for apache-2.4.10 for a  Windows 2008 64-bit
(Almost 99% it's the supported version for both applications)
I copied following two files from Subversion/bin to Apache/modules

*

*mod_dav_svn.so

*mod_authz_svn.so

I have edited Httpd.conf to add the Subversion reference to the end of the load modules section at the top and copied following lines:
LoadModule authz_svn modules/mod_authz_svn.so
LoadModule dav_svn modules/mod_dav_svn.so

as per the doc: Xstore_POS_and_Xstore_Office_-_Build_Server_Setup
# Configure Subversion repository
<Location /svn>
DAV svn
SVNPath "C:/Program Files (x86)/Subversion/bin/xyzxstorerepo"
AuthType Basic
AuthName "Subversion Repository"
AuthUserFile "htdocs/.htpasswd"
AuthzSVNAccessFile "C:/Program Files (x86)/Subversion/bin/xyzxstorerepo/conf/svn-acl-conf"
Require valid-user
</Location>

The error reads

The Apache service named  reported the following error:
  >>> httpd.exe: Syntax error on line 111 of C:/Program Files (x86)/apache-2.4.10/conf/httpd.conf: Cannot load modules/mod_authz_svn.so into server: The specified procedure could not be found."

How can I fix it.


text:
Q: Is this function, to determine the result of rock paper scissors, correct? I want to make a function that tells you the result of a rock paper scissors game given two inputs:
data Move = Paper | Rock | Scissors
    deriving (Eq, Show)

data Result =  Win | Draw | Lose
    deriving (Eq, Show)

-- function returns the move which beats the other move
beats :: Move -> Move
beats move = case move of
    Paper    -> Scissors
    Rock     -> Paper
    Scissors -> Rock

loses :: Move -> Move
loses move = case move of
    Scissors -> Paper
    Paper -> Rock
    Rock -> Scissors

-- find out what the score is for moves and return Win or Draw or Lose
score :: Move -> Move -> Result
score this_move opposing_move = case this_move of
    opposing_move -> Draw
    beats opposing_move -> Win
    loses opposing_move -> Lose

It returns the error message:
parse error on input '='

This means there is a problem with one of the equals signs i wrote in the code right? I don't see any problems with an of the equals signs though.

A: As Carsten pointed out, this is far simpler with pattern matching; you don't even need intermediate functions.
score :: Move -> Move -> Result
score Paper Rock = Win  -- paper beats rock
score Rock Scissors = Win -- rock beats scissors
score Scissors Paper = Win -- scissors beats paper
score x y | x == y = Draw  -- same move is a draw
score _ _ = Lose -- anything else is a loss

A: and here is a version very close to yours
-- function returns the move which beats the other move
beats :: Move -> Move -> Bool
beats Scissors Paper = True
beats Paper Rock     = True
beats Rock Scissors  = True
beats _ _            = False

loses_to :: Move -> Move -> Bool
loses_to = flip beats

-- find out what the score is for moves and return Win or Draw or Lose
score :: Move -> Move -> Result
score this_move opposing_move
  | this_move `beats` opposing_move    = Win
  | this_move `loses_to` opposing_move = Lose
  | otherwise                          = Draw


text:
Q: 1 URL --> 2 results : 1 before a certain hour, 2 after I'm looking for some pages like this:

Referer : "http://cheval-francais.eu/fr/resultats-officiels.html"
Menu    : "http://cheval-francais.eu/index.php?option=com_content&task=view&id=21&Itemid=45"
Results (XML) : "http://cheval-francais.eu/courses/result_officiel_ficheliste3_fic.php?date=20110213&&societe=4901&&course=01&&groupe="

Results on the page change after the time of the events.

1- partants : "etatPeriode = PAR"
2- arrivants: "etatPeriode = RES" or "REP".

Is there a way to block "time" or change something with vba code to get just the results
of the first state (before time event) or all results on 2-arrivants (without blanked data)?
For arrivants, the XML Result is on the same schema, with all fields of partants
but data are blank. I would like to get data from the past for partants (like <defere>, <ordre> and some others.
I use VBA, and just call the XML page "results".

A: If I understand correctly, you want to download XML data from a website over which you have no control, but you want to download the data as it was shown at an earlier date/time.
If so, I think the only possiblity would be if you can add some parameter to the URL to specify what you want to download.
So for example, if you currently download from the URL:
http://cheval-francais.eu/courses/result_officiel_ficheliste3_fic.php?date=20110213&&societe=4901&&course=01&&groupe=

Then maybe you could instead change this to:
http://cheval-francais.eu/courses/result_officiel_ficheliste3_fic.php?date=20110213&&etatPeriode=PAR&&societe=4901&&course=01&&groupe=

But it would be up to the website code if it handles the etatPeriode parameter or not. Otherwise I can't see how you could get access to historical data. Though if you only need access to the historical data in the future and you don't need access to older data than "now", I suppose you could just create your code to download the data from the website every day before the specified time and store it locally in some way (assuming that this is allowed according to any licenses for usage of the data etc).


text:
Q: Why can I not get all wireless clients to connect to my DIR-655 router? I'm having difficulty getting all my wireless clients to connect.  They all have my WPA2 code.
Initially all clients worked (iPods, Android phone, PC, etc.) Then DirecTV gave us a free upgrade which included Pandora. All seemed well. Then we tried to add a Nexus 7 tablet but it would not connect - it couldn't find the IP address.
I did some resetting (and not sure what else I changed) then the Nexus worked but the iPods wouldn't.
Anyway, I can't seem to get everything to connect.
I did a rest a couple of days ago and below are my Number of Dynamic DHCP Clients : 7
Computer Name :Bpa-PC
IP Address :192.168.5.100
MAC Address: 50:e5:49:ce:91:fe

Computer Name :kindle-ff6a5ee36
IP Address : 192.168.5.103
MAC Address : e0:cb:1d:58:f4:95

Computer Name :Netbook
IP Address : 192.168.5.104
MAC Address : 00:25:d3:c8:97:86

Computer Name :Nana-PC
IP Address : 192.168.5.105
MAC Address : 00:1e:e5:ea:fe:f4

Computer Name :UNKNOWN
IP Address : 192.168.5.106
MAC Address: 94:44:44:3d:e1:57

Computer Name :DIRECTV-HR24-783E9B8A
IP Address :192.168.5.101
MAC Address: 00:03:78:3e:9b:8a

Computer Name :DIRECTV-HR24-78CA974C
IP Address :192.168.5.102
MAC Address: 00:03:78:ca:97:4c

These were the devices in the house at the time.
I did the reset because the Kindle wouldn't connect.  Now it connects but my Android cell phone will not.

A: Check the DHCP setup and be sure you have a large enogh range to allow for the clients.  It should be under Network Settings- DHCP IP Address Range :  Default is  from .100-.199 which should be plenty.
Make sure "Always Broadcast" is selected as that can help some clients.
Also make sure you have latest firmware.  If udating, be sure to back up. Some firmware updates wipe the config. Record any special ISP settings before attempting.
You may also want to do a factory reset of the DIR-655 and start clean.


text:
Q: Copy list structure from SharePoint Online to SharePoint 2010 I have one list (RequestList) in SharePoint Online.
I have a requirement for which I want to create a replica of this list (RequestList)  in SharePoint 2010.
I tried to copy structure of a list from SharePoint Online to SharePoint 2010 using Sharegate but I open the list, I am getting an error as below:
Could not load file or assembly 'Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' or one of its dependencies
is there any way to copy list structure from SharePoint Online to SharePoint 2010? Or I will have to create this list manually?
Thanks.

A: Try the following:

*

*Save the list in the SP Online as a template

*Download that file to your computer

*import it into the list template gallery for the 2010 site

*add an app in 2010 and choose that template

I do not have a way to test this out with a 2010 environment but this should work for you.
Also, another option would be to export to excel and save and import into 2010 with spreadsheet, of course you will have to go back and fix any non SLOT columns to date/choice etc.


text:
Q: Porting cshell code to bourne shell cat /tmp/SYSLOG | tee >( egrep -i "session limit" > sess.txt) | egrep "dst_port=3389 " > dst.txt

Works n C-shell but not Bourne.  I escaped the brackets and it no longer complains but it does not work. HELP!

A: That looks like Process substitution in bash.
If you're looking for genuine Bourne shell (rather than bash), you will have your work cut out simulating that.  In fact, your best bet would be to obtain a program that explicitly runs other programs (pee is one such; ISTR there being others — see Is it possible to distribute stdin over parallel processes? where GNU parallel is mentioned).
If you can't do that either, then you'll have to revisit the code.  The simplest fix looks like:
egrep -i "session limit"  /tmp/SYSLOG > sess.txt &
egrep    "dst_port=3389 " /tmp/SYSLOG > dst.txt  &
wait

This runs the commands in parallel. The second & is unnecessary but present for symmetry. In fact, this will work in any shell, so it is the portable solution. Unless the cat /tmp/SYSLOG operation is actually a complex program, this works at least as neatly as the original code.

A: Bourne doesn't do process substitution, i.e. >(...). Use bash instead.

A: You can call out to awk in your bourne shell script:
awk '
    tolower($0) ~ /session limit/ {print > "sess.txt"}
    /dst_port=3389 /              {print > "dst.txt"}
' /tmp/SYSLOG

If you happen to have GNU awk:
gawk -v IGNORECASE=1 '
    /session limit/  {print > "sess.txt"}
    /dst_port=3389 / {print > "dst.txt"}
' /tmp/SYSLOG


text:
Q: Instantiate and Fire Object, when OnTriggerEnter or OnCollisionEnter I would like a bullet that is fired from the Enemy, to bounce back off my Players shield.
I have set up my character and the enemy fires towards me at time intervals.
I can then activate my players shield (turning on a BoxCollider) and pressing a button.
So when the Bullet (IsTrigger) collides with my Players Shield (IsNotTrigger) I want to remove this Bullet and then Instantiate a new Bullet from the shield, in the direction of the Enemy.
I am also having an issue destroying the Bullet.
When the OnTriggerEvent or OnColliderEvent occurs (tried both), hundreds of bullets will appear from my Shield.  How do I only allow one bullet to be fired towards the enemy?
Below is part of my script, which is located in the GameObject of my Players Shield.
Ideally I would like to destroy the bullet once it has collided with an object.
void OnTriggerEnter(Collider col) {
    if (col.tag == "Weapon") {

        attack();
    }
}

private void attack() {

    if (!GameManager.instance.GameOver) {

    bulletReturnClone = Instantiate(bulletReturn, transform.position, transform.rotation) as GameObject;
    bulletReturnClone.GetComponent<Rigidbody>().velocity = transform.forward * 25f;

A: Im not really sure why you would want to despawn and respawn the bullet with a new velocity?
Depending on the shield geometry you could look up Coefficients of Restitution and therefore reflect the kinetic energy of the bullet into a realistic velocity.
Note the complexity of that maths will be proportional to the complexity of your shield geometry depending on the different collision primitives.

*

*Sphere-sphere

*Sphere-plane

*Sphere-terrain (terrain could represent any un-even surface)

Or are you trying to collect the bullets in some sort of "charge" mechanic to release them back at a different time?

A: Strachan,
That's not how I would approach the problem but I will stick to your desired solution then share some ideas for improvement.
void OnTriggerEnter(Collider col) {
if (col.tag == "Weapon") {

    attack(col);
    }
}

private void attack(Collider col) {

if (!GameManager.instance.GameOver) {

bulletReturnClone = Instantiate(bulletReturn,  transform.position, transform.rotation) as GameObject;
bulletReturnClone.GetComponent<Rigidbody>().velocity = transform.forward * 25f;
// the following line of code should remove the bullet from the shield collider in order to prevent any future problems like spawning multiple bullets or instantly destroying the newly created bullet
bulletReturnClone.GetComponent<Transform>().position *= bulletReturnClone.GetComponent<Rigidbody>().velocity;
Destroy(col.gameObject);
    }
}

If your trigger(Bullet) is tagged as weapon this code should achieve your intentional goal of reflecting the bullet in the direction of your shield pointing to by destroying the bullet and instantiating a new one and modifying it's velocity. It works but it's kind of sloppy development. It can be much better if you approach the problem from a different perspective - the one of the Bullet not the Shield.
Let's pretend for a moment you are a Bullet. All you do is fly in the direction you are shot. Once you collide with a terrain you stop/disappear. If this terrain is a shield you don't stop/disappear but change your direction (you get reflected).
  So... long story short... the one who should have a trigger collider is the bullet not the shield. OnTriggerEnter(Collider col) for the bullet script will destroy it but if col.tag == "Shield" the bullet will only change its direction without all the useless instantiations and transformations.
I'm too lazy to write the code  for the 2nd solution. If you got my point you should be able to easily write it down. Also learning through trials and errors helps you develop (excuse for me being lazy).


text:
Q: Implement vibrancy effect on NSTextField How can I implement vibrancy effect on NSTextField
I added an NSVisualEffectView with interface builder and try to use NSAppearance to add vibrancy to the label
var varLabel = NSTextField()
varLabel.stringValue = "Some"
varLabel.appearance = NSAppearance(named: .vibrantLight)

A: *

*Override allowsVibrancy.

Objective-C
@interface VibrancyTextField : NSTextField
@end

@implementation VibrancyTextField

- (BOOL)allowsVibrancy {
    return YES;
}

@end

Swift
class VibrancyTextField: NSTextField {
    override var allowsVibrancy {
        return true
    }
}

*Use textColor as Standard Colors. Other colors like RGB or Default Label Color won't work.

Objective-C
VibrancyTextField *testField = [VibrancyTextField new];
testField.stringValue = @"Hello ████████████████████";
testField.textColor = NSColor.systemGrayColor;
[testField release];

Swift
let testField = VibrancyTextField()
testField.stringValue = "Hello ████████████████████"
testField.textColor = .systemGrayColor

Screenshot


text:
Q: Density Function of Random Variable Related to Brownian Motion
Above is my question. I've done the first two parts, that's no problem. I'm stuck on finding the density of the rv $R = W_1 / M$. I have got as far as
$$g(x,y) = \frac{\partial^2}{\partial x \partial y} \Bbb P(M \le x, W_1 \le y) = \frac{2(2x-y)}{\sqrt{2\pi}}\exp \left(-\frac{1}{2}(2x - y)^2 \right)$$
for $x \ge y$ and $g(x,y) = 0$ for $x \le y$. I also have
$$ \Bbb P(R \ge r) = \Bbb P (W_1 \ge rM),$$
and so I'm now interested in evaluating a probability of the form "$\Bbb P(X \ge Y)$" for rvs $X = W_1$ and $Y = rM$. My attempt is then
$$\Bbb P(W_1 \le rM) = \int_{y < x} \frac{1}{r} g\left(\frac{x}{r},y\right) d(x,y),$$
where the $1/r$ factors come from the fact that $Y = rM$, not just $M$.
My issue is that this then gives $1$, for each $r$. So my density function is $1$ everywhere... which is of course not right (eg doesn't integrate to $1$). Of course, I only want to consider $r < 1$ as the probability is $0$ for $r > 1$, by definition of the two rvs. Also, I am concerned with the $1/r$ factors... when $r$ could be $0$.
Any advice would be most appreciated. Thanks.
PS - This is a probability question - not a finance question - so please don't suggest migrating it to quant.SE - thanks! :)

A: I don't see anything wrong in your calulations.
Integration yields
$$\begin{align*} \mathbb{P}(W_1 \leq r M) &= \frac{1}{r} \int_{\mathbb{R}} \int_{y<x} \frac{2(2x/r-y)}{\sqrt{2\pi}} \exp \left(- \frac{1}{2} (2x/r-y)^2 \right) \, dy \, dx \\ &= \frac{1}{r} \frac{2}{\sqrt{2\pi}} \int_{\mathbb{R}} \exp \left(- \frac{(2x/r-x)^2}{2} \right) \, dx \\ &= \frac{1}{r} \frac{2}{\sqrt{2\pi}} \int_{\mathbb{R}} \exp \left( -\frac{x^2 (2/r-1)^2}{2} \right) \, dx\end{align*}$$
Using the identity $$\int_{[0,\infty)} \exp \left(- \frac{x^2}{2\sigma^2} \right) \, dx = \frac{1}{2} \int \exp \left(- \frac{x^2}{2\sigma^2} \right) \, dx = \frac{1}{2} \sqrt{2\pi \sigma^2},$$ we get
$$\begin{align*} \mathbb{P}(W_1 \leq r M) = \frac{1}{r} \frac{1}{|2/r-1|} = \frac{1}{2-r} \tag{1} \end{align*}$$
for any $r \leq 1$, $r \neq 0$. Since
$$\mathbb{P} \left( \frac{W_1}{M} \leq 0 \right) = \mathbb{P}(W_1 \leq 0) = \frac{1}{2},$$
$(1)$ holds also for $r=0$. Differentiating $(1)$ with respect to $r$ gives the density of $W_1/M$.


text:
Q: How could I pass data to childView About
I'm developping ios app with MXParallaxHeader.
I use it in order to create twitter-like UI.
However, I don't know how to pass data from MXScrollView to childViewController when I go MXScrollView page.
Question
How could I pass data from MXScrollView to childViewController?
Sample Code
PreviousViewController
//MXScrollViewController=ParentVC of MarkerInfoTabViewController
class PreviousViewController:UIViewController {
.
.
    @IBAction func goMXScrollView(_ sender: Any) {
        let nextView = self.storyboard?.instantiateViewController(withIdentifier: "MXScrollViewController") as! MXScrollViewController
        self.navigationController?.pushViewController(nextView, animated: true)
    }
}

childViewController
//MarkerInfoTabViewController(=childVC of MXScrollView)

import Tabman
import UIKit
import MXParallaxHeader

class MarkerInfoTabViewController: TabmanViewController {

    var marker:Marker!
    private var viewControllers = [UIViewController?]()

    override func viewDidLoad() {
        super.viewDidLoad()

        let leftView = self.storyboard?.instantiateViewController(withIdentifier: "MarkerInfoLeftViewController") as! MarkerInfoLeftViewController
        let rightView = self.storyboard?.instantiateViewController(withIdentifier: "MarkerInfoRightViewController") as! MarkerInfoRightViewController

        //↓I want to pass data here
        leftView.marker = marker

        viewControllers = [leftView, rightView]

        self.dataSource = self

        // Create bar
        let bar = TMBar.ButtonBar()
        bar.layout.transitionStyle = .snap // Customize

        // Add to view
        addBar(bar, dataSource: self, at: .top)
    }
}

My App Image
・storyboard
・segue to header
・segue to childVC
Reference
My app is mostly the same as this app.

A: Just define a property in the child controller class
class ChildViewController {
    var passedData: MY_DATA_TYPE
    ...

and set it after the instantiation
let nextView = self.storyboard?.instantiateViewController(withIdentifier: "ChildViewController") as! ChildViewController
nextView.passedData = MY_PASSED_DATA
self.navigationController?.pushViewController(nextView, animated: true)


text:
Q: Enabling flags (Wall, pedantic) for C/C++ compilation within Eclipse I am using Eclipse to write C/C++ programs. I would like to compile my code using the -Wall and -pedantic flags. How do I enable these flags within Eclipse so they are used by default whenever I compile a C/C++ program?

A: Go to Eclipse -> Project Explorer -> your project -> context menu -> Properties.
A dialog appears. In the left pane, open "C/C++ Build" -> Settings. In the right pane, ensure that tab "Tool Settings" is selected -> Under "GCC C++ Compiler" select "Warnings" -> check the boxes that you want.
In your case, you want "Pedantic (-pedantic)". "All warnings (-Wall)" should already be checked by default. You may want "Extra warnings (-Wextra)" (alias "-W"), too.


text:
Q: UnintentionalCodeFirstException thrown by mstest I have a test project which references another project, which in turn references a third project containing my Entity Framework 5.0 file (edmx). I find that I can run database-driven unit tests directly from Visual Studio, but when I run from mstest I get the following errors:

System.Data.Entity.Infrastructure.UnintentionalCodeFirstException:
  Code generated using the T4 templates for Database First and Model
  First development may not work correctly if used in Code First mode.
  To continue using Database First or Model First ensure that the Entity
  Framework connection string is specified in the config file of
  executing application.

I have non-database connecting unit tests which run fine. I've fiddled with my various app.config EF connection strings and they seem to be OK (every tests runs fine on Visual Studio). The problem is when I run mstest from a command line on my desktop or on a build server. This is the command I use:

MSTest.exe /nologo /searchpathroot:"\Binaries"
  /resultsfileroot:"\TestResults"
  /testcontainer:"\Binaries\driver.orderedtest"
  /testcontainer:"\Binaries\EF.DataAccess.dll"
  /publish:"http://"
  /publishbuild:"vstfs:///Build/Build/99" /teamproject:"ProjectName"
  /platform:"Any CPU" /flavor:"Debug" /noisolation /detail:errormessage
  /detail:errorstacktrace /detail:stderr

I have references to all dll's in the test project, as outlined here: Entity Framework custom tool does not correctly embed or load the model as resource files
I've been on this for a few days off and on, and it looks to me that this is an EF 5.0 bug, but according to the connect link this should be fixed, but it doesn't seem to be the case.


text:
Q: PDMENU application missing in 22.04 Is there any reason to remove PDMENU application from version  Ubuntu 22.04 LTS?
Was it done consciously or is it a mistake?
Is there any recommended replacement for it that work in terminal?

A: I will not speak for this specific package or software, but the reason an application is removed from the software center commonly is that

*

*it appears not to be maintained anymore and, especially,

*it uses libraries that are outdated and not anymore supported on newer versions.


text:
Q: jQuery validate remote not sending correct json data There are a number of similar posts but this is not working for me.  I've tried it about 20 different ways now so if someone can put me on the right track its much appreciated.
First I tried this.  Seems to be correct according to the docs but the JSON that is being sent is just the element id ('element' is a jQuery element ref)
if (valData.ValidationItems[i].Date) {
    element.rules("add", {
        remote: {
            url: websiteBase + "Home/DateValidation",
            type: "post",
            data: {
                Date: function () { return $("#" + element[0].id).val() },
                Min: valData.ValidationItems[i].RangeMin,
                Max: valData.ValidationItems[i].RangeMax
            },
            dataType: "json"
        },
        messages: { remote: valData.ValidationItems[i].ValidationMessage }
    });
}

This next bit that I tried works one time but then locks up the browser
remote: function () {
    var remoteData = {
        Date: $("#" + element[0].id).val(),
        Min: data.ValidationItems[i].RangeMin,
        Max: data.ValidationItems[i].RangeMax
    }
    var remoteJSON = JSON.stringify(remoteData);
    var r = {
        url: websiteBase + "Home/DateValidation",
        type: "post",
        dataType: "json",
        data: remoteJSON
    }
    return r;
}

This is using jQuery validate 1.8 which is the version installed for MVC 3 projects.

A: So after trying this about 40 different ways I found one that works.  jQuery validate remote really tries to NOT encode your result as JSON if at all possible.  In most cases it encoded the "data" like a query string.
remote: {
    url: websiteBase + "Home/DateValidation",
    type: "post",
    dataType: "json",
    data: JSON.stringify({
        Date: $("#" + element[0].id).val(),
        Min: valData.ValidationItems[i].RangeMin,
        Max: valData.ValidationItems[i].RangeMax
    })
}

A: OK got this working.  The key is do NOT try to send valid JSON data to the server using the remote function.  Don't specify the contentType or dataType.  Make sure your controller or web service is prepared to receive a form POST.  Also the documentation is incorrect in that it says if you specify the "data" property it will override the default.  That is not true.  Finally, none of the methods from the Documentation or other posts about retrieving the element's value in the remote function work.  The only way to get it to fire the event and retrieve the updated element value every time it is updated is by using the "remote" method's default functionality.  In my case the element ID is a variable so this was undesirable.
In the end this is what worked for me, sending 3 values to the server encoded as form post parameters.
remote: {
    url: websiteBase + "Home/DateValidation",
    type: "post",
    cache: false,
    data: {
        Min: valData.ValidationItems[i].RangeMin,
        Max: valData.ValidationItems[i].RangeMax
    }
}

In the controller I retrieve the value and the dynamic element ID using
public ActionResult DateValidation(FormCollection parameters) {
    bool valid = true;
    try {
        string date = parameters[0];
        string elementID = parameters.Keys[0].ToString();
   ...


text:
Q: Python (3.5) - urllib.request.urlopen - Progress Bar Available? I'm trying to search the world wide web for this answer, but I feel there answer may be no. I'm using Python 3.5 and a library called urllib.request with a method called urllib.request.urlopen(url) to open a link and download a file.
It would be nice to have some kind of measure of progress for this, as the file(s) are over 200MB. I'm looking at the API here, and don't see any kind of parameter with a hook.
Here's my code:
downloadURL = results[3] #got this from code earlier up
rel_path = account + '/' + eventID + '_' + title + '.mp4'

filename_abs_path = os.path.join(script_dir, rel_path)
print('>>> Downloading >>> ' + title)

# Download .mp4 from a url and save it locally under `file_name`:
with urllib.request.urlopen(downloadURL) as response, open(filename_abs_path, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

Can anyone provide insight if they think I can potentially have a progress bar or would the only way be to use a different library? I'm looking to keep the code quite short and simple, I just need some indication of the file being downloaded. Thanks for any help provided!

A: @tdelaney's answer is great, but in Python 3.8 you have to use getvalue() method instead of read():
    import io, urllib.request

    with urllib.request.urlopen(Url) as Response:
        Length = Response.getheader('content-length')
        BlockSize = 1000000  # default value

        if Length:
            Length = int(Length)
            BlockSize = max(4096, Length // 20)

        print("UrlLib len, blocksize: ", Length, BlockSize)

        BufferAll = io.BytesIO()
        Size = 0
        while True:
            BufferNow = Response.read(BlockSize)
            if not BufferNow:
                break
            BufferAll.write(BufferNow)
            Size += len(BufferNow)
            if Length:
                Percent = int((Size / Length)*100)
                print(f"download: {Percent}% {Url}")

        print("Buffer All len:", len(BufferAll.getvalue()))

A: If the response includes a content-length you can read the incoming data in blocks and calculate percent done. Unfortunately, web servers that "chunk" responses don't always provide a content length, so it doesn't always work. Here is an example to test.
import urllib.request
import sys
import io

try:
    url = sys.argv[1]
except IndexError:
    print("usage: test.py url")
    exit(2)

resp = urllib.request.urlopen(url)
length = resp.getheader('content-length')
if length:
    length = int(length)
    blocksize = max(4096, length//100)
else:
    blocksize = 1000000 # just made something up

print(length, blocksize)

buf = io.BytesIO()
size = 0
while True:
    buf1 = resp.read(blocksize)
    if not buf1:
        break
    buf.write(buf1)
    size += len(buf1)
    if length:
        print('{:.2f}\r done'.format(size/length), end='')
print()


text:
Q: Multiple IOC Containers We've created some domain services.  On top of our services, we've added a Web Api layer on top to allow RESTFUL interactions with our services.  We are using StructureMap for IOC.  To get this to work I had to reference the domain and repository projects to our Web Api project.  I want to avoid this.
With these references, it could allow developers to start referencing domain objects or repositories in our service layer.  Through code reviews we can prevent that but I'd prefer to remove the references completely.
Our container is registered in this manner:
IContainer container = IoC.Initialize();
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);

[Service Layer] --> [Domain Services] -- >[Domain Models] and [Repositories]
How do I register these dependencies in our Domain Services but not the Web Api Service Layer?  Or have an IoC container for the Web Api Layer and then one for the Domain Services?  Domain Services is nothing more than a Façade/Orchestration.  It can be consumed by a Web Api Service Layer, WCF Service, or directly from applications like WPF or WinForms.
Thoughts?


text:
Q: WebPack: Module not found: Error: Can't resolve './src' in '...' I use webpack to create a project name KUAKUA. It always turn to this error and I have no idea. How can I fix the problem? I have search for many answers similar to mine but they don't work.Here are ralative screenshot:
menu


text:
Q: Why Isn't My Info Button Working? My Info button is showing up when I run my app but it doesn't do anything, no response when I click it.
In my ProfileViewController file:
- (void)viewDidLoad
{
    UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
    infoButton.frame = CGRectMake(290.0, 10.0, 15.0, 15.0);
    [infoButton addTarget:self action:@selector(toggleCreditsOpen:)forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:infoButton];

    [super viewDidLoad];
}

I also have the following two methods to load the about view (the screen that loads up when the button is clicked):
- (IBAction) toggleCreditsOpen:(id)inSender
{
    UIViewController *theController = [[UIViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];
    [self.navigationController presentModalViewController:theController animated:TRUE];
}

- (IBAction) toggleCreditsClosed:(id)inSender
{
    [self.navigationController dismissModalViewControllerAnimated:TRUE];
}

EDIT:
I am adding my full implementation file here:
#import "ProfileViewController.h"
#import "AboutViewController.h"

@implementation ProfileViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (IBAction)toggleCreditsOpen:(id)inSender
{
    UIViewController *theController = [[UIViewController alloc] initWithNibName:@"AboutViewController" bundle:nil];
    [self.navigationController presentModalViewController:theController animated:YES];
}

- (IBAction)toggleCreditsClosed:(id)inSender
{
    [self.navigationController dismissModalViewControllerAnimated:TRUE];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    UIButton *infoButton = [[UIButton buttonWithType:UIButtonTypeInfoDark] retain];
    infoButton.frame = CGRectMake(290.0, 10.0, 15.0, 15.0);
    //[infoButton addTarget:self action:@selector(toggleCreditsOpen:)forControlEvents:UIControlEventTouchUpInside];
    [infoButton addTarget:self action:@selector(toggleCreditsOpen:)forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:infoButton];

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

A: I don't know at all why this isn't working, but if I were to take a guess, I'd say it's in the         [self.navigationController presentModalViewController:theController animated:TRUE];
statement. From what I know, it should be:
[self.navigationController presentModalViewController:theController animated:YES];

See if it works after you do that. I'm not sure, but that could be the problem with your code.

A: hi
you are took a mistake to define your button..
just assign retain property at the end of button
like
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark] retain];
and also give
  [infoButton addTarget:self action:@selector(toggleCreditsOpen:)forControlEvents:UIControlEventTouchDown];

A: Using your provided code works for me, if self.navigationController is non-nil, and there exists an AboutViewController.xib in your main bundle. Otherwise, I don't see anything readily wrong.
If you don't have a navigation controller, the proper line in toggleCreditsOpen: would be:
[self presentModalViewController:theController animated:YES];

Edit:
If you want to dismiss the modal view later, its usually a good idea to do this with a delegate. Instead of
UIViewController *theController = [[UIViewController alloc] initWithWhatever];

you can do
AboutViewController *theController = [[AboutViewController alloc] initWithWhatever];

where AboutViewController has a delegate. Probably something like id<DismissModalProtocol> delegate;. Then, your view controller would implement this @protocol, and before it calls presentModalViewController:animated:, it'll set itself as the delegate. So very roughly, it would look something like this:
// AboutViewController.h
@protocol DismissModalProtocol;

@interface AboutViewController : UIViewController {
  id<DismissModalProtocol> delegate;
}
@property id<DismissModalProtocol> delegate;
@end

@protocol DismissModalProtocol <NSObject>
- (void)dismissController:(UIViewController *)viewController;
@end

// ProfileViewController.h
#import "AboutViewController.h"

@interface ProfileViewController : UIViewController <DismissModalProtocol>
@end

// ProfileViewController.m
@implementation ProfileViewController
- (void)dismissController:(UIViewController *)viewController {
  [self dismissModalViewControllerAnimated:YES];
}

- (void)toggleCreditsOpen:(id)sender {
  AboutViewController *controller = [[AboutViewController alloc] init];
  controller.delegate = self;
  [self presentModalViewController:controller animated:YES];
}
@end


text:
Q: Can't find file - FileNotFoundError: [Errno 2] No such file or directory my code looks like this:
import os
from os import listdir
from os.path import isfile, join
import pyexcel as p

rootdir = r'C:/Users/aleks/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith('.xls'):
            new_file = p.save_book_as(file_name=file, dest_file_name=file.split('.')[0]+ '.xlsx')
            os.remove(file)
        else:
            continue

Now I know that this part works fine as it returns exactly what I want:
rootdir = r'C:\Users\aleks\Desktop\test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(file)

Files are correctly listed after using print(file), but i can't convert them to xlsx as there is an error showing up: FileNotFoundError: [Errno 2] No such file or directory: 'file1.xls'. Which I find weird because I can clearly see the files after using print(file)
To clarify, in rootdir there are directories which contain .xls files that have to be converted into.xlsx

A: Try below code. I guess the problem is that you try to delete files in sub_directory that are different from your Python root.
for root, dirs, files in os.walk(rootdir):
    for name in files:
        if name.endswith('.xls'):
            fname = os.path.join(root, name)
            new_file = p.save_book_as(file_name=fname, dest_file_name=os.path.join(root, fname.split('.')[0]+ '.xlsx'))
            os.remove(fname)


text:
Q: XSL disable-output-escaping removes whitespaces Part of the XML:
<text>Title Happy</text>

In my XSL I have:
<xsl:value-of select="text" disable-output-escaping="yes" />

My output becomes
**TitleHappy**

My spacing went missing - there's supposed to be a space between  and .
I tried normalize-space(), it doesn't work.
Any suggestions? Thanks!

A: if you want whitespace from an xsl, use:
    <xsl:text> </xsl:text>
whitespace is only preserved if its recognized as a text node (ie: " a " both spaces will be recognized)
whitespace from the orignal source xml has to be preserved by telling the parser (for example)
parser.setPreserveWhitespace(true);

A: As your outputting HTML you could substitute your space with a non-breaking space

A: Do you have any control over the generation of the original XML? If so, you could try adding xml:space="preserve" to the text element which should tell the processor to keep the whitespace.
<text xml:space="preserve">Title Happy</text>

Alternatively, try looking at the "xsl:preserve-space" element in XSLT.
<xsl:preserve-space elements="text"/>

Although I have never used this personally, it might of some help. See W3Schools for more information.

A: thank you for everyone's input.
Currently I am using MattH suggestion which is to test for space and substitue to non-breaking space. Another method I thought of is to test for " " and substitue with " ". The space contain within a bold tags are actually output. Both methods worked. Don't know what the implications are though. And I still can't figure out why the spacing is removed when it is found between 2 seperate bold tags.


text:
Q: Should I store uploaded images outside webroot? For a website I am helping out on, they want to allow users to upload images for display. Obviously this has security implications. I have seen it discussed that uploaded images should be stored outside the webroot and than accessed by a script only.
However, when I reviewed OWASPS's discussion on file upload security, I did not see any mention by them of the necessity to store uploaded files outside of the webroot. https://www.owasp.org/index.php/Unrestricted_File_Upload . Their list of developer recommendations had a number of other steps to take, but surprisingly to me at least did not seem to mention storing the files outside the webroot.
Can it be considered safe to allow images to be uploaded in the webroot assuming that you follow the recommendations listed by OWASP at the link above?

A: No it's not necessary to store the images outside the webroot. You should however make sure that you limit all uploads to jpg's, png's, etc. Only image formats, otherwise as explained in the link you posted you do have a risk of attacks on your system. I would also create a folder dedicated to the uploaded images inside the webroot, keeps things more orderly, and make sure all images inside are set to read-only for web users.


text:
Q: Extract detailed symbol information (struct members) from elf file compiled with ARM-GCC I'm using ARM-GCC 4.7.4 to compile Code for a Cortex-M4. For our Debug tool I need knowledge about names, types and addresses of all variables in human readable format (e.g. .txt). The map file provides most of the information, unfortunately not for structure contents like below:
typedef struct {    float32_t   Ref;        // Input:   Reference Value
            float32_t   Fdb;        // Variable:    Feedback Value
            float32_t   Err;        // Input:   Control Error
            float32_t   Kp;     // Parameter:   Gain of the Proportional Part
            float32_t   Up;         // Output:  Output of Proportional Part
            float32_t   Ki;     // Parameter:   Gain of the Integral Part
            float32_t   Ui;     // Output:  Output of the Integral Part
            float32_t   OutPreSat;  // Output:  Not saturated Output
            float32_t   OutMax;     // Parameter:   Maximum Output
            float32_t   OutMin;     // Parameter:   Minimum Output
            float32_t   Out;        // Output:  Saturated Output
        } PI_REG;

 PI_REG BU_Uctrl_Udc_PI_Reg = BU_UCTRL_UDC_PI_REG_INIT;

Therefore I tried the tools nm, readelf and objdump to get something out of the .elf file which is compiled with parameter –g3 in dwarf-2 format. Only with objdump I could find the information I searched for:
objdump –Wi myfile.elf >symbols.txt

The following information about the typedef PI_REG can be found in symbols.txt file:
 <1><38883>: Abbrev Number: 2 (DW_TAG_base_type)
    <38884>   DW_AT_byte_size   : 4
    <38885>   DW_AT_encoding    : 4 (float)
    <38886>   DW_AT_name        : (indirect string, offset: 0x2c63e): float
 <1><38891>: Abbrev Number: 11 (DW_TAG_typedef)
    <38892>   DW_AT_name        : (indirect string, offset: 0xb336d): float32_t
    <38896>   DW_AT_decl_file   : 4
    <38897>   DW_AT_decl_line   : 370
    <38899>   DW_AT_type        : <0x38883>
 <1><390d7>: Abbrev Number: 14 (DW_TAG_structure_type)
    <390d8>   DW_AT_byte_size   : 44
    <390d9>   DW_AT_decl_file   : 6
    <390da>   DW_AT_decl_line   : 26
    <390db>   DW_AT_sibling     : <0x39176>
 <2><390df>: Abbrev Number: 16 (DW_TAG_member)
    <390e0>   DW_AT_name        : Ref
    <390e4>   DW_AT_decl_file   : 6
    <390e5>   DW_AT_decl_line   : 26
    <390e6>   DW_AT_type        : <0x38891>
    <390ea>   DW_AT_data_member_location: 2 byte block: 23 0 (DW_OP_plus_uconst: 0)
 <2><390ed>: Abbrev Number: 16 (DW_TAG_member)
    <390ee>   DW_AT_name        : Fdb
    <390f2>   DW_AT_decl_file   : 6
    <390f3>   DW_AT_decl_line   : 27
    <390f4>   DW_AT_type        : <0x38891>
    <390f8>   DW_AT_data_member_location: 2 byte block: 23 4 (DW_OP_plus_uconst: 4)

[left out structure members with offsets 6-32]
 <2><39159>: Abbrev Number: 15 (DW_TAG_member)
    <3915a>   DW_AT_name        : (indirect string, offset: 0xc1d9a): OutMin
    <3915e>   DW_AT_decl_file   : 6
    <3915f>   DW_AT_decl_line   : 35
    <39160>   DW_AT_type        : <0x38891>
    <39164>   DW_AT_data_member_location: 2 byte block: 23 24 (DW_OP_plus_uconst: 36)
 <2><39167>: Abbrev Number: 16 (DW_TAG_member)
    <39168>   DW_AT_name        : Out
    <3916c>   DW_AT_decl_file   : 6
    <3916d>   DW_AT_decl_line   : 36
    <3916e>   DW_AT_type        : <0x38891>
    <39172>   DW_AT_data_member_location: 2 byte block: 23 28 (DW_OP_plus_uconst: 40)
 <1><39176>: Abbrev Number: 3 (DW_TAG_typedef)
    <39177>   DW_AT_name        : (indirect string, offset: 0xc00d0): PI_REG
    <3917b>   DW_AT_decl_file   : 6
    <3917c>   DW_AT_decl_line   : 37
    <3917d>   DW_AT_type        : <0x390d7>

 <1><3c348>: Abbrev Number: 29 (DW_TAG_variable)
    <3c349>   DW_AT_name        : (indirect string, offset: 0xc3ece): BU_Uctrl_Udc_PI_Reg
    <3c34d>   DW_AT_decl_file   : 1
    <3c34e>   DW_AT_decl_line   : 40
    <3c34f>   DW_AT_type        : <0x39176>
    <3c353>   DW_AT_external    : 1
    <3c354>   DW_AT_location    : 5 byte block: 3 fc 67 0 20 (DW_OP_addr: 200067fc)

If I want to get information about variables, e.g. the structure BU_Uctrl_Udc_PI_Reg, I have to do the following:
Find an entry called "DW_TAG_variable" and gather following information:
------------------------------------------------------------------------
 - DW_AT_name: The name is BU_Uctrl_Udc_PI_Reg
 - DW_OP_addr: Base address is 200067fc
 - DW_AT_type: The data type can be found at line 39176

Search line 39176 and gather following information:
-----------------------------------------------------
 - It is a typedef (DW_TAG_typedef)
 - DW_AT_name: The typedef name is PI_REG
 - DW_AT_type: The definition can be found at line 390d7

Search line 390d7 and gather following information:
---------------------------------------------------
 - It is a structure (DW_TAG_structure_type)
 - DW_AT_byte_size: It is 44 bytes wide

Search the structure Members in upcoming lines until 44 bytes are reached:
--------------------------------------------------------

1. Member (DW_TAG_member):
 - DW_AT_name: Ref
 - DW_AT_data_member_location: 200067fc + 0
 - DW_AT_type: The data type can be found at line 38891:
 - DW_TAG_typedef: float32_t
 - DW_AT_type: The data type can be found at line 38883:
 - DW_TAG_base_type: float
 - DW_AT_byte_size: 4 bytes

2. Member (DW_TAG_member):
 - DW_AT_name: Fdb
 - DW_AT_data_member_location: 200067fc + 4
 - DW_AT_type: The data type can be found at line 38891:
 - DW_TAG_typedef: float32_t
 - DW_AT_type: The data type can be found at line 38883:
 - DW_TAG_base_type: float
 - DW_AT_byte_size: 4 bytes

[left out Members 3-9]

10. Member (DW_TAG_member):
 - DW_AT_name: OutMin
 - DW_AT_data_member_location: 200067fc + 36
 - DW_AT_type: The data type can be found at line 38891:
 - DW_TAG_typedef: float32_t
 - DW_AT_type: The data type can be found at line 38883:
 - DW_TAG_base_type: float
 - DW_AT_byte_size: 4 bytes

 11. Member (DW_TAG_member):
 - DW_AT_name: Out
 - DW_AT_data_member_location: 200067fc + 40
 - DW_AT_type: The data type can be found at line 38891:
 - DW_TAG_typedef: float32_t
 - DW_AT_type: The data type can be found at line 38883:
 - DW_TAG_base_type: float
 - DW_AT_byte_size: 4 bytes

Frankly speaking, a script file, which automatically gathers the information as above mentioned, would be more complex than my application. Additionally I have to admit that I not really know how I could write such a script. Is there a more easy way to get this type of information? Is there maybe some parameter for the objdump which would help me with that, although I think I tried all the relevant ones? Or does a tool exist which is able to do this? In the end I need a table like this (additionally it would be nice to have all the enums which of course can also be found within the .elf file):
0x200067fc  float   BU_Uctrl_Udc_PI_Reg.Ref
0x20006800  float   BU_Uctrl_Udc_PI_Reg.Fdb
[…]
0x20006832  float   BU_Uctrl_Udc_PI_Reg.OutMin
0x20006836  float   BU_Uctrl_Udc_PI_Reg.Out

The tool Fromelf http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0477c/index.html (included in Keil µVision) with the parameter --text exactly delivers such a table, but unfortunately I can't use this because it supposedly needs the .elf or in this case called .axf files compiled with Arm Compiler Toolchain to work. Additionally there are license issues.
Thanks for any hints.

A: is pahole what you need? it can dump variable structure with size and offset.
pahole −−reorganize −C foo xxx.out

struct foo {
int a; / 0 4 /
char c[4]; / 4 4 /
void b; / 8 8 /
long g; / 16 8 /
}; / size: 24, cachelines: 1 /
/ last cacheline: 24 bytes /
/ saved 8 bytes! /

A: You should be able to ask GDB to print this info for you, e.g.
gdb -q a.out
(gdb) ptype PI_REG

A: You can use eclipse CDT's gdb mi interface to programatically get this information.
private def loadElfFile(String elfFilePath) {
    var plugin = new MIPlugin

    var file = new File(elfFilePath)

    var cmdFactory = new CommandFactory("mi2")
    session = plugin.createSession(
        MISession::PROGRAM,
        'gdb',
        cmdFactory,
        file,
        #[],
        true,
        new NullProgressMonitor
    )
}

There you can query global variables and their types. Addresses are stored in the hexAddress property of values.
The problem with this approach is its slowness. A struct with 50 members takes almost 10 seconds to process. Querying all structs would take minutes. For IDE tool use cases (like a model transformation) this is impractical. You have to deep dive to elf and dwarf.


text:
Q: Given $n$ iid random variables $X_1, ..., X_n$ with mean $\mu$, then $X_1+...+X_n = n \mu + o(n)$ a.s. Here's my attempt, is it correct?
Let $S_n = X_1+...+X_n$. Since $S_n / n = \mu$ almost surely as $n \rightarrow \infty$, then $S_n = n \mu + o(n)$ almost surely as $n \rightarrow \infty$.

A: This is basically correct. However, one would say that $\lim_{n\to\infty}S_n/n=\mu$ almost surely instead of "$S_n / n = \mu$ almost surely as $n \rightarrow \infty$", as equality may not take place.


text:
Q: Finding Week, using current date ? In C#? In C# how can i find the week of the current date, i am trying to get the week number of the current date, can you help me, thank you.

A: See Calendar.GetWeekOfYear
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
      DateTime date1 = new DateTime(2011, 1, 1);
      Calendar cal = dfi.Calendar;

      Console.WriteLine("{0:d}: Week {1} ({2})", date1,
                        cal.GetWeekOfYear(date1, dfi.CalendarWeekRule,
                                          dfi.FirstDayOfWeek),
                        cal.ToString().Substring(cal.ToString().LastIndexOf(".") + 1));
   }
}
// The example displays the following output:
//       1/1/2011: Week 1 (GregorianCalendar)

A: If you need current week "global" number, you can use this:
using System;
using System.Globalization;

DateTime date = DateTime.Now;
int res = 0;

// First day of year
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstDay, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

// (Default) First four day week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday);

// First four day week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFourDayWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

// First full week from Sunday
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DayOfWeek.Sunday);

// First full week from StartOfWeek
res = CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(date, CalendarWeekRule.FirstFullWeek, DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek);

If you need week number in a month, use smth like such code:
 DateTime beginningOfMonth = DateTime.Now;

 while (date.Date.AddDays(1).DayOfWeek != CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
     date = date.AddDays(1);

 int result = (int)Math.Truncate((double)date.Subtract(beginningOfMonth).TotalDays / 7f) + 1;


text:
Q: В чём проблема ? Error making cache directory: /var/cache/yum/x86_64/7/base Я столкнулся с проблемой. Centos 7. Нет доступа к установке nginx и других пакетов. Директория по пути /var/cache/yum не присутствует. Также нет доступа для создания папки yum в каталоге /var/cache.
Пользователь "gent" был добавлен в группу "wheel".
Останавливал процесс selniux. Тоже не помогло. Но его я конфигурировать не умею. Может даже после отключения настройки доступа сохранились. Кроме того, после переключения на root sudo su произошла та же ошибка. Чистки кеша yum так же не удалась, сразу та же ошибка ниже.
Скажите, какие есть варианты?
Обновление:
$ ls -Z
drwx------. root root system_u:object_r:ldconfig_cache_t:s0 ldconfig
drwxr-xr-x. root root system_u:object_r:mandb_cache_t:s0 man

$ ls -l
total 4
drwx------.  2 root root   23 Apr  8  2020 ldconfig
drwxr-xr-x. 32 root root 4096 Apr  9  2020 man

ОШИБКА:
$ sudo yum install nginx Loaded plugins: fastestmirror
Error making cache directory: /var/cache/yum/x86_64/7/base error was: [Errno 13] Permission denied: '/var/cache/yum'

A: На каталоге бит immutable, в чём можно убедиться при помощи команды lsattr.
selinux также можно проверить при помощи просмотра аудит - лога.


text:
Q: Separated asset and ddp server for meteor mobile apps Is there a way to separate asset and ddp servers for clients running meteor mobile apps (IOS/Android). For web apps it's simple just need to setup ROOT_URL for DDP service and deliver the content of the app from a different server.
In case of mobile app option --server is working for both parts at the same time. Mobile apps will be updating assets from the server as connecting to DDP server.
For purpose of caching and distribution content for a large scale application we need to have separate channels for assets and for ddp connections.


text:
Q: CSS selector by inline style attribute Is there a CSS selector to select this element by its inline style attribute value?

...

something like
div[cssAttribute=cssValue]

A: Always look how the attribute is written in HTML (you can check it in the Elements tab in the browser). You have to use the exact same value. In my case: style="left: 100%;". And not style="left:100%" or anything like that.

A: The inline style attribute is no different to any other HTML attribute and can be matched with a substring attribute selector:
div[style*="display:block"]

It is for this very reason however that it's extremely fragile. As attribute selectors don't support regular expressions, you can only perform exact substring matches of the attribute value. For instance, if you have a space somewhere in the attribute value, like this:

...

It won't match until you change your selector to accommodate the space. And then it will stop matching values that don't contain the space, unless you include all the permutations, ad nauseam. But if you're working with a document in which the inline style declarations themselves are unlikely to change at all, you should be fine.
Note also that this is not at all selecting elements by their actual specified, computed or used values as reflected in the DOM. That is not possible with CSS selectors.

A: Including ";" works better for me.
div[style*="display:block;"]


text:
Q: Multiple Callouts - Making a Separate Callout for Each Record in a List I have to callout to an external API whenever a contact record has a certain field updated. The external API will only accept one record at a time, but of course I want to bulkify my code in the event that someone updates multiple contacts in Salesforce in a single transaction. What is the best way to generate separate requests to this API for each contact record that is updated?  Right now I am thinking of the following basic framework, but I imagine there could be better ways.
I realize only so many callouts can be made in a single transaction, but I will only be dealing with 2 or 3 records at most.
Many thanks
    public static void MakeSeparateRequests(List<Contact> Cons){

        for(Contact C : Cons){
            CreateMachine(C.ID);
        }
    }

    @future(callout=true)
    public static void CreateMachine(ID ContactID){

        Contact C = [SELECT Name, Title, Email, Phone, Account.Name, Account.NumberOfEmployees
                     FROM Contact WHERE ID = :ContactID LIMIT 1];

        Http http = new Http();
        HttpRequest request = new HttpRequest();
        etc...

A: You can have up to 100 callouts in a transaction, but the total number of asynchronous calls per day is relatively limited, and this design can cause a bottleneck. Much better if you just split them into groups of 100 and go from there:
Id[] values = new Id[0];
for(Contact record: Trigger.new) {
  values.add(record.Id);
  if(values.size() == 100) {
    CalloutUtils.doApiCall(values);
    values.clear();
  }
}
if(!values.isEmpty()) {
  CalloutUtils.doApiCall(values);
}

...
@future(callout=true)
public static void doApiCall(Id[] recordIds) {
  for(Contact record: [SELECT Name, Title, ... FROM Contact WHERE Id = :recordIds]) {
    HttpRequest req = new HttpRequest();
    ...

Doing it this way gives maximum performance while minimizing resource usage. Unless you run in to a problem that requires smaller batches, this is probably the simplest way to go.
You could also use Queueable, which would be my preference, but that requires a bit more setup.


text:
Q: Finding an $c>0$ such that $|x-y|<\delta$ implies $|f(x)-f(y)|Let $\delta>0$ be given and $f: A \subset \mathbb{R} \rightarrow \mathbb{R}$ an uniformly continuous function (with $A$ a nonempty interval (?)).
Is it possible to find a $c >0$ such that for all $x,y \in A$ we have
$|x-y| < \delta \Rightarrow |f(x) - f(y) | < c$?
This holds for example for each linear function (which are uniformly continuous). But it does not hold for the exponential function, which is not uniformly continuous.

A: To elaborate Did's comment:
Let $A\subseteq \Bbb R$ be an interval $f\colon A\to\Bbb R$ be uniformly continuous. By uniform continuity, there exists $a>0$ such that for all $x,y\in A$ with $|x-y|<a$, we have $|f(x)-f(y)|<1$.
For given $\delta>0$, let $n=\left\lceil \frac{\delta}a\right\rceil$ (so that $n-1<\frac \delta a\le n$). Then we succeed with $c=n$:
Let $x,y\in A$ with $|x-y|<\delta$.
For $k=0,\ldots, n$, let $t_k=x+\frac kn(y-x)$. Then $t_0=x$, $t_n=y$ and $|t_{k+1}-t_k|=\frac{|y-x|}{n}<\frac \delta n\le a$ for $0\le k<n$.
Note that $t_k\in A$ for all $k$ (this is where we use that $A$ is an interval!) We conclude $|f(t_{k+1})-f(t_k)|<1$ and so $$|f(y)-f(x)|\le |f(t_n)-f(t_{n-1})|+\ldots+|f(t_1)-f(t_0)|<n.$$


text:
Q: What are your "must-have" MacPorts? I hate to be all cliché with yet another "best [something]" question, but I am genuinely interested in what you most often install with MacPorts. When you get a new Mac, which ports do you first install?
So far, I've installed wget and watch, since I find those to be very useful on Linux machines. I also installed wine and winetricks to run a Windows program or two. And earlier today I started playing with Scala, so I installed the scala28 port.
Tip: to see your installed ports, use the port installed command.

A: I just compile from source, since all of the important programs build easily on Mac OS X these days. Here's a great article on the advantages of building your own stuff vs. using package managers.
Having said that, here's my quick list:

*

*Mercurial

*Git

*GNU Privacy
Guard 1.4.x

*ffmpeg

*MySQL Best directions I've seen for building 32 or 64-bit MySQL on Mac OS X:
DIYMacServer

A: In no particular order:

*

*git - git

*signing-party - GnuPG key signing utils, pulls in GnuPG as well

*ntop - A Unix tool that shows the network usage, similar to what the popular top Unix command does.

*sslscan - sslscan queries SSL services, such as HTTPS, in order to determine the ciphers that are supported

*watch - execute a program periodically, showing output fullscreen

*nmap - Network port scan to see what ports are open

*coreutils GNU coreutils. Includes gnu versions of basic unix commands, including "color ls" (gls)

*pstree - Process tree listing

*tcping - tcp
based network connectivity checker
(like ping but with TCP for when ICMP
is blocked)

*wget - non-interactive
network downloader. Supports http,
https and ftp

*apg - Automated Password Generator - toolset for generating random passwords

A: First thing I do is update to the latest bash version... then I usually grab some updated versions of utilities:

*

*grep

*sudo

*man

*info (although i had to go with the fink version for this, macports is bugged)

*gdiff

Then on to my development tools like subversion, git, vim, macvim, python3, etc.  I heart MacPorts :P

A: *

*bash

*bash-completion (very important)

*nmap

*file

A: *

*wget : is command-line that allow me to retrieve any file using HTTP, HTTPS and FTP.

*tree : displays a tree-view of my directories & files, with deep-level option.

You can participate with your MacPorts by typing :

port installed requested

A: The Google CL tools are cool and useful (I do a lot with Docs).

A: This is my essential list, in the order that I install them.

*

*arping

*watch

*wireshark

*figlet

*git

*gnupg

*ipcalc

*lynx +ssl

*minicom

*mtr

*ncftp

*nmap

*pstree

*pwgen

*p0f

*ssldump

*stunnel

*tcpflow

*unrar

*w3m

*wget

A: For PHP web development:

*

*coreutils

*kcachegrind

*git

*svn


text:
Q: Friend function can't access class variables and can't understand Namespaces I thought that friend functions could access class variables as in how I try to do v.x, v.y, v.z in the << function. But it doesn't compile. It says it's unable to resolve identifier at those lines.
Also I'm trying to learn how to use namespaces. Even though I use the namespace vec in the implementation file I still have to include Vector:: before everything so what's the point?
Header file:
#ifndef VECTOR_H
#define VECTOR_H

namespace vec {

    class Vector {
    private:
        double x, y, z;

    public:
        Vector(double, double, double);
        friend std::ostream& operator<<(std::ostream&,  const Vector&);

    };

}

#endif  /* VECTOR_H */

.cpp file:
#include "Vector.h"
#include <iostream>
using namespace vec;

//Constructor
Vector::Vector(double x1 = 0, double y1 = 0, double z1 = 0) {
    x = x1;
    y = y1;
    z = z1;
}

//Have also tried adding vec:: and Vector:: before operator<< here.
std::ostream& operator<<(std::ostream& out, const Vector& v) {
    out<<"<"<<v.x<<", "<<v.y<<", "<<v.z<<">";
    return out;
}

A: Your compile error may relative to below issues:

*

*Default parameter only goes to function declaration not function
definition, you are doing the other way around.

*Also, in Vector.cpp you should wrap up your class member function
definitions in namespace instead of calling using directive.

Try:
Vector.h
#include <iostream>
class Vector {
    private:
        double x, y, z;

    public:
        Vector(double x1 = 0, double y1 = 0, double z1 = 0);
                        ^^              ^^             ^^
        friend std::ostream& operator<<(std::ostream&,  const Vector&);

    };

Vector.cpp
namespace vec
{
   Vector::Vector(double x1, double y1, double z1)
   :x(x1), y(y1), z(z1)
   {
   }
}

A: I believe part of the problem is that your vec.h doesn't have #include <iostream>, so the type std::ostream is unidentified in that file, and since that part is compiled before the vec.cpp main part, it fails to recognise your function.
You also need to put your operator<< into the namespace of vec. After all, you have asked for a friend function within that namespace.
With these two changes, your code compiles with gcc -Wall -Wextra -O2.

A: The friend std::ostream& operator<< declaration appears in namespace vec, so the definition should be prefixed by vec::.  Your comment says you tried that - maybe you got confused by the other error messages billz documents, but you should reinstate vec::operator<< or surround it with namespace vec { ... }.
This creates an error like:
ns.cc: In function `int main()':
ns.cc:26: error: ambiguous overload for 'operator<<' in 'std::cout << w'
ns.cc:19: note: candidates are: std::ostream& operator<<(std::ostream&, const vec::Vec&)
ns.cc:10: note:                 std::ostream& vec::operator<<(std::ostream&, const vec::Vec&)


text:
Q: What does "double encoding" mean for a Zoom API URL? In the Zoom Video SDK API documentation found here: https://marketplace.zoom.us/docs/api-reference/video-sdk/methods/#operation/sessionStatus it says

The session's ID. If the ID begins with a / character or contains // characters, you must double-encode the ID value.

The session ID is used in the URL itself, like /api/sessions/:sessionId/status. So having a '/' character in the URL does seem like a problem (and in practice, it is). For example, I can get a session id like "4I8wtN3QRkmf4izPrc/2qA==" What's not clear to me is what "double encoding" means here. I've tried:

*

*URL encoding the session ID

*Base64 encoding the session ID

*"Data" escaping the session ID (from the Uri class)

But none of it results in a valid session ID according to Zoom. What am I expected to do to escape the / in the session id?
Note that if I get a session ID without a / in it, my code works perfectly. So the problem is definitley escaping that slash.

A: After a bunch more searching I found this post:
https://devforum.zoom.us/t/double-encoding-on-uuids/50695
Which shows an ID with the correct "double encoded" version. It had this token 4//M4niJTOCN0Sx/yjwA6w== with the correct encoding being 4%252F%252FM4niJTOCN0Sx%252FyjwA6w%253D%253D. Upon inspection, this appeared to be a double URL encoding. When I did:
HttpUtility.UrlEncode(HttpUtility.UrlEncode(sessionId)
the endpoint responds correctly.
In short, the endpoint expects a double URL encoding of any id that contains a / (not just begins with or double as the documentation says).


text:
Q: Populating the dropdown on the basis of selected value I have four drop down and each drop down having corresponding Id's. I want to hide and show second drop down on the basis of selected value from drop down1.
Update:
For example, on the selection of M I want to hide
 having id "c"

 <select>
   <option value="F">F</option>
   <option value="M">M</option>
  </select>

   <select>
     <option value="S">S</option>
     <option value="M">M</option>
   </select>

A: You can try something along the following:

$("select").change(function() {
  $(this).next("select").toggleClass("hidden", this.value == "no")
});
.hidden {
  display: none;
}

<select>
  <option></option>
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>
<select class="hidden">
  <option></option>
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>
<select class="hidden">
  <option></option>
  <option value="yes">Yes</option>
  <option value="no">No</option>
</select>

Updated answer according to comments:

$("select").change(function() {
  $(this).parent().next().toggleClass("hidden", this.value == "M")
});
.hidden {
  display: none;
}

  <select>
    <option value="F">F</option>
    <option value="M">M</option>
  </select>

  <select>
    <option value="S">S</option>
    <option value="M">M</option>
  </select>

Reference:

*

*parent()

*next()

*toggleClass()

*jQuery selectors

A: You can try something like this and repeat the pattern for every select you want.
HTML
<select id="slc1">
    <option value="0">No</option>
    <option value="1">Yes</option>
</select>

<select id="slc2" style="display: none">
    <option value="0">No</option>
    <option value="1">Yes</option>
</select>

JS
$( "#slc1" ).change(function () {
    value = $("#slc1").val();
    if ( value === '0' ) $( "#slc2" ).hide();
    else if (value === '1') $( "#slc2" ).show();
});


text:
Q: How to POST an MP4 using Python requests? I am trying to upload an MP4 file, using requests.post. I'm not sure if it is due to the size of the file, as it is 3.2MB and I have seen people saying they have issues over 1.5MB. Any help is appreciated. Thanks
def post_video(URL):
files = {'file': open(file_path, 'rb')}
response = requests.post(URL, files=files)
return response

The response code should 204, however it is returning 500. The request works on Swagger UI

A: It won't let me comment,
The most likely cause is that you're not adding a header to your post that is required. I'd look at the REST API's documentation or even the Swagger UI and enter the developer console, watch the output and ensure you're adding everything needed.
Headers usually include the content type and sometimes include an authentication token, have you authenticated with the end point?
Here is an example of my proposition:
    def getresponse:
     userpass = b64encode(b"<username>:<password>").decode("ascii")
     headers = {'Content-type':'video/mp4', 'Authorization': 'Basic ' + userpass}
     files = {'file': open(file_path, 'rb')}
     response = requests.post(URL, files=files, headers=headers)
     return response


text:
Q: PHP to download zip file works when called directly but not from web application I have a PHP code which produces a zip file and make it downloadable from browser. The download part looks like:
download.php
// force client download
if (headers_sent()) {
    echo 'HTTP header already sent';
} else {
    if (!is_file($zipFile)) {
    header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
    echo $zipFile . ' not found';
    } else if (!is_readable($zipFile)) {
        header($_SERVER['SERVER_PROTOCOL'].' 403 Forbidden');
        echo $zipFile . ' not readable';
    } else {
        ob_start();
        // http headers for zip downloads
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $zipName . '"');
        header('Content-Transfer-Encoding: binary');
        header('Connection: Keep-Alive');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');

        set_time_limit(0);
        ob_flush();
        ob_clean();
        readfile($zipFile);
    }
}

When called from the browser directly like localhost/download.php it works and makes me download the zipped file properly.
However, I need to call it from my JS web application.
The way I am invoking it is via a POST AJAX request that look like this:
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE

var php_url = '/localhost/download.php' // ?wfs_url=' + url + 'format=' + format_list[0];
// (https://stackoverflow.com/a/53982364/1979665)
var formData = new FormData();
formData.append('wfs_url', url);
formData.append('format', format_list[0]);
xhr.open('POST', php_url);
xhr.onreadystatechange = function () {
    if (xhr.readyState===4 && xhr.status===200) {
        alert('Server reply: ' + xhr.responseText);
    }
}
xhr.send(formData);

return false;

The code is triggered when I click on a button.
Apparently it's doing "something". The PHP intermediate outputs (some folders) are correctly created, but the download does not begin.
The alert('Server reply: ' + xhr.responseText); part shows a strange message with some messy symbols, which I guess derives from the files created and read as text somehow.
Here is a screenshot of the message:

A: The PHP script is sending the actual binary source of the zip file, while the AJAX request is trying to display it as text, that's the garbage you get.
If you really want to keep the AJAX (it would be more simple to just make a <form> that is sent to download.php), you could do one two things:

*

*Just print the URL to $zipFile in PHP, and then when you get the response redirect to it with window.location.href=xhr.responseText;.

*Save the response as a zip file. See How to save binary data of zip file in Javascript?

A: After following option 2 in @Gabriel accepted answer I was able to make my code working. Here is the modified version of the JS (I didn't make any change in the PHP code):
var php_url = '/localhost/download.php' // ?wfs_url=' + url + 'format=' + format_list[0];
// (https://stackoverflow.com/a/53982364/1979665)
var formData = new FormData();
formData.append('wfs_url', url);
formData.append('format', format_list[0]);
xhr.open('POST', php_url);
xhr.onreadystatechange = function () {
    if (xhr.readyState===4 && xhr.status===200) {
        var blob = new Blob([xhr.response], { // SOLUTION
            type: "application/zip", // SOLUTION
        }); // SOLUTION
        var filename = "test.zip"; // SOLUTION
        if (navigator.msSaveOrOpenBlob) { // SOLUTION
            navigator.msSaveOrOpenBlob(blob, filename); // SOLUTION
        } else { // SOLUTION
            var a = document.createElement("a"); // SOLUTION
            document.body.appendChild(a); // SOLUTION
            a.style = "display:none"; // SOLUTION
            var url = window.URL.createObjectURL(blob); // SOLUTION
            a.href = url; // SOLUTION
            a.download = filename; // SOLUTION
            a.click(); // SOLUTION
            window.URL.revokeObjectURL(url); // SOLUTION
            a.remove(); // SOLUTION
         } // SOLUTION
    }
}
xhr.responseType = "arraybuffer"; // SOLUTION
xhr.send(formData);


text:
Q: Desktop appears as a terminal when viewed via VNCserver client I have installed vnc server on a RHEL 6.5 machine using the following commands:
yum -y install tigervnc-server xorg-x11-fonts-Type1

and have made the changes to the /etc/sysconfig/vncservers file to add the user and set the password and adjusted the resolution.
When I try to access the server via vnc client I am seeing something like this (NOT THE ORIGINAL IMAGE but a look alike) instead of the desktop:

I found an other issue which is relevant to the same issue, Why VNC not showing actual Remote Desktop, but was unable to understand from it how I can make it work on a RHEL 6.4 machine.
Here is the snapshot of /.vnc/xstartup:


text:
Q: countdowntimer in OnlineExam autosubmit with time elapsed & load next data by AJAX & if page refresh then next load with old time when refresh I used Reverse countdown to zero from time set to minutes
A student need to appear exam and complete it for a given time in minutes.
1>After n minutes the page must be auto submitted.
i>if yes,then the page must be submitted.But during that duration the countdown must continued.
ii>if exit,then student must proceed the exam for rest of his time duration.
$('#hour_timer').countdowntimer({
    hours: hours,
    minutes: minutes,
    seconds: seconds,
    size: "xs",
    tickInterval: 1,
    timeUp: timeisUp
});

A:  $('#hour_timer').countdowntimer({
hours: hours,
minutes: minutes,
seconds: seconds,
size: "xs",
tickInterval: 1,
timeUp: timeisUp
});

Here
      timeisUp is function which invoke after times up. Which fulfill my requirement of times up issue.
And save time after each question submission which helps me to next time to load the question with remaining time with little bit calculation.