text:
Q: Too few arguments to function Slim\Views\TwigExtension::__construct(), 0 passed and exactly 2 expected I'm trying to generate a link to a delete method using the urlFor helper, and i am using twig extensions to utilize the urlFor method but im getting the error
Too few arguments to function Slim\Views\TwigExtension::__construct(), 0 passed in /Applications/MAMP/htdocs/eli35/src/dependencies.php on line 47 and exactly 2 expected
not sure what to include in the parameters.
Ultimately im trying to click on the delete link to delete a task.
Any suggestions, thanks in advance.
Here is the dependencies.php file.
<?php
// DIC configuration

$container = $app->getContainer();

// view renderer
$container['renderer'] = function ($c) {
    $settings = $c->get('settings')['renderer'];
    return new Slim\Views\PhpRenderer($settings['template_path']);
};

// monolog
$container['logger'] = function ($c) {
    $settings = $c->get('settings')['logger'];
    $logger = new Monolog\Logger($settings['name']);
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    $logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
    return $logger;
};

$container['db'] = function($c){
    $settings = $c->get('settings')['db'];
    $pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'] . ";port=" . $settings['port'],
    $settings['user'], $settings['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig( 'views', [
        'cache' => false,
    ]);
    $view->addExtension(new \Slim\Views\TwigExtension(
        $container->router,
        $container->request->getUri()
    ));

    $view->parserExtensions = array(
        new \Slim\Views\TwigExtension(),
    );

    return $view;
};

here is the section of the TodosController.php for my delete method
public function deleteTodo($request, $response, $args)
{
    $sth = $this->db->prepare("DELETE FROM tasks WHERE id=:id");
    $sth->bindParam("id", $args['id']);
    $sth->execute();
    $todos = $sth->fetchAll();

    return $this->response->withRedirect('/todos');

}

here is the route link for my delete method, its in the routes file
$app->delete('/todo/[{id}]', '\App\Controllers\TodosController:deleteTodo')->setName("deletetask");
here is todos.twig where im displaying the delete link
{% extends "templates/layout.html" %}

{% block content %}

My Todos

  {% for task in todos %}

{{ task.task}}

        {{task.created_at |date("m/d/Y")}}

        Delete

    {% endfor %}

{% endblock %}

A: Remove the extra junk code.
$container['view'] = function ($container) {
        $view = new \Slim\Views\Twig( 'views', [
            'cache' => false,
        ]);
        $view->addExtension(new \Slim\Views\TwigExtension(
            $container->router,
            '/'
        ));

        return $view;
    };


text:
Q: Spinner from shinycssloaders package loads before pressing the action button I am creating a shiny app with some tabs and I am using the shinycssloaders package in order to show a spinner AFTER pressing the actionButton. I saw this post because I was having the same problem... I followed the solution that it was given to the post, but as I my app is different (it has tabPanels, it doesn't work properly, the spinner still apears).
For example, if you click on "Show the plot" in the first tab (selection) and then you want to want to do the log2 transformation o calculate the square root (3rd tab, calculations), before clicking the actionButton the spinner appears and the plot updates. It happens the same when you want to change the titles (2nd tab).

Does anyone know how to fix it?
Thanks very much in advance
The code:
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))

ui <- fluidPage(

  # Application title
  titlePanel("My shiny app"),

  sidebarLayout(
    sidebarPanel(

      tabsetPanel(
          tabPanel("Selection",
                  selectInput("x_axis", "Choose x axis",
                            choices = new_choices),

                  selectInput("y_axis", "Choose y axis",
                              choices = new_choices),

                  hr(),
                ),

          tabPanel("Titles",
                    hr(),

                    textInput(inputId = "title", "You can write the title:",  value = "This is the title"),
                    textInput(inputId = "xlab", "You can re-name the x-axis:",  value = "x-axis...."),
                    textInput(inputId = "ylab", "You can re-name the y-axis:",  value = "y-axis ...."),

                  ),

          tabPanel("Calculations",
                    hr(),

                    checkboxInput("log2", "Do the log2 transformation", value = F),
                    checkboxInput("sqrt", "Calculate the square root", value = F),

                   )

          ),
      actionButton(inputId = "drawplot", label = "Show the plot")

      ),

              # Show a plot of the generated distribution
              mainPanel(
               # plotOutput("plot")
                uiOutput("spinner"),

              )
      )
    )

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

  data <- reactive({
    mtcars
  })

  filtered_data <- reactive({
    data <- data()
    if(input$log2 == TRUE){
      data <- log2(data+1)
    }
    if(input$sqrt == TRUE){
      data <- sqrt(data)
    }
    return(data)

  })

  observeEvent(input$drawplot, {

    output$spinner <- renderUI({
      withSpinner(plotOutput("plot"), color="black")
    })

    output$plot <- renderPlot({
      Sys.sleep(3)
      ggplot() +
        geom_point(data = filtered_data(),
                   aes_string(x = input$x_axis, y = input$y_axis)) +
        xlab(input$xlab) +
        ylab(input$ylab) +
        ggtitle(input$title)
    })

  })

}

shinyApp(ui, server)

A: You need to isolate the expressions that you don't want to trigger the rendering event inside renderPlot
library(shiny)
library(magrittr)
library(DT)
library(ggplot2)
library(shinycssloaders)
new_choices <- setNames(names(mtcars), names(mtcars))

ui <- fluidPage(

    # Application title
    titlePanel("My shiny app"),

    sidebarLayout(
        sidebarPanel(

            tabsetPanel(
                tabPanel("Selection",
                         selectInput("x_axis", "Choose x axis",
                                     choices = new_choices),

                         selectInput("y_axis", "Choose y axis",
                                     choices = new_choices),

                         hr(),
                ),

                tabPanel("Titles",
                         hr(),

                         textInput(inputId = "title", "You can write the title:",  value = "This is the title"),
                         textInput(inputId = "xlab", "You can re-name the x-axis:",  value = "x-axis...."),
                         textInput(inputId = "ylab", "You can re-name the y-axis:",  value = "y-axis ...."),

                ),

                tabPanel("Calculations",
                         hr(),

                         checkboxInput("log2", "Do the log2 transformation", value = F),
                         checkboxInput("sqrt", "Calculate the square root", value = F),

                )

            ),
            actionButton(inputId = "drawplot", label = "Show the plot")

        ),

        # Show a plot of the generated distribution
        mainPanel(
            # plotOutput("plot")
            uiOutput("spinner"),

        )
    )
)

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

    data <- reactive({
        mtcars
    })

    filtered_data <- reactive({
        data <- data()
        if(input$log2 == TRUE){
            data <- log2(data+1)
        }
        if(input$sqrt == TRUE){
            data <- sqrt(data)
        }
        return(data)

    })

    observeEvent(input$drawplot, {

        output$spinner <- renderUI({
            withSpinner(plotOutput("plot"), color="black")
        })

        output$plot <- renderPlot({
            Sys.sleep(3)
            ggplot() +
                geom_point(data = isolate(filtered_data()),
                           aes_string(x = isolate(input$x_axis), y = isolate(input$y_axis))) +
                xlab(isolate(input$xlab)) +
                ylab(isolate(input$ylab)) +
                ggtitle(isolate(input$title))
        })

    })

}

shinyApp(ui, server)

Read more about shiny reactivity and isolation: https://shiny.rstudio.com/articles/isolation.html

A: Is it OK like this? I'm not sure to understand all your requirements. To avoid the spinner at the start-up, I use a conditionalPanel. In the server code, I did some changes. It is not recommended to define some output inside an observer.
library(shiny)
library(magrittr)
library(ggplot2)
library(shinycssloaders)

new_choices <- setNames(names(mtcars), names(mtcars))

ui <- fluidPage(

  # Application title
  titlePanel("My shiny app"),

  sidebarLayout(
    sidebarPanel(

      tabsetPanel(
        tabPanel(
          "Selection",
          selectInput("x_axis", "Choose x axis",
                      choices = new_choices),

          selectInput("y_axis", "Choose y axis",
                      choices = new_choices),

          hr(),
        ),

        tabPanel(
          "Titles",
          hr(),

          textInput(inputId = "title", "You can write the title:",  value = "This is the title"),
          textInput(inputId = "xlab", "You can re-name the x-axis:",  value = "x-axis...."),
          textInput(inputId = "ylab", "You can re-name the y-axis:",  value = "y-axis ...."),

        ),

        tabPanel(
          "Calculations",
          hr(),

          checkboxInput("log2", "Do the log2 transformation", value = F),
          checkboxInput("sqrt", "Calculate the square root", value = F),

        )

      ),
      actionButton(inputId = "drawplot", label = "Show the plot")

    ),

    # Show a plot of the generated distribution
    mainPanel(
      conditionalPanel(
        condition = "input.drawplot > 0",
        style = "display: none;",
        withSpinner(plotOutput("plot"))
      )
    )
  )
)

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

  data <- reactive({
    mtcars
  })

  filtered_data <- reactive({
    data <- data()
    if(input$log2 == TRUE){
      data <- log2(data+1)
    }
    if(input$sqrt == TRUE){
      data <- sqrt(data)
    }
    return(data)
  })

  gg <- reactive({
    ggplot() +
      geom_point(data = filtered_data(),
                 aes_string(x = input$x_axis, y = input$y_axis)) +
      xlab(input$xlab) +
      ylab(input$ylab) +
      ggtitle(input$title)
  }) %>%
    bindEvent(input$drawplot)

  output$plot <- renderPlot({
    Sys.sleep(3)
    gg()
  })

}

shinyApp(ui, server)

redpajama_set_name: RedPajamaStackExchange


text:
Q: much more a lot with adjective Are these correct?

*

*much more + adjective (I was much more busy);

*a lot more + adjective (I was a lot more busy);

*much less + adjective (I was much less busy);

*a lot less + adjective (I was a lot less busy);

*a little + adjective;

*much/ a lot + adjective;

*a little more/less + adjective;
What is right? Which may be similar?

A: "More busy" could almost always be phrased more concisely as "busier." There are few cases in which "more busy" is preferable to the comparative adjective "busier."
One such case is when "more busy" is comparative and positioned against another adjective in the sentence: "I was more busy than [adjective]." For a more specific example, "I was more busy than free" or "I was more busy than not."
"More busy" may also be acceptable when used as a rhetorical or oratorical device. For example, this quote by Dag Hammerskjöld: "The more we do, the more we can do; the more busy we are, the more leisure we have," uses "more busy" to create parallelism.
"Less busy" does not have an equivalent word the way "more busy" does. Therefore, "less busy" is correct, as long as it is followed by "than." E.g., "less busy than..." You could also use "not as busy as [noun]" to convey a similar meaning.
In short, I'd recommend rephrasing to say "busier" anytime you find yourself using the phrase "more busy." It's rarely incorrect, and will make your writing more concise.


text:
Q: How to change image name in multiupload with CodeIgniter? I want to change image names when uploading more than one image. I have tried to use this config but it doesn't work $config['file_name'] = $this->getRandomString(); So, I need help with this
function addProductPhotoGallery() {
    if ($this->session->userdata('admin_login')) {
        $this->load->model('admin/admin_model');
        $gallery_photo = array();
        $gallery_path = realpath(APPPATH . '../imgs/product_pic/');
        $config1['upload_path'] = $gallery_path;
        $config1['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
        $config1['max_size'] = '2000';
        $this->load->library('upload', $config1);
        $this->upload->initialize($config1);
        $thum_path = realpath(APPPATH . '../imgs/product_pic/thumbs');
        $config = array(
            'image_library' => 'gd2',
            'source_image' => '',
            'maintain_ratio' => TRUE,
            'width' => 300,
            'height' => 200,
            'new_image' => $thum_path
        );
        $this->load->library('image_lib', $config);

        ///////////// for loop and code that upload  photo /////////////////////
        $i = 1;
        foreach ($_FILES as $filey) {
            if (isset($_FILES['file' . $i])) {
                $config['file_name'] = $this->input->post('username').$this->getRandomString();
                // $_FILES['file' . $i]['name'] = $this->input->post('username').$this->getRandomString();
                if($this->upload->do_upload('file' . $i)){
                $phot_data = $this->upload->data();
                $gallery_photo[$i] = $phot_data['file_name'];
                $config['source_image'] = $phot_data['full_path'];
                $this->image_lib->initialize($config);
                $this->image_lib->resize();
                $i++;
            }else{
                break;
                return false;

            }
            }
        }
        return serialize($gallery_photo);

    } else {
        redirect('civou/home');
    }
}

A: Try to putting $this->image_lib->clear()
after $this->image_lib->resize() so that on the next loop the/a new $config['file_name'] is used.


text:
Q: WinForms Application Form "Shakes" When Audio Playing I have a C# game program that i'm developing. it uses sound samples and winsock.
when i test run the game most of the audio works fine but from time to time if it is multiple samples being played sequentially the application form shakes a little bit and then goes back to its old position.
how do i go about debugging this or present it to you folks in a manageable manner? i'm sure no one is going to want the whole app code in fear of virus attacks.
please guide me..
EDIT: i have not been able to pin down any code section that produces this result. it just does and i cannot explain it.
EDIT: no the x/y position are not changing. the window like shakes around a few pixels and then goes back to the position were it was before the shake.
if (audio)
{
    Stream stream;
    SoundPlayer player;

    stream = Properties.Resources.ResourceManager.GetStream("_home");
    player = new System.Media.SoundPlayer(stream);
    player.PlaySync();
    player.Dispose();

    string ShipID = fireResult.DestroyedShipType.ToString();
    stream = Properties.Resources.ResourceManager.GetStream("_" + ShipID);
    player = new System.Media.SoundPlayer(stream);
    player.PlaySync();
    player.Dispose();

    stream = Properties.Resources.ResourceManager.GetStream("_destroyed");
    player = new System.Media.SoundPlayer(stream);
    player.PlaySync();
    player.Dispose();
}

can you see anything in the above code that would produce this shake?
EDIT: yes the code is being executed within a: this.Invoke(new Action(delegate(){ ....})); could this be it? how do i resolve this?
EDIT:
           stream = Properties.Resources.ResourceManager.GetStream("_destroyed");
           player = new System.Media.SoundPlayer(stream);
           player.PlaySync();
           player.Dispose();
           stream.Dispose();

if the take out the above code, then it works fine! any ideas?
EDIT: i replaced the line with:
stream = Properties.Resources.ResourceManager.GetStream("_destroyed");

to a different file name but the problem is still there but at least it is not the audio file is corrupt.
EDIT:  MSN when someone sends a nudge? it is bit like that but only happens 2 or 3 times.
EDIT: Are you using any 3rd party libraries? - no i am not using any 3rd party libs.
EDIT: it seems no matter what file, the 3rd sample always causes this.
EDIT: happens everywhere i use sound samples. if i play 3 samples, the situation happens.
EDIT: @nobugz: yes  think you are right. the problem is holding up the UI thread for too long. as i have tried just using a merged audio file and the problem is there given its original duration.
EDIT: i solved this issue by putting Application.DoEvents(); after each sample play command. no shakes :)
EDIT: the above solution did not really work. as the number of player samples grew the application GUI got stuck again. a solution using QueueUserWorkItem has been employed instead. this still remains to be proven as a satisfactory solution as cross therading occurs i.e. a new thread of samples can be started while an old one is still playing.
will update this as more knowledge comes to light.

A: Calling PlaySync on the UI thread isn't so great.  It will make your main window unresponsive as your UI thread is busy waiting for the sound to finish, it doesn't get around to pumping messages like it should do.  If that takes long enough, Windows steps in and overlaps the window with a "ghost", it usually says "Not Responding" in the title bar (if it has one).  This ghost window might not quite match your own window, that could explain the "shaking".
Using Play() instead will solve that problem.  But gets you a new one, sequencing sounds becomes difficult.  Making the calls from a thread can solve both.  Check out NAudio for better control over sound.

A: Make a copy of your program.  Delete as many game elements from the copy as possible.  Remove modules, chop out game logic, shift functions between classes to reduce abstraction (so that you can delete classes), and generally hack up the game.
Each time you do so, check if the bug still exists.  Initially you'll be deleting bigger chunks of the program but over time the amount of deletion will reduce.
If you find something which, when deleted, fixes the bug, there are two possibilities: Either you found the bug, or there is some sort of synergy with the rest of the program to cause the bug.  In the latter case, continue deleting more of the program.
Eventually, you will end up with a minimal program that has the bug.  Post that here (or in a pastebin if it's too big).
This is one of the last-resort strategies I use when I encounter a bug that I am unable to locate at all.


text:
Q: Weird pdflatex log output my pdf generation works like pdflatex biber pdflatex pdflatex. In the context of final PDF generation, I checked the log file and stumbled upon several weird entries:
<graphics/measurementOverview.pdf, id=2875, 384.43625pt x 196.23312pt>

The weird thing about this is the dimension: I checked the text width (using \the\textwidth) to be 383.0pt. So I created all my pdf figures on exactly 383.0pt. Besides, I include figures like that:
\newcommand\figureFrame[3][ht]{%
    \begin{figure}[#1]
        \centering
        \includegraphics[width=\textwidth]{graphics/#2}
        \caption{#3}
        \label{fig:#2}
    \end{figure}
}

As you can see, also there is the text width of 383.0pt used. So why the hell prints the pdflatex run this strange dimension of 384.43625pt? This happens for nearly all my figures... thank you!


text:
Q: How to Keep Frozen Panes from Scrolling? - Excel I want to make a sheet that has some columns that are frozen, but I don't want the rows in those columns to scroll with the rest of the sheet when I scroll down. For example, I want A1:D40 to be frozen, and when I scroll down through the sheet, I want A41:D(end of sheet) to slide behind A1:D40. Is this possible? And could the the same thing be done for rows at the same time? I'm hoping to use this to make a control panel type thing and i'd rather the buttons and what not always be visible.
Thanks,
Brad


text:
Q: Displace axes in pstricks using paxes I am using this code to produce the following plot with pstricks:
\documentclass[pstricks]{standalone}
\usepackage{pst-func,amsmath,xfp}
\begin{document}
\definecolor{fillColor}{RGB}{125, 185, 250}
\psset{xunit=1cm,yunit=5cm}%
\begin{pspicture}(-2,-0.25)(7.5,2.1)%
    \rput(0,1.4)
    {
    \uput[-90](7,0){$x$} \uput[60](0,0.5){$P(X=x)={}^N\!C_x \\~\\ p^x(1-p)^{N-x}$}
    \psBinomial[markZeros,fillstyle=solid,opacity=0.5,fillcolor=fillColor,
    barwidth=0.01,linecolor=fillColor]{6}{0.5}
    \uput[90](6,0.5){$X \sim B(6,0.5)$}
    \psaxes[Dy=0.1,dy=0.1\psyunit,tickstyle=bottom]{->}(0,0)(0,0)(7,0.5)
   }
\end{pspicture}

\end{document}

and I am getting this plot:

But for consistency with other plots in the paper I would like to displace the axes like the ones we get when using frame=FALSEe R base plot:

I have played with the \psaxes coordinates but got no luck. Any ideas?
Thanks in advance!

A: for example with different \psaxes:
\documentclass[pstricks]{standalone}
\usepackage{pst-func,amsmath,xfp}
\begin{document}
    \definecolor{fillColor}{RGB}{125, 185, 250}
    \psset{yunit=5cm}%
    \begin{pspicture}(-2,-0.25)(7.5,2)%
            \uput[0](5,0){$x$} \uput[60](0,1.5){$P(X=x)={}^N\!C_x \\~\\ p^x(1-p)^{N-x}$}
            \rput(0.2,0){\psBinomial[markZeros,fillstyle=solid,opacity=0.5,fillcolor=fillColor,
                barwidth=0.01,linecolor=fillColor,xunit=0.2,yunit=4.5]{6}{0.5}}
            \uput[90](6,1.5){$X \sim B(6,0.5)$}
            \psaxes[yAxis=false,Dx=5,dx=1,tickstyle=bottom](5,0.5)
            \rput(0,0.5cm){\psaxes[xAxis=false,Dy=0.05,dy=0.25,Oy=0.05,tickstyle=bottom](0,1.25)}
    \end{pspicture}

\end{document}

A: So, this is the closest I can get:

Just add these lines and change the psaxes as below:
\psaxes[yAxis=false,Dy=0.1,dy=0.1\psyunit,tickstyle=bottom]{->}(0,0)(0,0)(7,0.5)
    \psline[linewidth=0.94pt]{->}(-0.3,0.0)(-0.3,.5)
    \multido{\n=0.1+0.1}{4}{%
        \psdots[dotstyle=|, dotangle=90,dotsize=4pt,fillcolor=black](-0.35,\n)
        \rput(-0.8, \n){\n}}


text:
Q: How to join results of two variables in Powershell with a forward slash? With this script i am able to get a csv file containing different coulmns like ip address and subnetmask prefix of a vm but i want to have the ip address and the netmask Prefix in this format eg.: 10.1.1.1/26 combined in one coulmn. What is the possible best way to do that. Thanks
connect-AzAccount -Confirm
        # Report Name and location
        $reportFile = "C:\Users\john\Desktop\Inventory\Final Scripts\IP Address Details_$(get-date -f dd.MM.yyyy).csv"

        # Create Report Array
        $report = @()

        # Get all the VMs from the selected subscription
        $vms = Get-AzVM

        # Get all the Network Interfaces
        $nics = Get-AzNetworkInterface | Where-Object { $Null -ne $_.VirtualMachine }
        $ReportDetails = foreach ($nic in $nics) {
        $vnet = Get-AzVirtualNetwork -Name $nic.IpConfigurations.Subnet.Id.Split("/")[-3]
        $subnet = $nic.IpConfigurations.Subnet.Id.Split("/")[-1]
        $vm = $vms | Where-Object -Property Id -eq $nic.VirtualMachine.id
        $nic.IpConfigurations.PrivateIpAddress.foreach{
        [PSCustomObject]@{
        vm_name = $vm.Name
        ip_address = $_
        interface_name = $nic.Name
        netmask= (Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name $subnet).AddressPrefix.Split("/")[-1]

    }
}

}
        $ReportDetails| Sort-Object VMName | Format-Table ip-address, vm_name, interface_name, netmask
        $ReportDetails |  Export-Csv -NoTypeInformation -Path $reportFile

A: assuming $ip_address contains a single IP and $netInfo contains the subnetmask u can use -join "\" to merge the data:
$ip_address = $_
$netmask= (Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet -Name $subnet).AddressPrefix.Split("/")[-1]
$netInfo = $ip_address,$netmask -join "/"

[PSCustomObject]@{
    vm_name = $vm.Name
    netInfo = $netInfo
    interface_name = $nic.Name
}


text:
Q: What makes energy "the" conserved quantity associated with temporal translation symmetry? This kind of relates to my prior question about the non-triviality of temporal translation symmetry and will use some of the same concepts:
How is energy conservation & Noether's theorem a non-trivial statement?
Because it seems that, in fact, temporal translation symmetry, when taken under the formalism there which I consider to be a good and rigorous way to make sense of the idea of a "law of physics", there are many conserved quantities associated with that symmetry.
Suppose that we have a dynamical system $(M, \Phi^t)$, with phase manifold $M$ and evolution map ("law of physics") $\Phi^t$, $t \in \mathbb{R}$. Any such system is temporal translation symmetric in that a point $P \in M$ uniquely determines the trajectory $t \mapsto \Phi^t(P)$, whether the dynamical object is imagined to be at that point $P$ at time 0, or at any other time. In particular, this means that no two trajectories cross.
In such a formalism, a "quantity" is just a real-valued function of the phase point $P$. It follows rather simply from the temporal translation symmetry's property above - that no phase trajectories cross - and also the fact that every phase point generates a trajectory under $\Phi^t$, that we can create a conserved quantity by, for each trajectory, picking a real number value freely, and then assigning every point on that trajectory the same value. When we have done enough such choices as to cover the entire phase space, we have a conserved quantity, whose conservation is thus due to temporal translation symmetry.
Formally, let $S \subseteq M$ be a subset of the phase space such that the orbits, i.e. the sets $\mathrm{Orb}(P) := \{ \Phi^t(P)\ |\ t \in \mathbb{R} \}$ are pairwise disjoint, i.e. $\mathrm{Orb}(P_1) \cap \mathrm{Orb}(P_2) = \emptyset$ for all $P_1, P_2 \in S$ with $P_1 \ne P_2$. Call such a subset an initial subset because, if it contains a point that is different from a given one but that appears on the same orbit as the previous, it will generate a furtherance of that orbit and thus the two sets will not be disjoint - at the maximal possible way. Hence it can only contain one point from each orbit involved. Further, call such an $S$ maximal or generator if $\Phi^t[S]$, i.e. applying it to every point in $S$ elementwise, generates the whole manifold $M$.
Then for such a generator, pick an arbitrary function $f_S: S \rightarrow \mathbb{R}$ define a quantity $Q: M \rightarrow \mathbb{R}$ via the following: if $P \in S$, then $Q(P) := f_S(P)$, but if $P \notin S$, then figure out the time delta $\Delta t$ required so that $\Phi^{\Delta t}(P) \in S$ (it could be either positive or negative, and moreover one must exist by the above argumentation). Then define $Q(P) := f_S(\Phi^{\Delta t}(P))$.
This quantity $Q$ is then conserved via temporal translation symmetry.
There are $\beth_2$ such quantities, and $\beth_1$ if we require continuity.
These numbers are uncountably infinite. $\beth_2$ is enormous; much bigger than the real number continuum.
Why then do we speak of the energy as "the" conserved quantity associated with this symmetry? What, among that huge infinity of other potential quantities, singles it out over all the different contenders? I do note that all such quantities will be functions of each other, but then why is energy the "canonical" or "go-to" representative of this class?

A: *

*For what it's worth, OP seems to be mischaracterizing Noether's theorem by seemingly ignoring one of its main assumptions: That the physical system is equipped with an action formulation
$$S~=~\int\! dt~ L(q, \dot{q},t).\tag{1}$$

*The action formulation in turn leads to a notion of
momentum
$$ p_i ~:=~\frac{\partial L}{\partial \dot{q}^i },\tag{2} $$
and energy
$$ h~:=~p_i\dot{q}^i-L.\tag{3}$$

*And a time translation symmetry of the action leads to energy conservation, cf. e.g. this Phys.SE post.

A: If I understand the question correctly, then a flow $\Phi^t$ uniquely determines a Hamiltonian vector field $\mathbf X :=  \mathrm d\Phi^t\big|_{t=0}$.  Such a vector field can be written as
$$\mathbf X = \{\cdot, F\} \iff X^\mu = \omega^{\mu\nu} (\mathrm dF)_\nu \iff (\mathrm dF)_\mu = \omega_{\mu\nu} X^\nu$$
where $\{\cdot,\cdot\}$ is the Poisson bracket, $\omega$ is the symplectic form, $F$ is a smooth function on the phase space, and $\cdot$ denotes an empty slot.  We say that $F$ generates the vector field $\mathbf X$, and by extension the flow $\Phi^t$.

Example of the non-uniqueness: Let the $M$ be given by the 2-dimensional real phase space with points $(x, p)$. Define the time-evolve map via
$$\Phi^t(x, p) = \left(x \cos(t) + p \sin(t), -x \sin(t) + p \cos(t)\right)$$

This flow induces the Hamltonian vector field
$$\mathbf X = \mathrm d\Phi^t\big|_{t=0} = p \frac{\partial}{\partial x} - x \frac{\partial}{\partial p}$$
Comparing this with $\{\cdot, H\}= \frac{\partial H}{\partial p} \frac{\partial}{\partial x} - \frac{\partial H}{\partial x} \frac{\partial}{\partial p}$ for some smooth function $H$, we observe that $\frac{\partial H}{\partial p} = p$ and $\frac{\partial H}{\partial x} = x$, which implies that $H(x,p) = \frac{1}{2}(p^2+x^2) + C$ for some arbitrary constant $C$ which we may set to zero with no loss of generality.

From the expression $\mathrm dF = \omega( \cdot, \mathbf X) = \omega(\cdot,\mathrm d\Phi^t\big|_{t=0}\big)$ and the fact that $\omega$ is non-degenerate, we see that given a smooth flow $\Phi^t$ we obtain a function $F$ which generates it (up to a constant) and vice-versa.

QUESTION 1: What is special about the conserved quantity $Q(x,p)=\frac{1}{2}(x^2+p^2)$, when also the quantity $Q_2(x,p)=\sin(x^2+p^2)$ is conserved too, by the same temporal translational symmetry?

$Q$ and $Q_2$ are both conserved by the flow you specify, $Q$ actually generates that flow while $Q_2$ does not.

QUESTION 2: Is a better statement of Noether's theorem perhaps that every symmetry law of a dynamical system implies the existence of a naturally-associated set of conserved quantities?

In the context of Hamiltonian dynamics, Noether's theorem may be expressed as follows. If the flow $\Phi_F$ generated by $F$ preserves the Hamiltonian, then $H\circ\Phi_F^t = H$ and so $\frac{d}{dt}(H\circ \Phi_F^t)\big|_{t=0}=0$. Such a flow is called a symmetry of the system. This implies immediately that time evolution (i.e. the flow generated by $H$) preserves $F$, i.e. $F\circ \Phi_H^t = F \implies \frac{d}{dt}(F\circ \Phi_H^t)\big|_{t=0} = 0$.  The proof consists of a single line:
$$\frac{d}{dt} \big(H \circ \Phi_F^t\big)\big|_{t=0} = \mathbf X_F (H) = \{H,F\} = -\{F,H\} = -\mathbf X_H(F) = -\frac{d}{dt}(F\circ\Phi_H^t)\big|_{t=0}$$
If $F$ is such a conserved quantity, then obviously $f(F)$ will be conserved. However, note that $F$ and $f(F)$ will induce different flows.

A: There are nice answers already. I just want to add one small observation.
If $H$ is the energy, ordinary time is defined by the Hamiltonian flow with $H$, so observables evolve according to
$$\frac{dO}{dt} = \{H,O\}.$$
For any $f: \mathbb{R} \to \mathbb{R}$, $f(H)$ will be a constant of motion. If we consider the Hamiltonian flow by $f(H)$, which has a new parameter $\tau$, we have
$$\frac{dO}{d\tau} = \{f(H),O\} = f'(H)\{H,O\} = f'(H) \frac{dO}{dt}.$$
So if you like, $f(H)$ generates time translation but with a strange definition of the time,
$$f'(H) d\tau = dt.$$

A: The OP's question is basically stating that in a system with time-translation invariant dynamics, we can define a conserved quantity by arbitrarily assigning a real number to each orbit; when the system is in a particular state, the value of the quantity is the number assigned to the orbit that the state belongs to. The OP is asking why one particular quantity, the energy, is the conserved quantity associated with the time-translation symmetry and not any of the other possible arbitrary assignments.
In general, we are not interested in most of the possible conserved quantities that could be defined using this approach. Conserved quantities themselves are not useful; conservation laws are useful in the following sense: if $Q$ is a conserved quantity and $P$ is the initial state of the system, then you know that the system cannot evolve into any state $P'$ such that $Q(P) \ne Q(P')$. This statement is of use to the physicist only if there is a method to calculate $Q$ without having to integrate the equations of motion.
If the only way to calculate the conserved quantity is to work out the entire orbit that a particular state belongs to, so that, only once the orbit is identified in this manner, it is possible to see what $Q$ value was assigned to that orbit, then knowing the value of $Q$ no longer adds anything to your understanding. You have already done the hard work of calculating the entire orbit explicitly, and you don't need $Q$.
Noether's system gives an explicit formula for a conserved quantity if the system is described by a known action and there is a known continuous symmetry of that action. Essentially, if you write down the action and the symmetry, you just plug and chug to get the formula for the corresponding conserved quantity. For time-translation symmetry, the corresponding conserved quantity is the energy. This is extremely useful because the energy may generally be computed easily from this formula even if you don't know the entire orbit. In general, Noether's theorem will not help you determine how long it takes for the system to reach a particular state, but it will help you place strong constraints on which states the system might visit at all, assuming that the (known) action actually has a known symmetry.

A:
What is special about the conserved quantity $Q(x, p) := \frac{1}{2} (x^2 + p^2)$, when also the quantity $Q_2(x, p) = \sin(x^2 + p^2)$ is conserved too, by the same temporal translational symmetry?

If $x^2+p^2$ is conserved, then so is any $f(x^2+p^2)$ such as $sine(x^2 + p^2)$. But manipulation like this is a little baroque.
You may remember where the Hamiltonian ($H$ or "energy") comes from in the first place. It is a useful quantity because we know the dynamics of the system can be determined from the Lagrangian, via the Euler-Lagrange equations:
$$
\frac{d}{dt}\frac{\partial L}{\partial \dot q} - \frac{\partial L}{\partial q} = 0
$$
This means that (if there is no explicit time-dependence):
$$
\frac{dL}{dt} = \frac{\partial L}{\partial q}\dot q + \frac{\partial L}{\partial \dot q}\frac{d\dot q}{dt}
$$
$$
=\dot q\frac{d}{dt}\frac{\partial L}{\partial \dot q}+ \frac{\partial L}{\partial \dot q}\frac{d\dot q}{dt}
$$
$$
=\frac{d}{dt}\left(\frac{\partial L}{\partial\dot q}\dot q\right)\;.
$$
Or, in other words:
$$
\frac{d}{dt}\left(L - \dot q\frac{\partial L}{\partial \dot q}\right) = 0
$$
Or, in other words:
$$
H = \dot q\frac{\partial L}{\partial \dot q} - L
$$
is conserved (i.e., constant in time).
Or, put another way: If there is "time translation symmetry" then $H$ is conserved.
Yes, any other function of $H$, $f(H)$, is also conserved if $H$ is conserved, but it is $H$ that is useful since we can use it to get Hamiltonian's form of the equations of motion. OTOH, you are certainly free to consider any other quantity you like and free to call it what you like. But if you call something other than $H$ the "energy" it will just not coincide with the common and conventional usage of the terms (common for at least over a hundred years or so).

An update based on comments
Given a Lagrangian $L$, a different Lagrangian $L'$ will generate the same equations of motions (same dynamics) if the two are related by:
$$
L'(q,\dot q, t) = L(q,\dot q, t) + \frac{dF}{dt}
$$
$$
=L(q,\dot q, t) + \frac{\partial F}{dq}\dot q + \frac{\partial F}{\partial t} \;,
$$
where $F$ is any function of $q$ and $t$, but not $\dot q$.
For the time-translation invariant systems of interest here $F=F(q)$.
The relationship between the momentum $p=\frac{\partial L}{\partial \dot q}$ and the momentum $p' = \frac{\partial L'}{\partial \dot q}$ is
$$
p' = p + \frac{\partial F}{\partial q}
$$
The relationship between the Hamiltonian $H$ and $H'$ is found from
$$
H' = \dot q p' - L'
$$
$$
=\dot q(p + \frac{\partial F}{\partial q}) - L - \frac{dF}{dt}
$$
$$
=\dot q (p + \frac{\partial F}{\partial q}) - L - \frac{\partial F}{\partial q}\dot q
$$
$$
=\dot q p-L
$$
$$
= H
$$
That is, H and H' are the same.

A: I think this is an interesting question. One should keep in mind that the symmetries are in the action S, which is in many cases composed of dual Fourier pairs (position and momentum, or energy and time, for instance). We focus a lot on invariance of time translation leading to conservation of energy in 4-momentum space, but I think you are pointing to a dual relationship, invariance of a quantity under translation in 4-momentum space (such as the zero of energy can be arbitrarily moved anywhere in 4-momentum space) leading to a conserved quantity in spacetime, as you say "the trajectory". It's called the "center-of-mass theorem".
The following snippet is from my original research on this, which I think is relevant here:
"Noether's theorem provides a link between physical symmetries and conservation laws. A conservation law will exist for a property if the Lagrangian $\mathcal{L}$ is not dependent on that property, i.e., if $\mathcal{L}$ is not a function of time, then energy is conserved over time, and similarly for the space/momentum pair. If both are true, then Noether's theorem results in the relation (Neuenschwander 2011)
$$p_\mu \xi^\mu - H\tau = \text{constant}$$
where $\xi^\mu$ and $\tau$ are generators of translation. Symmetries in spacetime (time translation) result in conserved coordinates in momentum-space (energy conservation). What does this look like in momentum-space? Just as invariance of the action under infinitesimal translations in spacetime leads to conserved quantities in momentum-space, invariance of the phase distribution in momentum-space under infinitesimal boosts leads to a conservation law in spacetime. The result thus obtained is known as the center-of-mass theorem (\url{http://users.physik.fu-berlin.de/~kleinert/b6/psfiles/Chapter-7-conslaw.pdf}). Space and time are not individually conserved in this manner, but a certain relationship between them is indeed conserved, a ``conservation of trajectory''."
(ref: https://www.mdpi.com/2624-960X/3/1/2)

A: The answer is that the statement that there is such a thing as "the" conserved quantity associated to temporal translation - or to any symmetry - of a dynamical system, is simply wrong: instead, the existence of a symmetry implies, by the given argumentation, an enormous class of conserved quantities.
What the correct statement is is that given the quantity we know of as "energy", we can determine it belongs to the class generated by temporal translation symmetry, and as a result its conservation is a consequence of said symmetry.
What distinguishes energy from the other conserved quantities in its class really is, I believe, what @J. Murray mentions: it, or more accurately the quantity "Hamiltonian", $H$, generates the flow $\Phi^t$ in that an infinitesimal temporal advance $\Phi^{dt}$ can be given as (informally)
$$\Phi^{dt}(P) = P + [\nabla H](P)\ dt.$$
The reason we like to use energy is given by @Brian Bi's answer, though it is crucial to note that while this makes energy useful, it is not the sole quantity that has the property he describes as, say, $\sin(H)$, would also have the same property. And if we were not aware we were working with $\sin(H)$, we would still be able to do the manipulations he describes with it and it would not betray that it was not the "real" energy in that way. However, taken together, these two reasons provide a compelling argument for  distinguishing it from the rest of the pack.


text:
Q: Remove Element from JavaScript array in .NET core Razor I have input when the user click on add button it should add a new li in the ul list and add a new object in array "Keywords" to send it to the action,
but the problem is when the user removes an element from the ul list I remove the index of the element from the array it didn't work however the removal of the li element works well.
here is the script:

and this is the HTML:

A: Try to change
delbtns = $(".delete");
        for (var i = 0; i < delbtns.length; i++) {
            delbtns[i].onclick = function () {
                this.parentNode.remove();
                keywords.splice(i, 1);
            }
        }

to
$(".delete").on('click', function (event) {
            var delbtns = $(".delete");
            for (var i = 0; i < delbtns.length; i++) {
                if (this == delbtns[i]) {
                    this.parentNode.remove();
                    keywords.splice(i, 1);
                    break;
                }
            }
        })

result:


text:
Q: Service Bus - Retrieve message from session by sequence number I am currently trying to retrieve a specific message from a session.
To do so I use want to use the .Receive(Int64) on the MessageSession where I pass in the sequence number of the message.
Here is my code -
long msgSequenceNr = 1337;

QueueClient queueClient = QueueClient.CreateFromConnectionString(Constants.ServiceBusConnectionString, Constants.TestQueueEntityName, ReceiveMode.PeekLock);
MessageSession msgSession = queueClient.AcceptMessageSession(Constants.TestSessionId);

var peekedMsg = msgSession.Peek(msgSequenceNr); // <-- Works fine!
var receivedMsg = msgSession.Receive(msgSequenceNr); // <-- MessageNotFoundException

Unfortunately the Receive will result in a MessageNotFoundException while the Peek works fine.
Is this a limitation that I missed or is there another way to achieve this.
Note that it is possible that there are multiple messages in the session

A: Receive with the SequenceNumber can only be used in combination with the Defer method. This is how you would implement it:

*

*Message received, but it can't be processed right now (maybe it's waiting for a different process to complete).

*Persist the SequenceNumber in some persistent storage (Table Storage, SQL Database, ...)

*When you know that processing can continue (eg: the dependent process is complete), load all SequenceNumbers from your persistent storage.

*Use Receive(int sequenceNumber) or ReceiveBatch(int[] sequenceNumbers) to received and process your deferred messages.

Sample application: https://code.msdn.microsoft.com/windowsazure/Brokered-Messaging-ccc4f879#content
Update:
Form your comment I noticed that "undeferring" a deferred message could be a solution. Here's some sample code to undefer the message which copies the deferred message to a new message, Completes the deferred message and sends the new message back in the queue. This uses a TransactionScope to transactionally Complete and Resend the message to avoid the risk of losing the message:
    var messageId = "12434539828282";

    // Send.
    var msg = new BrokeredMessage {SessionId = "user1", MessageId = messageId };
    msg.Properties.Add("Language", "Dutch");
    queue.Send(msg);

    // Receive.
    var session = queue.AcceptMessageSession();
    msg = session.Receive();

    // Store the sequence number.
    var sequenceNumber = msg.SequenceNumber;

    // Defer.
    msg.Defer();

    // Change to true to test if the transaction worked.
    var shouldThrow = false;

    // Later processing of deferred message.
    msg = session.Receive(sequenceNumber);

    try
    {
        using (var ts = new TransactionScope())
        {
            // Create a new message.
            var undeferredMessage = new BrokeredMessage {SessionId = msg.SessionId, MessageId = msg.MessageId};
            foreach (var prop in msg.Properties)
                undeferredMessage.Properties.Add(prop);

            // Complete and send within the same transaction.
            msg.Complete();
            if (shouldThrow)
                throw new InvalidOperationException("Some error");
            queue.Send(undeferredMessage);

            // Complete the transaction.
            ts.Complete();
        }
    }
    catch (Exception ex)
    {
        msg.Abandon();
    }

    if (shouldThrow)
    {
        msg = session.Receive(sequenceNumber);
        Console.WriteLine(msg.MessageId + " should match: " + messageId);
    }
    else
    {
        try
        {
            msg = session.Receive(sequenceNumber);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Message not found, transaction worked OK.");
        }
    }

Note: here I'm simply taking a copy of the Properties. Keep into account that you might want to copy the Body and any other additional information.


text:
Q: How to convert to integer a char[4] of "hexadecimal" numbers [C/Linux] So I'm working with system calls in Linux. I'm using "lseek" to navigate through the file and "read" to read. I'm also using Midnight Commander to see the file in hexadecimal. The next 4 bytes I have to read are in little-endian , and look like this : "2A 00 00 00". But of course, the bytes can be something like "2A 5F B3 00". I have to convert those bytes to an integer. How do I approach this? My initial thought was to read them into a vector of 4 chars, and then to build my integer from there, but I don't know how. Any ideas?
Let me give you an example of what I've tried. I have the following bytes in file "44 00". I have to convert that into the value 68 (4 + 4*16):
char value[2];
read(fd, value, 2);
int i = (value[0] << 8) | value[1];

The variable i is 17480 insead of 68.
UPDATE: Nvm. I solved it. I mixed the indexes when I shift. It shoud've been value[1] << 8 ... | value[0]

A: Suppose you point into your buffer:
unsigned char *p = &buf[20];

and you want to see the next 4 bytes as an integer and assign them to your integer, then you can cast it:
int i;
i = *(int *)p;

You just said that p is now a pointer to an int, you de-referenced that pointer and assigned it to i.
However, this depends on the endianness of your platform. If your platform has a different endianness, you may first have to reverse-copy the bytes to a small buffer and then use this technique. For example:
unsigned char ibuf[4];
for (i=3; i>=0; i--) ibuf[i]= *p++;
i = *(int *)ibuf;

EDIT
The suggestions and comments of Andrew Henle and Bodo could give:
unsigned char *p = &buf[20];
int i, j;

unsigned char *pi= &(unsigned char)i;
for (j=3; j>=0; j--) *pi++= *p++;

// and the other endian:
int i, j;
unsigned char *pi= (&(unsigned char)i)+3;
for (j=3; j>=0; j--) *pi--= *p++;

A: General considerations
There seem to be several pieces to the question -- at least how to read the data, what data type to use to hold the intermediate result, and how to perform the conversion.  If indeed you are assuming that the on-file representation consists of the bytes of a 32-bit integer in little-endian order, with all bits significant, then I probably would not use a char[] as the intermediate, but rather a uint32_t or an int32_t.  If you know or assume that the endianness of the data is the same as the machine's native endianness, then you don't need any other.
Determining native endianness
If you need to compute the host machine's native endianness, then this will do it:
static const uint32_t test = 1;
_Bool host_is_little_endian = *(char *)&test;

It is worthwhile doing that, because it may well be the case that you don't need to do any conversion at all.
Reading the data
I would read the data into a uint32_t (or possibly an int32_t), not into a char array.  Possibly I would read it into an array of uint8_t.
uint32_t data;
int num_read = fread(&data, 4, 1, my_file);
if (num_read != 1) { /* ... handle error ... */ }

Converting the data
It is worthwhile knowing whether the on-file representation matches the host's endianness, because if it does, you don't need to do any transformation (that is, you're done at this point in that case).  If you do need to swap endianness, however, then you can use ntohl() or htonl():
if (!host_is_little_endian) {
    data = ntohl(data);
}

(This assumes that little- and big-endian are the only host byte orders you need to be concerned with.  Historically, there have been others, which is why the byte-reorder functions come in pairs, but you are extremely unlikely ever to see one of the others.)
Signed integers
If you need a signed instead of unsigned integer, then you can do the same, but use a union:
union {
    uint32_t unsigned;
    int32_t signed;
} data;

In all of the preceding, use data.unsigned in place of plain data, and at the end, read out the signed result from data.signed.


text:
Q: Capture video with overlay data (or watermark)? I'm creating a video recording app that record video via camera and show some overlay data info (such as current location, weather,... in other word, we can call these as watermark) at the same time.
Currently, i create an overlay layout on top of camera view to display the data info then everything look OK.
But, now is the main part, i want to capture all what we can see on screen (what we can record with camera + all overlay data) to a video. I did try some solutions from tutorials/guide by google such as record screen... but still not success.
Below are some more related questions can be found on Stack Overflow but didn't help me much:

*

*Recording video from camera, overlaying bitmaps, adding audio, saving to the device all in as3/AIR mobile

*render overlay graphics into camera video

*Recording videos with overlay images without using third party library on android

*Android - capture video with watermark
So, did you try to achieve this before? Or anyone can give some hint on how to do it?


text:
Q: Why do my trees shine bright white in the background? I am making a location in Unity, and all of my trees shine in the background, then return to their normal color when I get close enough to the,.

It is also not the skybox since when I disable that it still happens. How can I fix this? Why is this happening? Thanks in advance

A: Turns out you just need to change the Shader to Nature/Soft Occlusion Bark Shader to fix the problem. I found this on the Tree page, where it says:

Trees must use the Nature/Soft Occlusion Leaves and Nature/Soft Occlusion Bark shader. In order to use those shaders you also have to place the tree in a special folder that contains the name "Ambient-Occlusion". When you place a model in that folder and reimport it, Unity will calculate soft ambient occlusion specialized for trees. The "Nature/Soft Occlusion" shaders need this information. If you don't follow the naming conventions the tree will look weird with completely black parts.

Hope this helps!


text:
Q: LRU cache in C++
Possible Duplicate:
LRU cache design

I got this question in a programming interview. Feel free to think about how you might answer it.
How would you implement an LRU (least-recently-updated) cache in C++? Basically, the cache can hold up to N items. If a new item is inserted and the number of items in the cache is less than N, it's just inserted. But if a new item is inserted and the number of items in the cache is already N, the item that's least recently used should be removed from the cache.
Think about what running time it would take for each of your operation.

A: I would have member of cache element that stores last access time. When element is accessed (member function is called) then access time member is updated. When cache gets full then element with smallest access time would be erased.
Other option is to have cache elements in intrusive list. When something is accessed and is not in top of list it comes to top of list. When cache is full the bottom element of list is erased. More work on each access, but the victim is quicker to find.
The basic idea is not to have typical maps and lists for such tasks, these will fragment your memory. My algorithms keep the cache constantly at one place.


text:
Q: Translate input text field without pressing shift key I have two input fields here

<input type="text" class="form-control formRow--input js-input" name="product_name" id="product_name" placeholder="Product Name (ENG)" required>
<input type="text"  class="form-control formRow--input js-input" id="product_name_mal" name="product_name_mal" placeholder="Product Name (MAL)" >

When i type the product name in English in the first input field and press the shift key, it get translated to malayalam in the second input field.
This is my code:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script type="text/javascript">
google.load("elements", "1", {packages: "transliteration"});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
function OnLoad() {
    var options = {
        sourceLanguage:
        google.elements.transliteration.LanguageCode.ENGLISH,
        destinationLanguage:
        [google.elements.transliteration.LanguageCode.MALAYALAM],
        shortcutKey: 'ctrl+g',
        transliterationEnabled: true
    };

    var control = new google.elements.transliteration.TransliterationControl(options);
    control.makeTransliteratable(["product_name_mal"]);
    var keyVal = 32; // Space key
    $("#product_name").on('keydown', function(event) {
        if(event.keyCode === 32) {
            var engText = $("#product_name").val() + " ";
            var engTextArray = engText.split(" ");
            $("#product_name_mal").val($("#product_name_mal").val() + engTextArray[engTextArray.length-2]);

            document.getElementById("product_name_mal").focus();
            $("#product_name_mal").trigger ( {
                type: 'keypress', keyCode: keyVal, which: keyVal, charCode: keyVal
            } );
        }
    });

    $("#product_name_mal").bind ("keyup",  function (event) {
        setTimeout(function(){ $("#product_name").val($("#product_name").val() + " "); document.getElementById("product_name").focus()},0);
    });
}

google.setOnLoadCallback(OnLoad);
</script>

I want the second input field to get converted to Malayalam without pressing the shift key. I'm not much into JS. Can someone please help me do it?


text:
Q: Can Castle DynamicProxy be configured to not write to 'ref' args? I'm hitting an AccessViolationException when trying to use an interface proxy that is wrapping a third-party interface.  The exception is being thrown when the emitted code writes the invocation arg array back to the original arg for a 'ref' type arg.  Presumably this is because the third-party component has given an 'in' only parameter and it should not be written to.
So, I was wondering if DynamicProxy could be configured (or enhanced/hacked) to not write back some args?   Maybe by configuring a custom code emitter or something...
Or thinking outside of the box, would it work to apply an [InAttribute] at runtime to the third-party interface (assuming DynamicProxy can be configured to adhere to this attribute)?
Other, maybe useful, information:

*

*The third-party interface doesn't use the 'in' keyword or InAttribute on the offending 'ref' arg.

*I'm trying to use interface proxies created with a target

Example code:
    namespace third_party
    {
      public class IService
      {
        public int DoSomething(ref Guid guid);
      }
    }
    namespace domain_ns
    {
      public class ServiceImpl : IService
      {
        public int DoSomething(ref Guid guid) { return 0; }
      }

      public static void main(string[] args)
      {
        ...
        var proxy = proxyGen.CreateInterfaceProxyWithTarget(..., new ServiceImpl(), ... );
        third_party.AddService(proxy);

        // Indirectly causes proxy.DoSomething() to be called.
        // Throws an AccessViolationException :(
        third_party.Go();
      }
    }


text:
Q: Сохранение пользовательских настроек Есть окно на котором 4 функции программы которые можно настраивать (см. скриншот). Проблема заключается в сохранении всех этих настроек. Как лучше реализовать сохранение настроек?
Сейчас у меня 3 выбора:

*

*Сериализовывать и записывать в settings.json состояние объектов

*Реест

*БД

Но все способы мне кажутся проигрышными, файл можно удалить и тогда мне влетит от начальства, в реест лезть вообще не хочется (боюсь), а клепать миллион таблиц в бд под каждую специфическую настройку ну уж совсем не хочется


text:
Q: Post data security in PHP using prepared statement I am using a prepared statement for submitting the form using ajax. I tried the below code which is working. I need to know some securities. I checked on google and found some answers and made the below code.
I want to know my post data is correct? Do I need to FILTER_SANITIZE_STRING?
I entered
naren
 and naren's and submitted. Below is database output.
Database output

I got slash (/) and apostrophy in the last row.
Process.php
function register($conn){
    global $currentdate;
    $name=$conn->real_escape_string(trim($_POST['name']));
    $country=$conn->real_escape_string(trim($_POST['country']));
    $mobileno=$conn->real_escape_string(trim($_POST['mobileno']));
    $email=$conn->real_escape_string(trim($_POST['email']));

    if($name == "") {
        $errorMsg="Name field is required";
        $code="1";
    } else if($country == "") {
        $errorMsg="Country field is required";
        $code="2";
    } elseif ($mobileno=="") {
        $errorMsg="Mobile number is required";
        $code="3";
    } elseif (is_numeric(trim($mobileno))==false) {
        $errorMsg="Only contain a number";
        $code="3";
    } elseif (strlen($mobileno)<10) {
        $errorMsg="Contain minimun 10 number ex:9892555555";
         $code="3";
    } elseif (strlen($mobileno)>10) {
        $errorMsg="Contain maximum 10 number ex:9892555555";
        $code="3";
    } elseif ($email =="") {
        $errorMsg="Email filed is required";
        $code="4";
    } elseif (!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
        $errorMsg="Please enter valid email id";
        $code="4";
    } else {
        $query="INSERT INTO `register` (name, country, mobileno, email ,date_of_added) VALUES (?,?,?,?,?)";

        if($stmt = $conn->prepare($query)) {
            $stmt->bind_param("sisss",
                                $name,$country,$mobileno,
                                $email,$currentdate);
            $stmt->execute();
            $errorMsg="Data Inserted";
            $code="5";
            $_SESSION['thankyouSession'] = "true";
        }else{
            $code= "6";
            $errorMsg='Something is wrong';
        }

        $stmt->close();
        $conn->close();
    }
    $response['error']=$errorMsg;
    $response['error_no']=$code;
    echo json_encode($response);
 }

AJAX
$("#register").validate({
    rules: {
        name:{required:true,minlength:3},
        country:{required:true},
        mobileno:{required:true,minlength:10,maxlength:10,number: true},
        email:{required:true,email: true}
    },

    submitHandler: function (r) {
        $.ajax({
            url: base_url + "/process.php",
            type: "post",
            dataType: 'json',
            data: $('#register').serialize(),
            success: function (response) {
                if (response.error_no == '1') {
                    $('#name').html(response.error);
                } else if (response.error_no == '2') {
                    $('#country').html(response.error);
                } else if (response.error_no == '3') {
                    $('#mobileno').html(response.error);
                } else if (response.error_no == '4') {
                    $('#email').html(response.error);
                } else if (response.error_no == '6') {
                    $('#failed').html(response.error);
                }else{
                    window.location.href=base_url+"/thankyou.php";
                }
            }
        })
      }
    });

Database connection
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";
?>

A: As far I know you don't need real_escape_string with prepared statements.
For the POST varables you maybe better can use isset, like:
$name = isset($_POST['name']) ? $conn->real_escape_string(trim($_POST['name'])) : '';

To prevent undefined errors
$country needs to be an integer when i take a look at your query.
$country= isset($_POST['country']) ? (int)$_POST['country']) : 0;

And then in the elseif check if $country > 0
For email check you can also use:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// No valid email
}

And maybe after excecute check for affected rows te be sure the data is really inserted.
A sanitize function can be necessary for showing the database results in your html


text:
Q: How do I add a ContextMenuStrip to a ToolStripButton? I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton.  I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip.
Setting the ContextMenuStrip for the ToolStripComboBox is easy:
myToolStripComboBox.ComboBox.ContextMenuStrip = myContextMenu;

but there's no obvious equivalent for the ToolStripButton.  How do I add a ContextMenuStrip to a ToolStripButton?

A: What Jeff Yates has suggested should work.
However, another alternative is to create your own derived classes (MyToolSTripButton, MyToolStripTextBox ...etc) give these items a ContextMenuStrip property that you can set at design time, and have your derived classes detect the right mouse down, or whatever other events will trigger the display of the context menu.
This offloads any of the knowledge needed to only those items interested.
Below is one such example using ToolStripTextBox as the item.
public class MyTextBox : ToolStripTextBox
{
    ContextMenuStrip _contextMenuStrip;

    public ContextMenuStrip ContextMenuStrip
    {
        get { return _contextMenuStrip; }
        set { _contextMenuStrip = value; }
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            if (_contextMenuStrip !=null)
                _contextMenuStrip.Show(Parent.PointToScreen(e.Location));
        }
    }
}

A: You will need to set the context menu to the ToolStrip and then handle the Popup of the context menu or a related event and hit test which button the mouse is over to determine if you should show the ToolStrip's context menu and what it should contain.

A: It's because a ToolStripComboBox contains "System.Windows.Forms.ComboBox" control, but "ToolStripButton" does not contains "System.Windows.Forms.Control". Its special toolstrip item, which's button is maintained by toolstip.
You should use ContextMenu on toolstip or you can add dropdown to toolstripbutton item.

A: Good question.  You might be able to get access to the parent toolstrip (myToolStripButton.Parent or something similar) and attach the context-menu there.


text:
Q: Incorrect filename and funcName when importing a module with a class for logging I want to use a decorator for logging and created a special Loggerator class for this. However, when I import this class into another file, when logging, filename and funcName are specified from the Loggerator.py file.
I want to get these attributes from the file where I am using the decorator. How can I do it?
#Loggerator.py
import logging

class Loggerator:

    def __init__(self, func):
        logging.basicConfig(
            filename='example3.log',
            format='%(asctime)s.%(msecs)03d | %(levelname)-8s | %(name)s | %(filename)s.%(funcName)s(%(lineno)d) | %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S',
            level=logging.DEBUG,
            encoding='utf-8')
        self.func = func
        self.log = logging.getLogger(func.__name__)

    def __call__(self, *args, **kwargs):
        try:
            self.log.debug(f'call {self.func.__name__}')
            return self.func(*args, **kwargs)
        except Exception as err:
            self.log.exception(err)
            return err
        finally:
            self.log.debug(f'end of {self.func.__name__}')

Second file.
#test.py
from Loggerator import Loggerator

@Loggerator
def mult(a, b):
    return a * b

print(mult(3, 2))
print(mult('a', 'b'))


text:
Q: Jquery dynamic updation of the values In my application am using jquery.In that i am generating dynamic jquery dropdowns.say for example the id will be like "dropdown1", "dropdown2" etc.The values of these dropdowns are similar.when am selecting a value from a dropdown the same should be removed from all the other dropdowns.Can anyone give me a helpfull solution for this.

A: check this:
HTML:

First

Second

Third

Fourth

First

Second

Third

Fourth

JQUERY:
$('.ddm li').click(function() {
    var me = $(this);
    var txt = me.text();
    var id = me.parent().attr('id');
    $('.ddm').not('#' + id + '').each(function(i) {
    $('li:contains(' + txt + ')', this).remove();
    });
});


text:
Q: Nested React  element loses focus on typing I have:

*

*A component App with a child component Filter.

*The child needs to mutate state in the parent, which it is doing via an <input onChange={handler}>.

*The handler is a prop that is set on the child by the parent.

All good so far.
However, whenever the a key is pressed on the input, it loses focus. I presume it's being destroyed and re-rendered.
If I hoist the Filter component up a level into the App and drive it off the state in that, then everything works as you'd expect, but obviously I'd like to be able to nest the components and share the state at the top level.
I guess calling setState at this higher level is causing the whole thing to get re-rendered, but I thought the diffing algorithm would be clever enough to avoid replacing the  node in the Filter sub-component and thus avoid blurring the focus on the <input>.
What am I doing wrong / how can I fix this? Is there a better way to structure this?
Working JSBin here: http://jsbin.com/fexoyoqi/10/edit?html,js,output
var App = React.createClass({
  getInitialState: function() {
    return {
      items: ["Tom", "Dick", "Harry"],
      filterText: ''
    };
  },

  setFilterText: function (event) {
    this.setState({filterText: event.target.value});
  },

  render: function () {
    var filter = React.createClass({
      render: function () {
        return <input value={this.props.filterText} onChange={this.props.onChange}/>;
      }
    });

    var rows = this.state.items
      .filter(function (item) {
        return this.state.filterText == ''
          ? true
          : item.toLowerCase().indexOf(
              this.state.filterText.toLowerCase()) > -1;
      }.bind(this))
      .map(function(item) {
        return
{item}

      });

    return (

        Filter: <filter filterText={this.state.filterText}
          onChange={this.setFilterText}/>

          {rows}

    );
  }
});

React.renderComponent(<App />, document.body);

A: You're creating a new component class inside the render function.
Part of react's diffing algorithm looks at the components, and if it sees you rendered a different type component in one spot it says "the structure is probably significantly different, so I won't waste time diffing the children".  It throws out the node, and renders the new result to the DOM.
Move var filter = React.createClass... somewhere it's only executed once, and it'll work fine.


text:
Q: Prove that this operator is continuous Let $X,Y,Z$ be Banach spaces, and let $T:X\to Y$ be linear. Let $J:Y\to Z$ be linear, bounded and injective. If $JT:X\to Z$ is bounded, then T is bounded.

A: Hint: Use the closed graph theorem and show that $T$ is closed.


text:
Q: Listar em HTML table separado por categoria Estou em um desenvolvimento utilizando Python e Django e como IDE o pycharm.
Tenho uma lista vindo via Rest por mobile, com o nome de 'Atletas', e vem com as colunas "nome", "categoria", "tempo".
Gostaria de listar esses atletas em um HTML TABLE, porem separado por categoria e de ordem decrescente por TEMPO. (Cada categoria separado por um HTML TABLE)
Como fazer?

A: Quando você trás os dados do banco você deve setar como order_by desc. Ex:
Atletas.objects.filter(categorias='spfc').order_by('-tempo')

Trás todos os jogadores que está no time do spfc com o tempo decrescente

A: Você quer um output assim?

    nome
    categoria
    tempo

    João
    futebol
    20

    Maria
    basquete
    40

    José
    volei
    30

| nome  | categoria | tempo |
|-------|-----------|-------|
| João  | futebol   | 20    |
| Maria | basquete  | 40    |
| José  | volei     | 30    |

Mas precisamos de mais informações. Naõ dá pra responder sem tem um exemplo melhor do seu input e uma explicação do que você quer. Mas principalmente, temos que saber o que você já está fazendo, quais o erros encontrados, etc?


text:
Q: Proof that this relation about divisiblity is reflexive, transitive, ... I can't handle this relation-evidence.

$xRy \iff (\forall  t\in\mathbb{N}  \ \text{with $t$ a prime-number}: \ t\mid x \Rightarrow t\mid y)$
($t\mid x$ means $t$ divides $x$; $t\mid y$ means $t$ divides $y$)

Now i have to prove

*

*reflexivity: xRx t|x => t|x

*transitivity:∃z∈N: xRy ∧ yRz => xRz (t|x => t|y)∧(t|y => t|z) => (t|x => t|z)

*symmetry: xRy <=> yRx (t|x => t|y) <=> (t|y => t|x)

*asymmetry: xRy => not(yRx) (t|x => t|y) => not(t|y => t|x)

*antisymmetry: xRy ∧ yRx => x=y (t|x => t|y)∧(t|y => t|x) => (x=y)

I have already shown that it's reflexive.
I also tried to show the other ones, but my proof was either wrong oder not concrete enough.
I also don't know, when $(t\mid x \Rightarrow t\mid y)$ from $t\mid x$ follows $t\mid y$, how can $(t\mid y \Rightarrow t\mid x)$ from $t\mid y$ follows $t\mid x$, and what the implication => means here. And because I don't understand it, i also can't show any example that proofs falseness.
So I am thankful for any help I can get.

A: Hint $\, x R y \!\iff\! \cal P_x \subseteq \cal P_y\,$ for $\,\cal P_n = $ set of prime factors of $\,n,\,$ reduces it to easy properties of $ $  '$\subseteq$'
Remark $ $ Similarly many equivalence relations can be obtained via function pullback - see equivalence kernels (e.g. fibers, preimages, level sets / curves, etc).

A: HINT:
The $\Rightarrow$ means "implies" so $t\mid x\Rightarrow t\mid y$ means that whenever $x$ has $t$ as a factor so does $y$
For transitivity assume $xRy$ and $yRz$ and think as follows
$$
xRy\iff( t\mid x\Rightarrow \underline{t\mid y})
$$
also
$$
yRz\iff( \underline{t\mid y}\Rightarrow t\mid z).
$$
Now the underlined parts are the same so you have $t\mid x\Rightarrow t\mid z$ which is $xRz$ which we wanted to prove for transitivity.
You could try now the other ones
Hope this helped

A: I assume the relation is given over $\mathbb{N}$
In order to show reflexivity, that is, $x\mathrel{R}x$ (for every $x\in\mathbb{N}$), you need to show that, given any prime number $t$, if $t\mid x$, then $t\mid x$. This is obviously true.
Is the relation antisymmetric? No: you can see that $2\mathrel{R}4$ and $4\mathrel{R}2$, but $2\ne 4$.
Transitivity. Suppose $x\mathrel{R}y$ and $y\mathrel{R}z$; you want to prove that $x\mathrel{R}z$. So, suppose $t$ is a prime with $t\mid x$; then $t\mid y$, because of $x\mathrel{R}y$, and therefore $t\mid z$, because of $y\mathrel{R}z$. The condition that $x\mathrel{R}z$ has been verified.
Try the others.


text:
Q: Convert String to Datetime C# I have a string value which is a datetime : "20100825161500" and I want to convert this to a System Datetime. I have tried Convert.ToDateTime and DateTime.Parse and these do not work.

A: Try to use something like this
Datetime D = DateTime.ParseExact("20100825161500","yyyymmdd...",null)
here you have a link about how to make you "format" string

A: You can use DateTime.ParseExact to pass the format you need.
Here is an example:
var parsed = DateTime.ParseExact("20100825161500","yyyyMMddHHmmss", null);
Possible format values are listed at
Standard Date and Time Format Strings and Custom Date and Time Format Strings

A: Because this string hasn't a format recognized by these 2 functions.
DateTime.Parse and Convert.ToDateTime require your string to be correctly formatted :
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx
You will have to write your custom parser for this kind of conversion


text:
Q: Add strongly named keys (pfx) to all users on a server I am trying to configure a jenkins windows slave msbuild tasks on, but I am having issues with click once projects and its strongly named keys.
Depending on which account installs the PFX key, it depends on what the results and errors are.
BACKGROUND:
Projects (ProjectX and ProjectY)

*

*.net 4

*ClickOnce app

*uses a pfx key "ABC.pfx" to sign the assembly

Jenkins Windows Slave:

*

*the Jenkins windows service runs under the user account "jenkins@work.com"

*As jenkins creates a workspace for each project and branch, we copied the "ABC.pfx" file to c:\

ATTEMPTED RESOLUTION 1:
I remote desktop onto server with my user account:

*

*copy ABC.pfx onto the server at C:\

*Run command prompt as Administrator
cd c:\
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -d VS_KEY_123456789
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -i ABC.pfx VS_KEY_123456789

*Open normal command prompt and run (ClickOnce projects have build, then publish msbuild commands):
"C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" "c:/jenkins/workspace/project-x/ProjectX/ProjectX.sln" "/verbosity:normal" /p:configuration="release" /p:outdir="c:/jenkins/workspace/project-x/output/ProjectX/" "/target:Clean;Build" /maxcpucount
"C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" "c:/jenkins/workspace/project-x/ProjectX/ProjectX.sln" "/verbosity:normal" /p:configuration="release" /p:outdir="c:/jenkins/workspace/project-x/output/ProjectX/" "/target:Publish" /maxcpucount

*Both of the msbuid command run fine for me

*When run under the Jenkins account we get the error:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3326: Cannot import the following key file: ABC.pfx. The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user's personal certificate store. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3321: Importing key file "ABC.pfx" was canceled. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
ATTEMPTED RESOLUTION 2:
I remote desktop onto server with the Jenkins user account

*

*copy ABC.pfx onto the server at C:\

*Run command prompt as Administrator
cd c:\
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -d VS_KEY_123456789
"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\sn.exe" -i ABC.pfx VS_KEY_123456789

*Open normal command prompt and run:
"C:/Windows/Microsoft.NET/Framework/v4.0.30319/MSBuild.exe" "c:/jenkins/workspace/project-x/ProjectX/ProjectX.sln" "/verbosity:normal" /p:configuration="release" /p:outdir="c:/jenkins/workspace/project-x/output/ProjectX/" "/target:Clean;Build" /maxcpucount

*Jenkins user account gets the error:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3326: Cannot import the following key file: ABC.pfx. The key file may be password protected. To correct this, try to import the certificate again or import the certificate manually into the current user's personal certificate store. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2482,5): error MSB3321: Importing key file "ABC.pfx" was canceled. [c:\jenkins\workspace\project-x\ProjectX\ProjectX.csproj]

*I also get a build error
Does anyone have any idea how to get the Jenkins user account to acknowledge the PFX key?
Thanks for any help,
Sandra

A: Finally I found the issue and solution to this, and thought I'd put it up if someone else was having a similar issue.
We cloned the build servers that the strongly named keys were on. After they were cloned all the keys and Click Once apps broke. No matter what we did we couldn't remove the old keys and reinstall them.
After building a new build server up from scratch and manually installing the PFX keys on the new server, everything worked again.
So for some reason, cloning servers does not clone pfx keys properly.


text:
Q: Server Root and MapPath() I have a file structure set up like this:
ServerRoot
    applicationRoot
        filePage.aspx
    files
        chart.png

My application page called filePage.aspx uses another app to custom build charts.  I need them saved in files folder.  This is how our client's production server is set up and I cannot change this.
I do a _page.Server.MapPath("/files") but it gives me a InvalidOperationException and states Failed to map the path '/files'.
UPDATE:
So it has to be set up this way MapPath("/").  My local asp.net server can't handle the MapPath that way, but our IIS development box has no problem with it and it works fine.  Interesting.
How do I get it to save to files?

A: I believe it's a security violation to go outside the directory structure of the virtual directory in asp.net 2.0 and up. You'll need to make a virtual directory to the directory and use that.

A: Use
Server.MapPath("~/files")

The ~ represents the root of the web application so the folder returned will be correct no matter which subdirectory you are in.

A: _page.Server.MapPath() will attempt to map from the root of the application (NOT the root of the server).
Try _page.Server.MapPath("../files").
EDIT
You may run into security issues when trying to map outside of your application root.  If that is the case, you can do something like this:
Server.MapPath("~").Substring(0, Server.MapPath("~").IndexOf(VirtualPathUtility.ToAbsolute("~").Replace("/", "\"))) + "\files"

This looks rather complex, but essentially says "map my application, then remove the application root from the end and add '\files' instead".

A: Try
_page.Server.MapPath("files")


text:
Q: 2D array prints unstable output My test program here is supposed to take a 1D array and sort it into a 2D array.
The file is 3000 common words from 'a' to 'z'. The setup seems correct and I even get an output that starts out correct. However, after words starting with 'b' I get nothing but nulls.
public static void main(String[] args) throws FileNotFoundException {
    int listSize = 0;

    File file = new File("3000-Common-Words.txt");

    Initialize a = new Initialize();
    String[] oneArray = a.Initialization(file);

    for (int i = 0; i < 26; i++) {

        int sizeCheck = 0;

        for (int j = 0; j < 3000; j++) {

            if (oneArray[j].charAt(0) == (char) (i + 97)) {
                sizeCheck++;
            }
            if (sizeCheck > listSize) {
                listSize = sizeCheck;
            }
        }
    }

    String[][] twoArray = new String[26][listSize];

    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < listSize; j++) {

            if (oneArray[j].charAt(0)==(char)(i+97)){
                twoArray[i][j]=oneArray[j];
            }
        }
    }

    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < listSize; j++) {
            System.out.println(twoArray[i][j]);
        }
    }
}

The initialisation of the first array is correct (I've checked the output).
I see why my array stops before 'c'. Its because I've got oneArray[j] but I'm still stuck on how to fill the array...
Any help is appreciated!

A: sizeCheck will be the number of words that start with the letter.
listSize will be the maximum of those.
However in your second loop
for (int j = 0; j < listSize; j++) {

        if (oneArray[j].charAt(0)==(char)(i+97)){
            twoArray[i][j]=oneArray[j];
        }
    }

you always only "scan" the first "listSize" amount of words in the first array, which actually is 3000 words long. So don't use j for iterating thru "oneArray", instead use another variable for this.

A: The logic to populate the array is slightly flawed.
You have correctly worked out the minimum dimension for the sparse matrix.
It will be 26 by highest number of words in any letter of the alphabet.
However, you have not chosen independent iteration counters for reading the word list and populating the array.
Here is a working solution:
public class WordSort {

    public static void main(String[] args) {
        int listSize = 0;

        String[] oneArray = {"a1","b1","c1","d1","e1","f1","g1","h1","i1","j1","k1","l1","m1","n1","o1","p1","q1","r1","s1","t1","u1","v1","w1","x1","y1","z1","a2","b2","d2","g2","n2","l2","z2","v2","g3","h3","p0","h9","r5","t3","o9","l7","h6","f5","q5",};

        for (int i = 0; i < 26; i++) {

            int sizeCheck = 0;

            for (int j = 0; j < oneArray.length; j++) {

                if (oneArray[j].charAt(0) == (char) (i + 97)) {
                    sizeCheck++;
                }
                if (sizeCheck > listSize) {
                    listSize = sizeCheck;
                }
            }
        }

        String[][] twoArray = new String[26][listSize];

        for (int i = 0; i < 26; i++) {
            int k = 0;
            for (int j = 0; j < oneArray.length; j++) {
                if (oneArray[j].charAt(0)==(char)(i+97)){
                    twoArray[i][k++]=oneArray[j];
                }
            }
        }

        for (int i = 0; i < 26; i++) {
            for (int j = 0; j < listSize; j++) {
                System.out.println(twoArray[i][j]);
            }
        }
    }
}


text:
Q: TFS -Location of build agent I am working on a project with two other people.
We are using TFS 2015 for source control and would also like to use TFS to build our project.
I am pretty new to TFS but I think I'm starting to understand the roles that build agents and build controllers play. I am not sure, however, where to install the build agent. Is it ok to install the build agent on my own development machine or is that considered bad practice? Are there any obvious drawbacks to install the build agent on my own machine (besides that building will be dependent on whether my machine is running or not)?

A: You can, but shouldn't, install build infrastructure on your development machine -- the idea of a build server is to have a consistent machine (or set of machines) with all of the necessary requirements to build your software. Consistency is the key here.
Developer machines (at least, if they're anything like mine :)) are a mess of different tools and configuration settings, based on personal preference and necessities. They are typically not consistent from person to person or from day to day.
It's also worth noting that XAML build controllers are considered deprecated in TFS 2015. They still work, you can still use them, but the XAML build system has been supplanted by the new build, which is agent-only.


text:
Q: A question about the additive group of the $p$-adic integers Let $J_p$ be the additive group of the $p$-adic integers. I know that it is torsion-free. I'm not pretty confortable with $p$-adic.
Is it possible to find a direct sum of infinitely many cyclic subgroup in $J_p$? (essentially I'm asking if they have finite special rank or not).
EDIT
I find out on Wikipedia that they effectively have infinite rank. But I still cannot find that direct sum.

A: Complete rewrite:
For this, you need to look at the fraction field $\Bbb Q_p$ of the $p$-adic integer ring $\Bbb Z_p$. It's a vector-space over $\Bbb Q$, and according to a well-known theorem depending on the Axiom of Choice, there's a $\Bbb Q$-basis of this vector space. Since $\Bbb Q_p$ is uncountable, the basis must be uncountable as well. For each $\beta$ in the basis, there's a rational number $\lambda_\beta$ such that $\lambda_\beta\beta\in\Bbb Z_p$. Now take the (uncountably-indexed) direct sum
$\bigoplus_\beta\lambda_\beta\beta\,\Bbb Z$. There you are.


text:
Q: Ehcache with Spring with CacheDecoratorFactory not configured I am implementing ehcache with Spring project but not success.
Here is my setting in applicationContext.xml:
<ehcache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="/META-INF/spring/ehcache.xml" />
</bean>

Here is my setting in ehcache.xml:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <diskStore path="java.io.tmpdir" />
    <defaultCache eternal="true" maxElementsInMemory="100" overflowToDisk="false" />
    <cache name="listTop" maxElementsInMemory="10" eternal="true" overflowToDisk="false" />

</ehcache>

Here is my implementation class:
@Cacheable(cacheName="listTop")
public void listTop(News news, String regionCode, Integer count, Integer categoryId, String listType){
//code here//
}

I got the following message that seems the cache is not configured:
1827 DEBUG net.sf.ehcache.config.BeanHandler  - Ignoring ehcache attribute xmlns:xsi
1827 DEBUG net.sf.ehcache.config.BeanHandler  - Ignoring ehcache attribute xsi:noNamespaceSchemaLocation
1828 DEBUG net.sf.ehcache.config.DiskStoreConfiguration  - Disk Store Path: C:\Users\TOMMY~1.LOC\AppData\Local\Temp\
1847 DEBUG net.sf.ehcache.util.PropertyUtil  - propertiesString is null.
1860 DEBUG net.sf.ehcache.config.ConfigurationHelper  - No CacheManagerEventListenerFactory class specified. Skipping...
1918 DEBUG net.sf.ehcache.Cache  - No BootstrapCacheLoaderFactory class specified. Skipping...
1918 DEBUG net.sf.ehcache.Cache  - CacheWriter factory not configured. Skipping...
1918 DEBUG net.sf.ehcache.config.ConfigurationHelper  - No CacheExceptionHandlerFactory class specified. Skipping...
1932 DEBUG net.sf.ehcache.Cache  - No BootstrapCacheLoaderFactory class specified. Skipping...
1932 DEBUG net.sf.ehcache.Cache  - CacheWriter factory not configured. Skipping...
1932 DEBUG net.sf.ehcache.config.ConfigurationHelper  - No CacheExceptionHandlerFactory class specified. Skipping...
1954 DEBUG net.sf.ehcache.store.MemoryStore  - Initialized net.sf.ehcache.store.MemoryStore for listTop
1991 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: LOCAL_OFFHEAP_SIZE
1993 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: LOCAL_OFFHEAP_SIZE_BYTES
1994 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: LOCAL_DISK_SIZE
1994 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: LOCAL_DISK_SIZE_BYTES
1994 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: WRITER_QUEUE_LENGTH
1994 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: REMOTE_SIZE
1995 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Pass-Through Statistic: LAST_REJOIN_TIMESTAMP
2012 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: OFFHEAP_GET
2013 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: OFFHEAP_PUT
2014 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: OFFHEAP_REMOVE
2014 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: DISK_GET
2014 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: DISK_PUT
2015 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: DISK_REMOVE
2015 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: XA_COMMIT
2015 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: XA_ROLLBACK
2016 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: XA_RECOVERY
2017 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: CLUSTER_EVENT
2017 DEBUG net.sf.ehcache.statistics.extended.ExtendedStatisticsImpl  - Mocking Operation Statistic: NONSTOP
2024 DEBUG net.sf.ehcache.Cache  - Initialised cache: listTop
2024 DEBUG net.sf.ehcache.config.ConfigurationHelper  - CacheDecoratorFactory not configured. Skipping for 'listTop'.
2024 DEBUG net.sf.ehcache.config.ConfigurationHelper  - CacheDecoratorFactory not configured for defaultCache. Skipping for 'listTop'.

Is there anyone know and help? Many thanks.

A: You need to tell EhCache to apply the decorator to the defined cache like this (and you have to implement MyCacheDecoratorFactory to do what you want):
<cache name="listTop" maxElementsInMemory="10" eternal="true" overflowToDisk="false" ><cacheDecoratorFactory class="com.test.MyCacheDecoratorFactory", properties="blah=true,someValue=2000" /></cache>

A: Cache not working has nothing to do with CacheDecoratorFactory.
These are debug logs telling you that you're not using a CacheDecoratorFactory.
CacheDecorator are a way for the developer to add functionalities to the cache. More on Ehcache 2.8 documentation.
Note that the CacheDecoratorFactory class disappeared in 3.0


text:
Q: CSS: glowing text with glow very wide and high I'm investigating since some days box-shadow and text-shadow. I'm trying to gain the following effect. I want a glow come out from the text of the <a> once hovered. Simple, this should be easy as I explored using text-shadow. Ok, but it works with small glows, I mean, once the glow is bigger you just cannot see the glow due to its high blur. There has to be a solution for this. An image will explain better than 100 words.
This is what I want to gain:
LINK:

HOVER:

This is the code I've used for
#projectBox a:LINK{
    background-image: url('../_img/showcase/projectTabs/link.png');
}

#projectBox a:HOVER{
    background-image: url('../_img/showcase/projectTabs/link.png');
    color:#fa0000;
    text-shadow: 0 0 80px white;
}

I know I can use background image again for the hover but I want to avoid this. The problem is that if you add more blur it doesnt appear anymore, as its too blur. the other two properties dont help too much, as I want the glow to begin from the middle.
Lets work out this together and see how we can do with CSS a wide and high glow effect.

A: You can add multiple text-shadows:
text-shadow:
-3px 0px 10px #FFF,
3px 0px 10px #FFF,
0px 0px 10px #FFF,
-3px -3px 10px #FFF,
3px -3px 10px #FFF,
0px -3px 10px #FFF,
-3px 3px 10px #FFF,
3px 3px 10px #FFF,
0px 3px 10px #FFF;

This would give you a wider, fuller glow, as there are 9 separate shadows surrounding the text. Adjust the values to get the intensity you're looking for.
(the values are a random guess - untested as I'm on my phone) :)
http://jsfiddle.net/pzMmC/ -

A: You can overlay concentric shadows to multiply the effect:
a:hover {
    text-shadow: 0 0 80px white,
                 0 0 70px white,
                 0 0 60px white,
                 0 0 50px white,
                 0 0 40px white,
                 0 0 30px white;
}

I've written a test: http://jsfiddle.net/simbirsk/DnHKk/

A: Why not use CSS3's gradients?
Take a look at this fiddle.
You can generate your own gradients here or here.