text:
Q: Executing viewmodels command on enter in TextBox I want to execute a command in my viewmodel when the user presses enter in a TextBox.
The command works when bound to a button.
<Button Content="Add" Command="{Binding Path=AddCommand}" />

But I can't bring it to work from the TextBox.
I tried an Inputbinding, but it didn't work.
<TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=AddCommand}" Key="Enter"/>
</TextBox.InputBindings>

I also tried to set the working button as default, but it doesn't get executed when enter is pressed.
Thanks for your help.

A: Here's an attached dependency property I created for this. It has the advantage of ensuring that your text binding is updated back to the ViewModel before the command fires (useful for silverlight which doesn't support the property changed update source trigger).
public static class EnterKeyHelpers
{
    public static ICommand GetEnterKeyCommand(DependencyObject target)
    {
        return (ICommand)target.GetValue(EnterKeyCommandProperty);
    }

    public static void SetEnterKeyCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(EnterKeyCommandProperty, value);
    }

    public static readonly DependencyProperty EnterKeyCommandProperty =
        DependencyProperty.RegisterAttached(
            "EnterKeyCommand",
            typeof(ICommand),
            typeof(EnterKeyHelpers),
            new PropertyMetadata(null, OnEnterKeyCommandChanged));

    static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        ICommand command = (ICommand)e.NewValue;
        FrameworkElement fe = (FrameworkElement)target;
        Control control = (Control)target;
        control.KeyDown += (s, args) =>
        {
            if (args.Key == Key.Enter)
            {
                // make sure the textbox binding updates its source first
                BindingExpression b = control.GetBindingExpression(TextBox.TextProperty);
                if (b != null)
                {
                    b.UpdateSource();
                }
                command.Execute(null);
            }
        };
    }
}

You use it like this:
<TextBox
    Text="{Binding Answer, Mode=TwoWay}"
    my:EnterKeyHelpers.EnterKeyCommand="{Binding SubmitAnswerCommand}"/>

A: You need to define Gesture instead of Key property of the KeyBinding:
<TextBox.InputBindings>
    <KeyBinding Gesture="Enter" Command="{Binding AddCommand}"/>
</TextBox.InputBindings>

A: I know I am late to the party, but I got this to work for me. Try using Key="Return" instead of Key="Enter"
Here is the full example
<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>

Make sure to use UpdateSourceTrigger=PropertyChanged in your binding, otherwise the property will not be updated until focus is lost, and pressing enter will not lose focus...
Hope this was helpful!

A: You have probably not made the command a property, but a field. It only works to bind to properties. Change your AddCommand to a property and it will work. (Your XAML works fine for me with a property instead of a field for the command -> no need for any code behind!)

A: In addition to Mark Heath's answer, I took the class one step further by implementing Command Parameter attached property in this way;
public static class EnterKeyHelpers
{
        public static ICommand GetEnterKeyCommand(DependencyObject target)
        {
            return (ICommand)target.GetValue(EnterKeyCommandProperty);
        }

        public static void SetEnterKeyCommand(DependencyObject target, ICommand value)
        {
            target.SetValue(EnterKeyCommandProperty, value);
        }

        public static readonly DependencyProperty EnterKeyCommandProperty =
            DependencyProperty.RegisterAttached(
                "EnterKeyCommand",
                typeof(ICommand),
                typeof(EnterKeyHelpers),
                new PropertyMetadata(null, OnEnterKeyCommandChanged));

        public static object GetEnterKeyCommandParam(DependencyObject target)
        {
            return (object)target.GetValue(EnterKeyCommandParamProperty);
        }

        public static void SetEnterKeyCommandParam(DependencyObject target, object value)
        {
            target.SetValue(EnterKeyCommandParamProperty, value);
        }

        public static readonly DependencyProperty EnterKeyCommandParamProperty =
            DependencyProperty.RegisterAttached(
                "EnterKeyCommandParam",
                typeof(object),
                typeof(EnterKeyHelpers),
                new PropertyMetadata(null));

        static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            ICommand command = (ICommand)e.NewValue;
            Control control = (Control)target;
            control.KeyDown += (s, args) =>
            {
                if (args.Key == Key.Enter)
                {
                    // make sure the textbox binding updates its source first
                    BindingExpression b = control.GetBindingExpression(TextBox.TextProperty);
                    if (b != null)
                    {
                        b.UpdateSource();
                    }
                    object commandParameter = GetEnterKeyCommandParam(target);
                    command.Execute(commandParameter);
                }
            };
        }
    }

Usage:
<TextBox Text="{Binding Answer, Mode=TwoWay}"
    my:EnterKeyHelpers.EnterKeyCommand="{Binding SubmitAnswerCommand}"
    my:EnterKeyHelpers.EnterKeyCommandParam="your parameter"/>


text:
Q: Types of deployment in asp.net What are the types of deployment we have in asp.net?
Till now what I am doing?
I use to publish my website in any folder than copy paste the compiled file to the inetpub folder [where my website is configured with the IIS]. I am not sure what kind of deployment this is, is it XCOPY? But I am not using any command line tool.

A: So you have the following options
xcopy deployment
Compile your asp.net application and copy all the files to your server. You can do this by using FTP or shared directories. (Or anything else to transfer files.)
WebDeploy
You have the possibility to deploy your asp.net webpage directly form your Visual Studio. If you go to "Build" and you choose "Publish Web". To be able to to do this you have to configure your server before. But this works automatically after you have set up everything. It's very handy since your deployment becomes easy to rebuild.
http://weblogs.asp.net/scottgu/archive/2010/09/13/automating-deployment-with-microsoft-web-deploy.aspx
Web Setup - Installer
Visual Studio provide also the option to build an installer. This works like installing usual software on your windows computer with the installer wizard. (See the link)
http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx
Manage multiple server
There is also a way of managing the deployment of multiple servers. It seems to be a bit more complicated but could be interesting for professionals. (Check out on Google Microsoft Web Farm Framework 2.0

A: To answer your question: yes, what you are using is called xcopy deployment. Even though you do not type xcopy . ... it is still a 'plain copy' and therefore called xcopy deployment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Yii: Following strict MVC rules to ensure that all the business logic is in appropriate places Sticking to MVC basics in Yii, I am trying to embed my business rules in the model class but facing problem in implementing it. The problem at hand is to stop the user from making duplicate entries and code the function in model class that checks if the entry already exists in table. I want to write a method in my model class which would query the sames model's underlying table and if the new business entity exists, it simply returns false. If I code this in controller, I can achieve the desired functionality but I want to keep this in model so that where ever the model is used, I can access the method and also stick to MVC basics which dictates Thin Controllers and Thick Models. Thanks in advance.

A: The best way would be to avoid the use of active record instances (at least) directly in the controller.
Instead you should create service-like structures, which contains the interaction between your CActiveRecord and CFormModel instances. This would let you better isolate the presentation layer (views, controllers and templates) from model layer.
Such services also would be able to hold (and sometimes, react upon) errors/exceptions thrown by CActiveRecord and CFormModel instances, that it utilizes.

A: Cross-site Request Forgery Prevention may be what you are looking for? unless your idea of 'duplicate entries' is directly related to your business model, in which case you can override the CActiveRecord.beforeSave() and put your logic in there, if this method returns false, the record won't be saved to the database.
If you use the later method, and you want to pass the error to the view and display to the user, you can always use the CModel.addError() method, in this case in your beforeSave method.
There is another option though, which is using custom validators.
which is more appropriate? depends on your business logic.


text:
Q: Jquery - Field value flickers after resetting the form I am running this function below:
    $('.cancelbutton').click( function() {

    $('#gform2').attr('action','/ajax/add.php');
            $('input[name=aid]').val('0');
            $('.cancelbutton').hide();

            var reset_formdate = $('#adate').val();

            $('#gform2')[0].reset();
            $('input[name=adate]').val(reset_formdate);

        });

The issue Im seeing is after this function is ran the value in in the field adate flickers at least 10-15 times. Any ideas why it would do that? Never seen this before. It doesnt matter what field I put a value in, if I add the value to the field after the reset command the value in that field flickers. When I mean by flickers I mean the value shows/hides really fast like its blinking. I ran Firebug in Firefox while this was happening and it doesnt show any additional calls being made. Any suggestions?

A: Looks like I figured it out. I had the function inside a js script that was being return via a ajax call. I moved the function to the page itself that was making the ajax call and now it doesnt flicker.


text:
Q: Flash can't show Azerbaijan characters I'm developing application on Azerbaijan Language(in flash cs5 on actionscript 3), when I copy symbols from word document to flash it shows only the letters which are same in Latin. For example in "fəallıq göstəricisi" flash converts second and 13th symbols(both are "ə") to rectangles. What is a problem and how to fix? I'm using Sylfaen font at the moment.

A: The file being loaded should be saved with UTF-8 encoding did you try it?


text:
Q: Read percentile data Pxx(a,b) Here is the data
P0(24,0) P25(32.1875,26.6735) P50(35.4167,31.383) P75(40.45,42.6203)
P90(50.55,59.1531) P95(53.05,77.3846) P99(60.21,128.643)
P99.5(60.605,236.321) P99.9(60.921,5854.43) P100(61,63000)

I know P0 means 0th percentile and so on. What are the values in the brackets

A: It seems like there are two variables, a and b.
The first entry corresponds to a and the second entry corresponds to b.
P25(32.1875,26.6735) means 32.1875 is the 25th percentile of a and 26.6735 is the 25th percentile of b.


text:
Q: selenium and webdriver manager I am having issues with selenium and webdriver_manager. This script works on my local machine but when I run it on a Linux(ubuntu) server it errors out. It has a problem with:..
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

Any ideas how to solve this?
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.utils import ChromeType

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get('http://python.org')

print(driver.title)

I am getting the following error
====== WebDriver manager ======
Current google-chrome version is 101.0.4951
Get LATEST chromedriver version for 101.0.4951 google-chrome
Trying to download new driver from https://chromedriver.storage.googleapis.com/101.0.4951.41/chromedriver_linux64.zip
Driver has been saved in cache [/root/.wdm/drivers/chromedriver/linux64/101.0.4951.41]
---------------------------------------------------------------------------
WebDriverException                        Traceback (most recent call last)
Input In [1], in <cell line: 4>()
      2 from selenium.webdriver.chrome.service import Service
      3 from webdriver_manager.chrome import ChromeDriverManager
----> 4 driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

Also gives me this error.
WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

A: I figured it out after quite a bit of testing.
Add this condition to build webdriver fixed it
if sys.platform == 'win32':
    driver = webdriver.Chrome(ChromeDriverManager().install())
if sys.platform == 'linux':
    driver = driver = webdriver.Chrome(service=s, options=chrome_options)
    driver.maximize_window()

final code:
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
s = Service(CHROMEDRIVER_PATH)
WINDOW_SIZE = "1920,1080"
# Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.add_argument('--no-sandbox')
from time import sleep

if sys.platform == 'win32':
    driver = webdriver.Chrome(ChromeDriverManager().install())
if sys.platform == 'linux':
    driver = driver = webdriver.Chrome(service=s, options=chrome_options)
    driver.maximize_window()
# Get the response and print title
driver.get("https://www.python.org")
print(driver.title)
driver.close()


text:
Q: JS validation, why this code won´t work? I can´t get the validation in JS, and don´t understand why it doesn´t work.
The user should get an alert if at least one of the checkboxes isn´t checked.
It doesn´t work, because the form gets submitted ok even if if none checkboxes are checked.

<form name="calcular" onsubmit="return validar()" method="post">
<input type ="checkbox" name="servicios[]" id="s1" value="sinservicios">Sin servicios

<input type ="checkbox" name="servicios[]" id="s2" value="dosservicios">Dos servicios

...

A: You may try using the checked property to ensure that at least one of the 2 checkboxes is checked:

Also notice we should return true in case the validation succeeds.
The reason why your code doesn't work is because you have used the value property. That's always gonna return the value attribute of your checkbox (sinservicios or dosservicios) no matter if the user checked or not this checkbox. It will never return an empty string which is what you seem to be testing for in your if condition.


text:
Q: How to read and write text between two pattern matches I am writing a code to read a text file and give output based on pattern
matching.
For example, if "aa" comes in a file, it should start writing from there
till it encounters another matched pattern "}}".
I have written a code which matches a pattern. but it only prints the  pattern that is being matched.
import java.util.regex.*;
import java.io.*;

public class Reader {
public static void main(String[] args) throws          ParserConfigurationException,             SAXException, IOException {

    File xmlFile = new File("location.txt");
    Reader fileReader = new FileReader(xmlFile);
    BufferedReader bufReader = new BufferedReader(fileReader);

    StringBuilder sb = new StringBuilder();
    String line = bufReader.readLine();
    while( line != null){
        sb.append(line).append("\n");
        line = bufReader.readLine();
    }
    String string = sb.toString();

    //System.out.println(string);

    int indexHello = string.lastIndexOf("aa");
    int indexBye = string.indexOf("}}", indexHello);
    String newString = string.substring(indexHello, indexBye+1);
    System.out.println(newString);}
    bufReader.close();

   }

         }

Expected result should be like
aa (all the content till it matches "}}")  .................}}
UPDATE: Somehow, I am able to read between "aa" and "}}". Now, my question is-  There are various occurrences of aa ....}} and I want to print all of them.

A: happy day. I hope what u want is this.
static String initiator = "aa";
static String finalizer = "}}";
static String target = "aa_Content_}}";

public static void main(String[] args) {
    int statrtIndex = getContentStartIndex(initiator, target);
    int endIndex = getContentEndIndex(finalizer, target);
    String content = target.substring(statrtIndex, endIndex);
    System.out.println(content);
}

private static int getContentStartIndex(String initiator, String target) {
    return target.indexOf(initiator) + initiator.length();
}

private static int getContentEndIndex(String finalizer, String target) {
    return target.indexOf(finalizer);
}

if right, i'm happy. else, i'm sorry.
i'm not good at English. but i want to be help. :)
it print between aa, }}.

A:                            import java.io.BufferedReader;
          import java.io.File;
          import java.io.FileReader;
           import java.io.IOException
              import java.io.Reader;
          import java.util.Scanner;
          import java.util.regex.Matcher;
          import java.util.regex.Pattern;

            import javax.xml.parsers.ParserConfigurationException;

              import org.xml.sax.SAXException;

      public class XmlAsStringInJava {

public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {

    File xmlFile = new File("filelocation.txt");
    Reader fileReader = new FileReader(xmlFile);
    BufferedReader bufReader = new BufferedReader(fileReader);

    StringBuilder sb = new StringBuilder();
    String line = bufReader.readLine();
    while( line != null){
        sb.append(line).append("\n");
        line = bufReader.readLine();
    }
    String string= sb.toString();
      bufReader.close();

    final Pattern pattern = Pattern.compile("aa(.+?)}}", Pattern.DOTALL);
    final Matcher matcher = pattern.matcher(string);
    while(matcher.find()) {
    System.out.println( matcher.group(0)); }

}
}


text:
Q: Getting Too many Open Files Error in logs Recently we got "(Too many open files)" error in production and this leads to very high CPU spike(98%) on Linux machine and finally brought machine down. We have to reboot the machine to bring it back.
Flow of code is like this :-
Consume message from one of IBM-MQ queue -> start processing it -> make some update entries into SQL-Server DB and commit the transaction.
We are using Hikari for connection pool management and value is set as 30
hikariConfig.setMaximumPoolSize(30);

While checking the logs, i found following stack trace :-
2021-03-24T20:00:22.404 WARNING org.apache.catalina.loader.WebappClassLoaderBase Failed to open JAR [null]
java.io.FileNotFoundException: /opt/apache-tomcat-7.0.88/webapps/ROOT/WEB-INF/lib/HikariCP-2.5.1.jar (Too many open files)
    at java.util.zip.ZipFile.open(Native Method)
    at java.util.zip.ZipFile.<init>(ZipFile.java:219)
    at java.util.zip.ZipFile.<init>(ZipFile.java:149)
    at java.util.jar.JarFile.<init>(JarFile.java:166)
    at java.util.jar.JarFile.<init>(JarFile.java:130)
    at org.apache.tomcat.util.compat.JreCompat.jarFileNewInstance(JreCompat.java:221)
    at org.apache.catalina.loader.WebappClassLoaderBase.openJARs(WebappClassLoaderBase.java:3102)
    at org.apache.catalina.loader.WebappClassLoaderBase.findResourceInternal(WebappClassLoaderBase.java:3414)
    at org.apache.catalina.loader.WebappClassLoaderBase.findResource(WebappClassLoaderBase.java:1494)
    at org.apache.catalina.loader.WebappClassLoaderBase.getResourceAsStream(WebappClassLoaderBase.java:1722)
    at java.util.ResourceBundle$Control$1.run(ResourceBundle.java:2677)
    at java.util.ResourceBundle$Control$1.run(ResourceBundle.java:2662)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.util.ResourceBundle$Control.newBundle(ResourceBundle.java:2661)
    at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1501)
    at java.util.ResourceBundle.findBundle(ResourceBundle.java:1465)
    at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1361)
    at java.util.ResourceBundle.getBundle(ResourceBundle.java:773)
    at com.ibm.mq.jmqi.JmqiException.buildMessage(JmqiException.java:428)
    at com.ibm.mq.jmqi.JmqiException.getMessage(JmqiException.java:543)
    at com.ibm.mq.jmqi.JmqiException.getMessage(JmqiException.java:515)
    at java.lang.Throwable.getLocalizedMessage(Throwable.java:391)
    at com.ibm.mq.jmqi.internal.JmqiTools.getExSumm(JmqiTools.java:947)
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:2282)
    at com.ibm.mq.jmqi.remote.api.RemoteFAP.jmqiConnect(RemoteFAP.java:1294)
    at com.ibm.msg.client.wmq.internal.WMQSession.connect(WMQSession.java:387)
    at com.ibm.msg.client.wmq.internal.WMQSession.<init>(WMQSession.java:331)
    at com.ibm.msg.client.wmq.internal.WMQConnection.createSession(WMQConnection.java:909)
    at com.ibm.msg.client.jms.internal.JmsConnectionImpl.createSession(JmsConnectionImpl.java:896)
    at com.ibm.mq.jms.MQConnection.createSession(MQConnection.java:337)
    at org.springframework.jms.connection.SingleConnectionFactory.createSession(SingleConnectionFactory.java:437)
    at org.springframework.jms.connection.CachingConnectionFactory.getSession(CachingConnectionFactory.java:236)
    at org.springframework.jms.connection.SingleConnectionFactory$SharedConnectionInvocationHandler.invoke(SingleConnectionFactory.java:604)
    at com.sun.proxy.$Proxy195.createSession(Unknown Source)
    at org.springframework.jms.support.JmsAccessor.createSession(JmsAccessor.java:192)
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:475)
    at org.springframework.jms.core.JmsTemplate.execute(JmsTemplate.java:526)
    at com.test.config.messaging.MainframeMessageProducer.lambda$sendMessageToQueueWithHeaders$0(MainframeMessageProducer.java:120)
    at org.springframework.retry.support.RetryTemplate.doExecute(RetryTemplate.java:287)
    at org.springframework.retry.support.RetryTemplate.execute(RetryTemplate.java:164)
    at com.test.config.messaging.MainframeMessageProducer.sendMessageToQueueWithHeaders(MainframeMessageProducer.java:118)
    at com.test.config.messaging.MainframeMessageProducer.sendMessageToMainframeQueue(MainframeMessageProducer.java:101)
    at com.test.config.messaging.MainframeMessageProducer$$FastClassBySpringCGLIB$$f2d092d2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.test.common.aop.RecordTimingAspect.recordTimingAspect(RecordTimingAspect.java:28)
    at sun.reflect.GeneratedMethodAccessor505.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
    at com.test.config.messaging.MainframeMessageProducer$$EnhancerBySpringCGLIB$$dc5ae691.sendMessageToMainframeQueue(<generated>)
    at com.test.posting.GDISPurchasePostServiceImpl.postMessage(GDISPurchasePostServiceImpl.java:315)
    at com.test.posting.GDISPostingService.processMessage(GDISPostingService.java:56)
    at com.test.posting.GDISPostingService$$FastClassBySpringCGLIB$$3c0c40af.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:85)
    at com.test.common.aop.CorrelationIdAspect.correlationIdAdvice(CorrelationIdAspect.java:40)
    at sun.reflect.GeneratedMethodAccessor554.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:629)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:618)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
    at com.test.posting.GDISPostingService$$EnhancerBySpringCGLIB$$dd870248.processMessage(<generated>)
    at com.test.posting.GDISPostingMessageListener.onMessage(GDISPostingMessageListener.java:167)
    at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:746)
    at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:684)
    at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:651)
    at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:317)
    at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:255)
    at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1166)
    at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1158)
    at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1055)
    at java.lang.Thread.run(Thread.java:748)

I am confused here what leads to max open files error here :-

*

*is it due to Hikari CP as this is first line we got as an error (java.io.FileNotFoundException: /opt/apache-tomcat-7.0.88/webapps/ROOT/WEB-INF/lib/HikariCP-2.5.1.jar (Too many open files) ) ?

*Is it due to IBM-MQ connection not available ?

A: You could use the lsof command to LiSt Open Files.
It produces lots of output, so you'll want to capture and post process it ( eg grep or sort)
You can list open files by pid, userid, disk etc.
You might try lsof > before  wait...  lsof > after then use diff to see the differences


text:
Q: Ajax não funciona no Firefox Funciona perfeitamente no navegador Chrome, e nos outros navegadores não...
Quando eu digito o login e senha ele exibe a mensagem "Login Efetuado com Sucesso!" e fica parada a página no Mozilla.
Veja o código:
echo "<meta http-equiv=\"refresh\" content=\"1;URL=inicio.php\" />";
echo "Login Efetuado com Sucesso!";

$(function() {
    caminho = $('.logar');
    action = 'ajax/php/logar.php';
    enviar = $('form[name="logar"]');

    function resposta(datas) {
        caminho.html(datas);
    }

    enviar.submit(function() {
        var cadastrar = $.post(action, $(this).serialize());
        cadastrar.progress(resposta('Carregando...'));
        cadastrar.done(resposta);
        cadastrar.fail(function() {
            resposta('Erro ao Cadastrar');
        });
        return false;
    });
});

O que estou fazendo de errado?

A: O problema não é que a requisição não esteja funcionando, é a forma com que você está tentando redirecionar o usuário. Provavelmente o Chrome é o único que considera a metatag que você está usando após o carregamento da página.
Como solução, eu lhe indico a trocar o seu código de resposta por algo parecido com isso:
echo "";

echo "Login Efetuado com Sucesso!";

Mas ainda assim, não gosto desta forma de colocar javascript no servidor. Embora seja de gosto de cada um, eu lhe recomendo a mudar a resposta do servidor, como por exemplo, retornar um objeto JSON e tratar a resposta no javascript. Segue exemplo:
// php
$resposta = array();
$resposta["loginEfetuado"] = true;
echo json_encode($resposta);

// js
function resposta(data) {
    if (data.loginEfetuado) {
        caminho.html("Login Efetuado com Sucesso!");
        setTimeout(function() {
            window.location.href = "inicio.php";
        }, 1000);
    } else {
        caminho.html("Falha ao tentar efetuar login!");
    }
}


text:
Q: Meaning of "$X$ is a sample from population $P \in \mathcal{P}$" in Jun Shao's "Mathematical Statistics" I am reading the textbook "Mathematical Statistics" 2nd edition written by Jun Shao http://www.mim.ac.mw/books/Mathematical%20statistics%202nd%20edition.pdf .
In precise terms, what does the author mean by "$X$ is a sample from population $P \in \mathcal{P}$"? To phrase my question in another way, how is $X$ related to probability measure $P \in \mathcal{P}$? Lots of theorems are started with this sentence and no precise definition was found. I need to sort it out before moving on.

Here are the earliest related definitions I can find:
On page 91-92:

In statistical inference and decision theory, the data set is viewed as a realization or observation of a random element defined on a probability space
$(\Omega, \mathcal{F}, P)$ related to the random experiment. The probability measure $P$ is
called the population. The data set or the random element that produces the data is called a sample from $P$. A population $P$ is known if and only if $P(A)$ is a known value
for every event $A \in \mathcal{F}$.

Later on page 92:

In statistical inference and decision theory, the data set, $(x_1, ..., x_n)$, is
viewed as an outcome of the experiment whose sample space is $\Omega = \mathcal{R}^n$.
We usually assume that the $n$ measurements are obtained in n independent trials of the experiment. Hence, we can define a random $n$-vector $X = (X_1, ..., X_n)$ on $\prod_{i=1}^n(\mathcal{R}, \mathcal{B},P)$ whose realization is $(x_1, ..., x_n)$. The
population in this problem is $P$ (note that the product probability measure
is determined by $P$) and is at least partially unknown.

But later, the author does not seem to be very certain about this. For example, on page 96, there is a sentence saying "$\Omega$ is usually $\mathcal{R}^k$. On page 100, the beginning of chapter 2.2 says "Let us assume now that our data set is a realization of a sample $X$ (a
random vector) from an unknown population $P$ on a probability space."

The paragraph on page 92 seems to suggest that $X = (X_1, \cdots, X_n)$ has nothing to do with $P$: it just seems to be a random variable defined on a measurable space $\prod_{i=1}^n(\mathcal{R}, \mathcal{B})$. The way the sentence in question constructed seems to suggest that $X$ and $P$ are somehow related: and they should be related as many important theorems (like theorem 2.2 on page 104) all start with this sentence.
My guess to make sense of it:
Whenever the sentence "$X$ is a sample from population $P \in \mathcal{P}$" is mentioned, assume the following:

*

*There is a probability space $(\Omega, \mathcal{F}, \mu)$ and $X = (X_1, \cdots, X_n): \Omega \to \mathcal{R}^n$ is a Borel function (i.e. $\mathcal{R}^n$ valued random variable or $n$-dimensional random vector).

*$\mathcal{P}$ is a (given) collection of Borel probability measures on $\mathcal{R}$. The probability measure $\mu$ on $\mathcal{F}$ is on a different space and is a priori assumed to be unrelated to $\mathcal{P}$.

*$X_1, \cdots, X_n$ are independent and identically distributed with common law $P$ and it just happens that $P \in \mathcal{P}$.
Is my guess correct ?

A:

*

*There is a probability space $(\Omega, \mathcal{F}, \mu)$ and $X = (X_1, \cdots, X_n): \Omega \to \mathcal{R}^n$ is a Borel function (i.e. $\mathcal{R}^n$ valued random variable or $n$-dimensional random vector).

*$\mathcal{P}$ is a (given) collection of Borel probability measures on $\mathcal{R}$. The probability measure $\mu$ on $\mathcal{F}$ is on a different space.

This is correct.

and is a priori assumed to be unrelated to $\mathcal{P}$.

Once you know $\mu$ and $X$ you can define the law (or distribution) of $X$ (see p.8-9).
The sentence "$X$ is a sample from population $P \in \mathcal{P}$" means that the law of $X$ is exactly the measure $P$ (i.e., $\mu_X=P$), and $P\in \mathcal P$.

*$X_1, \cdots, X_n$ are independent and identically distributed with common law $P$ and it just happens that $P \in \mathcal{P}$.

This is correct.


text:
Q: Else statement only giving output on odd input When giving invalid input, the program only returns the "Please enter a valid input." on an odd input, so the first, third, so on.
Welcome to ConversionKiosk by: xxx xxx.
Please deposit any number of coins and follow the number by the name of the coin
Valid coin names are quarters, dimes, nickels, and pennies.
Please enter 'Cashout' to complete the transaction.
poo
Please enter a valid input.
poo
poo
Please enter a valid input.

Here is my Class that is running.
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    CoinConverter kiosk = new CoinConverter();

    System.out.println("Welcome to ConversionKiosk by: xxx xxx.\nPlease deposit any number of coins and follow the number by the name of the coin.\nValid coin names are quarters, dimes, nickels, and pennies.\nPlease enter 'Cashout' to complete the transaction.");
    int x = 0;
    do{
        String coinCount = in.nextLine();
        if(coinCount.contains("quarters")) {
            coinCount = coinCount.replace(" quarters", "");

            kiosk.addQuarters(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("dimes")) {
            coinCount = coinCount.replace(" dimes", "");

            kiosk.addDimes(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("nickels")) {
            coinCount = coinCount.replace(" nickels", "");

            kiosk.addNickels(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("pennies")) {
            coinCount = coinCount.replace(" pennies", "");

            kiosk.addPennies(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("quarter")) {
            coinCount = coinCount.replace(" quarter", "");

            kiosk.addQuarters(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("dime")) {
            coinCount = coinCount.replace(" dime", "");

            kiosk.addDimes(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("nickel")) {
            coinCount = coinCount.replace(" nickel", "");

            kiosk.addNickels(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(coinCount.contains("penny")) {
            coinCount = coinCount.replace(" penny", "");

            kiosk.addPennies(Integer.parseInt(coinCount));
            coinCount = coinCount.replaceAll(coinCount, "");
        }else if(!coinCount.contains("quarter") || !coinCount.contains("quarters") || !coinCount.contains("dime") || !coinCount.contains("dimes") || !coinCount.contains("nickel") || !coinCount.contains("nickels") || !coinCount.contains("penny") || !coinCount.contains("pennies")) {
            System.out.println("Please enter a valid input.");
        }else {
            System.out.println("Please enter a valid input.");
        }
        String close = in.nextLine();
        if (close.contains("Cashout")) {
            System.out.println("Would you like another Transaction(y/n)?");
            String another = in.nextLine();
            if(another.contains("y")) {
                kiosk.getVoucher();
            }else {
                kiosk.getVoucher();
                x ++;
            }
        }
    }while (x == 0);
    in.close();
}

Is there any way to check the input for each time new input is added?

A: You can test your logic with a much smaller and simpler program; for example, you could try a version that only accepts cents. This would make the problem more visible. Essentially, your code looks like this:
while not bored,
  1. ask for coins
  2. process each coin type
     or if nothing processed, complain
  3. check for cashout

You probably intended to use
while not bored,
  1. ask for coins
  2. process each coin type
     or if nothing processed, complain and go back to step 1 <--- !
  3. check for cashout

You can achieve this by using a continue statement when you detect the error:
    else {
        System.out.println("Please enter a valid input.");
        continue; // <-- repeats loop from beginning, skipping remaining code
    }

Additionally, as it stands, you present no feedback regarding cashout. Users would expect a press enter to continue, or write "cashout" to exit as part of step 3.

Note that there are several other problems with the code, such as a redundant else, handling plurals, and the fact that it can be rewritten to be both shorter and more readable. You may want to post it on codereview to get expert feedback on how it could be rewritten.

A: The reason for this anomaly is that on an incorrect input you are reading the input again and assigning it to another variable. After that you are asking the user for another input in the first line of your do-while loop.
To resolve this remove the close variable and just check for exit condition using
if (coinCount.contains("Cashout")) {
  // rest of the code
}

Thereby, all inputs from user are stored in the variable coinCount. You don't need an extra one for an exit condition.


text:
Q: WordPress wpautop/shortcode generating invalid markup I notice that theres invalid markup in my shortcode. Its ok if I disable wpautop tho
function shortcode_banner($attrs, $content = '') {
    echo ' --- ' . $content . ' --- ';
    $html = '

' . do_shortcode($content) . '

';
    die($html);
}

When autop is enabled I get (notice the closing
 at the start?)
---

The title

xxx ... xxx ...
---

The title

xxx ... xxx ...

When disabled I get
 ---

The header

xxx ... xxx ...
 ---

The header

xxx ... xxx ...

UPDATE: I notice this happens only when I have a tag (e.g.
) after my shortcode. Like:
[banner]

Test

If I have
[banner]
xxx ...

it's ok, except Wordpress adds a

A: Try this:
// replaces [banner ...] .. [/banner] with  before the_content filters run
add_filter('the_content', 'protect_my_shortcode', -100);
function protect_my_shortcode($content){
  return preg_replace_callback('/\[(banner)\b(.*?)(?:(\/))?\](.+?)\[\/\1\]/s', 'protect_my_shortcode_callback', $content);
}

function protect_my_shortcode_callback($matches){
  global $__banners;
  $id = '';

  $__banners[$id] = do_shortcode($matches[0]);
  // or '['.$matches[1].' '.$matches[2].']'.$matches[4].'[/'.$matches[1].']'
  // if you need to run any filters on the shortcode content ($matches[4])

  return $id;
}

// replaces  with the processed shortcode after all the filters run
add_filter('the_content', 'unprotect_my_shortcode', 100);
function unprotect_my_shortcode($content){
  global $__banners;
  return str_replace(array_keys($__banners), array_values($__banners), $content);
}

A: I don't know what causes this issue, but you can use the force_balance_tags() function to clean up the markup after the fact.
Note that there are some caveats to using force_balance_tags() in practice.


text:
Q: How to open a mounted volume's location in OSX? I'm writing a shell (bash) script which uses SSHFS (not that it should matter) to mount a network drive ND at a specific path P. Then, I want Finder to open a window/tab at path P/ND.
The problem is whenever I attempt to open the network drive, Finder opens a window not at path P/ND, but at MacBookAir/ND, ie /Volumes .
I tried the obvious, open "$P". I also tried cd-ing to the directory and doing open .
ND (with the eject symbol) is visible both at the top level and at path P.


text:
Q: Android App Acts as if it is Launching when Rotated I am having an issue with my Android app returning to the state it is in whenever it is launched whenever the screen is rotated. The app has several ImageButtons that change their image whenever clicked on, and I have music playing in the background on a loop. Whenever the screen is rotated though, the ImageButtons return to their default image even if they have been changed by the user touching them, and another instance of the music loop starts to play. How can I stop this from happening? I have no idea what to do about the ImageButtons. As for the music loop, I have tried using onStart(), but it continues to happen anyway, even if I use a boolean to check if it has already completed the tasks once.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_activity);
}

@Override
protected void onStart() {
    if(firstRun)
    {
        super.onStart();
        mediaPlayer = MediaPlayer.create(this, R.raw.music);
        mediaPlayer.setLooping(true);
        mediaPlayer.start();
        firstRun = false;
    }
}

A: This is the classic behavior of android activities . Actually your app is not restarting but the Activity is restarting. You can use the solutions mentioned at :
How to avoid restarting activity when orientation changes on Android
I would also suggest you to get a solid grasp of the Activity LifeCyle to make sure u get in less trouble due to the quirky behaviour of Android Activities/Fragments.
Also, since you want to play music in the backround, try using a Service with a persistent notification in the task bar to make sure your app is not closed abruptly by Android.

A: Add this line to your activity declaration in the Manifest.xml file
android:configChanges="keyboardHidden|screenSize|orientation"

like this:
<activity android:name=".YourActivity"
            android:configChanges="keyboardHidden|screenSize|orientation" />


text: Q: Is running two (or more) programs at the same time or multithreading in one program faster? I am designing my first multiplayer game, and in my current server implementation I am just running multiple instances of the same file for each client. Compared to running just one file which is multithreaded, which would be faster? Or is it the same speed?


text:
Q: Advanced ATX Power Supply Modifications I know there are multiple tutorials and questions regarding converting an ATX power supply, new or old, to a benchtop power supply for projects. I'm fully aware of how to make the basic conversion to get 12V and 5V connections but I would like to take it a step further.
I have a relatively new 900W power supply which I got for very little money and would ultimately like to turn it into a variable high power supply. I plan on adding all of the extra circuitry to do what I want to do in an external housing and have the cables from the ATX power supply simply plug into my new box. The list of what I intend to do is as follows:

*

*Use an active load balancing circuit to combine all 5 of the 12V rails into one 12V rail that can handle roughly 70A.

*

*From what I understand most supplies use the same power source and multiple voltage regulator circuits to get the different rails.

*Use a Boost Converter Circuit on the new combined line above to produce voltages up to say 50-60VDC

*Use a Buck Converter on either a single 12V rail or the combined line to get voltages below 12VDC.

My question is, can I do the above as I intend? Are there issues with following an active voltage regulator load balancing circuit with an adjustable boost converter to step the voltage up and down? Same goes for the Buck Converter? Any alternative suggestions that would accomplish the same goal?
I am aware I could buy a decent variable power supply but I don't have the money currently for that and I thought this would be a fun project in power electronics. I intend to use the supply for some motor control development and testing, hence why I want to get much higher amperage than 1 12V rail can provide.


text:
Q: Slice to Map of pointers duplicates values This is a beginner question about why I get such a result when trying to obtain a Map from a Slice in go lang. I have this code:
func (p *ProductsStruct) ToMap() map[int32]*Product {
    result := map[int32]*Product{}

    for _, prod := range p.Products {
        result[prod.ProductId] = &prod
    }

    return result
}

ProductsStruct has just a slice of Product and Product struct is as follows
type ProductsMedusa struct {
    Products []ProductMedusa
}

type Product struct {
    ProductId    int32
    ProductTitle string
    PriceUSD     float32
}

I cannot understand why calling the function ToMap() produces a result with all the keys but pointers to same object: the last. Also, I am aware of the fact that if I don't use map values as pointers, it works fine.

Thanks


text:
Q: There is an empty file after updating I'm trying to update an existing document with help of Google Docs API. I'm using PHP+Curl. The gdata.class.php is base class. Updating finishes partly. A old content is cleaned. But a new content is not created. According to documentation, I send PUT-request (initial request) to address
http://docs.google.com/feeds/upload/create-session/default/private/full/document%123456

There are Etag of the document and the empty request body. I recive  the status code 200 Ok and the unique upload URI like this:
http://docs.google.com/feeds/upload/create-session/default/private/full/document%123456?upload_id=EnB2Uob7DWcFVJTX3oF8sdVv9koZTHacngmM_

What should I do???

*

*I'm sending the file content and headers to the unique upload URI:

[0] => Content-Length: 6
[1] => Content-Range: bytes 0-5/6
[2] => Content-Type: text / plain

The responce is recived:

HTTP/1.1 308 Resume Incomplete

Headers not contains the "Range" header. It's strange.
Result: the target file is not changed.

*I'm sending the file content and headers to the unique upload URI:

[0] => Content-Length: 6
[1] => Content-Type: text/plain

The responce is recived:

HTTP/1.1 200 OK

There is atom+xml in the body.
Result: the target file became an empty.
P.s. The curl_getinfo function returns "5". It's not depends on size of the file.

A: Well if it asks you to use PUT method, then tell CURL to use it..
curl_setopt($ch, CURLOPT_PUT, 1);


text:
Q: Time Counter - Typescript I want to count the time when I press a button. And what I did until now, was to display the minutes and seconds when I press the button.
Example Time: 21(min):02 (sec)
I want to see when the minutes and seconds change, but I don't know how to do that.
ts.
  startTime = false;
  minutes: number;
  seconds: number;

  getTime() {
    this.startTime = !this.startTime;
    this.runTime();
    setInterval(this.runTime, 1000);
  }

  runTime() {
    this.todayDate = new Date();
    this.minutes = this.todayDate.getMinutes();
    console.log(this.minutes) /* here I can see in console that it prints minutes and seconds in real
                                time, but in the UI nothing happens, it appears only the date when I
                                click the button */
    this.seconds = this.todayDate.getSeconds();
  }

.html
<button type="button" class="btn btn-primary" (click)="getTime()">Time</button>
<div *ngIf="startTime">
     Time: {{minutes}} : {{seconds}}
</div>

Could you, please help me with this ?

A: Simply write:
import { interval } from 'rxjs';
import { map } from 'rxjs/operators'

interval(1000).pipe(
  map((x) => { /* your code here */ })
);

In RxJS 6+ there's no Observable.interval function.


text:
Q: MpChartlibrary Background color change Is there any way to change the color of the selected section. I am Using Mp Chart Library. And Try to Show Some Stats in the form of Line Chart.
So far i have tried many changes but unable to change the color of selected part Image
public class Weight extends Fragment  {

private LineChart mChart;
LineChartRenderer lineChartRenderer;

private ILineDataSet boundaryDataSet;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {

    }
}

public Weight() {
    this(null);
}
//Pass the dataset of other line in the Constructor
@SuppressLint("ValidFragment")
public Weight(ILineDataSet boundaryDataSet) {
    this.boundaryDataSet = boundaryDataSet;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_weight, container, false);

    mChart = rootView.findViewById(R.id.chart1);

    mChart.setBackgroundColor(Color.parseColor("#ffffff"));
    // no description text
    mChart.getDescription().setEnabled(false);

    // enable touch gestures
    mChart.setTouchEnabled(true);
    mChart.setDragDecelerationFrictionCoef(0.9f);

    // enable scaling and dragging
    mChart.setDragEnabled(true);
    mChart.setScaleEnabled(true);
    mChart.setDrawGridBackground(false);
    mChart.setHighlightPerDragEnabled(true);

    // if disabled, scaling can be done on x- and y-axis separately
    mChart.setPinchZoom(false);

    // add data
    setData(20, 30);
    mChart.animateX(2500);

    // get the legend (only possible after setting data)
    Legend l = mChart.getLegend();

    // modify the legend ...
    l.setForm(Legend.LegendForm.LINE);
    l.setTextSize(11f);
    l.setTextColor(Color.BLACK);
    l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
    l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
    l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
    l.setDrawInside(false);

    //      l.setYOffset(11f);

    XAxis xAxis = mChart.getXAxis();
    xAxis.setTextSize(11f);
    xAxis.setTextColor(Color.BLACK);
    xAxis.setDrawGridLines(false);
    xAxis.setDrawAxisLine(false);

    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.setTextColor(ColorTemplate.getHoloBlue());
    leftAxis.setAxisMaximum(30);
    leftAxis.setAxisMinimum(0f);
    leftAxis.setDrawGridLines(true);
    leftAxis.setGranularityEnabled(true);

    YAxis rightAxis = mChart.getAxisRight();
    rightAxis.setTextColor(Color.BLACK);
    rightAxis.setAxisMaximum(30);
    rightAxis.setAxisMinimum(0);
    rightAxis.setDrawGridLines(false);
    rightAxis.setDrawZeroLine(false);
    rightAxis.setGranularityEnabled(false);

    return rootView;
}

private void setData(int count, float range) {

    ArrayList<String> first_line =new ArrayList<String>();
    ArrayList<String> second_line =new ArrayList<String>();
    ArrayList<String> theard_line =new ArrayList<String>();

    first_line.add("3");
    first_line.add("6");
    first_line.add("9");
    first_line.add("12");
    first_line.add("15");
    first_line.add("18");
    first_line.add("21");

    second_line.add("2");
    second_line.add("4");
    second_line.add("6");
    second_line.add("8");
    second_line.add("10");
    second_line.add("12");
    second_line.add("14");

    theard_line.add("1");
    theard_line.add("3");
    theard_line.add("3");
    theard_line.add("4");
    theard_line.add("7");
    theard_line.add("10");
    theard_line.add("12");

    ArrayList<Entry> yVals1 = new ArrayList<Entry>();

    for (int i = 0; i < first_line.size(); i++) {
        float mult = range / 1;
        float val = Float.parseFloat(first_line.get(i));
        yVals1.add(new Entry(i, val));

    }

    ArrayList<Entry> yVals2 = new ArrayList<Entry>();

    for (int i = 0; i < second_line.size(); i++) {
        float mult = range;
        float val = Float.parseFloat(second_line.get(i));
        yVals2.add(new Entry(i, val));

    }

    ArrayList<Entry> yVals3 = new ArrayList<Entry>();
    for (int i = 0; i < theard_line.size(); i++) {
        float mult = range;
        float val = Float.parseFloat(theard_line.get(i));
        yVals3.add(new Entry(i, val));
    }

    LineDataSet set1, set2, set3;
    if (mChart.getData() != null &&
            mChart.getData().getDataSetCount() > 0) {
        set1 = (LineDataSet) mChart.getData().getDataSetByIndex(0);
        set2 = (LineDataSet) mChart.getData().getDataSetByIndex(1);
        set3 = (LineDataSet) mChart.getData().getDataSetByIndex(2);
        set1.setValues(yVals1);
        set2.setValues(yVals2);
        set3.setValues(yVals3);
        mChart.getData().notifyDataChanged();
        mChart.notifyDataSetChanged();
    }

    else {

        // create a dataset and give it a type
        set1 = new LineDataSet(yVals1, "DataSet 1");
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        set1.setColor(Color.parseColor("#f5f3f3"));
        set1.setCircleColor(R.color.trans);
        set1.setLineWidth(2f);
        set1.setDrawCircles(false);
        set1.setFillColor(R.color.trans);
        set1.setDrawCircleHole(false);
        set1.setFillAlpha(60);
        set1.setHighLightColor(Color.parseColor("#f5f3f3"));
        set1.setHighlightLineWidth(300f);
        set1.setHighlightEnabled(true);
        set1.setDrawFilled(true);

        // create a dataset and give it a type
        set2 = new LineDataSet(yVals2, "DataSet 2");
        set2.setAxisDependency(YAxis.AxisDependency.RIGHT);
        set2.setColor(Color.parseColor("#f46a99"));
        set2.setCircleColor(Color.BLACK);
        set2.setLineWidth(2f);
        set2.setCircleRadius(3f);
        set2.setFillAlpha(65);
        set2.setFillColor(Color.RED);
        set2.setDrawCircleHole(false);
        //set2.setFillFormatter(new MyFillFormatter(900f));

        set3 = new LineDataSet(yVals3, "DataSet 3");
        set3.setAxisDependency(YAxis.AxisDependency.RIGHT);
        set3.setColor(Color.parseColor("#f5f3f3"));
        set3.setDrawCircles(false);
        set3.setLineWidth(2f);
        set3.setFillColor(Color.parseColor("#000000"));
        Drawable drawable = ContextCompat.getDrawable(getActivity(),
        R.drawable.fade_red);
        set3.setFillDrawable(drawable);
        set3.setHighlightEnabled(true);
        set3.setHighLightColor(Color.parseColor("#000000"));
        set3.setDrawCircleHole(false);
        set3.setFillAlpha(0);
        set3.setDrawFilled(true);

        // create a data object with the datasets
        LineData data = new LineData(set1, set2, set3);
        data.setValueTextColor(Color.BLACK);
        data.setValueTextSize(9f);

        // set data
        mChart.setData(data);

    }
}

}

I want to change the background color of set 3. Is it evenpossible to change the color usin this library or should i use some other code


text:
Q: how to add 10 values in array (5,2) and then compute the average of them Assume that there are 5 records, each containing temperature values. The first temperature value on each record represents a high temperature from weather station, and the second temperatures on each record represents a low temperature from a weather station, input these temperatures into a table TEMP (5, 2) the with high temperatures from the 5 stations in column 1 of the table, and the low temperatures of the 5 stations in column 2 of the table. After reading in all the temperatures, find and output the average high temperatures and the average low temperatures for the 5 weather stations.

A: You can use 2D array as well as dictionary in this situation
Using Dictionary
Dim temArray As Dictionary(Of Integer, Integer) = New Dictionary(Of Integer, Integer)() '<-- declaration of dictionary
'<--- you can get all these values from the user also
temArray.Add(31, 20)'<-- add first set of high and low temperature values
temArray.Add(28, 17)'<-- add second set of high and low temperature values
temArray.Add(27, 16)'<-- add third set of high and low temperature values
temArray.Add(22, 19)'<-- add fourth set of high and low temperature values
temArray.Add(30, 22)'<-- add fifth set of high and low temperature values
Dim avgHighTemp As Double = temArray.Keys.Sum() / 5 '<-- average high temperature 27.6
Dim avgLowTemp As Double = temArray.Values.Sum() / 5'<-- average high temperature 16.8

Using 2D array
    Dim temArray(,) As Integer = New Integer(4, 1) {{31, 20}, {28, 17}, {22, 19}, {30, 22}, {27, 6}}
    Dim avgHighTemp As Double = 0
    Dim avgLowTemp As Double = 0
    For i As Integer = 0 To 4
        avgHighTemp += temArray(i, 0)
        avgLowTemp += temArray(i, 1)
    Next
    MsgBox("Average high temperature :" & avgHighTemp / 5)
    MsgBox("Average high temperature :" & avgLowTemp / 5)


text:
Q: Serialize derived class root as base class name with type I am somehow not able to achieve this serialization. I have these classes
public class Data
{
    [XmlElement("Name")]
    public string Name { get; set; }
}

[XmlRoot("Data")]
public class DataA : Data
{
    [XmlElement("ADesc")]
    public string ADesc { get; set; }
}

[XmlRoot("Data")]
public class DataB : Data
{
    [XmlElement("BDesc")]
    public string BDesc { get; set; }
}

When I serialize either DataA or DataB I should get the XMLs in the below structure:
<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataA">
      <Name>A1</Name>
      <ADesc>Description for A</ADesc>
</Data>

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataB">
      <Name>B1</Name>
      <BDesc>Description for b</BDesc>
</Data>

What I am getting is the below (without the i:type="..." and xmlns="")
<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Name>A1</Name>
      <ADesc>Description for A</ADesc>
</Data>

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Name>B1</Name>
      <BDesc>Description for b</BDesc>
</Data>

I am not sure what I am missing here. any suggestions would be helpful.

*

*Girija

A: You should include the derived types for XML Serialization of the base class.
Then you can create a serializer for the base type, and when you serialize any derived type, it will add the type attribute: (You can even remove the [Root] sttribute from the derived classes now)
[XmlInclude(typeof(DataA))]
[XmlInclude(typeof(DataB))]
[XmlRoot("Data", Namespace = Data.XmlDefaultNameSpace)]
public class Data
{
    public const string XmlDefaultNameSpace = "http://www.stackoverflow.com/xsd/Data";

    [XmlElement("Name")]
    public string Name { get; set; }
}

Serialization:
DataA a = new DataA() { ADesc = "ADesc", Name = "A" };
DataB b = new DataB() { BDesc = "BDesc", Name = "B" };
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), a);
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), b);

Here is the output for DataA class serialization
<?xml version="1.0"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DataA" xmlns="http://www.stackoverflow.com/xsd/Data">
  <Name>A</Name>
  <ADesc xmlns="">ADesc</ADesc>


text:
Q: Crossover study design and statistical method (ANOVA or Linear mixed-effects models) I have a crossover study dataset. I would like to conduct a linear mixed-effects study. What are the pros of LME models over ANOVA, but, for specifically crossover studies.
Thanks in advance!


text:
Q: Compare two User Agents We have a database which include thousands of user agents and their properties. I need to build an API on top of this database which receives a user agent, matches it with one of the existing user agents and then return its properties.
Obviously the first way of finding a matching user agent is to do an "exact" match. But in majority of times user agents have tiny differences that fails the exact matching.
I tried UA-Parser but I did not find it useful much as it normally fails to detect the "Device/Brand Name" and/or "Model Name".
Is there a way to tell if two user agents belong to same Device (Name and Model)?

A: There is no reliable way you can parse device from user-agent as not all of them report it.
If you have a database with ready user-agents the best you can do is to use parser with suboptimal results and just embrace it.
There is parser compare repository with benchmarks for popular parsers.
https://github.com/diablomedia/useragent-parser-comparison
To save you time calculating - your best bet would be (for device detection and overall score): https://github.com/mimmi20/browscap-js
Here is their repo example:

var Browscap = require('browscap-js');
var browscap = new Browscap();

var browser = browscap.getBrowser("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; WinTSI 05.11.2009)");

console.log(browser);

This is an example of output:

{
  "Comment": "Chrome Generic",
  "Browser": "Chrome",
  "Browser_Type": "Browser",
  "Browser_Bits": "64",
  "Browser_Maker": "Google Inc",
  "Browser_Modus": "unknown",
  "Version": "0.0",
  "MajorVer": "0",
  "MinorVer": "0",
  "Platform": "Win10",
  "Platform_Version": "10.0",
  "Platform_Description": "Windows 10",
  "Platform_Bits": "64",
  "Platform_Maker": "Microsoft Corporation",
  "Alpha": false,
  "Beta": false,
  "Win16": false,
  "Win32": false,
  "Win64": true,
  "Frames": true,
  "IFrames": true,
  "Tables": true,
  "Cookies": true,
  "BackgroundSounds": false,
  "JavaScript": true,
  "VBScript": false,
  "JavaApplets": false,
  "ActiveXControls": false,
  "isMobileDevice": false,
  "isTablet": false,
  "isSyndicationReader": false,
  "Crawler": false,
  "isFake": false,
  "isAnonymized": false,
  "isModified": false,
  "CssVersion": "3",
  "AolVersion": "0",
  "Device_Name": "Windows Desktop",
  "Device_Maker": "unknown",
  "Device_Type": "Desktop",
  "Device_Pointing_Method": "mouse",
  "Device_Code_Name": "Windows Desktop",
  "Device_Brand_Name": "unknown",
  "RenderingEngine_Name": "Blink",
  "RenderingEngine_Version": "unknown",
  "RenderingEngine_Description": "a WebKit Fork by Google",
  "RenderingEngine_Maker": "Google Inc",
  "Parent": "Chrome Generic",
  "browser_name_regex": "/^mozilla\\/5\\.0 \\(.*windows nt 10\\.0.*win64. x64.*\\).*applewebkit.*\\(.*khtml.*like.*gecko.*\\).*chrome\\/.* safari\\/.*$/",
  "browser_name_pattern": "mozilla/5.0 (*windows nt 10.0*win64? x64*)*applewebkit*(*khtml*like*gecko*)*chrome/* safari/*"
}

This may not be related to the original post, but may be readers who look to parse UA can get better ways to achieve their needs:

*

*If you need to track device (in physical sense, usually for security needs) - you should issue them a secret and use Secure remote password protocol to send you confirmation codes

*If you have access to frontend development it would be easier for them to just report you this data, this is no less "secure" than user-agent header

*If you need feature support list - MDN actually suggests to request feature support requests directly https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent


text:
Q: How to change my site SharedHosting to Dedicated IP I have a dedicated IP address and there I host three site as
site1com

example1.com

example2.com

I need to implement SSL for my example1.com site, I purchased a SSL certificate. But I can't activate my SSL , because of the shared hosting.
So I Purchased another IP and I need to change my example1.com this IP..
Am using Plesk control panel so how can i proceed to enable the new IP an SSL.

A: This depends greatly on the version of Plesk you are running. But in general:
Plesk > YourDomain.com > Setup > IP address (it is a dropdown box, if you have more than one IP available)
If you are the owner & administrator of this server, you would first need to add the IP address to the available pool.
This should all also be covered in greater detail within the help documents in your Plesk control panel.


text:
Q: How to store audio file on server? <?php
include("db.php");
$uploadDir = "../audioupload/";
$uid=$_POST['uid'];
$meeting_id=$_POST['meeting_id'];
$fileName = $_FILES['audio']['name'];
$tmpName = $_FILES['audio']['tmp_name'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
if($result)
{
    $sql="INSERT INTO `audio`(`uid`,`meeting_id`,`audio`) VALUES ('".$uid."','".$meeting_id."','".$result."')";
    $result1 = mysqli_query($conn,$sql);
    if($result1)
    {
        $sql1="select * from `audio` where `uid`='$_POST[uid]'";
        $result = mysqli_query($conn,$sql1);
        $count = mysqli_num_rows($result);
    }
    if($count>0)
    {
        $emparray = array();
        while($row = mysqli_fetch_array($result))
        {
            $emparray=array(
                'success' => true,
                'message' => "Audio saved Successfully!",);

        }
    }
}
else
{
   $row = mysqli_fetch_array($result);
   $emparray=array(
            'success' => false,
            'message' => "Incorrect Data!",
            );
}

    echo json_encode($emparray,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT);
    mysqli_close($conn);
?>

this is my code. im creating restful api for storing audio on server.im testing this link with postman tool. it gives me correct json response on postman. and audio saves in mysql database. But it not store in folder named audioupload that is subfolder in another folder. please help me with the same


text:
Q: Not getting any highlights from ElasticSearch I'm trying to create a query that will return me a highlighted response. The query I have is:
POST myindex/_search
{
  "from": 0,
  "size": 1,
  "query": {
    "query_string": {
      "query": "search for this"
    }
  },
  "highlight": {
    "pre_tags": [
      "<b>"
    ],
    "post_tags": [
      "</b>"
    ],
    "fields": {
      "_all": {}
    }
}}

But the result won't have any highlights, all it contain is the hits like this:
{
   "took": 0,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 1,
      "max_score": 0.2791085,
      "hits": [
         {
            "_index": "devintranett_1",
            "_type": "searchdocuments",
            "_id": "/link/ae0089b649e14de080fd94acb79bdfcd.aspx?id=1412&epslanguage=no",
            "_score": 0.2791085,
            "_source": {
               "id": "/link/ae0089b649e14de080fd94acb79bdfcd.aspx?id=1412&epslanguage=no",
               "contentType": 0,
               "location": "/link/ae0089b649e14de080fd94acb79bdfcd.aspx?id=1412&epslanguage=no",
               "ingress": "...",
               "content": "...",
               "title": "...",
               "createdDate": "2014-01-15T15:16:24",
               "changedDate": "2014-01-15T15:16:45.887"
            }
         }
      ]
   }
}

What am I missing to get the highlighted results back?
UPDATE:
I think I figured it out, to get the highlights I need to have a match query, is that correct?

A: You chose the wrong field to highlight. In fact, highlighting means that the field needs to be indexed, so that its tokens can be retrieved (together with their positions and offsets). Also, the field needs to be stored in order to be highlighted and returned.
You don't usually need to store your fields separately as elasticsearch always stores the _source field by default. The problem is that you chose to highlight the _all field, which is not part of your documents, thus not part of the _source field either. It would need to be stored separately in lucene, but it isn't by default.
I would suggest to switch to make highlighting on fields that actually appear in your documents. In fact, given that the _all field contains the content coming from all fields in your documents, its content might not be that nice to be shown to your users. As an experiment you can configure the _all field to be stored in lucene by changing the mappings for it to "store":"yes". Just keep in mind that this would cause wasting some disk space too.


text:
Q: How do I use glyphtounicode to make Caslon Pro ligatures searchable? I am using Adobe Caslon Pro with a caslon.sty file which activates uncommon ligatures such as st, ct, longsl, longst &c. I use it in the following example (updated to match the answer in the comment below):
\documentclass[english]{book}
\usepackage[T1]{fontenc}
\input{glyphtounicode}
\pdfglyphtounicode{germandbls}{0073 0073} % Override: normally eszet does not match "ss"
% Extra Unicode characters
\pdfglyphtounicode{longst}{FB05}
\pdfglyphtounicode{st}{FB06} % This is not produced by caslon.sty
% Ligatures with no Unicode characters
\pdfglyphtounicode{longdbls}{0073 0073}
\pdfglyphtounicode{ct}{0063 0074}
\pdfglyphtounicode{longsh}{0068 0074}
\pdfglyphtounicode{longsi}{0069 0074}
\pdfglyphtounicode{longsl}{006c 0074}
\pdfgentounicode=1
\usepackage[longs]{caslon}
\begin{document}
Goose taste has hash sin slim fact passing pass past.
\end{document}

Unfortunately, I can no longer find the caslon.sty that I use online, nor do the files give any clue as to their authorship. (There are a few different Adobe Caslon Pro support files for LaTeX, in CTAN and other places, but none seems to support the extra ligatures.) Hence, I've put a Zip bundle online at:
http://rrt.adsensus.net/acaslon.zip
of the files exactly as I downloaded them.

A: This is easy if you use lualatex in the command line instead of pdflatex.
\documentclass[english]{book}
\usepackage{fontspec}
\setmainfont[Style = {Historic}] {ACaslonPro}
\begin{document}
In goose taste.
\end{document}

Is lualatex an option you could try?


text:
Q: Assignment operator with an explicit template in C++ I'd like to define multiple ways of assignment operators. Minimal example code.
enum class AssignType {
    DeepCopy,
    SharedCopy
};

struct Container
{
    const char* x;
    template<AssignType >
    Container& operator=(const Container& other) {
        x = other.x; return *this;
    }
    // ...some specialisations of operator=() could be made
};

int main()
{
    Container i1, i2;
    i2.operator=<AssignType::DeepCopy>(i1);
    i2 =<AssignType::DeepCopy> i1; // line 20
    return 0;
}

The g++'s parser gives me an error for line 20. Is there any way to use operators in the "short" form (like in line 20) with explicit templates? C++11 allowed.


text:
Q: How do I display the Kubernetes Pod Name in a Vue.js app I have a vue.js frontend connecting to an Express node.js backend. Both frontend and backend are running in separate Docker containers on Kubernetes. I have created a route on the backend to display the Kubernetes Pod name when I call the URL via Postman:
app.get('/api/probe1', (req, res) => {
    res.send("Hello from: " + process.env.HOSTNAME)
})

The above shows the name of the Pod on which the BACKEND container is running.
I now want to create a page in my vue.js app which will display the name of the Pod on which the FRONTEND container is running edit: (as per comment below vue.js not really running on the pod but rather nginx serving static html/js is running on the pod).
When I use process.env.HOSTNAME in the vue.js app I get "undefined" when I console.log it. edit: (I can now see why this isn't going to work)
<template>

{{displayPodName}}

Hello from the Pod

</template>

I'm clearly tackling this from the wrong angle. How can I display the name of the Pod edit: on which the Frontend is running in my Vue.js app somewhere from which a particular nginx server is serving the html/js to my browser for any given session please?


text:
Q: VMB (Vodafone Mobile Broadband) without Java I have a VMB key that I use with a SIM card to connect my MacBook to the Internet while mobile.
Recently I've formatted my Mac and I decided to avoid installing Java. No problem until I tried to install latest VMB software: it's based on Java!
Are there some alternative softwares independent from Java?

A: Luckily, there is usually a way to avoid installing Java while still using your mobile internet dongle.
The software they bundle with these devices is based on Java because it is multi-platform. They code one app to handle the functionality and deploy it. However, the drivers (for Windows) and kexts (for Mac) are not based on Java and use native code.
You need to ask yourself a question: do I need the SMS and extra functionality that their software provides? If the answer is no, then you can set up the device in the Network preference pane manually and avoid using their software (and thus avoid installing Java) at all.
If you have run the package installer they provided to you, great. If not, run it now. This should install the kext (and the horrid software) in to /System/Library/Extensions. You may find you get a pop-up notification when you do this telling you a new network interface has been found.
Open "System Preferences" and click on "Network" to open up your network settings and there should be an extra interface listed on the left named something similar to "Vodafone Mobile Broadband" or "Huawei" (depending on the make of the device). If not, click the "+" and add it to your interfaces.
Select the interface and on the right-hand pane you should see a few fields there; one for "Number", one for "Username" and one for "Password". Generally, these are consistent across all networks, but if the settings I provide here don't work then get hold of your service provider and they should give them to you.
Under "Number" type '*#99#' and leave username and password blank. Then, click the "Advanced" button to open the advanced overlay, and under "Modem" select the brand of the device that you have (it should be listed at the bottom). Leave the rest of the settings as they are, usually the defaults are correct, and simply change the APN to "internet". This is the one variable that will probably cause the most hassle as I know that at least here in South Africa each network has deviated from the standard "internet" now with the addition of LTE.
Click all the "OK"s and "Apply"s to save the settings and, with the device plugged in, click "Connect". If all the settings are correct (and hopefully they are) then you should connect to the network and be able to browse. If not, then get hold of your service provider and ask them for the correct APN and dial settings.
Good luck!


text:
Q: Calculate the limit $\lim_{x\rightarrow 0} \frac{\sin(\sin(2x))}{x}$ Calculate the following limit:
$$\lim_{x\rightarrow 0} \frac{\sin(\sin(2x))}{x}$$
I'm not allowed to use L'Hôpital's rule. I tried to make the substitutions $2x=y$ and $\sin(2x)=y$, but I couldn't get something to use $\lim_{x\rightarrow 0} \frac{\sin(x)}{x}$ (this is the only one I can use this moment). I tried to use $\sin(2x)=2\sin(x)\cos(x)$ as well, but I didn't get anywhere too. I'm only asking a hint this moment! Thanks!

A: We know that $\lim_{x \to 0} \frac{x}{\sin{x}} = 1$, so
$$\lim_{x\rightarrow 0} \frac{\sin(\sin(2x))}{x}=
2\lim_{x\rightarrow 0} \frac{\sin(\sin(2x))}{\sin(2x)}\frac{\sin(2x)}{2x}=2$$


text:
Q: Sphinx Search, compound key After my previous question (http://stackoverflow.com/questions/8217522/best-way-to-search-for-partial-words-in-large-mysql-dataset), I've chosen Sphinx as the search engine above my MySQL database.
I've done some small tests with it, and it looks great. However, i'm at a point right now, where I need some help / opinions.
I have a table articles (structure isn't important), a table properties (structure isn't important either), and a table with values of each property per article (this is what it's all about).
The table where these values are stored, has the following structure:
articleID   UNSIGNED INT
propertyID  UNSIGNED INT
value       VARCHAR(255)

The primary key is a compound key of articleID and propertyID.
I want Sphinx to search through the value column. However, to create an index in Sphinx, I need a unique id. I don't have right here.
Also when searching, I want to be able to filter on the propertyID column (only search values for propertyID 2 for example, which I can do by defining it as attribute).
On the Sphinx forum, I found I could create a multi-value attribute, and set this as query for my Sphinx index:
SELECT articleID, value, GROUP_CONCAT(propertyID) FROM t1 GROUP BY articleID

articleID will be unique now, however, now I'm missing values. So I'm pretty sure this isn't the solution, right?
There are a few other options, like:

*

*Add an extra column to the table, which is unique

*Create a calculated unique value in the query (like articleID*100000+propertyID)

Are there any other options I could use, and what would you do?

A: In your suggestions

*

*Add an extra column to the table, which is unique

This can not be done for an existing table with large number of records as adding a new field to a large table take some time and during that time the database will not be responsive.

*

*Create a calculated unique value in the query (like articleID*100000+propertyID)

If you do this you have to find a way to get the articleID and propertyID from the calculated unique id.
Another alternative way is that you can create a new table having a key field for sphinx and another two fields to hold articleID and propertyID.

*

*new_sphinx_table with following fields
id - UNSIGNED INT/ BIGINT
articleID - UNSIGNED INT
propertyID - UNSIGNED INT
Then you can write an indexing query like below
SELECT id, t1.articleID, t1.propertyID, value FROM t1 INNER JOIN new_sphinx_table nt ON t1.articleID  = nt.articleID AND t1.propertyID = nt.propertyID;

This is a sample so you can modify it to fit to your requirements.
What sphinx return is matched new_sphinx_table.id values with other attributed columns. You can get result by using new_sphinx_table.id values and joining your t1 named table and new_sphinx_table


text: Q: Как требовать от унаследованных классов предоставить реализацию метода c++? Необходимо в родительском класс в определенном методе строго требовать от всех унаследованных классов предоставить реализацию этого метода. Как это осуществить? А также позволить унаследованным классам использовать свои перегруженные реализации других определенных методов , но не требовать этого?


text:
Q: Exclude META-INF/maven folder from the generated jar file I am trying to create a jar file which has all the necessary classes extracted within the jar. But for few dependent jar like log4j, it creates some folders inside META-INF/maven/*. I have a limitation that the server in which I will be placing the generated jar file will not have Internet connectivity. So if there is any content in this META-INF/maven/* folder then it gives me an error.
My maven descriptor looks like the following
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <addMavenDescriptor>false</addMavenDescriptor>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <minimizeJar>true</minimizeJar>
                <finalName>myclient</finalName>
            </configuration>
        </plugin>
    </plugins>
</build>

I am able to extract the required class files in the generated jar but the maven folder is still getting generated under META-INF. I have to manually delete the folder to make everything work. Please advice on how to automate this removal of maven folder from the generated jar file.

A: Simple add this to either it is a jar,war,ear plugin
<configuration>
   ....
  <archive>
    <addMavenDescriptor>false</addMavenDescriptor>
   </archive>
   ....
</configuration>

A: You can use filters inside the maven-shade-plugin configuration to exclude everything that is under META-INF/maven for every artifact:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>2.4.1</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>META-INF/maven/**</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>

A solution for the maven-jar-plugin can be found here.


text:
Q: Function stops my program I am trying to use the print function of PrintWriter. When I use this method, my program continues to run but all my other functions doesn't work.
    public void printVertices(PrintWriter os) {
        for(int i = 0; i < vert.size(); i++) {
            os.print(vert.get(i) + " ");
        }
        os.close();
    }

A: Again, the problem is that you close the PrintWriter, which also closes the underlying OutputStream or Writer.
You probably added the os.close(); statement, because otherwise the PrintWriter will buffer the output and you won't see anything printed to the console.
Closing a PrintWriter will first flush() it, then close it. You probably don't want the second part.
The solution therefore is to simply flush the PrintWriter:
public void printVertices(PrintWriter os) {
    for(int i = 0; i < vert.size(); i++) {
        os.print(vert.get(i) + " ");
    }
    os.flush();
}


text:
Q: How to receive MySQL database notifications in Delphi? I am developing a Delphi XE7 application with data stored in an online Mysql database. For the database access I use FireDAC. Because the application can be used on more than one computer simultaneously I need to be notified when a table is changed, so I can update the displayed information on each computer. FireDAC has a component called TFDEventAlerted which sounded like exactly what I need for this. But this component gives an error when activating (calling Register): [FireDAC][Phys][MySQL]-303. Capability is not supported.
I am not sure what this means, but after reading more about the component it seems Mysql does not support this type of events? If so: can anyone tell me whether there is another solution to accomplish the same?
Any help would be appreciated as I cannot seem to find a good solution.

A: Native MySQL doesn't have the push-notification feature you're hoping to use. To make this work you'll need to poll (to regularly run a query) to look for changes.
There are some ways to overcome this limitation if the scale of your system makes polling infeasible. You could add a user-defined function to your MySQL server, like this one to send messages: https://github.com/mysqludf/lib_mysqludf_stomp#readme
This won't work if you don't own the MySQL server; most hosting services won't allow you to install UDFs.
Or, you could build a message publish/subscribe app. This is pretty easy to do with the Amazon simple queuing service or with rabbitmq. But it's a different kind of system design from what you are probably used to.

A: In my article series about Firebird Database Events I proposed a solution based on message-oriented middleware. The middle tier of your application then would notify all interested parties about certain database events. Middle tier code would be database independent, all you need is a message broker who is specialized in reliable message delivery. An imaginary example for a 'after post' event handler is shown below:
procedure TAppDataModule.PurchaseOrderAfterPost(DataSet: TDataSet);
var
  Notification: INotification;
begin
  Notification := NotificationService.CreateNotification(PURCHASE_ORDER_TABLE_UPDATED);
  Notification.SetIntProperty(PURCHASE_ORDER_ID, PurchaseOrderID.AsInteger);
  NotificationService.Send(Notification);
end;

Popular free/libre open source message brokers are for example Apache ActiveMQ and RabbitMQ.

A: TFDEventAlerted control is not for MySQL database. That database doesn't support event model. If you want update data in "real time" then you must add manual request for changed data
Here are steps:

*

*Add new field to your database table like "last_updated";

*Fill that field by now() value on update or insert actions (by trigger or sql);

*Add timer to delphi app and add request by SELECT MAX(last_updated) AS last_updated FROM my_table for last updated time;

*If that time is new then request updated data by SELECT * FROM my_table WHERE last_updated >= :need_last_updated.


text:
Q: Joomla creating pages dynamically I am quite new to joomla. But not to HTML nor to PHP.
Now I want my users to be able to see information about eachother. because of this I wish to create a page (article) for each of them.
Now this page (article) is ofcourse going to be generated through PHP (collecting data from my user database) and is then displayed.
now to my question:
This site(article) should not display in the menu, nor should it display in a module it should actually be hidden unless someone either search for the user or clicks the user name. So how do I redirect and create a "Hidden" page in joomla?