It does not work when installed as "subsite"

Question: I tried to install Drupal 8.03 on a windows 7 64 bit server, with MySQL, Apache and PHP 7.03, using the default install procedure / script.
Drupal is only one of the applications on the website and that is probably different from what Drupal 8 seems to expect.
The website is like https:/www.mysite.nl and overall root folder is x:\myroot\homepage. Drupal, however, is installed in x:\myroot\homepage\drupal and it is supposed to be accessible via https:/www.mysite.nl/drupal.
Back to the installation. To a "certain" extend that seems(!) to work. That will say the install script runs and ends. But than I want to access Drupal and that does not work. I can not access any thing "page missing". Both the base folder and the base url is not what Drupal expects (e.g. Drupal generates https:\www.mysite.nl\xyz where that should be https:\www.mysite.nl\drupal\xyz and I can not change that (at least not from the UI which is not accessible, assuming there is a setting for that).
So drupal seems is completely lost, does not understand what its base url is and does not understand where the files are (both at least the url should be a question during installation!!!!!).
By the way I never really used other drupal versions, but from a last year test install my impression is that this problem did not exist in drupal 7.
I do not know how to solve this. Hope you can help and perhaps initiate a few corrections/extensions in Drupal 8.
Answer: Look for this code in the .htaccess file in the root of the Drupal site's filesystem:
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

and remove the '#' from the beginning of the RewriteBase line. That should tell Apache/Drupal how to properly rewrite URLs for your case.
Comment: Thanks for your advice.

I tried your suggestion by activate the line RewriteBase /drupal in the htaccess file. It was not sufficient to make things working.

The url's seems to be OK now, but Drupal is still looking for the files at the wrong place I assume (http error 500).

Apart from that I have some mixed feelings. IMHO we are using apache functionality to compensate for Drupal short comings. Perhaps I get it working this way, but it is IMHO more a workaround that the correct solution.

Sincerely,

Louis
Comment: @Louis If you don't mind my saying, you've slightly misunderstood what's happening - needing to modify .htaccess for this purpose is actually a requirement of Apache, not Drupal. Any other PHP application that uses rewrite rules would have the same requirement, it's just how it works. The 500 error means either an error in Apache (commonly caused by invalid syntax in .htaccess), or a fatal PHP error; it's not a 404 so probably doesn't relate to a file not found. Check the server logs, they should contain the exact reason for the error, and you can go from there
Comment: um,
Not an expert in this regard, but using rewrites where the program could generate the correct url ... I do not know.
In the php error log I found:
Uncaught PHP Exception RuntimeException: "GuzzleHttp requires cURL, the allow_url_fopen ini setting, or a custom HTTP handler." at \Drupal\vendor\guzzlehttp\guzzle\src\functions.php line 116

it is true I do forbid that.
from the php.ini
; Whether to allow the treatment of URLs (like http:// or ftp://) as files.
;ORG allow_url_fopen = On
;20151002 on advise drupal closed for security reasons
allow_url_fopen = Off
Comment: @Louis Many CMS's that operate on Apache, including both WordPress and Joomla!, utilize rewrite rules, as that's generally the cleanest way of serving all pages on the site from an index.php at the root of the website, while still having user- and SEO-friendly URLs. Your last comment was a bit garbled, so I'm not sure I understood, but it looks like you're now seeing a different problem, related to a missing library or PHP setting?
Comment: Hello, I just tested if Drupal is running when accepting allow_url_open. The answer is, yes Drupal runs now. However, ...... I do agree with the previous Drupal advice (!), to block allow_url_open for security reasons ... So where drupal7 did not need that unsecure option activated,  drupal8 do need it. At least at this moment.
Comment: Hello, I just tested if Drupal is running when accepting allow_url_open. The answer is, yes Drupal runs now. However, ...... I do agree with the previous Drupal advice (!), to block allow_url_open for security reasons ... So where drupal7 did not need that unsecure option activated,  drupal8 do need it. At least at this moment. To comment on rewrite rules, I do have wordpress running as a subsite without creating a rewrite rule for that .... And even if that is the way to go (I still have doubts), than the setup script should take care ... IMHO
Comment: I was to early, still not working the rewrite rule works partly. E.g. logins are not using the correct url (still main side url and not mainsite/drupal) and do not work.
Comment: I think I made some little progress into the direction of a solution, however the site is not yet running at all.

First thing I did is to add RewriteBase / e.g.  in the drupal .htacess file (as described in that file and above). However that is not enough. Second issue is that you *never* reach the logon page / or startpage when you enter the expected url "/drupal. There should be an automatic redirect to the startpage, but that is not there / does not work. If you enter /drupal/user/login then drupal shows the login screen and you can enter Drupal.
Comment: But that is a workaround at best.

I tried to do that automatically by using "rewritebase /drupal" followed by the line rewriterule ^ user/login [L,R]. and yep you are redirected to the correct url (it seems), but it does NOT work (apache "Hmm, we can't reach this page"). That apart form the fact that you probably just want to visit the site (and not to login).

What however still not working. Hoping for more help :(

Sincerely, Louis (sorry I did post my comment in two parts, I did need more characters than seems to be allowed :( )


Como recuperar Actividade, em vez de criar nova, quando clicar na notificação?

Question: Na minha app quando actividade vai para o estado onPause faço disparar as notificações dela através do NotificationManager.
Pretendia que ela pudesse ser recuperada para o estado onResume caso fosse dado um click na notificação.
Através deste código consigo abrir uma nova actividade, mas o que eu pretendia era antes recuperar a actividade que está no estado onPause:
NotificationManager nm = (NotificationManager)  getSystemService(NOTIFICATION_SERVICE);
PendingIntent p = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MainActivity.class), 0);

NotificationCompat.Builder builder = new NotificationCompat.Builder(MainActivity.this);
builder.setTicker("Tiker Valor: "+Integer.toString(i));
builder.setContentTitle("Titulo Valor: "+Integer.toString(i));
builder.setContentText("Descrição");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(p);

Notification n = builder.build();
n.flags = Notification.FLAG_AUTO_CANCEL;// Retira a notificação quando esta for clicada
nm.notify(R.drawable.ic_launcher, n);

Answer: No AndroidManifest.xml, na declaração da actividade, coloque:
<activity
    android:name="........
    ............
    android:launchMode="singleTop"
    ......
    ......>
</activity>

Ou set as flags Intent.FLAG_ACTIVITY_CLEAR_TOP e Intent.FLAG_ACTIVITY_SINGLE_TOP no Intent usado para lançar a Activity:
...
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent p = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
...

Comment: ramaral, funcionou. Obrigado. Abraço.


Verifique se o controlador tem um construtor público sem parâmetros

Question: Alguém me ajuda, estou criando um projeto e na parte de injeção de dependência estou tendo o seguinte erro quando faço uma requisição do Postman na minha Api: Ocorreu um erro ao tentar criar um controlador do tipo 'PessoaController'. Verifique se o controlador tem um construtor público sem parâmetros.
Minha classe do simple injector:
using MonitoramentoEscolar.Domain.Interfaces.Entities;
using MonitoramentoEscolar.Domain.Entities;
using MonitoramentoEscolar.Domain.Interfaces;
using MonitoramentoEscolar.Context;
using MonitoramentoEscolar.Infrastructure.Repositories;
using SimpleInjector;

namespace MonitoramentoEscolar.Api.App_Start {
    public class SimpleInjectorRegistrar {
        public static Container Registrar() {
            var container = new Container();
            container.RegisterSingleton<MonitoramentoEscolarDbContext>();
            container.Register<IPessoaEntity, PessoaEntity>();
            container.Register<IPessoaTipoEntity, PessoaTipoEntity>();
            container.Register<IPessoaRepository, PessoaRepository>();
            container.Verify();
            return container;
        }
    }
}

Meu controller, se eu criar um construtor vazio sem parâmetros ele inicializa somente o construtor vazio e quando chega no Endpoint da erro de NullReference.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.UI.WebControls;
namespace MonitoramentoEscolar.Api.Controllers {

    public class PessoaController : ApiController {

        public readonly IPessoaRepository pessoaRepository;
        public readonly IPessoaTipoRepository pessoaTipoRepository;

        public PessoaController(IPessoaRepository pessoaRepository, IPessoaTipoRepository pessoaTipoRepository) {
            this.pessoaRepository = pessoaRepository;
            this.pessoaTipoRepository = pessoaTipoRepository;
        }
        public PessoaController() {

        }
        [HttpGet]
        [Route("api/Pessoa/GetAll")]
        public IHttpActionResult GetAll() {
            var pessoas = pessoaRepository.GetAll().ToList();
            if (pessoas == null)
                return BadRequest("Nenhum dado foi encontrado");
            return Content(HttpStatusCode.OK, pessoas);
        }

A classe SimpleInjectorRegistrar:
using MonitoramentoEscolar.Api.App_Start;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MonitoramentoEscolar.Api {
    public class WebApiApplication : HttpApplication {
        protected void Application_Start() {
            DependencyResolver.SetResolver(SimpleInjectorRegistrar.Registrar());
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Alguém me ajuda e se possível me explica o pq estou passando por isso. Obrigado.
Comment: Onde a classe SimpleInjectorRegistrar é chamada? Qual o framework? .Net Core? .Net Full Framework?
Comment: As suas entidades possuem um construtor sem parâmetros?
Answer: Pode ser uma das seguintes opcoes:

O seu service faz uso de outras interfaces que nao foram injetadas
O seu service nao tem construtor

Mais:

o seu metodo de injection esta errado DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
https://simpleinjector.readthedocs.io/en/latest/mvcintegration.html

e por ultimo vc nao precisa criar construtor vazio em um controller
 public PessoaController() {

        }

Comment: Muito obrigado, eu consegui resolver o problema, faltou eu adicionar no Nuget o SimpleInjector WebApi, registrar uma interface que faltava e passei a receber no metodo Registrar um HttpConfiguration, ficou assim: public static void Registrar(HttpConfiguration config) e utilizei mais essas duas linhas de codigo:  container.RegisterWebApiControllers(config); depois do Verify(); usei está tb:
GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);


Laravel - fazer DB::table() sem usar o Join

Question: Estou mexendo com laravel e estou aprendendo orientação a objeto e queria fazer um select sem usar o join porem como e orientado a objeto e sei pouco n estou conseguindo.
como sou acostumado a usar:
<code>$results = DB::select("SELECT u.foto, u.Ninck,o.Idsala,p.Aceitou, u.Id FROM Onsalas o , Usuarios u, Partidas p WHERE (o.Idusuario=u.Id) AND (u.Id != $Id) AND(o.Idsala = $sala) AND ((p.IdDesafiado = $Idop)  OR (p.IdDesafiante = $Idop))  ");
</code>
tentei fazer de farias formas porem todas sem sucesso
algumas formas que tentei:
<code> $results =  DB::table(' \'Onsalas\' , \'Usuarios\' ')
                        ->select('Onsala.Id')->get();

 $results =  DB::table('Onsalas' , 'Usuarios')
                        ->select('Onsala.Id')->get();

$results =  DB::table('Onsalas')->table( 'Usuarios')
                        ->select('Onsala.Id')->get();
</code>
Answer: Olá
Poderias usar isto, contudo deverias dar uma olhadela ao eloquent.
https://laravel.com/docs/5.6/eloquent
<code>$users = DB::table('Onsalas')
    ->join('Usuarios', 'Onsalas.Idusuario', '=', 'Usuarios.Id')
    ->join('Partidas', 'Partidas.Idusuario', '=', 'Usuarios.Id')
    ->select('Usuarios.foto', 'Usuarios.Ninck', 'Onsalas.Idsala', 'Partidas.Aceitou', 'Usuarios.Id')
    ->where('Usuarios.Id', '=', $Id)
    ->where('Onsalas.Idsala', '=', $sala)
    ->where(function ($query) use ($Idop) {
        $query->where('Partidas.IdDesafiado', '=', $Idop)
            ->orWhere('Partidas.IdDesafiante', '=', $Idop)
    })
    ->get();
</code>
Atualização não usando joins:
<code>$resultados = DB::select( DB::raw("SELECT u.foto, u.Ninck,o.Idsala,p.Aceitou, u.Id FROM Onsalas o , Usuarios u, Partidas p WHERE (o.Idusuario=u.Id) AND (u.Id != $Id) AND(o.Idsala = $sala) AND ((p.IdDesafiado = $Idop)  OR (p.IdDesafiante = $Idop))"));
</code>
Comment: ai vc usou o Join estava querendo fazer sem usar o Join


Java 8 Exception: com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer has no default (no arg) constructor

Question: I have a model class that has a field:
 @JsonDeserialize(using = InstantDeserializer.class)
 @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
 private OffsetDateTime offsetDt;

When a request of this model is sent to the server, my controller throws an exception:
Caused by: java.lang.IllegalArgumentException:
Class com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer
has no default (no arg) constructor

The pom.xml has the dependency of version 2.8.11:
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

I understand that it is caused by @JsonDeserialize requiring no-arg constructor, but is there a workaround?
Comment: Look at this answer https://stackoverflow.com/a/45215515/4727666, you need a class with a constructor that takes no arguments, so you can extend InstantDeserializer to create your own.
Comment: For the arguments, take a look at this https://github.com/FasterXML/jackson-datatype-jsr310/blob/master/src/main/java/com/fasterxml/jackson/datatype/jsr310/deser/InstantDeserializer.java#L53
Comment: `InstantDeserializer.class` is custom deserializer class?, if i believe in that class you may declared some arg constructor without no-arg constructor
Comment: @Deadpool no, it is not a custom class..   com.fasterxml.jackson.datatype.jsr310.deser
Comment: what does your POM look like?
Comment: @DarrenForsythe  Just updated above with the dependency.  Were you looking for something else in the pom.xml?
Comment: Have you tried `@JsonDeserialize(using = InstantDeserializer.INSTANT)` instead?
Comment: @JulioDanielReyes   I just tried and I got a compiler error -- Type mismatch: cannot convert from InstantDeserializer to Class
Comment: @JulioDanielReyes  Thank you very much.  I will take a look
Comment: @JulioDanielReyes  still doesn't work after adding the constructor.
Answer: The error says that you need a class with no arg constructor, so you could extend from InstantDeserializer. (Take as example the code in InstantDeserializer for the arguments of super())
public class DefaultInstantDeserializer extends InstantDeserializer<OffsetDateTime> {
    public DefaultInstantDeserializer() {
        super(OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
                OffsetDateTime::from,
                a -> OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId),
                a -> OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId),
                (d, z) -> d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())),
                true);
    }
}

Then you can use it:
@JsonDeserialize(using = DefaultInstantDeserializer.class)


Problem with trailing slash and global redirect

Question: I have a site with some languages, with language prefix enabled.
I wanted the homepage url will be with trailing slash (i.e /en/), so i installed the trailing slash module.
I also want that users who entered my site without language prefix will redirect to the url with the prefix (i.e www.mysite.com -> www.mysite.com/en/), so i istalled th global redirect module, which works well without the trailing slash module.
When the two modules enabled, the redirection in the home page not working. Does someone has solution for this?
Answer: if you are looking to redirect your users site or visitors to the right language you can do this without global redirect module
to do that

install [Localization update][1] , [variable][2] , [Internationalization],
after install modules active Locale , Localization update , Internationalization , Variable
go to Configuration > Languages > detection and selection
the 1st option URL u can choose between (Path prefix or domain)
the 2nd option is Browser and here u can Determine the language from the browser's language settings. if your browser's visitor is English he will go to English site ....
the 3rd option is User in this option the site Follow the user's language preference.

that's all
Comment: is there an option that the default prefix will be with trailing slash: www.mysite.com/en/ instead of www.mysite.com/en ?
Comment: i hope that i understand ur question
from  Configuration > Regional and language > Languages >
here u can see your installed languages and u can press edit
and choose your Path prefix language code your site will be like this http://www.example.com/en


403 error - unable to login into admin

Question: Recently I created two pages for http 403 and 404 and assigned them so that on error those two will be shown.
But today when I tried to login to my admin in my site: http://www.indiacustomercare.com/admin
it is giving error "Error 403 - Permission Denied".
The message:"Unfortunately the page you are looking for is not accessible by you." is from the page I had assigned for http 403.
Looks like I did some silly mistake, my other two D6 sites have no problem logging in.
How do I login into admin again?
Comment: Maybe you have also made some changes to the .htaccess??Can you show that?
Comment: What method did you use to assign/setup the 404/403 pages?
Comment: I did not change .htaccess. What I did was to create two nodes with 404 and 403 error messages and assigned them in admin/settings/error-reporting. Also please don't forget to click the site admin url and see the message.
Answer: this may seem a silly suggestion, but have you tried going to /user rather then /admin the former being the login page, the latter being the admin pages once logged in?
Comment: very nice! It worked! Nice silly suggestion!

403 error - unable to login into admin


How to convert *elbv2.DescribeLoadBalancersOutput to an JSON in goLang to perform data parsing

Question: I have been trying to work with AWS Go SDK Version 2. I am getting an where I want to convert the response I got from DescribeLoadBalancer() function into a JSON, so that I can parse it and perform further action but when I try to follow how to parse the JSON in go describe here https://blog.alexellis.io/golang-json-api-client/. I get an error in the compiler that I can't convert *elbv2.DescribeLoadBalancersOutput into []byte. I tried different approaches i.e trying to convert *elbv2.DescribeLoadBalancersOutput into string etc but I always get the same error i.e cannot convert  *elbv2.DescribeLoadBalancersOutput into the specified type. hence want to understand what would be the best to perform the required action. Here's my code.
package main

import (
    "encoding/gob"
    "fmt"
    "reflect"

    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/awserr"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/aws/aws-sdk-go/service/elbv2"
)

type LoadBalancerARN struct {
    loadBalancerARN string
}

func main() {
    session, error := session.NewSession(&aws.Config{
        Region: aws.String("eu-central-1"),
    })
    if error != nil {
        fmt.Printf("Cannot create a session, %v", error)
    }

    service := elbv2.New(session)

    input := &elbv2.DescribeLoadBalancersInput{}

    getLoadBalancersJson, error := service.DescribeLoadBalancers(input)
    if error != nil {
        if aerr, ok := error.(awserr.Error); ok {
            switch aerr.Code() {
            case elbv2.ErrCodeLoadBalancerNotFoundException:
                fmt.Println(elbv2.ErrCodeLoadBalancerNotFoundException, aerr.Error())
            default:
                fmt.Println(aerr.Error())
            }
        } else {
            fmt.Println(error.Error())
        }
        return
    }

    encodinglbJson := gob.NewEncoder(getLoadBalancersJson)

    //var arn LoadBalancerARN

    fmt.Println(getLoadBalancersJson)
    fmt.Println(reflect.TypeOf(getLoadBalancersJson))
}

Answer: So, I have figured the above out, best way to do the above is, AWS provide a LoadBalancer function which convert the *elbv2.DescribeLoadBalancersOutput into an object of type *[]elbv2.LoadBalancer and then you can convert that object into the byte array using json.Marshal function and from there you can perform the parsing as needed.
Here's code
type LoadBalancerJSONStructure struct {
    LoadBalancerArn       string
    DNSName               string
    CanonicalHostedZoneId string
    CreatedTime           string
    LoadBalancerName      string
    Scheme                string
    VpcId                 string
    Type                  string
    IpAddressType         string
}

response, error := json.Marshal(getLoadBalancers.LoadBalancers)
    if error != nil {
        fmt.Println("Error, %v", error)
    }

    fmt.Println(reflect.TypeOf(getLoadBalancers.LoadBalancers))

    var lbJson LoadBalancerJSONStructure

    err := json.Unmarshal(response, &lbJson)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("Struct is: ", lbJson)


Find the representation in series of $\displaystyle\int_0^z \frac{\sin t}{t}dt$

Question: Find the representation in series of $\displaystyle\int_0^z \frac{\sin t}{t}dt$
My attempt:
For this: Develop in the series of powers around the corresponding origin (Taylor or Laurent) the following functions...
$f(z)=\frac{\sin t}{t}=\displaystyle\sum_{n\geq 0} (-1)^n\frac{t^{2n}}{(2n+1)!}$
Moreover, the radius of uniform convergence is $C=\{z\in\mathbb{C}:|z|<\infty\}$
This implies:
$\displaystyle\int_0^z \frac{\sin t}{t}dt=\int_0^z\sum_{n\geq 0} (-1)^n\frac{t^{2n}}{(2n+1)!}dt=\sum_{n\geq 0} (-1)^n\frac{1}{(2n+1)!}\int_0^zt^{2n}dt=\sum_{n\geq 0} (-1)^n\frac{1}{(2n+1)!}\frac{z^{2n+1}}{2n+1}$
In convergence radius: $C=\{z\in\mathbb{C}:|z|<\infty\}$
is correct this?
Comment: The series converges for ALL complex numbers. There is NO complex number whose absolute value is infinity. The set of complex numbers is NOT the same as the complex projective line. There is a standard embedding from the set of complex numbers  C to the complex projective line defined by f(z)=(z:1) but f is NOT surjective, because (1:0) is not f(z) for any complex number z.
Comment: Yes, you have done it right.
Answer: The question has already been answered in the comments. Your approach and result are correct, except that a) you've specified the domain of convergence and called it the convergence radius, and b) your notation for the domain of convergence is unnecessarily complicated and confusing, since it coincides with $\mathbb C$.


Get the node title conditionally in a view rewrite field

Question: How can I get the field for the title of the content?
In twig I need to do this (for jssor slider) :
{% if field_titre_url_externe is not empty  %}
  {{ field_titre_url_externe }}
{% else %}
  {{ field_title }}
{% endif %}

but field_title is showing nothing, so what is the name of this?
EDIT :
I'm talking about the title of a node , article or content type
In my frontend, the title has the class views-field-title
See this image for more details (that's what I want to do):

Access the field_url_externe is not working actually... Accessing this field will solve my problem
Comment: The term "title field" is a generic, ambiguous term. It would help if you clarified and narrowed the scope of your question. Is this the "title" for a Node? The title of a view? Which template are you modifying and what are you doing? At the moment it's unclear to me what exactly you're trying to do. Thank you.
Answer: Is title a field you made or do you mean the node title? Node title can be printed with either {{ label }} or {{ node.getTitle() }}.
Fields that you created on the node, they are rendered out as:
{{ content.field_title }}
Which can be checked as:
{% if node.field_title_external is not empty  %}
  {{ content.field_title_external }}
{% else %}
  {{ node.getTitle() }}
{% endif %}

You can also use {{ label }} instead of {{ node.getTitle() }}.
Comment: It's indeed showing the external link, but the title of the node is not showing
Comment: That seems impossible unless this is not shown in the context of a node? Title of _what_ node exactly? Title of the node being viewed, or title of _a referenced_ node? A different field title?
Comment: Title of the node articles (drupal) and some custom content type. The title of a drupal article and it's external link will be the same, but the link won't. If the external link is set, don't show drupal article title but show external link
Comment: Ok, you are doing this from Views, which is different than the normal theming methods.
Answer: This is the correct value for the rewrite field:
{% if field_url_externe is not empty  %}
  {{ field_url_externe }}
{% else %}
  {{ title }}
{% endif %}

You can see the available fields in the "Replace Patterns" expandable link.
Comment: It's working, I wasn't on the right page. Thanks a lot !
Comment: This is for the plugin jssor slider, I don't think it has something to do with the theme... The twig part I'm trying to add is in the view part in backend
Comment: Twig is part of the theming system in Drupal...
Comment: Are you using the _jssor Drupal module_?, are you using a _Drupal view_? I am trying to understand better your implementation.
Comment: Yes for jssor drupal module. The part with title_prefix is not working. I'm using a view in drupal backend. This my update post for more details
Comment: Just updated the answer in a _views_ rewrite field title is the correct variable
Comment: Did you seem my update image ? {{ title }} is indeed the variable I was looking for, but how to access the order field value (as shown on my image)
Comment: Just updated the answer... Sorry, it had some wrong code from the 1st answer attempt.
Comment: I have these result, what should i do with theses patterns ?
Comment: Those are the names of the variables available to you in the _rewrite results_ area, the different fields and variations on them. The order of the fields matter. Are you getting an error? doesn't the twig snippet work?


Convex polygon inscribed in a circle with vertices that create matrix. Prove that the rank of this matrix is less or equal 2.

Question: Consider a convex polygon inscribed in a circle with vertices $P_1$, ..., $P_n, \ n \ge 3$. Let $A$ be the matrix $n \times n$ such that
$\begin{equation}
  a_{ij} =
    \begin{cases}
      |P_iP_j| & \text{if $i > j$,}\\
      -|P_iP_j| & \text{if $i \leq j$.}\\
    \end{cases}
\end{equation} $
Prove that $rank(A) \leq 2. $
Obviously:
$\begin{equation}
  A =
\begin{bmatrix}0 & -|P_1P_2| & ... & -|P_1P_n|\\|P_2P_1| & 0 & ... & -|P_2P_n|\\ ... & ... & ... & ...\\|P_nP_1| & |P_nP_2| & ... & 0 \end{bmatrix}
\end{equation} $
where every element on the left of diagonal is positive and on the right is negative. Don't really know how to continue. Any hints?
Comment: Is $|AB|$ the Euclidean distance between two points?
Comment: If I understand correctly that $|PQ|=|QP|$ for any two points $P$ and $Q$, then the correct result is that the rank is **at least** $2$, as explained in [this question](https://math.stackexchange.com/questions/7978/rank-of-skew-symmetric-matrix).
Comment: Of course, that result doesn't take into account that the points lie on a circle. In addition, that result seems rather trivial in our case, as clearly rows 1 and 2 are independent. That means the result is "rank=2", but clearly the part of this problem has much higher difficulty (if it's true).
Comment: @ArnaudMortier Yes, it is Euclidean distance between points, but not any points, as Ingix mentioned - these are points lying on the circle
Answer: Put the origin $O$ of a coordinate system at the center of the circle that has radius $r$. Choose the direction of the $x$-axis such that there exist angles $0 < \alpha_1 < \alpha_2 <\ldots <\alpha_n < 2\pi$ such that $P_i = (r\cos(\alpha_i),r\sin(\alpha_i))$.
The triangle $OP_iP_j$ is isoscales, so if $M$ is the midpoint of $P_iP_j$, then triangle $OMP_i$ is right-angled at $M$. Since $OM$ is also the angle bisector of the angle at $O$ in the triangle $OP_iP_j$, we get
$$\left\lvert\sin\left({\alpha_j-\alpha_i \over 2}\right)\right\rvert = \frac{\lvert MP_i\rvert}r$$
and thus
$$ \lvert P_iP_j\rvert = 2 \lvert MP_j\rvert = 2r\left\lvert\sin\left({\alpha_j-\alpha_i \over 2}\right)\right\rvert$$
Let's take a closer look at the sign of the trigonometric function here. We have $-2\pi < \alpha_j - \alpha_i < 2\pi$ and hence $-\pi < \frac{\alpha_j - \alpha_i}2 < \pi$. That means the $\sin$-function is positive/zero/negative exactly when $\alpha_j - \alpha_i$ is positive/zero/negative. By the choice of the $\alpha_k$ to be increasing, we have that $\alpha_j - \alpha_i$ is positive/zero/negative when $j>i/j=i/j<i$.
That means the general term $(a_{ij})$ of our matrix $A$ is
$$a_{ij}=2r\sin\left({\alpha_i-\alpha_j \over 2}\right)$$
For $i=j$ that term is $0$ (as it should be), for $i > j$ is is positive (as it should be) and for $i < j$ it is negative.
Not we write every row as a linear combination of the first 2 rows, which means that  rank$(A) \le 2$. Note that by the comment of Arnaud Mortier under the question we actually have rank$(A) = 2$. A little experimentation with $n=3$ shows that to get row $i$, you have to mulitply row $1$ with
$$-\sin\left({\alpha_2-\alpha_i \over 2}\right) \over \sin\left({\alpha_1-\alpha_2 \over 2}\right)$$
and row $2$ with
$$\sin\left({\alpha_1-\alpha_i \over 2}\right) \over \sin\left({\alpha_1-\alpha_2 \over 2}\right)$$
and add the results up. To prove that this leads to the correct result, we have to prove the following identity:
$$a_{ij}\sin\left({\alpha_1-\alpha_2 \over 2}\right) = -a_{1j}\sin\left({\alpha_2-\alpha_i \over 2}\right) + a_{2j}\sin\left({\alpha_1-\alpha_i \over 2}\right).$$
Using the formulas above and removing the common factor $2r$ on both sides, it needs to be proved that
$$\sin\left({\alpha_i-\alpha_j \over 2}\right)\sin\left({\alpha_1-\alpha_2 \over 2}\right) = -\sin\left({\alpha_1-\alpha_j \over 2}\right)\sin\left({\alpha_2-\alpha_i \over 2}\right) + \sin\left({\alpha_2-\alpha_j \over 2}\right)\sin\left({\alpha_1-\alpha_i \over 2}\right).$$
There might by multiple ways to prove this, I choose to apply the following formula for all 3 products:
$$\sin(X)\sin(Y)=\frac12(\cos(X-Y) - \cos(X+Y))$$
that can be easily proved by using the addition theorems on the right side. Using this on the equality to prove yields to (equivalently), after removing the common $\frac12$ in both sides:
$$ \begin{eqnarray}{}
\cos\left(\color{red}{\alpha_i-\alpha_j-\alpha_1+\alpha_2\over 2}\right) - \cos\left(\color{blue}{\alpha_i-\alpha_j+\alpha_1-\alpha_2\over 2}\right) = \\
-\cos\left(\color{blue}{\alpha_1-\alpha_j-\alpha_2+\alpha_i\over 2}\right) + \cos\left(\color{orange}{\alpha_1-\alpha_j+\alpha_2-\alpha_i\over 2}\right) + \\
\cos\left(\color{red}{\alpha_2-\alpha_j-\alpha_1+\alpha_i\over 2}\right) - \cos\left(\color{orange}{\alpha_2-\alpha_j+\alpha_1-\alpha_i\over 2}\right)
\end{eqnarray}
$$
I've marked with the same colors the terms that are equal on each side (red, blue) and that cancel each other on the RHS (orange). This concludes the proof of the proposition.


How to fit the textarea to the table cell

Question: I am showing a textarea in my input in a table. But I want to resize it so that it covers the entire table cell, till the borders.
Logic -
<textarea type="textarea" value="{{data.directRowNo}}" id = "abc"
></textarea>

The css  I use is -
  #abc{
width: 100%;
height: 443%;
box-sizing: border-box;
resize: vertical;
max-height: 500px;
}

Image -

There is a bifurcation line that shows up which I don't want.
Comment: Show HTML of the table
Comment: Give position relative to parent and make child absolute with 100% height
Comment: (Is there some voodoo in angular that actually creates a `textarea` element based on `<input type="textarea"` …?)
Comment: @ Abhishek Pandey. How to define that . Can you help ? Position relative to parent and child height 100% height
Comment: just add css to textarea i.e textarea{ resize: none }
Answer: Is this what you're looking for?
CSS
table {
    width: 500px;
    margin: 20px auto;
    border-collapse:collapse;
    border-spacing: 0;
}

table td {
    background-color: red;
    border: 0;
    min-height: 20px;
}

textarea {
    border: none;
    width: 100%;
    -webkit-box-sizing: border-box; /* <=iOS4, <= Android  2.3 */
    -moz-box-sizing: border-box; /* FF1+ */
    box-sizing: border-box; /* Chrome, IE8, Opera, Safari 5.1*/
}

HTML

            cell

            <textarea></textarea>

            cell

The above code will resize the <textarea> along with the cell and will stretch the textarea till the cell border.
Answer:

 #abc{
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    resize: vertical;
    max-height: 500px;
    resize:none;
    }
    table{
    border:solid 1px black;
    }
table th{
border:solid 1px black;
}

    Header

    <input type="textarea" id = "abc">

Comment: `` in ``?
Comment: @AbhishekPandey what's your answer?
Answer: Try setting the padding of td to 0: https://jsfiddle.net/upb51sth/
td {
  background-color: red;
  padding: 0;
}


How to Update all Dates in a Table

Question: I have a table with 5 million DATETIME records. I want to add a year to all the various datetimes in the table. Can I do it all with a single query? Something like:
SELECT DATE_ADD(*, INTERVAL 1 YEAR);

Or any other way you would recommend. Thanks!
Answer: This should do what you want:
UPDATE table SET datefield = DATE_ADD(datefield, INTERVAL 1 YEAR);

If you need to update every table in the database check the answers to this question
Comment: He wants to do it for *all* datetime fields in the whole database.
Comment: @MatthewFlaschen - This WILL update all records in a given table. In order to update every table without knowing the table names you'll have to first run the query "SHOW TABLES" then work off the results from that.
Comment: Yes, it will update the "datefield" field in all records.  However, his question is much more general, and will probably require use of `INFORMATION_SCHEMA.COLUMNS`.
Comment: @MatthewFlaschen: Sorry, I should be clearer. I just need it for one table. Thanks.
Comment: Thank a lot Pastor

How to Update all Dates in a Table


Show output of chef Execute in console as it runs

Question: I have the following snippet in a chef recipe:
<code>chef::Log.info("Installing pips using requirements file: #{requirements_file}")
execute "pip install -E #{ve.path} -r #{requirements_file}" do
  user deploy_user
  cwd deploy_path
end
</code>
This installs a number of packages, and I'd like to see the output of "pip install" as chef-client is working when I invoke it via SSH. Is there any way to log the output of the execute command so that writes to the log as pip is running?
Answer: If you are looking at chef to show, running it using '-l debug' which show it. Alternatively, pip can log the activity using '--log=FILENAME' option.


jquery ui slider page up/down increment value

Question: Is there a way to set by how much the slider moves when someone presses page up or page down? Currently, my slider moves by a value which is equivalent to one fifth of the slider range. I would like to set it to move by, say, 10 steps. Is there a way to do it?
Answer: You have to use the 'step' option for that:
    $( "#slider" ).slider({
        value:100,
        min: 0,
        max: 500,
        step: 50
    });

To solve the page up/ page down strange behavior, try this: http://jsfiddle.net/SPDBw/
Comment: Thanks, but the 'step' option affects by how much the slider moves with the arrow keys. I'd like to keep that at '1'. Instead, I want to change the amount it moves when the **page up/down** buttons are pressed.
Comment: My bad, I didn't know it has a different behavior when using page up/page down and I believe it's a bug as it makes a nonsense result.
I believe you'll have to directly prevent their default behavior and make a function that makes them work right.
Comment: Just updated my answer with this custom pageup/pagedown behavior.
Comment: Thanks, Robyflc. How can update the sample you gave me if there are multiple sliders and each slider has two scrollers (values)? I would like the the keystroke to only affect the selected scroller.
Comment: By "each slider has two scrollers" you mean something link this range example: http://jqueryui.com/demos/slider/#range?
Answer: From version 1.8. to 1.11., they've put the variable numPages inside the ui.slider container, and fixed it to 5.
Even if you override the keyCode handler to recognize the keys "PageUp" and 'PageDown" wouldn't fix the problem.
BUT, as a workaround, you can override this variable, contained in the prototype scope of the slider widget, at the beggining of your page load.
Pros: I don't need to worry about fetching the objects' max and min values
Cons: Solution is only a workaround, and solution can(and will) be broken in a future patch.
What I did was:
$(document).ready(function() {
  $.ui.slider.prototype.numPages = 10;
});

Hope it works ;)


Ruby - Como acertar o LOAD_PATH em tempo de desenvolvimento?

Question: Em primeiro lugar: Eu sou um novato em Ruby.
Eu tenho um projeto em Ruby que obedece ao padrão de projeto da grande maioria dos projetos. Portanto, o executável principal fica em bin/.
bin/exec
lib/
    |
     -- library.rb
     -- library/

O problema é que o executável principal depende do library.rb para rodar corretamente, e o library.rb depende de todo o resto dentro do diretório library.
Se eu empacotar o projeto numa gem e instalar essa gem, o executável principal roda porque o Rubygems vai cuidar de tudo, mas isso tem a desvantagem de que o executável principal não enxerga as mudanças dentro do diretório lib.
Isso sempre me leva a escrever código como esse:
$: << File.expand_path('../lib')

E em library.rb:
$: << File.expand_path(File.dirname(__FILE__))

Isso resolve o problema, mas distribuir o software com esse código é distribuir software com "debug code". E no pior dos casos isso pode causar um bug, caso algum azarado rode o executável principal num diretório onde coincidentemente também há um diretório chamado "lib" e por uma coincidência maior ainda, haja um arquivo chamado library.rb dentro do diretório.
Como deixar o LOAD_PATH correto em tempo de desenvolvimento sem necessidade de poluir o código?
Answer: Acredito que suas preocupações com esse código não deveriam existir. Diferente do que você afirma, esse é o procedimento padrão pra todas as aplicações com arquivos executáveis em Ruby: o executável fica em bin/ e este adiciona o ../lib no load path.


If $|f(x)|<x^2$ for $|x|<1$, then show that $f'(x) $ exists and find it

Question: I can intuitively guess the answer is 0
because if we graph of f(x) must be below x^2
looking for a clean and more logical attempt
Comment: Is the question about $f'(0)$?
Comment: I don't see how any function $f$ can satisfy the given condition.The condition implies that $|f(0)| < 0$, which is clearly impossible.
Comment: Most likely, the question should be "If $|f(x)| \le x^2$ for $|x| < 1$, then show that $f'(0)$ exists and find it." If that is what the question should have said, the OP needs to correct it.
Answer: Notice that $0 \le \left|\dfrac{f(x)-f(0)}{x-0}\right| = \dfrac{|f(x)|}{|x|} \le \dfrac{x^2}{|x|} = |x|$ for all $x$ such that $|x| < 1$ and $x \neq 0$.
What does this tell you about $f'(0) = \displaystyle\lim_{x \to 0}\dfrac{f(x)-f(0)}{x-0}$?

Also, note that $f'(x)$ isn't guaranteed to exist anywhere other than $x = 0$.
Consider $f(x) = \begin{cases}x^2 & x \ \text{is rational}\\-x^2 & x \ \text{is irrational}\end{cases}$. This function satisfies $|f(x)| \le x^2$ for $|x| < 1$, but isn't differentiable (or even continuous) anywhere except at $x = 0$.


Is censoring data necessary to calculate the hazard ratio between 2 KM curves?

Question: I would like to know if censoring data is necessary to calculate the hazard ratio between 2 Kaplan Meier (KM) curves.
Censoring data is typically represented by small vertical bars atop of the curve on KM graphs.
Censoring data has an impact on the shape of a KM curve already (for instance, if 98/100 people drop from a trial, and 1 person dies, the curve goes down much more than if no one had dropped out). This makes me think that the curves are perhaps enough for calculating hazard ratios (since I understand hazard rates are akin to the slope of the curves). Is this true?
I am asking a practical question:
Is having the values of survival curves over time, without the censoring information, enough to estimate the hazard ratio between these curves?
Context:
I am right now digitizing KM curves. I would like to estimate the hazard ratio between them. I cannot retrieve the censoring data. Not having the censoring data is a limitation to my analysis, I know. But I would like to know: Can I nonetheless calculate the hazard ratio? Can I calculate a confidence interval for this hazard ratio?
Ideally, please let me know how the answer differs depending on whether or not we assume relative hazards between the 2 groups are constant across time.
Answer: The KM-estimate is:
$$S(t_2) = P(T>t_2)  = P(T>t_2|T>t_1)P(T>t_1) \\
                     = P(T>t_2|T>t_1)S(t_1) $$
with $P(T>t_2|T>t_1)$ estimated as
$$P(T>t_2|T>t_1) = 1-\frac{\mathrm{number \ of \ events}}{\mathrm{number \ at \ risk}}$$
If you can accurately measure $S(t_1)$ and $S(t_2)$ based on the graphs, you can reproduce the number at risk at each event-time.
$$1-\frac{\mathrm{number \ of \ events}}{\mathrm{number \ at \ risk}} = P(T>t_2|T>t_1) \\
 = \frac{S(t_2)}{S(t_1)}$$
Of course, if $N_E$ and $N_R$ satisfy a drop from $S(t_1)$ to $S(t_2)$, then $2N_E$ in combination with $2N_R$ does so as well. Additional info on the order of magnitude of $N_R$ (and realizing that $N_E$ and $N_R$ are integers) is a great help.
As long as the resolution is good enough to accurately measure the survival probabilities and make the distinction between 1, 2 or more simultaneous events (with many people at risk, the drop in S(t) from 1 event may only be 0.1 %, which will difficult to distinguish from a drop of 0.2 % due to 2 simultaneous events), you can do the reverse calculation. From the numbers at risk at $t_1$ and $t_2$, you can deduce the number of censored between these times.
So yes, you can (approximately) recreate the numbers at risk and number of events at each timepoint, but (as pointed out by John L.) only within the arm where the event takes place. So if you have event times $t_1$, $t_2$ and $t_3$ with events in group A, B and A again, you can recreate the number at risk in group A at times $t_1$ and $t_3$ but not at $t_2$. In the same way, you can recreate the number at risk in group B for time $t_2$ but not at times $t_1$ and $t_3$ (at least, not without additional assumptions, like e.g. uniform censoring between two time points)
Comment: "If you can accurately measure S(t1) and S(t2) based on the graphs, you can reproduce the number at risk at each event-time." This is actually not true. You may have any number of patients censored, in either group, prior to the first event in that group, and you would never know the subsequent denominator size. A similar issue occurs with tied event times - say 4 are at risk following a censoring event, then two fail simultaneously, this renders the same curve as when two are at risk and one fails.
Answer: Yes, you would need to know the time of each event, the number of events at each time, and the number at risk at each time there was an event. There is not enough information on the figures to determine exactly how many subjects were at risk in both groups at each time there was an event- unless the figure actually shows the time of censoring using circles or some symbol.  Otherwise, no matter how accurate the software is, you will not be able to know how many were at risk at each time.
Example, where there is a jump in the Kaplan-Meier curve, using the product-limit estimator if the software is accurate enough, it is possible to work backwards to figure out the ratio of {# events}/{# at risk}. That part is fine and since you know approximately how many are at risk and assuming # events is a small number, it will be possible to pinpoint exactly # at risk and # events. However, what if it is a time point where there is an event in the other group only? Suppose there is an event in group A at time 100. There is no event in group B at that time. But, it is known that at time 95 there were 1000 patient at risk in group B and at time 105 there were 950 patients at risk  (no events occurred between time 95 and 105). You only know that at time 100 there was some number between 950 and 1000 at risk in group B. It is impossible to identify any more information from the graph no matter how precise the graph was drawn and no matter how good the software is. The information is simply not on the graph.
Of course, you could just assume it is half way in between 950 and 1000 (i.e. 975 patients at risk at time 100) and you could similarly use interpolation at all the time points like that (assume the number at risk goes down linearly between the two time points where you know the numbers at risk).
In practice, the software I have seen does not even try to help you to guess how many are at risk and how many events occur at each time point, it simply estimates the x and y values at different points on the graph.
Answer: You need to distinguish between the data analysis and the data display.
As you note, the Kaplan-Meier curves directly take censoring into account:

if 98/100 people drop from a trial, and 1 person dies, the curve goes down much more than if no one had dropped out.

That means that you need to include censored cases in the analysis. You can't just throw away the censored cases.
You don't necessarily need to display the censored cases on the curves, typically done with short vertical bars at censoring times. I think that most readers would like to see those, however, as it provides information about the distribution of censoring times versus the distribution of event times. That information helps the reader gauge the reliability of the analysis, and I urge you to show them for situations where there are moderate numbers of cases.
For Kaplan-Meier analysis, you need to be careful when you say:

hazard rates are akin to the slope of the curves.

A Kaplan-Meier curve has 0 slope between events and an infinitely steep slope at event times. For such curves, the instantaneous hazard is the probability of having an event given that there has been survival up to that time. So the hazard is 0 between event times and proportional to the magnitude of the drop at event times.
The log-rank test can determine whether 2 Kaplan-Meier curves differ significantly. As that Wikipedia reference notes, for 2 groups that test is equivalent to the score test in a Cox survival regression.
You also have to be careful in moving from a difference between 2 Kaplan-Meier curves to statements about hazard ratios, as estimated by Cox regressions. Unless the relative hazards between the 2 groups are constant across time (proportional hazards, PH, assumption), a hazard ratio between the 2 groups is at best difficult to interpret. Unless PH holds, there is no constant hazard ratio between the groups over time. With non-zero hazards only at event times in Kaplan-Meier or Cox models, it's even hard to gauge relative hazards between groups as a function of time. Parametric survival functions would better allow for comparing continuous hazard ratios as a function of time.
Comment: Thanks for this answer @EdM. It made me realise that my question wasn't specific enough, so I rephrase: Is having the values of survival curves over time, without the censoring information, enough to estimate the hazard ratio between these curves?


absolute asymptotic condition number uniqueness differential equation

Question: Suppose that we have a piecewise, differential equation. Say
$\frac{dx}{dt} = \begin{cases} x \sin \frac{1}{x} & x \neq 0 \\ 0 & x = 0\end{cases}$
$x(0) = 0$
I like to ask if the differential equation has a unique solution. I have tried two different methods, but none of them can seem to tell me anything. Later, a friend told me about his theorem, but I am unsure if his theorem is true or not.
Theorem 1 Lipschitz
$|f(x) - f(y)| \leq L |x - y|$,
It doesn't seem to satisfy the Lipschitz condition when $x^{-1} = \frac{\pi}{2} + 2 n \pi$ and $y^{-1} = \frac{3\pi}{2} + 2 n \pi$ because I end up getting $L$ to be $2(2n+1)$ and when $n \to \infty$, $L \to \infty$. So I don't think I can apply the theorem because it doesn't fit the first part of the theorem.
Theorem 2 Continuity
If $f(t,y)$ and $\frac{\partial f}{\partial y}$ are continuous functions in some rectangle $α<t<β$, $γ<y<δ$ containing the point $(t_o,y_o)$, then there is a unique solution to the IVP in some interval $t_o – h < t < t_o+h$ that is contained in $α<t<β$.
$\frac{\partial f}{\partial y}$ is not continuous so I don't think I can apply the theorem because it also doesn't fit the first part of the theorem.
Theorem 3 Absolute Asymptotic Condition Number (unsure of this theorem)
If $f(x)$ has a constant as an absolute asymptotic condition number, then the differential equation has a unique solution. It seems to be saying that if
$\underset{x \to 0}{\lim} \sup \frac{|f(x) - f(0)|}{|x - 0|} < \infty$
then it has a unique solution.
I calculated the absolute asymptotic condition number to be 1, which is a constant. I believe that it is also saying that it is asymptotically stable. Furthermore, since it satisfies the theorem, then I must say the differential equation has a unique solution.
So does this differential equation actually have a unique solution?
If I am wrong saying that, since I can't use the first part of the theorem, I cannot use the theorem, then let me know.
Please and thank you.
Comment: Is it $y'(x)=f(x)$ or $y'(x)=f(y(x))$? In the first case you are really asking about the integral $\int_0^x f(s)\,ds$ which exists as Riemann integral as this $f$ is continuous everywhere.
Comment: Oh sorry, thanks for noticing that. Yea I meant y' = f(y). I will see if I can fix it.
Answer: If $x(0)\in \left[\frac1{(n+1)\pi},\frac1{n\pi}\right]$ then go some step below, set $a=\frac1{2n\pi}$ and recognize that on $x\in[a,\infty)$ the right side is smooth, so the existence and uniqueness theorem applies.
But as $x_L(t)=\frac1{(n+1)\pi}$ and $x_U(t)=\frac1{n\pi}$ are constant solutions, they bound the solution $x(t)$ which thus exists for all times.
By exclusion, the solution $x(t)=0$ is also unique, no branching to non-zero values is possible.

Your counter-example for the Lipschitz condition is not correctly constructed, you probably wanted $x^{-1} = \frac{\pi}{2} + 2 n \pi$ and $y^{-1} = \frac{3\pi}{2} + 2 n \pi$ so that the sine factor has values $\pm 1$. But then
$$
|f(x)-f(y)|=x+y=\frac{2\pi+4n\pi}{(\frac{\pi}{2} + 2 n\pi)(\frac{3\pi}{2} + 2 n\pi)}\sim\frac1n
$$
which is still asymptotically larger than
$$x-y=\frac{\pi}{(\frac{\pi}{2} + 2 n\pi)(\frac{3\pi}{2} + 2 n\pi)}\sim\frac1{n^2},$$
so that no Lipschitz constant exists at $x=0$.
Comment: So are you saying that the piecewise differential equation has a unique solution and that solution is x(t) = 0? Which existence and uniqueness theorem are you applying? Is this just the same as the continuity theorem?
Comment: I'm referring to the standard Picard-Lindelöf theorem with extensions towards maximal solutions. The main point is that you have a sequence of roots of $f$ clustered around $x=0$, and each root generates a constant solution that acts as barrier for any other solution.
Comment: Oh ok then. It sounds like you can have more than one solution then, but you can only have one solution per root?
Comment: In principle yes, but you can not cross any of the constant solutions $x(t)=\pm\frac1{n\pi}$, which I mean with the "exclusion" idea.


Tem alguma forma de acessar uma posição por meio de string?

Question: Não teria alguma forma de acessar uma posição utilizando uma string?
Exemplo:
int vetor[1000000];

vetor["abc"]++;

Eu sei que é loucura minha, mas... "abc" = 01100001, 01100010, 01100011, 00000000 (caractere null), então "abc" não deveria representar 1633837824?
Comment: Só fazer map seuMap; seuMap["abc"] = 0; etc... http://www.cplusplus.com/reference/map/map/
Answer: É possível através de um map ou unordered_map, onde o índice pode ser propositalmente uma string. Mas onde se espera um valor inteiro não pode usar uma string, no máximo pode se usar algum algoritmo de conversão da string (pode ser um cast) para algum inteiro que faça sentido para utilização como índice. Então, sim, é "loucura" pensar que um texto poderia ser usado de forma direta em um índice de um array.
Fora o fato que nesse caso pegaria um local da memória que não pertence ao array declarado, pode fazer isto:
#include <iostream>
using namespace std;

int main() {
    int vetor[100000];
    vetor[(int)"a"] = 1; // é 0110000100000000
    cout << vetor[(int)"a"];
}

Coloquei no GitHub para referência futura.
Comment: Valeeeu! Eu tava querendo algo diferente do map por causa que ele é um pouco mais lento que um vetor, mas valeu ai :D


If $k^n$ no simple $kG$ module, then we can find a basis in a special form.

Question: I'm reading Lam's book "A first course in noncommutative rings". In the proof of Burnside's First Theorem ((9.4), p151). The statement says:

Let $k$ be a field of characteristic $p \geq 0$ and let $G$ be a
  subgroup of $GL_n(k)$. If  $G$ has exponent $N < \infty$ and $p \not|
 N$, then $|G| \leq N^{(n^3)}$.

In the proof, we can assume that $k$ is algebraically closed.
On a certain moment, the proof makes the following claim:
Assume $k^n$ is a non-simple $kG$-module. Then, after choosing a suitable basis for $k^n$ we may assume that the elements of $G$ have the form
$$\begin{pmatrix}g_1 \ h \\ 0 \ g_2\end{pmatrix}$$
where $g_1, g_2$ are square matrices of fixed size, say $n_1$ and $n_2$. Moreover, $g_i \in GL_{n_i}(k)$ for $i=1,2$.
Why is the above true? How do we choose this basis? Why can we assume our elements change?
Answer: I believe these matrices are intended to operate on the right of row vectors in $k^n$.

How do we choose this basis?

If $k^n$ is a nonsimple $kG$ module, it has a proper $kG$ submodule, call it $N$.  After fixing a $k$-basis of $N$, we can go about figuring out just how $G$ acts on $N$, and those will become the matrices that go into the $g_2$ spot.
Now extend the $k$-basis for $N$ to all of $k^n$. Now we can work out representations of elements of $G$ that act on all of $k^n$.  But look: this new matrix has to cause $N$ to be mapped into itself, since $N$ is a $kG$ submodule. Since that happens, it must be that the basis vectors not in $N$ have to be mapped to $0$, and this is what causes the lower left-hand block of zeros.

Why can we assume our elements change?

The elements don't change... just our representation of them changes. And after all, we are free to represent the vector space with whatever basis we prefer.

Why is $g_2\in GL_{n_2}(k)$?

Each element of $kG$ is acting as a $k$ linear transformation on the $n_2$ dimensional space $N$, and so it can be represented by a $n_2\times n_2$ matrix, i.e. $g_2$.
$g_1$ is an $n_1\times n_1$ matrix where $n_1=n-n_2$, just by your knowledge of the dimensions of the matrices and the size of that zero block. Using block-matrix arithemtic, you can easily show that the diagonal blocks are invertible, since the matrix is invertible (representing the invertible element $g\in G$.)
Comment: @user661541 Good luck! And let me know if I can elaborate somehow, when we meet here again.
Comment: Sorry for the late accept! It was really useful!
Comment: @user661541 glad to help
Comment: @user661541 It says *the elements of $G$ have the form*, and obviously elements of $G$ are invertible.  So when  $\begin{bmatrix}A&\ast\\0&B\end{bmatrix}$ has block-inverse $\begin{bmatrix}C&\ast\\0&D\end{bmatrix}$, it is trivial to show $A^{-1}=C$ and $B^{-1}=D$.
Comment: Thank you @rschwieb for your help, guidance and patience. Everything is clear now. Have a great day/night!
Comment: @user661541 No problem
Comment: Thanks for the answer! Why does have $N$ have a basis?
Comment: @user661541 Because it is a vector subspace of $k^n$. All vector spaces have bases.
Comment: So, you mean a $k$-basis and no $kG$-basis?
Comment: Of course. There is no sense in talking about a basis of a $kG$ module unless you know it is free. And we don't. The $k$-bases are what give us these matrix representations...
Comment: I'll think somewhat about this answer to see if I fully understand it. Thanks again
Comment: So, I thought a bit about it. I see that we can fix a $k$-basis for $N$: $N= e_1 k \oplus \dots e_{n_1} k$. Then we extend it to a $k$-basis for $k^n$: $k^n = e_1 k \oplus \dots e_{n_1} k \oplus e_{n_1 +1}k \oplus \dots  \oplus e_n k$. Now, I don't see why we can assume that an element of $g$ has this form. The idea is that we can let $k^n$ act on a matrix $g \in G$, but the form in which $g$ should come suggests that one works with something like $N = k^{n_1} \times 0^{n-n_1}$ which isn't the case here. Could you maybe help me further out?
Comment: @user661541 Suppose one of the rows in the bottom half of the matrix $A$ were non zero in the part we think ought to be zeros, say row $j$.  Now, the vectors corresponding to $N$ are those which are zero in the first part. Then the vector with a $1$ in the $j$ position and zeros elsewhere is in $N$, and $NA$  has nonzero entries in the first part (the part outside of $N$.) But that's not possible: $NA\in N$ since $N$ is a $kG$ submodule. See?
Comment: In my comment, the $e_i$ are not necessarily the vectors that are $1$ on one position and $0$ elsewhere. Are you assuming this in your last comment?
Comment: @user661541 The vectors in my comment are not elements of the set $N$, they are the coordinates with respect to the basis you chose. It's an isomorphism of $N$ with $k^n$.Likewise the matrix is the transformation with respect to the basis you chose. If you chose $e_i\in N$ as a basis element, then its corresponding vector is a unit vector.  The matrix equation you are talking about has to be done completely with the coordinate values according to the basis.
Comment: But why do my matrices  'change? In Lam's proposition, $G$ is a linear group of matrices. You say that these matrices change when you choose a basis? Does this mean that you view these matrices as $k$-endomorphisms $k^n \to k^n$?
Comment: @user661541 To represent a transformation $T$ of a vector space $V$ as a matrix, you need to fix a basis first. Different bases yield different matrices.  yes, the whole point of representing a transformation as a matrix is to use matrix multiplication with vectors over the same field.
Comment: If you don't mind, I have one follow up question. Why is $g_2 \in GL_{n_2}(k)$? (for $g_1$ I see why this is the case) I can see that the columns of $g$ are independent in $k^n$ and it will probably have something to do with this.
Comment: Thanks for the edit. But it is still unclear to me why the blocks $g_1, g_2$ are invertible?


Microsoft.AspNetCore.Authorization.AuthorizeAttribute returning 200 (OK) on failure

Question: I have some code similar to this:
[HttpGet]
[Authorize("MyCustomPolicy")]
public string TestCall()
{
    var lanId = User.GetSomeClaimOnTheUserObject() ?? "Not Found";
    return "Hello From a TestCall Get Operation.  Claim is " + lanId;
}

The Authorize Policy looks like this:
var myCustomPolicy = new AuthorizationPolicyBuilder()
    .RequireAuthenticatedUser()
    .AddAuthenticationSchemes("SomeScheme")
    .Build();
options.AddPolicy("MyCustomPolicy", myCustomPolicy);

When I call it, it allows the call through if the AuthenticationScheme has been met, and blocks it if it has not (as expected).
The part that is not working is when it blocks the call, I would expect a 403 or maybe a 401 to be returned, but instead I am getting a 200 (OK) being returned.
How can I get it to return a 401 when it fails the Authorize attribute?
Answer: I run into the same issue and after some search in SO I found basically this AuthorizeAttribute will return the view with login page when auth fails, instead of giving 401. To solve this you might want to try this answer or based on your use case search for some other examples, but essentially the cause of the problem is the same.


sed issue: -bash: syntax error near unexpected token `('

Question: I'm attempting to run this command:
 sed -i 's/if (DEFINED CMAKE_TOOLCHAIN_FILE)/if (NOT DEFINED CMAKE_TOOLCHAIN_FILE)/g' makefiles/cmake/arm-linux.cmake

But it seems my bash syntax is messed up when I copy that snippet from http://thinkrpi.wordpress.com/2013/05/22/opencvpi-cam-step-2-compilation/ and I get this:
-bash: syntax error near unexpected token `('

Any idea why?
Comment: @huertanix: Not backticks. Apostrophes. What you have now are neither apostrophes nor backticks.
Comment: When I change both apostrophes into backticks I get this:

    -bash: command substitution: line 1: syntax error near unexpected token `DEFINED'
    -bash: command substitution: line 1: `s/if (DEFINED CMAKE_TOOLCHAIN_FILE)/if (NOT DEFINED CMAKE_TOOLCHAIN_FILE)/g'
sed: -e expression #1, char 1: unknown command: `m'
Comment: Seems like you are using a mac. If so, then put empty quotes around the `-i` like `-i""`.
Comment: BTW, this error is mentioned in the first comment on the original posting, and the second has a pointer to the solution.
Comment: The second comment there points to a forum that no longer has the solution alluded to. I ended up manually doing a substitution in vim, which worked.
Answer: sed -i '
#      ^ a problem

This is a "smart quote" of sorts, U+2018. Use a regular apostrophe instead, '. Same for the closing quote.


System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto

Question: Estou desenvolvendo um projeto em asp.net, onde estou tentando realizar esta inserção no banco. Porem quando tento realizar este comando, acaba informando essa mensagem de erro: "System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto."
[WebMethod]
public void InsertUsuario(string usuario, string senha, string nome, string dtnasc, string fone, string email, int oab, string endereco, string bairro, string cep, int codcidade, string cpf, string cnpj)
{
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                string chav = "asfasdf";
                DateTime dateFromString = DateTime.Parse(dtnasc, System.Globalization.CultureInfo.InvariantCulture);
                SqlCommand command = new SqlCommand("INSERT Into Usuarios (IdUsuario, Usuario, Senha, Nome, Chave, DtNasc, Fone, Email, OAB, Endereco, Bairro, CEP, CodCidade, CPF, CNPJ) VALUES ((Select MAX(idusuario)+1 from Usuarios), '" + usuario + "', '" + senha + "', '" + nome + "', '" + chav + "', '"+dateFromString+"', '" + fone + "', '" + email + "', " + oab + ", '" + endereco + "', '" + bairro + "', '" + cep + "', " + codcidade + ", '" + cpf  + "','"+cnpj+"')");
                Console.WriteLine(dateFromString.ToString());
                conn.Open();
                command.ExecuteNonQuery();

            }
}

Esse é o banco criado:
Create table Usuarios (
IdUsuario              int  not null,
Usuario                varchar(30) not null,
Senha                  varchar(30) not null,
Nome                   varchar(50) not null,
Chave                  varchar(18) not null,
DtNasc                 date null,
Fone                   varchar(15) not null,
Email                  varchar(70) null,
OAB                    int null,
Endereco               varchar (100) null,
Bairro                 varchar (80) null,
CEP                    varchar (9) null,
CodCidade              int null,
CPF                    varchar (20) null,
CNPJ                   varchar (20) null
primary key (IdUsuario)
)

Mensagem de erro:
System.InvalidOperationException: ExecuteNonQuery: propriedade Connection não foi inicializada. em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) em System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) em System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

Comment: no seu web.config declarou a string ?
Comment: Declarei sim, já fiz outros testes no banco e a conexão esta funcionando corretamente.
Comment: em qual linha exatamente ocorre o erro ?
Comment: Ai que esta o porem, nao diz em qual linha que esta o erro:

System.NullReferenceException: Referência de objeto não definida para uma instância de um objeto.
   em OniPresenteAPI.oni.InsertUsuario(String usuario, String senha, String nome, String dtnasc, String fone, String email, Int32 oab, String endereco, String bairro, String cep, Int32 codcidade, String cpf, String cnpj)

essa é a mensagem de erro completa
Comment: print com a imagem do erro ?
Answer: Você não está atribuindo a conexão ao command,
tente fazer assim:
string sql = @"INSERT Into Usuarios (IdUsuario, Usuario, Senha, Nome, Chave, DtNasc, Fone, Email, OAB, Endereco, Bairro, CEP, CodCidade, CPF, CNPJ) VALUES ((Select MAX(idusuario)+1 from Usuarios), '" + usuario + "', '" + senha + "', '" + nome + "', '" + chav + "', '"+dateFromString+"', '" + fone + "', '" + email + "', " + oab + ", '" + endereco + "', '" + bairro + "', '" + cep + "', " + codcidade + ", '" + cpf  + "','"+cnpj+"')";

string chav = "asfasdf";
DateTime dateFromString = DateTime.Parse(dtnasc, System.Globalization.CultureInfo.InvariantCulture);
SqlCommand command = new SqlCommand(sql, conn);
Console.WriteLine(dateFromString.ToString());
conn.Open();
command.ExecuteNonQuery();

Comment: Agora apresenta essa mensagem

System.InvalidOperationException: ExecuteNonQuery: propriedade Connection não foi inicializada.
   em System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
   em System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
   em System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
Comment: edita sua pergunta e coloque o código atual como está


can you call next js server actions as a reactQuery queryFn

Question: Is it okay to replace an actual function with a server action when making a query or mutation with react query in next js 13-14
Answer: yh i hv tried it and it works fine
the trick is instead of calling the queryFn directly, wrap it with an async function first
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


What types of guitars are used for spanish music?

Question: I am fascinated by Spanish guitar music, and I have started exploring it. I have heard classical music like Gypsy Kings, Taranta, Romance, etc.
Does anyone here know what types of guitars are used in Spanish music?
Please also give a bit of your personal experience using these guitars.
Answer: First of all, Gipsy Kings music isn't classical :)
 Gipsy Kings play Flamenco guitar, major of their works is Rumba type.
Spanish guitar basically is two types:

Spanish classic guitar.
Famous players: Andres Segovia, John Williams, Julian Bream.
Flamenco guitar.
Famous players: Paco De Lucia, Vicente Amigo, Gerardo Nunez, Sabicas and of course many famous players.

Flamenco guitars are lighter in weight than classical guitars and have much brighter sound because they must be heard over the sound the dancers' shoes.
So what do you want to learn, classic guitar or Flamenco guitar? right hand techniques in Flamenco are really different and vast. It is a really demanding type of playing.
No matter what you pick, I really recommend to get a teacher. It is really easy to develop bad habits that will be hard to correct later.
You might want to check this question too:
Is it possible to learn Flamenco guitar on a steel-string guitar?  Will it sound right?
Comment: Hey! thanks. As i said, i have just started exploring this music. Loved the Gypsy king's music and dint knew it wasnt classical. I want to learn the classical guitar though. And thanks for listing out the famous players.
Comment: Also, flamenco guitars tend to have a "tap plate" or "golpeador" to protect the soundboard as the soundboard is used for percussion.
Comment: Angel Romero is a good audio resource for both styles. While Segovia was trying to take the guitar into the concert hall, the Romeros took theirs to the Ed Sullivan show.
Comment: @luserdroog Angel plays some Flamenco guitar but you aren't going to find any Flamenco players listen to Angel. Paco De Lucia is arguably the most successful Flamenco player who crossed over into other genres of music such as classical and Jazz.
Answer: While Chiron is correct, there is a fair amount of crossover betwen the two styles. If you play Spanish Classical pieces by Albeniz and Tarrega and even Sor, you will find rasgueados, trills, tremolos, pinched harmonics, and other flamenco effects. It's clear that those guys were playing flamenco on the weekend.
So know the difference, but study both. Listen to flamenco by Carlos Montoya. It's like Solo Blues with Spanish Technique. Being able to play flamenco allows you to isolate a fragment from a difficult Spanish Classical piece, and make a fun exercise out of it. You can even develop it into a new song.
Comment: Hey! thanks Carlos Montoya's music is really awesome.Earlier I was looking for music like "Malaguea" and "Alhambra" but couldnt find it. Thnks to you! this is what is always look for.
Answer: So...  Do you want a long-winded rant???
Actually, this question is difficult to answer because the range of "Spanish Music" is vast, even for the guitar.  There's Spanish Baroque guitar music, which uses a 5-course guitar, all but the highest course double-strung.  There's a strong movement of people playing this music on period instruments (I have one myself).  It's really unique stuff, and you have to hear it on the original instrument to appreciate it.  Gaspar Sanz is the best known Spanish guitar composer of that period.  You have probably heard his Canarios in D maj performed on modern instruments.
Much of the music from this period uses hemiola...  Divide 6/8 into groups of 3/3, 2/2/2...  They add up to 6 and 6, but the emphasis changes.  This is a fundamental rhythm for Flamenco forms such as Bularias.  There's a Baroque song form called Jacaras which is very reminiscent of the Bularias, except its kind of square, or old fashioned, by comparison.
BTW, it seems right-hand technique was restricted to the thumb and first two fingers, no fingernails.
Find youtubes by Xavier Diaz-Latorre for Baroque examples you won't regret.
The classical period (roughly speaking) brought in the 6-string guitar.  Still a small body, but six single-strung courses.  Of course, Fernando Sor is the famous composer of that period.  He still used just the thumb and two fingers (with perhaps rare exceptions).  Also, playing was still done without fingernails.  The guitar spread quite a bit thanks to salon playing.
Tarrega sits in the Romantic period, and played the Torres guitar -- a new design with a bigger body, and different bracing.  He still played without fingernails, although I believe there were players who used them in this period.  Following the art-music vein, you would probably come next to Emilio Pujol, and then Andres Segovia.  General use of the nails probably coincides pretty much with the switch from gut strings to nylon.
Preferred woods for classical guitars are spruce for the top, and rosewood for the back and sides.
Flamenco music is associated with the Gypsies in Spain (los Gitanos).  I have read that the Gypsy influence traces to India.  One analysis I read points out that in general these were marginalized, opportunistic people.  They learned that their music attracted attention, so they would put on shows to attract onlookers and then pick their pockets.  This could be apocryphal...  It's probable that there were Gypsies playing guitar in the classical period.  I can't say anything about the Baroque.
Flamenco guitars used tuning pegs instead of mechanical keys for a longer period than classical guitars.  It was said the machine heads were too heavy.  The guitar itself is lighter -- sides and back traditionally made of cypress.  Maybe this was because it was an easier wood to get.  Anyway, the result is a more percussive sound, with less sustain.  Modern Flamenco guitars are as likely to use rosewood, depending on the performer's preference.
Right hand technique for Flamenco is mind-boggling in its variation.  The rasgueados of the Baroque were quite varied and specialized.  It seems classical playing turned away from that.  But Flamenco has expanded significantly on the strumming repertoire.  Rasgueados in Flamenco can use all the fingers (pinkie included).  Tremelo adds an extra stroke to the classical tremelo, so it sounds even more florid.
One thing about Flamenco...  True to what I have heard of the Indian concept of music, song is primary.  There is a a Flamenco concept of Cante Jondo -- deep song.  Then comes guitar, and then comes dance.  As far as I recall from my reading, the dance was put together to attract the tourists, more or less.  That's not to diminish Flamenco dance, but I feel compelled to mention it.
Modern and fusion Flamenco is some of the hottest and freshest music in the world, in my opinion.  Listen to Tomatito...  Wow.  And Paco de Lucia is still riding the crest of the wave -- he's a guru.  For some reason, Spain as a country seems to dismiss Flamenco as just those guitar players...  I can't figure that one out.  This music really deserves a good hearing.
There's a good amount of pop music in Spain that sits on top of Flamenco.  Manzanita got pretty famous in the '70s/'80s, and his songs are pretty nice if you can enjoy the era.  The Gypsy Kings fit into this vein as well.  Estopa is a more modern group doing this. They throw in a good old electric guitar, too.
Whew...
Answer: I can only speak to the topic of flamenco guitar, as opposed to Spanish guitar as a whole:
The shape of flamenco guitars are slightly different from a classical guitar and tend to be lighter. They were traditionally made out of cypress. Cypress is not considered to be the best kind of wood for a guitar as it tends to absorb some of the range of sound. However, it is very good at projecting sound, making it one of the better choices if you want a "loud" guitar. As flamenco guitar began not with solo performances but with accompaniement of flamenco singers and dancers (both of which can be incredibly loud), cypress was the better choice simply because without it the guitar would have been drowned out by the other performers. Cypress was also cheap and easy of access in Andalucia, the home of flamenco.
Since the 1950s roughly, flamenco guitarists have opened to other types of guitar and many flamenco guitars are now made out of rosewood (which is considered much better in keeping the entire range of sound). This came about at a time when flamenco guitar was being recognized as a solist instrument (no need to be overheard over the dancer's taps in a solo performance) and also at the time were electronic amplification made if possible to increase the volume of an instrument without touching the instrument itself (so even if you were accompanying a dancer, you could simply turn up the volume).
Oftentimes, a cypress guitar will be referred to as a "guitarra blanca"
and a rosewood guitar as a "guitarra negra", due to the color of the wood used.
Comment: This answer has severe formatting problems. Could we ask you to introduce paragraphs?


Using class template and overloading / operators

Question: Heloo, I'm having trouble with overloading the / operator in a member function within a template class. I get the error 'error C2805: binary 'operator /' has too few parameters' but I think I'm giving the operator enough parameters. Here is part of my header file code
template <class T>
typename complex<T>::complex operator/(complex<T> &c)
{
    complex temp;
    temp.re = (re*c.getRe() + im*c.getIm())/(pow(c.getRe(),2)+pow(c.getIm(),2));
    temp.im = (im*c.getRe() - re*c.getIm())/(pow(c.getRe(),2)+pow(c.getIm(),2));
    return temp;
}

My function declaration is given below
T operator/(complex<T> &c);

My declaration is indside the class template and the declaration outside, but within the same namespace. If you need the whole code please let me know. Thank you.
Answer: You are missing the class prefix in the operator definition:
complex<T>::operator /(complex<T> &c)

Also, you declared the operator as returning T - why are you returning complex in the definition?
Comment: Sorry, the class prefix? What do you mean by this? I have also changed the declaration of the function from T to complex and the number of errors I get has gone down drastically. Thank you.
Comment: @user1303032, when you define the implementation of a member function outside of the class declaration, you need to precede the function name with class name like this: classA::func1.
Answer: Your declaring a new free function, not the one you declared inside the class definition.
template <class T>
typename complex<T>::complex  operator/(complex<T> &c)
         ^^^^^^^^^^^^^^^^^^^  ^^^^^^^^
            return type       function name

You can see what you're missing there - the scope resolution. You can only overload binary operators as free functions, hence the compiler error you're getting.
This would match your in-class declaration:
template<class T>
T complex<T>::operator/(complex<T>& c)
{
    // ...
}

Compilable example:
Ideone
Then again, returning the template parameter alone from operator/ is probably not what you wanted, you'd want to return a class instance instead. So I think what you really need is this:
template<class T>
complex<T> complex<T>::operator/(const complex<T>& c)
{
    // ...
}

Comment: Thank you. Could you explain to me why two complex's are needed?
Comment: @Gar Which of the two confuses you?
Comment: I'm just wondering why the complex is needed before the complex::operator... part?
Comment: It declares return type of the function. Now considering the declaration you provided (`T operator/(complex &c);`), a call to `operator/` on a class instantiated like `complex` will return an `int`. If you instead, you'd want it to return another instance of the same class, the return type would need to be `complex`. I hope that's clear.


Add class to page content output

Question: I have the following snippet in a theme's page.tpl.php:

          <?php print render($title_prefix); ?>
          <?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
          <?php print render($title_suffix); ?>
          <?php if (!empty($tabs['#primary'])): ?>
<?php print render($tabs); ?>
<?php endif; ?>
          <?php print render($page['help']); ?>
          <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
          <?php print "**59**". render($page['content'])."**88**"; ?>

The starred numbers in the last line for debugging. The output of render($page['content']) is something like the follwoing:

.....

What I need to perform is programmatically change or add class name to

Answer: You can do that in a module/theme by adding a region preprocess hook:
function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $vars['classes_array'][] = 'foo';
  }
}

Comment: Thank you very much. I found another way to do this by modifying `` in region.tpl.php. My theme contain this file, if it is not found in the theme we are able to overwrite it by copying it from modules/system/ and placing it the theme directory.
Comment: Do you mean template.php file?
Comment: Yes - add that, replace `MYTHEME` with name of your theme, and clear the caches. Hopefully you should see the changes straight away

Add class to page content output


Determining probability from categorical variable data

Question: Whist reviewing some test data I am looking for advice on identifying the correct statistical tool(s) to help me answer two questions. The data I am looking at is from a cytotoxicity test, whereby a single categorical variable result is returned for one test. A "0" denotes no cytotoxic response, whilst a "4" denotes the highest possible cytotoxic response. The acceptance criteria is that the cytotoxicity must be equal to or less than 2. I have access to Minitab software for analysis.
I have two sets of data: before and after an event which caused a shift in cytotoxicity results. I want to answer two questions:
1.) Are the proportions of each category significantly different between the two data sets?
2.) What is the probability of producing a score >2 for each sample data set at some point in the future, assuming no other shifts in the process?
I believe I can answer the first question using the Chi-Square Goodness-of-Fit test. However, I feel like I'm clutching at straws for the second question. I am thinking about the binomial probability of success but this only works with attribute data (pass/fail) and not categorical.
A basic bar chart has been included below using some example data to illustrate my point. As you can see the population on the right has a "wider" distribution compared with the left. Assuming I had more data, can I produce a probability that I will receive a score of 3 or 4 at some point in the future?
Answer: OK, I think you only need a simple test of proportions where you are testing that $H_0: p_0 = p_1$ where $p_i$ denotes the population proportion for cytotoxic. In Minitab I believe this is called a two-sample proportion test.
You have 0 cytotoxic responses before our of 133 trials, and 0 out of 133 after.
I think that is exactly as you describe.
If you want more information, I would fit a proportional odds logistic regression model with a single predictor variable (again, before/after), but that would let you model each level of your outcome variable.
Comment: Thanks for your suggestion Paul. You are correct, it is called exactly "2 Proportions" and I can see how that would be used. For the score of 3 you are again correct, the proportions are identical because both sets of data have 0 observations. However, from a logical stand point, if you were to collect an additional n=1,000 data points over time, you would naturally assume that the "after" data set is more likely to contain a 3 compared to the left data set. Is it possible to express this from a statistical point of view, or is it simply 0 because you have not observed it yet?


how can i fix use location error in my react app?

Question: import styled from "styled-components";
import Navbar from "../componant/Navbar";
import Announcement from "../componant/Announcement";
import Products from "../componant/Products";
import Newsletter from "../componant/Newsletter";
import Footer from "../componant/Footer";
import { mobile } from "../responsive";
import { useLocation } from "react-router";
import { useState } from "react";

const Container = styled.div``;

const Title = styled.h1`
  margin: 20px;
`;

const FilterContainer = styled.div`
  display: flex;
  justify-content: space-between;
`;

const Filter = styled.div`
  margin: 20px;
  ${mobile({ width: "0px 20px", display: "flex", flexDirection: "column" })}
`;

const FilterText = styled.span`
  font-size: 20px;
  font-weight: 600;
  margin-right: 20px;
  ${mobile({ marginRight: "0px" })}
`;

const Select = styled.select`
  padding: 10px;
  margin-right: 20px;
  ${mobile({ margin: "10px 0px" })}
`;

const Option = styled.option``;

const ProductList = () => {
  const location = useLocation();
  const cat = location.pathname.split("/")[2];
  const [filters, setFilters] = useState({});
  const [sort, setSort] = useState("newest");

  const handleFilters = (e) => {
    const value = e.target.value;
    setFilters({ ...filters, [e.target.name]: value, });
  };

  return (
    {cat} Filter Products: Color white black red blue yellow green Size XS S M L XL Sort Products:
    <Select onChange={(e) => setSort(e.target.value)}> Newest Price (asc) Price (desc)
  );
};

export default ProductList;

Comment: Error: useLocation() may be used only in the context of a  component.
invariant
C:/Users/hp/packages/react-router/index.tsx:19
  16 | export type { Location, Path, To, NavigationType };
  17 |
  18 | function invariant(cond: any, message: string): asserts cond {
> 19 |   if (!cond) throw new Error(message);
  20 | }
  21 |
  22 | function warning(cond: any, message: string): void {
View compiled
useLocation
C:/Users/hp/packages/react-router/index.tsx:397
  394 |  * @see https://reactrouter.com/docs/en/v6/api#uselocation
  395 |
Comment: Error: useLocation() may be used only in the context of a  component.
invariant
C:/Users/hp/packages/react-router/index.tsx:19
  16 | export type { Location, Path, To, NavigationType };
  17 |
  18 | function invariant(cond: any, message: string): asserts cond {
> 19 |   if (!cond) throw new Error(message);
  20 | }
Answer: The error useLocation() may be used only in the context of a <Router> component. is caused by an invariant violation. The error message is clear enough, you've not rendered the ProductList component using the useLocation hook within a routing context provided by a Router.
This is react-router-dom version 6
useLocation

export function useLocation(): Location {
  invariant(
    useInRouterContext(),
    // TODO: This error is probably because they somehow have 2 versions of the
    // router loaded. We can help them understand how to avoid that.
    `useLocation() may be used only in the context of a <Router> component.`
  );

  return React.useContext(LocationContext).location;
}

You should have a single router wrapping your App component to provide a routing context to the entire app, which would including this ProductList component.
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
);

Based on some comments of yours from the other answer it appears you are mixing up the RRDv5 and RRDv6 components. V6 has no Switch component, it was replaced by a Routes component.
Check the installed version of react-router and react-router-dom:
npm run list react-router react-router-dom

If you have v5 installed, follow the v5 docs, otherwise if you've v6 installed, see the v6 docs. The upgrading from v5 migration guide will detail the differences between the two versions.
Answer: Wrap your app in Routes component.
import React from "react";
import {
  BrowserRouter as Router,
  Routes,
} from "react-router-dom";

const AppWrapper = () => {
  return (
    <Router>
      <Routes>
        <App />
      </Routes>
    </Router>
  );
};

export default AppWrapper;

Comment: i have try this but it didnt work
Comment: @GaethOmari what did you try? Provide please the code you tried
Comment: import Product from "./pages/Product";
import Home from "./pages/Home";
import ProductList from "./pages/ProductList";
import Register from "./pages/Register";
import Login from "./pages/Login";
import Cart from "./pages/Cart"
import { useSelector } from "react-redux";3.

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Redirect,
} from "react-router-dom";
Comment: const App = () => {
  const user = true
  return (

{user ?  : }

          {user ?  : }

Comment:
  );
};

export default App;
Comment: you didn't wrap it by `Routes`


Can't mount ntfs drive anymore ($VOLUME_INFORMATION attribute not found in $Volume)

Question: I have a external hard drive with ntfs partition and it isn't accessible or mountable anymore. Last thing I did was a rsync copy to that usb drive. I still can see the ntfs partition with gnome-disks but I'm not able to mount it.
With gparted and ntfsfix (ntfs-3g package) I get the same error message:
<code>$VOLUME_INFORMATION attribute not found in $Volume
</code>
I also checked the smart data from the drive which is OK (No errors logged, thresholds not nearly reached)
I also checked the hard drive with a second linux client (same behavior) and a windows client (doesn't recognize even the ntfs partition, diskmgnt says it contains a 'raw' partition)
When I'm using testdisk I'm able to see the partition and also list the folders and files. When I want to write the partition details it looks like it worked (no error message from testdisk) but even after a reboot I can't mount my drive and the error message is still the same.
I wonder how can I access the data again without the need to copy it somewhere else (don't have the storage for it)
Answer: I couldn't restore the partition/hard drive itself but were able to restore all my files with testdisk to a second drive with the same size.
I used this 'forced' disk switch to get finally rid of my last ntfs partition and started new with a luks encrypted ext4 file system!


"Syntax error, unexpected T_STRING" problem with goto

Question: http://www.faressoft.org/test/hello.php
My Code :
<?php
echo "hello World";
goto end; // this is line 3
echo "before end";
end:
echo "end";
?>

Error :
Parse error: syntax error, unexpected T_STRING in /home/alfalah1/public_html/faressoft.org/test/hello.php on line 3
It works very well in my localhost but doesn't work in justhost server ? why ?
Comment: @Surreal what does `throw` do, if not exactly the same as goto? ;)
Comment: For the last many years, goto has been declared the bane of good code everywhere.  There are lots of control structures you can use instead of this.  In the end, it makes code to follow.  I learned to code in BASIC where goto was normal, but since then I have not used this since.
Answer:
but doesn't work in justhost server ? why ?

Probably because the remote server isn't running PHP 5.3, which is the minimum required version for goto.
That said, using the goto keyword is generally regarded as an awfully, awfully bad practice from the olden days. I still think this got introduced in PHP because of a lost bet or something. I would not get into the habit of using it.
Comment: Thx Pekka! I found solution, i.e.:
1) CLI doesn't respect .htaccess directives where you can place php version override command,
2) command system('php55-cli script.php'); in script executed by CRON solves the problem.
Comment: How can i know what is the php version ?
Comment: @faressoft `phpinfo();` or `echo PHP_VERSION;`
Comment: phpinfo() will tell you lots of useful information about both the server and PHP.
Comment: @faressoft: Create a php file with just the following content: ``. Open that file in the browser and you get all the information you need (and more).
Comment: @faressoft well, then it's clear why it doesn't work
Comment: On my PHP 5.5 server also getting this error but only if I fire script internally using cron. URL call works fine. Any ideas now?
Comment: @KrzysztofPrzygoda you may be running different PHP versions on the web server and when using the CLI (Command Line Interface).
Comment: OK, this is the clue... Does cron call read php.ini? I'm setting there php version. If not, how to force him?
Comment: @Krzysztof I may not be totally up to date here, but I'm not sure how you can set the PHP version in the php.ini file? Once that file is being read, the PHP interpreter is already running, no?
Comment: This may help http://superuser.com/questions/971867/why-is-the-php-version-different-in-phpinfo-and-cli