text:
Q: Move the Search Form to center I'm creating a webpage linkedin like with bootstrap-4. I am a beginner.
I'd like to move my form in the navbar to the center. How can I do it?
Here is my webpage:

                    Agora
                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                    </button>

                        Messages(current)

                            Settings

                            Logout

                    <form class="form-inline my-2 my-xlg">
                        <input class="form-control mr-sm-5" type="search" placeholder="Search" aria-label="Search">
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                    </form>

I removed some useless part of the page.

A: Move it before the navbar-nav and use mx-auto...

    Agora
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

    </button>

        <form class="form-inline mx-auto my-2">
            <input class="form-control mr-sm-1" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
        </form>

                Messages(current)

                    Settings

                    Logout

https://www.codeply.com/go/XxoZUwh5C3
Related: Bootstrap NavBar with left, center or right aligned items

A: Thanks to @zim I solved my problem a bit. With the solution that she gaves me I moved also "messages". So I updated a bit my code :

                    Agora
                    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                    </button>

                            Messages(current)

                        <form class="form-inline my-2 mx-auto">
                            <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
                            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
                        </form>

                            Settings

                            Logout

However the answer was really usefull! :)


text:
Q: Where can I see which permission you get with X number of points? I've just reached 1500 points on stackoverflow. Previously I could go to my account and see which permissions I get for each category of points.
But something has changed and now I cannot find this page any more. can anyone help?

A: Here it is:

Just hover the mouse over your own display name on top to open that card and see all the links you can't find anymore. This is global in the whole network, the screenshot from Meta is just an example.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Eclipse plugin develop configurations I am trying to develop an eclipse plugin and my orientor wants me to create a configuration file for the plugin.
She said all i need to put in this configuration file is a little variable and boolean value which i will need to get later: 'showPluginDestroyJavadoc=true'
I have already tried to search google for it, but you all know that plugin development don´t have a lot of info on web. Especially about configuration files
Question is: How do i create a configuration file for my eclipse plugin? I want the plugin to be able to read configuration file before the user does anything using my plugin. How do i do that?

A: Why a configuration file? Eclipse plugins are usually configured through the Eclipse preferences. A tutorial regarding how to add preference functionality to a plugin can be found here.
If your orientor absolutely want you to define the settings by a file, you can still use preferences and set the values throught a plugincustomization file, more info here


text:
Q: Electrical measurements of Chicago substation from where can I get it? I am doing a project on electrical load prediction using machine learning. Machine learning involves creating models based on past data. For creating these models where can I get data regarding electrical measurements of Wider Chicago substation?
If you provide any links it will be very helpful.

A: http://archive.ics.uci.edu/ml/
This is an archive for machine learning datasets..There is not the one which you want but there are datasets of some other Power Substations one in India.

A: You need to contact the electric company that runs whatever substation you want to get data about.  They may have the data to give you.  Otherwise, it's going to be a long and difficult process to convince them to connect your equipment to theirs to allow you to collect the data.  Basically, if they aren't already doing it, then there is no data to have.


text:
Q: Invariants under a transformation Consider a $j=1,\,SU(2)$ representation (or fundamental $SO(3)$ representation).  Suppose that $a_1, b_i, c_i$ with $i=1,2,3$ are vectors transforming under this representation i.e $a_i'=[\rho_1(\alpha)]_{ij}a_j=\rho_{ij}a_j$ and similarly for $b$ and $c$. Consider $$I_1(\vec{a},\vec{b} )=\delta_{im}a_i b_m\,\,\,\,\,\,;\,\,\,\,\,\,\,\,I_2(\vec{a}, \vec{b}, \vec{c} )=\epsilon_{imr}a_i b_m c_r$$
$1)$ Deduce the conditions on $\delta_{im}$ and $\epsilon_{imr}$ for which $I_1$ and $I_2$ are invariants under the transformation.
Attempt: $I_1(\vec{a}', \vec{b}') = a_j b_k (\rho^T \rho)_{jk} = \delta_{jk} a_j b_k$ provided $(\rho^T \rho)_{jk} = \delta_{jk}$.  So is that the condition on $\delta_{ij}?$
Similarly,  $I_2 (\vec{a}', \vec{b}', \vec{c}') = \epsilon_{jkl}\, \det \rho\,a_j b_k c_l$ but how to extract the condition on $\epsilon_{imr}$?
$2)$ Show that these conditions are related to the canonical definition of $SO(3)$: $$SO(3) = \left\{O \in GL(3,\mathbb{R}) : O^TO = \mathbf{1} , \det O = 1\right\}$$
The conditions for $I_1$ and $I_2$ to be invariant are precisely that $\rho^T \rho = \mathbf{1}$ and that $\det \rho = 1$ from $1),$ so that makes me think what I did in $1)$ should been done in $2)$.  If so, what are the conditions sought after in $1)$?
Thanks.


text:
Q: Stateless Bean is null It was working earlier when I was jersey 1.1. But now it says this.userBean is null.
Apart from that there is one warning in the log related com.sun.faces.flow.FlowDiscoveryCDIHelper is deprecated from CDI 1.1!
logs:
08:30:45,161 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-4) WFLYSRV0027: Starting deployment of "ejb2.war" (runtime-name: "ejb2.war")
08:30:45,753 INFO  [org.jboss.weld.deployer] (MSC service thread 1-3) WFLYWELD0003: Processing weld deployment ejb2.war
08:30:45,783 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-3) WFLYEJB0473: JNDI bindings for session bean named 'UserSessionBean' in deployment unit 'deployment "ejb2.war"' are as follows:

        java:global/ejb2/UserSessionBean!com.enovate.assignment.ejb2.UserSessionBeanLocal
        java:app/ejb2/UserSessionBean!com.enovate.assignment.ejb2.UserSessionBeanLocal
        java:module/UserSessionBean!com.enovate.assignment.ejb2.UserSessionBeanLocal
        java:global/ejb2/UserSessionBean
        java:app/ejb2/UserSessionBean
        java:module/UserSessionBean

08:30:45,845 INFO  [io.jaegertracing.internal.JaegerTracer] (MSC service thread 1-3) No shutdown hook registered: Please call close() manually on application shutdown.
08:30:45,999 INFO  [io.smallrye.metrics] (MSC service thread 1-3) MicroProfile: Metrics activated (SmallRye Metrics version: 2.4.2)
08:30:46,008 WARN  [org.jboss.weld.Bootstrap] (MSC service thread 1-3) WELD-000146: BeforeBeanDiscovery.addAnnotatedType(AnnotatedType<?>) used for class com.sun.faces.flow.FlowDiscoveryCDIHelper is deprecated from CDI 1.1!
08:30:46,210 INFO  [javax.enterprise.resource.webcontainer.jsf.config] (ServerService Thread Pool -- 126) Initializing Mojarra 2.3.14.SP01 for context '/ejb2'
08:30:47,353 INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 126) WFLYUT0021: Registered web context: '/ejb2' for server 'default-server'
08:30:47,440 INFO  [org.jboss.as.server] (DeploymentScanner-threads - 2) WFLYSRV0016: Replaced deployment "ejb2.war" with deployment "ejb2.war"
08:30:47,448 INFO  [org.jboss.as.repository] (DeploymentScanner-threads - 2) WFLYDR0002: Content removed from location C:\Users\teoti\Desktop\office\wildfly-21.0.2.Final\standalone\data\content\15\e071e0f42a2e0339da8b4d636a6496c5b1146e\content
08:33:05,177 ERROR [io.undertow.request] (default task-1) UT005023: Exception handling request to /ejb2/webapi/register: javax.servlet.ServletException: java.lang.NullPointerException: Cannot invoke "com.enovate.assignment.ejb2.UserSessionBeanLocal.isUserPresent(String)" because "this.userBean" is null

web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
     see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
    <servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.enovate.assignment.ejb2</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/webapi/*</url-pattern>
    </servlet-mapping>
</web-app>

services:
import javax.ejb.EJB;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("")
public class Service
{
    @EJB
    UserSessionBeanLocal userBean;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("register")
    public Response register(@FormParam("userName") final String name, @FormParam("userPassword") final String pass, @FormParam("userEmail")  String email)
    {
        if (userBean.isUserPresent(email))
            return Response.ok("Email already registered!!").build();
        userBean.addUser(new User(name, email, pass));
        return Response.ok("Registered!!").build();
    }
}

UserSessionBean:
import java.util.ArrayList;

import javax.ejb.Stateless;

@Stateless
public class UserSessionBean implements UserSessionBeanLocal
{
    static ArrayList<User> usersList = new ArrayList<User>();
    static int userCount = 0;
    User u = null;

    public boolean isUserPresent(final String email)
    {
        return usersList.stream().anyMatch(d -> d.getEmail().equals(email));
    }

    public void addUser(User newUser)
    {
        usersList.add(newUser);
        userCount++;
    }
}

User:
public class User
{
    private String name;
    private String password;
    private String email;

    User(final String name, final String email, final String password)
    {
        this.name = name;
        this.email = email;
        this.password = password;
    }

...
}

I thought it would work fine but I don't know how it is null. Maybe is related to CDI warning of log or something related to newer version of jersey or @EJB not working. I also tried adding beans.xml file.
Any help is appreciated

A: The reason was something related to Non-managed bean. And I can not use @EJB to initialize the bean, I have to use Jndi lookup way like this inside function:
@POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("register")
    public Response register(@FormParam("userName") final String name, @FormParam("userPassword") final String pass, @FormParam("userEmail") String email)
    {
        UserSessionBeanLocal userBean = null;
        try
        {
            InitialContext ic = new InitialContext();
            userBean = (UserSessionBeanLocal)ic.lookup("java:global/ejb/UserSessionBean!com.demo.ejb.UserSessionBeanLocal");
        } catch (NamingException e)
        {
            e.printStackTrace();
        }
...

A: If you only want to use @EJB this might work:
I was using jersey in the project and I feels like there is some problem with jersey libraries.

*

*So I deleted all the dependency inside the dependecies below build from the pom.xml and update the project

*Added to javaee-api-8.0.jar file to the classpath

*Clear the everything inside the web-app (everything)

*Added root resource file by extending javax.ws.rs.core.Application like here and it worked


text:
Q: C3P0 configuration in spring/hibernate application? I am using Spring/Hibernate. I configured c3p0 connection pool. After/before getting connection from the pool, it should valildate the connection to verify whether database is up or not. To achieve that, is configuring below property sufficient in spring configuration file ?
testConnectionOnCheckout to true without using preferredTestQuery

other properties that i already configured are as below:
    <prop key="hibernate.c3p0.min_size">5</prop>
            <prop key="hibernate.c3p0.max_size">20</prop>
            <prop key="hibernate.c3p0.timeout">300</prop>
            <prop key="hibernate.c3p0.max_statements">50</prop>
            <prop key="hibernate.c3p0.idle_test_period">3000</prop>
            <prop key="hibernate.jdbc.batch_size">50</prop>

Thanks!


text:
Q: Show two React Component in IF ELSE condition In React App.js i have condition if false then show two component if false show third component but i am not able to pass two component if condition is false
{ !this.state.imageView ?
              (  <OneComponent/> && <TwoComponent/>)
                 : // else
                  <ThridComponent />
              }

A: JSX needs to return a single element, to return multiple elements you need to wrap it in a Fragment, the simplest way is to wrap your elements within <> ... </> tags.
Change the (<OneComponent/> && <TwoComponent/>) to <><OneComponent/>  <TwoComponent/> </> and remove the &&
{ !this.state.imageView ?
    <>  <OneComponent/>  <TwoComponent/></>
    :
    <ThridComponent />
}

A: You need to wrap your two components with a single element.
If you don't need an additional element, such as a <div>, then you can use a fragment for this:
{!this.state.imageView
  ? (
    <>
      <OneComponent/>
      <TwoComponent/>
    </>
  )
  : (
    <ThridComponent />
  )
}

Note, the above <>...</> syntax is shorthand for:
{!this.state.imageView
  ? (
    <React.Fragment>
      <OneComponent/>
      <TwoComponent/>
    </React.Fragment>
  )
  : (
    <ThridComponent />
  )
}

You can read more about fragments here:
https://reactjs.org/docs/fragments.html


text:
Q: WeChat authentication for web I am creating a web app and I have implemented authentication using Facebook, Google. Now I want to authenticate using weChat. I understand I need to use "passport-wechat-auth" but for that I need to create wechat account and that throws me failure each time. SO if anyone have better idea to implement it will be very helpful.

A: Basically you must have a official wechat account to implement. For authentication as like FB etc, you an use WeChat-oauth npm module to do it.
In-Case if you don't have a actual official account. You can use sandbox account for development.Wechat Sandbox


text:
Q: Will enabling the debug shell affect the systemd shutdown sequence? I'm troubleshooting an issue where CentOS stops at "Reached target Shutdown" when I issue a reboot command. In other words the system does not reboot but remains as is after printing the mentioned message.
I've enabled the debug shell using:
systemctl enable debug-shell.service
On reaching the Shutdown target I see that I am still able to access the filesystem using ls, pwd etc. from the debug shell implying that the filesystem was not unmounted. Does this mean the debug shell service has somehow prevented filesystems from unmounting? If so, how do I run a debug shell without circumventing filesystem unmount?

A: In short, yes, having the debug shell around will affect the shutdown process, perhaps preventing systemd from unmounting filesystems in the normal order. But that shouldn't really prevent systemd from eventually being able to unmount them before rebooting.
systemd tries really hard to unmount everything while stopping units normally, but then once everything is down that should be down, it will go on a killing spree, terminating all processes that are still up (and that includes the debug shell) and then it will try to unmount everything that is still mounted.
If you think the debug shell might be causing issues that are interfering with your troubleshooting of your other issue, see Diagnosing Shutdown Problems for alternative techniques that might help you debug the problem, without some of the side effects of the debug shell.


text:
Q: How to select and each in Xml child element? I want to use jQuery.each() method on XML child elements.
Below is my code.
$(function() {
    var xml = "<approvalcontent><vac_applier>Name</vac_applier><vac_sdate>2017-02-03</vac_sdate><vac_edate>2017-02-10</vac_edate><vac_reason>kind</vac_reason></approvalcontent>";
    bindContent(xml);
});

function bindContent(xml) {
    $(xml).find("approvalcontent").children().each(function(){
        alert("here!");
    });
}

But this each function shows anything.
I want to roof as much as Xml  elements.
How can I solve it?

A: jQuery's find() only works for descendants, your <approvalcontent> element is a root element, so what you wanted was probably filter() instead
$(xml).filter("approvalcontent")...

You should however be parsing the XML before accessing it, as that would give you an actual valid XML document to work with, and you could use find()
function bindContent(xml) {
    var parsed = $.parseXML(xml);
    $(parsed).find("approvalcontent").children().each(function() {
        alert("here!");
    });
}

A: Just use $(xml).children()

$(function() {
  var xml = "<approvalcontent><vac_applier>Name</vac_applier><vac_sdate>2017-02-03</vac_sdate><vac_edate>2017-02-10</vac_edate><vac_reason>kind</vac_reason></approvalcontent>";
  bindContent(xml);
});

function bindContent(xml) {
  $(xml).children().each(function() {
    console.log("here!");
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You need to use .filter() instead of .find() as approvalcontent is at top level.

$(function() {
  var xml = "<approvalcontent><vac_applier>Name</vac_applier><vac_sdate>2017-02-03</vac_sdate><vac_edate>2017-02-10</vac_edate><vac_reason>kind</vac_reason></approvalcontent>";
  bindContent(xml);
});

function bindContent(xml) {
  $(xml).filter("approvalcontent").children().each(function() {
    alert("here!");
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: Iterations While loop syntax error I'm trying to create an iteration program. What I want it to do is:
n=5429 9542-2459=7083 n=7083 8730-0378=8352 n=8352 8532-2358 =6174 n=6174 7641−1467=6174
When i enter my code (below), idle responds  with

SyntaxError: expected an indented block

Code:
number=input("enter your 4 digits number:")
print("your number is",number)
KAPREKAR_NUMBER="6174"
i=0
while number!=KAPREKAR_NUMBER:
large="".join(sorted(number, reverse=True))
small="".join(sorted(number))
number=str(int(large)-int(small))
i+=1
if number==KAPREKAR_TAL:
print("it took ",i," iterations to solve the kaprekar aligoritm.)

A: Can you please check your tabs (4 spaces) in your editor.Python understands code blocks by looking at indentations.

A: I've guessed at some of what you're trying to do and the following version gets rid of a few different syntax errors, including two indentation errors, and one string literal error (no closing quote).
The first error you'd encountered was due to bad intenting.  Python is very strict on indenting.  It uses indent levels to define code blocks.
number=input("enter your 4 digits number:")
print("your number is",number)
KAPREKAR_NUMBER="6174"
i=0
while number!=KAPREKAR_NUMBER:
    large="".join(sorted(number, reverse=True))
    small="".join(sorted(number))
    number=str(int(large)-int(small))
    i+=1

if number==KAPREKAR_NUMBER:
    print("it took ",i," iterations to solve the kaprekar aligoritm.")

By the way, the last if here is redundant.  It could be deleted (and just keep the print), but I've included it in order to be true to the original code.


text:
Q: DBML changes & source control I'm having some issues with the DBML. Every time the team needs to synchronize changes into SVN, the DBML is changed which generates lots of conflicts. This seems to be related to some rearrangement in the dbml editor, because most of the associationConnector sections in the .dmbl.layout seem to change during development if you open the dbml file in the editor.
Do you have any best practices to avoid these layout rearrangements that can easily take more than one hour to fix?
Best regards,
Gustavo

A: If it is just the .layout being changed then I would actually ignore the request since the GUID's which link everything up will still match. They just won't be in the same place as I set them, something I could live with. If the .dbml changed as well, then I would accept both without merging.

A: If you willing to use KDiff3, then you can configure a pre-processor command to sort the dbml file before merging. I've posted a guide on my blog at http://blog.trumpi.co.za/the-one-tip-that-i-wish-i-knew-years-ago-that-merges-easier/. The instructions are for git, but I know that TortoiseSVN can be configured in a similar way to route dbml merging to KDiff3.


text:
Q: Как составить select запрос чтобы найти общие теги фильмов и сериалов? У меня есть 3 таблицы: Фильмы, Теги, Теги_Записи
create table movies (
    id int unsigned not null auto_increment,
    title varchar(255),
    type int unsigned not null default 1,
    primary key(id)
);

В таблице movies, поле type может иметь значения 0 для сериалов и 1 для фильмов.
create table tags (
    id int unsigned not null auto_increment,
    name varchar(255),
    primary key(id)
);

create table tags_items (
    tag_id int unsigned not null,
    movie_id int unsigned not null
);

Подробнее: http://sqlfiddle.com/#!9/b5e3d2/6
Когда я хочу узнать, сколько тегов у меня к фильмам или сериалам я делаю запрос:
select ti.* from tags_items ti
  join movies m on m.id = ti.movie_id
    where m.type = 1
      group by tag_id

Как мне можно сделать запрос, чтобы найти общие теги и для фильмов и для сериалов? Мои попытки сравнивать таблицу tags_items с самой собой не привели к успеху.

A: Если я правильно понял то вам нужно выбрать tags где айдишники равны айдишникам из tags_items которые в свою очередь содержаться в фильмах и сериалах
Не совсем аккуратно но отображает описанное выше
SELECT DISTINCT t.* FROM tags_items ti, tags t
    where t.id in(SELECT DISTINCT tag_id FROM tags_items
          where tag_id in (
            SELECT ti.tag_id FROM tags_items ti, movies m
            where ti.movie_id = m.id and m.type = 1
          )
          and tag_id in (
            SELECT ti.tag_id FROM tags_items ti, movies m
            where ti.movie_id = m.id and m.type = 0
          )
     );

sqlfiddle


text:
Q: Disable price & Add to cart button for particular category I want to disable the price and add to cart button for particular product or a category. Instead I need to place a button that takes me to a web form page. Is there any extension that provides this functionality? Or any code tweaks?

A: You can refer this
How to disable "Add to Cart" on specific products, and instead display "View Details" button in category list view?
To disable price and add to cart buttons on specific products.


text:
Q: Button click show den div hide prev div like slider Hello I want to create something like slider when I click a button show the next div and hide the prev div with 3 divs.
HTML:

1

 2

 3

jQuery:
$(document).ready(function () {
    $(".fa-chevron-right").click(function (e) {});
    $(".fa-chevron-left").click(function (e) {});
});

A: You can accomplish it with ease using jQuery's next(), prev() and siblings() methods. I spend five minutes writing some rough code.
http://jsfiddle.net/85kcffo9/1/
Hope it helps in you journey to learn jQuery.

A:

   left
   right

1

 2

 3


text:
Q: Is there a quality difference between output of AVCaptureMovieFileOutput and AVCaptureVideoDataOutput? In the process of capturing a light trail photo, I noticed that for fast moving objects, there is slightly more discontinuity between successive frames if I use the sample buffers from AVCaptureVideoDataOutput compared to if I record a movie and extract frames and run the same algo.
Is there a refresh rate/frame rate difference if the two modes are used?
A colleague who has experience in professional photography claims that there is a visible lag even in Apple's default camera app when comparing the preview in Photo mode and Video mode but it is not something very obvious to me.
Furthermore, I am actually capturing video at a low frame rate (close to highest exposure)
To conclude these experiments, I need to know if there is any definitive proof to confirm or disprove the same


text:
Q: Grails. How to send a request to my DB too see changes How can i send a request to my DB, mySql, then check if there are changes so that i can refresh a div if there are changes?
-EDIT-
This is my code. It just auto refreshes the load function every 5s so that it will apply new  changes to the table. I dont know how to send a request to my DB to see changes.
<div id="updateThis">
    Loading........
</div>

<script type="text/javascript">
    $(function refresh(){
        setInterval(function(){refresh()},5000);
        $('#updateThis').load('${createLink(controller:'table', action:'loadTables')}');

    });
</script>

A: A lot depends on the size of your system.
'Enterprise' - look at Flexviews and/or LinkedIn's Data Bus.  If neither of those work for you, you should probably look for topics/tools related to Data Warehouse ETL with MySQL, since a large portion of the ETL process is determine efficient ways to extract changed data.  For instance, you could look at JasperSoft ETL Pro or Talend Open Studio which has a number of tools to build a custom ETL process.
'Basic' - look at either adding timestamps to the tables in question and then querying for records with a timestamp value greater than the last time you checked (downside: no record of deletes) or add triggers to the database that record changes in data.
Also, if this system is large, you may want to look at pushing the changes via websockets or the like since polling every 5 seconds for changes is not going to scale well.  There are a number of articles and Grails plugins (Atmosphere and Events Push to name a couple) on the topic.


text:
Q: How to use IN prepared statement with single variable in typeorm I have a .sql file containing a query such as
SELECT * WHERE id IN ($1)

The sql query is read and passed into a typeorm query with an array of parameters.
const result = await this.entityManager.query(myQuery, parameters);

I would like to have parameters be an array with a single value that would be a string concatenation of all the ids I want to find.
This would allow me to use my sql file no matter the number of ids I want to filter by.
I have tried formatting parameters in such a way that I can have $1 only no matter the number of items in my array:
const ids = ['1', '2', '3'];

const parameters = [ids.join("', '")];

or
const parameters = ["'" + ids.join("', '") + "'"];

etc
I have not found a syntax that works.
Is this feasible somehow ?

A: I have replaced the IN ($1) by  = ANY($1) and am now passing the ids as an array. This works as I intend.
SELECT * WHERE id = ANY($1);

const ids = ['1', '2', '3'];
const result = await this.entityManager.query(myQuery, [ids]);


text:
Q: How to get RSS feed for custom field in post I have a list of post with different category, I am able to generate feed for a particular category,
But  I am trying to create a new custom field in post with the option selection box, If the particluar post is get selected with my custom field then the Feed need to generate based on the selection of custom field on that particular post
For Example : I am trying like this :  http://mydominain.com
/?post_type=post=customfield=rss_feed

A: Finally I find solution to hide that particular category which is showed in front end,
I use this code to hide the selected category front end : Function.php
add_filter('get_the_terms', 'hide_categories_terms', 10, 3);

function hide_categories_terms($terms, $post_id, $taxonomy){
// list of category slug to exclude,
$exclude = array('computer');

if (!is_admin()) {
    foreach($terms as $key => $term){
        if($term->taxonomy == "category"){
            if(in_array($term->slug, $exclude)) unset($terms[$key]);
        }
    }

But any answer for how to get RSS feed by using custome field will be more appreciated .


text:
Q: How many such numbers are there?
Using only the digits $2$, $3$ and $9$, how many six digit numbers can be
  formed which are divisible by $6$?

My attempt :
To be divisible by $6$, the number has to be divisible by $2$ and $3$. Thus, the one's digit has to be $2$ only. Now we need to arrange $2$, $3$, $9$ in the left  over five digits' places such that their sum is $3z-2$, where $z \in \mathbb{Z}^+$. But I am not able to proceed further. Can someone help?

A: As you pointed it, the unit number has to be a two.
As the digits $3$ and $9$ contribute to $0$ for the sum of the digits modulo $3$, the number of two's has to be a multiple of $3$.

*

*$6$ two's : only one possible number;

*$3$ two's : you have to choose the positions of the $2$ two's other than the unit number, you have $\binom{5}{2}$ ways to do this; then you are left with $3$ places where you can put a $3$ or a $9$, so you have $2^3$ ways to do this; so the number of possibilities is
$$\binom52\times2^3=80$$

So the total number of numbers you can form is $81$.

A: Suppose that there are $k$ twos, $m$ threes and $n$ nines
The remaining five digits must sum to $3z-2$ as you said. Therefore $2k+3m+9n=3z-2$
Of course all the threes and nines make up part of the $3z$ in the equation. We can simplify things by letting $z=r+m+3n$. Then the equation is
$2k+3m+9n=3(r+m+3n)-2$
This simplifies to
$2k = 3r-2$
We can see that $2k+2$ must be a multiple of three. Examine all cases $1 \leq k \leq 5$, we can see that this only happens when $k=2$ and $k=5$
Now you know the limited cases for $k$ which you must consider. Can you finish this and find how many combinations of threes and nines there are for each value of $k$?

A: You can use here divisibility rule of 6. For divisible by 6 we have number to be divisible by 2 and 3 both.
For divisible by 2 last digit should be 2. So only 1 way to arrange last digit.
Here some things to notice -
If number of 2's = 1 or 2 or 4 or 5 included last 2 then number formed not divisible by 6.
So we have left with only 2 cases.
Case 1- We have three 2's.
Last digit 2. Then to fill two 2's at any 2 places and at remaining 3 places we have 2 options(3,9) for each place.
$\binom{5}{2} \times 2 \times 2 \times 2 = 80$
Case 2- We have all 6-digits as 2.
Then only 1 way.
Total ways = 80 + 1 = 81


text:
Q: Linguagem C : "fseek.c: No such file or directory" fazendo um Unix Tac Pessoal estou tentando fazer um desafio de programação esse aqui. Não é um desafio muito díficil porém meu script não tem o comportamento esperado, em arquivos pequenos funciona porém em arquivos maiores como de 1GB eu recebo segmentation fault Analizando com o gdb o erro é esse:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7e55cb0 in __GI_fseek (fp=0x555555559220,
    offset=900935887, whence=0) at fseek.c:35
35      fseek.c: No such file or directory.

Muitos vão ler e dizer "O fseek não encontra o diretorio ou o arquivo" Porém esse script funciona com arquivos pequenos encontra, talvez perdeu o caminho durante o processo.
Meu código é este:
#include <stdio.h>
#include <stdlib.h>

//O programa deve ler arquivos de qualquer tamanho e funcionar com um limite de
//512MB de memória (ler o arquivo inteiro em memória não é uma alternativa
//viável).

void reversePrint(char *sentence) {
  long long i = 0;

  while(sentence[i] != '\0') {
    i++;
  }
  if((i> 0) && sentence[i-1] == '\n') {
    i -= 2;
    for(; i >= 0; i--) {
      putchar(sentence[i]);
    }
    puts("");
  }else {
    for(; i >= 0; i--) {
      putchar(sentence[i]);
    }
    puts("");
  }

}
int main(int argc, char** argv) {

  FILE *file;
  char ch;

  if( ! *++argv){
    fputs("Usage: tac <file>\n",stderr);
    exit(EXIT_FAILURE);
  }

  if((file = fopen(*argv, "r")) == NULL) {
    perror("error openig file");
    exit(EXIT_FAILURE);
  }

  fseek(file, 0, SEEK_END);

  long size;

  size = ftell(file);

  char bufferLine[10000];

  long j = 0;

  for ( size -=2 ; size >= 0; size--) {

      fseek(file, size, SEEK_SET);

      if(ferror(file)) {
        perror("seek error");
        exit(EXIT_FAILURE);
      }

      bufferLine[j] = getc(file);

      if((bufferLine[j] == '\n') || size == 0) {

          bufferLine[j+1] = '\0';
          reversePrint(bufferLine);
          j = -1;
      }
      j++;
  }

  fclose(file);
  return 0;
}

Para poder testar com o arquivo grande no qual me referi este é o link de download
Quero muito saber por que estou recebendo esse erro.

A: Bem havia 3 erros no meu código o principal.
1º Erro:
char bufferLine[10000];

Pode haver linhas que possuem mais de 10 mil bytes antes do proximo \n
2º erro:
O comportamento do ftell para stream de texto é indefinido
3º :
A função reversePrint estava imprimindo bytes nulos.


text:
Q: Can I use "be productive with something" as in "be successful at something"? I am trying to phrase the value proposition for my productivity app, which aims to help people get going with activities they easily give up on. At the moment it reads like this:

Thank you for installing %appname%.
  We hope it helps you to get more productive with the things you want to do.

It felt wrong (I wasn't sure whether to use productive with something or productive at something), so I checked Google and a few dictionaries only to find no evidence of using productive with an object (except phrases like "be productive at home/work"). So I wonder if it's an appropriate use at all.
I would rephrase it with "get [more] successful at the things you want to do", but this feels like a promise too strong: the fact that the user gets more engaged with the activity doesn't guarantee they find success at it. And I'd avoid the word 'engaged' as being too formal.

A: You say your app is designed to "help people get going with activities they easily give up on." I take this to mean your app is designed to increase the likelihood they will (with your app's help, of course) bring more projects to completion, and decrease the likelihood of starting a project but not completing it.
I would therefore word your value proposition as follows:

Thank you for installing %appname%. We designed it specifically to help you bring more and more projects to completion, thus saving you time and boosting your productivity.

You then need to spell out specifically the ways in which your app will make this happen. First, however, I recommend you come up with a list of factors which tend to sidetrack a person who starts a project but does not finish it. Then answer the question "How will our app address these factors, making them less formidable and easier to deal with?"
Best wishes to you!

A: I suggest you use "productive with the things". It sounds better than "productive at the things". Based on what you found on google: "be productive at home/work" the 'at' refers to a place and not 'with something'. So you should use 'at' when referring to a place and 'with' when referring to things.


text:
Q: int main(void) giving error Hello programming world.
I am currently doing my first programming course at university and our instructor said the function
int main (); //without the curly braces// is valid.

I may have misheard him/misinterpreted him, as when I try and run a console with that, it gives an error. But when I do int main() {}; it runs fine.
So:
1. Are the curly braces needed regardless of the content in the body?

*

*How did the function run without the return 0.

*Using this, what is the shortest possible int main / void main function possible?
as requested, here is the error:
Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thank you so much :)

A: In C++, there are two correct definitions for main:
int main() {
    // ...
}

and
 int main(int argc, char *argv[]) {
     // ...
 }

or equivalent. (Other implementation-defined forms are possible, but we can ignore those. And the return type is always int, at least for hosted implementations; void main() is wrong.)
The braces { and } are part of the syntax of a function definition; they're not optional.
You can provide a declaration for main, such as
int main();

but there's no real point in doing so. That's a declaration, not a definition -- and you still need to have a definition somewhere.
A return 0; at the end is not required. This is a special case that applies only to main, not to other functions: if execution reaches the closing }, it does an implicit return 0;.
The shortest legal program would probably be:
int main(){}

A: Thats the difference between a function definition and declaration (see What is the difference between a definition and a declaration?
Basically int main(); is a prototype telling the compiler that you will have a function called main, which returns an int, but you do not implement it yet.
the int main() {} is the implementation of the function, thus the curly braces, giving it a function body and full implementation.

A: I'd like to clarify a few things.
int main();

is a function declaration, i.e. it lets other functions / classes know about it.
However, it does not define main, meaning it says nothing about what main actually does.
Since every C++ program must define main, as it is run first, your compiler will definitely give a compile error.
By writing
int main() {}

You are defining main by specifying that main does nothing, so it will run.
Finally, C++ compilers will implicitly add a return 0; statement if you do not return anything, as it is an indicator to the operating system that the program ran successfully.
For more information, see https://stackoverflow.com/a/204483/2512775 on what main should return.

A: Your error code means that you have not declared the main() function properly. What you should do is add the curly braces to signify the block of code that your application will run in.
Although the compiler will add a return statement if it isn't given one, just add one to make sure.


text:
Q: Mahalanobis distance with 0 variance I'm developing a clustering algorithm, I'm using the Mahalanobis distance to decide if a point must be included in a cluster or not.
A cluster is represented by the statistics of the points that are included in it, the statistics are:

*

*the sum of the components of all the points in each dimension named SUMi;

*the sum of the squares of the components of all the points in each dimension, named SUMQi.

Choosing these statistics, the centroid's coordinate in the ith dimension is the SUMi/N, where N is the number of points in the cluster. Talking about the variance, I should compute the variance in the ith dimension as SUMSQi/N − (SUMi/N)^2.
To initialize clusters I choose k random point in the dataset, where k is a priori known number of clusters, in this way I have k clusters, each represented by the statistics of 1 point, this means that SUMSQi/N = (SUMi/N)^2 and thus variance is 0, so I can't compute Mahalanobis distance because it need to divide by the variance of the cluster and in this case, it is 0.
Which is the correct approach to this problem? And since I'm working with d-dimensional points how should I choose the threshold to discriminate if a point should be added to a cluster? Is using the module or the mean of the element of the variance vector a good idea?
The clusters are represtend by (2*d) + 1 elements: the first is the number of points in the cluster, from the second to the d-th element there are the SUMi, from the d-th to the (2*d)-th there are the SUMQi.
This is the function I implemented in C to compute variance of a cluster and Mahalanobis distance of a point from the cluster:
double mahalanobis(double *cluster, double *point, int dimension) {

    double* std_dev = malloc(dimension * sizeof(double ));

    /**
     * variance of the cluster
     */

    for (int i = 0; i < dimension; ++i) {
        std_dev[i] = cluster[i + dimension + 1]/cluster[0] - pow(cluster[i + 1]/cluster[0], 2);
    }

    /**
     * mahalanobis distance
     */

    double sum = 0;
    for (int i = 0; i < dimension; ++i) {
        sum += pow(point[i] - ((cluster[i+1] + point[i])/(cluster[0] + 1)), 2)/std_dev[i];
    }

    free(std_dev);

    return sqrt(sum);
}


text:
Q: inputbox seperation css different in ff and chrome this thing has irritated me a lot . ive used a html reset css code and added my simple code of 2 different inputboxes one below other , the total spacing in chrome  and ff,ie are different.
chrome has a bit wider space whereas ff and ie have 0 space between the input boxes.
here's the rendering of it
http://jsfiddle.net/LLsyw/
here's the html part of it

<input type='text' />

<input type='text' class='second' placeholder='data'/>

and here's the css
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    outline:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

body {
    line-height:1;
}

article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
    display:block;
}

nav ul {
    list-style:none;
}

blockquote, q {
    quotes:none;
}

blockquote:before, blockquote:after,
q:before, q:after {
    content:'';
    content:none;
}

a {
    margin:0;
    padding:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

/* change colours to suit your needs */
ins {
    background-color:#ff9;
    color:#000;
    text-decoration:none;
}

/* change colours to suit your needs */
mark {
    background-color:#ff9;
    color:#000;
    font-style:italic;
    font-weight:bold;
}

del {
    text-decoration: line-through;
}

abbr[title], dfn[title] {
    border-bottom:1px dotted;
    cursor:help;
}

table {
    border-collapse:collapse;
    border-spacing:0;
}

/* change border colour to suit your needs */
hr {
    display:block;
    height:1px;
    border:0;
    border-top:1px solid #cccccc;
    margin:1em 0;
    padding:0;
}

input, select {
    vertical-align:middle;
}

could someone plz point me in the right direction.

A: Explicitly give your inputs their own margin. The css reset code doesn't even address the input elements. if you really want to reset everything why not do this:
* {
margin:0;
padding:0;
border:0;
outline:0;
font-size:100%;
vertical-align:baseline;
background:transparent;
}

By using an incomplete list in the reset, browsers are left to choose their own defaults for the unlisted elements.

A: use specific Css reset for the input element:input {margin:0;padding:0;display:block;}


text:
Q: iPhone Application Exit when scrolling the UITableView I have declared a NSMutableArray and I populated it with information from the database. The table displays information well. But when I scroll down, the application exits. Seems like its loosing the pointer to the array.
Here is the code for declaration of the array:
@interface RootViewController : UITableViewController <CLLocationManagerDelegate> {
 sqlite3 *database;

 NSMutableArray *storeList;
 CLLocationManager *locationManager;
 CLLocation *startingPoint;

}

@property (nonatomic, retain) NSMutableArray *storeList;
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, retain) CLLocation *startingPoint;

- (void) createCopyOfDatabaseIfNeeded;
- (void) initializeStoreList;
- (void) getDistanceFromUserLocation;

Here I am initializing the array with object of type StoreInfo:
- (void) initializeStoreList{
 self.storeList = [[NSMutableArray alloc] init];

 //database is stored in the application bundle.
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *dbPath = [documentsDirectory stringByAppendingPathComponent:kFileName];

 if (sqlite3_open([dbPath UTF8String], &database)== SQLITE_OK) {
  const char *sql = "select id, storename, ratings, lattitude, longitude from storeinformation";
  sqlite3_stmt *statement;

  if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
   while (sqlite3_step(statement) == SQLITE_ROW) {
    NSInteger *_pk = (NSInteger *) sqlite3_column_int(statement, 0);
    NSString *_storeName =  [NSString stringWithUTF8String:(char*) sqlite3_column_text(statement, 1)];
    NSString *_ratings = [NSString stringWithUTF8String:(char*) sqlite3_column_text(statement, 2)];
    double _lattitude = [[NSString stringWithUTF8String:(char*) sqlite3_column_text(statement, 3)] doubleValue];
    double _longitude = [[NSString stringWithUTF8String:(char*) sqlite3_column_text(statement, 4)] doubleValue];

    StoreInfo *si = [[StoreInfo alloc] initWithBasicInformation:_pk storeName:_storeName ratings:_ratings lattitude:_lattitude longitude:_longitude];
    [self.storeList addObject:si];
    [si release];

   }
  }

  sqlite3_finalize(statement);
 } else {
  sqlite3_close(database);
  NSAssert1(0,@"Failed to open the database with message '%s'.", sqlite3_errmsg(database));
 }

}

here is the constructor for StoreInfo object
-(id)initWithBasicInformation:(NSInteger *)_pk storeName:(NSString *) _storeName ratings:(NSString *) _ratings lattitude:(double) _lattitude longitude:(double) _longitude;
{
     if (self = [super init]) {
  self.primaryKey = _pk;
  self.storeName = _storeName;
  self.ratings = _ratings;
  self.lattitude = _lattitude;
  self.longitude = _longitude;
 }
 return self;
}

Here is the code for displaying the cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

 // Configure the cell.
 StoreInfo *si = (StoreInfo *)[self.storeList objectAtIndex:indexPath.row];
 cell.textLabel.text = si.storeName;
    return cell;
}

The table displays alright first. But when I scroll down, this even gets fired and somehow it is not able to find reference to the si.storeName.
I have spent hours trying to debug the issue. Any help is greatly appreciated.

A: First of all, how have you defined the property for the problematic field?
Is it retain?
Secondly, Can you access any other property in si?
And finally, I see that there is a memory leak in self.storeList = [[NSMutableArray alloc] init]; - the object is retained twice (in init and in the property setter)...


text:
Q: Android listview, swipe to action I have listview with some text. I want to show images on swipe action (almost like in gmail app). For example, if I  swipe from left to right - my list item is moving right, and image is sliding from the left. My list item can move right no more than image width. After swipe stops, list item is moving to start position. How could I make such thing?

A: check out this.
There you can see the listview swipe to the right to show the views.
Snap:

main_activity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:swipe="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

   <com.fortysevendeg.swipelistview.SwipeListView
            android:id="@+id/example_swipe_lv_list"
            android:listSelector="#00000000"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            swipe:swipeFrontView="@+id/front"
            swipe:swipeBackView="@+id/back"
            swipe:swipeDrawableChecked="@drawable/choice_selected"
            swipe:swipeDrawableUnchecked="@drawable/choice_unselected"
            swipe:swipeCloseAllItemsWhenMoveList="true"
            swipe:swipeMode="both"
            />

</LinearLayout>

A: you can use onFling() event of gesturedetector. it will give you the motionevent points and touch velocity points using that you can identify the gesture and can load a view using animations like left to right and right to left.

A: I couldn't find any library that does just that but it's not hard to make it by yourself. As Nick pointed out pay a look at android-swipetodismiss, look at SwipeDismissListViewTouchListener.java.
First, you have to create a custom View for you ListView's child. You will need an ImageView which is overlapped by another View that contains the text.
Then, you add an onTouch() listener to your ListView. On MotionEvent.ACTION_DOWN (when you start the gesture) you take the touch coordinates and calculate which child in the ListView you are touching, for example:
        int[] listViewCoords = new int[2];
        mListView.getLocationOnScreen(listViewCoords);
        int x = (int) motionEvent.getRawX() - listViewCoords[0];
        int y = (int) motionEvent.getRawY() - listViewCoords[1];
        View child;
        for (int i = 0; i < childCount; i++) {
            child = mListView.getChildAt(i);
            child.getHitRect(rect);
            if (rect.contains(x, y)) {
                mDownView = child;
                break;
            }
        }

On MotionEvent.ACTION_MOVE you measure the difference in X coordinates between the point you touched in MotionEvent.ACTION_DOWN and the current coordinate:
float deltaX = motionEvent.getRawX() - mDownX;

So then you have translate the View that contains the text so the ImageView is revealed:
mDownView.setTranslationX(deltaX);

When you lift your finger you just set mDownView .setTranslationX(0) and the image is covered again. This is just a guide, there are some details that are not covered but you should be able to start with this.


text:
Q: Python reverse iteration to split a word I need to split my words from my punctuation-
I'm thinking about having the function look at each word and determining if there is a punctuation mark in it by starting at [-1], index of -1, and then splitting the word from the punctuation as soon as it hits a letter and not a punctuation mark...
sent=['I', 'went', 'to', 'the', 'best', 'movie!','Do','you', 'want', 'to', 'see', 'it', 'again!?!']
import string
def revF(List):
    for word in List:
        for ch in word[::-1]:
            if ch is string.punctuation:
                 #go to next character and check if it's punctuation
                newList= #then split the word between the last letter and first puctuation mark
    return newList

A: If all you want is to remove punctuation from a string. Python provides much better ways of doing this -
>>> import string
>>> line
'I went to the best movie! Do you want to see it again!?!'
>>> line.translate(None, string.punctuation)
'I went to the best movie Do you want to see it again'

A: From your example, I gather that you want to split your string on a space. You can do this quite simply like this:
my_str = "I went to the best movie! Do you want to see it again!?!"
sent   = my_str.split(' ')

A: Use a regexp containing the punctuation you want to split on:
re.split('re.split(r"[!?.]", text)

Demonstration:
>>> import re
>>> re.split(r"[!?.]", 'bra det. där du! som du gjorde?')
['bra det', ' d\xc3\xa4r du', ' som du gjorde', '']


text:
Q: In AS3, why do mouse events seem to skip "root" and go to "stage"? Run the following code, once with block.mouseEnabled = true, and again with block.mouseEnabled = false, clicking the block once during each run.
var block:Sprite = new Sprite();
block.name = "block";
with(block.graphics){beginFill(0x000000,1);moveTo(0,0);lineTo(100,0);lineTo(100,100);lineTo(0,100);lineTo(0,0);endFill();}
block.mouseEnabled = true; //change to false to see how event target skips root
addChild(block)
stage.addEventListener( MouseEvent.MOUSE_DOWN, mouse_down, false, 0, true );
function mouse_down( e:MouseEvent ):void{trace( e.target );}

Why is "root" skipped as a target?  Is this by design?   What is or what might be the design reason for this anomaly?
I ask this because it's a clear a break from the normal pattern where when the child object has mouseEnabled set to false, the parent becomes the target when it's child area is clicked.
It may be that the root is simply a non-participant endpoint in the event capture/target/bubbling rount-trip, and anything that reaches it gets applied to stage instead of root.

A: Any strokes and vector-fills on graphics are not interactive and cant catch interactive events. U can use graphics.beginBitmapFill method or add Bitmap (or any other) as child into.


text:
Q: Smooth scroll with navbar fixed top i have a little question. I use smooth-scroll,its perfect... but when i use a navbar fixed top?
My problem is when i click on link the anchor div its under the navbar. The navbar have height 154px and the code are simplyfy to this:

    Anchor 1
    Anchor 2

...

...

how can I lower my anchor anchor point?

A: I use this code for smooth scrolling:
$(document).ready(function () {
     $('a[href^="#"]').on('click', function (e) {
         e.preventDefault();

         var target = this.hash,
             $target = $(target);

         $('html, body').stop().animate({
             'scrollTop': $target.offset().top - 80
         }, 900, 'swing', function () {
             window.location.hash = target;
         });
     });
 });

fund on http://www.paulund.co.uk/smooth-scroll-to-internal-links-with-jquery .
If you change the $target.offset().top - 80 with the height of your navbar you do the trick.

A: The code below works fine for me. No jquery, pure JS using scrollby.
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            var node = document.querySelector(this.getAttribute('href'));
            let item = node;
            //this is the parent container, overflow wrapper
            let wrapper = document.querySelector('#wr-page');
            let count = item.offsetTop - wrapper.scrollTop ;
            wrapper.scrollBy({top: count, left: 0, behavior: 'smooth'})
        });
    });


text:
Q: Health Endpoint Metrics not being exported after Spring Boot 2 migration My Team migrated our Microservices from Spring Boot 1 to Version 2 and since the Actuator changed, our Health Endpoint Metrics exported via prometheus jmx exporter do not work anymore.
The usual /actuator/health is working as expected, but the prometheus-jmx-exporter won't pick it up although several things tried:

*

*I changed the Metainformation in the exporter-config.yaml to reflect the name change in Spring Boot 2

*I added the io.micrometer:micrometer-registry-prometheus to our build.gradle to see if this is the issue

*I exposed web and jmx endpoints acording to the Spring Boot 2 Documentation

So now I run out of ideas and would appreciate any hints oyu might be able to give me
old prometheus-jmx-exporter exporter-config.yaml:
---
lowercaseOutputName: true
lowercaseOutputLabelNames: true
whitelistObjectNames: ["org.springframework.boot:type=Endpoint,name=healthEndpoint"]
rules:
- pattern: 'org.springframework.boot<type=Endpoint, name=healthEndpoint><(.*, )?(.*)>(.*):'
  name: health_endpoint_$1$3
  attrNameSnakeCase: true

new prometheus-jmx-exporter exporter-config.yaml:
---
lowercaseOutputName: true
lowercaseOutputLabelNames: true
whitelistObjectNames: ["org.springframework.boot:type=Endpoint,name=Health"]
rules:
- pattern: 'org.springframework.boot<type=Endpoint, name=Health>'
  name: health_endpoint_$1$3
  attrNameSnakeCase: true

current application properties about actuator endpoints:
management.endpoints.web.exposure.include=info, health, refresh, metrics, prometheus
management.endpoints.jmx.exposure.include=health, metrics, prometheus

in Spring Boot 1 with the old exporter-config.yaml I get results like this:
# HELP health_endpoint_hystrix_status Invoke the underlying endpoint (org.springframework.boot<type=Endpoint, name=healthEndpoint><hystrix, status>status)
# TYPE health_endpoint_hystrix_status untyped
health_endpoint_hystrix_status 1.0
# HELP health_endpoint_status Invoke the underlying endpoint (org.springframework.boot<type=Endpoint, name=healthEndpoint><status>status)
# TYPE health_endpoint_status untyped
health_endpoint_status 1.0

But with all the changes and in Spring Boot 2 I get nothing out of this.

A: You can cofigure your own health value and add it to the Prometheus Metrics endpoint:
@Configuration
public class HealthMetricsConfiguration {

    @Bean
    public MeterRegistryCustomizer prometheusHealthCheck(HealthEndpoint healthEndpoint) {
        return registry -> registry.gauge("health", healthEndpoint, HealthMetricsConfiguration::healthToCode);
    }

    public static int healthToCode(HealthEndpoint ep) {
        Status status = ep.health().getStatus();

        return status.equals(Status.UP) ? 1 : 0;
    }
}


text:
Q: AngularJS doesn't work with yii2 I'm trying to get simple Hello World from yii2 layout.
AppAsset.php:
...
    public $js = [
       'js/angular.min.js',
    ];
...

layout/main.php:
...
<html lang="<?= Yii::$app->language ?>" ng-app="app">
...
<body ng-contoller="ctrl">
...
    <div class="container">
        {{hello}}
...
<?php $this->endBody() ?>
<?=Html::jsFile('@web/js/app.js')?>
</body>
...

/js/app.js
angular.module('app', [])
       .controller('ctrl', function($scope){
            $scope.hello = 'Hello World!';
            console.log('inside ctrl');
    });

console.log('outside ctrl');

'outside ctrl' works fine. but block 'inside ctrl' doesn't.
Page not shows anything about {{hello}}.
Where I missed?

A: Why are you loading the app js outside the AppAsset? Should be there too in order to work.
If you dont want to do that at lest load de app js above the endbody function.

A: You need to just include your app.js file in AppAsset.php like as
public $js = [
    'js/angular.min.js',
    'js/app.js',
];

its working for me.


text:
Q: R - query position of the graphics/plot window Is it possible to ask a plot window for its position in R?
I'm doing some plotting whereby a number of windows get successively opened, and it would be useful if these appeared at the same position and with the same size as previous graph windows for quick comparison.
I can get the size of a window via dev.size and set the size of subsequent windows with this.
However, how can I get the position of the window?
(Imagine the first graph pops up - the user moves and resizes it to suit them. All subsequent windows should appear at that position/size so it almost looks like an animation, making it easier to tell what has changed between subsequent graphs.
I can't simply use the same graph window and graph over the top of it, because sometimes I want to remove lines from the graph (keeping all else the same) as opposed to adding them.)

A: As I recall you cannot do this as "R does not know", only the window manager does and there is no callback mechanism between the window manager and the application, ie R, that is passed through to us as application level developers.


text:
Q: What do 2 pairs of three numbers separated by colon mean in SDF files when describing delays of cells? OK here is an example:
(CELL
  (CELLTYPE "AND2")
  (INSTANCE top/b/d)
  (DELAY
    (ABSOLUTE
      (IOPATH a y (1.5:2.5:3.4) (2.5:3.6:4.7))
      (IOPATH b y (1.4:2.3:3.2) (2.3:3.4:4.3))
    )
  )
)

I think that we have 2 inputs a and b. We are trying to describe the worst case, typical and best case delays between them and the output? If this is the case why are there 2 pair of 3 numbers rather than just 1. I am looking for a straight-forward answer to this specific point but have not been able to get it from google.

A: The reference of the SDF file format contains all information and can be found here. Another good starting source for reading SDF files is this blog entry.
The SDF snippet you posted defines a cell with the name "AND2" and the path to the cell INSTANCE "top/b/d" and is giving DELAY information for it. ABSOLUTE means it is replacing previous delay information. The two IOPATH entries define the delay between the input ports (a/b) and the output y. This information can be found with more detail in the blog entry mentioned above.
To fully understand the IOPATH entries you need to look at the SDF reference. SDF allows to define different delay values dependent on the transition (e.g. 0->1 or 1->0). Therefore you can specify one, two, three, six or twelve delay values. More information can be found in the SDF reference on page 3-16 and 3-17. In this case there are given two delay values.
Each of the delay values can contain one, two or three values. If one value is given it defines the delay from the input to the output (to get the duration you have to consider the TIMESPEC in the SDF header). For two values the first defines the delay and the second the pulse rejection limit and the X-limit. If three values are given the first specifies the delay, the second the pulse rejection limit and the third the X-limit.
The pulse rejection limit defines the maximal width of pulses that do not change the output.
The X-limit defines the maximal width of pulses that leave the output in an unknown state (X). All pulses with a width greater than the pulse rejection limit and less or equal than the X-limit will change the output to unknown.
This information can be found in the blog entry and the SDF reference on page 3-18. The reference lacks a description of the pulse rejection limit and X-limit but the blog provides a description.


text:
Q: R: reading geotiff data straight from web url (httr::GET raw content) I would like to create a RasterLayer from GeoTIFF data provided by a server. I'll query the server for this data using a httr::GET call (the data is provided on-demand, so in the application there won't be a url ending in .tif but a query url).
After writing the result of this call to disk as a GeoTIFF file it's easy enough to create the RasterLayer from the resulting GeoTIFF file on disk:
library(httr)
library(raster)

url <- 'http://download.osgeo.org/geotiff/samples/gdal_eg/cea.tif'

geotiff_file <- tempfile(fileext='.tif')
httr::GET(url,httr::write_disk(path=geotiff_file))
my_raster <- raster(geotiff_file)
my_raster

However, I would like to skip the write to disk part and create the raster straight from the in-memory server response.
response <- httr::GET(url,httr::write_memory())
response

The content of the response is a raw string which I would need to interpret as geoTIFF data.
str(httr::content(response))

However, I can only find raster or rgdal functions to read from a file. Any suggestions on translating this raw string to a raster?
Thanks!

A: GDAL has some cool virtual file system driver, one of which is /vsicurl that

allows on-the-fly random reading of files available through HTTP/FTP web protocols, without prior download of the entire file. It requires GDAL to be built against libcurl.

Since the raster package builds on rgdal you can simply do this:
library(raster)

r <- raster('/vsicurl/http://download.osgeo.org/geotiff/samples/gdal_eg/cea.tif')

plot(r)


text:
Q: sending an email with libcurl/smtp with gmail: login denied I know there are hundreds of posts out there but somehow this does not work for me. I am trying to send an email with libcurl. This is my code:
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

#define FROM    "<myemail@gmail.com>"
#define TO      "<someother@gmail.com>"
#define CC      "<someother2@hotmail.com>"

static const char *payload_text[] = {
  "Date: Mon, 29 Nov 2010 21:54:29 +1100\r\n",
  "To: " TO "\r\n",
  "From: " FROM "(Example User)\r\n",
  "Cc: " CC "(Another example User)\r\n",
  "Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@"
  "rfcpedant.example.org>\r\n",
  "Subject: SMTP example message\r\n",
  "\r\n", /* empty line to divide headers from body, see RFC5322 */
  "The body of the message starts here.\r\n",
  "\r\n",
  "It could be a lot of lines, could be MIME encoded, whatever.\r\n",
  "Check RFC5322.\r\n",
  NULL
};

struct upload_status {
  int lines_read;
};

static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)
{
  struct upload_status *upload_ctx = (struct upload_status *)userp;
  const char *data;

  if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {
    return 0;
  }

  data = payload_text[upload_ctx->lines_read];

  if(data) {
    size_t len = strlen(data);
    memcpy(ptr, data, len);
    upload_ctx->lines_read++;

    return len;
  }

  return 0;
}

int main(void)
{
  CURL *curl;
  CURLcode res = CURLE_OK;
  struct curl_slist *recipients = NULL;
  struct upload_status upload_ctx;

  upload_ctx.lines_read = 0;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:587");
    curl_easy_setopt(curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);
    curl_easy_setopt(curl, CURLOPT_USERNAME, "myemail@gmail.com");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "mypassword");
    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, FROM);

    recipients = curl_slist_append(recipients, TO);
    recipients = curl_slist_append(recipients, CC);
    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);

   curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);
curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);
    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

    res = curl_easy_perform(curl);

    /* Check for errors */
    if(res != CURLE_OK)
      fprintf(stderr, "curl_easy_perform() failed: %s\n",
              curl_easy_strerror(res));

    curl_slist_free_all(recipients);

    curl_easy_cleanup(curl);
  }

  return (int)res;
}

I also tried this example which is very similar except the text gets piped through a different file.
But I always get

curl_easy_perform() failed: Login denied

and then gmail sends me a message saying that someone tried to hack into my account. (login credentials are correct)
This curl-config --feature
gives me

SSL IPv6 UnixSockets libz NTLM NTLM_WB

Reading a couple of blogposts I also tried with hotmail using smtp://smtp.live.com:465
But here I get

curl_easy_perform() failed: Couldn't connect to server

What am I doing wrong here?

A: I had to spend a great deal of time to get this to work but I finally got it to work. Here's what I found:
First:
#define FROM    "<myemail@gmail.com>"
#define TO      "<someother@gmail.com>"
#define CC      "<someother2@hotmail.com>"

There should not be any "<" or ">" in the email adress. I did the mistake of reusing the defines and could not for my life understand why the login failed.
Second:
You will most likely need to go here and allow unsecure apps: https://www.google.com/settings/security/lesssecureapps
Third:
If you're using port 587 you will need the following line:
curl_easy_setopt(m_curl, CURLOPT_USE_SSL, CURLUSESSL_ALL);

This does not seem to be needed for 465.
Note:
It's ok to use either port 465 or 587. 465 requires SSL so you will need to use smtps instead of smtp to specify this - smtps://smtp.gmail.com:465. I found some info about it here: https://support.google.com/a/answer/176600?hl=en

A: In 2022, you need to create a App Password on you google account. And then using this password you can send the emails without problem.
Take a look on this link: https://support.google.com/mail/answer/185833?hl=en

A: i am use libcurl, so i've been downloaded the curl-7.49.1 and inside the directory
i copied the imap-fetch.c to generate an specific imap for gmail, than i copy, paste and rename to imap-fetch-gmail.h
inside the imap-fetch-gmail.h i set my parameters on this lines:
curl_easy_setopt(curl, CURLOPT_USERNAME, "myemail@gmail.com");
curl_easy_setopt(curl, CURLOPT_PASSWORD, "mypassword");

/* This will fetch message 1 from the user's inbox */
curl_easy_setopt(curl, CURLOPT_URL,
                 "imaps://imap.gmail.com:993/INBOX/;UID=1");

then, inside the curl folder i call GCC to compile my imap-fetch-gmail.h with my account settings such as E-mail, Password and parameters  with this command
gcc imap-fetch-gmail.c -o imap-fetch-gmail -lcurl
After this,
First, you need to enable your IMAP Settings on your GMAIL account, then you need to enable less secure apps to access your gmail account. If you does not do it you've receice an security email with the subject : "Attempting to login prevented"
You can manage access to less secure apps on this link:
https://www.google.com/settings/security/lesssecureapps
For more information about the individual components of an IMAP URL please see RFC 5092.


text:
Q: Extracting data from one Javascript object and putting it into another The situation I'm dealing with is taking the the data from a JSON object (represented as a JavaScript object) extracting some of the data and with that data producing a new object, using JavaScript. The new object will also consist of new added data.
Lets say I have the following object:
sprite_set = {
    "frames": {
        "grass.png": {
            "frame": {
                "x": 1766,
                "y": 202
            },
            "rotated": false,
            "sourceSize": {
                "w": 128,
                "h": 128
            }
        },
        "dirt1.png": {
            "frame": {
                "x": 1766,
                "y": 202
            },
            "rotated": false,
            "sourceSize": {
                "w": 128,
                "h": 128
            }
        },
        "dirt2.png": {
            "frame": {
                "x": 2766,
                "y": 402
            },
            "rotated": false,
            "sourceSize": {
                "w": 128,
                "h": 128
            }
        }
    }
};

From this object I want to form a new object of the from:
sprite_set = {
    "frames": {
        "grass": {
            "frame": {
                "x": 1766,
                "y": 202
            },
            "sourceSize": {
                "w": 128,
                "h": 128
            }
        },
        "dirt": {
            "multi_frames": {
                "frame1": {
                    "x": 1766,
                    "y": 202
                },
                "frame2": {
                    "x": 2766,
                    "y": 402
                }
             },
            "sourceSize": {
                "w": 128,
                "h": 128
            }
        }
    }
};

So I need to construct a function that takes the raw object and spits out the new object using the following rules:

*

*
  Remove all "rotated" properties from each "frames"

*
  Rename each sub-object in "frames" to remove the .png so "grass.png" will be changed to "grass"

*
  If a "frames" sub-objects name contains no leading number then just place it unchanged in the new object

*
  If a "frames" sub-objects name does contains a leading number then break each subsequent number into a new subobject whos parent is "multi_frames"

I am really completely new to JSON so any help on just how to start with this would be great. I wan't to learn so as I get some help I will tackle this problem and constantly give an update to how I'm doing it at the bottom of this answer.
One further question, is there a JavaScript library that can make this process a lot easier?
Thanks for anyone's help.
Update
From help from people comments this is that I have so far:
HTML
<input type="file" id="files" name="files[]" />

*JavaScript*
var JsonObj = null;

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object
    f = files[0];
    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function (theFile) {
        return function (e) {
            JsonObj = e.target.result
            console.log(JsonObj);
            var parsedJSON = JSON.parse(JsonObj);

            var oldframes = parsedJSON.frames,
                newframes = {};
            for (var framename in oldframes) {
                // var m = framename.match(/(.*)\.[^.]+$/);
                var m = framename.match(/^(.+?)(\d*)\.png$/);
                var newname = m[1];
                var frame = oldframes[framename];
                if (newname in newframes) newframes[newname].multi_frames["frame" + m[2]] = frame.frame;
                else newframes[newname] = {
                    frame: frame.frame,
                    sourcesize: frame.sourcsize
                };
                // or, if it's OK to mutate the old objects, just:
                // delete frame.rotated;
                // newframes[newname] = frame;
            }
            parsedJSON.frames = newframes;

            JsonObj = JSON.stringify(parsedJSON, null, 4)
            console.log(JsonObj);

        };
    })(f);

    // Read in JSON as a data URL.
    reader.readAsText(f, 'UTF-8');
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);

I use the HTML5 File Api to get the JSON file. I get the following error
Uncaught TypeError: Cannot set property 'frame2' of undefined fiddle >
(anonymous function)
in reference to the line:
if (newname in newframes) newframes[newname].multi_frames["frame" + m[2]] = frame.frame;
I can't see what the problem is, any ideas anyone?
I have a live JSFiddle here: http://jsfiddle.net/jamiefearon/8kUYj/48/
Now fixed: Fiddle here: http://jsfiddle.net/jamiefearon/8kUYj/50/

A: This should do it:
var oldframes = sprite_set.frames,
    newframes = {};
for (var framename in oldframes) {
    var m = framename.match(/^(.+?)(\d*)\.png$/); // not assuming it would not match
    var newname = m[1];
    var frame = oldframes[framename];
    if (! (newname in newframes)) {
        newframes[newname] = {
            sourceSize: frame.sourceSize
        };
        if (m[2])
            newframes[newname].multi_frames = {};
    }
    if (m[2])
        newframes[newname].multi_frames["frame"+m[2]] = frame.frame;
    else
        newframes[newname].frame = frame.frame;
}
sprite_set.frames = newframes;


text:
Q: Regex match pattern more than once in the same line I am trying to perform this transformation to a string (using javascript):
Input:
[hello]{world}and[good]{night}

Output:
helloworldandgoodnight

To do that I am using the following regex:
text.replace(/\[(.*)\]\{(.*)\}/gim, "$1$2")

It works correctly when only setting one occurrence of the pattern in a string [hello]{world}
But if I add a string with more than one, the regex matches the first [] and the last {} instead, and prints this:
hello]{world}and[goodnight

How can I tell regex to match the first pattern and the second pattern instead of matching it as one bigger pattern?
Note that between the [] and {} I expect there to be no text. So [hello]world and good{night} should not be matched.

A: You need to put ? after .* to make the quantifier lazy, instead of greedy.

const text = '[hello]{world}and[good]{night}'

const result = text.replace(/\[(.*?)\]\{(.*?)\}/gim, "$1$2")

console.log(result)


text:
Q: My Powershell loop is overwriting the previous excel entry. Using Export-CSV -append duplicates entries Powershell is definitely not one of my "strengths" but every once in a while I try to script something to automate a manual task.  Anyway, here is my problem.  The script as is WORKS and WILL export a csv file and sort by the Hostname header.  My issues is there has got to be a better way of doing this?
#Clear the output screen
cls

#set the working directory to where the script and text files are located (must be same directory)
$scriptdir = Split-Path -Parent $PSCommandPath
cd $scriptdir

#set fileNamePaths for Export-Csv No Sort and Sorted to excel
$FilePathNS = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll_NoSort.csv"
$FilePathSort = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll.csv"

#set up the ip subnet import
$path = ".\EnclosureSubnets.txt"
$ip = Get-Content $path

#Loop to find OA information
foreach ($subnet in $ip) {

    $OAS = Find-HPOA $subnet -Timeout 250 -Verbose
    $OAS | where {$_.Role -eq "Active"} | Export-Csv -NoTypeInformation -Append $FilePathNS
}

#Sort AOInfoAll.csv by hostname
Import-Csv $FilePathNS | Sort-Object Hostname | Export-Csv $FilePathSort -NoTypeInformation

If I take out the append then the loop will overwrite the previous entry and I will only end up with 2 IPs and 2 Hostnames.  Append fixes this BUT when I run the script again I get duplicate/repeating entries.
Also, I've tried using the Sort-Object Hostname inside the loop but it only sorts each individual entry as they are written. Here is an example (IPs and Hostnames are made up):
IP                  Hostname
192.168.1.10        chassis03
192.168.1.12        chassis05
192.168.2.16        chassis01
192.168.2.18        chassis02
192.168.3.14        chassis07
192.168.3.16        chassis08

So while my script works I'd like some feedback from "The Pros"  Thanks in advance!

A: Don't export inside your loop, instead capture all capture all OAS in a variable and sort that before outputting to a CSV.
foreach ($subnet in $ip) {

    [array]$OAS += Find-HPOA $subnet -Timeout 250 -Verbose

}

$OAS | Where{$_.Role -eq 'Active'} | Sort Hostname | Export-Csv $FilePathSort -NoTypeInformation

That dramatically reduces the number of disk reads/writes.


text:
Q: Node js, module net, array of servers Hi i've been asked to make an array of servers listening to some ports, the problem here is that when I use:
"serviceSocket.connect(parseInt(80),"elpais.es",
what I really need is to use the adress and remotePorts arrays.
Like this:
"serviceSocket.connect(remotePort[i],adress[i])
but I'm not able to pass that information to serviceSocket.
Besides, when I try to get the  port that has been trigered with server.address() (for example, I connect through 8002), all the time what I'm getting in return is 8008.
How can I get the right port, or pass the information?
var ports = [8001,8002,8003,8004,8005,8006,8007,8008];
var adress = ["www.cnc.uji.es","en.wikipedia.org","random.random2.es","ftp.rediris.es", "elpais.es" ,"","",""]
var remotePort = [80,80,443,21,80,"","",""]

for (i=0 ;i<ports.length; i++){

  var server = net.createServer(function(socket){

        socket.on('data', function(data){
console.log(server.address());
            var serviceSocket = new net.Socket();
    serviceSocket.connect(parseInt(80),"elpais.es", function(){
serviceSocket.write(data);});
    serviceSocket.on('data',function(data){console.log(server.address());
socket.write(data);});
        });
        }).listen(ports[i]);
}
console.log('TCP server accepting connection on port ' + ports)

A: your code is running asynchronously and when the callback function calls i,the for loop's already finished so that's why you always get the last element of the array.
try something like this
var net = require('http');
var ports = [8001,8002,8003,8004,8005,8006,8007,8008];
var adress = ["www.cnc.uji.es","en.wikipedia.org","random.random2.es","ftp.rediris.es",     "elpais.es" ,"","",""];
var remotePort = [80,80,443,21,80,"","",""];

for (i=0 ;i<ports.length; i++){
makeServer(i);
}
console.log('TCP server accepting connection on port ' + ports);

function makeServer(i){
    var server = net.createServer(function(socket){
        socket.on('data', function(data){
console.log(server.address());
        var serviceSocket = new net.Socket();
serviceSocket.connect(parseInt(80),"elpais.es", function(){
serviceSocket.write(data);});
    serviceSocket.on('data',function(data){console.log(server.address());
socket.write(data);});
        });
        }).listen(ports[i]);

};

code isn't tested.


text:
Q: RequiredValidation only active when another control contain a value I have two dropdownlists, if one of them contain a value (not default value, which is empty string), the other should also have a value (like requredvalidator). But if no one has a value the page should validate 'true'.
I cannot solve it with a validation group, because the button that trigger the validation is already triggering other validations.

A: Could you just use a custom validator control and put your logic in the server side validation method. Keep it in the same validation group.
<asp:CustomValidator ID="valCust" runat="server"
                ControlToValidate="ddlControl" ErrorMessage="error Message"
                ValidationGroup="Group"
                onservervalidate="valCust_ServerValidate" >*</asp:CustomValidator>

code behind
 protected void valCust_ServerValidate(object source, ServerValidateEventArgs args)
{
     args.IsValid = MethodToWorkOutValidation();

}

A: please check below code snippet.
 function EnableDisableValidator() {
        var DropDownList1 = document.getElementById('DropDownList1');
        var DropDownList2 = document.getElementById('DropDownList2');
        var RequiredFieldValidator12 = document.getElementById('RequiredFieldValidator12');
        if (DropDownList1.selectedIndex > 0 && DropDownList2.selectedIndex > 0) {
            ValidatorEnable(document.getElementById('RequiredFieldValidator12'), true);

        }
        else {
            ValidatorEnable(document.getElementById('RequiredFieldValidator12'), false);
        }
    }

..........
 <asp:DropDownList ID="DropDownList1" runat="server" onchange="EnableDisableValidator();">
    <asp:ListItem Text="" Value=""></asp:ListItem>
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" onchange="EnableDisableValidator();">
    <asp:ListItem Text="" Value=""></asp:ListItem>
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
</asp:DropDownList>
<div style="display: none;">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ControlToValidate="TextBox1"
    Enabled="false" ErrorMessage="*************" ></asp:RequiredFieldValidator>

Let me know if any concern


text:
Q: iphone: copy or move file from document directory folder Here is my code.
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"Songs"];
    NSString *fromPath=[[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"abc"];
    NSString *strdestination = [fromPath stringByAppendingPathComponent:@"sg.mp3"];
    NSError *Error;
    if([[NSFileManager defaultManager]fileExistsAtPath:strdestination]){
        if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO){
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"copy" message:[NSString stringWithFormat:@"%@",Error] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }
        else{
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Not copy" message:[NSString stringWithFormat:@"%@",Error] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }
    }

I am getting the error logo :

Error Domain=NSCocoaErrorDominCode=516 "The operation couldn't be
  completed .(Cocoa arrow 516.)" userInfo=0x681abf0
NSUnderlyingError =0x681b920 "The operation couldn't be completed
  .File exists"

abc folder  there is no song name "sg.mp3" but I'm still getting the file exists error. I don't know where I did mistake?

A: Drawing upon the Midhun MP answer, here's a helper
BOOL moveFile(NSString *srcPath, NSString *dstPath)
{
    NSLog(@"moving %@ -> %@", srcPath, dstPath);

    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:dstPath])
    {
        // in my usecase this is a hard error, bolt to prevent overwriting
        return NO;
    }

    if ([fm fileExistsAtPath:srcPath])
    {
        NSError *error = nil;
        NSString *destDir = [dstPath stringByDeletingLastPathComponent];
        [fm createDirectoryAtPath:destDir withIntermediateDirectories:YES attributes:nil error:nil];

        if ([[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dstPath error:&error]==NO)
        {
            NSLog(@"failure declassing %@", srcPath);
            return NO;
        }
        else
        {
            [fm removeItemAtPath:srcPath error:NULL]; // gr8t success
            return YES;
        }
    }

    return NO;
 }

A: There is two issues in your code:

*

*You need to remove the file if it is already there

*You need to specify a name for the destination file, means if you use like:

NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"Songs"];
and
[[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error];

Then if copy occurs, it will copy the Sg.mp3 file as Songs without any type.
So you need to write it like:
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *tempPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"Songs"];
NSString *toPath = [tempPath stringByAppendingPathComponent:@"yourFileName.mp3"];
NSString *fromPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:@"sg.mp3"];
NSError *Error = nil;

if([[NSFileManager defaultManager]fileExistsAtPath:strdestination])
{

  if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO)
   {
       UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"copy" message:[NSString stringWithFormat:@"%@",Error] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
       [Alert show];
   }
   else
   {
      [fileManager removeItemAtPath:strdestination error:NULL];
       UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Not copy" message:[NSString stringWithFormat:@"%@",Error] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
       [Alert show];
   }
}

This code will remove the file if exist at destination and then copy  the sg.mp3 from abc folder to Songs folder with the name yourFileName.mp3

A: I think its because you are trying to overwrite a file with your copy.
Check your permission mask, try using the cache instead of the documents directory.
Do you mean if(!fileExistsAtPath)

A: You need to delete the file that's already there:
NSArray *pathSong = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *toPath = [[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"Songs"];
NSString *fromPath=[[pathSong objectAtIndex:0] stringByAppendingPathComponent:@"abc"];
NSString *strdestination = [fromPath stringByAppendingPathComponent:@"sg.mp3"];
NSError *Error;

//DELETE THE FILE AT THE LOCATION YOU'RE COPYING TO
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:strdestination error:NULL];

if([[NSFileManager defaultManager]copyItemAtPath:strdestination toPath:toPath error:&Error]==NO){
        UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"copy" message:[NSString stringWithFormat:@"%@",Error] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [Alert show];
    }
else{
        UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Not copy" message:[NSString stringWithFormat:@"%@",Error] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [Alert show];
    }


text:
Q: How to use variables containing numbers in regular expression? I have this as my code:
motifSearch = ''
intMin = 15
intMax = 21
intlen = intMax - intMin
SD = "TTGACA"
PBN = "TATAAT"

fastaFile = open('testseq.fsa', 'r')
for line in fastaFile:
    if deviation == 0:
        motSearch = re.search(SD+'([A-Z|a-z]){'+intMin,intMax+'}('+PBN+')', line)
        if motSearch is not None:
            motifSearch = motSearch.group(0)
print(motifSearch)

I have to find a first signal that is SD, then jump {intMin,intMax} number of characters, and then find the second signal PBN. When I print this out I get: "TypeError: Can't convert 'int' object to str implicitly".
What am I doing wrong?

A: Use string formatting.
regex = '{}([A-Z|a-z]){{},{}}({})'.format(SD, intMin, intMax, PBN)

motSearch = re.search(regex, line)

If your reusing variables or want something more readable you can also specify order this way...
regex = '{0}([A-Z|a-z]){{1},{2}}({3})'.format(SD, intMin, intMax, PBN)

Another example of string formatting to address string formatting issues (not sure how to get around the case of of using {} as you cannot escape them)
regex = '%s([A-Z|a-z]){%s,%s}(%s)' % (SD, intMin, intMax, PBN)


text: Q: Where did G. W. Hill develop his relative motion equations? The equations for relative orbital motion are commonly known as "Hill's equations" (also Clohessy-Wiltshire equations), and the citation given to G. W. Hill's 1878 "Researches in Lunar Theory" in the American Journal of Mathematics (usually citing only the first segment of pages and overlooking the fact that it is continued into two more segments).  I've looked through the whole paper (on JSTOR Segment 1, Segment 2, Segment 3) and not found anything that resembles the equations as we know them today.  Does anyone know if they are hidden in a notation that is unfamiliar to the modern eye, or did they appear in another of his papers?  One thing I noticed is that the end of the third segment on page 260, it says "to be continued" as it does at the end of the first two segments, but JSTOR doesn't list any more segments that I can find.  Is there more to this paper?


text:
Q: Find $f$ on $[1,a]$ such that $f \ge x\log x$, $f$ is strictly convex, analytic, and touches $x \log x$ only $n$ times. I am looking for a function $f$ defined on $[1,a]$ that satisfies the following:

*

*$f(x) \ge x \log x$ on $[1,a]$

*$f(x)$ is strictly convex

*$f(x)$ is analytic  on $[1,a]$.

*$f(x)-x\log(x)=0$ only $n$ times on $[1,a]$.

My attempt was to construct $f$ as follows:
$f(x)=x\log(x)+g(x)$
where $g(x)$ would have oscillatory behavior (e.g., $\cos(x)$). However, every time I try to add oscillations I violate strict convexity condition.

A: Example, $n=3$  on the interval $[1,3]$,
$$
f(x) = x\log x+\frac{(x-1)^2(x-2)^2(x-3)^2}{10}
$$
It is analytic on $(0,+\infty)$.
Here is $f(x)$ on $[1,3]$

Here is $f(x) - x\log x$.  It is of course nonnegative and vanishes only at $1,2,3$.

Here is $f''(x)$.  It is positive, so $f$ is strictly convex.

The coefficient $1/10$ was chosen so that $f''(x)$ is strictly positive.
If we consider $f(x)= x\log x+k(x-1)^2(x-2)^2(x-3)^2$ for $k>0$, then $f''(x)$
converges uniformly to $1/x$ as $k \to 0$, so of course we can choose $k$ so close to zero that $f''(x)$ is positive on $[1,3]$.