Process of identifying quotients of polynomial rings

Question: I'm taking an abstract algebra class and we are introducing quotient rings specifically polynomial quotient rings and I'm trying to work out some example problems, but I cannot figure out a general way to approach problems where we're asked to identify something like $\Bbb Z[x]/I$.
The example I have is that we can identify $\Bbb Z[i]/(i-2)$ to $\Bbb F_5$ first by killing $g=x-2$ and then killing $f=x^2+1$.
So with this approach if I have for example $$\Bbb Z[x]/ (6, 2x-1)$$ then if I first kill $2x-1$ and then $6$ I should be able to arrive to some isomorphic ring to this?
Killing $2x-1$ is apparrently done by defining a map $\Bbb Z[x] \to \Bbb Z[1/2]$ where $x \mapsto 1/2$ and since the kernel of this map is generated by $(2x-1)$ I'll get an isomorphism $$\Bbb Z[x]/(2x-1) \cong \Bbb Z[1/2].$$
Now following this I should kill $6$ in $\Bbb Z[1/2]$ to get some kind of isomorphism from $\Bbb Z[1/2]$ to some other ring and I suppose then I can conclude that $\Bbb Z[x]/ (6, 2x-1)$ is isomorphic to the obtained ring?
How do I go about killing $6$ in $\Bbb Z[1/2]$? I don't think I understand how to construct something like this and what should the target ring even be in this case?
Comment: Z[x]/(6,2x−1) = Z_6[x]/(2x-1)
Answer: Solution 1. As you were told, $\mathbb Z[x]/(6,2x−1)\simeq\mathbb  Z_6[x]/(2x-1)$. But
$$\mathbb Z_6[x]/(2x-1)\simeq
\mathbb Z_2[x]/(2x-1)\times\mathbb Z_3[x]/(2x-1)\simeq\mathbb Z_3.$$
Solution 2. You can use the rings of fractions: $$\mathbb Z_6[x]/(2x-1)\simeq S^{-1}\mathbb Z_6,$$ where $S=\{\bar 1,\bar 2,\bar 4\}$, and then notice that $S^{-1}\mathbb Z_6\simeq\mathbb Z_3$.
Solution 3. As you noticed,  $$\mathbb Z[x]/(2x-1)\simeq\mathbb Z[\frac12].$$ Then $$\mathbb Z[x]/(6,2x-1)\simeq\mathbb Z[\frac12]/6\mathbb Z[\frac12].$$ But $6\mathbb Z[\frac12]=3\mathbb Z[\frac12]$, and you arrived at $\mathbb Z[\frac12]/3\mathbb Z[\frac12]$. This is isomorphic to
$S^{-1}\mathbb Z_3$, where $S=\{\bar 1,\bar 2\}$. Since $\bar 2$ is invertible in $\mathbb Z_3$, you actually got $\mathbb Z_3$.
Comment: Thanks for the multiple approaches! Solution 3 makes most sense to me at this point. May I ask how do you get the isomorphism $\mathbb Z[x]/(6,2x-1)\simeq\mathbb Z[\frac12]/6\mathbb Z[\frac12]$ from $\mathbb Z[x]/(2x-1)\simeq\mathbb Z[\frac12]$?
Comment: Also btw is it true in general that $\Bbb Z[x]/(n, p(x)) \cong \Bbb Z_n[x]/(p(x))$ for $p(x) \in \Bbb Z[x]$ and $n \in \Bbb Z$? I think that you're using something like this in Solution 1?
Comment: If you have an isomorphism of rings $f:R\to S$, and $I$ is an ideal of $R$, then we get an isomorphism $\bar f:R/I\to S/f(I)$. This is what I used in solution 3.
Comment: What you say in the second comment is true. Here one uses the following isomorphism theorem: $(R/I)/(J/I)\simeq R/J$.
Comment: Solution 4: Consider the ideal $I = \langle 6, 2x - 1 \rangle$.  Then $x(6) - 3(2x-1) = 3$ is also an element of $I$.  So also, $x(3) - (2x-1) = x+1$ is in $I$.  From here, it should be straightforward to show $I = \langle 3, x+1 \rangle$.  Once you have that representation of $I$, it should be easy enough to either mod out by 3 and then by $x+1$, or vice versa.
Comment: @DanielSchepler Why don't post it as an answer? Comments are for referring to an existing answer.


Is there any way to force a custom block in the Custom Block Library to invalidate cache on edit update?

Question: I have created custom blocks in the Custom Block Library and placed instances of the blocks on a page in Block Layout.  The blocks get cached for anonymous users.
Editing the custom block and saving does not invalidate the cache for those instances of the blocks. Looking in the "cache_render" table I see that caches for blocks get created through the Custom Blocks Library are set to never expire as a default with no options I can see available in the admin UI.
I have to actually "Flush All Caches" using the Devel module to have the changes appear, or another way I have found is to go to the Block Layout page and click the "Save Blocks" button without changing anything.  The cahces for all the blocks will invalidate.
I don't want to give access to Devel to an average content manager or have to try to explain that they have to do a non-obvious extra step to have their block content changes appear.  Am I missing a setting in the UI that will invalidate the cache of those blocks on edit save?
I can cobble together a module that would add an extra submit handler that would invalidate the cache using \Drupal::service('cache_tags.invalidator')->invalidateTags() if I can get the cachetags for all instances of the block on save ... but I'm not sure how to get that info, and that just seems like a hack.
I'm hoping I'm just missing something.
Comment: @Jaypan Since these blocks aren't ones that I've created programmatically but created through the standard admin UI, I'm not setting the cache tags, Drupal assigns the tags. I would think that any update made to to those blocks would handle invalidating cache like updates to nodes seem to do.  But, since that doesn't seem to be the case, I've thought about hooking into the block form submit and doing it myself if I could get all instances of the block's cache tags. I just don't want to do something that seems hackish if there is any standard way to force these UI created blocks to invalidate.
Comment: You have the right idea on invalidating the cache using cache tags. But rather than pulling the cache tags from the block, you should set them as something that can be determined without the need to do so. For example if your custom block is based around a user entity, you may want to set the cache tag as #custom_block-user-[UID] or something like that.
Answer: I came across this question in the related questions sidebar on my question that seems to be the same issue with out-of-the-box core blocks:
Block cache not clearing on save?
The accepted answer from @4k4 on that question seems to confirm the issue, but doesn't hook in to the block save to invalidate the cache like I was thinking, but mentions, as one possible workaround, adding this to the theme:
function mytheme_preprocess_block(&$variables) {
  if ($variables['base_plugin_id'] == 'block_content') {
    $renderer = \Drupal::service('renderer');
    $renderer->addCacheableDependency($variables, $variables['content']['#block_content']);
  }
}

I don't know if this is the best answer, but it's simple and straightforward and seems to work at the moment, though it's a wonder that this would need to be done at all.  It's probably less of a hack than what I was thinking.
Comment: I had a similar issue, and the solution was to render the `{{ content }}` field in the block template because it otherwise won't bubble up. That solved it, and I relented to doing `{{ content|without('field_foo', 'field_bar', etc) }}` because the twig template needed a very specific markup.
Answer: Setting max age to 0 saved my day
function MODULE_NAME_preprocess_block(&$variables) {
    if ($variables['base_plugin_id'] == 'block_content') {
        $variables['#cache']['max-age'] = 0;
    }
}

Comment: You saved me! Thanks a lot. This works like a charm.


If $p>0$ and$ q>0$, And $p^2-q^2$ is a prime number, then $p-q$ is...? Please help

Question:
The answer is part $d)$none of the above, How do i proceed with such questions?
Comment: $(p^2-q^2)=(p-q)(p+q)$, from the fact that $p^2-q^2$ is a prime number and $p+q>p-q$, what do you have?
Comment: It can't be a prime number unless p-q=1
Comment: I know you know how to use MathJax, so you should take the time to write out what the textbook or handout says instead of just posting a photo of it.
Answer: Note that $$p^2-q^2=(p-q)(p+q)$$
From the definition of prime numbers, it follows that $p-q=1$.
If $p-q \neq 1$, then $p-q$ is a number that divides $p^2-q^2$ that is not $1$ or $p^2-q^2$.
Comment: so $p=3$ and $q=2$
Comment: @JorgeFernándezHidalgo I'm afraid I don't see how that follows.
Comment: @JorgeFernándezHidalgo On the contrary, $p=4, q=3$ are solutions as well. There is no mention that $p,q$ are prime numbers.
Comment: oh, my bad. I assumed by the variables
Comment: And if $p-q$ is not$ 1$ then $p^2-q^2$ ceases to be a prime number. I understand your solution, Thankyou!
Comment: @MAthsjunky Your welcome. :) Would you accept my solution?
Comment: why can't it be -1?
Comment: @SubhashChandBhoria A prime number is a natural. If $p-q=-1$, $p+q>0$, then $p^2-q^2$ is a negative number. So it can't be a prime number.
Answer: given Since $p,q$ are integers and $p^2-q^2=(p-q)(p+q)$ is prime, it means that we got integer factors of primes number. And since we know that the only factors of prime are $1$ and prime only therefore we are force to believe that $p-q=+1$ or $-1$ which leaves no other choice as integrs are positive


Change plid of existing administration menu items

Question: I'm building an internal portal for an organisation and I want to change the standard administration menu, putting a number of the front-facing website options under a menu item called 'Website' and the rest under 'Drupal Config'.
So I'm simply trying to change the plid of 'admin/content', but it's not working. Could somebody guide me on where I'm going wrong please?
function eac_sponsorship_menu_alter(&$items) {

    $items['admin/content']['plid'] = 592; //592 is id of 'Website' menu item
    menu_link_save($items);

}

Also are there likely to be any repercussions from doing this?
Note that in the final solution the plid wont be hard coded as "592", but will use a DB look up to get the mlid of the 'Website' menu.
Also it is not a cache issue, when checking the DB the plid of admin/content remains to be '1'.
Comment: This seems like an unnecessary dependency just for a menu alteration.
Comment: Is there a particular reason you're not doing this in configuration (and exporting a Feature if needed)?
Comment: As in using the menu interface in 'Structure'? The module has the potential to be used on a number of sites so I want the ability to simply upload and deploy.
Comment: Menus created via the GUI can be exported using Features.
Comment: Hard-coding a plid seems less portable, which is something you said you wanted? Anyway, what is "not working" exactly? Did you already look whether it appears in the menu admin screen, and is just not enabled?
Comment: Oh. That would be a problem. What's your lookup code?
Comment: The lookup doesn't appear to be the issue as I'm now testing with the hard coded number and it still doesn't apply the changes :S
Comment: And you are calling `menu_link_save()`?
Comment: @beth I did and it wasn't applying, so commented out as I don't know if it's necessary
Answer: If you want your own top level admin menu group, you should probably create your own parent menu item and section there using hook_menu
e.g admin/website and put your menu items under that.
/**
 * Implements hook_menu
 */
function my_module_menu(){

  $items = array();

  // Provide own admin configuration menu section
  // using system_admin_menu_block_page for item groups
  // Top level section
  $items['admin/website'] = array(
    'title' => 'Website',
    'description' => 'Local website configuration.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child admin menu group
  $items['admin/website/config'] = array(
    'title' => 'Configuration',
    'description' => 'Configure website settings.',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 50,
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
  );
  // Child group menu item
  $items['admin/website/config/advanced'] = array(
    'title' => 'Advanced settings',
    'description' => 'Configure advanced website settings.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_website_settings_form'),
    'access arguments' => array('administer site configuration'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'includes/my_module.admin.inc',
  );

  return $items;

}

See system_menu for an example hook_menu using system_admin_menu_block_page
Comment: Hey @David-Thomas, I have created admin/website in this way but I what I am trying to achieve is to move the existing Admin menu items 'Content', 'Structure' and 'Appearance' to be children of this.
Answer: In my example here I'm using hook_flush_caches instead of hook_menu_alter.
Also you can replace/alter db_select to return list of menu links you need to change.
/**
 * Implements hook_flush_caches().
 */
function eac_sponsorship_flush_caches() {

  $mlid = db_select('menu_links', 'ml')
    ->fields('ml', array('mlid'))
    ->condition('menu_name', 'management')
    ->condition('link_path', 'admin/content')
    ->execute()
    ->fetchField();

  if($mlid) {

    $item = menu_link_load($mlid);
    $item['customized'] = 1;
    $item['plid'] = 592; //592 is id of 'Website' menu item
    menu_link_save($item);
  }
}

also don't forget to clear/flush Drupal cache.
Answer: I am using this https://drupal.stackexchange.com/a/53531/12153
That way I tweak menus depending on weather the user logged in or not. I also used it to slightly change the secondary menu.
Together with menu_rules which allows me to add new links, I have full control over what my menus do. So far I had no issues with this solution.


$\int_{\gamma} \frac{f(z)}{z^3}dz$ - Cauchy formula

Question:
Compute the integral $$\int_{\gamma} \frac{f(z)}{z^3}dz,$$ where
  $f(z)=az^3+bz^2+cz+d$ and $\gamma : [0, 4 \pi] \to \mathbb{C}$,
  $\gamma(t)=e^{it}$.

So by the Cauchy formula $\int_{\gamma} \frac{f(z)}{z^3}dz= \frac{f^{(2)}(0)2 \pi i}{2!}=2\pi b i$, but the real answer is $4\pi b i$. How could we consider the interval $[0, 4 \pi]$ to obtain the good answer?
Answer: Since the curve wraps around twice, you forgot to multiply by 2. In general, you multiply by the winding number of the curve you do the integral around.
A quick and dirty way to see this for your simple curve is to just partition the curve tracing out the circle twice into two curves, each tracing the circle once. Call these $\gamma_1$ and $\gamma_2$. Then
$$\int_{\gamma}\frac{f(z)}{z^3} dz = \int_{\gamma_1+\gamma_2} \frac{f(z)}{z^3}dz =\int_{\gamma_1} \frac{f(z)}{z^3}dz + \int_{\gamma_2} \frac{f(z)}{z^3}dz $$
by linearity of the integral.
The general proof doesn't work quite like this because curves can be quite complicated. For a proof of the general case, you could check out Conway's text "Functions of One Complex Variable". The case involving the general curve of arbitrary winding number is  Theorem 4.5.4.
Comment: I understand, but could you explain rigourously?
Comment: @Dr.Dray See if this helps.


Problem 6.10, I. Martin Isaacs' Character Theory

Question: Let $N \triangleleft G$ with $(|G : N|, |N|) = 1$. Suppose that every subgroup of $G/N$ is an $M$-group. Show that $G$ is a relative $M$-group with respect to $N$.
Here are definitions of $M$-group and relative $M$-group in the book:

Let $\chi$ be a character of $G$. Then $\chi$ is monomial if $\chi = \lambda^G$, where $\lambda$ is a linear character of some (not necessarily proper) subgroup of $G$. The group $G$ is an $M$-group if every $\chi \in \operatorname{Irr}(G)$ is monomial.
Let $N \triangleleft G$ and let $\chi \in \operatorname{Irr}(G)$. Then $\chi$ is a relative $M$-character with respect to $N$ if there exists $H$ with $N \subseteq H \subseteq G$ and $\psi \in \operatorname{Irr}(H)$ such that $\psi^G = \chi$ and $\psi_N \in \operatorname{Irr}(N)$. Iff every $\chi \operatorname{Irr}(G)$ is a relative $M$-character with respect to $N$, then $G$ is a relative $M$-group with respect to $N$.

Since $G/N$ is an $M$-group, it is solvable. I want to use Theorem 6.22, but I don't know how to prove that every chief factor of every subgroup of $G/N$  has nonsquare order. And I don't know how to use the fact that $(|G : N|, |N|) = 1$.
Can anyone help me?
Answer: I think an argument along the following lines will work, but I haven't filled in all of the details.
Let $\psi \in {\rm Irr}(G)$. If $\psi_N$ is not homogeneous, then $\psi$  is induced from a character of a proper subgroup $H$ of $G$ (i.e. the inertia group of an irreducible component of $\psi_N$). So we can assume that $G=H$ and hence that $\psi_N$ is homogeneous.
So $\psi_N = e \theta$ for some $\theta \in {\rm Irr}(N)$ and $e \ge 1$. Since $(|N|,|G:N|) = 1$, Corollary (6.28) of Isaacs says that $\theta$ extends to some $\chi \in {\rm Irr}(G)$. Then Corollary (6.17) of Isaacs implies that $\psi =  \chi \beta$ for some $\beta \in {\rm Irr}(G/N)$.
Now use the fact that $G/N$ is an $M$-group to deduce that $\beta = \lambda^{H/N}$ for some subgroup $H/N$ of $G/N$ and a linear character $\lambda$ of $H/N$,  and so (by Frobenius Reciprocity) $\psi = (\chi_H \lambda)^G$ with $(\chi_H\lambda)_N = \chi_N$ irreducible.
Comment: Hi Derek! If you have a moment, would you mind elaborating on the first paragraph?  In particular, I am reading this as if...
 if $\psi_N$ is not homogenous, then the $e$ in definition 6.10 is equal to $1$, and since $e$ divides $|G:H|$, then $|G:H|$=1, which would violate $H$ being a proper subgroup of $G$.  is this correct?

Also, I know that if $\psi_N$ is not homogenous, then $psi_N$ is not a multiple of an irreducible character.  So that implies that we are in case c of theorem 6.11? Or am I not thinking of this quite correctly?  Thank you!
Comment: One last thing... I think in the second paragraph, don't we need $\theta\in \text{Irr}N$?
Comment: Yes, thanks, corrected!
Comment: Would you mind, if you have a moment, answering my first comment? :)
It would be much appreciated!
Comment: I can't make much sense of what you wrote. Why should $e$ in Definition 6.10 be equal to $1$? And why would that imply that $|G:H|=1$? When I wrote "we can assume that $G=H$", I meant that it is sufficient to prove the result with $H$ in place of $G$. But unfortunately, at first sight, that seems to depend on $H/N$ being and $M$-group, and I can't for the moment see how to justify that, because AFAIK being an $M$-group is not closed under taking subgroups. So I am afraid that I can't help you for the moment!


Output result depending on a second output result to extract

Question: I am trying to create a survey app with shiny. The idea here is to give a kind of weight for each question, depending on the answer of the user (Answer 1 for question 1 is 10 points, Answer 2 for question 1 is 50 points, ...). The final result of the survey is simply the sum of all answers given by the user.
For now, my code is this one:
library(shiny)

ui <- fluidPage(
      tags$h3("Test 1"),
      verticalLayout(sidebarPanel(width=8,
      radioButtons(inputId = "Q1", label = "Question 1?",choices =  c("Choice 1", "Choice 2", "Choice 3"))),
      tags$h3("Test 2"),
      sidebarPanel(width=8,
      radioButtons(inputId = "Q2", label = "Question 2?",choices =  c("Choice 4", "Choice 5", "Choice 6"))),
      actionButton(inputId="go", label="Update"),
      textOutput("result_txt"),imageOutput("result_img")))

server <- shinyServer(function(input,output) {

# Text output #
    output$result_txt <- renderText({

        Answer1 <- "Choice 1" %in% input$Q1
        Answer2 <- "Choice 2" %in% input$Q1
        Answer3 <- "Choice 3" %in% input$Q1

        Answer4 <- "Choice 4" %in% input$Q2
        Answer5 <- "Choice 5" %in% input$Q2
        Answer6 <- "Choice 6" %in% input$Q2

        if (Answer1){ resultQ1 <- 10 }
        else if (Answer2){ resultQ1 <- 50 }
        else if (Answer3){ resultQ1 <- 100 }

        if (Answer4){ resultQ2 <- 20 }
        else if (Answer5){ resultQ2 <- 40 }
        else if (Answer6){ resultQ2 <- 60 }

        tags$h4 <- paste("Your final result is ",resultQ1+resultQ2)
        })

})

    shinyApp(ui, server)

I would like to extract the final result (e.g resultQ1+resultQ2), for using it in a second output. Depending on this result, I would like shiny to display a specific image as a second output.
It should be something like that:
output$result_img <- renderImage({

if(as.numeric(resultQ1+resultQ2)>=100){
png("Image1.png")}
if(as.numeric(resultQ1+resultQ2)<100){
png("Image2.png")}

},deleteFile=FALSE)

How can I display both results (numeric result and image result) at the end of my survey, and also update the results with the action button according to the user's input?
Answer: Tested and working minimal example.
We can take advantage of the radioButtons choiceValues to simplify our code.
library(shiny)

ui <- fluidPage(

    #Question 1
    tags$h3("Test 1"),
    wellPanel(
        radioButtons(inputId = "Q1", label = "Question 1?", choiceNames = c("Choice 1", "Choice 2", "Choice 3"), choiceValues = c(10, 50, 100))
    ),

    #Question 2
    tags$h3("Test 2"),
    wellPanel(
        radioButtons(inputId = "Q2", label = "Question 2?", choiceNames = c("Choice 4", "Choice 5", "Choice 6"), choiceValues = c(20, 40, 60))
    ),

    #Action Button
    actionButton(inputId = "go", label = "Update"),

    #Text Output
    textOutput("result_txt"),

    #Image Output
    imageOutput("result_img")

)

server <- shinyServer(function(input,output) {

    #Button 'Go' is Pressed
    observeEvent(input$go, {

        #Text Output
        output$result_txt <- renderText({

            tags$h4 <- paste("Your final result is ", isolate(as.numeric(input$Q1) + as.numeric(input$Q2)))

        })

        #Image Output
        output$result_img <- renderImage({

            if(isolate(as.numeric(input$Q1) + as.numeric(input$Q2) >= 100)) {
                list(src = "Image1.png")
            } else {
                list(src = "Image2.png")
            }

        }, deleteFile = FALSE)

    }, ignoreInit = TRUE)

})

shinyApp(ui, server)

Comment: Also working on my side with my real inputs and outputs. Thanks a lot!
Answer: I haven't tested the part with the image but this should work:
library(shiny)

ui <- fluidPage(
  tags$h3("Test 1"),
  verticalLayout(sidebarPanel(width=8,
                              radioButtons(inputId = "Q1", label = "Question 1?",choices =  c("Choice 1" = 10, "Choice 2" = 50, "Choice 3" = 100))),
                 tags$h3("Test 2"),
                 sidebarPanel(width=8,
                              radioButtons(inputId = "Q2", label = "Question 2?",choices =  c("Choice 4" = 20, "Choice 5" = 40, "Choice 6" = 60))),
                 actionButton(inputId="go", label="Update"),
                 textOutput("result_txt"),imageOutput("result_img")))

server <- shinyServer(function(input,output) {

  rv <- reactiveValues(
    result = NULL,
    trigger = 0
  )

  observe({
    req(input$Q1)
    req(input$Q2)
    rv$result <- as.numeric(input$Q1) + as.numeric(input$Q2)
  })

  # Text output #
  output$result_txt <- renderText({
    req(rv$trigger > 1)
    rv$trigger
    tags$h4 <- paste("Your final result is ", isolate(rv$result))
  })

  observeEvent(input$go, {
    rv$trigger <- rv$trigger + 1
  })

  # output$result_img <- renderImage({
  #   req(rv$trigger > 1)
  #   rv$trigger
  #
  #   if(as.numeric(isolate(rv$result))>=100){
  #     png("Image1.png")}
  #   else {
  #     png("Image2.png")}
  #
  # },deleteFile=FALSE)

})

shinyApp(ui, server)

Comment: I tested with my inputs and outputs and your code is working (including the part with the image). I just changed `png("MyImage.png")` with `list(src="MyImage.png")` and it works nice, thanks.


How to load a textbox using ajax

Question: Below is my Jquery and ajax code to  load text box data sending from server
class. Am getting response so that alert inside success function executed data sent from the server browser console why its not loading to textbox
     The error am getting
$(document).ready(function () {
                $('#userCheck').change(function (event) {
                    if(!$(this).is(":checked"))
                        return;
                    var userNumber = $('#userNumber').val();
                    if(userNumber != ""){
                        $.ajax({
                            type : 'GET',
                            url : 'populateTextBox',
                            dataType : 'json',
                            data : {
                                userNumber : $('#userNumber').val()
                                },
                            success : function(data, success) {
                                alert("babu code")
                                console.log(data)
                                /* var json = data; */
                                $('#Name').value(data.name);
                            },
                            error : function(data, success) {
                                console.log(data)
                                document.getElementById("er").innerHTML = "Problem to upload a name";
                                er.style.color='red';
                                $('#er').show();
                            }
                        });
                    }else {
                        //FIXME: Handle this properly
                        alert("Enter User Number")
                    }
                });
            });

<s:form action="populateTextBox">
        <s:textfield name="userNumber" id="userNumber"></s:textfield>
        <s:checkbox id="userCheck" name="userCheck"></s:checkbox>
        <s:textfield name="userName" id="Name"></s:textfield>

        <s:submit/>
    </s:form>

Comment: Possible duplicate of [Uncaught TypeError: $(...).value is not a function when trying to send a value via JQuery](http://stackoverflow.com/questions/30074935/uncaught-typeerror-value-is-not-a-function-when-trying-to-send-a-value-v)
Comment: `$('#Name').value(data.name);`

It is wrong, correct it to `$('#Name').val(data.name); ` at line 18 (if you paste this code)
Answer: Try:
$('#Name').val(data);

If console.log(data) is returning pradeep in your console, then that is all you need.
And, as Grégoire Fruleux also pointed out in the comments, use .val() instead of .value()
Comment: Use of inputEncoding is deprecated. opt_content.js:1:804232
unreachable code after return statement

How to load a textbox using ajax


How to select rows from a table where a word appears? (MySQL + PHP)

Question: I have to make a search for keywords as part of my Computer Science work.
I have the names and descriptions of several DVD's.
The user has to search a word, and then displayed are all the names of DVD's where the word appeared in either the title or description.
Let's say my columns in my table
 were "dvd title" and "description", and the word the person has entered is $keyword.
How would i select rows in mysql where $keyword appears at least once in either columns "dvd title" and "description".
Thanks for reading. Any help appreciated.
Answer: You could create a full text index on those columns, but that probably isn't what they want you do do.
You need wildcards, and to you wildcards compare with the keyword LIKE instead of =.  A wildcard in mysql is %
SELECT * FROM mutable WHERE dvdtitle like '%keyword%' or description like '%keyword%';

As for using PHP variable and creating the string, you've got to do some of your own homework.
Comment: Thanks buddy, i found your answer the best because you explained it best for me. I know how to do the PHP variable and string so that won't be a problem :) just didn't know which clause to use and i hadn't a clue about the wildcards... Thanks again for helping me
Answer: Use this query:
SELECT  *
FROM    table_name
WHERE   dvd_title like '%$keyword%'
OR      description like '%$keyword%'

Answer: You can use following code sample, it's not a full code but will give you an idea:
$query_str = "select * from dvd_table_name where dvd_title like '%$keyword%' or description like '%$keyword%'";
$qh = mysql_query($query_str);

Then use mysql_fetch_assoc($qh) to retrive data using while loop;
Comment: I'm up voting this. most complete answer so far for such a basic question.
Answer: $sql = "SELECT * FROM table_name WHERE dvdtitle LIKE '%".$keyword."%' OR description LIKE '%".$keyword."%'";

Executing the above SQL query would return all the rows in the table that has the specified keyword in either the column dvdtitle or description.


optimize ajax code and don't repeat myself

Question: This is my code I don't want repeat my ajax how can I optimize it ? and then have shorter code?
so i show you just an example here:
function for() {
if (forceexs) {
    if (login == "inte") {
        $.ajax({
            url: "index_content.php?mode=ppanel=forgotten&force_mssante=0",
            success: function (html) {
                $(".panel-body").html(i18n.tr(html));
                $("#rpps").focus();
            },
        });
    } else if (login == "ex") {
        $.ajax({
            url: "index.php?mode=nel=forgorce_mssante=1",
            success: function (html) {
                $(".panel-body").html(i18n.tr(html));
                $("#rpps").focus();
            },
        });
    } else {
        $.ajax({
            url: "index.php?mode=phel=internal_or_external",
            success: function (html) {
                $(".panel-body").html(i18n.tr(html));
                $("#rpps").focus();
            },
        });
    }
} else {
    $.ajax({
        url: "index.php?mode=pel=forgotten",
        success: function (html) {
            $(".panel-body").html(i18n.tr(html));
            $("#rpps").focus();
        },
    });
}
}

This is the shortest one more easy to understand
Comment: This question should go on code review: https://codereview.stackexchange.com/
Comment: No, you definitely can do it. I'm pointing you in the direction of doing it without doing it for you.
Comment: When you're trying to remove duplication, read your code and separate the pieces that change from the pieces that don't change. In your case, it appears like the only thing that changes is the URL. How could you write this `ajax` call only one time while still giving the URL the freedom to change?
Comment: @Tom so you mean I can not do it ?
Comment: @Tom thanks for your edit but when i put this function on the code instead of mine i need to have the url (GETQuery) how can i have that one ?
Comment: @abcd please stop changing the edits. I edited the code to remove the duplicated statement at the bottom. There is no need to have this twice.
Comment: @Cjmarkham Hello i make it ok now
Answer: function ajaxRequest(GETQuery) {
  $.ajax({
    url:'index_content?'+GETQuery,
    success: function(html) {
      $(".panel-body").html(i18n.tr(html));
      $("#rpps").focus();}
    })
  }
}

Comment: It looks good but does not working !!!
Comment: could you please  put the whole code?
Comment: You can call this function instead of `$.ajax({url: "index_content.php?",success: function (html) {$(".panel-body").html(i18n.tr(html));$("#rpps").focus();},});`,  passing the GET query as the argument.
Comment: so how can I get +GETQuery ?
Comment: At the first case it the `mode=physician&panel=forgotten&force_mssante=0` (so its text after the `?` at the url). [About GET queries](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).


bootstrap tooltip success on first time but get Uncaught TypeError on second time

Question: I am trying to use bootstrap tooltip in my laravel project.
Here's my blade.php code:
...
@foreach($patients => $patient)
  ...
  //This is the tooltip button

patient_id }}">

  //this is the div i wanna show after hovering tooltip button

patient_id}}" style="visibility: hidden">
    some text

  ...
@endforeach
...

And here's my javascript code
 $(document).ready(function() {

    $('.comment-tooltip').tooltip({
      title: function () {
        var patient_id = $(this).data('patient-id');
        var element = document.getElementById(patient_id);
        element.style.visibility = 'visible';
        return element;
      },
      html: true,
      placement: 'right',
      callback: function(){
        var patient_id = $(this).data('patient-id');
        var element = document.getElementById(patient_id);
        element.style.display = 'none';
      }
    });
 });

And when I hover the button on first time, it works
But when I hover it on second time, it shows error message below in console
Uncaught TypeError: Cannot read property 'style' of null

Hope someone can help me fix this problem. Thanks!!
Comment: This is because `var element = document.getElementById(patient_id);` is `null` the second time. Without seeing more code and having a [MCVE](https://stackoverflow.com/help/mcve) it's hard to help.
Comment: [getElementById returns null?](https://stackoverflow.com/questions/8739605/getelementbyid-returns-null)
Answer: You can use below for tooltip

no need for this long code
Answer:

you do not want to worry about callback function.
this is very simple way i am using it in many projects.
very simple and effective.
as i understand you are getting a problem to show tooltip.
correct me if i am wrong.


How to awk every nth line starting from different lines each iteration

Question: I would like awk to print every nth line out of a file starting from line 0. Then, after awk has gone through the whole file, I would like it to print every nth line starting from line 1...then print every nth line starting from line 2...etc, up to printing every nth line starting from line n-1. My sad attempt thus far:
#!/bin/bash

rm *.sad *.sadd *.out

#Create loop index
for i in $(seq 20 1 36);
do
        listm+=($i)
done

#Create input file
for j in "${listm[@]}"
do
        if [ $j -eq 20 ];
        then
                awk 'NR % 20 == 0' vel_VMDout > atomvel.dat
                awk '{print $2,$3,$4}' atomvel.dat > velocity.dat
        else
                awk 'NR % 20 == 1' vel_VMDout  > $j.sad
                egrep -v "^[[:space:]]*$|^#" $j.sad > $j.sadd
                awk '{print $2, $3, $4}' $j.sadd > $j.out
                paste velocity.dat $j.out  > taste
        fi
done

Let me try to clarify this by providing the input and what the output should look like. Th input is an xyz file of an MD simulation consisting of frames of the atoms' xyz coordinates.
INPUT:

This image shows the 1st snapshot and part of the second snapshot. Because these are snapshot, the ordering of the atoms do not change. Thus, I am trying to print the xyz coordinates from each snapshot for each specific atom in their own columns as shown below. This would eventually make a file consisting of 3N columns, where N is the number of atoms.
OUTPUT:

As you can see, the each atoms' coordinates are in their own columns and the total file is a Nx3N array. My bash script was me trying to do this, but could only do the first two atoms. I wanted to print every nth line (coordinates of the nth atom) so they look like the output. I really appreciate your patience all.
Comment: When you say `awk` in statements like `I would like to awk every nth line` - do you mean `print` or something else?
Comment: How are we supposed to test a potential solution against an **image** of the input and output? Edit your question to provide the textual sample input and output, not a picture of it, and make sure the output is exactly what you want given that input. And be very clear in your requirements about which rows and columns from the input are moving to which rows and columns of the output - don't assume that anyone reading this has a clue what `Th input is an xyz file of an MD simulation consisting of frames of the atoms' xyz coordinates`or any other terminology specific to your domain means.
Comment: It is very often useful to show sample input and desired output.  It removes ambiguities.  (To keep the sample a manageable size, you might the sample for a relatively small n but state that the final version will have n=20.)  Your script removes blank and empty lines for `NR % 20 == 1` but not for `NR % 20 == 0`.  Is that intentional?  What happens when `NR % 20` has other values?
Comment: How big is the data set?  Is it too large to keep in memory?  Also, it helps everyone help you if you don't post images of your data but you post an editable copy of the data.
Answer: Generating sample data
This is a step that should not be necessary; the question should have included usable sample data and the required output from that sample data.
At one level, it won't help much because you don't have my random number generator program, but the script below shows how I generated the data that follows, and it illustrates the lengths to which it might be necessary to go when the question doesn't supply readable data.  I generated some data that looks similar to the data in the question (at least superficially):
18
 Generated by VMD in absentia
 C     0.979485   -6.665347   0.575383
 C     1.191999   -3.002386   2.859484
 C     3.151517   -5.610077   0.429413
 C     3.439828   -6.454984   1.319724
 C     3.726201   -0.123038   2.096854
 C     1.363325   -3.031238   0.016019
 C     6.090283   -3.915340   2.396358
 C     0.407755   -7.957784   -0.846842
 C     0.203074   -0.796428   2.659573
 O     2.600610   -2.259674   -0.260378
 O     4.773839   -6.765097   0.588508
 H     2.743424   -2.890016   2.906452
 H     2.810233   -6.641054   -0.797672
 H     6.854169   -3.191721   -0.925670
 O     2.914233   -1.060001   0.776983
 H     3.803923   -1.497032   2.908799
 H     5.669443   -7.227666   -0.647552
 H     0.092455   -5.850637   2.959987
18
 Generated by VMD in absentia
 C     6.042840   -7.254720   2.093573
 C     2.551942   -6.044322   2.061072
 C     3.523150   -6.167163   2.451689
 C     5.197316   -3.429866   -0.412062
 C     2.548777   -6.422851   1.282846
 C     3.775197   -2.012031   1.377440
 C     3.405112   -3.206415   -0.879886
 C     1.448359   -5.419629   0.467291
 C     3.661964   -2.789234   2.644294
 O     4.214854   -2.439574   -0.951704
 O     5.297609   -2.320418   2.709898
 H     2.653940   -4.431080   -0.511743
 H     5.040635   -0.676199   -0.590970
 H     1.546725   -1.294582   2.562937
 O     4.231461   -7.180908   1.629901
 H     3.297836   -1.557133   -0.133280
 H     3.442481   -4.489962   2.111930
 H     1.423611   -7.982655   0.715618
18
 Generated by VMD in absentia
 C     1.432495   -7.686243   2.525734
 C     5.038409   -4.976270   2.826846
 C     6.184137   -7.303094   2.711561
 C     3.208125   -0.606556   1.978725
 C     2.171859   -6.792060   0.678988
 C     6.521124   -5.622797   -0.773797
 C     1.725619   -5.768633   -0.223397
 C     3.602427   -2.325680   1.762008
 C     1.937521   -1.686895   1.743159
 O     0.745526   -0.114246   -0.949490
 O     4.754360   -6.531145   1.998913
 H     1.114732   -1.158810   1.486939
 H     6.410490   -5.411647   0.062737
 H     4.164330   -6.743763   1.802804
 O     2.587841   -3.979700   2.609748
 H     2.192073   -2.815376   -0.809569
 H     5.501795   -2.326438   1.325829
 H     3.285032   -1.212541   1.284453
18
 Generated by VMD in absentia
 C     3.564424   -3.117406   -0.032879
 C     2.894745   -0.632591   0.532311
 C     3.384916   -5.383135   1.179585
 C     0.793488   -0.894539   -0.886891
 C     1.348785   -6.501867   1.648604
 C     2.189941   -2.438067   0.616090
 C     2.043378   -4.966472   0.691603
 C     3.124161   -5.792896   0.545362
 C     5.741472   -0.640590   2.825374
 O     0.300550   -7.149663   0.942726
 O     1.344387   -0.121382   2.169401
 H     4.963296   -0.964665   -0.230523
 H     6.651423   -4.905053   2.509626
 H     5.059694   -6.166516   0.102255
 O     5.046864   -3.288883   0.853948
 H     2.389007   -3.057664   1.806301
 H     2.365876   -0.956860   1.458959
 H     2.892502   -0.097422   -0.531714

The script I used to do it was:
random -n $((4 * 18)) -T '%8:6[0:7]F   %8:6[-8:0]F   %8:6[-1:3]F' |
awk 'BEGIN { n = split("CCCCCCCCCOOHHHOHHH", atoms, ""); atoms[0] = atoms[n] }
     NR % n == 1 { print n; print " Generated by VMD in absentia" }
     { print "", atoms[NR%18], "   ", $0 }'

The -n option to random says how many rows to generate; I chose 72.  The -T option is a template, and the notation %8:6[0:7]F means use %8.6F format to print uniformly distributed random numbers between 0 and 7.  The awk script takes the data that is so generated and interpolates the noise (the number of atoms and a variant on the 'generated by VMD' line), as well as tagging the lines with the appropriate atomic symbol.
Processing the sample data
Given some data, you then need to munge it to get the required output.  This script more or less does the job.  There are endless ways it should be improved, of course, such as taking file names as command line arguments, using temporary file names instead of fixed names, cleaning up the intermediate files, different compounds, different atoms (nitrogen, phosphorous, etc), and so on.  However, it should adapt reasonably easily.
input="data"
output="output"
n=$(sed 1q "$input")
n2=$(($n+2))

for ((i = 3; i <= n2; i++))
do
    colno=$(printf "%.2d" $(($i-2)))
    awk -v N=$n2 -v R=$i \
        '   BEGIN { name["C"] = "Carbon"; name["H"] = "Hydrogen"; name["O"] = "Oxygen";
                    R0 = R % N }
            NR > 2 && NR <= R { count[$1]++; }
            NR == R { printf "%-32.32s\n", name[$1] " " count[$1]; }
            NR % N == R0 { xyz = sprintf("%s %s %s", $2, $3, $4); printf "%-32.32s\n", xyz }
        ' "$input" > "column.$colno"
done

paste -d ' ' column.* > "$output"

The first four lines set up the control parameters, collecting the number of lines per unit of data from the input file, and adjusting things accordingly.  The for loop iterates over offsets 3 to $n2 inclusive (skipping the two header lines), and runs the awk script.  That encodes atom types (BEGIN), determines which atom it is processing this time (NR > 2 && NR <= R and NR == R), and then arranges to print the triplets of data for the relevant atom. The formatting is carefully organized so that the column headings and the actual xyz-triplets are uniformly spaced.  These are written to a file column.$colno.  When all's done, the column.* files are pasted to generate a single output file, which looks like this:
Carbon 1                         Carbon 2                         Carbon 3                         Carbon 4                         Carbon 5                         Carbon 6                         Carbon 7                         Carbon 8                         Carbon 9                         Oxygen 1                         Oxygen 2                         Hydrogen 1                       Hydrogen 2                       Hydrogen 3                       Oxygen 3                         Hydrogen 4                       Hydrogen 5                       Hydrogen 6
0.979485 -6.665347 0.575383      1.191999 -3.002386 2.859484      3.151517 -5.610077 0.429413      3.439828 -6.454984 1.319724      3.726201 -0.123038 2.096854      1.363325 -3.031238 0.016019      6.090283 -3.915340 2.396358      0.407755 -7.957784 -0.846842     0.203074 -0.796428 2.659573      2.600610 -2.259674 -0.260378     4.773839 -6.765097 0.588508      2.743424 -2.890016 2.906452      2.810233 -6.641054 -0.797672     6.854169 -3.191721 -0.925670     2.914233 -1.060001 0.776983      3.803923 -1.497032 2.908799      5.669443 -7.227666 -0.647552     0.092455 -5.850637 2.959987
6.042840 -7.254720 2.093573      2.551942 -6.044322 2.061072      3.523150 -6.167163 2.451689      5.197316 -3.429866 -0.412062     2.548777 -6.422851 1.282846      3.775197 -2.012031 1.377440      3.405112 -3.206415 -0.879886     1.448359 -5.419629 0.467291      3.661964 -2.789234 2.644294      4.214854 -2.439574 -0.951704     5.297609 -2.320418 2.709898      2.653940 -4.431080 -0.511743     5.040635 -0.676199 -0.590970     1.546725 -1.294582 2.562937      4.231461 -7.180908 1.629901      3.297836 -1.557133 -0.133280     3.442481 -4.489962 2.111930      1.423611 -7.982655 0.715618
1.432495 -7.686243 2.525734      5.038409 -4.976270 2.826846      6.184137 -7.303094 2.711561      3.208125 -0.606556 1.978725      2.171859 -6.792060 0.678988      6.521124 -5.622797 -0.773797     1.725619 -5.768633 -0.223397     3.602427 -2.325680 1.762008      1.937521 -1.686895 1.743159      0.745526 -0.114246 -0.949490     4.754360 -6.531145 1.998913      1.114732 -1.158810 1.486939      6.410490 -5.411647 0.062737      4.164330 -6.743763 1.802804      2.587841 -3.979700 2.609748      2.192073 -2.815376 -0.809569     5.501795 -2.326438 1.325829      3.285032 -1.212541 1.284453
3.564424 -3.117406 -0.032879     2.894745 -0.632591 0.532311      3.384916 -5.383135 1.179585      0.793488 -0.894539 -0.886891     1.348785 -6.501867 1.648604      2.189941 -2.438067 0.616090      2.043378 -4.966472 0.691603      3.124161 -5.792896 0.545362      5.741472 -0.640590 2.825374      0.300550 -7.149663 0.942726      1.344387 -0.121382 2.169401      4.963296 -0.964665 -0.230523     6.651423 -4.905053 2.509626      5.059694 -6.166516 0.102255      5.046864 -3.288883 0.853948      2.389007 -3.057664 1.806301      2.365876 -0.956860 1.458959      2.892502 -0.097422 -0.531714

Your task is to understand why all the bits of the awk script are present.  For example, why is R0 needed (hint, experiment without the R0 calculation, and use R in its place).


Getting a linkable table of children in hook_block_view from taxonomy_get_children (Drupal 7)

Question: I am trying to programmatically create a block that will display all of the children of the term being referenced by the current page in a linkable table (so that I can click on any of the taxonomy terms and then go to their page).  So far I have managed to create an ordered list of children names with the following code:
function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);
      $children = taxonomy_get_children($term->tid, $term->vid);
      $stack = array();

      foreach ($children as $child) {
        array_push($stack,$child->name);
      }

      $theme_args = array('items' => $stack, 'type' => 'ol');
      $content = theme('item_list' , $theme_args);

      $block = array(
        'subject' => t('Children'),
        'content' => $content
      );
    break;
  }
  return $block;
}

But what I really want is a table that might contain some other details about the taxonomies but more importantly I would like each taxonomy in the list to be a link that will take me to that taoxnomies term page.  I image the reason these terms are not linkable is because I am only passing the name into the array but when I tried to pass the actual term into the array I get an error from the theme module.  How would I make these linkable?  Also, I imagine that I could change the ordered list into a table by replacing the 'ol' in the call:
      $theme_args = array('items' => $stack, 'type' => 'ol');

with a table but I am not sure what I would pass instead of 'ol' and I could not find any documentation about this.  Could anyone link me to such documentation?
Answer: You can use the l() function to create the link to each term, and the theme_table() function to build your table:
function children_view_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'children':
      $path = explode('/', drupal_get_path_alias($_GET['q']));

      $tid = array_pop($path);
      $term = taxonomy_term_load($tid);

      // Set up the table rows and headers array
      $rows = array();
      $header = array('Link', 'Vocab ID');

      $children = taxonomy_get_children($term->tid, $term->vid);

      // Add a new row for each child term
      foreach ($children as $child) {
        $rows[] = array(
          l($child->name, "taxonomy/term/$child->tid"),
          $child->vid
        );
      }

      // Set up the params for the theme_table call
      $table = array('rows' => $rows, 'header' => $header, 'empty' => 'No terms found');

      $block['subject'] = t('Children');
      $block['content'] = theme('table', $table);

      break;
  }

  return $block;
}

I've put a second column in there (Vocab ID) just as an example of how to add extra columns to the table.


Put form labels left of the fields?

Question: This is an age-old debate in Drupal, and I am surprised this has not been asked before on Drupal Answers. Maybe I missed it.
By default, Drupal form labels are always displayed at the top of form elements.
How can I display form element labels to the left (or right) of the element, instead of at the top?
I am talking about entity edit forms, but also other forms.
I am sure I will find a solution with hook_form_alter() or on the theme layer. But the question is, what is a convenient and maintainable way to do this?
I am personally working with Bootstrap theme, but a generic answer is preferable, so others can benefit too.
EDIT: It also would be nice to have an elegant way to control which forms this should apply to, and where it should not. Since I added this later, it should be considered optional.
UX background
The main argument for labels at the top is that they are supposedly easier to read. E.g. here, http://www.wunderkraut.com/blog/why-top-aligned-labels-are-better-in-drupal-forms/2010-12-28
I personally think this is an answer to the wrong question. The form labels might be easier to read this way. But if you look at a pre-filled form, e.g. when editing an entity, then usually the field values are far more interesting than the labels. Often the labels are already evident from the field value. E.g. a street name looks like a street name. An email looks like an email.
And of course with labels on the side the form will look more compact and less cluttered, and more of it will fit "above the fold".
Another design option would be in-field labels. But with these, the label is completely gone when the field is filled out. You may still want the labels to make sure that every value is in the correct field.
So having labels on the side is a valid design goal..
Answer: As when it comes to theming stuff, you should always ask your self: Can I do this with CSS? The answer in this case is yes.
label { float: left padding-right: 3px; }
Example
OR (probably best to go with)
label { display: inline }
input { display: inline }

Example 2
You will need to add the css code to your administration theme .css file.
Comment: With this css, the elements will not be nicely aligned, I'm afraid.
Comment: with `display: inline` method it should be
Comment: How so? Different labels will have different width.
I guess the solution would be either an explicit width setting on the label, or something with display:table-cell..
Comment: Also: This would apply to all labels throughout the site. This can be intended, or maybe it's not. It is possible to target specific forms with more specific css.. I'm not sure this is the best possible solution, but it is a solution.
Comment: And why the admin theme? To let this apply to forms on the admin side? Fair point. I was more interested in user-facing forms, but I did not say this.
Comment: I give +1, but will give others a chance. Maybe we will see some surprising answers :)

Put form labels left of the fields?


Guardando multiplos valores de uma enum no banco de dados

Question: Gostaria de poder guardar várias opções de uma enum (dia da semana) algo como
1,3,5 (segunda, quarta, sexta)
Conforme modelagem descrita aqui.
Criei uma model
public class Horario
{
[Key]
public int ModalidadeProfessorSalaHorarioId { get; set; }

    [DataType(DataType.Text)]
    public DiaDaSemana DiaDaSemana { get; set; }
}

Esse dia da semana é um enum
 [Flags]
    public enum DiaDaSemana
    {
        Domingo=0,
        Segunda=1,
        Terça=2,
        Quarta=3,
        Quinta=4,
        Sexta=5,
        Sábado=6
    }

Porém ao dar o migrations ele cria como int
Na view o Insert estou fazendo
@Html.EnumDropDownListFor(model => model.DiaDaSemana, new { @class = "form-control", multiple = "true"  })

Estou pensando em criar o campo como string, criar uma viewmodel mandar o campo como string e o enum, e dai na controller fazer a união, não sei se isso é uma gambiarra, mas acho que funcionaria.
OBS: O campo [flag] do enum junto com o @Html.EnumDropDownListFor não roda, preciso desabilitar o flag

O tipo de retorno 'Enums.DiaDaSemana' não tem suporte. O tipo não deve ter um atributo 'Flags'.
Nome do parâmetro: expression

Tentei utilizar essa solução mais sem sucesso.
Comment: Qual a necessidade de guardar no banco?
Comment: preciso guardar os dias da semana no banco!
Comment: Isso eu entendi, estou perguntando o motivo.
Comment: coloquei o link da modelagem
Comment: Uma enum é apenas um Apelido para uma constante de mapeamento  ou id. Internamente é convertido para o tipo adequado. Trate como tal, receba do banco o int e faça o cast. Deve-se ter cuidado com isso: https://msdn.microsoft.com/pt-br/library/sbbt4032.aspx
Answer: Modifique suas flags para que elas correspondam a bits, permitindo assim operações booleanas:
[Flags]
public enum DiaDaSemana
{
    Domingo = 1, // 0x00000001
    Segunda = 2, // 0x00000010
    Terca = 4,   // 0x00000100
    Quarta = 8,  // 0x00001000
    Quinta = 16, // 0x00010000
    Sexta = 32,  // 0x00100000
    Sabado = 64  // 0x01000000
}

Assim combinações de datas podem ser expressas somando os valores:
var QuintaSextaESabado = DiaDaSemana.Quinta + DiaDaSemana.Sexta + DiaDaSemana.Sabado;
//  QuintaSextaESabado = 112 decimal, 0x01110000 binario

Para verificar se um dado dia está presente em um dado valor, utilize um operador booleano AND:
var temSexta = QuintaSextaESabado && DiaDaSemana.Sexta;

Dica: não utilize diacríticos (acentos, cedilha, etc.) em objetos. Note como modifiquei as entradas em seu enum para Terca e Sabado.
Comment: e depois se eu tiver o 112 em decimal consigo saber quais dias da semana eram? como ele fará isso?
Comment: @Dorathoto utilizando o último exemplo da resposta; realize uma operação AND entre os itens do `enum` e o valor armazenado.


get coordinates to draw a triangle inside another triangle

Question: I am not a Math guy. So, if this question is silly, then please forgive me.
I have a triangle which has the following coordinates: (all the measurements are in cm.)
<code>A - (35, 0)
B - (70, 70)
C - (0, 70)
</code>
I have filled this triangle with black color.
Now, I want to draw another triangle inside it. I don't know what the co-ordinates of that triangle will be. But after drawing new triangle i will fill it with red color and it should look like there is a black border of 1 cm around it.
Can you please let me know the co-ordinates for new triangle?
Update:
@Floris gave me this value of 3 pairs of vertices:
$(70-\frac{1}{2}(\sqrt{5}+1),69)$, $(35,\sqrt{5})$ and $(\frac{1}{2}(\sqrt{5}+1),69)$
In this case:
A - (35, 0)
B - (70, 70)
C - (0, 70)
P - $(35,\sqrt{5})$
Q - $(70-\frac{1}{2}(\sqrt{5}+1),69)$
R - $(\frac{1}{2}(\sqrt{5}+1),69)$
Which gives me output like:

But now suppose I want to have border of 10 cm:
So, I changed the value to: (please consider x = 10)
A - (35, 0)
B - (70, 70)
C - (0, 70)
P - 35,x√5
Q - 70-((x/2)(√5+x)),70-x
R - (1/2)(√5+x),70-x
But I am getting

I want the formula for inner triangle's vertices. In short I need P, Q, and R having some x.
Answer: Note that the edges are given by $\overline{AB}=\{(x+35,2x):x\in[0,35]\}$, $\overline{BC}=\{(x,70):x\in[0,70]\}$ and $\overline{AC}=\{(35-x,2x):x\in[0,35]\}$. The linepieces on centimetre from the edges are given by
$$\hat{AB}=\{(35+x-\frac{2}{5}\sqrt{5},2x+\frac{1}{5}\sqrt{5}):x\in[0,35]\},$$
$$\hat{BC}=\{(x,69):x\in[0,70]\}$$
 and
$$\hat{AC}=\{(35-x+\frac{2}{5}\sqrt{5},2x+\frac{1}{5}\sqrt{5}):x\in[0,35]\}$$
which have intersections $(70-\frac{1}{2}(\sqrt{5}+1),69)$, $(35,\sqrt{5})$ and $(\frac{1}{2}(\sqrt{5}+1),69)$, which are the coordinates of the red triangle.
This process can be generalised for different borders. Note that
$$\hat{AB}=\overline{AB}-(\frac{2}{5}\sqrt{5},\frac{1}{5}\sqrt{5})$$
here $(\frac{2}{5}\sqrt{5},\frac{1}{5}\sqrt{5})$ is a unit vector which is orthogonal to $\overline{AB}$. So if we want a border of length $l$, then we can just take
$$\hat{AB}_{l}=\overline{AB}-l\cdot(\frac{2}{5}\sqrt{5},\frac{1}{5}\sqrt{5})$$
This gives us
$$\hat{AB}_{l}=\{(35+x-\frac{2l}{5}\sqrt{5},2x+\frac{l}{5}\sqrt{5}):x\in[0,35]\},$$
$$\hat{BC}_{l}=\{(x,70-l):x\in[0,70]\}$$
 and
$$\hat{AC}_{l}=\{(35-x+\frac{2l}{5}\sqrt{5},2x+\frac{l}{5}\sqrt{5}):x\in[0,35]\}.$$
To calculate the coordinates of the new triangle we have to find the intersections of the triangles, these are given by:
$$\hat{AB}_{l}\cap\hat{AC}_{l}=\{(35,l\sqrt{5})\}$$
as due to symmetry $35=35-x+\frac{2l}{5}\sqrt{5}\Leftrightarrow x=\frac{2l}{5}\sqrt{5}$. From which it then follows that $2x+\frac{l}{5}\sqrt{5}=l\sqrt{5}$.
For $\hat{AB}_{l}\cap\hat{BC}_{l}$ we can solve
$$70-l=2x+\frac{l}{5}\sqrt{5}\Leftrightarrow x=35-\frac{l}{2}(1+\frac{1}{5}\sqrt{5})$$
which then gives $35+x-\frac{2l}{5}\sqrt{5}=70-\frac{l}{2}(1+\sqrt{5})$. Hence
$$\hat{AB}_{l}\cap\hat{BC}_{l}=\{(70-\frac{l}{2}(1+\sqrt{5}),70-l)\}.$$
Finally by symmetry we find that
$$\hat{AC}_{l}\cap\hat{BC}_{l}=\{(\frac{l}{2}(1+\sqrt{5}),70-l)\}.$$
Comment: First of all thanks for giving me an accurate answer. I have checked (70−12(5‾√+1),69) , (35,5‾√) and (12(5‾√+1),69), and it works perfectly. I really don't understand the calculations that you have put in your answer. And now I need a border of 2 or 3 pixels at some places. So, can you please give me the formula for `border = x`? Sorry, if I asked for too much help.
Comment: @Vishal I've changed the bounds of $x$ to precisely give the edges of the red triangle.
Comment: Sorry, i was unable to explain you what exactly i need. You have given me the formula to get the sides of red triangle, but I need the formula for the vertices of red triangle. The vertices that you gave me last time works fine for me. But thats static for 1 cm border. I want that dynamic. So, that in some triangles I have border = 2 or border = 3 or border = 10, where I will be able to calculate the vertices of inner triangle by just replacing x with the desired border.
Comment: I'm not exactly sure what you need, could you explain by for example giving what you understand to be the vertices of a simple triangle? I'll try to go from there.
Comment: I have updated the question with relevent information. Please take a look at it. Thanks again for taking time for me.
Comment: I've given a formula for a border of length $l$ plus some explanation of how to calculate this yourself for different cases.
Comment: Thanks for taking time to update the answer. I will try it and let you know the results.
Comment: Thank you @Floris. I am really very bad at math, but you kept patience and explained me everything till I understood that. After staring at your answer and looking at every step by implementing it, i realized that i needed what you call `intersections`. Now it is working good. Thanks from the bottom of my heart.


Displaying values associated with each color gradient mapped from range in D3 legend

Question: I'm trying to draw a heatmap using D3. So far I was able to draw one by modifying the code from http://bl.ocks.org/tjdecke/5558084. At the moment, my legend is only showing two colors; yellow (for value 0) and red (for value 1). I would like to display the legend showing all the color gradient from yellow to red and the value associated with each color. Can someone help me with this? Part of the code is shown below. Thank you
// X-axis labels
// This has to be generated dynamically
loop_ids1 = ["HL_1S72_010", "HL_1S72_039", "HL_1S72_005", "HL_1VX6_037", "HL_2A64_002", "HL_2GDI_002", "HL_2GDI_004", "HL_2HOJ_002", "HL_2QBG_011", "HL_3DHS_002", "HL_3J7A_004", "HL_3U5F_006", "HL_3U5H_005", "HL_4A1B_005", "HL_4A1B_037", "HL_4BPP_006", "HL_4CUV_005", "HL_4CUX_006", "HL_4IOA_009", "HL_4QCN_009", "HL_4W21_039"];

// Y-axis labels
// This has to be generated dynamically
loop_ids2 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21" ];
// Open and load the csv file
d3.csv("disc_parsed.csv", function(error, data) {
  data.forEach(function(d) {
    loop_id1 = d.loop_id1;
    loop_id2 = d.loop_id2;
    coordx = +d.coordx
    coordy = +d.coordy
    discrepancy = +d.discrepancy;
    //console.log(d.discrepancy);
  });

  //var colorScale = d3.scale.quantile()
          //.domain([0, buckets - 1, d3.max(data, function (d) { return d.discrepancy; })])
          //.range(colors);
  var colorScale = d3.scale.linear()
    .domain([0,1])
    .range(['yellow', 'red'])
  // Set the svg container
  var svg = d3.select("#chart").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  // Draw the x-axis label
  var dayLabels = svg.selectAll(".dayLabel")
    .data(loop_ids1)
    .enter().append("text")
    .text(function(d) {
      return d;
    })
    .attr("x", 0)
    .attr("y", function(d, i) {
      return i * gridSize;
    })
    .style("text-anchor", "end")
    .attr("transform", "translate(-5," + gridSize / 1.5 + ")")
    .attr("class", function(d, i) { console.log(i);
      return ((i >= 0)
        ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis");
    });
  // Draw the y-axis label
  var timeLabels = svg.selectAll(".timeLabel")
    .data(loop_ids2)
    .enter().append("text")
    //.attr("font-size", 12)
    //.attr("glyph-orientation-vertical: 180")
    .text(function(d) {
      return d;
    })
    .attr("x", function(d, i) {
      return  (i * gridSize);
    })
    .attr("y", 0)
    .style("text-anchor", "middle")
    .attr("transform", "translate(" + gridSize / 2 + '-5' + ")")
    .attr("class", function(d, i) {
      return ((i >= 0) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis");
    });
  // Create the paired elements
  var heatMap = svg.selectAll(".coordy")
    .data(data, function(d) { return d.coordx+':'+d.coordy;});

  // Draw the grid to make the heatmap
  heatMap.enter().append("rect")
    .attr("x", function(d) { return d.coordy * gridSize; })
    .attr("y", function(d) { return d.coordx * gridSize; })
    .attr("rx", 4)
    .attr("ry", 4)
    .attr("class", "bordered")
    .attr("width", gridSize)
    .attr("height", gridSize)
    .style("fill", function(d) {
        return colorScale(d.discrepancy);
    });
  // Show the value of discrepancy between two motifs when the user hovers over a heatmap grid
  heatMap.append("title").text(function(d) {
    return d.loop_id1 + ':' + d.loop_id2 + ' = ' + d.discrepancy;
  });
  heatMap.exit().remove();
  var legend = svg.selectAll(".legend")
    .data(colorScale.domain())
  legend.enter().append("g")
    .attr("class", "legend");
  // Draw the legend
  legend.append("rect")
    .attr("x", function(d, i) {
      return legendElementWidth * i;
    })
    .attr("y", height)
    .attr("width", legendElementWidth)
    .attr("height", gridSize / 2)
    .style("fill", function(d) {
      return colorScale(d);
    });
  // Add text to the legend
  legend.append("text")
    .attr("class", "mono")
    .text(function(d) {
      return (d);
    })
    .attr("x", function(d, i) {
      return legendElementWidth * i;
    })
    .attr("y", height + gridSize);
  legend.exit().remove();
});

Comment: The problem is the `data` for the legend. Do a `console.log(data(colorScale.domain()))` and tell me what do you see (I'll give you a hint: an array with 2 values).
Comment: @GerardoFurtado I see [0,1]. So should I do this differently? How do I replicate the color gradient shown in the heatmap with the legend? The discrepancy value ranges from 0 to 1. Should I use a different type of scale maybe?
Comment: I just wrote an answer explaining it, without changing the scale. Of corse, you can change the scale for a quantile one, like in the original code, so you can just copy the legends part.
Answer: The problem is the data used for the legends:
var legend = svg.selectAll(".legend")
    .data(colorScale.domain());

Right now, your data is an array containing only 2 values, 0 and 1, because of this snippet:
var colorScale = d3.scale.linear()
    .domain([0,1])

What happened in the original code? In the original code, the author created an array with several values, using the quantiles() function:
var legend = svg.selectAll(".legend")
    .data([0].concat(colorScale.quantiles()), function(d) { return d; });

Solution:
You have several different solutions here, the easier and uglier one being simply hardcoding your data. So, if you want a legend with 6 rectangles:
var dataLegend = [0, 0.2, 0.4, 0.6, 0.8, 1];
var legend = svg.selectAll(".legend")
    .data(dataLegend);

Comment: Thank you for clarifying this!
Comment: No worries. Using D3 v4.x (not your case) you can simple write this: `var dataLegend = d3.ticks(0, 1, steps)`, where `steps` is the number of values you want (including 0 and 1), changing it whenever you want.


Is there a version of the structure theorem for f.g. abelian groups that applies to homomorphisms?

Question: The structure theorem for finitely-generated (f.g.) abelian groups tells us that every f.g. abelian group can be written in a very special form. Suppose I have a group homomorphism $f : X \rightarrow Y$ here $X$ and $Y$ are f.g. abelian groups. Is there a theorem which guarantees that not only can $X$ and $Y$ be decomposed in a very particular way, but in fact we can decompose $f$ somehow as well?
Generalization to modules over a PID is also of interest.
Comment: The Smith normal form (for a map between finitely generated torsion-free modules over a PID) seems like a place to start.
Comment: This is a general inquiry question. It isn't homework. Asking for what we've tried is not really useful since it's probably a very non-trivial result.
Comment: What have you done to solve the problem?
Comment: @goblin, what have you tried?
Comment: If you decompose $X$ and $Y$ according to the structure theorem, you will end up decomposing your homomorphism as well, namely into a matrix of homomorphisms between various cyclic groups which are either of infinite order or of order $p^n$ for some prime $p$ and natural number $n$. So the structure theorem already gives you some kind of decomposition of homomorphisms. Or did you aim at something different?
Comment: @asdq, that sounds good, but I'm not sure I understand how it works. Can you elaborate on how this accidental decomposition actually occurs?
Answer: If $X$ and $Y$ are finitely generated $R$-modules for a PID $R$, then the structure theorem tells us that there are isomorphisms $\phi: X\rightarrow R^n\oplus \bigoplus_{i=1}^r R/(p_i^{e_i})$ and $\psi: Y\rightarrow R^m\oplus \bigoplus_{j=1}^s R/(q_j^{f_j})$ where $p_i$ and $q_j$ are prime elements in $R$ and $n,m,e_i,f_j$ are natural numbers (allowed to be zero in case of $n$ and $m$). If $f:X\rightarrow Y$ is a homomorphism, then we consequently get
$$\psi\circ f \circ \phi^{-1}:R^n\oplus\bigoplus_{i=1}^r R/(p_i^{e_i})\rightarrow R^m\oplus\bigoplus_{j=1}^s R/(q_j^{f_j}).$$
But this homomorphism we understand pretty well: In general, if $M=\bigoplus_{k=1}^m M_k$ and $N=\bigoplus N_{l=1}^n N_l$ are $R$-modules, the universal property of direct sums gives us
$$\hom_{R}(M,N)=\bigoplus_{k,l}\hom_R(M_k,N_l).$$
Explicitly, this equality is achieved by precomposition and postcomposition of a homomorphism $M\to N$ by the various inclusions and projections of the direct summands. Each element of the right-hand side can be considered as an $n\times m$-matrix of homomorphisms between the individual direct summands. Specializing this to the homomorphism $\psi\circ f\circ \phi^{-1}$, we can therefore consider this map as an $(m+s)\times (n+r)$-matrix of homomorphism between the various direct summands that occur in the decomposition, which are all cyclic modules.
As a consequence, we get a decomposition of $f$ into a matrix of homomorphisms that are easily understood, since each homomorphism out of a cyclic module is determined by what a generator is mapped to.


Alterar propriedade CSS ao fazer :hover em cima de outro link do menu

Question:
Preciso fazer com que ao passar o mouse por cima dos links do menu, seja removido ou alterado para transparent o background do link que está ativo (da página que estou).

Demonstração:

Quando se passa o mouse sobre outro link:

Como deve ficar:

Como proceder?

.nav-item { padding:5px; }
.nav-item:hover > .nav-link{ background:#000; color:#FFF; }
.ativo > .nav-link { background:blue; color: #FFF; }
body {font-size:14px; font-family: Arial; }
a {color:#000;}

     Início

     Transparência

Ao passar o mouse aqui o azul do Início deve sumir

Comment: Você tem o código real disso ai, sem ser a demonstração?
Comment: Tenho sim, mas é muito complexo, muito conteúdo. Coloquei esse trecho como base pra mim implementar ao original.
Comment: Basicamente a estrutura é a mesma.
Answer: Basicamente o que vc precisa é um :hover > :hover. Tipo quando fizer :hover na nav vc "desfaz" todos os atributos .ativo,  sendo que se vc fizer :hover na nav e :hover no item esse item sim fica o estilo que vc definir.
Então basicamente vc precisa dessas duas regras
    .nav:hover .ativo>.nav-link {
        background: none;
        color: black;
    }

    .nav:hover .nav-item:hover>.nav-link {
        background: #000;
        color: #FFF;
    }

Segue o código completo:

.nav-item {
    padding: 5px;
}

body {
    font-size: 14px;
    font-family: Arial;
}

a {
    color: #000;
}

.nav:hover .ativo>.nav-link {
    background: none;
    color: black;
}

.nav:hover .nav-item:hover>.nav-link {
    background: #000;
    color: #FFF;
}

.nav .ativo>.nav-link {
    background: blue;
    color: #FFF;
}

        Início

        item

        item

        Transparência

Ao passar o mouse aqui o azul do Início deve sumir

Comment: É exatamente isso!!!!!!
Comment: @AlexandreLopes fico feliz em ter ajudado, depois que optar por uma uma das resposta não deixe de marca-la como aceita ;) qq dúvida comenta ai!
Comment: Caramba! Você foi o único que entendeu o que realmente precisava! Você é um gênio!!!! Obrigado!
Comment: @AlexandreLopes hahaha experiencia de quem trabalha com UI :D. Quando bati o olho imaginei o efeito que desejava. Agora é só fazer o JS para quando clicar adicionar a classe ativo e tira a classe Ativo do que já estiver marcado. []´s
Comment: Nem precisou, só copiei o seu CSS e colei, mudei só o nome de 1 classe, e ficou perfeitoo!!! =D
Answer: Olá. Fiz a seguinte solução usando js puro.

var hovers = document.getElementsByName("hover");
var ativo = document.getElementsByClassName("ativo")[0];

for(let i = 0; i < hovers.length; i++){
  hovers[i].addEventListener("mouseover", () => {
    for(let j = 0; j < hovers.length; j++){
      if(!j == i) hovers[j].style.background = "transparent";
      else hovers[j].style.background="#000";
    }
  });

  hovers[i].addEventListener("mouseout", () => {
    ativo.children[0].style.background = "yellow";
  });
}
.nav-item { padding:5px; }
.ativo > .nav-link { background:yellow; }
body {font-size:14px; font-family: Arial; }

 Início

 Transparência

Passe o Mouse aqui

Comment: Basicamente é isso! Mas há um problema, quando tiro o mouse de cima, ele não volta ao normal. Deve voltar ao normal. Outra coisa, deve funcionar quando se coloca o mouse em qualquer parte, seja no Link "Transparência", ou no Texto "Passe o Mouse aqui"
Comment: Olhei seu código, ele deveria funcionar para várias `` pois se trata de um menu. E seria interessante ao invés de inserir um `style`, inserir uma `class` que já está predefinida no css.
Comment: Se liga aí no Fiddle que fiz, de mais ou menos como deve ser: https://jsfiddle.net/wg7ktenp/ baseado no seu código.
Answer: O problema é o seletor de onde você está utilizando o :hover, coloque-o direto no nav-link e vai funcionar normal:

.nav-item {
  padding: 5px;
}
.nav-link:hover {
  background: #000;
  color: #fff;
}

body {
  font-size: 14px;
  font-family: Arial;
}
a {
  color: #000;
}

    Início

    Transparência

Ao passar o mouse aqui o azul do Início deve sumir

Comment: @AlexandreLopes Funciona sim po, clica em "Executar". Ele ta fazendo exatamente oq vc disse.
Comment: Rapaz, mas é exatamente isso que esta ocorrendo. O que ta dando ai pra vc? @AlexandreLopes
Comment: Não funcionou. Basicamente é como se fosse feito uma troca, o link "Transparência" deve ficar ativo no lugar do "Início" que está ativo. Os dois não podem ficar ao mesmo tempo.
Comment: Quando eu passasse o mouse sobre a `` Transparência, ele deveria remover o background da `` Início. E quando tirasse o mouse de cima, ele deveria voltar ao normal.
Comment: Olha esse fiddle: https://jsfiddle.net/wg7ktenp/ é tipo isso


How to handle Errors while using pipe and mergemap in angular

Question: I have the below code calling two APIs. How can I handle errors in this, if there are any errors in first API call then the second API should not be called.
this.userService.signUp(this.signUpForm.value.fullName, this.signUpForm.value.email, this.signUpForm.value.password)
        .pipe(mergeMap((res: any)=>
          this.notificationService.sendVerificationEmail(res.email)))
        .subscribe((notificationResponse: any)=>{
            console.log(notificationResponse.message)
        })

Answer: You should consider using switchMap instead of mergeMap.
switchMap requires the previous observable to be completed then only proceed to the next observable.
this.userService.signUp(this.signUpForm.value.fullName, this.signUpForm.value.email, this.signUpForm.value.password)
  .pipe(switchMap((res: any) =>
    this.notificationService.sendVerificationEmail(res.email)))
  .subscribe({
    next: (notificationResponse: any) => {
      console.log(notificationResponse.message)
    },
    error: (err: any) => console.error(err)
  })

Comment: Created a [demo](https://stackblitz.com/edit/stackblitz-starters-skkpfz?file=src%2Fmain.ts) for success and error observables.


Erro limit Codeigniter

Question: Olá pessoal do Codeigniter Brasil,
Eu estou com uma query que retorna tudo perfeito no localhost mas no servidor não retorna da forma que foi escrita.
É para retornar 6 resultados mas no servidor retorna a quantidade que ele achar melhor até 6.
$this->db->limit(6);
$this->db->select("*");
$this->db->from("vips");
$this->db->join("anuncios", "anuncios.id = vips.idPostVip");
$this->db->order_by('RAND()');
return $this->db->get()->result_array();

Alguma dica ?
Alguma configuração do PHP ?
Me ajudem Rs.
Obrigado.
Comment: Então o limite ele está respeitando se trás 1, 2 ou 3. Deve ser esse where vip > 0. Verifique os dados. Não devem estar atendendo o where.
Comment: @BrunoLuiz já tentou tirar a linha `$this->db->where("vip > ",0);` para ver se funciona?
Comment: qual é o resultado esperado com esse código, quantos registros deveriam retornar?
Comment: Deveriam retornar 3 resultados.
Comment: Olá, então no servidor tem muitos posts vips, ele puxa só os vips mas não trás os 3 que eu preciso.
É isso que não estou entendendo.
Comment: Eu colocaria a linha do limit depois do order_by, mas não sei se isso é o problema.
Comment: Já tirei e continua igual rs.
Comment: Poxa então precisa ver todo o processo para termos certeza do que está acontecendo ... complicado mesmo
Comment: Oque me deixa sem entender é que só tenho o model, puxo no Controller e exibo na View, não tem mais nada.
Será que tem outra forma de fazer random sem order by ?
Comment: Tem sim! .... ....
Comment: Quando vc roda essa consulta direto no banco (via phpmyadmin) do servidor de produção vem 6 registros?
Comment: Este post não foi respondido aqui e não foi respondido aqui.
Ficam colocando que meu post foi resolvivo aqui mas não foi, as respostas foram erradas e eu continuo com o problema.
Answer: Utilize dessa forma:
public function exibeSugestaoHome()
{
    $this->db->limit(3);
    $this->db->select("*");
    $this->db->from("anuncios");
    $this->db->where("vip > ",0);
    $this->db->order_by('RAND()');
    return $this->db->get()->result_array();
}

pode ser feito assim também, fazendo o embaralhamento de itens pela função do php, shuffle:
public function exibeSugestaoHome()
{
    $this->db->limit(3);
    $this->db->select("*");
    $this->db->from("anuncios");
    $this->db->where("vip > ",0);
    $result = $this->db->get()->result_array();
    shuffle($result);
    return $result;
}

a diferença das formas apresentadas que a primeira embaralha os itens direto na tabela, e o segundo somente nos resultados obtidos. Dependendo da situação uma delas se encaixa.
Comment: Verdade @BrunoLuiz o ultimo ele pega os 3 e gera um embaralhamento desses itens, já o primeiro gera o embaralhamento nos dados da tabela. Talvez tenha algo na sua tabela que está ocasionando ou na SQL que não está trazendo os 3 itens, tem que ver a fundo.
Comment: Pior que acabei de perceber que não funcionou, a última opção puxa os três e embaralha somente.
Eu preciso puxar itens aleatórios do banco para não ficar repetindo.
Comment: Então, no banco a opção vip é 0 ou 1.
Comment: @BrunoLuiz, então remova essa linha `$this->db->where("vip > ",0);` não faz sentido ou pior não recomendo `$this->db->where("vip >= ",0);` que é a mesma coisa que a primeira
Comment: Mas este campo eu só posso puxar os carros que são patrocinados no site, ali eu marco eles como patrocinado "vip" ou não.
Comment: @BrunoLuiz se vip é igual = 1 coloque `$this->db->where("vip",1);` ou o valor correspondente?

Erro limit Codeigniter


What would cause a wired vs wireless speed difference of 16mbps vs 9 mbps?

Question: Tested via speedtest.net
I've set my wireless router to be b/g/n mode (there's no n-only mode on my router).
And I am using a USB stick (N, not G) on on PC and an internal wireless on another laptop running XP Pro.
Answer: There are several factors that can cause a speed difference between wireless and wired.  Several common factors include environmental factors such as electrical interference, other wireless clients communicating with the same wireless device, and distance from the router.  It is important to understand that the wireless media(air) is a shared resource and can have collisions requiring retransmission of data.  This retransmission will cause the network to slow as the same data must be sent again.
Comment: Speed being cut to half? That much difference?
Comment: It can be that much yes.
Comment: Anything obvious I can check to eliminate some 'easy stuff' ?
Comment: honestly it is hit or miss.  Sometimes something will help greatly(turning off unneeded electronics), other times nothing makes a noticeable difference.  It could also be your network connection was congested at the time.  To many variables to really suggest anything specific.
Comment: @user1008636 -Plugged in to the router directly I get 120Mpbs internet. Over Wireless-N or G 2.4Ghz I get about 1Mbps (crowded spectrum). Over Wireless-N 5Ghz I get 100Mbps (almost empty spectrum). Wireless is hugely dependant on so many factors, whereas being plugged in to the router is not.
Comment: fwiw I also did a wireless scan of my house, there were 8 neighbouring AP's using Channel 11, 2 on Channel 7 and 2 on Channel 5. My router came defaulted to Channel 11, making the wifi almost useless. Changing it to Channel 9 made a significant difference.


can't connect to Parse with Xcode

Question: Im new on Parse.. I'm trying to connect to parse with Xcode, I'm follow the guide and this steps "Test the SDK" doesn't work for me. When om follow the guide and write exactly what they say on the website and run the app there an window pop up "build failed" and Xcode say " "PFObject" does not have a member named "SaveinBackground".
<code>var testObject: PFObject = PFObject(className: "TestObject")
    testObject["Foo"] = "bar"
    testObject.SaveinBackground()
</code>
How can i fix this ?
help me plz..
have a nice day!
Comment: Did you initialize your ParseFramework in the delegate?
Comment: That code is Swift, not Objective-C.  The method is probably named saveInBackground (lowercase "s", uppercase "I").  The languages are case-sensitive.
Comment: ashraf, yes i have initialize that..
Comment: anna: but how do i write ? doesn't work with swift ? I'm programming in swift.
Comment: `saveInBackground` not `SaveinBackground`
Comment: doesn't work. i have test all. upper and low case. error and "PFObject" does not have a member named "saveInBackground".
Answer: Did you follow this guide: http://codewithchris.com/using-parse-swift-xcode-6/? This is for Swift. Maybe that could help.

can't connect to Parse with Xcode


What is the difference between googly and doosra spin?

Question: I can see some of the spin bowlers bowl googly and some bowl doosra in international cricket matches.
What is the basic difference between googly and doosra spin?
How they differ from each other?
Answer: A 'doosra' is a delivery that an off-spinner bowls with an off spin action that spins from right to left. (This is different to a normal off spin delivery that spins left to right.)
A 'googly' is a delivery that a leg spinner bowls with a leg spin action that spins from left to right. A 'googly' is also referred to as a 'wrong'un'. (This is different to a normal leg spin delivery that spins right to left.)
Saqlain Mushtaq was the inventor of the 'doosra' and he bowled it quite well. Currently, Muttiah Muralidaran, Harbhajan Singh and Ajantha Mendis bowl it very well. The master of the Doosra is definitely Muttiah Muralidaran.
Shane Warne and Anil Kumble are one of best 'wrong-un' bowler ever.
Comment: @Bogdanovist: Thanks for your comment and valuable information
Comment: Good answer, the only inaccuracy is that Shane Warne didn't bowl many wrong-uns. His main variation delivery early in his career with 'the Flipper' that went straight on, low and fast off the pitch and later in his career he developed a 'slider' that was similar to the Flipper but was easier on his shoulder. Warne always has shoulder problems and the wrong-in strains the shoulder to bowl, hence he didn't bowl them often. Another example of a great wrong-un bowler is Brad Hogg who would often bowl more wrong-uns than regular leg breaks.
Answer: dossra is better than googly .When a batsmaen is a righthanded the doosra spins in the other direction and at confuses the batsmen .And the googly spins inside the righthanded batsmen the googly is a legspinner variations and the doosra is a off spinner variations .BUT but i am a offspinner
Answer: Dusra delivery comes faster without spin where as googly spins a bit after meeting the pitch with a flighted delivery.


Why is Chr(3) a constant expression but not Chr(172)?

Question: If I write the following code, ReSharper will suggest I convert the first variable, chr3 to a constant, but not the second variable, chr127.
Public Class ClassX
    Public Sub SomeMethod()
        Dim chr3 As String = Chr(3)
        Dim chr172 As String = Chr(172)

        Debug.WriteLine(chr3)
        Debug.WriteLine(chr172)
    End Sub
End Class

If I convert both to constants, I get a Visual Studio compiler warning on the Chr(172) stating that a "Constant expression is required", but no compiler warning for Chr(3).
Public Class ClassX
    Public Sub SomeMethod()
        Const chr3 As String = Chr(3)
        Const chr172 As String = Chr(172)

        Debug.WriteLine(chr3)
        Debug.WriteLine(chr172)
    End Sub
End Class

What makes Chr(3) a constant expression but not Chr(172)?
Comment: +1 interesting question. I'm pretty sure it has something to do with 172 being outside the standard ASCII table (it's 7 bits, I expect your problem thus to occur at values above 127), I have no clue however why it would bother the compiler like that.
Comment: Good insight.  It does appear to have something to do with 8-bit values, since sample values of 122 and 127 are accepted as constant expressions, but 128 and 172 are not.
Answer: Character 3 is the "end of text" character so it seems unsurprising that it might exhibit strange behaviour. This, and other similar characters, are rarely used directly.
Answer: Looking into the source code for Microsoft.VisualBasic.Strings.Chr(), I see the following (which I've simplified for this post by removing exception handling):
///
/// Returns the character associated with the specified character code.
///
///
/// <returns>
/// Returns the character associated with the specified character code.
/// </returns>
/// <param name="CharCode">Required. An Integer expression representing the code point, or character code, for the character.</param><exception cref="T:System.ArgumentException"><paramref name="CharCode"/> < 0 or > 255 for Chr.</exception><filterpriority>1</filterpriority>
public static char Chr(int CharCode)
{
  if (CharCode <= (int) sbyte.MaxValue)
    return Convert.ToChar(CharCode);

  Encoding encoding = Encoding.GetEncoding(Utils.GetLocaleCodePage());
  char[] chars1 = new char[2];
  byte[] bytes = new byte[2];
  Decoder decoder = encoding.GetDecoder();
  int chars2;
  if (CharCode >= 0 && CharCode <= (int) byte.MaxValue)
  {
    bytes[0] = checked ((byte) (CharCode & (int) byte.MaxValue));
    chars2 = decoder.GetChars(bytes, 0, 1, chars1, 0);
  }
  else
  {
    bytes[0] = checked ((byte) ((CharCode & 65280) >> 8));
    bytes[1] = checked ((byte) (CharCode & (int) byte.MaxValue));
    chars2 = decoder.GetChars(bytes, 0, 2, chars1, 0);
  }
  return chars1[0];
}

It appears to be that for 7-bit values, Convert.ToChar(CharCode) is returned, which I'm guessing the compiler is smart enough to conclude is a constant, whereas for 8-bit values the current culture's CodePage gets involved, which will give different results based on the computer the code runs on, and therefore cannot be a constant.
Update:  I've tried to replicate the situation in a method I wrote myself, but cannot, which suggests the compiler itself may have a special case rule for evaluating constant expressions.
Private Function ConstOrNot(input As Int32) As Int32
    If input = 3 Then Return 7
    Return (New Random).Next
End Function

Const intC1 As Int32 = ConstOrNot(3)

(That said, ConstOrNot() exists in the same assembly as the code calling it, so this might not have worked anyway.)


Same value being inserted into table with cursor

Question: I'm trying to dynamically count the number of null values held in a table. So far I have this:
BEGIN
    DECLARE STMT VARCHAR(2000);
    FOR v AS CRS CURSOR FOR
        SELECT NAME
        FROM SESSION.TT1
    DO
        SET STMT = 'UPDATE SESSION.TT1 TT1
                        SET NULL_COUNT = (
                            SELECT COUNT(*) - COUNT('''||v.NAME||''') NULL_COUNT
                            FROM Table1
                        )
                    WHERE TT1.COLUMN_NAME = '''||v.NAME||'''';
        EXECUTE IMMEDIATE STMT;
    END FOR;
END

This runs fine, and does populate the temp table with data, but it updates every row with the same value (which is obviously incorrect).
Where have I gone wrong?
Note:

The temporary table, TT1, was generated by another procedure, it contains two columns; NAME, and NULL_COUNT. All values in the NULL_COUNT column are undefined at this point, and the NAME column contains column names retrieved from syscolumns.
I also tried removing the row and then inserting a new row rather than updating on the matched column name but this provides the same results.
Comment: Out of interest `NUMNULLS` in `SYSCAT.COLUMNS` will give you the number of NULL values in a column (as at the last RUNSTATS command)
Comment: @P.Vernon Ah yeah sorry, I should have mentioned that NUMNULLS isn't up to date and I don't have authorization to run the RUNSTATS command.
Answer: You need double quotes (or no quotes) around the column name, otherwise you are are simply counting a literal value, rather than the column...
DROP   TABLE TABLE1@
CREATE TABLE TABLE1(C INT)@
INSERT INTO TABLE1 VALUES(NULL),( NULL)@
DECLARE GLOBAL TEMPORARY TABLE TT1(NAME VARCHAR(128), NULL_COUNT BIGINT)@
INSERT INTO SESSION.TT1 VALUES ('C',null)@

BEGIN
    DECLARE STMT VARCHAR(2000);
    FOR v AS CRS CURSOR FOR
        SELECT NAME
        FROM SESSION.TT1
    DO
        SET STMT = 'UPDATE SESSION.TT1 TT1
                        SET NULL_COUNT = (
                            SELECT COUNT(*) - COUNT("'||v.NAME||'") NULL_COUNT
                            FROM TABLE1
                        )
                    WHERE TT1.NAME = '''||v.NAME||'''';
        EXECUTE IMMEDIATE STMT;
    END FOR;
END
@
SELECT * FROM SESSION.TT1
@
NAME NULL_COUNT
---- ----------
 C             2

Comment: BTW, unless you are using `ORGANIZE BY COLUMN` tables, it would be more efficient to count the NULLs in all columns in one SELECT rather than one column at a time.. (assuming you want to run the above for more than one column in the same table).


FreeImage problems on Android (NDK)

Question: I tried to use FreeImage library to load PNG as a texture (from memory). That's the fragment of code:
FIMEMORY *fiStream = FreeImage_OpenMemory(streamData, size);
FREE_IMAGE_FORMAT fileFormat = FreeImage_GetFileTypeFromMemory(fiStream, 0);
FIBITMAP *image = FreeImage_LoadFromMemory(fileFormat, fiStream, 0);

int bitsPerPixel = FreeImage_GetBPP(image);

width = (int)FreeImage_GetWidth(image);
height = (int)FreeImage_GetHeight(image);

I'm using FILE with fopen to open file and then read stream to streamData object. File and stream is read correctly.
The result is: fileFormat = -1 and image is NULL.
I also tried to use FreeImage to load PNG file directly from disk using FreeImage_Load, but the result is the same - it returns NULL.
Has anybody faced similar problem? Can you suggest an alternative to FreeImage that can read data from memory?
Comment: Have you solved it? I have similiar problem here:
http://stackoverflow.com/questions/42120978/freeimage-getfiletype-not-working-in-android-ndk
Comment: @user7428910 Actually we changed library for processing png. Couldn't make it work with FreeImage
Answer: try this code to load your image from memory:
File file = new  File("/sdcard/Images/image1.jpg");

if(file.exists()){
    Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    ImageView image = (ImageView) findViewById(R.id.imageview);
    image.setImageBitmap(bitmap);
}

Comment: Thanks for quick answer but rather looking for pure native solution

FreeImage problems on Android (NDK)


Jumping-index summations

Question: If we had a code segment like this:
int sum = 0;
for(int j = 1; j <= n; j++){
    for(int k = 1; k <= j; k++){
        sum += k;
return sum;

then we could convert it into summation notation to evaluate it:
$$\sum_{j=1}^n \sum_{k=1}^j k = \frac 16 n (n + 1) (n + 2)$$
which is trivial to compute.
However, what if we have something like this? (here $j$ and $k$ increase by an integer more than $1$)
int sum = 0;
for(int j = 1; j <= n; j += 3){
    for(int k = 1; k <= j; k += 2){
        sum += k;
return sum;

With these "jumping summations," is it possible to convert into summation notation? I considered putting, say, $j$ in the form $1+3x$ and $k$ in the form $1+2u$, but then one must manually solve for each the index bounds, which isn't pure enough for me (and I'm not convinced that such an approach would work, anyway).
Is there developed theory on how to approach such summations? I feel like there should be an easy way to convert them into typical summations, but I'm not sure how to do so.
Comment: Yes it is possible. A hint could be to think of derivatives and integrals (if you have done some calculus).
Comment: I've done some calculus, but I'm not entirely sure how that applies here. Could you please elaborate a bit on this?
Comment: I don't quite know how to explain it well. Maybe I will be able to formulate it better later.
Answer: Take the code
int sum = 0;
for (int j=1; j<=n; j += t){
    sum += f(j);
}
return sum;

for some function
float f(int);

The output of this code would be
$$f(1)+f(1+t)+\cdots+f(1+st)=\sum_{j=0}^{s}f\big(jt+1\big)$$
where $s=\max\{\sigma\in\Bbb Z:1+\sigma t\le n\}$. Then $s=\max\{\sigma\in\Bbb Z:\sigma\le (n-1)/t\}=\lfloor (n-1)/t\rfloor$.
Applying this to your code, we get
$$\sum_{j=0}^{\lfloor (n-1)/3\rfloor}\sum_{k=0}^{\lfloor 3j/2\rfloor}(2k+1)=\sum_{j=0}^{\lfloor (n-1)/3\rfloor}(\lfloor 3j/2\rfloor+1)^2$$
This is
$$S-T$$
where
$$S=1^2+2^2+\cdots+(a+1)^2,$$
$$T=3^2+6^2+\cdots+(3b)^2$$
where $a$ is the half, rounded down, of the greatest multiple of $3$ strictly lesser than $n$, and $3b$ is the greatest multiple of $3$ not greater than $a+1$.
Comment: Why don't we have $\lfloor (j-1)/2 \rfloor$ as the upper bound of the inner summation? Also, how did you get to the $S - T$ part? I don't see how it follows.
Answer: Your new version can be written $$\sum_{j=1}^{\lfloor \frac n3\rfloor} \sum_{k=1}^{\lfloor\frac j2\rfloor}(2k-1)=\sum_{j=1}^{\lfloor\frac n3\rfloor}\left \lfloor\frac j2\right \rfloor^2$$ which you can sum the same way.

Jumping-index summations


Proving that a 4th degree polynomial function has four fixed points and finding those fixed points

Question: So I have this function: $g(x)=-\mu^3x^4+2\mu^3x^3-\mu^2(\mu+1)x^2+\mu^2x$ where $\mu \in [0, 4]$ and $x\in[0, 1]$. Mu is a constant parameter. I have to prove that this function has 4 fixed points and I have to calculate them which means finding them without numerical methods. I have no idea how to proceed for both of these questions so I was hoping maybe someone here could guide me. So far I was thinking that since $g(x) = x$ I could subtract x on both sides and obtain a function that is equal to zero and then show that the function has 4 zeros because it is a 4th degree polynomial but I am not sure about that. As for the fixed points, other than x=0 I don't know how I can find them, because I don't know how to factor this polynomial or the one obtained by dividing by x and subtracting by 1. Also, I have to prove that $g(x) \in [0, 1]$ for the ranges I gave earlier for $x$ and $\mu$. I tried using the derivative to find the max value of the function but once again I am stuck with a third degree polynomial.
I would be very grateful if anyone could help or at least point me in the right direction, I am totally stuck on this problem. Thanks
Comment: $x=0$ is one of them
Comment: And a polynomial of degree $N$ has $N$ roots. But in this case you need to prove that they are all real.
Comment: Hint: $g(x)-x$ has another linear factor besides $x$. Try looking for another nice root the way you would use the rational root theorem to look for a nice root of a polynomial with integer coefficients.
Comment: Not sure if this helps ? But the graph ... https://www.desmos.com/calculator/eg5qwmgn2j
Comment: @GregMartin Oh right I forgot I could use polynomial division to factor the polynomial once I find a root. Thank you!
Answer: For the mentioned range for $\mu$, it is not true that you always have four fixed points... For instance,

If $\mu = 1$, you have a single fixed point
If $\mu = 2$, you have two fixed points
If $\mu = 4$, you have four fixed points

Maybe you want to rephrase the question?
Comment: That is how the question was phrased in my homework. It is actually correctly phrased because we are studying $g_\mu$ which means it comprises every value $\mu$ can have in the chosen interval. We aren't working with $g_1$ or $g_3$.  Either way I already know what you said, I managed to find the answer to each of my questions myself.
Comment: @Samishe That is my point exactly... If you are dealing with $g_{\mu}$ for $\mu \in [0,4]$, it is not true, in general, that $g_{\mu}$ has four fixed points.
Comment: I don't think you understand. We are not working with a specific value of $\mu$. By subtracting x on both sides we get a 4th degree polynomial and a 4th degree polynomial has 4 roots which means 4 fixed points.
Comment: @Samishe This is a matter of definition. Fixed points are not counted according to their multiplicity has roots of $g_{\mu}(x) -x$. The number of fixed points is the number of **distinct** solutions of $g_{\mu}(x) = x$.
Comment: Isn't that the exact same thing? A fixed point verifies the equation $g_\mu (x) = x$ which means it must also verify the equation $g_\mu (x) - x = 0$. Both equations are equivalent...
Comment: Also, it is literally the reason why one can convert fixed points into roots and use numerical methods that are used to find roots like Newton's in order to find those fixed points. The equations are equivalent which means the number of fixed points is actually equal to the number of roots of $g_\mu (x) - x = 0$
Comment: @Samishe It is not the same... If your forth order polynomial has two real roots with multiplicity 1 and one root with multiplicity 2 (four roots, considering the multiplicities) you have 3 fixed points, not four.
Comment: @samishe that is what I am saying... A forth order polynomial may have less than 4 distinct roots, hence, there may be less than 4 fixed points. This is why the question is poorly phrased (I understand this is not your fault).
Comment: Fair enough, I understand what you mean but I can't really alter the question I was asked in the homework. However, in that case the function does have 4 distinct roots so I guess maybe that is why my teacher phrased it that way.