text:
Q: Como seleccionar un id que esta en otro id desde CSS No soy para nada bueno con el css y tengo la siguiente duda.
Ya tengo el formato del menú de la pagina y no lo puedo cambiar ya que es para múltiples paginas el css (Padre css).
La idea es que muestre un menu para Desktop y que muestre otro para telefono y tablet
Entonces tengo:

 -->para Desktop

Inicio

Productos

Commercial

Sobre Nosotros

Contactar

 --> para celular y tablet

Inicio

Productos

                            para sala
                            para Bano

                      X

Us

Todo esto me funciona perfecto si uso javascript
if (window.innerWidth<= 768){
    document.getElementById('mobile').style.display ="block";
    document.getElementById('menu').style.display ="none";
    }else{

    document.getElementById('mobile').style.display ="none";
    document.getElementById('menu').style.display ="block";

    }

pero a la hora de pasarlo a css, no se como hacerlo :(, ya que id="menu" esta en las dos secciones (Desktop, celular ) y si le doy #menu{ display: none;} #mobile{ display: block;} me muestra el menu de Desktop
Como puedo solucionarlo?

A: Eso te pasa porque tenes dos id "menu", al menu desktop podrías contenerlo dentro de un div id "desktop" y actualizar tu js.

 -->para Desktop

Inicio

Productos

Commercial

Sobre Nosotros

Contactar

Tu js corregido:
if (window.innerWidth<= 768){
       document.getElementById('mobile').style.display ="block";
       document.getElementById('desktop').style.display ="none";
    }else{
       document.getElementById('mobile').style.display ="none";
       document.getElementById('desktop').style.display ="block";
    }

Si querés hacerlo con CSS seteale display:none a mobile y utilizá la etiqueta media:
@media (max-width: 768px) {
   #mobile { display:block; }
   #desktop { display:none; }
}

Saludos.

A: CSS toma el ultimo valor osea tú #mobile #menu, por eso lo esconde, ya que id solo afecta a 1 y solo 1 elemento, por eso te afecta a tu menú en mobile, podrías apuntar a el de la siguiente manera:
#menu { display: none; }
#mobile > #menu { display: block; }

Aunque te recomiendo le cambies el id, o lo vuelvas una clase.


text:
Q: CSS formatting a template to get layout working properly Hi guys wondering if I could get a little assistance with my site. It is for a uni assignment on e-Business and I have used a template. I have gotten a Javascript code to keep track of amount of items in the basket and cost but I can't get it to display nicely.
It is either on the same line as 'Shopping Cart' or if I use
 goes well below the header menu section.
http://i.imgur.com/PjX4VtB.png
to give you an idea of what I mean
Code for header.php

Pet Accessories

        Your Shopping Cart

Home

About Us

Contact

Code for relevant style.css
    #header { height:64px; background:url(images/header.gif); position:relative;}
    #navigation { float:right; white-space:nowrap; }
    #navigation ul{ list-style-type: none; height:64px; font-weight: bold; float:left;}
    #navigation ul li{ float:left; display:inline; }
    #navigation ul li a{ float:left; height:64px; line-height:64px; text-decoration: none; color:#fff; padding:0 15px;}
    #navigation ul li a.active,
    #navigation ul li a:hover{ background:#fff; color:#8b0000; }

    #cart { float:right; width:160px; top:0; right:0; height:51px; background:#8b0000; color:#fff; padding:13px 10px 0 10px; white-space:nowrap; line-height:38px;}
    a.cart-link { color:#fff; background:url(images/cart-link.gif) no-repeat 0 0; padding:0 0 0 32px; text-decoration: none;}
    a.cart-link:hover { text-decoration: underline;}

    #sidebar { float:left; width:226px;}
    #content { float:right; width:724px;}

    #main { padding:10px 0 0 0; }

I have tried to provide as much information as possible, any help would be greatly appreciated. I don't know if I need to modify the .css file or use another type of
 to get my text to show in right spot.
Thanks
Jamie

A: The #cart element has a 38px line-height. Remove that.
Another thing you may want to do is remove the
 tag to let them be in the same line.
Note that the 160px width won't be enough. You should make it higher (changing all other elements width too) or remove white-space:nowrap; in the #cart element.

A: Change height in #cart to min-height (and for the rest of the top section for that matter) or remove it completely.
If you must have it at that fixed height, change the line-height in #cart small enough that it will fit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how use np.append with np.where method? I'm trying to convert this code :
df = pd.DataFrame({'values': [np.nan,-1.2,3,6,7,2]})

def f_evol (df) :
list1 = []
for i in range (len(df)) :
    if df['values'].isnull()[i] :
        list1.append(0)
    else :
        if df['values'][i] > 0 :
            k = list1[i-1] + 1
            list1.append(k)
        if df['values'][i] < 0:
            k = list1[i-1] - 1
            list1.append(k)
return list1

df['count'] = f_evol(df)

on this one :
def v_evol (df) :
k = [1]
a = np.where(df['values'].isnull().shift(0).values,
             k,
             np.where(df['values'].shift(0).values > 0,
                      k.append(k[-1] + 1),
                      np.where(df['values'].shift(0).values < 0,
                              k.append(k[-1] - 1),
                              np.nan
                              )
                     )
            )
return a

i failed to append the last value of k like in the first code ...
i tried, to replace 'k[0] + 1' by 'np.concatenate()', by 'np.append()' without succes... b

A: With numpy
This will give you want you want without any explicit iteration (generally, you want to avoid for loops when working with arrays and dataframes):
np.sign(df["values"].fillna(0)).cumsum()

Demo:
In [3]: df["count"] = np.sign(df["values"].fillna(0)).cumsum()

In [4]: df
Out[4]:
   values  count
0     NaN    0.0
1    -1.2   -1.0
2     3.0    0.0
3     6.0    1.0
4     7.0    2.0
5     2.0    3.0

You can certainly cast the "count" column to an integer dtype if you want.
Without numpy
This will produce the same result without the numpy dependency, if that matters:
(df["values"] // df["values"].abs()).fillna(0).cumsum()


text:
Q: Multiple Database connections using fastapi I am new to FAST API and don't have much knowledge on the same. I wanted to connect multiple databases.
I tried to go through the https://github.com/tiangolo/fastapi/issues/2592 but was unable to understand the approach. I was also curious as to how will I be able to fetch data from the database and also update the values in the database.
It will be great if anyone can help me out, also are there any other examples or methods which would do the job?

A: Make yourself a middleware.Here is my example:
# extends BaseHTTPMiddleware filter your router name and set database_url in your envioment.
class DatabaseSelector(BaseHTTPMiddleware):
    def __init__(self, app):
        super().__init__(app)

    async def dispatch(self, request: Request, call_next):
        url_param = str(request.url).split("/")
        if "api" in str(request.url):
            url_param.remove("api")
        route_name = url_param[3]
        if route_name not in list(routeMap.keys()):
            SQLALCHEMY_DATABASE_URI = routeMap["base_mysql"]
        else:
            SQLALCHEMY_DATABASE_URI = routeMap[route_name]
        os.environ["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
        response = await call_next(request)
        return response

And make your config params like this:
routeMap = {
    "base_mysql": 'mysql+pymysql://{}:{}@{}:{}/{}'.format(*BaseMysql.values()),
    "show_data": 'mysql+pymysql://{}:{}@{}:{}/{}'.format(*RequestMysql.values()),
    "else_data": "xxxxxxx",
    }

while send http request. you can get your router name base on this routeMap:
def get_db():
    SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI')
    engine = create_engine(SQLALCHEMY_DATABASE_URI, echo=True, pool_size=50)
    SessionLocal = sessionmaker(bind=engine)
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

finally, you just call get_db without care which database you will connect.


text:
Q: Как на странице ошибок получить имя сайта на языке оригинала? Нужно перевести фразу на странице ошибок, чтобы в ней ссылка вела на главную страницу сайта.

    <?php
    printf(
    /* translators: %s: a link to the embedded site */
    __( 'It looks like nothing was found at this location. Maybe try visiting %s directly?' ),
'' . esc_html( get_bloginfo( 'name' ) ) . '');?>

Однако код ссылки выводится за абзацем.

По данному адресу ничего не найдено. Попробуйте перейти на сайт .

В результате тестирования выяснил, что на странице ошибок в принципе не отрабатывают функции bloginfo( 'name' ) и get_bloginfo( 'name' )
Вот такая запись выводит пустой абзац
$name = bloginfo( 'name' );
  echo '
'.$name.'
';

Хотя, к примеру, вот такая функция отрабатывает и выводит ссылку
$url = esc_html( get_bloginfo( 'template_url' ) );
       echo '
'.$url.'
';

Можно ли как-то обойти этот момент?


text:
Q: Java Regex, capturing items inside of "[...]" I am trying to capture text inside of XML tags like ... and the content inside of strings like "[[A]]" that would be inside of the XML tags. So far my patterns are as follows:
    Pattern titleText = Pattern.compile("<title>([A-Z])</title>");
    Pattern extractLink = Pattern.compile("(\[\[([A-Z])\]\])");

I'm getting an error on the second pattern, and it's because of the \s. However, I'm not sure how to let Regex know that I want to escape the [s and ]s so it captures the text inside of them.
An example of input I am trying to capture is:
<title>random text [[A]] more random text [[B]] ...</title>

Where [[A]] and [[B]] can happen any number of times, and I am trying to find all of them.
Any help/advice would be greatly appreciated.

A: You can't extract a regex group in Java an arbitrary number of times without specifying each one in the pattern.  However, here is an alternative solution which splits the String on the bracketed item you want to match:
Pattern titleText = Pattern.compile("<title>(.*?)</title>");
String input = "<title>random text [[A]] more random text [[B]] ...</title>";
String text = "";

Matcher m = titleText.matcher(input);
if (m.find( )) {
    text = m.group(1);
}

String[] parts = text.split("\\[\\[");

for (int i=1; i < parts.length; ++i) {
    int index = parts[i].indexOf("]]");
    String match = parts[i].substring(0, index);
    System.out.println("Found a match: " + match);
}

Output:
Found a match: A
Found a match: B

A: import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class TestTag {

    public static void main(String[] args) {
        String INPUT = "<title>random text [[ABBA]] more random text [[B]] ...</title>";
        String REGEX = "(\\[\\[\\S*]])";

        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(INPUT);

        while (m.find()) {
        System.out.println(" data: "
            + INPUT.substring(m.start() + 2, m.end() - 2));
        }

    }
}


text:
Q: How to find the time travelling between two vertices in a directed graph using R I'm trying to solve a pretty straightforward problem about phone calls simulation. I could just introduce all the data and write a very long and messy code, but I'm trying to solve it using graphs and maybe the package "igraph" on R (or something similar), but i'm never used it before.
To make it simple, I want to make a phone call from New York to Moscow and to reach Moscow, the signal can go through 3 cities with different probabilities:

*

*The call will go through London with a 0.2 probability

*Paris with 0.3 probability

*Berlin with 0.5 probability

The time for the signal to travel between cities follows a normal distribution. For simplicity, say all the times  follow a standard normal distribution. So, for instance, the sign use 0.2 minutes to travel from London to Moscow.
So, I have something like this picture in mind:
http://i.imgur.com/X4WnyxO.jpg
The numbers on the edges are the probabilities that the signal will follow that path.
Now, I would have to simulate the travel of the signal lots of times and say what is the average time it takes to go from New York to Moscow.
My question is how can I program this problem since I don't know how to get two weights on an edge, and I don't know how to loop through vertices.
Any advice you can give me would be very helpful.

A: One way to do this uses Monte Carlo simulation. The example below is just meant to get you started.
Assume you have three cities, L, P, and B. The call routing is (0.2, 0.3, 0.5) respectively. The time it takes for a call to go through a given city is normally distributed with mean dependant on the city, and standard deviation = 1 (say, millisecond). In this example, I define the mean time as (30 ms, 20 ms, 10 ms) for L, P, B, respectively. This is what is meant in the comment about defining how long it takes to travel through a city.
Then, we perform the simulation using the code below.
Monte.Carlo <- function(df) {
  set.seed(1)
  path   <- sample(df$cities, 1000, p=c(0.2,0.3,0.5), replace=T)
  mu     <- df[match(path,df$cities),]$t.mean
  time   <- sapply(mu,function(mu)rnorm(1,mu))
}
par(mfrow=c(3,1))
cities <- c("L","P","B")
t.mean <- c(30,20,10)
df     <- data.frame(cities,t.mean)
hist(Monte.Carlo(df), breaks=50, xlim=c(5,35),main="(L,P,B)=(30,20,10)")
t.mean <- c(25,20,15)
df     <- data.frame(cities,t.mean)
hist(Monte.Carlo(df), breaks=50, xlim=c(5,35), main="(L,P,B)=(25,20,15)")
t.mean <- c(22,20,18)
df     <- data.frame(cities,t.mean)
hist(Monte.Carlo(df), breaks=50, xlim=c(5,35), main="(L,P,B)=(22,20,18)")

The simulation proceeds as follows:

*

*Define a path vector which indicates which city the call is routed through, for each of 1000 calls. This is a random vector of "L", "P", or "B" with the probabilities given in the problem statement.

*Map the city "names" to mean time using the definitions in df.

*For each call in path calculate the routing time as a single random sample from a normal distribution with the appropriate mean.

We then run the simulation three times using different definitions of the mean routing time. Notice in the first case that most calls take around 10ms. This is because, according to our definitions, routing through B(erlin) takes on average 10ms, and on average 50% of the calls go through Berlin.


text:
Q: Impossible to configure LDAP correctly in JBoss 7.1 I have to configure LDAP authentication under JBoss 7.1 but I face an issue when I try to use my credentials. My configuration is like that:
<login-module code="org.jboss.security.auth.spi.LdapLoginModule" flag="required">
    <module-option name="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory"/>
    <module-option name="java.naming.provider.url" value="ldap://domain.com:389"/>
    <module-option name="java.naming.security.authentication" value="simple"/>
    <module-option name="java.naming.referral" value="follow"/>
    <module-option name="baseFilter" value="(uid={0})"/>
    <module-option name="baseCtxDN" value="ou=people,dc=domain,dc=com"/>
    <module-option name="throwValidateError" value="true"/>
    <module-option name="principalDNPrefix" value="suid="/>
    <module-option name="principalDNSuffix" value=",ou=people,dc=domain,dc=com"/>
    <module-option name="searchTimeLimit" value="5000"/>
    <module-option name="searchScope" value="ONELEVEL"/>
</login-module>

"uid" represents username used to login ("surname name") and "suid" represents an unique id.
So, when I try to use LDAP in my Java class like that, it works:
Hashtable env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
env.put("java.naming.provider.url", "ldap://domain.com:389");
env.put("java.naming.security.authentication", "simple");
env.put("java.naming.security.principal", "suid=123456789001234,ou=people,dc=st,dc=com");
env.put("java.naming.referral", "follow");
env.put("java.naming.security.credentials", "123456");
DirContext directoryContext = new InitialDirContext(env);

But, I can't configure how JBoss has to transform uid to suid ("surname name" to "123456789001234" for example).

A: In your LDAP server create next hierarchy:
+ o=your-organization-name (partition)
   + ou=users (organizationalUnit)
      - uid=your-id-user (inetOrgPerson), add userPassword attribute
   + ou=groups (organizationalUnit)
      - cn=your-user-role (groupOfNames), add the uid before created

security-domain on JBoss 7.1 (standalone.xml):
 <subsystem xmlns="urn:jboss:domain:security:1.1">
            <security-domains>
             ...
 <security-domain name="SecurityRealm" cache-type="default">
                    <authentication>
                        <login-module code="org.jboss.security.auth.spi.LdapLoginModule" flag="required">
                            <module-option name="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory"/>
                            <module-option name="java.naming.provider.url" value="ldap://host-ldap-server:port-ldap-server/"/>
                            <module-option name="java.naming.security.authentication" value="simple"/>
                            <module-option name="principalDNPrefix" value="uid="/>
                            <module-option name="principalDNSuffix" value=",ou=users,o=your-organization-name"/>
                            <module-option name="rolesCtxDN" value="ou=groups,o=your-organization-name"/>
                            <module-option name="uidAttributeID" value="member"/>
                            <module-option name="matchOnUserDN" value="true"/>
                            <module-option name="roleAttributeID" value="cn"/>
                            <module-option name="roleAttributeIsDN" value="false"/>
                        </login-module>
                    </authentication>
                </security-domain>
            </security-domains>

in your jboss-web.xml
<security-domain>SecurityRealm</security-domain>

and the most important: is the user allowed to access to this page? (web.xml):
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <!-- Protected Areas -->
    <security-constraint>
         <display-name>Protected</display-name>
        <web-resource-collection>
            <url-pattern>url-pages-you-want-protect</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>your-user-role</role-name>
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <!-- Validation By Form -->
    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>your-login-page</form-login-page>
            <form-error-page>your-error-page</form-error-page>
        </form-login-config>
    </login-config>

    <!-- Allowed Roles -->
    <security-role>
        <role-name>your-user-role</role-name>
    </security-role>
</web-app>

to test the connection use this:
public class LoginModulesTestCase extends TestCase
{
   static
   {
      try
      {
         Configuration.setConfiguration(new TestConfig());
         System.out.println("Installed TestConfig as JAAS Configuration");
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }
   }
   /** Hard coded login configurations for the test cases. The configuration
    name corresponds to the unit test function that uses the configuration.
    */
   static class TestConfig extends Configuration
   {
      public void refresh()
      {
      }

      public AppConfigurationEntry[] getAppConfigurationEntry(String name)
      {
         AppConfigurationEntry[] entry = null;
         try
         {
            Class[] parameterTypes = {};
            Method m = getClass().getDeclaredMethod(name, parameterTypes);
            Object[] args = {};
            entry = (AppConfigurationEntry[]) m.invoke(this, args);
         }
         catch(Exception e)
         {
         }
         return entry;
      }

      AppConfigurationEntry[] testLdapExample1()
      {
         String name = "org.jboss.security.auth.spi.LdapLoginModule";
         HashMap options = new HashMap();
         options.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
         options.put("java.naming.provider.url", "ldap://host-ldap-server:port-ldap-server/");
         options.put("java.naming.security.authentication", "simple");
         options.put("principalDNPrefix", "uid=");
         options.put("principalDNSuffix", ",ou=users,o=your-organization-name");
         options.put("rolesCtxDN", "ou=groups,o=your-organization-name");
         options.put("uidAttributeID", "member");
         options.put("matchOnUserDN", "true");
         options.put("roleAttributeID", "cn");
         options.put("roleAttributeIsDN", "false");
         AppConfigurationEntry ace = new AppConfigurationEntry(name,
         AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
         AppConfigurationEntry[] entry = {ace};
         return entry;
      }
   }

   public LoginModulesTestCase(String testName)
   {
      super(testName);
   }

   @Test
   public void testLdapExample1() throws Exception
   {
      System.out.println("testLdapExample1");
      UsernamePasswordHandler handler = new UsernamePasswordHandler("your-uid", "your-uid-password".toCharArray());
      LoginContext lc = new LoginContext("testLdapExample1", handler);
      lc.login();

      Subject subject = lc.getSubject();
      System.out.println("Subject: "+subject);

      Set groups = subject.getPrincipals(Group.class);
      assertTrue("Principals contains your-uid", subject.getPrincipals().contains(new SimplePrincipal("your-uid")));
      Group roles = (Group) groups.iterator().next();
      assertTrue("your-uid-role is a role", roles.isMember(new SimplePrincipal("your-uid-role")));

      lc.logout();
   }

}

hey I have to ask you something:

*

*is your ldap host = domain.com?

*and your ldap port = 389?

*where is your ldap server installed?

*is your organization's ldap partition ou=people,dc=domain,dc=com?

*don't use suid, use uid like the example I had shown you, the uid is unique

*is your uid located on ou=people,dc=domain,dc=com?

*is this code an example copy?

*I'm using Apache Directory server as lpad server on my own machine,
who is your server?

*where your server located?

if you want I can help you to configure Apache Directory Server, you only have to ask a stackoverflow question and add the jboss 7.x and ldap stackoverflow tags

A: I managed to connect with this, using jldap:
LDAPConnection conn = new LDAPConnection();
conn.connect("ldap.mycompany.com",389);
LDAPSearchResults searchResults = conn.search("ou=people,dc=mycompany,dc=com",
    LDAPConnection.SCOPE_ONE, "cn=Surname Name", null, false);
LDAPEntry entry = searchResults.next();
if (entry != null) {
    // the username is valid, lets pull out the CN from the attributes
    String cnValue = null;
    LDAPAttributeSet attrSet = entry.getAttributeSet();

    Iterator<LDAPAttribute> allAttrs = attrSet.iterator();
    while (allAttrs.hasNext()) {
        LDAPAttribute attr = allAttrs.next();
        String attrName = attr.getName();
        System.out.println(attrName);
        if (attrName.equalsIgnoreCase("suid")) {  // we got the CN
            cnValue = (String) attr.getStringValues().nextElement();
            System.out.println(cnValue);
        } else {
            continue;
        }
    }

    if (cnValue == null) {
        // return auth failed, the username doesn't exist
    }

    // attempt a bind with CN and given password
    LDAPConnection tmp = new LDAPConnection();
    tmp.connect("ldap.mycompany.com", 389);
    tmp.bind("suid=" + cnValue + "," + "ou=people,dc=mycompany,dc=com", "MYPASSWORD");

    // <password> came from the user trying to login*/
    // return auth successful, username and password are valid
    // an LDAPException is thrown if the credentials are invalid
}

But I don't manage to use this for my jboss configuration.
EDIT, this works in Java:
String username = "surname name";

Hashtable<String, String> env = new Hashtable<String, String>(11);

boolean b = false;

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.mycompany.com:389");
env.put(Context.SECURITY_AUTHENTICATION, "none");
env.put(Context.SECURITY_PRINCIPAL, "uid="+ username +",ou=people,dc=mycompany,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "PASS");

try {
    // Create initial context
    DirContext ctx = new InitialDirContext(env);

    // Close the context when we're done
    b = true;
    ctx.close();

} catch (NamingException e) {
    b = false;
    e.printStackTrace();
}finally{
    if(b){
        System.out.print("Success");
    }else{
        System.out.print("Failure");
    }
}


text:
Q: Gridviews in TabControl losing binding on ActiveTabChanged I have a ajax tab control with 7 tabs and a gridview in each tab. I have it set to autopostback and fill each gridview when that tab is selected. This all works fine. What I would like to be able to do is not fill a gridview if it has already been filled once, but each time I switch tabs the gridviews lose their binding and HAVE to be bound to their datasource again. Any ideas?

A: you need to bind all your grid of every tab in page load event of page in side
if(!IsPostback)
{
   Bindgrid();
   Bindgrid2();
   ....
}


text:
Q: What's the difference between gets and scanf? If the code is
scanf("%s\n",message)

vs
gets(message)

what's the difference?It seems that both of them get input to message.

A: Disambiguation: In the following context I'd consider "safe" if not leading to trouble when correctly used. And "unsafe" if the "unsafetyness" cannot be maneuvered around.

scanf("%s\n",message)

vs
gets(message)

What's the difference?

In terms of safety there is no difference, both read in from Standard Input and might very well overflow message, if the user enters more data then messageprovides memory for.
Whereas scanf() allows you to be used safely by specifying the maximum amount of data to be scanned in:
char message[42];

...

scanf("%41s", message); /* Only read in one few then the buffer (messega here)
                           provides as one byte is necessary to store the
                           C-"string"'s 0-terminator. */

With gets() it is  not possible to specify the maximum number of characters be read in, that's why the latter shall not be used!

A: The main difference is that gets reads until EOF or \n, while scanf("%s") reads until any whitespace has been encountered. scanf also provides more formatting options, but at the same time it has worse type safety than gets.
Another big difference is that scanf is a standard C function, while gets has been removed from the language, since it was both superfluous and dangerous: there was no protection against buffer overruns. The very same security flaw exists with scanf however, so neither of those two functions should be used in production code.
You should always use fgets, the C standard itself even recommends this, see C11 K.3.5.4.1

Recommended practice
6 The fgets function allows properly-written
  programs to safely process input lines too long to store in the result
  array. In general this requires that callers of fgets pay attention to
  the presence or absence of a new-line character in the result array.
  Consider using fgets (along with any needed processing based on
  new-line characters) instead of gets_s.

(emphasis mine)

A: gets -    Reads characters from stdin and stores them as a string.
scanf - Reads data from stdin and stores them according to the format specified int the scanf statement like %d, %f, %s, etc.

A: There are several. One is that gets() will only get character string data. Another is that gets() will get only one variable at a time. scanf() on the other hand is a much, much more flexible tool. It can read multiple items of different data types.
In the particular example you have picked, there is not much of a difference.

A: gets:->

gets() reads a line from stdin into the buffer pointed to  by  s  until either a terminating newline or EOF, which it replaces with a null byte ('\0').

BUGS:->

Never use gets(). Because it is impossible to tell without knowing the data in advance how many  characters  gets() will  read,  and  because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has  been  used  to  break  computer security.  Use fgets() instead.

scanf:->

The scanf() function reads input from the standard input stream stdin;

BUG:->

Some times scanf makes boundary problems when deals with array and string concepts.

A: The basic difference [in reference to your particular scenario],

*

*scanf() ends taking input upon encountering a whitespace, newline or EOF

*gets() considers a whitespace as a part of the input string and ends the input upon encountering newline or EOF.
However, to avoid buffer overflow errors and to avoid security risks, its safer to use fgets().

A: In case of scanf you need that format mentioned, unlike in gets. So in gets you enter charecters, strings, numbers and spaces.
In case of scanf , you input ends as soon as a white-space is encountered.
But then in your example you are using '%s' so, neither gets() nor scanf() that the strings are valid pointers to arrays of sufficient length to hold the characters you are sending to them. Hence can easily cause an buffer overflow.
Tip: use fgets() , but that all depends on the use case

A: The concept that scanf does not take white space is completely wrong. If you use this part of code it will take white white space also :
#include<stdio.h>
int main()
{
char name[25];
printf("Enter your name :\n");
scanf("%[^\n]s",name);
printf("%s",name);
return 0;
}

Where the use of new line will only stop taking input. That means if you press enter only then it will stop taking inputs.
So, there is basically no difference between scanf and gets functions. It is just a tricky way of implementation.

A: scanf() is much more flexible tool while gets() only gets one variable at a time.

A: gets() is unsafe, for example: char str[1]; gets(str)
if you input more then the length, it will end with SIGSEGV.
if only can use gets, use malloc as the base variable.


text:
Q: EOFError: EOF when reading a line (Python 3.11) Hello StackOverflow Community,
I'm struggling in resolving an EOFError: EOF when reading a line ERROR I've been hitting in my code for some reason and I've tried some possible ways to solve it I could find, ex. try/except function, but couldn't resolve it anyway, so that I'm asking you If you could help me on resolving this issue.
Here is the ERROR:
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.181.0_x64__qbz5n2kfra8p0\Lib\multiprocessing\process.py", line 314, in _bootstrap
    self.run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.181.0_x64__qbz5n2kfra8p0\Lib\multiprocessing\process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\grego\Documents\GitHub\notes-app\Noti.py", line 17, in checkPath
    takeQuickiPy()
  File "C:\Users\grego\Documents\GitHub\notes-app\Noti.py", line 23, in takeQuickiPy
    quickiPy = input(">    ")
               ^^^^^^^^^^^^^^
EOFError: EOF when reading a line

Here is the full code:
import os
import multiprocessing as mp
from os import listdir
import simple_chalk as chk

path = "./QuickiPies"
pathBoolean = os.path.exists(path)
quickiPy = "null"

def checkPath():
    if pathBoolean == False:
        os.mkdir(path)

    takeQuickiPy()

def takeQuickiPy():
    print(chk.greenBright.bold(
        "Welcome to NotiPy! By pressing Ctrl+Shift+S your QuickiPy will be saved to the QuickiPy directory. Open an existing QuickiPy with Ctrl+Shift+O."))
    quickiPy = input(">    ")

def checkShortcut():
    while True:
        if kd.is_pressed("ctrl+shift+o"):
            listDir()
            break
        elif kd.is_pressed("ctrl+shift+s"):
            saveQuickiPy()
            break

def listDir():
    print("Choose your QuickiPy:")
    for i in listdir(path):
        print(i)

def saveQuickiPy():
    file = open(path + "/" + "note.txt", "w")
    file.write(quickiPy)
    file.close()
    print(chk.greenBright.bold("QuickiPy saved!"))

if __name__ == '__main__':
    jobs = []
    process1 = mp.Process(target=checkPath)
    jobs.append(process1)
    process2 = mp.Process(target=checkShortcut)
    jobs.append(process2)
    process1.start()
    process2.start()

PS: The program is supposed to be a notepad terminal-like program in which you are prompted to write input, but when Ctrl+Shift+S is hit, the program will save the input into a file, and if Ctrl+Shift+O is hit, the program will list all the files available in the directory to open (this function isn't implemented for now).
Thank you for any possible solutions.

A: Instead of using multiprocessing, you should use threading as multiprocessing does not wait until a user input is given on the input() function.
You should see multiprocessing as a single processing line handling multiple processes at the same time without waiting for any of those processes' long tasks to finish. On the other hand, threading is like having various processing lines each at its own speed that allows waiting for individual processing tasks to finish.
Because you were using multiprocessing, the while True loop and the input() function were colliding and python responded with a EOF (End Of File) error in the input() process. You should adjust your code as follows:
import os
from threading import Thread
from os import listdir
import simple_chalk as chk

path = "./QuickiPies"
pathBoolean = os.path.exists(path)
quickiPy = "null"

def checkPath():
    if pathBoolean == False:
        os.mkdir(path)

    takeQuickiPy()

def takeQuickiPy():
    print(chk.greenBright.bold(
        "Welcome to NotiPy! By pressing Ctrl+Shift+S your QuickiPy will be saved to the QuickiPy directory. Open an existing QuickiPy with Ctrl+Shift+O."))
    quickiPy = input(">    ")

def checkShortcut():
    while True:
        if kd.is_pressed("ctrl+shift+o"):
            listDir()
            break
        elif kd.is_pressed("ctrl+shift+s"):
            saveQuickiPy()
            break

def listDir():
    print("Choose your QuickiPy:")
    for i in listdir(path):
        print(i)

def saveQuickiPy():
    file = open(path + "/" + "note.txt", "w")
    file.write(quickiPy)
    file.close()
    print(chk.greenBright.bold("QuickiPy saved!"))

if __name__ == '__main__':
    jobs = []
    process1 = Thread(target=checkPath)
    jobs.append(process1)
    process2 = Thread(target=checkShortcut)
    jobs.append(process2)
    process1.start()
    process2.start()


text:
Q: Android find difference between two ImageView I am developing a puzzle game like find differences on images in Android (Java).
So how can i know, where user touched on image, and is it right place where user touched.

A: make some CustomView extends View and override onTouchEvent method. or handle all touch events in Activity by overriding dispatchTouchEvent. you can obtain precise point of touch/action with getX() and getY() methods of MotionEvent (which is an object passed to both methods mentioned above), now its your turn to do some math and calculate which item has been touched (by default Activity is dispatching touch events to its layout e.g. inflated from XML)


text:
Q: Python - How do i delete more than one character on python using slice method, find and rfind I need some help in removing two sets of curly brackets with string.Right now it's only removing one set. I tired to use find and rfind to find the first and last occurence of the string index and using slice method to cut out the curly brackets but it can only remove one set of it.
It should work something like that
Input: {fefeef}this{feofeow}.4849
Output this.4849
Here is my code
 def help_mmtf():

       while True:

           user_input = input("Filename?")
           text_input = str(user_input)

           if (text_input !=""):

                word = text_input

                index1 = word.find("{")
                index2 = word.find("}")
                print(index1)
                print(index2)

                index3 = word.rfind("{")
                index4 = word.rfind("}")

                print(index3)
                print(index4)

                splice_input = text_input[:index1] + text_input[index4+1:]
                print(f'"{splice_input}"')

      else:

               break

A: Use sub function from re module:
import re

s = "{fefeef}this{feofeow}.4849"
out = re.sub(r'{[^}]*}', '', s)

Output:
>>> out
'this.4849'

For more explanation: Regex101

A: You can use sub
import re

def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            word = text_input

            splice_input = re.sub("\{.*?\}", "", word)
            print(f'"{splice_input}"')

        else:

         break

Time complexity: O(2^m + n).
or you can use the for loop
def help_mmtf():
    while True:

        user_input = input("Filename?")
        text_input = str(user_input)

        if (text_input != ""):
            splice_input = ''

            paren = 0
            for ch in text_input:

                if ch == '{':
                    paren = paren + 1
                    splice_input = splice_input

                elif (ch == '}') and paren:
                    splice_input = splice_input
                    paren = paren - 1

                elif not paren:
                    splice_input += ch

            print(splice_input)

        else:

         break

Time complexity: O(n).


text:
Q: VBA Macro If cell found in multiple cells then i need help with the below if then statement.  will try and explain as best as i can.
cells E21 and F21 is merged and the value varies.  i have a list of numbers underneath each other from o1 to o100 and the same for p q r s t u that the values are constant.
i need a macro to check in which column the value in cell E21 is and put the number (that is in the macro) in cell E23(also merged with F23).
below is the macro that works if it only checks cell o1 but it does not work if i change it to o1:o100.  the macro is very basic and only the first piece.  please can you tell me how to get the macro to search the entire list.
Sub RunSelect()

    If Range("E21").Value = Range("o1:o100").Value Then
        Range("E23").Value = "3"

    ElseIf Range("E21").Value = Range("p1:p100").Value Then
        Range("E23").Value = "4"

    Else: MsgBox ("Incorrect number entered")

    End If

End Sub

thanks for all the help

A: I'm not ENTIRELY sure what you're looking for, but you need to write a For Each...Next loop to loop through each cell and check it's value. Excel doesn't know you want to look at each cell in those ranges, therefore you need to tell it to using a loop.
Trying working with this.
For Each c In Worksheets("Sheet1").Range("O1:O100").Cells
     If c.Value = Range("E21").Value Then Range("E23").Value = "3"
        Next

http://msdn.microsoft.com/en-us/library/office/aa221353(v=office.11).aspx


text:
Q: Installed applications are not working or unable to uninstall I have few applications which were working properly, suddenly those applications logos are missing only name shown in the application list. When I click those applications it shows like opening but not. So, I tried to uninstall but it failed with the result
sudo apt-get remove --purge sublime-text
[sudo] password for yasithan:
Reading package lists... Done
Building dependency tree
Reading state information... Done

No apt package "sublime-text", but there is a snap with that name.
Try "snap install sublime-text"

E: Unable to locate package sublime-text

But when i try to install it
snap install sublime-text
snap "sublime-text" is already installed, see 'snap help refresh'

Please help me with this issue.
And please let me know if any feather details required.
Thanks in advance.

A: snap & apt are different tools
apt manages packages (debian-type packages as ubuntu uses)
snap allows to install software in another way
some software is available in both formats and then you should use one or the other
to remove a snap : sudo snap remove
to install a snap : sudo snap install
some snaps require the --classic option when installing : sudo snap install sublime-text --classic
list installed snaps : sudo snap list


text:
Q: VBA Send Email Notification when User Login Success or Error in UserForm Option Explicit
Private Trial As Long
Private Sub cmdCheck_Click()
    'Declare the variables
    Dim AddData As Range, Current As Range
    Dim user As Variant, Code As Variant
    Dim PName As Variant, AName As Variant
    Dim ws As Worksheet, ws2 As Worksheet, ws3 As Worksheet
    Dim result As Integer
    Dim TitleStr As String
    Dim msg As VbMsgBoxResult

    'Variables
    user = Me.txtUser.Value
    Code = Me.txtPass.Value
    TitleStr = "Password check"
    result = 0
    Set Current = Sheet2.Range("U8")

    'Error handler`enter code here`
    On Error GoTo errHandler:
    'Destination location for login storage
    Set AddData = Sheet2.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0)
    'Check the login and passcode for the administrator
    If user <> "" And Not IsNumeric(user) And Code <> "" And IsNumeric(Code) Then
        For Each AName In Sheet2.Range("Z8:Z108")
            'If AName = Code Then 'Use this for passcode text
            If AName = CLng(Code) And AName.Offset(0, -1) = user Then ' Use this for passcode numbers only
                MsgBox "Welcome Back: – " & user & " "

                'record user login
                AddData.Value = user
                AddData.Offset(0, 1).Value = Now
                'Add usernmae to the worksheet
                Current.Value = user
                'Change variable if the condition is meet
                result = 1
                'Unload the form
                Sheet2.Visible = True
                Sheet2.Select
                Unload Me
                'Show the navigation form
                'frmNavigation.Show
                Exit Sub
            End If
        Next AName
    End If

    'Check user login with loop
    If user <> "" And Not IsNumeric(user) And Code <> "" And IsNumeric(Code) Then
    For Each PName In Sheet2.Range("H8:H108")
        'If PName = Code Then 'Use this for passcode text
        If PName = CLng(Code) And PName.Offset(0, -1) = user Then ' Use this for passcode numbers only
            MsgBox "Welcome Back: – " & user & " "
            'record user login
            AddData.Value = user
            AddData.Offset(0, 1).Value = Now
            'Add usernmae to the worksheet
            Current.Value = user

            'unhide worksheet for user
            If PName.Offset(0, 1) <> "" Then
                Set ws = Worksheets(PName.Offset(0, 1).Value)
                ws.Visible = True
            End If

            'show sheet tab if hidden
            ActiveWindow.DisplayWorkbookTabs = True

            'Change variable if the condition is meet
            result = 1
            'Unload the form
            Unload Me
            'Show the navigation form
            'frmNavigation.Show
            Exit Sub
            End If
        Next PName
    End If

    'Check to see if an error occurred
    If result = 0 Then
        'Increment error variable
        Trial = Trial + 1
        'Less then 3 error message
        If Trial < 3 Then msg = MsgBox("Wrong password, please try again", vbExclamation + vbOKOnly, TitleStr)
        Me.txtUser.SetFocus
        'Last chance and close the workbook
        If Trial = 3 Then
            msg = MsgBox("Wrong password, the form will close…", vbCritical + vbOKOnly, TitleStr)
            ActiveWorkbook.Close False
        End If
    End If
    Exit Sub
    'Error block
    errHandler:
    MsgBox "An Error has Occurred " & vbCrLf & "The error number is: " _
    & Err.Number & vbCrLf & Err.Description & vbCrLf & _
    "Please notify the administrator"
End Sub

Can someone help me modify this code to include Email Notification whenever the user successfully or attempted to enter a wrong password in the user form? If we can have the user name and date and time of login access.
I found this code but I don't know how and where to include it?
Private Sub SendMail_Click()
    Dim OutApp As Outlook.Application
    Dim OutMail As Outlook.MailItem
    Dim strbody As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(olMailItem)

    strbody = "Hi Admin," & vbNewLine & vbNewLine & _
              "Message Line 1" & vbNewLine & _
          "Username:" & vbNewLine & _
          "Password:"

    On Error Resume Next
    With OutMail
        .To = "email address"
        .CC = ""
        .BCC = ""
        .Subject = "Message Request"
        .Body = strbody
        .Send

    End With
    On Error GoTo 0
    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Any help is very much appreciated.
Thanks,
Mielkew


text:
Q: NSSetUncaughtExceptionHandler not firing in Swift 3? I'm trying to catch all NSExceptions in a Swift3 program - have been following this Stack Overflow answer
So I've got this:
override func viewDidLoad() {
    super.viewDidLoad()
    NSSetUncaughtExceptionHandler { exception in
        print("EXCEPTION CAUGHT HERE....")
        print(exception)
        print(exception.callStackSymbols)
    }

    // force NSException
    let array = NSArray()
    _ = array.object(at: 99)

}

but the exception's not being called
Instead I get this output:

2016-09-04 14:49:14.252 catchAllErrorsTest[8126:164827] Failed to set
  (contentViewController) user defined inspected property on (NSWindow):
  *** -[__NSArray0 objectAtIndex:]: index 99 beyond bounds for empty NSArray

I also tried putting the exception into AppDelegate (in applicationWillFinishLaunching and applicationDidFinishLaunching), but same result

A: I did as follows and works for me in Swift 3.
Define your NSSetUncaughtExceptionHandler as a constant outside any method declaration in your AppDelegate:
let uncaughtExceptionHandler : Void = NSSetUncaughtExceptionHandler { exception in
NSLog("Name:" + exception.name.rawValue)
if exception.reason == nil
    {
        NSLog("Reason: nil")
    }
    else
    {
        NSLog("Reason:" + exception.reason!)
    }

}

This fires at any uncaught exception as this constant is evaluated as soon as your App Delegate instance loads i.e. at app launch.
Note: the Void type declaration removes a compiler warning for a Void inferred type that "could be unexpected" ;-) .


text:
Q: Block android watch batery ambient mode There is an ambient state that my watch goes into when it is on the charger that dims slightly but keeps the normal color depth.
And another ambient mode that the watch enters on battery with reduced color depth.
Some of the colors on my ambient palate are brighter in the reduced depth, others go black and do not show.
Is there a way to force the ambient mode that does not reduce the color depth?

A: Is there a way to force the ambient mode that does not reduce the color depth?
I think not. It would help if we have an idea what's happening when an Android Watch goes to Ambient mode.

Ambient
  mode
  helps the device conserve power. Your design should make clear to the
  user that the screen is in ambient mode. The background color scheme
  is strictly limited to black, white, and grays. Your watch face may
  use some color elements on screens that support it provided it is
  unambiguous that the device is in ambient mode. You can use color
  elements for up to 5 percent of total pixels. In this mode, the screen
  is only updated once every minute. Only show hours and minutes in
  ambient mode; do not show seconds. Your watch face is notified when
  the device switches to ambient mode, and you should thoughtfully
  design for it.

So, your watch losing the vivid colors in Ambient mode is it's way of conserving battery power.
You can also read more about Ambient mode here.


text:
Q: How can I include another js file file in today's v8? I find an old anwser and later updates here, but it is hard for me to adapt this code to the latest(2020) V8 version.
There are many difficulties that I encounter:

*

*String::New is removed and now a String::NewFromUtf8Literal needs an Isolate* isolate which I don't know how to pass to function Include, should I just add this before const Arguments& args?

*Script::Compile takes a Context object as paramater now

*And I don't know where to put the last two line codes
Handle<ObjectTemplate> global = ObjectTemplate::New();
global->Set(String::New("include"), FunctionTemplate::New(Include));

-- UPDATE --
After some work, I have my code like the this.
However, it still won't compile because of there errors:

*

*Seems that I can't get a Local from a Persistent, even I have used danijar's strategy. Maybe it is because I have not used the constructor, but I don't think I can construct a Persist here inside this function scope.
samples/import.cc:74:103: Error:cannot convert 'v8::Local<v8::Context>' to 'v8::Context*'
   74 |     global_context = v8::Persistent<v8::Context, CopyablePersistentTraits<v8::Context>>::New(isolate, local_context);
      |                                                                                ^~~~~~~~~~~~~
      |                                                                                |
      |                                                                                v8::Local<v8::Context>

*There are some errors with String::NewFromUtf8Literal here
samples/import.cc:34:110: Error:'static v8::Local<v8::String> v8::String::NewFromUtf8Literal(v8::Isolate*, const char*, v8::NewStringType, int)' is private within this context
   34 |   Handle<String> source = String::NewFromUtf8Literal(args.GetIsolate(), buff, v8::NewStringType::kNormal, len);
      |

A:
I don't know how to pass to function Include, should I just add this before const Arguments& args?

No, you can't modify the signature of functions that will be called from JS, but you don't need to: FunctionCallbackInfo (which is the replacement for Arguments) has a GetIsolate() method.

Script::Compile takes a Context object as parameter now

Since you're having a question about this, I'm guessing you're only using a single Context for everything. Just store it in a v8::Persistent, and create a v8::Local from it whenever you need it. (For the time being, you can also use the deprecated Isolate::GetCurrentContext(), but for newly written code I would advise against that, as you'd only create more work for yourself in the future when you have to migrate away from it.)

I don't know where to put the last two line codes

Wherever you're setting up the global object, somewhere in the startup sequence of your app.
All of these questions (and more) could be answered by studying the "shell" sample app that the V8 project maintains: https://chromium.googlesource.com/v8/v8/+/master/samples/shell.cc.
In particular, its Load function does pretty much what you want.


text:
Q: UICollectionView scrollToItemAtIndex after button action executed When the currentViewController is popped I want to scroll the UICollectionView in the mainViewController to the index of the item which the currentViewController was currently at. I've tried implementing this in viewWillDisappear of the currentViewController but nothing happens when the back button action is executed.
   override func viewWillDisappear(animated : Bool) {
        super.viewWillDisappear(animated)
        if (self.isMovingFromParentViewController()){
            let parent = parentViewController as! UINavigationController
            let child = parent.childViewControllers[0] as! MainViewController
            child.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex, inSection: 0), atScrollPosition: .Top, animated: true)
        }
    }

A: since you are not dismissing but popping the viewcontroller something like this should work:
override func viewWillDisappear(animated: Bool) {
    if let mainViewController = navigationController?.topViewController as? MainViewController {
        mainViewController.collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex, inSection: 0), atScrollPosition: .CenteredVertically, animated: false)
    }
    super.viewWillDisappear(animated)
}

A: When your currentViewController is dismissed, then ViewWillAppear of mainViewController will be called. Here you can implement the scrollToItemAtIndexPath with condition check that viewwillappear was called from currentVC was dismissed not when mainVC was launch from other sources.

A: Ended up created a protocol which was a lot more manageable that writtig everything in the viewWillDisappear of the childVC. Thank you André Slotta for the suggestion.
protocol CurrentIndexDelegate{
    func setCurrentIndex(index: Int?)
}

class ChildViewController: UIViewController{
    var currentIndexDelegate : CurrentIndexDelegate? = nil
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        if currentIndexDelegate != nil {
            currentIndexDelegate!.setCurrentIndex(currentIndex)
        }
    }
}

class MainViewController: UIViewController, CurrentIndexDelegate{
    var currentIndex: Int?
    func setCurrentIndex(index: Int?){
        currentIndex = index!
    }
    override func viewWillAppear(animated: Bool) {
        //Current index is set from delegate
        if(currentIndex != nil){
            collectionView?.scrollToItemAtIndexPath(NSIndexPath(forItem: currentIndex!, inSection: 0), atScrollPosition: .Top, animated: true)
        }
    }

}


text:
Q: How to match elements in a ClassName with jQuery I have a random number of elements (which can be divs, headers and so on) with a particular class.
I need to split that class into maximum 4 words but I can't get any result.
I want to let people custom this plugin. The first number is the number of column, and the second number is the max width desired to reset this plugin
I'm coding this way:
//HTML

//JS
$( document ).ready(function() {
    $( '[class*=boo-]' ).each(function() {
        var boo = $( this );
        var n = parseInt( boo.attr( 'class' ).match( /boo-(.*)/ )[1] );
        var booReset = boo.attr( 'class' ).match( /foo/ );
        var numb = boo.attr( 'class' ).match( /foo-(.*)/ );
    });
});

the variable n returns the X number.
the variable booReset returns the ["foo"] or null value.
the variable numb returns ["foo-Y", "Y"] and I only need the Y number.
I need to parse the Y integer.
I tried by doing the same thing as the n variable but the console returns "TypeError: boo.attr(...).match(...) is null". Why?
I tried in other way like:
/.?<=reset/ returns null
/(.$)?<=reset/ returns null
anything I do is always NULL!
Is there a way to section the class-name according to hyphens?
foo-X-boo-Y
should be
foo, x, boo, y
and then work with these four variables?
here the fiddle with the entire JS
http://jsfiddle.net/dcdeiv/yAn5K/3/

A: How about that: Split the class names by the -character and filter out any non-numeric values.
Like so:
$( '[class*=boo-]' ).each(function() {
      var boo = $( this );
      var className = boo.attr("class");
      var numbersInClassName = $.grep(className.split("-"),function(item){
          var num = parseInt(item);
          return !isNaN(item);
      });
      console.log(className + ": " + numbersInClassName);
});

Here's a modification of your original fiddle: http://jsfiddle.net/yAn5K/7/

A: As I understand it you want to parse out the X and Y numbers, and do some logic based on them. If so then you need to do a string split:
var tokens = "foo-1-boo-2".split("-");
// => ["foo", "1", "boo", "2"]

var tokens = "foo-42".split("-");
// => ["foo", "42"]

Then you can handle the cases using the global function parseInt().
As for HTML, don't forget that divs can have many classes. You can handle that case with another string split (on " " this time).

A: I would use String.split(delimiter)
var pieces = $(this).attr('class').split('-');
console.log(pieces);
> ['foo', 'X', 'boo', 'Y']

So now you have an array (pieces) of all the words in the classname.

A: parsing the class seems a bit strange. Would it be an option to use data attributes?
e.g.

var n = $(".foo-X-boo-Y").data("X")


text:
Q: Well-definedness of translation functor Fix $\eta, \nu \in \mathfrak{h}^*$ and write
$pr_\eta$ and $pr_\nu$ for the natural projections of the category $\mathcal{O}$ onto $\mathcal{O}_{\chi_\eta}$ and $\mathcal{O}_{\chi_\nu}$. If $L$ is finite
dimensional and $M \in \mathcal{O}$, then $M \mapsto pr_
\nu \left(L \otimes (pr_\eta M)\right)$ followed by inclusion into $\mathcal{O}$ defines an exact functor $\mathcal{O} \to \mathcal{O}$.
Its restriction to $\mathcal{O}_{\chi_\eta}$ (without the inclusion) relates  the two subcategories $\mathcal{O}_{\chi_\eta}$ and $\mathcal{O}_{\chi_\nu}$.
Write $T^\nu_\eta$ for the resulting functor
on $\mathcal{O}$ (or on $\mathcal{O}_{\chi_\eta}$). We call $T^\nu_\eta$ a translation functor.
My question: The definition of a translation functor $T^\nu_\eta$ depends on the choice of a finite dimensional module $L$, how to show it is well-defined?

A: Jantzen first defined translation functors around 1977, using a definite finite dimensional module, in 2.10 of his Habilitationsschrift here.    Note that at around the same time, Gregg Zuckerman was also considering tensor products with finite dimensional modules in the Lie group representation framework here.  The ideas in both constructions are similar but independent, and the use of a finite dimensional representation is quite specific.
Chapter 7 of my 2008 AMS textbook (with corrections!) follows the same pattern.    But note that the Jantzen idea of crossing walls does require a choice of weight in the wall involved: see 7.15 in my book.   This seems to need input from Jantzen's student Soergel, which still leaves an open question as to methodology:   Is there a simpler method of wall-crossing?


text:
Q: How do I use the 'to' and 'from' property for a bootstrap carousel? On the documentation page for bootstrap's carousel there is a property for on under the events tab but I don't know the syntax to use it and can't find any examples.
From bootstrap's carousel documentation:
Bootstrap's carousel class exposes two events for hooking into carousel functionality. Both events have the following additional properties:
from: The index of the current item
to: The index of the next item


text:
Q: Calling a python program from an external link and communicating with it I have no idea if this has an official name, nor do I know a better way to really describe what I'm going for here so I'll list the two things I'd like to accomplish.
In a nutshell I have a task management program that emails people when they've been assigned a task. What I'd like is some way to generate a link (html or otherwise) that can be clicked that will either:

*

*Launch the program with some command-line arguments, or

*If the program is already open, communicate some commands to it, so that it could be, perhaps, set as the top window and then it could switch to the task.
I know this must be possible, but I have not yet gleaned the knowledge of how to communicate with programs outside of themselves. Any ideas? Thanks in advance!

A: I use tools like itty and flask to implement this kind of functionality.
For example, using itty here's how you could launch a program with some command-line arguments:
from itty import *

@post('/someprogram/(?P<args>\w+)')
def launcher(request, args):
    'Launch a program with some command-line arguments'
    return subprocess.check_output('someprogram', shlex.split(args))

run_itty()

The front-end for this could be a simple web page with an html form to get command-line arguments and a submit button to make the POST request.
This approach works equally well over a local network or over the web.


text:
Q: Methods for scheduling I am working on a PHP application for an at home care company. They have x amount of carers that are scheduled every week to attend the houses of x amount of service users (clients). Each service user has a set 'schedule' of when they are to be visited which includes periods plus the visit duration in minutes.
So for example, a service user could have the following schedule.
      AM   Lunch   Tea   Late   Night   Respite
Mon   30m  -       30m   60m    -       -
Tue   30m  -       -     60m    -       -
Wed   20m  25m     30m   60m    120m    -
Thu   -    -       30m   -      -       -
Fri   30m  25m     -     -      -       -
Sat   -    -       -     -      -       -
Sun   20m  25m     -     -      -       -

These periods are currently stored in a database in the following format:
Table: Service_user_schedules
id   service_user_id   day   period   duration

Every week, the carers fill out a table of what periods they are available to work. This data is then input into the system and is stored in the database in the following format:
Table: Carer_available_shifts
id   carer_id   day   period

Now the problem is, I need to create a controller that will take this data and automatically assign carers to service users based on the availability they have supplied. This needs to be editable so that in the event that nobody is available for a particular carer, the user can select one that isn't available and they will still be added to the database.
At the moment, I have a mess of loops, functions and echo's to check if carers are available for a particular service user and to make it editable.
Has anyone performed this sort of task before and if so, did you find a simple way to complete it. I would prefer to make it object orientated so I could reuse the same generic class but at the moment, I'm at a complete loss!
EDIT: I have now added a bounty to this question. I am currently researching genetic algorithms (something that I have never even heard of let alone used!) as a solution to this problem based on some of the answers. I would like to know if any of you have used other methods of solving this type of problem or if you have used genetic algorithms, could you provide a less general explanation on how you applied them to this particular issue.
I would assume that this hurdle would be fairly common in many "staffing" type applications  and am surprised at how little discussion there is on this anywhere on the web!
UPDATE
For this particular project, I think I may end up using the database method as described by Tak but may possibly convert to the use of GA's in the future when I have more development time set aside.
I am now at a bit of a loss as to who to award the bounty to. duedl0r put alot of effort into his (or her) answer. It has given me a great insight into the world of Genetic Algorithm's - a problem solving method that I had never come across before. However, the answer provided by Tak provides the solution that I will be using for this project. Therefore, I have awarded the bounty to Tak.

A: Sounds like the employee shift rostering problem, which is NP-complete.
If you think metaheuristics (such as genetic algorithms, tabu search, simulated annealing, ...) is overkill, then just go for a simple First Fit Decreasing algorithm.

A: Maybe you can use a genetic algorithm. This has the advantage that you can do really crazy stuff (if you have set up the basics), e.g. you could also say that a carer should optimally visit a service user he used to visit before, or minimize the distance between visits :)
Doing it like that every service user gets a carer even if there is no available schedule.
The algorithm just tries to create a optimal solution..
Probably it's a bit overkill, but it's an interesting topic.. :) I wanted to mention it because it may be a new way to tackle your problem. At least worth a thought ;)
Some Links:
Genetic Algorithm Resource, Genetic Algorithm Tutorial, Wikipedia

Edit: More concrete explanation of genetic algorithms.
A genetic algorithm consists of modelling the theory of evolutionary development. Evolutionary development needs a population of certain creatures. Then you simulate the development of the population using certain biological effects like mutation, selection, crossing etc.. Like darwin found out a few years ago :)
Now you have to map your problem to such a creature (or a DNA). This means every creature represents a solution in your problem space (every DNA is a solution to your problem).
So the phrase "survival of the fittest" just means "I get a solution to my problem which might be optimal" (not guaranteed though).
A mapping from your problem to such a DNA can be done very differently. First you need an array to represent your DNA. You can specify for example this:
You create chunks of 42 elements for every service user (6 slots per day, 7 days a week). Then your first entry in the array is the "AM"/Mon slot for service user 1. Your second entry the "Lunch"/Mon slot for service user 1. Your 43th entry is the "AM"/Mon slot for service user 2. This defines the DNA of your creature. Then you let them hump each other so they can develop :)
In order to find out which creature is well fitted, you also need a formula which calculates the fittness. You create a formula which has a DNA as input and a number as output. This is depending on your rules. For example you can give some plus or minus points if there are certain rules holding or not. If a carer is used for two different service user at the same time you give some minus points, if a carer has actually time for a slot and he is really scheduled for a service user you can give plus points.
You can also say: A genetic algortihm tries to find out how to maximize this formula using a genetic approach.
Very short introduction to genetic algorithms..if you have enough time and if you're also interested in the topic it's really worth digging into it.. you can some really cool stuff with it. But keep in mind, it can get also messy and complicated :)

A: I'd approach it like this. First a database table that links schedule slots to available carers...
Table schedules_shifts
id   service_user_schedules_id   carer_available_shifts_id

Now a function that matches available carers to required schedule slots and populates the table...
* Fetch service_user_schedules for the next week
* For each service_user_schedules row
 * Fetch carer_available_shifts that match the schedule slot
 * For each carer_available_shift row
  * If results
   * Fetch schedules_shifts rows where carer_available_shifts_id is already used
   * If no results
    * Insert a row in the schedules_shifts table for each carer
   * Otherwise carer is busy, do nothing and continue
  * If no results, flag for review or trigger e-mail to manager, or other action
* Trigger e-mail or save log of completion for peace of mind

The new table now has possible carer matches for schedule slots with no duplicate allocation of a carer's time. It does however match multiple carer's shifts with a schedule slot. This could be a feature! Leave them as-is and add a confirmed column on schedules_shifts so a manager can manually assign the work, or carers can volunteer, or automatically mark the first match as confirmed and keep the other rows as alternatives in case the first carer can't make it.
This can all be triggered by a cron every week, or when the final career updates their week's schedule. Probably the first because users are often unpredictable.
Now the automated data is in a table you can open it up for editing. Create a normal admin console as you would to change the rows in schedules_shifts as appropriate, or flag different rows "confirmed".
Translating it into a generic class shouldn't be too difficult - just a matter of using generic terminology. It's late and I can't think of any though :)
It's possible to do all the data sifting in PHP arrays rather than the database dance I've created above, but I think SQL is more appropriate for sorting through the data and making amendments.
Genetic algorithms sound interesting though, and if you've got the time investigate them ^_^
Hope that helps?


text:
Q: Need to apply same left alignment to multiple line text Simple question for CSS experts:
Have a look here:
http://jsfiddle.net/TFU4U/
The text is currently appearing like this:
* Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum:

I need to make it look like this, by only changing the CSS being used:
* Lorem Ipsum Lorem Ipsum Lorem Ipsum
  Lorem Ipsum Lorem Ipsum Lorem Ipsum:

How can I do that ?
EDIT:
If really needed, the HTML code can also be changed.
But I cannot use .required CSS rule, because that is already being used elsewhere, and if I change that, it will cause other problems ..

A: Add a margin to your paragraphes and position your spans absolutely. Here's a demo.

    *

Lorem ipsum

Lorem ipsum

CSS
.wrapper {
  position: relative;
}

.x span {
  position: absolute;
  left: 0;
}

.x p {
  margin-left: 50px;
}

A: Why dont you use li element to achieve this? It does what you are after...
jsfiddle example
CSS
.option-l li {
    clear: both;
    float: left;
    width: 50%;
    margin-left: 20px;
}
.option-r {
    margin-left: 60%;
}

HTML
Remove the span and just use li

Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum:

A: HTML

*Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.

CSS
#test {
    padding-left: 15px;
    position: relative;
}

#test span {
    position: absolute;
    left: 0;
}


text:
Q: Energy density of components as a function of the scale factor In Barbara Ryden's Intro to Cosmology, she says that, since we can write the energy density of the universe as $\varepsilon(t) = \sum\limits_{w}\varepsilon_w$, where $w$ runs over the possible equation-of-state parameters of different parts of the universe, and also $P = \sum\limits_{w}w\varepsilon_w$ (from the equation-of-state), then the fluid equation
$$
\dot{\varepsilon} + 3\frac{\dot{a}}{a}\left(\varepsilon + P\right) = 0
$$
should hold for each component separately, as long as there is no interaction between the different components.
She then concludes that the energy density of matter falls like $a^{-3}$ and of radiation as $a^{-4}$.
In a latter chapter in her book, when she talks about recombination and decoupling, where matter and radiation clearly interact, she also states that the number density of matter falls like $a^{-3}$. But since matter and radiation do interact, then above conclusion that the fluid equation holds for every component separately, fails.
How, then, can she safely say that the energy density of matter, at the epoch of recombination and decoupling, falls like $a^{-3}$?

A: The universe switched from radiation dominated to matter dominated about 50,000 years after the Big Bang. See How long was the universe radiation dominated? for the details of the calculation. However recombination happened about 380,000 thousand years after the Big Bang and by then the energy density of radiation made a negligible contribution to the total energy density. That's why Ryden can safely ignore the radiation.
If you were looking at times near the switchover, i.e. around 50,000 years after the Big Bang, then you're quite correct that you would need to include the contributions from both matter and radiation, and the scaling would be somewhere between $a^{-4}$ and $a^{-3}$.


text:
Q: Как сдвинуть ячейки таблицы к правому краю? Имеется таблица с примерно такой структурой строк:

3начение_1 3начение_2 3начение_3 3начение_4 3начение_5  3начение_6 3начение_7
3начение_1 3начение_2
3начение_1
3начение_1 3начение_2 3начение_3
3начение_1 3начение_2 3начение_3 3начение_4 3начение_5  3начение_6 3начение_7
3начение_1 3начение_2
3начение_1

Нужно их сместить к такому виду:

3начение_1 3начение_2 3начение_3 3начение_4 3начение_5 3начение_6 3начение_7
                                                       3начение_1 3начение_2
                                                                  3начение_1
                                            3начение_1 3начение_2 3начение_3
3начение_1 3начение_2 3начение_3 3начение_4 3начение_5 3начение_6 3начение_7
                                                       3начение_1 3начение_2
                                                                  3начение_1

Вручную сместить можно, но если строк за тысячу и больше, то на это уйдет  довольно много времени.
Как при помощи макроса реализовать подобный сдвиг?

A: Как-то так, без проверок и ограничений:
Sub OffsetData()
Dim rRng As Range, ArrData()
Dim lClmns As Long, lCnt As Long
Dim bFlag As Boolean
Dim i As Long, j As Long, p As Long, k As Long
    Set rRng = Application.InputBox("Выделить диапазон данных", "", , Type:=8)
    ArrData = rRng.Value: lClmns = UBound(ArrData, 2)

    For i = 1 To UBound(ArrData) ' по строкам
        k = 0: bFlag = False

        For j = lClmns - 1 To 1 Step -1 ' поиск первого правого значения
            If ArrData(i, j) <> Empty Then ' найдено первое правое значение
                For p = j To 1 Step -1 ' перенос значений
                    ArrData(i, lClmns - k) = ArrData(i, p) ' переносим значение
                    ArrData(i, p) = Empty ' удаляем значение
                    k = k + 1: bFlag = True
                Next p

                If bFlag Then Exit For ' переходим на следующую строку
            End If
        Next j
    Next i

    rRng.Value = ArrData
End Sub

A: Dim i As Integer, j As Integer
Dim ws As Worksheet
Dim maxColumn As Integer, valuesColumn As Integer

Set ws = ThisWorkbook.Worksheets("Нужный Лист")
maxColumn = ws.UsedRange.Columns.Count ' Максимальное кол-во столбцов
For i = 1 To ws.UsedRange.Rows.Count
    ' количество столбцов со значениями в текущей строке
    valuesColumn = WorksheetFunction.CountA(ws.Range(ws.Rows(i).Address))
    If valuesColumn < maxColumn Then
        For j = 1 To maxColumn - valuesColumn
            ws.Cells(i, 1).Insert shift:=xlToRight
        Next j
    End If
Next i

Set ws = Nothing


text:
Q: Stieltjes Integral meaning. Can anybody give a geometrical interpretation of the Stieltjes integral:
$$\int_a^bf(\xi)\,d\alpha(\xi)$$
How would we calculate?
$$\int_a^b \xi^3\,d\alpha(\xi)$$
for example.

A: $$\int_a^b \xi^3\,d\alpha(\xi)=\int_a^b\xi^3a'(\xi)d\mu(\xi) $$
in case that $a$ is differentiable. Also $\mu(\xi) $ indicates the Legesgue measure.
In order to find the above formula, you have to use Radon-Nikodym derivatives. (http://en.wikipedia.org/wiki/Radon%E2%80%93Nikodym_theorem).
Generally the function $a$ gives you a way to measure elementary sets, such as intervals. This function will produce the corresponding Stieltjes  measure. In the same way, measuring intervals(or cubes) with the natural way ($\mu([0,1])=1)$, produces Lebesgue measure.

A: You can imagine $\alpha(\xi)$ as a non-uniform scaling applied to the $x$-axis.
Imagine, for example, that you're driving through the andes in peru, and your car's fancy GPS records the current elevation every kilometer (or mile if you prefer to keep it imperial). A few days later you compete in a marathon, and are asked to disclose the average altitude you were on, since your blood test shows an elevated count of red blood cells which is an indication of doping unless you spent a considerable amount of time at high altitudes.
Easy, you think, and download the data from your GPS, compute the sum, and divide by the number of data points. You report that value, and a prompty disqualified from this and any further events. What happened? It turns out your average speed was much higher at low altitudes than it was at high ones - perfectly reasonable, given the condition of some of the streets in those mountainous regions. Thus, you actually spent much more times at higher altitudes than the graph of altitude over distance that your GPS record shows. What you need is a graph of altitude over time, but you don't have that.
When you discover the problem, you check your car's logs as well, and are delighted to discover that your car maintens a log of the elapsed time, also recorded every kilometer (or mile). Can I use this to compute a corrected average, you ask a friend of yours, and thus rehabilitate my good name in the runner community? You can, he answers, and for once you're glad that you have a mathematician amongst your friends...
What does your mathematically inclined friend do? He aligns the list of altitudes from your GPS with the list of times from your car, and gets a table like the following $$
\begin{array}{lll}
\textrm{Distance} & \textrm{Altitude} & \textrm{Time} \\
\hline \\
0\textrm{km}      & 500\textrm{m}     & 0\textrm{s} \\
1\textrm{km}      & 550\textrm{m}     & 30\textrm{s} \\
2\textrm{km}      & 600\textrm{m}     & 65\textrm{s} \\
\ldots
\end{array}
$$
He then computes a new column "Time Delta" which contains the difference between each time and the one that immediatly precedes it. The new table looks like this
$$
\begin{array}{lll}
\textrm{Distance} & \textrm{Altitude} & \textrm{Time} & \textrm{Time Delta} \\
\hline \\
0\textrm{km}      & 500\textrm{m}     & 0\textrm{s}   & - \\
1\textrm{km}      & 550\textrm{m}     & 30\textrm{s}  & 30\textrm{s} \\
2\textrm{km}      & 600\textrm{m}     & 65\textrm{s}  & 35\textrm{s} \\
\ldots
\end{array}
$$
Each time delta then reflects the time it took to drive 1 kilometer (or mile), i.e. it reflects the velocity you were driving with (altough in seconds/kilometer, not kilometers/hour as usual. You could call that "slowness" instead of "speed", because while it refelects the velocity, it reflects higher velocities with lower values, and lower velocities with higher values). Each Time Delta also reflects the time you spend at the given altitude, since it's simply the time between the last altitude measurement and the current one.
All your friends needs to do then is to again average the altitude values, but weighted with their corresponding time deltas. In other words, he simply multiplies each altitude with the corresponding time delta, adds up all those producs, and divides by the sum of the time deltas (which is simply the delta between the first and the last logged time). And voila, the resulting average is much higher than the one you got, and upon notifying the authorities your ban is lifted and your name is cleared.
Stiltjes Integrals do exactly this kind of weighted summation. In the Stiltjes integral
$$
  \int f(\xi) \,d\alpha(\xi)
$$
$f(\xi)$ corresponds to the mapping from distance to altitude that your GPS gave you, while $\alpha(\xi)$ corresponds to the mapping of distance to time that your car logged. The integral weights each $f(\xi)$ with the rate of change of $\alpha$ at $\xi)$, i.e. it computes $$
  \int f(\xi) \alpha'(\xi) d\xi \text{.}
$$
Note how, compared to the tables above, the computation of differences between successive values has been replaced by taking the derivative. This is necessary since when $x$ ranges over a continuum, there's no longer such a thing as an immediate predecessor of a certain $x$.
Beware that this formula is only correct if $\alpha(\xi)$ is continously differentiable!

A: Since, Steiltjes integral is the generalization of Reimann integral so, basic ideas on R integral is must before getting into the R-S integral or simply Steiltjes integral.
Ok, i would like to give the geometrical interpretation of Steiltjes integral so that you will get the intuitive meaning of R-S integral.
GEOMETRICAL INTERPRETATION OF R-S INTEGRAL:
Here in R-S integral, let's consider we are integrating the function $f(\xi )$ with respect to the monotonic function $\alpha (\xi )$within the interval$[a,b]$.
mathematically we represent as below,
$$\int_{a}^{b}f(\xi )d\alpha (\xi )$$
let's get into the geometrical interpretation of above integral.
we generally take the area of the $f(\xi )$with respect to the x-axis within certain interval in Reimann integral. Similarly we are calculating the area but a bit complex than the Reimann integral.
let's take three axes where we keep $\xi $ and the functions $f(\xi )$ and $\alpha (\xi )$ at x-axis,y-axis and z-axis respectively. Now, we erect the wall from the curve traced by those functions then we can have the junction curve(since the intersection of the planes is curve). let's take a light source emitting the parallel rays of light along the x-axis which results in the formation of shadow behind the wall on $f− \alpha$ plane.
Hence, the R-S integral gives the area of the shadow.
For your another question(calculation), you can use the relation between the Reimann integral and Reimann-Steiltjes integral,
$$\int_{a}^{b}\xi ^{3}d\alpha (\xi ) = \int_{a}^{b}\xi ^{3}{\alpha }'(\xi )d\xi $$
thanks!


text:
Q: How do I correctly use the 960 grid system if the body container itself will be 940px? I am now using the 960 grid system and how can I have a centered container using the 960 grid system whose width is 940px and then the margin-left and margin-right is set to 10px.
I checked sites using the grid and it seems that their container is 940px.  I googled and it seems that that's because the margin-left and margin-right might 10px.  I am a bit confused about this and I would like to have 10px on both left and right.
Question:
Using the code below how can I have margin-left and margin-right in at 10px if the container is 940px and how do I center the container?
This is what I have so far:
HTML:

CSS:
My Class
.container {
background-color: #999;
margin-top: 130px;
min-height: 320px;
overflow: auto;
}

Below is from 960 grid system:
body {
  min-width: 960px;
}

Grid >> 12 Columns

.container_12 .grid_12 {
  width: 940px;
}
.container_12 {
  margin-left: auto;
  margin-right: auto;
  width: 960px;
}

Grid >> Global

.grid_1,
.grid_2,
.grid_3,
.grid_4,
.grid_5,
.grid_6,
.grid_7,
.grid_8,
.grid_9,
.grid_10,
.grid_11,
.grid_12 {
  display: inline;
  float: left;
  margin-left: 10px;
  margin-right: 10px;
}

How can I use container_12 and one of those other grids (from 1-12) to have the left and right at 10px?

A: The 960 Grid uses classes from .grid_1 ... .grid_12 (max number of columns)
CSS
.grid_1, .grid_2, .grid_3, .grid_4, .grid_5, .grid_6, .grid_7, .grid_8, .grid_9, .grid_10, .grid_11, .grid_12 {
    display: inline;
    float: left;
    margin-left: 10px;
    margin-right: 10px;
}

Take a look on http://960.gs/demo.html

A: UPDATE
Are you asking how to nest containers without messing up the widths due to the extra 10px of left/right margin?
If you're using the http://960.gs grid system, there are two classes provided to remove the extra margin: .alpha (removes left margin) and .omega (removes right margin). So your HTML would then look like this (here's a fiddle):

Nested 16 Column Grid

ORIGINAL ANSWER
I'm a bit confused by your question as the 960 grid system provided here http://960.gs already does what you're asking for. It sounds like you're confused between the container and grids.
A container is defined as being 960px wide with margin-left: auto; margin-right: auto to keep it centered; no additional margin and padding are needed. It should be the outer most parent of your grid structure.
A grid is a nested element with a specified width (depending on the size indicated, i.e., grid_12) and margin-left: 10px; margin-right: 10px.
So your HTML should be structured something like this:

So, a container will always have a width of 960px, but the largest a grid can ever by is 940px because of the left and right margin. For more information, read up on the CSS box model: http://www.w3.org/TR/CSS2/box.html


text:
Q: Java: LOAD DATA LOCAL INFILE not executing So I'm looking to find a way to import data from a .txt file into my mysql table using a java desktop application, I wrote these lines of code but when I run my program I can see the Jform and the first button work properly, but when I press the second one, nothing happens. What should I change?
  private void ouvrirActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            JFileChooser chooser = new JFileChooser();
            chooser.showOpenDialog(null);
            File f=chooser.getSelectedFile();
            filename=f.getAbsolutePath();
            chemin.setText(filename);
        }

    private void chargerActionPerformed(java.awt.event.ActionEvent evt) {

               String tablename = "tmp";

            try{

            stm=maConnexion.ObtenirConnexion().createStatement();
            stm.executeUpdate("LOAD DATA LOCAL INFILE \"" + filename + "\" INTO TABLE " + tablename);
            JOptionPane.showMessageDialog(null,"Fichier trace chargé avec succés");

        }
        catch(SQLException ex){
            System.err.println(ex);

        }

A: For clarifying your situation, you can run the command in your mysql console. If succeeds, then you can try it in your code.
First try,
LOAD DATA LOCAL INFILE '/tmp/foo.txt'
INTO TABLE tmp;

Second try,
LOAD DATA LOCAL INFILE '/tmp/foo.txt'
INTO TABLE tmp COLUMNS TERMINATED BY '\t';

Third try,
LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE tmp
FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n';

Forth try,
LOAD DATA LOCAL
    INFILE '/tmp/mydata.txt' INTO TABLE tmp
    COLUMNS TERMINATED BY '\t'  ## This should be your delimiter
    OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here

From those, which runs perfectly, you can implement your code.
For more,
You can go through MySQL manual
Resource Link:
LOAD DATA INFILE Syntax


text:
Q: Custom TypeConverter ConvertTo() method not called for char property I have a class with a char property, that might be unprintable, which is used as part of a communications protocol.
If I rely on the default CharConverter class, then certain unprintable character values cannot be displayed or edited in the resulting property form (there's apparently no output for the unprintable characters). So, I've written a custom TypeConverter for this char property that outputs characters by displaying their Unicode codepoint as a hex value, instead of outputting the character itself.
Alas, my custom type converter's CanConvertTo and ConvertTo methods are not being called when displaying the property value; if the character is printable, then that character is displayed in the property grid, but if it's unprintable, nothing is displayed—as though the default CharConverter is still in use.
(Oddly, my custom type converter's CanConvertFrom method is being called, for conversion from a string, and returns true.)
Here's my class with the char property:
using System.ComponentModel;

public class SomeClass {

    // ...

    // Property for setting a communications character.
    [
        DisplayName("SomeCharacter"),
        Category("Configuration"),
        Description("Some special communications character, as a hex value."),
        TypeConverter(typeof(CustomCharConverter)),
    ]
    public char SpecialChar {
        get => // ...
        set => // ...
    }
}

Here's my CustomCharConverter class (I'm omitting the methods for converting back to a char, as we don't that far):
public class CustomCharConverter: TypeConverter {

    // ...

    // Overridden CanConvertTo. This is never called.
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {

        // This code never executes.
        if(destinationType == typeof(string) || destinationType == typeof(char)) {
            return true;
        }
        return base.CanConvertTo(context, destinationType);
    }

    // Overridden ConvertTo. This is never called.
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,
    Type destinationType) {

        // This code never executes.
        if(destinationType == typeof(string)) {
            return $"0x{((int)((char)value)):X2}"; // Convert char to hex value.
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }
}

I haven't been able to figure out why my ConvertTo method has not been called to convert the char value to a hex value on output. Am I missing something?


text:
Q: Set method of TPicture property doesn't get called when the form is created Here's my component overall structure:

*

*My Component

*

*property Categories: TCollection (of TCategory)

*

*TCategory

*

*property Icon: TPicture read FIcon write SetIcon;

*property Example: Integer read FExample write SetExample;

*(Other category properties...)

*(Other properties...)

In the Object Inspector of the IDE, I choose a picture and it gets serialized successfully (I checked it in form view as text). I set a breakpoint on SetIcon method and when I compile and run the application, it doesn't get called at all. At the same time, SetExample gets called right as it should.
What's wrong with the TPicture property?
P.S: Set method is called in IDE, but not at runtime.
Here's a MCVE of the code:
unit MCVE;

interface

uses
  System.SysUtils, System.Classes, Vcl.Controls, Graphics, Dialogs;

type
  TMyCollectionItem = class(TCollectionItem)
  private
    FIcon: TPicture;
    procedure SetIcon(const Value: TPicture);
  public
    constructor Create(Collection: TCollection); override;
  published
    property Icon: TPicture read FIcon write SetIcon;
  end;

  TMyCollection = class(TCollection)
  end;

  TMCVE = class(TCustomControl)
  private
    FCollection: TMyCollection;
    procedure SetCollection(const Value: TMyCollection);
  public
    constructor Create(AOwner: TComponent); override;
  published
    property MyCollection: TMyCollection read FCollection write SetCollection;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('Samples', [TMCVE]);
end;

{ TMyCollectionItem }

constructor TMyCollectionItem.Create(Collection: TCollection);
begin
  inherited;
  FIcon := TPicture.Create;
end;

procedure TMyCollectionItem.SetIcon(const Value: TPicture);
begin
  ShowMessage('SetIcon is called!');
  FIcon.Assign(Value);
end;

{ TMCVE }

constructor TMCVE.Create(AOwner: TComponent);
begin
  inherited;
  FCollection := TMyCollection.Create(TMyCollectionItem);
end;

procedure TMCVE.SetCollection(const Value: TMyCollection);
begin
  FCollection := Value;
end;

end.

A: For simple types like Integer, Boolean, Double etc., streaming operates the way you describe. The streaming framework reads the value, and calls the property setter.
For a more complex type like TPicture, it does not happen that way. The streaming framework cannot call the property setter. In order to do so it would need to get hold of a fully formed TPicture. And it doesn't know how to do that, a priori.
So what happens instead, is that the streaming framework calls the getter of the property to obtain the TPicture instance that your component's constructor created. And then streams in the state of the TPicture stored in the .dfm file.
As it happens, TPicture has no published properties. The picture data is saved to the .dfm file under a property named Data. So, where does that come from. The answer is in the overridden DefineProperties method. The code looks like this:
procedure TPicture.DefineProperties(Filer: TFiler);

  function DoWrite: Boolean;
  begin
    // .... code removed for brevity
  end;

begin
  Filer.DefineBinaryProperty('Data', ReadData, WriteData, DoWrite);
end;

The WriteData and ReadData methods do the streaming.
So, to recap. You asked why the setter for a TPicture property was not called when streaming in the picture's properties. It is not called because the picture object that you created in your constructor streams in its properties.