text:
Q: Has anyone used RE2 in a C# application? I started my search a for a decent Regular Expression engine.  It landed me to this page  Benchmark of Regex Libraries.  I decided to use RE2 because it seems to be the best FSA engine in this list.
My final application will be built using WPF in C#.  The regex library will be used more in batch mode.  However most of the other Business Logic will be written in C# and thus I am planning on using the RE2 library through C#.
If anyone has done anything similar or just used the RE2 through C# and has some advice or pointers please tell me about it.
Thanks.

A: I have used RE2 .Net in an application, and let me tell you that this is best regex filtering tool ever. It has given me more than 10x improvement in the performance in most cases.
You can download the source code which is in C++ and the .net libraries here,
https://github.com/0xcb/Re2.Net
It depends on your requirement though. If you have a text file and if the need is to filter the file using a list of regular expressions then I would recommend GREP.
If you are trying to filter a large data set using a huge set of regex's where performance is a concern, then you could go with RE2. But, beware of the limitations in the syntax which are listed in https://code.google.com/p/re2/wiki/Syntax.

A: Yeah, I'm with Daniel on this one . . . before I'd go hunting from some rogue implementation of Reg Exp . . . I'd make sure I was pre-compiling regular expressions where I could, that greedy options, etc were all set correctly and that the reg expression themselves were not "dumb" in some way . . .
I suspect replacing the standard package is not the optimal solution.  Of course without knowing more about your requirements it is hard to know for sure . . . but if the impact of the RegExp package is that huge on your performance, I'd look at the RegExp's themselves first.
Frank


text:
Q: Keypress event of aspxMemo control Hi..
I have added aspxMemo control in my webpage :
txtComments.ClientSideEvents.KeyPress = "function(s,e){e.processOnServer = false;}";

but user can type every word in the textbox.. e.processOnServer = false doesn't effect
how can i prevent user to write single word in the MEmo control ?

A: I think you are misunderstanding what processonserver does.
It causes the related event to fire when a postback occurs. If you never perform a postback then your server side code will never run.
See the documentation here.
If you want to control what the user can type into a Memo you should handle this at the client side as calling back to the server after each key press is not recommended unless you can guarantee extremely fast response times.

A: Try to use ASPxClientTextEdit Methods, may be these solve your problem.
I have restricted some level, but try to improve it more. the following example write the single character but clear the editor text.
     <dx:ASPxMemo ID="ASPxMemo1" ClientInstanceName ="aspxMemo" runat="server" Height="71px" Width="170px">
            <ClientSideEvents KeyUp="function(s, e) {
    //s.SetValue('');

s.SetText('');
}" />

Hope this help you to implement your functionality..

redpajama_set_name: RedPajamaStackExchange


text:
Q: Impementing Authorize.Net CIM for guest customer, are these basically one-time use only When implementing Authorize.Net CIM for guests (unregistered) and customers who choose NOT to save their credit cards, but where we still require the CIM feature of being able to refer to the credit card information for later processing (pre-orders, backorders, drop-ship orders)...
Does this imply that the CIM profile created for those customer types will be pretty much one-time use only?  One CIM Profile ID per credit card transaction, in other words.
If I understand correctly, the CIM Profile IDs won't expire.  Wouldn't that potentially generate way too many one-time use Profile IDs?
According to other posts Authorize.Net CIM doesn't really have a Reference Transaction concept like PayFlow Pro Reference Transaction for Authorize.Net CIM, and that using the CIM profile is the solution.


text:
Q: How to use a partial view from a different module in Zend? I'm trying to access a partial view in foo from another module bar. Simplified file structure:
application/
    modules/
        foo/
            index.phtml
        bar/
            partial.phtml

And in index.html you would have the following code:
<?php echo $this->partialLoop('../bar/partial.phtml', $this->paginator);
echo $this->paginator; ?>

The problem is that you can't actually use parent traversal, as I get this error:
Requested scripts may not include parent directory traversal ("../", "..\" notation)

Is there any way to still include the partial view into my content page? (Or am I doing it wrong?) Thanks in advance.

A: I have gone through the same issue.
I had to include views from one module into another module's views.
I have solved the issue by adding the script path within the controller of the view (in which I had to include the other view)
$this->view->addScriptPath(APPLICATION_PATH.'/modules/moduleName/views/scripts/actionName');

and then included the script within the view file:
<?php
    echo $this->render('common-header.phtml');
    //Name of the file you want to include
?>

A: You need to pass the module argument:
<?php echo $this->partialLoop('partial.phtml', 'bar', $this->paginator); ?>


text:
Q: Firebase UserCredential and initializeApp error in my flutter app Am having this problem in my app where UserCredential is showing an error like this

I have firebase_auth installed already in my pubspec.yaml file and imported import 'package:firebase_auth/firebase_auth.dart'; but it still keeps throwing this error and the same happen to my await Firebase.initializeApp(); in main.dart. I don't know where this issue is coming from, I even upgraded my flutter to flutter 2.0 and it still persist.
Pubspec.yaml
dependencies:
  google_sign_in: ^5.0.0
  firebase_auth:
  provider: ^5.0.0
  flutter_switch: ^0.2.0
  shared_preferences: ^0.5.12+4
  image_picker: ^0.6.7+17
  flutter_image_compress: ^0.7.0
  cached_network_image: ^2.5.0
  image_cropper: ^1.3.1
  intl: ^0.17.0
  http: ^0.12.2
  transparent_image: ^1.0.0
  animations: ^2.0.0
  smooth_star_rating: ^1.1.1
  csc_picker: ^0.0.4
  flutter:
    sdk: flutter

Please is there something am missing because it was working yesterday but today it isn't even after created a new folder and moving everything to it. Please help and if you need more explanation you can ask.

A: Try adding firebase_core as dependency. As all the firebase product depends on it.


text:
Q: Python, display images located in sub directories with jupyter I'm trying to display images located in different sub directories.
I'm trying this code:
files = glob.glob('Ensemble/*/*', recursive = True)
for file in files:
    print(file) #This print the path of all the images
    for j in file.glob("*.jpg"):
       image = cv2.imread(str(j))
       plt.imshow(image)
       plt.show()

Output:
Ensemble\Cercles\Cercle2
Ensemble\Cercles\Cercle3
Ensemble\Cercles\Cercle4
Ensemble\Cercles\Cercle5
Ensemble\Diamants\Diamant2
Ensemble\Diamants\Diamant3
Ensemble\Diamants\Diamant4
Ensemble\Diamants\Diamant5
Ensemble\Hexagones\Hexagone2
Ensemble\Hexagones\Hexagone3
Ensemble\Hexagones\Hexagone4
Ensemble\Hexagones\Hexagone5
Ensemble\Triangles\Triangle2
Ensemble\Triangles\Triangle3
Ensemble\Triangles\Triangle4
Ensemble\Triangles\Triangle5

I get easily the the path of all images, with this code. But how to display the images?
I have this error:
AttributeError                            Traceback (most recent call last)
<ipython-input-34-c624a5120e94> in <module>
     22     #plt.show()
     23     #type(image)
---> 24     for j in file.glob("*.jpg"):
     25         image = cv2.imread(str(j))
     26         plt.imshow(image)

AttributeError: 'str' object has no attribute 'glob'

A: Change for j in file.glob("*.jpg"): to the following:
if file.endswith(".jpg"):

And change image = cv2.imread(str(j)) to the following
image = cv2.imread(file)


text:
Q: autowiring sessionbean with hibernate3 and spring3 Apologies as I'm relatively new to Spring.  I have the following code...
org.assessme.com.dao.UserDAOImpl.java
@Repository
public class UserDAOImpl implements UserDAO{

    @Autowired
    private SessionFactory sessionFactory;

     @Transactional
    public User getById(Long id) {
        return (User) sessionFactory.getCurrentSession().load(User.class, id);
    }

}

This uses org.assessme.com.dao.UserDAO.java
public interface UserDAO {
    public User getById(Long id);
}

When I try to run my program, I get...
ERROR: org.springframework.web.servlet.DispatcherServlet - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory org.assessme.com.bean.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

My spring.xml is...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"

       xsi:schemaLocation=
       "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/db" />
        <property name="username" value="username" />
        <property name="password" value="password" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="annotatedClasses">
        <list>
            <value>org.assessme.com.entity.User</value>
        </list>
    </property>
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="data" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
                <prop key="hibernate.current_session_context_class">thread</prop>
                <prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>

    <context:component-scan base-package="org.assessme" />

    <tx:annotation-driven/>

    <bean id="transactionManager"  class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

</beans>

Can anyone see what I'm doing incorrectly?  I'm not quite sure how to autowire the sessionFactory.
My entity class is as follows...
org.assessme.com.entity.User.java
@Entity
@Table(name = "users")
public class User {

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "id")
    private long id;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
}

Thanks,
I'm using this in springmvc by the way, should this be in servlet-context.xml?

A: Here is the relevant part of the error message:
NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory]

The problem is AnnotationSessionFactoryBean does not implement the org.hibernate.SessionFactory interface.  To get one of those you need to call the buildSessionFactory method.


text:
Q: Does anyone know why this isn't working? When I load the page nothing prompts. This is in the  tags of my html file Why does this not prompt when the page loads? Located in the <body> tags. Want it to prompt when the page loads for purchaseType. Thank you. Goal is for it to continuously prompt for variables and then alert totals, taxes, tip, etc.

    <script>
        var purchaseType = (prompt("Enter purchase type: (Store/Delivery)"));
        var numOfPies;
        var numOfToppings;
        var numofFountainDrinks;
        var deliveryTipOption;
        var deliveryTipAmount;
        var contactlessDeliveryOption;
        var totalPrice;
        var salesTax;
        var tip;
        var finalCost;

        if (purchaseType == "Store"){
        numOfPies = Number(prompt("Enter number of pies: "));
        result1 = (numOfPies * 15);
        numOfToppings = Number(prompt("Enter number of toppings: "));
        result2 = (numOfToppings * 0.50);
        numofFountainDrinks = Number(prompt("Enter number of drinks: "));
        result3 = (numofFountainDrinks * 2);
        totalPrice = (result1 + result2 + result3);
        salesTax = (totalPrice * 0.07);
        finalCost = (totalPrice salesTax);
        alert("Total Price: $" totalPrice);
        alert("Sales Tax: $" salesTax.toFixed(2));
        alert("Final Cost: $" finalCost);
        }
        else (purchaseType == "Delivery"){
        numOfPies = Number(prompt("Enter number of pies: "));
        result1 = (numOfPies * 15);
        numOfToppings = Number(prompt("Enter number of toppings: "));
        result2 = (numOfToppings * 0.50);
        deliveryTipOption = (prompt("Enter tip option: (Yes/No)"));
            if (deliveryTipOption == "Yes"){
            deliveryTipAmount = (prompt("Enter tip amount: "));
            contactlessDeliveryOption = (prompt("Enter contactless option: (Yes/No)"));
            }
            else (deliveryTipOption == "No"){
            deliveryTipAmount = 0.00;
            contactlessDeliveryOption = (prompt("Enter contactless option: (Yes/No)"));
            }
        totalPrice = (result1 + result2 + 3.00);
        salesTax = (totalPrice * 0.07);
        finalCost = (totalPrice salesTax);
        alert("Total Price: $" totalPrice);
        alert("Sales Tax: $" salesTax.toFixed(2));
        alert("Tip amount: $" deliveryTipAmount);
        alert("Final Cost: $" finalCost);
        alert("Contactless Delivery: $" contactlessDeliveryOption);
        }
    </script>

A: This line finalCost = (totalPrice salesTax); misses an operator (which I assumed to be +).
This line else (purchaseType == "Delivery"){ misses an if.
This line alert("Total Price: $" totalPrice); and all other concatenations are missing a +.
Initialize your variables!
Numbers with zeros and strings with their default value.
This will avoid some NaN when a variable gets used without a value.
Also, I suggest you move your calculations and alerts out of the prompting logic.
I added an else in case the purchaseType value is wrong.
I also added an if to avoid showing all zero results.

<script>
  let purchaseType = (prompt("Enter purchase type: (Store/Delivery)"));
  let numOfPies = 0;
  let numOfToppings = 0;
  let numofFountainDrinks = 0;
  let deliveryTipOption = "No";
  let deliveryTipAmount = 0;
  let contactlessDeliveryOption = "No";
  let totalPrice = 0;
  let salesTax = 0;
  let tip = 0;
  let finalCost = 0;
  let result1 = 0;
  let result2 = 0;
  let result3 = 3;

  if (purchaseType === "Store") {
    numOfPies = Number(prompt("Enter number of pies: "));
    numOfToppings = Number(prompt("Enter number of toppings: "));
    numofFountainDrinks = Number(prompt("Enter number of drinks: "));

  } else if (purchaseType === "Delivery") {
    numOfPies = Number(prompt("Enter number of pies: "));
    numOfToppings = Number(prompt("Enter number of toppings: "));
    deliveryTipOption = (prompt("Enter tip option: (Yes/No)"));

    if (deliveryTipOption === "Yes") {
      deliveryTipAmount = (prompt("Enter tip amount: "));
      contactlessDeliveryOption = (prompt("Enter contactless option: (Yes/No)"));
    } else if (deliveryTipOption === "No") {
      contactlessDeliveryOption = (prompt("Enter contactless option: (Yes/No)"));
    }
  } else {
    alert("Wrong input")
  }

  // Calculations
  result1 = (numOfPies * 15);
  result2 = (numOfToppings * 0.50);
  result3 = (numofFountainDrinks * 2);
  totalPrice = (result1 + result2 + result3);
  salesTax = (totalPrice * 0.07);
  finalCost = (totalPrice + salesTax);

  // Results
  if (totalPrice !== 0) {
    alert("Total Price: $" + totalPrice.toFixed(2));
    alert("Sales Tax: $" + salesTax.toFixed(2));
    alert("Tip amount: $" + deliveryTipAmount.toFixed(2));
    alert("Final Cost: $" + finalCost.toFixed(2));
    alert("Contactless Delivery: $" + contactlessDeliveryOption.toFixed(2));
  }
</script>


text:
Q: css precedence ambiguity I have following css rules:
input[type="submit"],input[type="reset"]{
    background-image:url(skins/images/bg_mega_hdr_on.png);
    background-repeat:no-repeat;
    padding:5px;
    margin:5px;
    color:#000;
    cursor:pointer;
}

#submit-search{
    background-image:url(skins/images/bg_blue.png) !important;
}

Now according to css rule, id selector has higher precedence over the generic selector then
why is it that, when I apply this rule, the second one is overridden by first one? note that i have even applied !important, then also first one is only applied.

A: something like this id="submit-search " notice the space can cause odd selector behaviors !
ps . cant comment yet , to little points ...

A: Works correct for me. See this jfiddle. There must be something else wrong (I removed !important and it still works fine).


text:
Q: Pandas: How to get the size of each chunk from big csv file? I have a big csv file having million rows. I would like to read that csv in chunks and save the count of rows of each chunks in dataframe for reference.
chunk_size=50000
for chunk in pd.read_csv('file.csv',chunksize=chunk_size):
    print(chunk.shape)

I want to save each chunk shape in dataframe. My expected output as below. Please suggest.
 column1  column2
 chunk1   50,000
 chunk2   50,000
 chunk3   50,000

A: IIUC, you want something like this:
sizes = pd.DataFrame(columns=["Chunk", "Size"])
for i, chunk in enumerate(pd.read_csv("file.csv", chunksize=50000)):
    sizes.loc[i] = [f"chunk{i+1}", chunk.shape[0]]

A: You can try something like:
chunk_size=50000
i = 1
lengths = []
names = []
for chunk in pd.read_csv('file.csv',chunksize=chunk_size):
    lengths.append(len(chunk))
    names.append('chunk %s' % i)
    chunk.to_csv('chunk_%s.csv' % i)
    i+=1

df= pd.DataFrame({'size': lengths}, index=names)


text:
Q: Run startup code in the parent with Django and Gunicorn I need my code run at Django application startup, before Django starts listening for incoming connections. Running my code upon the first HTTP request is not good enough. When I use Gunicorn, my code must run in the parent process, before it forks.
https://stackoverflow.com/a/2781488/97248 doesn't seem to work in Django 1.4.2: it doesn't run the Middleware's __init__ method until the first request is received. Ditto for adding code to urls.py.
A quick Google search didn't reveal anything useful.

A: This is old but in Gunicorn version 19.0 and above, you can create a custom script to run your application and include the startup code that you need there. Here is an example script using a django app:
#!/usr/bin/env python

"""
Script for running Gunicorn using our WSGI application
"""

import multiprocessing

from gunicorn.app.base import BaseApplication

from myapp.wsgi import application  # Must be imported first

class StandaloneApplication(BaseApplication):
    """Our Gunicorn application."""

    def __init__(self, app, options=None):
        self.options = options or {}
        self.application = app
        super().__init__()

    def load_config(self):
        config = {
            key: value for key, value in self.options.items()
            if key in self.cfg.settings and value is not None
        }
        for key, value in config.items():
            self.cfg.set(key.lower(), value)

    def load(self):
        return self.application

if __name__ == '__main__':
    gunicorn_options = {
        'bind': '0.0.0.0:8080',
        'workers': (multiprocessing.cpu_count() * 2) + 1,
    }

    # Your startup code here

    StandaloneApplication(application, gunicorn_options).run()

A: I have just run into this problem myself, and the solution was to basically chain the commands to guarantee execution and correct order:
Script started by systemd, supervisord or any other such system:
#!/bin/sh
python manage.py my_custom_command && gunicorn project.wsgi $@

Create your own custom django command and off you go. You can get some speedups if you disable sanity checks in the command (requires_system_checks and requires_migrations_checks set to False).
To make things more generic, you could create a "boot" signal to which you connect arbitrary functions, and just emit the signal from this custom command.


text: Q: вычитание с разных активностей Как я могу сделать вычитание с разных активностей. То есть у меня есть некий баланс на первой активности, на второй активности я пишу число которое вычитается из основного баланса. В итоге когда я снова захожу на основную активность, у меня остается только число из которого вычли. как пример изначально у меня было 3, потом на второй активности вычли 2 и когда я снова захожу на первую активность должно стать число 1. Я посмотрел в интернете создание по принципу калькулятора ,но нигде не упоминается как вычитать с разных активностей и как сделать оставшийся баланс.  Есть предложения?


text:
Q: What would be the application of prooving inequality problems? What would be the application of prooving inequality problems or inequalities themself like this (in addition to train your mind)? They're very hard (at least for me) but as an engineer I'm curious about its application.   Please don't judge, I'm not a math major and just curious if they have some real applications.
Something like complex number, integral, Laplace, Fourier transforms are very useful for engineering but I don't know if these inequalities would be used somehow for EE or some real applications.
Please note that I don't want to just focus on the equalities in the images but I want to know about this type of equalities in general.

Or this:

And many more from this page:


text:
Q: OBIEE Recipients can't see all other recipients of a sent email I am trying to figure out how to show all recipients in email sent by OBIEE ..
I am totally lost in EM, since I am not able to find where is this configuration
I tried to google for it but found nothing ..
Do you know where this could be set or if it is even possible?
example:
I will sent an analysis created in OBIEE to me@example.com and you@example.com .. but I (me@example.com) can't see you@example.com recieved it too, because it is (most probably) sent as bcc ...
Thank you for your advice

A: *

*Log into EM using Admin credentials

*Navigate to Mail tab (Business Intelligence > coreapplication > Deployment>Mail

*Click Lock and Edit Configuration to enable changes to be made.

*You should see an Addressing Method radial button. Select To instead of Bcc.

*Click Apply, and then click Activate Changes.

*Return to the Business Intelligence Overview page and click Restart.


text:
Q: apex:enhancedList component not displaying with Lightning enabled I have a Visualforce page that uses an apex:enhancedList component on the page. When I have the Salesforce Classic look enabled, the list works properly (shown below):

However, when I switch to the Lightning view, the list does not display anything, and all that is shown is the 'Loading...' message at the bottom. And when I try to switch List Views, there is a javascript error in the console:

Has anyone else encountered this issue? If so, what was your workaround, or did you have to stop using this component?

A: The reason this component was not loading is because the ApexPage that was using the component did not have a high enough API Version Number. Once I changed the API Version to be 28.0, the component rendered correctly.


text:
Q: R select single data points from data frame I have an R data frame with the following structure
Iterations Subset EqIT  lSBR  rSBR contrast_rl contrast_rb contrast_lb noise_r noise_l noise_bg
1          2     10   20 14.26 10.82        0.24        0.82        0.85    0.78    0.66     1.16
2          3     10   30 14.15 10.84        0.25        0.83        0.86    0.82    0.67     1.28
3          4     10   40 13.93 10.73        0.25        0.83        0.86    0.83    0.68     1.33
4          5     10   50 13.85 10.65        0.25        0.83        0.86    0.83    0.69     1.39
5          6     10   60 13.84 10.68        0.25        0.83        0.86    0.83    0.69     1.39
6          7     10   70 13.68 10.54        0.25        0.83        0.86    0.83    0.70     1.39

I would like to assign the values of lSBR and rSBR to variable l_norm and r_norm and then normalise all other lSBR and rSBR values by these values. I am unsure on the best way to do this. My cumbersome approach at the moment is
subs <- subset(df,Subset==20 & EqIT==200)
l_norm <- subs[1,4]
r_norm <- subs[1,5]
df <- transform(df, lSBR = lSBR / l_norm, rSBR = rSBR/r_norm)

Can someone give me some guidance on a better way to approach this simple task in R as I am still struggling with the basics.
The data frame structure is given below:
 structure(list(Iterations = c(2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
    10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 1L, 2L,
    3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 2L, 3L, 4L, 5L, 6L, 7L, 8L,
    9L, 10L, 11L, 12L, 13L), Subset = c(10L, 10L, 10L, 10L, 10L,
    10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
    10L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 5L, 5L,
    5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L), EqIT = c(20L, 30L, 40L,
    50L, 60L, 70L, 80L, 90L, 100L, 110L, 120L, 130L, 140L, 150L,
    160L, 170L, 180L, 190L, 200L, 20L, 40L, 60L, 80L, 100L, 120L,
    140L, 160L, 180L, 200L, 10L, 15L, 20L, 25L, 30L, 35L, 40L, 45L,
    50L, 55L, 60L, 65L), lSBR = c(14.26, 14.15, 13.93, 13.85, 13.84,
    13.68, 13.78, 13.76, 13.71, 13.71, 13.59, 13.58, 13.7, 13.6,
    13.57, 13.53, 13.57, 13.58, 13.56, 14.17, 13.66, 13.4, 13.35,
    13.3, 13.3, 13.29, 13.26, 13.29, 13.35, 14.62, 14.64, 14.58,
    14.51, 14.41, 14.35, 14.3, 14.25, 14.19, 14.11, 14.06, 14.07),
        rSBR = c(10.82, 10.84, 10.73, 10.65, 10.68, 10.54, 10.65,
        10.61, 10.56, 10.56, 10.44, 10.43, 10.54, 10.41, 10.4, 10.4,
        10.4, 10.41, 10.39, 11.03, 10.73, 10.54, 10.49, 10.43, 10.45,
        10.43, 10.42, 10.42, 10.49, 10.78, 10.9, 10.87, 10.89, 10.89,
        10.87, 10.83, 10.8, 10.78, 10.74, 10.69, 10.65), contrast_rl = c(0.24,
        0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.24, 0.24, 0.24, 0.24,
        0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24, 0.24,
        0.24, 0.25, 0.25, 0.24, 0.23, 0.23, 0.23, 0.23, 0.28, 0.27,
        0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26, 0.26
        ), contrast_rb = c(0.82, 0.83, 0.83, 0.83, 0.83, 0.83, 0.83,
        0.83, 0.83, 0.83, 0.83, 0.83, 0.83, 0.82, 0.82, 0.82, 0.82,
        0.82, 0.82, 0.81, 0.82, 0.82, 0.82, 0.82, 0.82, 0.82, 0.82,
        0.82, 0.82, 0.81, 0.82, 0.82, 0.83, 0.83, 0.83, 0.83, 0.83,
        0.83, 0.83, 0.83, 0.83), contrast_lb = c(0.85, 0.86, 0.86,
        0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.86,
        0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.86, 0.86, 0.86,
        0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.85, 0.86, 0.85, 0.86,
        0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.86, 0.86), noise_r = c(0.78,
        0.82, 0.83, 0.83, 0.83, 0.83, 0.83, 0.84, 0.84, 0.84, 0.84,
        0.84, 0.84, 0.84, 0.84, 0.84, 0.84, 0.84, 0.84, 0.78, 0.81,
        0.82, 0.84, 0.84, 0.84, 0.83, 0.83, 0.83, 0.84, 0.73, 0.77,
        0.79, 0.8, 0.81, 0.82, 0.82, 0.83, 0.83, 0.83, 0.84, 0.84
        ), noise_l = c(0.66, 0.67, 0.68, 0.69, 0.69, 0.7, 0.7, 0.7,
        0.71, 0.71, 0.71, 0.71, 0.71, 0.71, 0.71, 0.71, 0.71, 0.71,
        0.71, 0.67, 0.69, 0.7, 0.7, 0.71, 0.71, 0.71, 0.71, 0.71,
        0.72, 0.6, 0.63, 0.65, 0.66, 0.67, 0.68, 0.68, 0.69, 0.69,
        0.69, 0.69, 0.69), noise_bg = c(1.16, 1.28, 1.33, 1.39, 1.39,
        1.39, 1.44, 1.44, 1.44, 1.44, 1.44, 1.44, 1.44, 1.37, 1.37,
        1.37, 1.37, 1.37, 1.37, 1.16, 1.33, 1.39, 1.44, 1.44, 1.44,
        1.44, 1.5, 1.5, 1.5, 0.9, 1.05, 1.11, 1.22, 1.28, 1.33, 1.33,
        1.33, 1.39, 1.39, 1.39, 1.39)), .Names = c("Iterations",
    "Subset", "EqIT", "lSBR", "rSBR", "contrast_rl", "contrast_rb",
    "contrast_lb", "noise_r", "noise_l", "noise_bg"), row.names = c(NA,
    -41L), class = "data.frame")

A: Your approach:
subs <- subset(df,Subset==20 & EqIT==200)
l_norm <- subs[1,4]
r_norm <- subs[1,5]
df2 <- transform(df, lSBR = lSBR / l_norm, rSBR = rSBR/r_norm)

It doesn't seem so bad to me, but you can do it in two lines instead
of four as follows:
subline <- with(df,which(Subset==20 & EqIT==200))
## OR  subline <- which(df$Subset==20 & df$EqIT==200)
df3 <- transform(df, lSBR = lSBR/lSBR[subline], rSBR=rSBR/rSBR[subline])

all.equal(df2,df3)  ## TRUE


text:
Q: Perl Class Inheritance I just wrote three perl objects that do relatively similar things, but with slightly different data. I realized after finishing the project that a lot of methods can be consolidated into a base class to reduce this duplication, so now I am in the process of moving the code around and I am running into some problems, one thing to keep in mind is that I am using 5.8.8, so some of the latest things don't work. Upgrading to a newer version is not an option for me at this time.
I have a method that is invoked form the base class that is supposed to invoke another method also in the base class, but work on the data in the actual object, they look like this:
sub check_cache{
my ($self, @data) = @_;
#do stuff to check cache, return 0 if cache is not hit, otherwise return value
}

sub update_cache {
 my ($self, @data) = @_;
 if ($self->check_cache(@data) == 0 ) {
  #Check to see if value is already in cache, if not update it
 }
}

The update_cache method is invoked from the actual object as $self->SUPER::update_cache(@data)
The update_cache methods gets called fine, however it can't find the check_cache method. check_cache method seems to work fine if called from outside the base class. Can you guys give me a hand here?
I've tried to invoke it in a number of different ways, but I keep getting something along the lines of
"Can't locate object method "check_cache" via package "ACTUAL OBJECT=hash(0x1231231)" (perhaps you forgot to load ACTUAL OBJECT=hash(0x1231231))? at line number.

line number points at update_cache's invokation of check cache in base class.
What is the proper way for me to invoke this?
EDIT:
I got my code working, but I am not sure why I ran into this problem. Maybe someone can help me understand this a bit better. Here is some code that you can run that will demonstrate the problem, I ran this on perl 5.18.2 and I still ran into the same issue.
All in all, it was just sloppy copying and pasting on my part, but it looks like the $self variable gets overwritten with some other data in here. I was able to troubleshoot it by placing Dumping statements throughout the culprit function to see if the object was still there, narrowed it down to this.
Thanks in advance
parentclass.pm:
package parentclass;
use Data::Dumper;

sub _print1{
    my $self = shift;
    print($self->{class});
    $self->_print2();
}

sub _print2{
    $self = shift;
    my @arr = [1,2,3];
    my @b = $self->uniq(@arr); #<---This line is the culprit if enabled the class tring won't print
    print("\n\nSecondPrint\n\n");
    print($self->{class});

}

sub uniq {
    my %seen = (); #<---I wasn't pulling self or returning it here
    my @r = ();
    foreach my $a (@_) {
        $a = lc($a);
    unless ($seen{$a}) {
        push @r, $a;
        $seen{$a} = 1;
    }
    }
    return @r;
}
1;

class.pm:
package class;
use Data::Dumper;
use parent parentclass;

sub new {
    my $class = shift;
    my $self = {};
    $self->{class} = "Class Value";
    bless $self, $class;

return $self;
}

sub _class_print{
    my $self = shift;
    $self->_print1;

}

1;

run.pl:
use class;

my $class = class->new();
$class->_class_print();

I got my code working, but I am not sure why I ran into this problem. Maybe someone can help me understand this a bit better. Here is some code that you can run that will demonstrate the problem, I ran this on perl 5.18.2 and I still ran into the same issue.
All in all, it was just sloppy copying and pasting on my part, but it looks like the $self variable gets overwritten with some other data in here. I was able to troubleshoot it by placing Dumping statements throughout the culprit function to see if the object was still there, narrowed it down to this.
Thanks in advance
parentclass.pm:
package parentclass;
use Data::Dumper;

sub _print1{
    my $self = shift;
    print($self->{class});
    $self->_print2();
}

sub _print2{
    $self = shift;
    my @arr = [1,2,3];
    my @b = $self->uniq(@arr); #<---This line is the culprit if enabled the class tring won't print
    print("\n\nSecondPrint\n\n");
    print($self->{class});

}

sub uniq {
    my %seen = (); #<---I wasn't pulling self or returning it at the end
    my @r = ();
    foreach my $a (@_) {
        $a = lc($a);
    unless ($seen{$a}) {
        push @r, $a;
        $seen{$a} = 1;
    }
    }
    return @r;
}
1;

class.pm:
package class;
use Data::Dumper;
use parent parentclass;

sub new {
    my $class = shift;
    my $self = {};
    $self->{class} = "Class Value";
    bless $self, $class;

return $self;
}

sub _class_print{
    my $self = shift;
    $self->_print1;

}

1;

invoker.pl
use class;
my $class = class->new();
$class->_class_print();

A: Always use use strict; use warning;!!!

use parent parentclass

should be
use parent 'parentclass';

Found by strict. No harm done.

Also,
sub _print2 { $self = shift; ... }

should be
sub _print2 { my $self = shift; ... }

No harm done, but mostly by luck. Caught by strict.

Then you get
Can't use string ("class=hash(0x4a9334)") as a HASH ref while "strict refs"
   in use at parentclass.pm line 18.

That comes from the line
$self->{class}

It means $self is the string class=hash(0x4a9334). Somehow, $self got stringified and converted the lowercase.
It's due to a combination of two bugs.

*

*You call uniq as a method, but it's not a method.

*uniq modifies @_, which means it's modifying the arguments passed to it.
Don't forget that foreach doesn't copy the value into the loop variable; it aliases the loop variable to the value.
When you modify $a, you modify $_[0]. When you modify $self (uniq's first arg).
Fix:
sub _print2{
    ...
    my @b = uniq(@arr);
    ...
}

sub uniq {
    my %seen;
    return grep !$seen{lc($_)}++, @_;
}

or
use List::MoreUtils qw( uniq );

sub _print2{
    ...
    my @b = uniq(@arr);
    ...
}

After that, there's yet another bug.
my @arr = [1,2,3];  # Assign a single scalar that's a reference to an array.

should be
my @arr = (1,2,3);  # Assign three scalar that are numbers.


text:
Q: Все положительные, отрицательные и числа в скобках между скобками Как получить все числа в подобной записи: string(1,-2,5*(4-2))?
Пробовал так: re.sub("([+-]?\d+(?:\.\d+)?)","found",s), но запись игнорирует скобки.
Так как же получить все положительные, отрицательные и числа в скобках между string().


text:
Q: Assigning variable from a factory to a control doesn't work My html is this:
<body ng-controller="MainCtrl as ctrl" class="bodyContainer">
<div ng-repeat="stuff in ctrl.stuffies">
    here
</div>

This is my controller:
angular.module("AuthenticationApp", ["BaseApp"])
    .controller("MainCtrl", ["$http", "$window", "BaseService", function($http, $window, BaseService) {
        var self = this;

        BaseService.fetch.stuffs(function() {
            self.stuffies = BaseService.stuffies;
            console.log(self.stuffies);
            self.cerrorMessages = BaseService.cerrorMessages;
        });
    }]);

And this is my BaseApp:
angular.module("BaseApp", [])
    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    }])

    .config(['$locationProvider', function($locationProvider){
        $locationProvider.html5Mode(true);
    }])

    .factory("BaseService", ["$http", "$window", function($http, $window) {
        var self = this;

        /* All functions which call fetch should have a callback function
         * on the front-end which sets
         * 1) a variable (i.e. stuffies etc.)
         * 2) and BaseService.cerrorMessages. */
        self.fetch = {
             stuff: function(callback) {
                 $http.get("/stuffs/")
                 .then(function(response) {
                     self.stuffies = response.data;
                     callback();
                 }, function(response) {
                     self.accessErrors(response.data);
                     callback();
                 });
             }
        };

The problem is, even though it logs an item inside self.stuffies (when this line is run: console.log(self.stuffies);), here is not printed in the HTML. There doesn't seem to be anything inside ctrl.stuffies. I tried moving console.log(self.stuffies); outside of BaseService.fetch.stuffs(function() and it logs undefined. How do I get ctrl.stuffies to be BaseService.stuffies?

A: You're using a factory like a service.
Have your factory self call (initialize) its self.fetch function, then upon construction of your controller, set the controller's stuffies variable equal to the factory's stuffies variable.
Edit:
If you only want some of the data initialized at once, you can self call only the functions you want to retrieve data initially.
You can then use a resolve in your routing to initialize more data when a specific route is hit.

A: There is no need to use callbacks with the $http service as it returns promises:
//.factory("BaseService", ["$http", "$window", function($http, $window) {
app.service("BaseService", ["$http", "$window", function($http, $window) {
    //var self = this;

    /* All functions which call fetch should have a callback function
     * on the front-end which sets
     * 1) a variable (i.e. stuffies etc.)
     * 2) and BaseService.cerrorMessages. */
    this.fetch = {
         stuff: function() {
           //vvvv RETURN the promise
           return $http.get("/stuffs/")
             .then(function(response) {
                 //vvvv RETURN the data
                 return response.data;
                 //self.stuffies = response.data;
                 //callback();
           });//, function(response) {
             //    self.accessErrors(response.data);
             //    callback();
             //});
         }
    };
});

There is no need to do anything with $http errors in the service. Errors will be carried forward automatically in the promise.
Then in the controller extract the data (or the error) from the promise:
/* REPLACE
BaseService.fetch.stuffs(function() {
    self.stuffies = BaseService.stuffies;
    console.log(self.stuffies);
    self.cerrorMessages = BaseService.cerrorMessages;
});
*/

BaseService.fetch.stuffs
  .then(function(data) {
    self.stuffies = data;
    console.log(self.stuffies);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});

For more information, see

*

*AngularJS $http Service API Reference.

*MDN JavaScript Reference - return Statement

I changed your service to a factory and made it this: and used it this way:
BaseService.fetch.stuffs()
  .then(function(data) {
    self.stuffs = data;
    console.log(self.stuffs);
}).catch(function(errorResponse) {
    self.cerrorMessages = errorResponse.data;
});

Is this fine (using factory because there are other functions inside the factory as well and I don't want to have to change them all to services)?

Sorry, the factory is
self.fetch = {
    stuffs: function() {
        return $http.get("/stuffs/")
          .then(function(response) {
              return response.data;
        });
    }
};

Either a service or a factory will work. With a service, functions can be added by adding properties to the this context which is automatically returned (unless overridden with a return statement). With a factory, a return statement is manditory. Functions are added to the object returned. The choice is a question of style. They are both used the same way.


text:
Q: Best Practice - Share UnityContainer across Tiers in Asp.net MVC? I have a UnityContainer that gets it's configuration information at runtime in the global.asax file of an MVC web app.
I also have services in another assembly that need access to this container so that they can perform resolutions manually.
How can I best share the two?  I don't want to have a reference between my Data assembly and MVC, but I want the data assembly to have access to the UnityContainer that was configured by the web app.
I'm wondering what others are doing in this situation.

A: I just registered the container into itself, and then let the dependencies cascade throughout the referenced tiers.
ie
// configure container
blah
blah
blah
// register itself
Container.RegisterInstance(Container);
Then anyone that needs it just has it as a dependent property or constructor param.

A: I am using StructureMap (similar tool) and generally share my configuration across projects in a solution.  This means that they are not directly sharing the same object per-se unless they are working in the same context.  In a simple application where the website is loading the assembly to perform work from the controller to the business layer and then into the dal...they are indeed using the same object.  But as soon as you need to put your tier's into physically separate layers (hardware) then the config can go with it.  This becomes a deployment issue at that time.


text:
Q: SQL Server - Copy database from Server 2008 to Server 2012 I have two servers one in Denmark the other here in the UK. I need to make a copy of a database out of SQL Server Management 2008 (1st server) and place it in SQL Server Management 2012(2nd server). I have tried connecting to the remote server but have been getting difficulties so instead of connecting both up and doing it that way I was hoping there is a function like copy database which could do this for me. I have gone into tasks and copy database in SQL Server 2008 but in the Copy Database Wizard that appears it says "You can use this wizard to move or copy databases from an instance of SQL Server 2000 or later to an instance of SQL Server 2008". I'm looking for something like this that will work for Server 2012.

A: You can create a backup with the Management Studio on the source and restore it on the target.

A: *

*Copy your database file .mdf and log file .ldf and paste in your SQL Server

*Install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA.

*Open SQL Server. Right-click on Databases then Select Attach... option.

A: You need Management Studio 2012 to make this step. You can then create empty database on 2012 server. Right click on this empty DB->Tasks->Copy database..
Wizard will guide you. You should to this under 2012 Management Studio because it is compatible with 2008 Server - vice versa it will not work.
Of course, cleanest way is to do this via backup (.bak file - Tasks->Backup.. then on 2012 server Tasks->Restore->Files or FileGroups) but you need remote access (RDP) to the server.


text:
Q: Mipmapping with generating textures in xna I'm generating some textures in my game, but I need mipmaps for them. Why are there no mipmaps generating even when I'm setting mipMap to true in the constructor and how can I generate the mipmaps?

A: You have to perform the downscaling yourself, and then fill each mipmap level yourself.
You can use this version of SetData to specify which mipmap level you are setting.
Use the LevelCount property to determine how many mipmap levels were created by the constructor.


text:
Q: Zero of a complex polynomial satisfying one of three assertions. Let $n$ be a positive integer greater than $1$. Prove that if $x$ is a zero of  $ X^n+1+(-1)^n(X+1)^n$ then $|x|=1$ or $|x+1|=1$ or $|x+1|=|x|$.
My initial thought was to study the cases $n=2,3,4$ (that confirm indeed the result) in order to establish a general approach, but I didn't succeed to do this.

A: The set of roots of this polynomial has several symmetries:

*

*It is symmetric in the line $\operatorname{Im}(z) = 0$.

*It is symmetric in the line $\operatorname{Re}(z) = -\tfrac{1}{2}$.

*It is symmetric under $z \mapsto z^{-1}$ ($z \neq 0$).

Note that the last symmetry maps the line $\operatorname{Re}(z) = -\tfrac{1}{2}$ to $\{z \mid |z+1|=1\}$ and vice versa.
If $n$ is odd then $\{-1,0\}$ are roots.  Let $\zeta$ be a primitive third root of unity.  Then $\zeta + 1$ is a primitive sixth root of unity.  If $3 \nmid n$ then $\zeta^{\pm 1}$ are roots and if $n \equiv 1, 4$ ($\bmod$ $6$) then $\zeta^{\pm 1}$ are double roots.  (One can check this by considering the derivative at $\zeta^{\pm 1}$.)
If we can show that the polynomial has sufficiently many zeroes on the unit circle then its symmetries may suffice to locate all zeroes, which will then automatically satisfy the required conditions.
Substitute $X \leftarrow e^{2it}$ to get
$$\begin{eqnarray}
e^{2i n t} + 1 + (-1)^n(e^{2it} + 1)^n &=& e^{2int} + 1 + (-1)^ne^{int}(2\cos(t))^n \\
&=& e^{int}\left(2\cos(nt) + 2^n(-\cos(t))^n \right)
\end{eqnarray}
$$
and therefore $e^{2it}$ is a zero precisely if $$ \cos(nt) + 2^{n-1}(-\cos(t))^n = 0.$$
If $t \in [\tfrac{\pi}{3}, \tfrac{\pi}{2}]$ then $|2^{n-1}\cos(t)^n| \leq \tfrac{1}{2}$ while $\cos(n t)$ oscillates between $-1$ and $1$.  Therefore there must be a root between any two points where $\cos(nt)$ goes from $-1$ to $1$ or vice versa.  Now $\cos(n t)= \pm 1$ precisely if $nt=m \pi$ for some integer $m$.  By symmetry, each root in the open interval accounts for six roots of the polynomial.  Let's check what happens by considering six different cases $n$ $\bmod$ $6$.
$n = 6k$: $\cos(n t) = \pm 1$ when $2k \leq m \leq 3k$ so $k+1$ times and therefore at least $k$ roots on the open interval. All $6k$ roots are accounted for.
$n=6k+1$. At least double roots at $\zeta^{\pm 1}$ and simple roots at $\{-1,0\}$. Now $\cos(n t) = \pm 1$ when $2k + 1 \leq m \leq 3k$ so $k$ times accounting for at least $k-1$ roots.  So all $6k$ roots are accounted for.
$n=6k+2$. At least simple roots at $\zeta^{\pm 1}$. Now $\cos(n t) = \pm 1$ when $2k + 1 \leq m \leq 3k + 1$ so $k + 1$ times accounting for at least $k$ roots.    So all $6k + 2$ roots are accounted for.
$n=6k+3$. At least simple roots at $\{-1,0\}$.  Now $\cos(n t) = \pm 1$ when $2k + 1 \leq m \leq 3k + 1$ so $k + 1$ times accounting for at least $k$ roots.    So all $6k + 2$ roots are accounted for.
$n=6k+4$. At least double roots at $\zeta^{\pm 1}$.  Now $\cos(n t) = \pm 1$ when $2k + 2 \leq m \leq 3k + 2$ so $k + 1$ times accounting for at least $k$ roots.    So all $6k + 4$ roots are accounted for.
$n=6k+5$. At least simple roots at $\zeta^{\pm 1}$ and $\{-1,0\}$.  Now $\cos(n t) = \pm 1$ when $2k + 2 \leq m \leq 3k + 2$ so $k + 1$ times accounting for at least $k$ roots.  So all $6k + 4$ roots are accounted for.
So in all cases we conclude that the roots satisfy the required conditions.

A: The following doesn't really help:
This seems like a homework problem, so I'm leaving the details to you. But the key idea is to use the argument principle. For example, we can show that there are no roots with |z|<1 examine what occurs when $|z|<1$ and either $|z+1|<1$ or $|z+1|>1$ by considering $\oint_C \frac{f'(z)}{f(z)}dz$ for any closed contour contained inside the unit circle one of these domains (where $f(z)$ is your polynomial, after factoring out the trivial zeros). Then the integrand is a holomorphic function on this domain (prove it), so the integral evaluates to zero and thus there are no zeros in the interior of the unit circle.
In a similar way, you can extend to consider the domain on which $|z|>1$ and $|z| > |z+1|$, as well as the domain on which $|z| > 1$ and $|z| < |z+1|$.
Hope this helps!


text:
Q: Finding the first day of this week in Informix How might I select the first day of this week in Informix SQL?

A: Informix takes Sunday as the first day of the week (number 0). If you want to find the most recent Sunday, then this would do it:
SELECT TODAY - (WEEKDAY(TODAY)) UNITS DAY
FROM   systables
WHERE  tabid=1;

The FROM clause is required, and you could put another table there depending on what else you want to retrieve.

A: Generalizing the answer by trincot, if you want the first day of the week to be the day with code N, then the expression should be:
date_col - MOD(7 + WEEKDAY(date_col) - N, 7)

Clearly, when N is 0, the MOD expression is equivalent to WEEKDAY(date_col) and the result is therefore the same as given by trincot.
For example, for Monday (day 1) as the first day of the week, for the dates in November 2015 (where 2015-11-01 was a Sunday), I created a table Date_List with a single column d of type DATE and inserted a record for each in November 2015.
SELECT d AS Date, WEEKDAY(d) AS W1,
       d - WEEKDAY(d) AS Sunday,
       MOD(7 + WEEKDAY(d) - 1, 7) AS W2,
       d - MOD(7 + WEEKDAY(d) - 1, 7) AS Mondat
  FROM date_list
 ORDER BY d;

Results
The column labelled 'Sunday' shows the date of the Sunday on or before the date in the first column; the column labelled 'Monday' shows the date of the Monday on or before the date in the first column.
Date        W1   Sunday      W2   Monday
2015-11-01   0   2015-11-01   6   2015-10-26
2015-11-02   1   2015-11-01   0   2015-11-02
2015-11-03   2   2015-11-01   1   2015-11-02
2015-11-04   3   2015-11-01   2   2015-11-02
2015-11-05   4   2015-11-01   3   2015-11-02
2015-11-06   5   2015-11-01   4   2015-11-02
2015-11-07   6   2015-11-01   5   2015-11-02
2015-11-08   0   2015-11-08   6   2015-11-02
2015-11-09   1   2015-11-08   0   2015-11-09
2015-11-10   2   2015-11-08   1   2015-11-09
2015-11-11   3   2015-11-08   2   2015-11-09
2015-11-12   4   2015-11-08   3   2015-11-09
2015-11-13   5   2015-11-08   4   2015-11-09
2015-11-14   6   2015-11-08   5   2015-11-09
2015-11-15   0   2015-11-15   6   2015-11-09
2015-11-16   1   2015-11-15   0   2015-11-16
2015-11-17   2   2015-11-15   1   2015-11-16
2015-11-18   3   2015-11-15   2   2015-11-16
2015-11-19   4   2015-11-15   3   2015-11-16
2015-11-20   5   2015-11-15   4   2015-11-16
2015-11-21   6   2015-11-15   5   2015-11-16
2015-11-22   0   2015-11-22   6   2015-11-16
2015-11-23   1   2015-11-22   0   2015-11-23
2015-11-24   2   2015-11-22   1   2015-11-23
2015-11-25   3   2015-11-22   2   2015-11-23
2015-11-26   4   2015-11-22   3   2015-11-23
2015-11-27   5   2015-11-22   4   2015-11-23
2015-11-28   6   2015-11-22   5   2015-11-23
2015-11-29   0   2015-11-29   6   2015-11-23
2015-11-30   1   2015-11-29   0   2015-11-30

Calendars for October and November 2015
    October 2015
Su Mo Tu We Th Fr Sa
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

   November 2015
Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

Stored procedures
It would be possible, and trivial to write stored procedures to do these calculations.
CREATE FUNCTION nday_on_or_before(ref_date DATE, nday INTEGER) RETURNING DATE;
    RETURN ref_date - MOD(7 + WEEKDAY(ref_date) - nday, 7);
END FUNCTION;

CREATE FUNCTION sunday_on_or_before(ref_date DATE) RETURNING DATE;
    RETURN nday_on_or_before(ref_date, 0);
END FUNCTION;

CREATE FUNCTION monday_on_or_before(ref_date DATE) RETURNING DATE;
    RETURN nday_on_or_before(ref_date, 1);
END FUNCTION;

Etc.
If you want the Monday strictly before the reference date, then you can use:
CREATE FUNCTION nday_before(ref_date DATE, nday INT) RETURNING DATE;
    RETURN nday_on_or_before(ref_date - 1, nday);
END FUNCTION;

CREATE FUNCTION sunday_before(ref_date DATE) RETURNING DATE;
    RETURN nday_on_or_before(ref_date - 1, 0);
END FUNCTION;

CREATE FUNCTION monday_before(ref_date DATE) RETURNING DATE;
    RETURN nday_on_or_before(ref_date - 1, 1);
END FUNCTION;

Etc.  Note that the nday_* functions do not validate that the nday parameter is in the range 0..6; that can be done by applying the MOD function more often:
 MOD(MOD(nday, 7) + 7, 7)

That yields a value in the range 0..6 regardless of whether the input value of nday is positive or negative, because the inner MOD returns a value in the range -6..+6, and the outer converts that to 0..6.  Alternatively, the functions could throw an exception when the nday value is out of range.


text:
Q: splunk alert to check every minute I'm trying to make an alert in splunk that checks every minute for query results. For testing purposes I set the interval to 361s to ensure that I get plenty of results and see if the results from one check will also still be there in the subsequent 5-6 checks.
This is what I configured: (sorry for posting german screenshot, but that is our splunk is installed)

I'm only getting an e-mail at the full hour. Considering my 361s interval, a successfull trigger are 11h00 should also result in a successfull trigger at 11h01, 11h02 etc., but there is no e-mail. And there definitely are query results every few minutes.
isn't "0 * * * *" the corret cron expression for "every minute"? And what is "Ablauf" anyways? Is this the issue maybe, I can't find any documentation what it is for.

A: I just noticed that the first digit for the cron expression is for minutes and not for seconds. I guess that explains it.


text:
Q: generate new Certificate Signing Request after upgrading to Snow Leopard? i recently updated my mac to Snow Leopard. But due to it all my provisioning profiles have been deleted. I didnt keep the backup for my keychain so i downloaded my Certificate Signing Request again from apple developer program and installed it in my mac.So to upload one of my old application i created a new App Id with a new Provisioning profile..I did not have MobileDevice folder in my Library so i created it manually and copied the profile to that folder..Now in my xcode when i try to select my provisioning profile it does not show any.I selected the Iphone Distribution profile(Xcode3.2 might automatcally detect it) but it doesnt work.I manually entered the name of my profile via other but still it gives me error.

Code Sign error: The identity 'iPhone Distribution' doesn't match any valid certificate/private key pair in the default keychain

Do i have to create a new Certificate Signing Request for Os 10.6??
Or creating MobileDevice folder manually wont work??
What should i do??

A: I think you have to generate a new certificate. Unless you exported your previous certificates with your private key.


text:
Q: Questions Array into a file I created a program that asks the user 10 random multiple choice questions. I also created a question class that feeds into my main method. I have an array for my 10 multiple choice questions and I need to take those questions and store them in a text file. The file needs to be formatted as such:
Question Text
Answer Option A
Answer Option B
Answer Option C
Answer Option D
Correct Answer
My question class has a constructor that is suppose correspond to the text file I need to create.
I am unsure how to start this and hoping to get some ideas that could help me.
Example of my code:
//Set question and answers.
            questions[0] = new P3A2_Harvey_4251833_Question("JVM stands for what?", "D");
            questions[0].setChoice("A. Java Variable Machine");
            questions[0].setChoice("B. Java Variable Method");
            questions[0].setChoice("C. Java Virtual Method");
            questions[0].setChoice("D. Java Virtual Machine");
            questions[1] = new P3A2_Harvey_4251833_Question("Every complete programming statement ends with what?", "A");
            questions[1].setChoice("A. Semicolon");
            questions[1].setChoice("B. Period");
            questions[1].setChoice("C. Colon");
            questions[1].setChoice("D. Question Mark");
            questions[2] = new P3A2_Harvey_4251833_Question("This type of expression can be either true or false", "C");
            questions[2].setChoice("A. Null Expression");
            questions[2].setChoice("B. Binary Expression");
            questions[2].setChoice("C. Boolean Expression");
            questions[2].setChoice("D. Method Expressions");
            for(int i = 0; i<questions.length;i++)
            {
                //Randomizing the questions in the array.
                int n = rand.nextInt(3);
                System.out.print("Question " + (n+1)+":");
                System.out.println(questions[n].getQuestion());
                System.out.println(questions[n].getChoice());
                System.out.print("Enter your answer: ");
                userInput = keyboard.nextLine();
                //Asking for users input reference to the question.
                while(!userInput.equals("A")&&!userInput.equals("B")&&!userInput.equals("C")&&!userInput.equals("D"))
                {
                    System.out.println("invalid response");
                    System.out.print("Enter your answer: ");
                    userInput = keyboard.nextLine();

A: I think you are very close to your solution. Here is a suggestion.
As you have successfully created a Question class, you could write an extra method for this class which will be in charge of writing the question's contents to the given file. Something like that:
public class Question {
    //...

    public void write (PrintWriter out) {
        //TODO write your desired output
        out.println("This line will be written to whatever is given as parameter");
    }
}

Then in your main, you could create a file and have each question written to it. For instance, if you have a single question q, this would write to file named filename.txt :
Question q = new Question(...);

PrintWriter writer = new PrintWriter("filename.txt");

q.write(writer); //Give the PrintWriter to the write method of Question class

writer.close();

I think you can figure out how to proceed from there on your own ;-).


text:
Q: AWS API Gateway client certificates in Go lang I'm trying to secure connection between AWS API Gateway and my API endpoint services exactly as it is described int his documentation: http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started-client-side-ssl-authentication.html
AFAIK I need to copy the cert form AWS API Gateway and use http.ListenAndServeTLS method. But it accepts two files: keyFile and certFile
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler).
When I click on copy link (see image below)

the only thing I get is the certificate in such format (I've shortened it for explanation purposes):
-----BEGIN CERTIFICATE-----
MIIC6TCCAdGgAwIBAgIJAKbyiCf2f5J2MA0GCSqGSIb3DQEBCwUAMDQxCzAJBgNV
fYe+dxR0PMFvfUpZaGgaY1ykQG1sNaw/b6NjNg9c1aEVSZ7b1eU/cBmb6XqHw0Ih
7yHtBm+p8Px4NMAT9YhytTxPRBYpApfUsfPMa3qfUWvvj4TD0LR6bW980bebyxUn
BigXToSFlPeiNGdU/Zpiw9crzplojNBFc=
-----END CERTIFICATE-----

So my question is, how exactly I need to configure ListenAndServeTLS method to make sure the any request to my service is from API Gateway? Where I can find private key? It's quite confusing for me.

A: The client certificate AWS is given you is for authenticating the client that send requests to your service, which is the AWS gateway.
This cert is not to be used to start your server, but to authenticates requests.
See an example of use below, untested code, but as a lead.
func Hello(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, "hello, world!\n")
}

func main() {
    http.HandleFunc("/hello", Hello)

    certBytes, err := ioutil.ReadFile("aws-gateway.pem")
    if err != nil {
        log.Fatal(err)
    }
    block, certBytes := pem.Decode(certBytes)

    cert, err := x509.ParseCertificate(block.Bytes)
    if err != nil {
       log.Fatal(err)
    }

    clientCertPool := x509.NewCertPool()
    clientCertPool.AddCerts(cert)

    tlsConfig := &tls.Config{
        ClientCAs: clientCertPool,
        // NoClientCert
        // RequestClientCert
        // RequireAnyClientCert
        // VerifyClientCertIfGiven
        // RequireAndVerifyClientCert
        ClientAuth: tls.RequireAndVerifyClientCert,
    }
    tlsConfig.BuildNameToCertificate()

    server := &http.Server{
        Addr:      ":8080",
        TLSConfig: tlsConfig,
    }

    server.ListenAndServeTLS("server.crt", "server.key")
}

This way, your service will require that all requests provide a certificate and will verify it against the pool of ClientCA. You could, of course, add more certificates to the client pool if desired.


text:
Q: Reliable Service Data Model Issue I'm new to Azure Service Fabric, and watched Ivan Gavryliuk's "Understanding the Programming Models of Azure Service Fabric" course on Pluralsight. I've been following along and the basic data model in the reliable service and API work as explained in the course.
However, if I increase the complexity of the data model used I hit an error.
Product.cs from the ECommerce.ProductCatelog.Model
namespace ECommerce.ProductCatalog.Model
{
   public class Product
   {
      public Guid Id { get; set; }

      public string Name { get; set; }

      public string Description { get; set; }

      public double Price { get; set; }

      public int Availability { get; set; }
      public Supplier Suppliers { get; set; }
   }

   public class Supplier
   {
      public Guid Id { get; set; }
      public string Name { get; set; }

   }
}

ApiProduct.cs from ECommerce.API.Model
   public class ApiProduct
   {
      [JsonProperty("id")]
      public Guid Id { get; set; }

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

      [JsonProperty("description")]
      public string Description { get; set; }

      [JsonProperty("price")]
      public double Price { get; set; }

      [JsonProperty("isAvailable")]
      public bool IsAvailable { get; set; }

      [JsonProperty("suppliers")]
      public ApiSupplier suppliers { get; set; }

   }

   public class ApiSupplier
   {
      [JsonProperty("id")]
      public Guid Id { get; set; }

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

   }

ProductController.cs from Ecommerce.API.Controlers
[HttpGet]
      public async Task<IEnumerable<ApiProduct>> GetAsync()
      {
         IEnumerable<Product> allProducts = await _service.GetAllProductsAsync();

         return allProducts.Select(p => new ApiProduct
         {
            Id = p.Id,
            Name = p.Name,
            Description = p.Description,
            Price = p.Price,
            IsAvailable = p.Availability > 0,
            suppliers = p.Suppliers
         });
      }

The last line in the above block triggers an intellisense error:
"Cannot implicitly convert type 'ECommerce.ProductCatelog.Model.Supplier' to 'ECommerce.API.Model.Supplier'"
Any suggestions on how to work around this welcome :)
Cheers,
Adam

A: Your problem is not specific to Service Fabric but C# in general. You are trying to set a variable with a value of a different type.
In this line:
IEnumerable<Product> allProducts = await _service.GetAllProductsAsync();

You get a collection of items of type ECommerce.ProductCatalog.Model.Product. In this class, you added the property Suppliers (which should be Supplier since it's not a collection) of type ECommerce.ProductCatalog.Model.Supplier.
Now, with the following line:
     return allProducts.Select(p => new ApiProduct
     {
        Id = p.Id,
        Name = p.Name,
        Description = p.Description,
        Price = p.Price,
        IsAvailable = p.Availability > 0,
        suppliers = p.Suppliers
     });

you are converting this collection to a collection of a new type ECommerce.API.Model.Product, to which you added a new property Suppliers of type ECommerce.API.Model.Supplier, but you set this property to the original value, without converting it. So, convert the original Suppliers property to the correct type:
     return allProducts.Select(p => new ApiProduct
     {
        Id = p.Id,
        Name = p.Name,
        Description = p.Description,
        Price = p.Price,
        IsAvailable = p.Availability > 0,
        suppliers = new ApiSupplier
        {
           Id = p.Suppliers.Id,
           Name = p.Suppliers.Name
        }
     });

Update: make Suppliers a collection
Make your Suppliers property a collection both in your data model and in your Api model:
 public Collection<ApiSupplier> suppliers { get; set; }

Then convert the collection accordingly:
     return allProducts.Select(p => new ApiProduct
     {
        Id = p.Id,
        Name = p.Name,
        Description = p.Description,
        Price = p.Price,
        IsAvailable = p.Availability > 0,
        suppliers = p.Suppliers.Select(s => new ApiSupplier
           {
             Id = s.Id,
             Name = s.Name
           }
     });


text:
Q: How can I show/hide a navbar with jquery on a specific width? I know the following code is wrong. I just need to know how to show a navbar on scroll and width at the same time. So I wrote it like that for better understanding:
if ($(window).scrollTop() > 300 ) && if ($(window).width() > 768 ) {

    $('#scroll-nav').slideDown(300);

} else {

    $('#scroll-nav').slideUp(300);
});

A: you can this:
 if ($(window).scrollTop() > 300 && $(window).width() > 768 ) {

        $('#scroll-nav').slideDown(300);

    } else {

        $('#scroll-nav').slideUp(300);
    }


text:
Q: Vue getter/setter behavior showing unexpected side effect when * and / by 100 I have a getter and setter function in a Vue component that ideally would allow the user to type in percentages as whole numbers and my application use them as decimals. Here is the getter/setter:
theValue:{
  //display whole numbers to the user
  get(){
    if(this.value < 1){
      return this.value * 100
    }
    return this.value
  },
  // set the decimal into the application
  set(update){
    this.$emit("input", val/100 );
  }
}

The setter works as expected, however, when the getter receives the value again I have some unexpected consequences.
When you type in the input 7 it displays 7.0000000001 on the input. The application sees .07 just fine.
When you type 111 in the input it displays 1.11 instantly.
I can duplicate the issue in the console, what would be a practical way about going about remedying this.
Caveats: These are reusable components and some values in the application can have up to 7 leading zeros for valid values. Using toFixed() is not going to work as there needs to be flexibility in this component for these fields. In theory, I could write 2 different components, one for simple numbers to the hundredth and another for past that. I'm wondering if there are any ideas to do this gracefully.


text:
Q: Iota iota.adapter.BadApiResponse: 403 response from node Message=forbidden I am attempting to connect to the one-click-tangle I have set up on WSL2 ubuntu locally. However, when I try and connect to the automatically generated node at http://localhost:14265 I get an error and the following response: iota.adapter.BadApiResponse: 403 response from node: {'error': {'code': '403', 'message': 'Forbidden, error: code=403, message=Forbidden'}}. I'm guessing I'm missing something small.
from iota import Iota
from iota import ProposedTransaction
from iota import Address
from iota import TryteString

api = Iota('http://localhost:14265')

print(api.get_node_info())

I have also tried the above with a generated seed.

A: Ok, I was struggling with this one for a while too. If you want to get info, the way to go is GET request at
http://localhost:14265/api/v1/info

If you want to send a message to the tangle, you want a POST request to
http://localhost:14265/api/v1/messages


text:
Q: simple form tutorial, php method doesnt invoke i'm doing some simple tutorial from jQuery and as for now i have problems with php script, sending data from the input form...
My input form looks like follows:
<form method="post" action="submit_to_db.php">

    Name
    <input type="text" name="name" id="name" />

    E-mail address
    <input type="text" name="email" id="email" />

    Any comments
    <textarea rows="5" cols="35" name="comments" id="comments"> </textarea>

    <input type="submit" name="submit" id="submit" value="Send costam" />

</form>

The script for jQuery is:

Ok, so why after I clicked the Submit button the action isnt invoked... i mean my database isn't changing, no data is added and my browser just present the code for submit_to_db.php... Maybe it can be useful that I'm using XAMPP and at the beginning I had to change my localhost's port to 81 - in httpd. conf I chinge Listen: 80 to 81...
Really sorry for such n00b question, I really don't know how to move on with this tutorial :( thanks a lot for ur help.
Ahh. Just in case - php file:
<?php
    $conn = new mysqli('localhost:81', 'root', '', 'my_db');
    $query = "INSERT into comments(name, email, comments) VALUES (?, ?, ?)";

    $stmt = $conn->stmt_init();
    if($stmt->prepare($query)) {
        $stmt->bind_param('sss', $_POST['name'], $_POST['email'],     $_POST['comments']);
        $stmt->execute();
    }
    ?>

A: As comments pointed, the submit button does his default action while you are waiting for the ajax.
You can get the form to use your function instead of the form action by selecting the form and using the submit method, like this :
$('form').submit(function(){
/// function goes here
})

A: In addition to the comments about preventing the default action, you may also need to url encode your query string.  Otherwise things that are written in the forms could potentially cause problems in your query string.


text:
Q: Can we pass 3 url to backend(asp.net core, 1 master, 2 slave) appsettins.json have 1 connectionstring yandex cloud? postgresSql master-slave We have datacenter in 3 zone and 3 different url.
Connect to database postgres is psql "hostname=url1,url2,url3 \port=......"
Yandex understand what is master now and if master with url1 broken, Yandex start using url2 or url3.
url2, url3- slave.
But in backend we can't pass 3 url. We connect to database with "hostname=url1 \port=......"
We have only 1 url and can't using slave.
Can we pass 3 url to backend(asp.net core). If database in datacenter1 work correctly - using url1, if datacenter1 broken- using url2 in datacenter2

A: There are two particular FQDN types in Yandex Cloud managed databases that can help you here: one always points to the master, second always points to the least lagging replica.
How does it work? When the master is switching in your managed Postgres cluster, a script goes to the DNS and amends the master pointing FQDN, resolving it into the correct IP. The exact process handles the consistency of the replica pointed FQDN.
You don't have to pass three hosts. Use the master FQDN instead.
https://cloud.yandex.com/en/docs/managed-postgresql/operations/connect#special-fqdns


text:
Q: Parse error: syntax error, unexpected '=' in *.php on line? Every thing is OK.but i can not find why Parse error
my code
<?php
    if ($_REQUEST["submit"] == "ChangeTheBgColor")
        $bgcolor = strval($_REQUEST["thecolor"]);
    else
        $bgcolor = "white";
?>
<html>
<body bgcolor="<?php =$bgcolor; ?>" >
<form name= "color" method="get" action="<?php = $_SERVER['PHP_SELF'];?>">
Enter a Color:
<input type="text" name="thecolor" value="">
<input type="submit" name="submit" value="ChangeTheBgColor">
</form>
</body>

</html>

I use devPhp .
Why I get the below Error and how Fix it?

Parse error: syntax error, unexpected '=' in C:\doc\demo.php on line 8

A: You should write :
<?php echo $_SERVER['PHP_SELF'];?>

And not :
<?php = $_SERVER['PHP_SELF'];?>


text:
Q: Conjugating a permutation I am trying to see that two permutations are conjugate exactly when they have the same cycle decomposition. I fail to see that

$$r(i_1,i_2,\dots,i_k)r^{−1}=(r(i_1),r(i_2),\dots,r(i_k))$$
  for permutations $r$ in a set $X\ni \{i_p\}^k_0$

Any thoughts would be appreciated.
p.s. I ask this question in a new post as suggested by Mr. Gerry Myerson. Still, I believe it belongs to the above thread.

A: Evaluate the permutation function on LHS at  $r(i_1), r(i_2)$ etc and verify that it matches the cycle on the RHS. Note that LHS is a composition of 3 functions (permutations). You also have to verify that others are fixed points for that permutation.
Let me verify the value of LHS at the element $r(i_1)$. First applying $r^{-1}$ takes it to $i_1$, which in turn is taken  to $i_2$ by the cycle. Now this element is carried to $r(i_2)$ by $r$, the third element in the composition. Now you can proceed this way.


text:
Q: How to access a variable from another activity So I'm trying to access a string from my main activity in my Locator activity, if I try to instantiate the String as public static it throws an error and says I cannot declare a static string in a non-static class, and when I tried to get it through intents I get an error that says.[EDIT] Now I've been able to access the intent without an error now I get a NullPointerException
No Activity found to handle Intent { (has extras) }

this is my main activity code:
options = (Spinner) findViewById(R.id.optionselect);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.options, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        options.setAdapter(adapter);
        String XxXSelect =options.getSelectedItem().toString();
         Intent i = new Intent(MainActivity.this,Locator.class);
    i.putExtra("XxXchoice",XxXSelect);
    startActivity(i);

my locator activity code:
Line -> 204   String XxXChoicei = getIntent().getStringExtra("XxXchoice");
full logcat
Caused by: java.lang.NullPointerException
            at com.example.adrian.trucktracker.Locator.Updater(Locator.java:204)
            at com.example.adrian.trucktracker.Locator.clickedUpdate(Locator.java:265)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3860)
            at android.view.View.performClick(View.java:4480)
            at android.view.View$PerformClick.run(View.java:18686)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5872)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)

A: you need Static Variable to declare global variable in Application Class,
so Change your code to:
class GlobalClass extends Application {

  public static String myVal;

}

then whereever you need to access this data, get Application object by:
GlobalClass global=(GlobalClass)context.getApplication();
global.myVal="anything";

and don't forget to add it to the AndroidManifest.xml file
<application
        android:name="packagename.GlobalClass"
        ....
        ....
        //other codes here
</application>

A: Try this
 Intent i = new Intent(Youractivity.this, locator.class);
 Bundle b = new Bundle();
 b.putString("XxXchoice", XxXSelect);
 i.putExtras(b);
 startActivity(i);

and for more info go to #Intent

A: Change your code to get rid of the Bundle.
Intent i = new Intent(MainActivity.this, Locator.class);
i.putExtra("XxXchoice", XxXSelect);
startActivity(i);

Then in the Locator class do this...
String XxXChoicei = getIntent().getStringExtra("XxXchoice");

You were complicating things by adding an exta Bundle to the Intent which already has the ability to carry a Bundle of its own.

A: you can use M D answer if you want to use intent. if you want to access String from Main Activity.java you can do like this
in your **MainActivity**

//declare a method
public static String getString() {

   String result;

   // assign value to string here
     result = "your assingment"

     return result;
}

and in your another activity
//get value like this

  String string = MainActivity.getString();

This way is used to access variable whenever required.


text:
Q: Is the image f(A) of a n-Lebesgue measurable function m-Lebesgue measurable when f is Lipschitz? Suppose $f:\mathbb{R}^n \rightarrow \mathbb{R}^m$ is Lipschitz, where $n\geq m$. Let $\lambda_n$ and $\lambda_m$ denote the Lebesgue measure on $\mathbb{R}^n$ and $\mathbb{R}^m$ respectively. If $A\subset\mathbb{R}^n$ is $\lambda_n$--measurable,  is $f(A)$ $\lambda_m$--measurable?
This statement appears in Evans-Gariepi's book on Measure Theory and fine properties of functions (Lemma 2 (i) in section 3.4.1) Using the machinery of Analytic sets I think the statement is true if $A$ is analytic, but without that machinery a prove for any $\lambda_n$-measurable set that uses the fact that $f$ is Lipschitz escapes me at the moment.
Just found out that the statement is actually incorrect. Evans-Gariepi already listed the statement above as errata and removed the statement in their second edition.


text:
Q: Работа с шаблонами документов Передо мной поставили такую задачу: создать шаблон документа(doc/excel), а после в приложении заполнять этот шаблон данными из БД с последующей отправкой на сервис с помощью API.
Сразу в голове появился вариант с установкой на сервер с приложением Microsoft Offic'a, создание на этом сервере шаблонов Word'a/Excel'я, заполнение и отправка на сервис, но ставить Microsoft Office на сервер с приложением не хочется.
Далее я подумал о Google Docs, но проблема в том, что приложение будет использовать в Китае, а доступ к Google у них нету. Соответственно Этот вариант отпадает.
Собственно, какие еще варианты существуют?

A: Как вариант использовать Visual Studio Tools For Office (VSTO). Есть возможность создавать: Надстройки (Add-Ins) и Шаблоны для MS EXCEL, MS Word. В код шаблона MS Excel добавить процесс загрузки данных из базы, например на событие: открытие книги Excel.

A: Нашёл отличную библиотеку TemplateEngine.Docx, работаю с ней.
Не требуется установки Word'a на сервер, при этом быстро и просто обрабатывает документы.


text:
Q: tippy.js html content / multiline text I am having problems with tippy.js tooltip and multiline html content. I cannot get the line breaks to work at all. HTML template below:

  Criticality*

    <select name="criticality" class="select form-control" required="" id="id_criticality">

      <option value="">-- Select criticality --</option>

        {% for key, value in criticality.items %}
          <option value="{{ key }}">{{ value }}</option>
        {% endfor %}

    </select>

  Line 1

  Line 2

  Line 3

  Line 4

I also have CSS file containing:
.tippy-multiline {
    white-space:pre !important;
}

Also tried:
.tippy-multiline {
    white-space:pre-wrap !important;
}

What happens is that the tooltip shows single line of text "Line 1
Line 2
Line 3
Line 4".
What I am missing here?


text:
Q: Can I encode a UIImage into the URL that is sent with an MSMessage in an iMessage app extension? I am trying to send an image along with the message that my app creates and inserts to send to other users. The image will be the same image used in the layout property of the message, but there is apparently no way to access the image property on the layout of the message on the receiving user's end.
Is it possible to send the image in the URL attached to the message and then access it on the second user's instance of the app? How could I go about this?

A: A couple ideas:

*

*Implement CloudKit to save/request the image (or another 'cloud' solution) and use message.url to share the image's url

*If the image is created and not an asset, use the message.url to carry "instructions" for rebuilding if possible?

A: As iMessage url scheme supports 5000 characters as written in apple documentation: https://developer.apple.com/reference/messages/msmessage/1649739-url
You can use convert your UIImage to NSData and then convert NSData to String and send the string in the url scheme. To retrieve, decode from string to UIImage.
E.g.:
let image = UIImage.init(named: "myImage.png")
let data = UIImagePNGRepresentation(image!)
let strImageData = data?.base64EncodedString(options: .lineLength64Characters)

Hope this helps


text:
Q: Check if apps have been transferred in iPad backup to iTunes I just backed up my iPad 1st Gen into iTunes on my MacBook Pro, but I need to make sure all my apps have been transferred. How can I check this?

A: You could use an app such as iPhone / iPod Touch Backup Extractor (for Mac) and iPhone Backup Extractor (for Windows) to check the backup to make sure that the files that you require have been successfully backed up.
If necessary, you could attempt to restore the files to be certain that you have access to them.


text:
Q: Run JQuery animation on numbers when I scroll once on a div I have an one-page-style website and somewhere in the middle I have a few numbers as statistics. I try to make them counting until they reach the stats when a user find the div for the first time after refreshing the page. I don't have the option to use a plugin, so I am trying to do it with JQuery only.
Here is the code:
$(window).scroll(function(){
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $("#our-company").offset().top;
    var elemBottom = elemTop + $("#our-company").height();

    if ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
       start_count();
    }
});

function start_count(){
    $('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});
}

The div with the id = our-company is the one containing the stats and all the numbers are in a span with a class of class = count. The problem in my code is that after I scrolled down on the stats and see the numbers counting, if I scroll up and down again, they start from the beginning. How can I make it run once?

A: Why not just put a flag var ?
var alreadyRun = false;
[...]
 if (alreadyRun == false && (elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
   alreadyRun = true;
   start_count();
}
[...]

Cheers


text:
Q: ModuleNotFoundError: No module named 'tflite_support.metadata_writers' from tflite_support.metadata_writers import object_detector
from tflite_support.metadata_writers import writer_utils
from tflite_support import metadata

ObjectDetectorWriter = object_detector.MetadataWriter
_MODEL_PATH = "mobile.tflite"
_LABEL_FILE = "labelmap.txt"
_SAVE_TO_PATH = "detect_metadata.tflite"

writer = ObjectDetectorWriter.create_for_inference(
    writer_utils.load_file(_MODEL_PATH), [127.5], [127.5], [_LABEL_FILE])
writer_utils.save_file(writer.populate(), _SAVE_TO_PATH)

# Verify the populated metadata and associated files.
displayer = metadata.MetadataDisplayer.with_model_file(_SAVE_TO_PATH)
print("Metadata populated:")
print(displayer.get_metadata_json())
print("Associated file(s) populated:")
print(displayer.get_packed_associated_file_list())

I use this code from link Github: https://github.com/tensorflow/tensorflow/issues/43775
But this code was a bug. Below that is an error after running the above code.

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-87-39fd915e7a2a> in <module>()

---->     1 from tflite_support.metadata_writers import object_detector
          2 from tflite_support.metadata_writers import writer_utils
          3 from tflite_support import metadata
          4
          5 ObjectDetectorWriter = object_detector.MetadataWriter

ModuleNotFoundError: No module named 'tflite_support.metadata_writers'
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
To view examples of installing some common dependencies, click the
"Open Examples" button below.
How to fix this bug?

A: You must have installed via
!pip install tflite_support

This is only supported in nightly(https://github.com/tensorflow/tensorflow/issues/26422) so install via
!pip install tflite_support_nightly

A: The tflite_support package on pypi now includes tflite_support.task
However, it will not run on Python 3.6. Version 0.3.1 is the latest one that supports Python 3.6. Using Python 3.7 instead of 3.6, and then installing verison 0.4.2 of tflite_support fixed the problem for me.


text:
Q: Why is eval signaling me the following error: Uncaught SyntaxError: Invalid or unexpected token at HTMLButtonElement.  (index.js: 11) I have a question about using eval in this little calculator. I get the error:

Uncaught SyntaxError: Invalid or unexpected token
at HTMLButtonElement.  (index.js: 11)
(anonymous) @ index.js: 11

const buttons = document.querySelectorAll(".btn");
const result = document.getElementById("result");

buttons.forEach((button)=>{
button.addEventListener("click",(e)=>{
    result.textContent += e.target.id;
   });
});

 equal.addEventListener("click",()=>{
 result.textContent = eval(result.textContent);
});

 clear.addEventListener("click",()=>{
  result.textContent= "";
})

<button class="btn" id="9">9</button>
<button class="btn" id="8">8</button>
<button class="btn" id="7">7</button>
<button class="btn" id="6">6</button>
<button class="btn" id="5">5</button>
<button class="btn" id="4">4</button>
<button class="btn" id="3">3</button>
<button class="btn" id="2">2</button>
<button class="btn" id="1">1</button>
<button class="btn" id="0">0</button>
<button class="btn" id=".">.</button>
<button class="btn" id="-">-</button>
<button class="btn" id="+">+</button>
<button class="btn" id="equal">=</button>
<button class="btn" id="*">*</button>
<button class="btn" id="/">/</button>
<button class="btn" id="clear">C</button>

A: It's because your id="equal" button is one of the buttons you hook up here:
buttons.forEach((button)=>{
button.addEventListener("click",(e)=>{
    result.textContent += e.target.id;
   });
});

Since you hooked it up before the other code hooking it up for a different reason, it adds its equal ID to the result text before trying to eval it, which means the result is not valid syntax for JavaScript code (for instance, 5-9equal).
The minimal fix is to skip it in that loop:
buttons.forEach((button)=>{
    if (button.id !== "equal") {
        button.addEventListener("click",(e)=>{
            result.textContent += e.target.id;
         });
    }
});

const buttons = document.querySelectorAll(".btn");
const result = document.getElementById("result");

buttons.forEach((button)=>{
    if (button.id !== "equal") {
        button.addEventListener("click",(e)=>{
            result.textContent += e.target.id;
         });
    }
});

equal.addEventListener("click",()=>{
    result.textContent = eval(result.textContent);
});

clear.addEventListener("click",()=>{
    result.textContent= "";
})

<button class="btn" id="9">9</button>
<button class="btn" id="8">8</button>
<button class="btn" id="7">7</button>
<button class="btn" id="6">6</button>
<button class="btn" id="5">5</button>
<button class="btn" id="4">4</button>
<button class="btn" id="3">3</button>
<button class="btn" id="2">2</button>
<button class="btn" id="1">1</button>
<button class="btn" id="0">0</button>
<button class="btn" id=".">.</button>
<button class="btn" id="-">-</button>
<button class="btn" id="+">+</button>
<button class="btn" id="equal">=</button>
<button class="btn" id="*">*</button>
<button class="btn" id="/">/</button>
<button class="btn" id="clear">C</button>

...or to otherwise leave that button out of the list you're looping through (by putting a different class only on the ones you want to handle in that loop, putting those buttons in a container the equal button isn't in, etc).

That said, in general it's best to avoid eval if you can. It's fine if you have absolute control over the text being evald, but since it executes any JavaScript code you pass to it (not just math equations), it's important not to use it on any string that you can't absolutely trust didn't come from a malicious source. For instance, if you have an app that allows User A to enter text you're going to use eval on, you must not use eval on it in User B's browser without User B's express permission and action.


text:
Q: return a remote image from php I have a database that sometimes returns a blob as an image and sometimes needs to fetch an image, when its a blob - I simply
$imageInfo = getimagesize($row['dealImage']);
switch ($imageInfo[2]) {
    case IMAGETYPE_JPEG:
        header("Content-Type: image/jpeg");
        break;
    case IMAGETYPE_GIF:
        header("Content-Type: image/gif");
        break;
    case IMAGETYPE_PNG:
        header("Content-Type: image/png");
        break;
    default:
        break;
}

    if(base64_decode($row['dealImage']) == false)
        echo $row['dealImage'];
    else
        echo base64_decode($row['dealImage']);

In my other case I get the URL from
$from['dealpromoimageURL']

But I need to return it the same was as above


text:
Q: Enterprise library: Roll back multiple transactions I'm currently using Microsoft Enterprise Library 5.0, and I'm wondering if the code below is an accepted way of handling transactions.
I've simplified the scenario a bit, but the essence is that I want to perform multiple inserts in different databases within the same transaction.
If either of the inserts fail, all transactions should be rolled back.
I've looked at TransactionScope, but I want to know if I could manage without it.
public void InsertStuff_AcrossDbs()
{
    //Create a ref to 2 different Db's on the same server
    Database db_a = DatabaseFactory.CreateDatabase("Data Source=localhost;Initial Catalog=db_a");
    Database db_b = DatabaseFactory.CreateDatabase("Data Source=localhost;Initial Catalog=db_b");

    //Create Connections for the 2 db's
    using (DbConnection connection_db_a = db_a.CreateConnection())
    using (DbConnection connection_db_b = db_b.CreateConnection())
    {
        //Create DbTransactions for the 2 db's
        DbTransaction transaction_dbA = connection_db_a.BeginTransaction();
        DbTransaction transaction_dbB = connection_db_b.BeginTransaction();

        try
        {
            //Insert into DbA.Person and get the PK
            DbCommand dbCmd_dbA_insert = db_a.GetSqlStringCommand("Insert INTO Person(Name,Age)Values('test',23); SET @pkReturnId= SCOPE_IDENTITY() ");
            db_a.AddOutParameter(dbCmd_dbA_insert, "pkReturnId", DbType.Int32, 0);
            db_a.ExecuteNonQuery(dbCmd_dbA_insert, transaction_dbA);
            int personID = Convert.ToInt32(db_a.GetParameterValue(dbCmd_dbA_insert, "@pkReturnId"));

            //Insert 'personId' into dbB.Employee  (a different table in a different db)
            DbCommand dbCmd_dbB_delete = db_a.GetSqlStringCommand("Insert INTO Employee(personId) VALUES(" + personID + ")");
            db_a.ExecuteNonQuery(dbCmd_dbB_delete, transaction_dbB);

            //try to commit both transactions
            transaction_dbA.Commit();
            transaction_dbB.Commit();
        }
        catch (Exception ex)
        {
            //If either transactions fails, roll back both
            try
            {
                transaction_dbA.Rollback();
            }
            catch { }

            try
            {
                transaction_dbB.Rollback();
            }
            catch { }

            throw ex;
        }
        finally
        {
            connection_db_a.Close();
            connection_db_b.Close();
        }

    }

}

Is this code considered OK, or will there be scenarios where not all of the transactions will be rolled back if one of them should throw an error?

A: Your code is not OK.  There are scenarios where the two databases will not be consistent.
In your code you are creating two local transactions: one in database A and one in database B.  This isn't what you want since you want both operations to occur within one transaction in order to maintain consistency. To do this you need to use a distributed transaction and, as you mention, TransactionScope is the best way to do this. It will also make the code more readable.
e.g.
Database db_a = DatabaseFactory.CreateDatabase("Data Source=localhost;Initial Catalog=db_a");
Database db_b = DatabaseFactory.CreateDatabase("Data Source=localhost;Initial Catalog=db_b");

using (TransactionScope scope = new TransactionScope())
{
    using (DbConnection connA = db_a.CreateConnection())
    {
        // ...
    }

    using (DbConnection connB = db_b.CreateConnection())
    {
        // ...
    }

    scope.Complete();
}

I realize your code is a simplified scenario so I'm not sure if these apply to your actual code but here are some other comments:
DbCommand dbCmd_dbB_delete =
    db_a.GetSqlStringCommand("Insert INTO Employee(personId) VALUES(" + personID + ")");

Dynamic SQL strings should be avoided.  They are vulnerable to SQL injection attacks and also lower performance since the database execution plan will not be reused for other requests with different parameters.
finally
{
    connection_db_a.Close();
    connection_db_b.Close();
}

You don't need to manually close your connections since you are disposing the connections via your using statements and Close and Dispose are functionally equivalent.