getSignedRequest Facebook SDK 4

Question: I'm creating a Fan gate on Facebook SDK 4,
I'm trying to use $signed_request = $facebook->getSignedRequest();
However, I'm currently not sure which object I should be calling getSignedRequest() on.
The doc says $facebook, when I create a $facebook object from
$facebook = FacebookSession::setDefaultApplication('app_id 'secret');
I get the following error
Fatal error: Call to a member function getSignedRequest() on a non-object

CODE
$facebook = FacebookSession::setDefaultApplication('app_id', 'secret);

// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper( 'http://www.metah.ch/' );

try {
  $session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
  // When Facebook returns an error
} catch( Exception $ex ) {
  // When validation fails or other local issues
}

$signed_request = $facebook->getSignedRequest();

var_dump($signed_request);

Answer: I don't imagine that FacebookSession::setDefaultApplication('app_id', 'secret'); returns a facebook object. You can try to var_dump($facebook); to confirm.
The docs didn't seem to suggest it returned a facebook object either. https://developers.facebook.com/docs/php/gettingstarted/4.0.0
I haven't used the SDK in some time but it used to be that you'd do new Facebook() to get a facebook object. The docs seem to indicate the getSignedRequest method exists in the BaseFacebook class. https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest
Comment: Hey Jaisen,
Your right about the FacebookSession not returning an object, the vardump shows NULL.

I also do recall the old SDK allow for new Facebook() to create an object.

It seems that "getSignedRequest" is apart of BaseFacebook, with that said, not quite sure what to call the method on.
Comment: Looks like `FacebookSession` has that method defined. https://github.com/facebook/facebook-php-sdk-v4/blob/56d40c32400bcf36d41d4224bfee1406c5dba962/src/Facebook/FacebookSession.php#L105

getSignedRequest Facebook SDK 4


Is there a way to use space between buttons in landscape

Question: After much digging I've realised there is no Qt-way to use 3 middle buttons in landscape mode in S50v5, however I don't like to waste this precious space. I've tried to place my widgets there but menu bar is on top and widgets aren't visible.
Is there any way to utilise this space without using native Symbian APIs?
Answer: Controlling the stock softkeys in Qt is a pain. The strategy I have used is to make the QMainWindow full-screen with showFullScreen() which allows you to use the softkey space yourself. You will have to make sure any widgets you create are ultimately parents of the main window, and be mindful of this bug when creating pop-ups.
Comment: It answers my question in no way. BTW controlling two standard softkeys in Qt is easy.
Comment: Maybe I misunderstood your question. You say you've tried to use your own widgets 'there' (in place of the softkeys, I presume) - the method I mention above certainly allows you to place softkeys there. I have a couple of apps that do this, replacing the system softkeys with my own (and replacing the menu, which is also very easy).
Comment: I've tried to place my widgets between standard buttons, not instead.


How to run a Symfony command in Windows task scheduler?

Question: I created a Symfony command that I can now use in cmd. I like it to be run every 15 minutes in my Windows task schedular. I created the task and everything to make it run every 15 minutes, but it doesn't execute the command. What am I doing wrong?
Answer: While writing the answer I figured out what I was doing wrong. I belive it is still worth posting since I've seen more people trying to get the question, in general, working but without success.
I had to remove the "" in the field Parameters toevoegen (dutch for "add parameters"). It now looks like this:

EDIT: To answer DavidG it's comment; You can get into this screen by pressing the Windows button and search for task schedular (or Windows Key + R -> taskschd.msc). Create a new folder with the name of your project or whatever. Press right mouse button on the folder and click "create task". If you then go to the actions tab you are where I am in the picture above.
The "Beginnen in" full path is: C:\xampp\htdocs\testExample, where testExample should just be your project directory name, not command or public directory, just the main directory with all of Symfony in it.
Comment: @Alart Yes I was able to do it with `Start in` set to the project path.
Comment: Can you share the article that you followed to create this window task from the scratch ?
Comment: Also what is the `Beginnen in` complete path ? Is is the path to the symfony command file ?
Comment: @DavidG See my edit.


Criteria builder group by and having count does not work

Question: This is the query i want to achieve:
 SELECT *
FROM ROOMENTITY R
JOIN CALENDARENTITY C ON R.id = C.room_id
WHERE C.available = TRUE AND
      C.date BETWEEN :checkin AND
      :checkout
GROUP BY C.room_id
HAVING COUNT(C.room_id)>= diffdays

This is my code:
manager = factory.createEntityManager();
boolean hasPredicates = false;
final CriteriaBuilder criteriaBuilder = manager.getCriteriaBuilder();

final CriteriaQuery<RoomEntity> q = criteriaBuilder.createQuery(RoomEntity.class);

List<Predicate> predicates = new ArrayList<Predicate>();

Root<RoomEntity> fromRooms = q.from(RoomEntity.class);
String checkinDate = filter.getCheckinDate();
String checkoutDate = filter.getCheckoutDate();
if (checkinDate != null || checkoutDate != null) {
    hasPredicates = true;
    java.sql.Date checkin = java.sql.Date.valueOf(filter.getCheckinDate());
    java.sql.Date checkout = ava.sql.Date.valueOf(filter.getCheckoutDate());
    int diffInDays = (int)( (checkout.getTime() - checkin.getTime()) / (1000 * 60 * 60 * 24) ) + 1;
    System.out.println("Days: " + diffInDays);
    Join<RoomEntity, CalendarEntity> calendarEntityJoin= fromRooms.join("calendarEntities", JoinType.INNER);
    calendarEntityJoin.on(
                        criteriaBuilder.equal(calendarEntityJoin.join("calendarId").<Integer>get("room_id"),  fromRooms.<Integer>get("id"))
                );
    predicates.add(criteriaBuilder.and(
                        criteriaBuilder.equal(calendarEntityJoin.<String>get("available"), true),
                        criteriaBuilder.between(calendarEntityJoin.join("calendarId").<Date>get("date"),
                                checkin, checkout)
                ));
    q.groupBy(calendarEntityJoin);
    q.having(criteriaBuilder.gt(criteriaBuilder.count(fromRooms), diffInDays));
}

My Room Entity:
public class RoomEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "id", nullable = false, unique = true)
    private Integer id;

    @OneToMany(mappedBy = "roomEntity", cascade = CascadeType.ALL)
    private Collection<CalendarEntity> calendarEntities;
}

My CalendarEntity:
public class CalendarEntity {

@EmbeddedId
private CalendarId calendarId;

@Basic
@Column(name = "available", nullable = false)
private Boolean available;

@ManyToOne
@JoinColumn(name = "room_id", referencedColumnName = "id", insertable = false, updatable = false)
private RoomEntity roomEntity;
}

My CalendarEntity Embedded id:
@Embeddable
public class CalendarId implements Serializable {

    @Column(name= "date", nullable = false)
    private Date date;

    @Column(name = "room_id", nullable = false)
    private Integer room_id;
}

Everything is good up until group by and having count. When i run this  and i print the query with this code below, then there is groupby/having:
if (hasPredicates)
            q.where(criteriaBuilder.and(predicates.toArray(new Predicate[0])));
final TypedQuery<RoomEntity> TQ = manager.createQuery(q);
TQ.setFirstResult(filter.getStart());
TQ.setMaxResults(filter.getSize());
System.out.println("\n\nQuery:\n" + +Q.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString() + "\n\n\n");

The query in the end is not what i want and it does implement group by and having count.
UPDATE:
This is the query i am getting right now:
SELECT t1.id, t1.bathrooms, t1.bedrooms, t1.beds, t1.description, t1.exta_person_price, t1.house_rules, t1.max_people, t1.min_overnights, t1.neightborhood, t1.overnight_price, t1.square_meters, t1.title, t1.transport, t1.room_host, t1.room_location, t1.room_type_id FROM CALENDARENTITY t0, ROOMENTITY t1 WHERE (((t0.available = ?) AND (t0.date BETWEEN ? AND ?)) AND ((t0.room_id = t1.id) AND (t0.room_id = t1.id))) ORDER BY t1.overnight_price ASC

It is missing group by and having count!
Comment: Add some information about your expected result or errors which you are getting.
Comment: What i am expecting is the top query to be created, but in the end what is getting created is the top query with the 2 last lines, group by and having count.
Comment: Did you check if you have created the entities properly, using proper annotations you need not write so much code. Also, verify the query you are trying to create, it can be easily modified to do the same job in a more cleaner way.
Comment: The query i am trying to get in the end, already works if i run it as it is, but i cannot build it correctly with criteria builder. Group by and having count do not work and i dont know why.
Comment: Share code for RoomEntity and CalendarEntity @peterthunder .
Comment: I typed the basics of my 2 entities.
Comment: `` Another case where 3rd party software gets in the way of writing a query, rather than helping? ``  In this case it sounds like the SQL was easier to learn than the Builder package.
Comment: Why not just manager.createNativeQuery("SELECT ... ",RoomEntity.class)
Comment: The query worked after i used multiselect. Thanks everyone for your answers.
Answer: The query worked after i used multiselect.
    Q.multiselect(fromRooms);


Compile code with java8 and run with java17

Question: I want to compile project using jdk8 and run it using jdk17. And my project use libraries which have been deleted in modern jdk (jdk.xml.bind, jdk.xml.ws).
My question is - will I get errors related to removed dependencies from modern jdk - jdk.xml.bind, jdk.xml.ws? Or if project was compiled using jdk8 which contains these packages inside, it would work fine with jdk17 in runtime?
Maybe I need to add these dependencies explicitly (rg.glassfish.jaxb:jaxb-runtime, com.sun.xml.ws:jaxws-ri)?
Comment: When your code needs these classes, you have to add them.
Comment: @Holger got it, thanks for answering me!
Answer: In general, it really depends on how you compiled your code.
For instance, you can use a build tool, such as Maven for instance, and just include these dependencies in the project with the compile scope, which is the default one. And then if you are using some kind of a plugin that does fat jar creation: maven shade plugin, for instance, or spring-boot maven plugin etc, then your project will have these dependencies at Runtime so you are good to go.
Of course you may not have these dependencies in the project or even more so you simply do not an access to the source code. So another option is to include them separately in the JVM classpath during execution. This approach is similar (but not the same) to one people have when they deploy their Java application into an Enterprise web server such as WebSphere or JBoss.
Usually, the web server has required implementations and Java classes that are not present during compilation and they are just provided to JVM via classpath.
Comment: Thank you @vashdivan, if I helped you solve the problem, please accept the answer and upvote it :)


How should one start composing with a 10+ year experience as an amateur pianist?

Question: I've been playing the piano for about 13 years, I play many different styles from classical to jazz to film music (never really attempted contemporary classical music unless that includes electronic music). In my repertoir I have Chopin, Rachmaninoff, Debussy, Gershwin, Liszt, Beethoven, Bach, Eroll Garner, Louis Armstrong, bossa nova/the girl from ipanema, Erik Satie, Paul McCartney, The Stranglers... And I've tried to compose a piece for piano but with zero success. When I get something good by pressing random keys (literally this is one of my best methods) I then simplify the chords and strip away all the complexity to end up with only major and minor chords (and sometimes major/minor 7). I have trouble choosing what to keep and what to throw away so there is never much structure.
How do I make my composition not look like a written down improvisation and how do I achieve something that is more complexe then just min/maj chords with a melody?
Comment: @StanislasHildebrandt most compositions start off with improvisation, Bach was mainly an improviser. If you're primarily reading sheet music, switch to learning songs 'by ear'. I find reading music kills all creativity. Once you can play what your hear in your head you can more easily improvise and compose. I have alot of melodies buzzing in my head alot of the times, so it's just a matter of getting them out. I don't think a class will help you with this skill. Composing is being creative, the complete opposite of a classroom setting.
Comment: Take a composition class.
Comment: I can't, I study something completely different and it would take too much time, I was looking for some tips
Comment: Well, there is no magic wand out there.   Either you put in the time (class, or maybe reading the textbook on your own)  or you don't learn properly.
Comment: Taking a class will take "too much time"? What exactly are you expecting to happen? It will probably take you another 10 years to learn to compose, so a class seems like nothing from that perspective.
Comment: Composing is a very time consuming task. Some are faster, some are slower. But you need the basics. I absolutely agree with Carl and Todd - Taking a class to learn the basics is the best start.
Answer: Don't worry about sounding like improvisation. Improvisation is composition with about 2 seconds to work things out; composition allows unlimited time to work things out.
You might look at some of the books (many downloadable pdf) on composition. There are those discussing elementary harmony and those discussing composition of phrases, stringing phrases together, writing small scale melodies, etc. One I like is Goetschius' book, "Exercises in melody writing." He shows how to write melodies up to about 32 bars or the like. Schoenberg's "Fundamentals of Music Composition" is too. There are also several books on popular theory but I don't really know them. Preston Ware Orem has a book on composition that's pretty good although it's not online; my only complaint is that his harmony discussions is not in line with other theorists (he has augmented sixths as "dominant" chords instead of subdominant, but most writers have minor problems with their books.)
Also, just keep trying. Check some songs or classical pieces and try to see how phrases are ended. See how sections are ended. See what harmonic outlines are followed. Much of classical, jazz, pop, Spanish, etc. music goes through the sequence: exposition (play some themes), re-state the themes (play in another key), develop (play around with the themes), restate the themes again (play the themes). It's the common AABA format. Of course, each part will have inner structure and there are cadences marking off sections.


two digit multiplication (for loops)

Question: def getProduct(n):
    product = 1
    while (n != 0):
        product = product * (n % 10)
        n = n // 10
    return product
calc = list()
for number in range(10, 100):
    num = getProduct(number)
    if number == 2 * num:
        calc.append(number)
print(calc)

So, the question is to have a column of two digit numbers, which is equal to the (product of the two digits * 2). How should I solve this problem?
Comment: Your question needs to be a bit more refined and detailed. Please edit your question so it's easy to understand what you are trying to do, what you have done.
Answer: i dont know what you mean but im guessing you need code for a two digit calulator
def multiply(x, y):
    return x * y
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print(num1, "*", num2, "=", multiply(num1, num2))

Comment: Is this what you wanted or something else?
Answer: def getProduct(n):
    product = 1
    if (n != 0):
        product = product * (n % 10) * (n//10)
    return product
calc = list()
for number in range(10, 100):
    num = getProduct(number)
    if number == 2 * num:
        calc.append(number)
print(calc)

two digit multiplication (for loops)


Como pegar todos os elementos da  utilizando o document.querySelectorAll() - JavaScript

Question:
Quero pegar essas li dentro da ul usando o document.querySelectorAll()

Tentei desse jeito , mas não veio o NodeList das li , só apareceu a ul
    function TrocaLataPrincipal(){
    let pepsiPrincipal = document.querySelector(".pepsi")
    let lataPepsi = document.querySelectorAll(".latasDeRefri")
    console.log(lataPepsi)
}

TrocaLataPrincipal()

Resultado no console
Answer: Você está pegando somente a UL, então precisa selecionar as LI dentro do UL:
function TrocaLataPrincipal(){
    const pepsiPrincipal = document.querySelector(".pepsi")
    const lataPepsi = document.querySelectorAll(".latasDeRefri li")
    console.log(lataPepsi)
}

TrocaLataPrincipal()

Comment: Muito Obrigado, Marcos :)
Answer: Quando você busca por .latasDeRefri, está trazendo somente o elemento que possui a classe "latasDeRefri", que no caso é o ul.
Se quer todas as li dentro dele, basta incluir isso no seletor:

let latasPepsi = document.querySelectorAll(".latasDeRefri li");
//                                                   aqui ^^
for (const li of latasPepsi)
    console.log(li);

pepsi 1

pepsi 2

pepsi 3

Outra alternativa é fazer a busca por li a partir da ul:

// busca o primeiro ul com a classe latasDeRefri
let ul = document.querySelector(".latasDeRefri");
// busca os "li" dentro do ul
for (const li of ul.querySelectorAll('li'))
    console.log(li);

pepsi 1

pepsi 2

pepsi 3

outro

Note que agora fiz a busca por "li" a partir do ul encontrado (e não a partir do document). Assim, ele só busca o que está dentro do ul (se eu fizesse a busca no document, ele também encontraria o
outro
).

Leia a documentação para mais informações sobre os seletores.
Comment: Muito Obrigado, hkotsubo  :)


Using multiple templates in a Drupal 8 module

Question: I have produced a simple Drupal module which provides a wrapper for a JavaScript library. I'm working on a separate module which will produce several pages of examples of the library and wrapper in action. These pages will each contain a two sections, the library, and description text and miscellaneous HTML.
What is the best technique to do this the Drupal 8 way?  I can imagine two strategies:

Each page will be a separate function within my controller. The function can first add two entries to the output array, the first will contain the data for the library, and the second the raw HTML and text.
In the second technique, I would place all the HTML and text in a twig template. Then I would add all the data for the library in the controller and add a reference to this new theme template as a second entry in the output array. I like the idea of this second strategy, but I don't know how to accomplish it. I've look at code for several Drupal 8 projects and read a few tutorials, and I haven't seen an example of this. The hook_theme function always contains a single return statement. How would I add a switch or if statement within hook_theme to determine which twig template to return.

If there is a third option that is even better, let me know.
Answer: hook_theme() returns a list of templates that will then be cached in the registry. You don't need conditions there, in fact, you can not, since it will be called only once.
Just return multiple templates and then reference them in your render arrays, like you already have to when using a single one.


cant set fancybox iframe from javascript

Question: I am trying to set and call fancybox from within javascrip like this
$.fancybox.open({
        type : 'iframe',
        'width'             : '75%',
        'height'            : '75%',
        'autoScale'         : false,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        src : url,
        smallBtn : false,
        fitToView: false,
        autoSize: false,
        autoDimensions: false
  })

It opens it fine but does not define the sizes, what am I doing wrong? o i need to set something else up? It just loads a page that displays a map, Thanks
Answer: Use either CSS or iframe.css option:
    iframe : {
        css : {
            width  : '75%',
            height : '75%'
        }
    }

See docs - https://fancyapps.com/fancybox/3/docs/#iframe - for more info.


How to handle the cache per user in REST Resource?

Question: I have a requirement to expose a specific content type data via REST end point. Below is my code:
public function get() {
    $current_user = $this->currentUser->id();
    $user = $this->entityTypeManager->getStorage('user')->load($current_user);
    $userLangId = $user->language()->getId();

    // You must to implement the logic of your REST Resource here.
    // Use current user after pass authentication to validate access.
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }
    $news_values = [
      'langcode' => $userLangId,
      'type' => ['story'],
      'status' => 1,
    ];
    $news_data = $this->entityTypeManager->getStorage('node')->loadByProperties($news_values);
    $newsfeed = [];
    $newsfeed['stories'] = ['Story' => array_values($news_data)];
    if (empty($newsfeed)) {
      return new ResourceResponse('No Newsfeed exist for this user.', 400);
    }
    $response = new ResourceResponse($newsfeed, 200);
//    $response->addCacheableDependency($current_user);

    $response->addCacheableDependency(CacheableMetadata::createFromRenderArray([
      '#cache' => [
        'context' => ['user.roles'],
        'tags' => ['user:3', 'languages:' . $userLangId],
      ],
    ]));
    return $response;
  }

I am getting a proper response with this but I am facing issues in handling the cache.
This content is user specific. Based on user language content will popup when they access.
In Response Headers I am getting below things:
X-Drupal-Cache-Contexts: languages:language_interface theme url.site user.permissions
X-Drupal-Cache-Tags: config:filter.format.basic_html config:rest.resource.newsfeed_rest_resource config:rest.settings config:system.site http_response languages:fr node:7 node:9 user:3
X-Drupal-Dynamic-Cache: MISS/HIT

In Cache-tags i have not added node key but its automatically coming and its working once node updated. But if i try to login with different user via basic auth on postman client, content is not changing at all. Its showing cached content for previous user. How I can cache the content per user. Please help me in this regard.
Comment: Just change `['user.roles']` to `['user']` and clear your caches should work
Comment: Looks like your cache context is by the users role. Is that what you want? As if 2 of your users have the same roles so they'd get the same cached response
Comment: Ohh right. But how I can make it user specific instead of roles or permissions?
Comment: Its not working. As i can see in this article https://www.drupal.org/docs/8/api/cache-api/cache-contexts there is no ['user'] context.
Comment: When i changed the weight for USER in Detection and selection in language interface. It started working without cache context.
Comment: This makes sense because then the page language depends on the user and the language detection needs to bubble up the `user` context to the page.
Answer: @Leigh is right and user does exist. Cache contexts are hierarchical (see change record https://www.drupal.org/node/2451661) and user is a top level context.
So this should work (note the plural form of contexts):
  '#cache' => [
    'contexts' => ['user'],

You can also add the cache context by IDE autocompleting:
$response->getCacheableMetadata()->addCacheContexts(['user']);

Comment: Hey @4k4, Thanks for your detailed explanation. When i add above line, X-Drupal-Dynamic-Cache: UNCACHEABLE. Is it caching or not?
Comment: The response might be not cacheable for a different reason, which could be for example the line you have commented out. $current_user is not a cacheable object, then Drupal doesn't raise an error, it silently adds a cache max age of 0 as fallback.


Display and Modify CSS variable ? (Module)

Question: I'm developing a basic module that allows site admin to have the NavBar for mobile and Administration menu for the desktop view.
This can easily be done by adding this CSS.
#navbar-administration {
    display: none;
}

@media only screen and (min-width: 0px) and (max-width: 959px) {

    #navbar-administration {
        display: block;
    }  /* show it on small screens */;
}

#admin-menu {
    display: block;
}

@media (max-width: 960px) {

    #admin-menu {
        display: none;
    }
}

I'm using hook_page_build() to display it on every page. Now I want user to be able to change on an administration page the 960 width which is the default line break to changes menu to their desired value.
My question  how can I display  the default variable value (960) on a text field and it can be modify the css once the number on the text field is been change.
Comment: I have seen similar set ups whereby the module recreates the css file after saving a change, then the css file is loaded as normal per page request
Comment: Core color module does this. https://api.drupal.org/api/drupal/modules!color!color.module/function/color_scheme_form_submit/7
Answer: You have many options:

Make a system settings form that stores the value to a drupal variable. Read that value from your (themes) css. Then when that form is submitted in your theme form submit handler have code clears the cache:   cache_clear_all("{$theme}:css:*", NULL, TRUE);. Where $theme is your theme name. The CSS should be re-generated on page load.
I believe the LESS module allows you to easily make CSS variables applied to your files (in Less-3.x or greater for drupal). If you're not currently using LESS, then this is less helpful (pun NOT intended!)
Answer: If you make the menu 100% wide inside the div and use jquery resize by dragging it should auto adjust the menu when dragged.
example of div resizing when dragged


An Inequality Related to Absolute Values

Question: There exist two very known inequalities related to absolute values of complex numbers $x$ and $y$, namely, $|x|-|y|\leq |x+y|\leq |x|+|y|$.
However, I would like to find a kind of reverse inequality with possible constants and with some (which can be useful) hypothesis. In fact, my question is:
Question. Does there exist positive constants $k$ and $r$, such that for any complex numbers $x$ and $y$, with $|x|>|y|>2$, the estimate
$$
|x|-|y|\geq k(|x-y|)^r
$$
holds?
Any suggestion?
Note that if $x$ and $y$ are positive real numbers, then $x=y+\delta$, for some positive $\delta$. Then,
$$
|x|-|y|=\delta\geq \delta=k(|x-y|)^r,
$$
for $k=r=1$.
Answer: Let $y = -x + \delta$ where $\operatorname{arg}x = \operatorname{arg}\delta$, then $|x| - |y| = |\delta|$
$\forall k,r > 0\ \ k |x - y|^r \ge k$ if $|x - y| \ge 1$
$\therefore \exists \delta \ \text{s.t} \ |\delta| < k$
$\therefore \forall k,r > 0\ \exists x,y\ \text{s.t.} |x| - |y| < k |x - y|^r$ where |x| > |y| > 2
Comment: Note that in the statement of question is written that ||>||>2, so y cannot be -x
Comment: Sorry, I didn't notice that initially. I have updated my answer.
Comment: @Jean (forgot the ping)
Answer: No such inequality exists. Take $x=1+\epsilon$ and $y=-1$. The inequality fails for $\epsilon$ sufficiently small (whatever $k$ and $r$ may be).
Comment: Note that in the statement of question is written that ||>||>2, so y cannot be -x.
Comment: @Jean Thanks for the comment. I have edited my answer.


$_SERVER["DOCUMENT_ROOT"] is blank

Question: Just found out that document_root is empty. Any alternative or idea how to fix it?
echo <?php $HTTP_SERVER_VARS["PATH_TRANSLATED"]  ?>
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/inc/config.php");
include(ROOT_PATH . "/inc/header.php");
?>

Answer: You have a syntax error, your echo should be inside php tags, and add a semiclumn ;
<?php echo $HTTP_SERVER_VARS["PATH_TRANSLATED"];  ?>
    //^echo should be inside php tags          ^semicolumn was missed here

Comment: While it's best practice to have the semi-colon, that's actually not a syntax error. It's valid if it's the only line. The echo part is definitely an error though :)
Comment: @Jes that's what i meant to say :)
Answer: The $_SERVER['DocumentRoot'] global depends on the server you are using, not PHP itself. If you're using Apache then just add a DocumentRoot entry to your apache configuration file:
DocumentRoot /absolute/path/to/website/

You may have an easier time just modifying your PHP to be a relative path from the current directory. Use:
require_once __DIR__ . '/inc/config.php';

Or some variation of this with the correct relative path to get from the folder of the PHP script you're editing to the config.php file, ex:
require_once __DIR__ . '/../inc/config.php';

Answer: I prefer to use: define('FOO_ROOT', dirname($_SERVER['SCRIPT_FILENAME']))
This is useful in the case where perhaps you have index.php in the root and then you may have the code setting the root path in this way in /inc/init.php.
I don't believe their are any downsides to this technique and it's useful when perhaps you have something like cron.php (something run via a cron job) which also needs access to things in init.php. So in this context you just require inc/init.php in both of those files. I find it more DRY.

$_SERVER["DOCUMENT_ROOT"] is blank


Distance between two circles on a cube

Question: I found this problem in a book on undergraduate maths in the Soviet Union (http://www.ftpi.umn.edu/shifman/ComradeEinstein.pdf):

A circle is inscribed in a face of a cube of side a. Another circle is circumscribed about a neighboring face of the cube. Find the least distance between points of the circles.

The solution to the problem is in the book (page 61), but I am wondering how to find the maximum distance between points of the circles and I cannot see how the method used there can be used to find this.
Answer: I'll consider just the two-spheres method.
For simplicity, I'll assume $a = 2$; the general solution will be
proportional to the solution for this special case.
Both spheres have their centers at the body center of the cube;
call that point $O$.
The sphere containing the smaller circle is tangent to all twelve
edges of the cube, radius $\sqrt2$, and the larger sphere is circumscribed around the cube, radius $\sqrt3$.
The difference of the radii is clearly a lower bound of the "minimum" distance,
since no two points (one on each sphere) can be closer and every point on
each circle is on the corresponding sphere.
For similar reasons the sum of the radii is an upper bound on the "maximum" distance.
To paraphrase a remark by grand_chat, for the difference of the radii to
be the exact answer to the "minimum" question, there must be a line through $O$ that intersects both circles on the same side of $O$.
For the sum of the radii to be the exact answer to the "maximum" question,
there must be a line through $O$ that intersects the two circles on opposite sides of $O$.
[Update: The following is (I think) a much simpler argument than I
originally posted here.]
Consider the double cone defined by all the lines through $O$ that intersect
the smaller circle. This cone is tangent to the edges of the square face
inscribed in the larger circle, and the points on the large circle near
the centers of those edges are inside the cone; but other points on the
larger circle (such as the vertices of the square) are outside the cone.
In fact, the large circle must intersect the cone in at least four points.
Take one of these points nearest to the small circle and call it $Q$;
then $Q$ is collinear with $O$ and a point $P$ on the small circle
(because every point on the cone is collinear with $O$ and a point
on the small circle), $P$ and $Q$ are on the same side of $O$, and the
lower bound of the distance between points on the circles
is achieved at $PQ = \sqrt3 - \sqrt2$.
Now take one of the intersection points farthest from the small circle
and call it $Q'$; then then $Q'$ is collinear with $O$ and a point $P$
on the small circle, but $P$ and $Q'$ are on opposite sides of $O$, so the
upper bound of the distance between points on the circles
is achieved at $PQ' = \sqrt3 + \sqrt2$.

[For reference, the following was my earlier argument.]
Let $C$ be the center of the small circle.
Consider the set of planes through $O$ and $C$;
parameterize this set, using an arbitrary point $P$ on the small circle
as the parameter, by defining
$\mathop{plane}(P)$ as the plane through $O$, $P$, and $C$.
The angle $\angle COP$ is $\pi/4$.
For certain choices of $P$, $\mathop{plane}(P)$ intersects the larger circle.
For the "minimum" question, let $Q$ be the intersection
point of the larger circle and $\mathop{plane}(P)$ closer to $P$.
If $P = P_0$ is the single point of the smaller circle in the plane of the larger circle, clearly $\angle COQ < \pi/4$.
If $P = P_1$ is one of the two nearest points such that $\mathop{plane}(P)$
is tangent to the larger circle, $\angle COQ = \pi/2 > \pi/4$.
For $P$ between $P_0$ and $P_1$, $\angle COQ$ is a continuous function of the arc distance from $P_0$ to $P$.
Therefore there  is an intermediate point $P$ at which $\angle COQ = \pi/4$.
Then $PQ = \sqrt3 - \sqrt2$ and the previously-stated
lower bound of the distance is achieved.
For the "maximum" question, we do a similar parameterization $\mathop{plane}(P)$, but we take $P_0$ as the point on the small circle
farthest from the plane of the larger circle (at the midpoint of the
opposite edge of the cube, in fact) and let $Q$ be the intersection of
the larger circle with $\mathop{plane}(P)$ farthest from $P$.
Then for $P = P_0$, $\angle COQ > 3\pi/4$,
but for $P = P_1$, $\angle COQ = \pi/2$.
Hence for some intermediate point $P$, $\angle COQ = 3\pi/4$,
and then $P$ and $Q$ are collinear with $O$ and on opposite sides of $O$,
so the upper bound of the distance is achieved at $PQ = \sqrt3 + \sqrt2$.
Answer: To find the maximum distance instead of the minimum distance, you can follow the same method, but interchange "maximize" with "minimize" everywhere. In particular the analog of Lemma 21.1 is
Lemma 21.1b. Let $\alpha$ and $\beta$ be real numbers. Then
$$\min_{t\in[0,2\pi)}\alpha\cos t +\beta\sin t=-\sqrt{\alpha^2+\beta^2}.$$
The rest of the proof can be followed. You'll see negative signs popping up where they used to be positive.
Comment: @Jamie Yep, I'm guessing there is similar intuition for the maximum distance, which turns out to be the *sum* of the spheres' radii: $\sqrt 3 + \sqrt 2$. The 'elegant' solution to the original problem hinges on the fact that there is a ray from the center of the cube that intersects both circles; to adapt this solution to the maximization problem, we need a similar insight using a pair of collinear rays from the center of the cube that intersect both circles at opposite ends.
Comment: Right, thanks. I essentially wasn't sure how that Lemma translated to minimising the function, but it makes sense now you say it. Incidentally, the book notes that you can find the minimum distance by considering two sphere centred on the origin each containing one of the circles - obviously the difference of the radii is the minimum distance possible. Is there a similar intuition for the maximum distance?
Answer: I placed the inscribed circle on the top face (+y direction) and the circumscribed circle on the front face (+z direction). Their locus of points is
$$ \begin{align}
\vec{r}_1 & = \begin{bmatrix} r_1 \cos \theta_1 & \frac{a}{2} & r_1 \sin \theta_1 \end{bmatrix} \\
\vec{r}_2 & = \begin{bmatrix} r_2 \cos \theta_2 & r_2 \sin \theta_2 & \frac{a}{2} \end{bmatrix}
\end{align} $$
where $r_1 = \frac{a}{2}$, $r_2 = \frac{a}{\sqrt{2}}$ and $a$ is the side of the cube.
The distance (squared) is $$d^2 = \| \vec{r}_1 -\vec{r}_2 \|^2 $$ which is a function of $\theta_1$ and $\theta_2$.
It comes out as
$$ \frac{d^2}{a^2} = \frac{5}{4} - \frac{\sqrt{2} \cos\theta_1 \cos \theta_2 + \sin \theta_1 + \sqrt{2} \sin \theta_2}{2} $$
To minimize this you have to set $$\frac{\partial}{\partial \theta_1} \frac{d^2}{a^2} = 0$$ and at the same time $$\frac{\partial}{\partial \theta_2} \frac{d^2}{a^2} = 0$$
The system to solve is $$\begin{align} \frac{\sin \theta_1 \cos \theta_2}{\sqrt{2}} - \frac{\cos\theta_1}{2} & = 0 \\ \frac{\cos \theta_1 \sin \theta_2}{\sqrt{2}} - \frac{\cos\theta_2}{\sqrt{2}} & = 0 \end{align} $$
From the first equation $\cos \theta_2 = \frac{\cot \theta_1}{\sqrt{2}}$. When used in the second equation I get $\theta_1 = \arctan \sqrt{2}$.
The result I get was $$\frac{d^2}{a^2} = \frac{5}{4} - \frac{\sqrt{6}}{2} $$

Distance between two circles on a cube


Intersection of two convex functions such that their derivatives are also the same at the intersections

Question: I have two functions $T_1(x)$ and $T_2(x)$ defined on the interval $[0,1]$ such that $T_1(0) = T_2(0) = 0$ and $T_1(1) = T_2(1) = 1$. Furthermore, both of these are strictly monotone functions and are convex in the given interval. Also, they are  differentiable at least twice.  My aim is to prove these two functions are exactly equal. I have the following additional constraints on them.

$T_1'(0) = T_2'(0)$ and  $T_1'(1) = T_2'(1)$
They intersect at $2$ points in (0,1).

Intuitively, I think that the functions should be the same given the constraints and I think only the first condition is sufficient to prove this. However, I am not able to get a proof for the same even with both these conditions. I tried a variety of things but they did not lead me anywhere. Any help on this would be highly appreciated. Thanks!
Comment: I doubt that this is true.
Answer: This is not true. Set $T_1(x) = x^2$, consider a smooth function $g$ which has compact support in $(0,1)$ and set $T_2(x) := T_1(x) + \epsilon \, g(x)$ for $\epsilon$ small enough.
Answer: Here is a rather tedious counterexample.
Define $f(x) = {1 \over 3} x$ for $x \in [0, { 1\over 3}]$, and
$f(x) = 3x-2$ for $x \in [{8 \over 9}, 1]$.
Note that $f({1 \over 3}) = {1 \over 9}$, $f'({1 \over 3}) = {1 \over 3}$, $f''({1 \over 3}) = 0$, and
$f({8 \over 9}) = {2 \over 3}$, $f'({8 \over 9}) =  3$, $f''({8 \over 9}) = 0$.
In particular, if we let $a={1 \over 3}, b={8 \over 9}$, then we have
$f'(a) < f'(b), f''(a) = f''(b) = 0$.
We can construct many convex functions $\phi$ on $[a,b]$ such that
$\phi(a) = f(a), \phi(b) = f(b) $, $\phi'(a) = f'(a), \phi'(b) = f'(b) $, $\phi''(a) = \phi''(b) = 0$. Then if we define $f(x) = \phi(x)$ for
$x \in [a,b]$ we have many functions that satisfy the criteria.
To show one such construction, it will be easier to work in terms of $g=\phi'$. Then the constraints are $g(a)=f'(a), g(b)=f'(b)$, $g'(a)=g'(b) = 0$, $g'(x) \ge 0$ for $x \in [a,b]$ and $\int_a^b g(t)dt = f(b)-f(a)$.
To see one way of doing this, choose $t_t,t_2$ such that $a < t_1 < t_2 < b$ and define $g(x) = f'(a)$ for $x \in [a,t_1]$, $g(x) = f'(b)$ for $x \in [t_2,b]$ and
$g(x) = {f'(a)+f'(b) \over 2} + {f'(a) -f'(b) \over 2} \cos ({x - t_2 \over t_2-t_1}\pi)$ for $x \in [t_1,t_2]$. It is easy to confirm that all of the constraints except the integral one are satisfied.
To show that there are multiple values of $(t_1,t_2)$ that satisfy the integral constraint, note that
$\int_a^b g(t)dt= f'(a) ({t_1+t_2 \over 2} -a) + f'(b) (b-{t_1+t_2 \over 2})$.
Since $f'(a)(b-a) < {f(b)-f(a)} < f'(b)(b-a)$, we see that we can choose a
value of ${t_1+t_2 \over 2}$ such that the integral constraint is satisfied.
Now we can choose $t_1-\delta,t_2+\delta$ for small $\delta$ to get different functions.
Comment: Ah I missed out on functions with a piecewise definition. It was more probably more like that I wished that were true because it would have helped me prove another part. :P

Thanks a lot for your help! :D


How do I preserve GIF animation with the image field and image styles?

Question: Currently, when I upload animated GIFs to image fields, image styles breaks the animation as part of the crop/resize sequence.
I'd love to be able to preserve animation while also taking advantage of image styles. Is there a way to achieve this?
Answer: It is possible, there already is some discussion:

Pure PHP with imageMagick - https://stackoverflow.com/questions/718491/resize-animated-gif-file-without-destroying-animation
Drupal discussion - https://drupal.org/node/1115658
Issue for ImageMagick module with patch - https://drupal.org/node/1802534 - several users claim that it is working.


Logic Proof: Predicate Calculus

Question: Is my proof correct? Thank you so much for your help!
Premise:
$\forall x ((Lx \rightarrow Ix) \rightarrow ((Wx \land Sx) \rightarrow \neg Lx))$
Conclusion:
$\forall x ((Wx \land Ix) \rightarrow (\forall y (Wy \rightarrow Sy) \rightarrow \neg Lx))$
My first step is to rewrite the premise (I would love if you can show me a proof without doing this because conditionals make crazy, but I want to learn how to use them without changing $\rightarrow$ to $\lor$ symbols!!!)
1) $\forall x ((\neg(\neg Lx \lor Ix) \lor \neg(Wx \land Sx)) \lor \neg Lx)$
2) $((\neg(\neg La \lor Ia) \lor \neg(Wa \land Sa) \lor \neg La))$ Universal Instantiation 1), a/x, flag a
3) $\forall x (Wx \land Ix)$ Conditional Proof Assumption
4) $\forall y (Wy \rightarrow Sy)$ Conditional Proof Assumption
5) $Wa \land Ia$ Universal Instantiation 3)
6) $Wa \rightarrow Sa$ Universal Instantiation 4)
7) $Wa$ Simplification 5)
8) $Ia$ Simplification 5)
9) $Sa$ Modus Ponens 6), 7)
10) $\neg La$ Disjunctive Syllogism 2), 7), 8), 9)
11) $\forall x ((Wx \land Ix) \rightarrow (\forall y (Wy \rightarrow Sy) \rightarrow \neg Lx))$ Universal Generalization, a/x, a/y
Q.E.D.
Here is one example of the logic book that I am using, Symbolic Logic by Virgina Klerk

Example 2 Part A

Example 2 Part B
Comment: What book/text are you using? In particular, how is your universal generalization rule defined?
Comment: Ah, thanks, that helps!  ... what does F.S. stand for?
Comment: F.S. means Flag Subproof
Comment: Got it, thanks!
Answer: Your proof has a few problems:
On line 11 you do two universal generalizations, and yet one of the universals ends up in the middle of the statement. You need to do the inside generalization first, then get the conditional, and then do the outside generalization.
Line 3 is also not correct, given that you need that same $x$ later in the conclusion. Put a different way: you seem to treat the conclusion as if it were a conditional, with $\forall x (Wx \land Ix)$ being its antecedent, but that is npt what the conclusion is. The conclusion is a universal with a conditional on the inside, so you need to introduce a new constant, and then prove the conditional with that constant filled in for the variable.
Finally, to deal with the conditional in the premise is not too hard. I'll show you below:
1) $\forall x ((Lx \rightarrow Ix) \rightarrow ((Wx \land Sx) \rightarrow \neg Lx))$ Premise
2) $\qquad$ flag $a$
3) $\qquad \qquad Wa \land Ia$  Cond. Proof Assumption (CPA)
4) $\qquad \qquad (La \rightarrow Ia) \rightarrow ((Wa \land Sa) \rightarrow \neg La)$ UI 1
5) $\qquad \qquad \qquad La$ ******CPA
6) $\qquad \qquad \qquad Ia$ Simp. 3
7) $\qquad \qquad La \rightarrow Ia$ CP 5-6
8) $\qquad \qquad (Wa \land Sa) \rightarrow \neg La$ MP 4,7
9) $\qquad \qquad \qquad \forall y (Wy \rightarrow Sy)$ CPA
10) $\qquad \qquad \qquad(Wa \rightarrow Sa)$ UI 9
11) $\qquad \qquad \qquad Wa$ Simp. 3
12) $\qquad \qquad \qquad Sa$ MP 10,11
13) $\qquad \qquad \qquad Wa \land Sa$ Conj. 11,12
14) $\qquad \qquad \qquad \neg La$ MP 8,13
15) $\qquad \qquad \forall y (Wy \rightarrow Sy) \rightarrow \neg La$ CP 9-14
16) $\qquad (Wa \land Ia) \rightarrow (\forall y (Wy \rightarrow Sy) \rightarrow \neg La)$ CP 3-15
17) $\forall x (Wx \land Ix) \rightarrow (\forall y (Wy \rightarrow Sy) \rightarrow \neg Lx)$ UG 2-16
Comment: Thank you for your fast and helpful answer! I am also wondering if line 11 is right. I am reading Understanding Symbolic Logic, Fifth Edition, by Virginia Klenk
Comment: @Beginner Aye, I don't have that book.  OK, can you explain to me how universal generalization is defined in that book? Or maybe give a small example the book gives that you know is a correct use of it?
Comment: Sure. It will be my pleasure I will post an image soon.
Comment: What can I say? It looks fantantic! Thank you so much! You explain much better than my professor, and my professor is an amazing guy!
Comment: I will edit my other proof trying to use your teachings! Thank you!
Comment: @Beginner Well, thanks, but I really just gave the proof without much explanation at all. If I have some more time I may add the actual thinking process behind creating these proofs, but hopefully your professor has been doing that.
Comment: Really, my professor did not teach this chapter. We are learning it by reading the book. However, you have done a great job! If you have time, please add those explanations I will enjoy them a lot!

Logic Proof: Predicate Calculus


Does anyone know of a non-trivial algebraic structure satisfying these four identities?

Question: Does anyone know of a non-trivial (i.e. cardinality $\geq 2)$ algebraic structure $(X,+,-)$ satisfying the following identities?

$(x+a)-a=x$
$(x-a)+a=x$
$(x+y)+a = (x+a)+(y+a)$
$(x-y)+a = (x+a)-(y+a)$

Remark. The Abelian group of order $2$ doesn't satisfy the last two conditions.
Motivation. I think its cool that if $X$ is such an algebraic structure, then for every $a \in X$, the functions $$x \mapsto x+a, \qquad x \mapsto x-a$$
are automorphism of $X$. This mean that if $a \in X$ and $f \in \mathrm{Aut}(X)$, then $f+a \in \mathrm{Aut}(X)$ and $f-a \in \mathrm{Aut}(X).$
Comment: can we take the free non-associative algebra on $X$ and then quotient out by the relations?
Comment: @JC574 : And how do you that it doesn't give a trivial structure?
Comment: well i don't, it was just an idea. That's why I left it as a comment and not an answer.
Comment: - Although it depends on what you define as trivial, for example then with this algebra we would have $x+a \neq x$ I think for at least some $x$ and $a$
Comment: This seems like something a proof assistant could construct for you.
Comment: Does $\,a\,$ denote a constant?
Answer: Instead of $+$ and $-$, let us use $\tilde{+}$ and $\tilde{-}$ as the algebraic operations
we wish to invent.
Let $\mathcal{D} = \{\; a + b \epsilon : a, b \in \mathbb{R} \;\}$ be the the set of
dual numbers over $\mathbb{R}$. i.e.
the algebra extending $\mathbb{R}$ by adjoining one new element $\epsilon$ with the property
$\epsilon^2 = 0$. Now define binary operations $\tilde{+}$ and $\tilde{-}$ on $\mathcal{D}$ by
$$\begin{align}
( a + b\epsilon)\;\tilde{+}\;(c + d\epsilon ) &\;\stackrel{def}{=}
(a + b\epsilon) + (c + d\epsilon)\epsilon = a + (b + c)\epsilon\\
( a + b\epsilon)\;\tilde{-}\; (c + d\epsilon ) &\;\stackrel{def}{=}
(a + b\epsilon) - (c + d\epsilon)\epsilon = a + (b - c)\epsilon
\end{align}$$
It is easy to check

$(x \;\tilde{+}\; a) \;\tilde{-}\; a
 = (x + a\epsilon) - a\epsilon = x$.
$(x \;\tilde{-}\; a) \;\tilde{+}\; a
 = (x - a\epsilon) + a\epsilon = x$.
$(x \;\tilde{+}\; y) \;\tilde{+}\; a = ( x + y\epsilon) + a\epsilon
   = ( x + a\epsilon ) + (y + a\epsilon)\epsilon
   = (x \;\tilde{+}\; a) \;\tilde{+}\; (y \;\tilde{+}\; a)$
$(x \;\tilde{-}\; y) \;\tilde{+}\; a = (x - y\epsilon) + a \epsilon
   = ( x + a\epsilon ) - ( y + a\epsilon)\epsilon
   = ( x \;\tilde{+}\; a ) \;\tilde{-}\; ( y \;\tilde{+} a )$

As a result, $( \mathcal{D}, \tilde{+}, \tilde{-} )$ is a non-trivial example for the
algebra structure you are seeking.
Answer: A structure with these properties is called an involuntary quandle, or kei. They arise as important algebraic invariants of knots. See here.
Comment: If I've understood the wikipedia article correctly, they're called [racks](http://en.wikipedia.org/wiki/Racks_and_quandles#Racks). A quandle is an idempotent rack.
Comment: @goblin Yes, precisely.
Answer: Well I get one stupid example where $X$ is any set and $+$ and $-$ act trivially. What I mean by trivially is:
$x+a=x-a=x$ for all $x, a \in X$. Which is clearly not interesting.
Comment: True! **Corollary:** My definition of "non-trivial" was chosen badly.
Comment: Through some calculation I obtain $x+(x+x) = (x+x)$ is this OK for an algebraic structure??
Comment: That's an interesting result; how do you prove it?
Comment: (x-x)+x = x = (x+x) - (x+x). So 'add' x+x to the both side
Comment: Right, so we get $((x-x)+x)+(x+x) = x+x$, thus $x+(x+x)=x+x$. Very nice.
Comment: Having said that how do you obtain $x \rightarrow x-a$ is a homomorphism? ( I assume homomorphism in this setting would be (call a function f) f(x+y) = f(x) + f(y) and f(x-y)=f(x)-f(y)?
Comment: Yes, that's what I mean by a homomorphism. To answer your question: I can't remember the proof, but if $f : X \rightarrow Y$ is a bijective homomorphism of algebraic structures, then so too is the corresponding inverse function. Hence since $x \mapsto x+a$ is a bijective homomorphism, so too is its inverse, namely $x \mapsto x-a$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/16067/discussion-between-jack-yoon-and-goblin).
Comment: Hey I'm heading to bed soon; maybe we'll chat in the next few days though.
Comment: $x↦x+a$ being homomorphism is automatic consequence of 3,4 but $x↦x−a$ being homomorphism seem to require another one like 3,4 but with - instead of +. But maybe you can do more with axiom 3,4
Answer: Below I will demonstrate that, if $+$ is associative, then $x+a = x$ and $x-a = x$ for all $x$ and $a$.  This is enough, I think, to qualify as a "trivial" algebraic structure, even though the underlying set can be as large as you like.
Beginning from (3):
\begin{align*}
(x+y)+a &= (x+a) + (y+a)\\
(x+y)+a &= ((x+a)+y) + a & \text{by associativity}\\
x+y &= (x+a)+y & \text{by (1)}\\
x &= x+a & \text{by (1)}
\end{align*}
Further, using (2) we find that $x = (x+a) - a = x - a$.


Fazer post em duas tabelas simultaneamente em AJAX

Question: o código abaixo ele está funcionando, porém a minha dúvida é a seguinte: Existe alguma forma de fazer um post em dois endereços diferentes simultaneamente utilizando esse mesmo código sem repeti-lo?
Por exemplo, no código abaixo eu faço a inserção dos dados em uma tabela, porém existem outros campos da minha página que vão para outra tabela. Nessa situação existe algum artifício que possa ser feito nesse mesmo código ou eu teria que repeti-lo e inserir os dados da outra tabela?
<code>$.ajax({

        url:'http://localhost:8080/teste/rest/cadastro',
        type:'POST',
        contentType: "application/json",
        data :  dados,
        dataType: 'JSON',
        success: function(data) {

            }
    });
</code>
Obrigado desde já!
Comment: Uma dúvida, os outros campos, que vão para outra tabela, algum destes dados depende do outro post?
Comment: Sim, depende desse primeiro post.
Answer: Não é possível utilizar mais de uma url na mesma requisição. Como alternativa, você pode utilizar uma função para enviar a requisição à partir de uma url fornecida, assim não repetindo o código.
Exemplo:
<code>    function sendMyAjax(URL_address){
       $.ajax({
            url: URL_address,
            type:'POST',
            contentType: "application/json",
            data :  dados,
            dataType: 'JSON',
            success: function(data) {

                }
        });
    };

sendMyAjax('http://localhost:8080/teste/rest/cadastro');
sendMyAjax('http://localhost:8080/teste2/rest/cadastro2');
</code>
Fonte: Multiple url in same ajax call?is this possible?
Comment: Obrigado pela ajuda!


jquery date range picker not working on ajax callback

Question: Here is the picker init

<input type="text" id="pick" />

$('#pick').daterangepicker({
    timePickerIncrement: 30, format: 'YYYY-MM-DD'
}, function(start, end) {
    start = start.format('YYYY-MM-DD');
    end = end.format('YYYY-MM-DD');
    $.ajax({
        url: global_url+'statistics/analytics-ajax',
        data: 'start='+start+'&end='+end,
        dataType: 'html',
        method: 'post',
        beforeSend: function() {

        },
        complete: function() {

        },
        success: function(data) {
            $('.app').html(data);
            //$('#pick').daterangepicker();
        }

    })
});

On success call back I have a
div with class app will be replaced with
<input type="text" id="pick" />

But once the content is loaded through ajax daterangepicker not working so I added
$('#pick').daterangepicker();

and successfully I can see the daterangepicker but Ajax is not working. What is happening here.
Answer: In case datepicker is part of ajax response data then include datepicker js script in that page itself.
or
Include this code before call to datepicker on success
setTimeout(function(){alert('delay');}, 000);
Comment: That is not my question
Comment: Is your datepicker part of ajax reponse data?


How do I retrieve the names of functions used in an .m file in MATLAB?

Question: Say I have the following MATLAB function do_this.m
function result = do_this(input1, input2)
% input1 and input2 must have the same size.
    A = input1 + diag(input2);
    result = rand(size(input1)) + A;
end

I would like to know how to return an array of all the functions used in a given .m file. For example,
>> func_names = get_func_names('do_this.m')

So that func_names is ['diag', 'rand', 'size']
Answer: You can get this sort of information from depfun().
% See depfun helpfile
[TRACE_LIST, BUILTINS] = depfun('do_this.m');

BUILTINS is a cell array of all built-in functions needed by your function, and returns something like
BUILTINS =

'colon'
'datenummx'
'diag'
'evalin'
'horzcat'
'loadobj'
'numel'
'plus'
'rand'
'saveobj'
'size'
'subsindex'
'subsref'
'vertcat'

Note that this also returns functions used by diag(), rand(), etc.
In R2014a (and up?), MATLAB warns Warning: DEPFUN will be removed in a future release. Use matlab.codetools.requiredFilesAndProducts instead. However, the suggested function does not return built-in functions, only user-defined ones.
Comment: BTW: R2014a warns: `Warning: DEPFUN will be removed in a future release. Use matlab.codetools.requiredFilesAndProducts instead.`.
Comment: Good to know, I'll update the answer once I get to a machine w/ R2014a+.
Comment: No need to wait: http://www.mathworks.com/help/matlab/ref/matlab.codetools.requiredfilesandproducts.html ;-)
Comment: But that only returns "user-authored" files, and OP wants to include built-in ones.
Comment: Ok. Didn't know about either of those functions until now. I just meant you could add the info to your answer.
Comment: Same! I didn't know if you meant they had the same functionality.


Multiple imputation in prognostic studies

Question: I have 2 questions about Multiple imputation (MI) in the assessment of the prognostic performance of a test. This test acts as a predictor of a specific outcome, 3 years in the future. I have 26 % of missing data in my outcome.
First, I performed the MI with a predictive matrix (an $N \times (n+1)$ matrix) that contains all the input variables in my database and the desired outcome of the predictor test. Here, $N$ is the number of observations and $n$ the number of input variables. I need to know whether this approach is sound. Can it be that multiple imputation needs to be performed in a $N \times n$ predictive matrix without the predictor outcome?
Second, after MI, the imputed data are obtained. How can I pool these data in one imputation data matrix? Can anyone share a script in R that performs this? Or are there other ways to analyze the imputed data, for this application?
Thanks in advance
Answer: It's quite proper to include the outcome variable among those used for imputations, although if only outcome values are missing there might be limited value to doing so. If there are missing values in the predictors too, you need the outcome values to help impute the missing predictors. See the discussion on this page for example.
Second, you don't combine all of the imputations into a single imputed data matrix. Instead you run your analysis on each of the imputed data sets separately, then use Rubin's rules to combine the estimates in a way that takes both variability in the modeling and variability in the imputation into account. There is software that will do that for you, including the mice package in R. Stef van Buuren provides a useful web site with information on multiple imputation in general and that package in particular.


How to update failed transaction detail in drupal commerce

Question: I am using drupal commerce to built a e-commerce site .
My problem is when a transaction is failed or get a late response then the transaction is not created.
Can i create it manually or i have to ? if yes then how?
Or is their any other way to attach my transaction detail to order .
Any help most appriciate. Thank you.
Comment: This question is very vague. What payment module are you using? This sounds like a bug in the module or perhaps PHP is dying before the request times out.
Answer: You need to load the failed transaction from order id as shown below:
<?php
  $query = new EntityFieldQuery;
  $result = $query
    ->entityCondition('entity_type', 'commerce_payment_transaction')
    ->propertyCondition('order_id', $order->order_id)
    ->propertyOrderBy('transaction_id', 'DESC')
    ->range(0, 1)
    ->execute();
?>

Then load transaction using commerce_payment_transaction_load($transaction_id) & update transaction object as shown below:
<?php
//Use following line instead of loading transaction in order to create new transaction object
//$transaction = commerce_payment_transaction_new('commerce_payment_example', $order->order_id);
$transaction = commerce_payment_transaction_load($transaction_id);
$transaction->amount = $charge['amount'];
$transaction->currency_code = $charge['currency_code'];
$transaction->status = COMMERCE_PAYMENT_STATUS_SUCCESS;
commerce_payment_transaction_save($transaction);
?>

You can set a cron to periodically check failed transaction & check status of same at Payment Gateway & update accordingly.
Comment: Thanks for your interest but in my case transaction is not created yet. i.e, if customer close the window just after payment.


Why javascript function return NaN value?

Question: I try to use a int value from a JSON file like
{
 "buenos":274.0,
 "desaprobacion":0.13564668769716087,
 "malos":43.0,
 "proporcion":6.372093023255814
}

app:
var app = angular.module('angularSpa', ['ngRoute','nvd3'])

    .service('QueryService', function($http){
        var urlBase = 'http://localhost:8080/tweets';
        this.getJson = function(){
            return $http.get(urlBase+"/compañias/vtr");
        };  //I know this works because I use it on another controller to display values inside an html
        //... more functions

})

controller:
   function getValue(){
        QueryService.getJson()
        .success(function(data){
            return JSON.parse(data.buenos); // here always return NaN
        })
        .error(function(error){
            $scope.status = 'Error at query';
            console.log('error');
        });
    }

is there something wrong with the return of getValue()?
Comment: Where/how/when/what exactly are you coming to the conclusion that this "returns NaN"…? I see no log statement or any place where you use that value…
Comment: try using data.data.buenos in success method.
Comment: Just log the `data` that is passed to the `success` function
Comment: What Manish says, and also JSON.parse() should be angular.fromJson()
Comment: Where are you calling `getValue()`? This code is full of promises, how are you handling them?
Comment: Is it working now ?
Comment: No :(, i calling in the same controller [http://pastebin.com/JFVrTu56](http://pastebin.com/JFVrTu56)
Answer: You parse data.buenos, but your json is in data (JSON.parse(data.buenos);).
You should parse data, then return parsed data buenos.
 var a = JSON.parse(data);
 return a.buenos;


Finding count of string(seperated by delimeter) in data frame?

Question: i have this dataframe.
df

   userId  movieId  rating                genres
0      41    97921    4.0          Comedy|Drama|Sci-Fi
1      47    97921    3.5          Comedy|Drama|Sci-Fi
2     594    539      5.0          Comedy|Drama|Romance|Adventure
3       4    539      5.0          Comedy|Drama|Romance|Adventure
4     113    1733     4.0          Drama|Romance
5     594    1733     5.0          Drama|Romance

Also i have the list of all genres:
genres = ['Comedy','Drama','Romance','Action','Adventure','Sci-Fi','Thriller','Crime',\
          'Animation','Children','Musical','Film-Noir','Fantasy','War','Mystery','IMAX',\
             'Horror','Western','Documentary' ]

i want to count each genre in the data frame.
Expected Output:
Comedy :4
Drama :6
Sci-Fi: 2
Romance: 2
Adventure: 2

Answer: You can use:
df['genres'].str.split('|').explode().value_counts().to_dict() #requires pandas 0.25+

#{'Drama': 6, 'Comedy': 4, 'Romance': 4, 'Sci-Fi': 2, 'Adventure': 2}

Or:
df['genres'].str.get_dummies().sum().to_dict()
#{'Adventure': 2, 'Comedy': 4, 'Drama': 6, 'Romance': 4, 'Sci-Fi': 2}


Python: os.system() without return or error

Question: I need to use os.system() a few times in my script, but I don't want errors from the shell to appear in my script's window.  Is there a way to do this?  I guess it's sort of like silent commands, running to their full extent, but not returning any text.  I can't use 'try', because it's not a Python error.
Comment: `os.system()` is deprecated. Use the [subprocess library](http://docs.python.org/library/subprocess.html) instead.
Answer: You could redirect the command's standard error away from the terminal. For example:
# without redirect
In [2]: os.system('ls xyz')
ls: cannot access xyz: No such file or directory
Out[2]: 512

# with redirect
In [3]: os.system('ls xyz 2> /dev/null')
Out[3]: 512

P.S. As pointed out by @Spencer Rathbun, the subprocess module should be preferred over os.system(). Among other things, it gives you direct control over the subprocess's stdout and stderr.
Comment: @lucase.62 no- Use `subprocess.Popen`
Answer: The recommended way to call a subprocess and manipulate its standard output and standard error is to use the subprocess module.  Here is how you can suppress both the standard output and the standard output:
import subprocess

# New process, connected to the Python interpreter through pipes:
prog = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prog.communicate()  # Returns (stdoutdata, stderrdata): stdout and stderr are ignored, here
if prog.returncode:
    raise Exception('program returned error code {0}'.format(prog.returncode))

If you want the subprocess to print to standard output, you can simply remove the stdout=….


RPM Build Issue

Question: I build my rpms as such:
rpmbuild -bb SPECS/python.spec
With the following spec file:
%define _topdir /home/rpmbuild/python
%define name Python
%define release 1
%define version 2.6.4
%define buildroot %{_topdir}/%{name}-%{version}-root

BuildRoot: %{buildroot}
Summary: python
License: GPL
Name: %{name}
Version: %{version}
Release: %{release}
Source: %{name}-%{version}.tar.bz2
Group: Python

%description
Python, compiled by Jon Haddad for CentOS

%prep
%setup -q

%build
./configure --prefix=/usr/local
make

%install
%makeinstall

%files
%defattr(-,root,root)
/usr

Here's the error I get when I try to install:

[root@puppet rpms]# rpm -ivh
  Python-2.6.4-1.x86_64.rpm error:
  Failed dependencies:
  /home/rpmbuild/python/Python-2.6.4-root/usr/bin/python2.6
  is needed by Python-2.6.4-1.x86_64
  /usr/local/bin/python is needed by
  Python-2.6.4-1.x86_64
  /usr/local/bin/python2.6 is needed by
  Python-2.6.4-1.x86_64

I really don't have any experience building my own RPMs, but I'm trying to set up a puppet server, and it seems to favor install via RPM.  I need to use versions of software that aren't available as RPM yet on CentOS.
The RPM file is created in the RPM directory - but I have no idea what the error means.
Any ideas?  Thanks in advance.
Answer: It helps to understand a little about how RPM works here.
RPM will be automatically adding requirements for particular classifications of file that it knows about (eg ELF shared libraries, #! scripts, etc):
http://www.rpm.org/max-rpm-snapshot/s1-rpm-depend-auto-depend.html
What is happening here is that some of the contents of the payload have been picked up with having requirements that are not packaged:
/home/rpmbuild/python/Python-2.6.4-root/usr/bin/python2.6
/usr/local/bin/python2.6

We can verify this by running rpmbuild -bi Python.spec to run the build up to the install stage. Based on the information supplied above you could search for files:
find /home/rpmbuild/python/Python-2.6.4-root/ -type f -exec grep \ /home/rpmbuild/python/Python-2.6.4-root/usr/bin/python2.6
I'd say you're looking at:
/home/rpmbuild/Python-2.6.4-root/usr/bin/python2.6-config for the the file that has a shebang that refers to the full buildroot and a bunch of scripts that refer to  /usr/local/bin/python2.6
RPM isn't doing anything wrong here, and the details of the right way to fix this up will often be specific to the build of the package you're building.
One approach to fixing this would be to set AutoProvReq: no in the preamble of the SPEC file, eg directly after Group: Python. This should give you an installable RPM but you could argue that it's not taking full advantage of RPM's dependency model and you'd have incorrect paths in some of your Python package files.
Lets specifically look at the Python build and try and understand what we could do to fix this in a more comprehensive way.
Your %install section uses the macro %makeinstall which expands by default as:
[pnasrat@centos5 ~]$ rpm -E '%makeinstall'

  /usr/bin/make \
    prefix=/usr \
    exec_prefix=/usr \
    bindir=/usr/bin \
    sbindir=/usr/sbin \
    sysconfdir=/etc \
    datadir=/usr/share \
    includedir=/usr/include \
    libdir=/usr/lib64 \
    libexecdir=/usr/libexec \
    localstatedir=/var \
    sharedstatedir=/usr/com \
    mandir=/usr/share/man \
    infodir=/usr/share/info \
  install

For reference I tend to consult the upstream Fedora SPEC, which is much more complicated but can be made to build (with some modification and a patch for autotools versions IIRC) a parallel python26 package. I'm not going to go into the detail of that right now but if we look at how they install the key line is:
make install DESTDIR=%{buildroot}
I'd strongly recommend doing that rather than disabling AutoProvReq. As Python is a libtool based build that is probably better than the %makeinstall macro as you've already configured prefix. That seems to do the right thing by inspecting here. Note, if you are rebuilding with this change you'll also want to add:
%clean
rm -rf $RPM_BUILD_ROOT

And want a similar rm line at the beginning of the %install section. This all seems to work for me:
[pnasrat@centos5 RPMS]$ rpm --test -ivh x86_64/Python-2.6.4-1.x86_64.rpm
Preparing...                ########################################### [100%]

It might well be worth using a python2.6 package provided elsewhere, I believe IUSCommunity provides packages, as documented here - http://agilesysadmin.net/recent-python-on-rhel-or-centos. These are probably much closer to the fedora packages.
Comment: Adding the 2 rm lines and changing the %makeinstall worked perfectly.  Thanks paul!

Even if there's Python packages for Centos, I'm sure there's other packages I'll need that aren't, so this is more of a crash course in building RPMs.

RPM Build Issue


Calculate the measure of a measurable set under nonlinear mapping.

Question: It is known that:
If $\cal{A} \subset \mathbb{R}^n$ is Lebesgue measurable, and $L: \mathbb{R}^n \rightarrow \mathbb{R}^n$ is a linear mapping, then $L(\cal{A})$ is Lebesgue measurable and
\begin{align}
\mu(L({\cal{A}})) = |\det L|\mu(\cal{A}),
\end{align}
where $\mu({\cal A})$ is the Lebesgue measure of ${\cal A}$, and $|x|$ returns the absolute value of a real number $x$.
But what if the mapping is nonlinear? In particular, if $F:\mathbb{R}^n \rightarrow \mathbb{R}^n$ is a continuously differentiable nonlinear mapping (but is not bijective), what the value $\mu(F({\cal{A}}))$ should be? Are there any textbooks for explaining it? Thank you very much!
Comment: The question is quite broad, and I doubt there will be a general formula to simply calculate $\mu(F(\mathcal A))$ because the set of mappings you allow is huge and varied.
Comment: There is the following generalization of the usual change of variables formula: If $f : \Bbb{R}^n \to \Bbb{R}^n$ is Lipschitz, then $\int_A |\det(Df)| \, dx = \int_{\Bbb{R}^n} |A \cap f^{-1}(\{y\})| \, dy$, where $|A|$ denotes the cardinality of a set. The right-hand side coincides with $\mu(f(A))$ **if $f$ is injective** (otherwise you have to take "multiplicities" into account).
Answer: In the case where $F$ is injective, you have $\mu(F(A)) = \int_A |\det DF| \; d\mu$ where $DF$ is the Jacobian matrix of $F$.  If it's not injective, find (if possible) a measurable set $B$ such that $F$ is one-to-one on $B$ and $F(B) = F(A)$, and then $\mu(F(A)) = \mu(F(B)) = \int_B |\det DF|\; d\mu$.


I can recognise intervals, but why do I have difficulty in hearing them in a song?

Question: I have been transcribing music without an instrument for quite some time now, if I have my instrument in hand I am able to almost always quickly figure out what is being played but when I step away from it which I have been doing a lot lately while actively listening to music, why do I find it difficult to quickly decipher the intervals even when I  know the intervals. Does internalizing the intervals take time...
Comment: Your description is confusing. "transcribing music without an instrument for quite some time" and also "when I step away from [my instrument] ...difficult to quickly decipher the intervals." It seems like you mean it's hard to transcribe without an instrument, but you want to do it by ear alone. Is that the issue?
Comment: You've learned how to reproduce intervals with your instrument. If you learn to do this with your voice you'll always have your instrument with you.
Comment: @BobsaysreinstateMonica - not so easy with voice. With any instrument, there's something to actually see, so it's totally tangiable. With voice...it's like saying 'well, you can always play a G note on whatever instrument. So sing a G now!'
Comment: @tim I'd say it's easier with voice - no keys to press or bows to move about. And the voice is more tangible than any other instrument - you can feel it inside you.
Comment: @BobsaysreinstateMonica - I used tangible on purpose (but spelled it wrongly!) as I don't believe one's voice is - tangible. We'll agree to differ.
Comment: @Tim - sounds like you have a closer connection to your guitar than your voice. Guess I'm the other way round (which is a good thing since I can't play the guitar for toffee).
Comment: @BobsaysreinstateMonica - not actually saying that from a me position - I'm fine with vox, guitar, piano etc. I just feel that more people would find an instrument easier to play an interval on, than sing that interval.
Answer: As Tim correctly says, it's an entirely different thing. Here's what I would recommend (i. e. what helped me):

Practice sight-singing (i. e. singing from the score only if you are played the first note on an instrument). It's sort of an inverse problem but it helps immensely (and not only with transcribing). I bought a sight-singing book to practice with; you might do the same or just look something up on the Internet.

Transcribing takes time even if you know how to do it. Typically you will need to break the song into bits (each few seconds long) and play each of them multiple times. (It's not something you would plan beforehand. You just play the song, and pause it when you see you won't be able to transcribe more in that one go.) It also helps to slow the playback down, if you have a player that can do it.

If a particular bit is too hard to transcribe, use your singing as a proxy. You will quickly catch the problematic melody and be able to reproduce it by singing, and then you can sing it as slow and as many times as you want. I use this especially when transcribing complicated rhythms (they are often easy to reproduce but hard to write down).

Obviously it also helps to practice transcription itself. There are many apps for ear training and this is usually dubbed "Melodic Dictation". I have been using ToneSavvy, but there is gazillion more — just Google for them or look into your phone's app store and you will find several.

There are two different ways of attacking the sight-singing/transcription problem: you either track intervals between each note and its successor, or you concentrate on the tonic and track each note's relation to it. For me, the second method wins, but everybody needs to decide what works the best for them — it's entirely personal.

In short, it's just like transcribing with an instrument, but the instrument in question is your voice. However that's far more than using just another instrument, since when singing, your brain will internalize the intervals etc. much better (it's much "closer to the CPU" in a sense and not reduced to putting your fingers somewhere).
Comment: Great answer. I'd add that there are also apps to help with transcription, which can be a good learning tool. Some just help to manipulate playback, others identify tones and suggest chords etc.
Answer: I think there's a big difference between hearing two notes (or more), and being able to play them on your instrument, and hearing those same notes and naming their intervals with no other reference.
In fact, often, on guitar in particular, (but in reality on any instrument) we can hear a couple of notes, and instinctively hit the second one once the first has been found. I think that most of us will not even consider what the note/s are called, or even what interval there is between them. After lots of playing, it often becomes 'second nature'. It's known as having relative pitch.
Once the instrument isn't there to help, it becomes more academic, and especially where two notes in the middle of a phrase are concerned, we need to stop and count. And referring to scale or root note often doesn't help.
Like most things, getting good at something does take time, and I guess you've spent a lot more time playing your guitar than trying to internalise those intervals. So keep going!
Something which will help is to visualise the two notes involved, referring to how you'd play them on guitar. Which string, which fret each would be on. Then you can  come up with an answer. But - bear in mind that each interval heard or played will have a variety of names - e.g. is it an augmented 4th or a diminished 5th. For that solution, you need to determine what each note would be when written down. The plot thickens...
Comment: +1 especially for the last paragraph - it's quite a few years ago now, but when studying for theory exams at school I literally used to draw out a fretboard and plop notes onto it to help me visualise what I was trying to learn. Scribbling 6 parallel lines all over the place made my notes very messy but it really helped.
Comment: I think you're complicating things unneccessarily - visualising how you'd play a note on guitar (or any other instrument) is an extra mental step. But if it works it works.
Answer: This may be a different perspective from other answers, but this fairly-influential study in patients with intractable epilepsy looked at the ability to distinguish note intervals in order to correlate the brain ares responsible for processing such things. They noted that with respect to timing of notes, there was a fundamental dissociation between metre and rhythm in terms of which areas might be involved. For example, the two hemispheres were involved differently during musical processing; the posterior part of the superior temporal gyrus appears to be exceptionally important during such processing. This is not to say that anything is wrong with your brain, but only to suggest that there is at least some empirical evidence to suggest that there are stereotyped pathways in the brain that are recruited during such behavior (interpreting music).
As far as the difference you experience when you have a guitar in your hand or when you do not: in motor control, the cerebral cortex is sometimes described as a "dynamical engine" that drives volitional movement. In this conception, there is a latent encoding of the state of the limb in the ongoing activity of many thousands of neurons simultaneously in the motor cortical areas, which might serve as an internal model and enable adaptive movements when the cortex is required (for example, if you are paying close attention to the way your hand moves along the guitar).
My speculation is that these things might be related in some way to your situation (please understand that it is purely speculative and not based in any empirical observation to directly validate such a claim). I think it would be interesting if the limb state information in the cerebral cortex while you have a guitar in-hand is transferred in some way to the temporal gyrus, facilitating your ability to encode or decode interval information in the music. Again, I do not have the background to imply whether such a thing actually does occur in reality.
Answer:
You probably know the trick to connect each interval with the first motif (interval) of a song: e.g. dim 5th (respectively aug. 4th) => "Maria" and minor 7th => "Somewhere" (West Side Story)
Each tone of a melody has a function by its tension, or may better, a tension by its function: tonic and dominant are stable, fa and ti are leading tones, la is somehow hanging over sol, re = passing tone between do and mi etc.
Trial and error: listen, write, play, correct.
Composing short motifs to each interval as your own unique modules for sight reading, recognizing and working tools.
Training systematic solfege:
scale back to root: doredomidofadosodoladotidodo up and down.
scale of 3rds: domi refa miso fala ...
scale of 4ths etc.
Triads and tetrads on all degrees (with resolution)
e.g.: sotirefa ... mido
Inversions and augmented 6th chords and resolution:
Arpeggios: singing preludes by Bach with names of moveable doremi.


How much randomness is in human-generated random digit string?

Question: Suppose someone is asked to provide a long string of random digits, for example:
<code>4866710938572235108576927175549668592830123185576923856998372006958477486523
(just typed on keyboard, not generated in any way)
</code>
How good is it expected to be if used as random source?
For example, can I ask someone to think up a list of {1,2,3,4,5,6} numbers and use it instead of a dice (and expect each number to come with p=1/6 knowing the previous numbers).
Is it safe enough to just think up UUIDs without looking for UUID generator tools?
Is there some simple (not requiring any devices or pencil&paper) algorithm to improve "thought up" random sequences?
Update: Trying little experiment as suggested in one comment:
<code>$ xxd -r -p > test
93B83C5F40691FBE582D54886E590C59B8A39623D7C5013B693D0598C58EB58A482BC857283D859C5830F5829C58BD482ACB4829E4859D58CBA482E859BCEF5928877018394E492855810F0384911D1496839B58394D36829C5029304E6839402885D59329D58F47B573FCE572BFCE472D768CB573D729559EF1905928492DC68BA58C8F83EF4823BC59ED5BAA582CE183944919EDE758B1120B060704B60330D16637D6477283BC5829E204CD3811B859E3AD8B50233549D12984BC5823591BCEADA86923EB568C923DD5482F694BCD68492BEA584BC9684BE8D8B8CA8C858BE45B9C9DB5CD62D8592ED8A923BC69E92D91343DCA9F3E042934

$ paq8l -4 test
    Creating archive test.paq8l with 1 file(s)...
    test 250 -> 270
    250 -> 292
    $ tail -n +3 test.paq8l  | wc -c
272
$ dd if=/dev/random of=test2 bs=10 count=25 iflag=fullblock 2> /dev/null
    $ paq8l -4 test2
Creating archive test2.paq8l with 1 file(s)...
test2 250 -> 274
250 -> 297
</code>
Both files (manualy typed and /dev/random-generated) seem to be uncompressible.
Comment: This isn't really a mathematical question. It's more of a psychological one.
Comment: This seems a bit like asking "how good are people at estimating the areas of triangles?"  There's certainly a mathematical aspect to it, but the main question itself is about how good humans are at something, so it's essentially a psychological question.
Comment: I don't remember the source, but I've seen it reported that human-generated strings typically have fewer repetitions than would be expected of a randomly generated string.
Comment: I thought measuring the randomness/entropy is a mathematical thing.
Comment: There are statistical test suites to test quality of PRNGs - for example TestU01 or DieHard tests.
Comment: The thing here is that randomness depends on perception.  For example, there are mathematical theories on electoral fraud based on the assumption that humans percieve numbers like 333, 123, etc to be less random than, say, 738. As consecuence, if one individual is altering large ammounts of data, the distribution of digits, adjacent numbers, etc, won't be natural. Of course, as any other _soft_ theory, it can be rebated very well.
Comment: There are programs that typically beat a human at rock-paper-scissors, so in that sense I think it's psychologically difficult for a human to make up good impromptu pseudorandom sequences: http://ro-sham-bot.appspot.com/ If you memorize digits from a table of random numbers, you can do as well as any computer pseudorandom number generator. You could also learn some mentally computable algorithm for generating pseudorandom numbers.
Comment: @Ben Crowell, Tried that "rock-scissors-paper" bot. When I click the buttons at random the result is usually approximately equal score (as opposed of slightly losing if I try to think about moves and predict strategy).
Answer: I think I cannot answer your first question (and I would say that this is generally hard to tell - depends whether the person really wants to generate random numbers - I wouldn't use this in some critical applications).
However - speaking of pencil&paper PRNG there is one developed by Bruce Schneier in his Solitaire encryption algorithm.
Comment: Well its too subjective - Myself, I think I cannot filter outter things while thinking numbers from the top of my head. You could try to think off some numbers, convert them to bytes and then try to compress it and compare it's size with the uncompressed version to get a rough entropy estimate. Truly random stuff is almost incompressible.
Comment: The person wants to generate random thing (i.e. not trying to cheat anyway) yet does not calculate anything in head, just say numbers.
Comment: Tried to compress the file I typed. It does not seem to be compressible.
Answer: If a human be asked to select random number from 1 to 10, the number 7 would be selected with probability near to 1/3.  So, don't believe human-generated random numbers.  :-)
Comment: Citation needed?
Comment: Citation needed!
Comment: This is experimental data from a Russian forum, hundreds of laymans participated in that poll.  Unfortunately, I did not save the link to that thread.  But you can easily reproduce this result by making the same poll in any forum not concerning with math: question = "select random number from 1 to 10", answer choices = 1, 2, .., 10.


How to fetch manual flate rate token on replacement pattern

Question: How to fetch manual flate rate token on replacement pattern
I added Flate Rate cost manually on orders, but I don't find this token on REPLACEMENT PATTERNS. How to fetch this token for my invoice?
here screenshot that I did
Answer: You would need to two things to make this happen:

How to programmatically create a custom token. And you'll definitely want to read the API docs on the relevant hook function.
How to get at the line item given an order.

Let's assume your token has an $order object inside the $data variable. The next step would be to use entity metadata wrappers to pull in all the information, including line items.
<?php
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $line_item = $line_item_wrapper->value();
}
?>

Your shipping line item is in there. dpm($line_item); to find it and then construct your token output.
Comment: If you're using rules, you could always "fetch an entity by id" and actually fetch the shipping line item based on the order field. Anything brought into scope for rules would show up as a token.
Comment: Thanks  a lot joshmiller, but i'm a programmer and need more time to learn. I guess and I wish this token show up when click replacement pattern.


hide/resolve warning messages on my website

Question: Warning: mkdir() [function.mkdir]: No such file or directory in
 /var/www/humspm/data/www/humspm.com/gettext.php on line 17 CMD:EXIT
can you please help me to resolve this issue
Thanks in adavence
Answer: You can turn off notifications in PHP:
<?php error_reporting(0); ?>

More:
http://php.net/manual/de/function.error-reporting.php
http://www.w3schools.com/php/php_error.asp
I recommend to solve the issue with correct coding instead of just turning off errors and warnings!
For your issue, just check if the file or directory exists before you try to work with the filesystem. (check the PHP manual for file_exists() and is_dir())
Answer: From the CAKEphp manual:

Error configuration is done inside your application's
  app/Config/core.php file. You can define a callback to be fired each
  time your application triggers any PHP error - exceptions are handled
  Exceptions separately. The callback can be any PHP callable, including
  an anonymous function. The default error handling configuration looks
  like:

Configure::write('Error', array(
    'handler' => 'ErrorHandler::handleError',
    'level' => E_ALL & ~E_DEPRECATED,
    'trace' => true ));

You have 5 built-in options when configuring error handlers:
handler - callback - The callback to handle errors. You can set this
  to any callable type, including anonymous functions.
level - int - The
  level of errors you are interested in capturing. Use the built-in PHP
  error constants, and bitmasks to select the level of error you are
  interested in.
trace - boolean - Include stack traces for errors in
  log files. Stack traces will be included in the log after each error.
  This is helpful for finding where/when errors are being raised.
consoleHandler - callback - The callback used to handle errors when
  running in the console.
If undefined, CakePHP's default handlers will
  be used. ErrorHandler by default, displays errors when debug > 0, and
  logs errors when debug = 0. The type of errors captured in both cases
  is controlled by Error.level. The fatal error handler will be called
  independent of debug level or Error.level configuration, but the
  result will be different based on debug level.

Link to manual
Answer: First of all check what causes this issue,

Check folder permission
Check whether you have privileges to create a directory inside the specific location.

Still if you want to silence the error

You can add @ in front of mkdir
You can disable error reporting.
Comment: Nishanth: File location is not there like /var/www/humspm/data/www/humspm.com/gettext.php in my code but it is showing  message my site
Answer: Please see your directory structor carefully.According to url something is repeating into your url.
/var/www/humspm/data/www/humspm.com/gettext.php

Also see mkdir is only working with the directory path, not the URL or domain.
    You should have to point to your subdomain's absolute path, not the URL.
Comment: Hello Manoj Greetings, I do not have directory structure like /var/www
Comment: Cheers dear  :)
Please be careful about url and domain path.Both are different things.
Answer: I ran into the same error on a client's WordPress site:
(Warning: mkdir() [function.mkdir]: No such file or directory in /var/www/humspm/data/www/humspm.com/gettext.php on line 17 CMD:EXIT)

I found that their index.php file was calling a file named cache.php on line 1.
cache.php contained obfuscated code that appears to have been attempting to use the invalid absolute path. The use of obfuscated code probably explains why you couldn't find any reference to that directory path in your code.
The actual file name may differ in your site, I'd recommend looking out for any unfamiliar php files in the same directory as your index.
Commenting out the line in index.php that called to this cache.php fixed the issue with the warning message.
However, the file itself appears to be malicious so I'm recommending that my client harden their security and scan for additional malware. You might want to do the same.


The module does not dissapear after disable, uninstall, clear cache and cron job

Question: I want to completely remove the File entitymodule from my Drupal site.
I've disabled the module via Modules in admin panal. Then I also uninstalled it though the panel. After that, I've deleted the files from ftp located under /sites/all/modules/file_entity.
I've cleared the cache. I've run the cron. I even tried /update.php but it says there's nothing to update Review updates step.
When I log into administration panel, I still see that ghost:

I don't have any module that is dependent on File entity.
How to remove that module? I want to do so I can install the new fresh version of it which I need.
Answer: This module might live in a profile or in a directory that is not sites/all/modules. It is possible to have the same module in multiple places in Drupal at the same time.
You should open up the database, go to the system table and look for the entry for file_entity and see what the path is. That will tell you. You could also grep your codebase for "File entity" or "file_entity" which should also produce results.
If not, perhaps you are on a dev/stage environment? Did your FTP program actually delete the files? Check that there wasn't a permission issue regarding deleting that.
edit: if this is an older release of the media module, it used to ship with file_entity under media/modules/file_entity if I recall. Also check there. If that is the case, what you should do is completely upgrade the media module to the latest version, which looks like rc2 right now.
Comment: Okay, thats what I thought. Media module used to ship with that module included, and at some point it was removed. I couldn't find that in the git history at a quick glance, so I removed that part of my answer. I will restore it.
Comment: That was the case! The module was located under `/sites/all/modules` but also e.g. `/sites/all/modules/media`.


Alternatives to Chi-Squared for Single Categorical Outcome and Single Categorical Predictor w/counts for factors [R]

Question: I am from an applied background, where X2 and G-tests are the default ways to analyze count data (default as in, until today, I had no idea there were other ways, as I was only taught these methods).  However, now that I see there are model-based approaches, I would like to analyze my data in this fashion (if possible).
The data is in a contingency table, and the first column is an individual.  Each of cells in the next five columns has a count for something, such as a clothing type.  Thus, I have something like
Person    Jeans    Collar.Shirt     Mini.Skirt     Maxi.Skirt     Tank.Top
1               5          10                4               2            7
2               7           5                12              5            15
3               15          7                10              10           8
4               6           7                3               11           17

If I consider my first column a response variable, and the next five as predictors, I should, in theory, be able to do some type of regression.  However, for this, it seems that since clothing types are all clothes, I end up with a single predictor, with counts as each level of a factor.
Because I have more outcomes than predictors, assuming I consider each its on IV, a multinomial logistic regression is going to end up with a lot of empty values, making this (in my mind, anyhow) inappropriate.
That leaves me with, as far as I know, Poisson and negative binomial regression.
When I attempted, in R, a NB model, using MASS on the wide-format table above, I get an error.
This is the code I used for the NB:
summary(NB <- glm.nb(Person ~ Jeans + Collar.Shirt + Mini.Skirt + Maxi.Skirt + Tank.Top, data = d))

This is the error:
 Warning messages:
    1: In theta.ml(Y, mu, sum(w), w, limit = control$maxit, trace = control$trace >  :  iteration limit reached
    2: In theta.ml(Y, mu, sum(w), w, limit = control$maxit, trace = control$trace >  :  iteration limit reached

When I do Poisson for this same dataframe, I do get results.  Nothing significant, other than the Null...and each of the IV's have Z=0 and p=1. The Null Deviance is 10.3 and the Residual is 0.4.  As I understand it, since the Residual is quite low, this model, as insignificant as it may be, does well at explaining the data. However, it seems inappropriate to use this model, given I technically have factors of a single predictor.
So, if I reshape the data into a long format, so that it looks like:
Person    Clothing         Count
1               Jeans             5
1               Mini.Skirt        4
1               Maxi.Skirt        2
1               Tank.Top          7
2               Jeans             7
...             ...               ...

where there are now five factors for the predictor "clothing" and counts of each item for "count",
and run the code for NB:
summary(NB2 <- glm.nb(Person ~ Clothing, data = d))

or run the code for Poisson:
summary(pois2 <- glm(Person ~ Clothing, family = poisson, data = d))

my Null and Residual Deviance values are the same (for both).  This indicates a problem, I would think.
So, this all being said...Is there a way to do this, or am I stuck with my old standby??
Thank you!
Comment: Welcome. I don't think I am the guy who can answer, but for the others : How your dataset looks like is not really clear, could you edit your question by giving us some rows and tell us what the variables are. Maybe giving the exact formula you typed in R could help too.
Comment: Made edits.  Let me know if it's still unclear.
Answer: [This was supposed to be a comment, but it got awfully long.]
Thanks for the edit ! This is much better ! Now I may see a part of the problem. I guessed $Person$ is the same as $Individual$. I think that in your mind, by analogy with the chi2 test, Person ~ Clothing represents the association between Individuals and Clothing. But as far as I know, it does not work like that. The response variable (at the left of the ~) is want you want to predict, what we call the response term. So in your case, you would prefer sthg along the line of Count~ Individual+Clothing. But you are looking for an interaction with Individual and Clothing, so Count~ Individual*Clothing, including all the interactions terms is more close from what you want.
But this won't work as you you will end up with too many free parameters. I think you should look at how mixed effects linear model works. This is certainly more complicated than a simple Chi squared test, but it's quite interesting. Very briefly, you may end up to study if individuals differ in their clothing by studying if there is a random effect or not at the scale at individual*clothing pick. Intuitively, one can think that it's less free parameters consuming than considering that each individual preferences must be estimated, on the contrary with a random effect model we only model a kind of random disturbance that create heterogeneity in individual preferences. If this disturbance is small enough to be rejected, there is independence, if it's a big one, there is no independance.
I don't know mixed effects models enough to get into more details (especially the specification of the random effects there), but may some more knowledgeable folks help you.
Comment: I actually am interested in discerning is there a difference between Person, given counts for the levels of Clothing.  Thus, I am trying to predict Person, not count.  In an ideal scenario, I would have more levels of IV than the number of classes of Person I am trying to predict, and a multinomial logistic regression would be my approach.
Comment: Oh. I see. I looked through multiple times your answer to get where I missed that until I check the title of your question...sorry. So let's talk about it and I ll edit my answer if I can later. 3 things I want to be sure : when you say more levels of IV, you mean more type of clothing ? Also you won't have any other IV ? Last thing : you won't have more rows by individual (like N_row will be always N_indiv*N_levels) ? If yes to three, you can't predict Person and I can more or less explain why.
Comment: I actually just found myself in another conundrum...after I adjust the counts for clothing based a separate variable (but one that is utterly non-independent from clothing counts, such as total number of articles of clothing), both at the level of individual and individual relative to total, I now end up with numerous cells having very small values...some <1.