text:
Q: Can an integral domain have an element that has no square root but has a square root in the field of fractions? A lemma states:

Let $R$ be a UFD and $F=\operatorname{Frac}(R)$. Let $d\in R$, then equation $a^2=d$ has a root in $R$ iff it has a root in $F$.

So I want to ask, is there a counterexample for this if $R$ is not a UFD?  I only know some non-UFD integral domains like ring of integers for some values.

A: You already have a very good example, but since you mentioned ring of integers, and to put this in a more general context:
A (full) ring of algebraic integers (a maximal order) can never work as a counter-example. The point is that those are (basically by definition) integrally closed.
This means that every element of the fraction field of $R$ that is a root of a monic polynomial over $R$ is already in $R$. Since your equation corresponds to a particular type of monic polynomial having a root, the assertion holds for this one in particular.
However, if you take subrings of rings of algebraic integers (non-maximal orders) you can get examples. For example, in $\mathbb{Z}[2\sqrt{2}]$ the equation $X^2 = 2$ has not solution. But $\sqrt{2}$  is of course in the quotient field.
Let me end with an abstract argument for UFDs having the property you recalled:
A UFD is integrally closed and thus it is also two-root closed (this is a somewhat common name for the property you give).
Put differently, when looking for counter-examples you need to avoid integrally closed domains, since they all still have the property mentioned in your lemma.

A: Let $k$ be a field and $R=k[x^2,x^3]$, the subring of $k[x]$ consisting of polynomials with no linear term.  Taking $d=x^2$, the equation $a^2=d$ has no root in $R$ since $x\not\in R$.  But $x=\frac{x^3}{x^2}$ is an element of the field of fractions $F$, so there does exist a root in $F$.
(To see directly that $R$ is not a UFD, note that $x^2$ and $x^3$ are both irreducible in $R$, but $(x^2)^3=(x^3)^2$, giving two distinct factorizations of $x^6$.)


text:
Q: Performance de file_get_contents() Estou pegando o conteúdo de um Feed RSS gerado pelo Wordpress, e o mesmo tem trazido as informações com um pouco de atraso (segundo o Google PageSpeed Insights, está tendo um delay de 1 a 2.5s).
Gostaria de saber se isso é devido ao meu trecho de código ou do Feed RSS em si.
PS: Ao comentar este trecho de código, o site flui normalmente.
$feed = file_get_contents('http://blog.exal.com.br/feed');
$rss = new SimpleXmlElement($feed);

$contadorNoticias = 0;

foreach($rss->channel->item as $post) {

    if($contadorNoticias < 3){
        $imagemNoticia = "/common/function/thumb.php?largura=730&altura=405&crop=true&imgCrop=center&url=".$post->enclosure['url'];
        $listaNoticia .= "

            link."\" title=\"Ir para: Notícias > ".$post->title."\">
                title."\" class=\"img-responsive\" />

".$post->title."

".str_truncate(strip_tags($post->description),220)." [...]

";
    }
    else{
        break;
    }

    $contadorNoticias++;
}

echo $listaNoticia;

A: Isso ocorre unicamente porque você está baixando um conteúdo externo. Sempre que executa isso ele irá se conectar com o http://blog.exal.com.br/feed, irá procurar o IP do endereço e se conectar, então irá aguardar a resposta do website e obter os dados, fazer o download, depois executar o resto do código baseado no que foi obtido, simples assim.
Se você fizer um:
curl "http://blog.exal.com.br/feed/" -o /dev/null -w "Tempo para conectar: %{time_connect}\nTempo para começar transferencia: %{time_starttransfer}\nTempo Total: %{time_total}"

No Windows utilize: -o null, para remover o alerta de Failed writing body porque não existe /dev/null no Windows. :S
Isso irá informar o tempo que levou para o seu servidor (ou qualquer dispositivo) se conectar e obter os dados do outro website.

Nos meus testes:
Tempo para conectar: 0.154
Tempo para começar transferencia: 1.501
Tempo Total: 1.878

Tempo para conectar: 0.031
Tempo para começar transferencia: 1.406
Tempo Total: 1.406

Tempo para conectar: 0.137
Tempo para começar transferencia: 1.184
Tempo Total: 1.557

...

*

*Tempo para conectar (time_connect): indica o tempo que demora para o CURL criar a conexão TCP até se conectar corretamente com o servidor (ou proxy).

*Tempo para começar transferencia (time_starttransfer): indica o tempo que demora para o CURL receber o primeiro byte de resposta, isso é o tempo que demorou para que o CURL começasse a receber algum dado.

*Tempo Total (time_total): indica o tempo total que demorou para obter o resultado.

Onde esta o problema?
O principal problema está no próprio website que gera o feed (http://blog.exal.com.br/feed), uma vez que ele demora em média 1350 milissegundos para retornar as informações, ou para começar a retornar, assim demorando que o seu website também exiba tais informações.
Como resolver?
Depende, não há informações suficientes na pergunta, a pergunta na verdade foi apenas "Gostaria de saber se isso é devido ao meu trecho de código ou do Feed RSS em si.", isto está respondido acima.
Entretanto, existe algumas soluções que pode fazer NO SEU LADO.
Utilize cache:
Porque precisa se conectar toda hora com o outro site? Ele atualiza de quanto em quanto tempo?
Uma opção é criar fazer um cronjob e salvar num arquivo /cache/feed e carrega-lo sempre.
Crie um atualizaFeed.php:
$getFeed = file_get_contents('http://blog.exal.com.br/feed');
file_put_contents('alguma/pasta/feed.xml', $getFeed);

Crie um cronjob, exemplo: * * * * * php atualizaFeed.php, pode usar o crontab -e para editar via vi.

Você pode simplesmente esquecer o PHP e utilizar diretamente: * * * * * curl "http://blog.exal.com.br/feed/" -o /alguma/pasta/feed.xml. ;)

Depois basta que carregue as informações do arquivo que é atualizado a cada minuto, utilizando:
$feed = file_get_contents('alguma/pasta/feed.xml');
$rss = new SimpleXmlElement($feed);

//...

O arquivo alguma/pasta/feed.xml será sempre atualizado, a cada um minuto. Logo, quando o usuário acessar a página será lido o arquivo que já está no seu servidor, isto é infinitamente mais rápido do que esperar a resposta do servidor externo a cada conexão.

Você também pode criar um banco de dados se quiser e ir atualizando quando houver novas publicações, enfim, várias opções...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap Form group I want this kind of a setup as in the below screenshot.

But currently with the code that I have written, I am getting the below output. I tried various options but unable to get the same output as above.

My current HTML Code:
<form role="form" class="form-horizontal">

                                    Package Name

                                        <input type="text" class="form-control" id="inputPackageName" placeholder="Package Name">

                                    Application
                                        Name

                                        <input type="text" class="form-control" id="inputApplicationName"
                                            placeholder="Package Name">

                            </form>

Any idea as to how to get the required layout as in screenshot. Also how to utilize the white space effectively. i.e. Some labels might require more space, some might require less space. How to have the consistency in bootstrap?

A: Just don't give the class col-sm-2 (in your case) to the labels.
Try to use this layout for the input fields:

        ...
        <input class="form-control" .../>

        ...
        <input class="form-control" .../>

This will render a row with 2 columns. To add more rows just copy the layout

A: Try this:
`.

        ...

        ...

      ...
      <input class="form-control" .../>

      ...
       <input class="form-control" .../>

    ...
    <input class="form-control" .../>

`

A: This should give you what you want (as long as you don't have other CSS rules that could override Bootstrap):
    <form class="form-horizontal">

        Project ID

          <input type="text" class="form-control" id="inputProjectId" placeholder="Project ID">

        Project Name

          <input type="text" class="form-control" id="inputProjectName" placeholder="Project Name">

        Release Date

          <input type="text" class="form-control" id="inputReleaseDate" placeholder="Release Date (mm/dd/yyyy)">

        Supervisor

          <input type="text" class="form-control" id="inputSupervisor" placeholder="Supervisor">

        Project Description

          <textarea class="form-control" id="inputProjectDescriptiond" rows="3" placeholder="Enter Project Description"></textarea>

    </form>

A: Just paste this code:
<form role="form" class="form-horizontal">

                        Project ID

                            <input type="text" class="form-control" id="inputProjectID" placeholder="Project ID">

                        Project Name

                            <input type="text" class="form-control" id="inputProjectName"
                                placeholder="Project Name">

                        Release Date

                            <input type="text" class="form-control" id="inputReleaseDate" placeholder="Release Date (mm/dd/yyyy)">

                        Supervisor

                            <input type="text" class="form-control" id="inputSupervisor" placeholder="Supervisor">

                Project Description

                    <textarea class="form-control" id="inputProjectDescription" rows="3" placeholder="Enter Project Description"></textarea>

    </form>

Hope this will help you!!

A: Finally got a better & easy implementation the same way I wanted.Below is the code!
<form class="form-horizontal" id="main-form" role="form" data- toggle="validator" action="blank.html" method="post">

        Project ID

            <input id="inputProjectID" name="inputProjectID" type="text" placeholder="Your Project ID" class="form-control input-md">

        Project Name

            <input id="inputProjectName" name="inputProjectName" type="text" placeholder="Your Project Name" class="form-control input-md">

            Release Date

                <input id="datepicker" name="inputReleaseDate" type="text" placeholder="Select Release Date" class="form-control input-md">

            Supervisor

                <input id="textinput" name="textinput" type="text" placeholder="Your Supervisor's Name" class="form-control input-md">

        Project Description

            <textarea style="resize: none;" rows="3" class="form-control" id="inputProjectDesc" name="inputProjectDesc" placeholder="Your Project Description"></textarea>

</form>


text:
Q: starting Android Device Monitor from Android Studio in Ubuntu 14.10 I am trying to start Android device monitor from Android Studio, but I get this error message

A Java Runtime Environment (JRE) or Java Development Kit (JDK)
  must be available in order to run Monitor. No Java virtual machine
  was found after searching the following locations:
  /home/agusgambina/Android/Sdk/tools/lib/monitor-x86_64/jre/bin/java
  java in your current PATH

If in a terminal I execute
$ javac -version

I get this
javac 1.7.0_80

So I have declared the java compiler on the PATH, I don't know what I have to change to make it work
Thank you

A: This problem had troubled me a long time.
I found a solution:

*

*open termimal

*cd {you sdk home path}/tools/lib/monitor-x86_64

*mkdir jre

*cd jre

*ln -s {you java home path}/bin bin
To find your Java home path type:
echo $JAVA_HOME

If nothing appears type: export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
Actually, I just created a link to your Java home. But I am confused why Android Studio finds Java in this path.

A: Look at your path environment variable (echo $PATH) to see where the OS is finding java.
Verify that the path to java is the same as the path that android-studio is assuming it to be. (/home/agusgambina/Android/Sdk/tools/lib/monitor-x86_64/jre/bin/java in your case)
If they are not the same, you will have to tell android-studio the correct path to java.
(I believe the option can be found at File->Other Settings->Default Project Structure->SDKs)
b.t.w.
javac is different from java
javac is the java compiler
java is the JVM exectuable (this is the one that is relevant in your problem)

A: go to your Android Studio JDK path (If you don't know then see it from File->Other Settings->Default Project Structure->SDKs in android studio)
(in ubuntu it is normally /usr/local/jdk1.x.x)
inside jdk folder copy jre folder
and paste it to your android studio assuming path which is in your case
"/home/agusgambina/Android/Sdk/tools/lib/monitor-x86_64/"
paste it inside monitor-x86_64 folder in sdk
Hope this will work!

A: What worked for me was just
sudo apt-get install default-jdk
then restart Android Studio and the Device Monitor worked

A: Create a new file or edit the existing file called .bash_profile in your home directory:
E.g. vi ~/.bash_profile
Insert the following lines and adopt the paths to where your jdk is installed (probably it won't be /home/anuradha/installs/jdk1.7.0_02:
JAVA_HOME=/home/anuradha/installs/jdk1.7.0_02
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
JRE_HOME=/home/anuradha/installs/jdk1.7.0_02
PATH=$PATH:$HOME/bin:$JRE_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Source the .bash_profile, e.g. by calling . ~/.bash_profile or by opening a new terminal.
Check the java version by running java -version.

A: You can make sure the location of the JRE in Project Structure UI which is in File menu. And then you just link the jre directory in  {you sdk home path}/tools/lib/monitor-x86_64.


text:
Q: Wierd XML not being parsed I'm facing a strange problem with parsing xml with libxmljs.
It's not my first XML to parse and I've done quite a number of them, but this one acts really strange.
I'm having these namespaces:
var nsUri = {
        "xmlns:SOAP-ENV": "http://schemas.xmlsoap.org/soap/envelope/",
        "xmlns:SIG": "https://sigtest.tais.ru/SIG/"
    };

And doing this:
var xmlDoc = xmljs.parseXml(providerResponse);
var ShopOptions = xmlDoc.find('//ShopOptions/ShopOption',self.provider.nsUri);

Which results in zero length array. I'm trying to go for different xquery stings: */ShopOption, //ShopOption etc. But nothing works out.

A: The <ShopOption/> element inherits the namespace of its <SIG_Response/> ancestor, https://sigtest.tais.ru/SIG/. You already declared that namespace, but also have to use it.
//SIG:ShopOptions/SIG:ShopOption

The other two queries you tried also don't use namespaces. */ShopOption looks for all second-level <ShopOption/> children starting at the current context, probably the root here; //ShopOption also searches for elements without namespace.


text:
Q: Apple watch: How to scroll only table contents, and not the whole watch user interface? To learn watch programming, I have set up a little test app that consists only of an image and a table:

The app is executed by the iOS and watch simulators. Image and table contents are correctly set by the app.
When the table is too long to fit completely on the watch screen, I expected that tapping on the table would allow it to scroll the table contents.
However, the complete watch content is scrolled, including the image (please note that the green disk has been scrolled half out of sight):

What do I have to do to keep the image fixed on the screen, yet allow the table contents to vertically scroll?

A: While the private API supports what you want to do, that feature isn't publicly available to us either in watchOS 2 or watchOS 3.
We're limited to either the entire interface scrolling (when its content is larger than the screen size), or the entire interface not scrolling at all (when its content fits within the screen size).
You may want to submit a feature request asking for a static group, sticky table row header, or scrolling region.
What comes close...
The new WKCrownSequencer and WKCrownDelegate would let you interact with a scene or specific interface object, but there's no way to override the system's gesture recognition and scroll support on behalf of the entire scrolling interface controller.
I don't think there's an elegant way to implement what you want now, that would work perfectly.
If you're determined to hack or rethink this...
If you don't want to wait for Apple to eventually offer proper support for what you want, here are a few options which might help you approach this from a different direction.

*

*Try replacing the table with a picker. The picker would let you scroll through different items on the smaller screen, but it obviously won't look like a table.

*Limit your table to a fixed number of rows which didn't exceed the screen size. You could update the row content as the crown scrolls but it would be a paging effect rather than a scrolling effect.

*Drop down to Core Graphics to either draw the location activity indicator, or the table text to create the illusion that a portion of the screen is (not) scrolling.

*Change the background color of table's row(s), and let the background color function as the location activity indicator.

A: In watchOS 3 just set any object as a delegate by:
let crownSequencer = WKExtension.shared().rootInterfaceController!.crownSequencer
crownSequencer.delegate = self
crownSequencer.focus()

Then read back the value by implementing:
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double)


text:
Q: document.onload without images or other elements (just HTML) I need to trigger a document.onload kinda event, but I want it to be triggered just when the HTML is completely loaded, without waiting for images or other elements.
I've been looking arround but I can't find something like that. Is there any way to do it?
Thanks!

A: You could just put a <script> tag with your code right at the bottom just before your </body> with the code to execute.
There's nothing to guarentee that images won't be loaded. But it certainly won't wait until they are loaded before it runs.

A: Use the DOMContentLoaded event:
https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/DOMContentLoaded

The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).

(and just for the heck of it, but with jQuery: $(document).ready(function () {});)

A: I don't remember a specific event for that, but you can trigger your event by putting this just before your last closing html tag:
...
    <script type="text/javascript">
        html_loaded(); // Custom function call
    </script>
</html>

That should work very effectively for any purpose.
HTH
Francisco

A: The DOMContentLoaded event proposed by @Ian would work, but it is in the HTML5 specification and therefore would not be supported by legacy browsers like IE8.
Other wise I think @Chris Farmiloe's script solution is the best way to go.


text:
Q: C# element to create a specifiy json output from a C# aspnet core controller I produce the following output :
[
{
    "info": {
        "type": 6,
        "message": "a message"
    }
},
{
    "detail": {
        "type": 8,
        "something": "a different thing"
     }
}
]

I'm doing this at the moment with:
Dictionary<string, object> Result = new Dictionary<string, object>();
Result.Add("info", new Info() { Type = 6, message = "a message"});
Result.Add("detail", new Detail() { Type = 8, something = "a different thing" });
JsonConvert.SerializeObject(new object[] { _Errors });

But this won't work when it comes to an output like this:
[
{
    "info": {
        "type": 6,
        "message": "a message"
    }
},
{
    "info": {
        "type": 6,
        "message": "another message"
     }
}
]

Since this would need duplicate keys in the dictionary I have no idea how which structure will produce this output.
KeyValuePair wont work since this results in "key": "info"... and so on.
Also a class with several members using the same JsonProperty attribute wont work since the number of elements is dynamic.

A: I assume what you want is this output:
[
  {
    "Info": {
      "Type": 5,
      "Message": "A message 1"
    }
  },
  {
    "Info": {
      "Type": 6,
      "Message": "A message 3"
    }
  },
  {
    "Info": {
      "Type": 7,
      "Message": "A message 2"
    }
  },
  {
    "Error": {
      "Type": 8,
      "Something": "A different thing"
    }
  }
]

Implement your own JsonConvert, here is an example that provides the above serialization
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace JsonSerialization
{
    public class ResultsEntrySerializer : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var entry = value as IResultsEntry;
            if (entry == null) throw new ArgumentException("Cannot convert parameter", nameof(value));
            writer.WriteStartObject();
            writer.WritePropertyName(entry.Name);
            serializer.Serialize(writer, entry.Entry);
            writer.WriteEndObject();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            //TODO: I leave this up to the reader
            throw new NotImplementedException();
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.GetInterfaces().Contains(typeof(IResultsEntry));
        }
    }

    [JsonConverter(typeof(ResultsEntrySerializer))]
    interface IResultsEntry
    {
        string Name { get; }
        object Entry { get; set; }
    }

    class Info
    {
        public int Type { get; set; }
        public string Message { get; set; }
    }

    class InfoEntry : IResultsEntry
    {
        string IResultsEntry.Name => "Info";

        object IResultsEntry.Entry
        {
            get => Entry;
            set => Entry = (Info)value;
        }

        public Info Entry { get; set; }
    }

    class Detail
    {
        public int Type { get; set; }
        public string Something { get; set; }
    }

    class DetailEntry : IResultsEntry
    {
        string IResultsEntry.Name => "Error";

        object IResultsEntry.Entry
        {
            get => Entry;
            set => Entry = (Detail)value;
        }

        public Detail Entry { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<IResultsEntry>
            {
                new InfoEntry
                {
                    Entry = new Info { Type = 5, Message = "A message 1" }
                },
                new InfoEntry
                {
                    Entry = new Info { Type = 6, Message = "A message 3" }
                },
                new InfoEntry
                {
                    Entry = new Info { Type = 7, Message = "A message 2" }
                },
                new DetailEntry
                {
                    Entry = new Detail { Type = 8, Something = "A different thing" }
                }
            };
            Console.WriteLine(JsonConvert.SerializeObject(list));
            Console.ReadLine();
        }
    }
}

Also, if you want them lowercase that's trivial too see this Stackoverflow post: Json keys lowercase

A: sorry for the confusion. After checking the things a bit I found (not really) a solution.
I came up with a dictionary which has a special key.
Json.Net just uses ToString() for the dictionary keys so something like this seemed to do what I wanted.
    public class DupKey {
    public string Name { get; set; }
    public int Index { get; set; }
    public override string ToString() {
        return Name;
    }
    public override bool Equals(object obj) {
        if(!(obj is DupKey)) return false;
        return Index == ((DupKey)obj).Index;
    }
    public override int GetHashCode() {
        return Index.GetHashCode();
    }
}

But finally I found that this produces a wrong result.
Last not least I found a solution (without the need for an own serializer) which gives the correct result.
Since this looks some kind of universal for me I post it here.
    public class DynamicJsonEntry : DynamicObject {
    private string _JsonName;
    public object Element { get; set; }
    public DynamicJsonEntry(string pJsonName, object pElement) : this(pJsonName) {
        Element = pElement;
    }
    public DynamicJsonEntry(string pJsonName) {
        if(string.IsNullOrWhiteSpace(pJsonName)) {
            throw new ArgumentNullException(nameof(pJsonName));
        }
        _JsonName = pJsonName;
    }
    public override IEnumerable<string> GetDynamicMemberNames() {
        yield return _JsonName;
        foreach(var prop in GetType().GetProperties().Where(a => a.CanRead && a.GetIndexParameters().Length == 0 && a.Name != nameof(Element))) {
            yield return prop.Name;
        }
    }
    public override bool TryGetMember(GetMemberBinder pBinder, out object pResult) {
        if(pBinder.Name == _JsonName) {
            pResult = Element;
            return true;
        }
        return base.TryGetMember(pBinder, out pResult);
    }
}

Now I can add any entry with the name I want simply like this:
List<DynamicJsonEntry> lRet = new List<DynamicJsonEntry>();
lRet.Add(new DynamicJsonEntry("info", new Info() { Type = 6, message = "a message" }));
lRet.Add(new DynamicJsonEntry("detail", new Detail() { Type = 8, something = "a different thing" }));
lRet.Add(new DynamicJsonEntry("info", new Info() { Type = 6, message = "a second message" }));

Thank you Joachim for your help.


text:
Q: Service creation loop using range function in Helm I am trying to create k8s service of type load balancer using range loop in helm.I need to create k8s service pointing to dedicated POD.I have deployed 3 pods, up and running.I am trying to create 3 services pointing to 3 different pods.
{{- $replicas := .Values.replicaCount | int -}}
{{- $namespace := .Release.Namespace  }}
{{- range $i,$e := until $replicas }}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-{{ $i }}
  name: service-{{ $i }}
  namespace: {{ $namespace  }}
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: {{  . | printf ".Value.ports.port_%d" | int }}
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-{{ $i }}
  type: LoadBalancer
{{- end }}

my values.yaml
ports:
  port_1: 30001
  port_2: 30002
  port_3: 30003
replicaCount: 3

dry-run is giving below put:
# Source: t1/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-0
  name: service-0
  namespace: xyz
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: 0
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-0
  type: LoadBalancer
---
# Source: t1/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-1
  name: service-1
  namespace: xyz
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: 0
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-1
  type: LoadBalancer
---
# Source: t1/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  labels:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-2
  name: service-2
  namespace: xyz
spec:
  ports:
  - protocol: TCP
    targetPort: 2000
    port: 0
  selector:
    app: abc-svc
    statefulset.kubernetes.io/pod-name: abc-2
  type: LoadBalancer

I need port number pointing to correct port in according to values.yaml file.For service-0,service-1,service-2 I need 30001,30002,30002 ports assigned.Please suggest.Thank you !!

A: To do the dynamic lookup in the port list, you need to use the index function.  This is part of the standard Go text/template language and not a Helm extension:
port: {{ index .Values.ports (add $i 1 | printf "port_%d") }}

This could be slightly simpler if you change the list of ports to be a list and not a map:
# values.yaml
ports:
  - 30001
  - 30002
  - 30003
replicaCount: 3

port: {{ index .Values.ports $i }}

If you didn't require access to specific pods from outside the cluster, a StatefulSet creates a cluster-internal DNS name for each pod on its own, and you could avoid this loop entirely.


text:
Q: Pandoc: Images intersect with codeblock I am generating a pdf with pandoc (source is markdown) and as latex formatting is want to do, the images sometimes go onto the next page and not exactly where they are inside the content.
This is okay, but my latest version of a document has an image which is intersecting a code block.
code here

IMAGE + image tile
code continues

For obvious reasons this is jarring and not what I expected to happen.  Is there a way to fix this?  I do not want to inline the image (everything about how the image is displayed is how I want it, except its location).
Thanks!

A: The answer is on @Fran comment. It's simple, you either add a backslash plus a blank line or a \newpage after the image.
![Alt text](image.png)
\
{blank line here}

or
![Alt text](image.png)
\newpage


text:
Q: CC-mode indentation of C++ lambda functions with a return type that has template parameters I am using CC-mode in Emacs that was installed with apt on Ubuntu 20.04.
It formats code as follows:
#include <vector>
int main() {
  auto f1 = [](int a) {
              return std::vector<int>({a});
            };
  auto f2 = [](int a) -> std::vector<int> {
                                           return std::vector<int>({a});
  };
}

In my opinion, format for f1 is acceptable but f2 not.  Is there a way
to have it format f2 as in f1?  Or, more preferably, as in the following,
which was achieved with CC-mode installed on Ubuntu 16.04.
#include <vector>
int main() {
  auto f1 = [](int a) {
    return std::vector<int>({a});
  };
  auto f2 = [](int a) -> std::vector<int> {
    return std::vector<int>({a});
  };
}

My current workaround is as follows, but not ideal:
  using vector_t = std::vector<int>;
  auto f2wa = [](int a) -> vector_t {
                return vector_t({a});
              };

A: If you use google-set-c-style.el from melpa you get your preferred formatting,
#include <vector>
int main() {
  auto f1 = [](int a) {
    return std::vector<int>({a});
  };
  auto f2 = [](int a) -> std::vector<int> {
    return std::vector<int>({a});
  };
}

In general, with cc-modes, you can play around with c-guess to examine and set the style rules until you find what you want.


text:
Q: PHP readfile return data (my first question on stack, so sorry for errors and/or inaccuracies...)
So : I've developed a Wordpress Theme and I'd like my users to download the attachments of a post. So I created a Zip Archive and use a readfile(). The function is called by link and using a $_GET['zip'] test.
The Problem : readfile() returns (i mean display) binary characters like this (here I tried to download a test .png file) : �PNG  IHDRp�r�*�  pHYs�� OiCCPPhotoshop ICC profilexڝSgTS�=���BK���KoR
And nothing is downloaded.
Here my code (the readfile part) :
$zip = new ZipArchive();
if ($zip->open($file_path.$archive_file_name, ZIPARCHIVE::CREATE)!==TRUE) {
  exit("cannot open <$archive_file_name>\n");
}
foreach($file_names as $file){
  $zip->addFile($file,$file);
}
$zip->close();
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($file_path.$file).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path.$file));
ob_clean();
flush();
readfile($file_path.'screenshot.png');

I don't know where to search, and it's my first time with zip archive AND readfile()...
Thanks for the tracks (? do we say that? ) !

A: I don't know how exactly but it works now. I added an ob_start() just at the beginning of the function. Thanks for support !
The entire function :
if (!function_exists('zipThoseFiles')) {
    ob_start();
    function zipThoseFiles($id){
        if (!function_exists('zipFilesDownload')) {
            function zipFilesDownload($file_names,$archive_file_name,$file_path){
                $zip = new ZipArchive();
                if ($zip->open($file_path.$archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
                  exit("cannot open <$archive_file_name>\n");
                }
                foreach($file_names as $file){
                  $zip->addFile($file,$file);
                }
                $zip->close();

                header('Content-Description: File Transfer');
                header('Content-Type: application/zip');
                header('Content-Disposition: attachment; filename="'.basename($file_path.$archive_file_name).'"');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($file_path.$archive_file_name));
                ob_end_clean();
                flush();
                readfile($file_path.$archive_file_name);
                unlink($file_path.$archive_file_name);
                exit;
            }
        }
        $fileNames = array();
        $args = array(
            'post_type' => 'attachment',
            'numberposts' => null,
            'post_status' => null,
            'post_parent' => $id
        );
        $attachments = get_posts($args);
        if ($attachments) {
            foreach ($attachments as $attachment) {
                $fileNames[] = get_attached_file( $attachment->ID );
            }
        }
        $zip_file_name = 'mediasArchive.zip';
        $file_path = dirname(__FILE__).'/';
        zipFilesDownload($fileNames,$zip_file_name,$file_path);
    }
}


text:
Q: best way to upload uint8_t array to azure blob storage with wastorage in c++ I would like to upload a uint8_t array to azure storage using the azure storage SDK. I m struggling to construct the input stream from the array, I managed to get something that compile by using a std::vector but that require an extra copy of the array.
Do you think of a better way?
void upload(azure::storage::cloud_blob_container container, const wchar_t* blobName, const uint8_t * data, size_t dataLength) {

    std::vector<uint8_t> bytes(dataLength, (const unsigned char)data);
    concurrency::streams::bytestream byteStream = concurrency::streams::bytestream();
    concurrency::streams::istream inputStream = byteStream.open_istream(bytes);

    const utility::string_t myBlobName(blobName);
    azure::storage::cloud_block_blob blockBlob = container.get_block_blob_reference(myBlobName);
    blockBlob.upload_from_stream(inputStream);

    inputStream.close();
}

the upload_from_stream method requieres a concurrency::streams::istream but I don't know how to construct if from a basic array
thank you by advance

A: I managed to find a better solution using rawptr_buffer:
void BlobService::upload(cloud_blob_container container, const wchar_t* blobName, const uint8_t * data, size_t dataLength) {

    rawptr_buffer<uint8_t> buffer(data, dataLength);
    istream inputStream = buffer.create_istream();

    cloud_block_blob blob = container.get_block_blob_reference(utility::string_t(blobName));
    blob.upload_from_stream(inputStream);

    inputStream.close().wait();
    buffer.close().wait();

}


text:
Q: Is there an easy way to return a string repeated X number of times? I'm trying to insert a certain number of indentations before a string based on an items depth and I'm wondering if there is a way to return a string repeated X times.  Example:
string indent = "---";
Console.WriteLine(indent.Repeat(0)); //would print nothing.
Console.WriteLine(indent.Repeat(1)); //would print "---".
Console.WriteLine(indent.Repeat(2)); //would print "------".
Console.WriteLine(indent.Repeat(3)); //would print "---------".

A: If you only intend to repeat the same character you can use the string constructor that accepts a char and the number of times to repeat it new String(char c, int count).
For example, to repeat a dash five times:
string result = new String('-', 5);
Output: -----

A: most performant solution for string
string result = new StringBuilder().Insert(0, "---", 5).ToString();

A: public static class StringExtensions
{
    public static string Repeat(this string input, int count)
    {
        if (string.IsNullOrEmpty(input) || count <= 1)
            return input;

        var builder = new StringBuilder(input.Length * count);

        for(var i = 0; i < count; i++) builder.Append(input);

        return builder.ToString();
    }
}

A:         string indent = "---";
        string n = string.Concat(Enumerable.Repeat(indent, 1).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 2).ToArray());
        string n = string.Concat(Enumerable.Repeat(indent, 3).ToArray());

A: Adding the Extension Method I am using all over my projects:
public static string Repeat(this string text, int count)
{
    if (!String.IsNullOrEmpty(text))
    {
        return String.Concat(Enumerable.Repeat(text, count));
    }
    return "";
}

Hope someone can take use of it...

A: For many scenarios, this is probably the neatest solution:
public static class StringExtensions
{
    public static string Repeat(this string s, int n)
        => new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}

Usage is then:
text = "Hello World! ".Repeat(5);

This builds on other answers (particularly @c0rd's). As well as simplicity, it has the following features, which not all the other techniques discussed share:

*

*Repetition of a string of any length, not just a character (as requested by the OP).

*Efficient use of StringBuilder through storage preallocation.

A: If you're using .NET 4.0, you could use string.Concat together with Enumerable.Repeat.
int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));

Otherwise I'd go with something like Adam's answer.
The reason I generally wouldn't advise using Andrey's answer is simply that the ToArray() call introduces superfluous overhead that is avoided with the StringBuilder approach suggested by Adam. That said, at least it works without requiring .NET 4.0; and it's quick and easy (and isn't going to kill you if efficiency isn't too much of a concern).

A: Surprised nobody went old-school.
I am not making any claims about this code, but just for fun:
public static string Repeat(this string @this, int count)
{
    var dest = new char[@this.Length * count];
    for (int i = 0; i < dest.Length; i += 1)
    {
        dest[i] = @this[i % @this.Length];
    }
    return new string(dest);
}

A: I like the answer given. Along the same lines though is what I've used in the past:
"".PadLeft(3*Indent,'-')

This will fulfill creating an indent but technically the question was to repeat a string. If the string indent is something like >-< then this as well as the accepted answer would not work. In this case, c0rd's solution using StringBuilder looks good, though the overhead of StringBuilder may in fact not make it the most performant. One option is to build an array of strings, fill it with indent strings, then concat that. To whit:
int Indent = 2;

string[] sarray = new string[6];  //assuming max of 6 levels of indent, 0 based

for (int iter = 0; iter < 6; iter++)
{
    //using c0rd's stringbuilder concept, insert ABC as the indent characters to demonstrate any string can be used
    sarray[iter] = new StringBuilder().Insert(0, "ABC", iter).ToString();
}

Console.WriteLine(sarray[Indent] +"blah");  //now pretend to output some indented line

We all love a clever solution but sometimes simple is best.

A: Strings and chars [version 1]
string.Join("", Enumerable.Repeat("text" , 2 ));
//result: texttext

Strings and chars [version 2]:
String.Concat(Enumerable.Repeat("text", 2));
//result: texttext

Strings and chars [version 3]
new StringBuilder().Insert(0, "text", 2).ToString();
//result: texttext

Chars only:
new string('5', 3);
//result: 555

Extension way:
(works FASTER - better for WEB)
public static class RepeatExtensions
{
    public static string Repeat(this string str, int times)
    {
        var a = new StringBuilder();

        //Append is faster than Insert
        ( () => a.Append(str) ).RepeatAction(times) ;

        return a.ToString();
    }

    public static void RepeatAction(this Action action, int count)
    {
        for (int i = 0; i < count; i++)
        {
            action();
        }
    }

}

usage:
 var a = "Hello".Repeat(3);
 //result: HelloHelloHello

A: Use String.PadLeft, if your desired string contains only a single char.
public static string Indent(int count, char pad)
{
    return String.Empty.PadLeft(count, pad);
}

Credit due here

A: You can repeat your string (in case it's not a single char) and concat the result, like this:
String.Concat(Enumerable.Repeat("---", 5))

A: Print a line with repetition.
Console.Write(new string('=', 30) + "\n");

==============================

A: For general use, solutions involving the StringBuilder class are best for repeating multi-character strings. It's optimized to handle the combination of large numbers of strings in a way that simple concatenation can't and that would be difficult or impossible to do more efficiently by hand. The StringBuilder solutions shown here use O(N) iterations to complete, a flat rate proportional to the number of times it is repeated.
However, for very large number of repeats, or where high levels of efficiency must be squeezed out of it, a better approach is to do something similar to StringBuilder's basic functionality but to produce additional copies from the destination, rather than from the original string, as below.
    public static string Repeat_CharArray_LogN(this string str, int times)
    {
        int limit = (int)Math.Log(times, 2);
        char[] buffer = new char[str.Length * times];
        int width = str.Length;
        Array.Copy(str.ToCharArray(), buffer, width);

        for (int index = 0; index < limit; index++)
        {
            Array.Copy(buffer, 0, buffer, width, width);
            width *= 2;
        }
        Array.Copy(buffer, 0, buffer, width, str.Length * times - width);

        return new string(buffer);
    }

This doubles the length of the source/destination string with each iteration, which saves the overhead of resetting counters each time it would go through the original string, instead smoothly reading through and copying the now much longer string, something that modern processors can do much more efficiently.
It uses a base-2 logarithm to find how many times it needs to double the length of the string and then proceeds to do so that many times. Since the remainder to be copied is now less than the total length it is copying from, it can then simply copy a subset of what it has already generated.
I have used the Array.Copy() method over the use of StringBuilder, as a copying of the content of the StringBuilder into itself would have the overhead of producing a new string  with that content with each iteration. Array.Copy() avoids this, while still operating with an extremely high rate of efficiency.
This solution takes O(1 + log N) iterations to complete, a rate that increases logarithmically  with the number of repeats (doubling the number of repeats equals one additional iteration), a substantial savings over the other methods, which increase proportionally.

A: I would go for Dan Tao's answer, but if you're not using .NET 4.0 you can do something like that:
public static string Repeat(this string str, int count)
{
    return Enumerable.Repeat(str, count)
                     .Aggregate(
                        new StringBuilder(str.Length * count),
                        (sb, s) => sb.Append(s))
                     .ToString();
}

A: Another approach is to consider string as  IEnumerable<char> and have a generic extension method which will multiply the items in a collection by the specified factor.
public static IEnumerable<T> Repeat<T>(this IEnumerable<T> source, int times)
{
    source = source.ToArray();
    return Enumerable.Range(0, times).SelectMany(_ => source);
}

So in your case:
string indent = "---";
var f = string.Concat(indent.Repeat(0)); //.NET 4 required
//or
var g = new string(indent.Repeat(5).ToArray());

A: Not sure how this would perform, but it's an easy piece of code.  (I have probably made it appear more complicated than it is.)
int indentCount = 3;
string indent = "---";
string stringToBeIndented = "Blah";
// Need dummy char NOT in stringToBeIndented - vertical tab, anyone?
char dummy = '\v';
stringToBeIndented.PadLeft(stringToBeIndented.Length + indentCount, dummy).Replace(dummy.ToString(), indent);

Alternatively, if you know the maximum number of levels you can expect, you could just declare an array and index into it.  You would probably want to make this array static or a constant.
string[] indents = new string[4] { "", indent, indent.Replace("-", "--"), indent.Replace("-", "---"), indent.Replace("-", "----") };
output = indents[indentCount] + stringToBeIndented;

A: I don't have enough rep to comment on Adam's answer, but the best way to do it imo is like this:
public static string RepeatString(string content, int numTimes) {
        if(!string.IsNullOrEmpty(content) && numTimes > 0) {
            StringBuilder builder = new StringBuilder(content.Length * numTimes);

            for(int i = 0; i < numTimes; i++) builder.Append(content);

            return builder.ToString();
        }

        return string.Empty;
    }

You must check to see if numTimes is greater then zero, otherwise you will get an exception.

A: Using the new string.Create function, we can pre-allocate the right size and copy a single string in a loop using Span<char>.
I suspect this is likely to be the fastest method, as there is no extra allocation at all: the string is precisely allocated.
 public static string Repeat(this string source, int times)
 {
     return string.Create(source.Length * times, source, RepeatFromString);
 }

 private static void RepeatFromString(Span<char> result, string source)
 {
     ReadOnlySpan<char> sourceSpan = source.AsSpan();
     for (var i = 0; i < result.Length; i += sourceSpan.Length)
         sourceSpan.CopyTo(result.Slice(i, sourceSpan.Length));
 }

dotnetfiddle

A: You can create an ExtensionMethod to do that!
public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    string ret = "";

    for (var x = 0; x < count; x++)
    {
      ret += str;
    }

    return ret;
  }
}

Or using @Dan Tao solution:
public static class StringExtension
{
  public static string Repeat(this string str, int count)
  {
    if (count == 0)
      return "";

    return string.Concat(Enumerable.Repeat(indent, N))
  }
}

A: I didn't see this solution. I find it simpler for where I currently am in software development:
public static void PrintFigure(int shapeSize)
{
    string figure = "\\/";
    for (int loopTwo = 1; loopTwo <= shapeSize - 1; loopTwo++)
    {
        Console.Write($"{figure}");
    }
}


text:
Q: Hyper-prparameter tuning and classification algorithm comparation I have a doubt about classification algorithm comparation.
I am doing a project regarding hyperparameter tuning and classification model comparation for a dataset.
The Goal is to find out the best fitted model with the best hyperparameters for my dataset.
For example: I have 2 classification models (SVM and Random Forest), my dataset has 1000 rows and 10 columns (9 columns are features) and 1 last column is lable.
First of all, I splitted dataset into 2 portions (80-10) for training (800 rows) and tesing (200rows) correspondingly. After that, I use Grid Search with CV = 10 to tune hyperparameter on training set with these 2 models (SVM and Random Forest). When hyperparameters are identified for each model, I use these hyperparameters of these 2 models to test Accuracy_score on training and testing set again in order to find out which model is the best one for my data (conditions: Accuracy_score on training set < Accuracy_score on testing set (not overfiting) and which Accuracy_score on testing set of model is higher, that model is the best model).
However, SVM shows the accuracy_score of training set is 100 and the accuracy_score of testing set is 83.56, this means SVM with tuning hyperparameters is overfitting. On the other hand, Random Forest shows the accuracy_score of training set is 72.36 and the accuracy_score of testing set is 81.23. It is clear that the accuracy_score of testing set of SVM is higher than the accuracy_score of testing set of Random Forest, but SVM is overfitting.
I have some question as below:
_ Is my method correst when I implement comparation of accuracy_score for training and testing set as above instead of using Cross-Validation? (if use Cross-Validation, how to do it?
_ It is clear that SVM above is overfitting but its accuracy_score of testing set is higher than accuracy_score of testing set of Random Forest, could I conclude that SVM is a best model in this case?
Thank you!

A: I would suggest splitting your data into three sets, rather than two:

*

*Training

*Validation

*Testing

Training is used to train the model, as you have been doing. The validation set is used to evaluate the performance of a model trained with a given set of hyperparameters. The optimal set of hyperparameters is then used to generate predictions on the test set, which wasn't part of either training or hyper parameter selection. You can then compare performance on the test set between your classifiers.
The large decrease in performance on your SVM model on your validation dataset does suggest overfitting, though it is common for a classifier to perform better on the training dataset than an evaluation or test dataset.

A: For your second question, yes your SVM would be overfitting although in most machine-learning cases, the training set's accuracy would not really matter. It is much more important to look at the testing set's accuracy. It is not unusual to have a higher training accuracy than testing accuracy so I suggest to not look to overfitting and only look at the difference in the testing accuracy. With the information provided, yes you could say that the SVM is the best model in your case.
For your first question, you are already doing a type of cross validation and it is an acceptable way to do evaluate the model.
This might be a useful article for you to read

A: It's good that you've done quite an analysis on your part to investigate the best model. However, I would suggest you elaborate on your investigation a bit. As you're searching for the best model for your data, "Accuracy" alone is not a good evaluation metric for your models. You should also evaluate your model on "Precision Score", "Recall Score", "ROC", "Sensitivity", "Specificity" etc. Find out if your data has imbalance (If they do, there're techniques to work 'em around). After evaluating all those metrics you may come up with a decision.
For the training-testing part, you're quite on the right track, with only one issue (which is quite severe), the time you're testing your model on the test set, you're injecting a sort of bias. So I would say make 3 partitions of your data, and use cross-validation (sklearn has got what you need for this) on your "training set", after cross-validation, you may use another partition "validation set" for testing the generalization power of your model (performance on unseen data), you may change some parameter after that. And after you've come up to a conclusion and tuning everything you needed to, only then use your "test set". No matter what the results are (on the test set) don't change the model after that, as those scores represent the true capability of your model.
you can create 3 partitions of your data in the following way for example-
from sklearn.model_selection import train_test_split
 from sklearn.datasets import make_blobs

#  Dummy dataset for example purpose
 X, y = make_blobs(n_samples=1000, centers=2, n_features=2, cluster_std=6.0)

# first partition i.e. "train-set" and "test-set"
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.9, random_state=123)

# second partition, we're splitting the "train-set" into 2 sets, thus creating a new partition of "train-set" and "validation-set"
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, train_size=0.9, random_state=123)

print(X_train.shape, X_test.shape, X_val.shape)  # output : ((810, 2), (100, 2), (90, 2))


text: Q: Ghost external drive in disk utility I noticed recently when I open up disk utility and I see my external hard drive show up even though nothing is connected to my Mac. I can't unmount it and it does not do anything. Just wondering, is this just a bug in my system or is there something wrong with my Mac?


text:
Q: Hive error : Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable I am facing an error when I try to query a table in hive when hive uses spark. For example, when I do:
select count(*) from ma_table;

I get this:
Exception in thread "main" java.lang.NoClassDefFoundError: scala/collection/Iterable
    at org.apache.hadoop.hive.ql.parse.spark.GenSparkProcContext.<init>(GenSparkProcContext.java:163)
    at org.apache.hadoop.hive.ql.parse.spark.SparkCompiler.generateTaskTree(SparkCompiler.java:195)
    at org.apache.hadoop.hive.ql.parse.TaskCompiler.compile(TaskCompiler.java:267)
    at org.apache.hadoop.hive.ql.parse.SemanticAnalyzer.analyzeInternal(SemanticAnalyzer.java:10947)
    at org.apache.hadoop.hive.ql.parse.CalcitePlanner.analyzeInternal(CalcitePlanner.java:246)
    at org.apache.hadoop.hive.ql.parse.BaseSemanticAnalyzer.analyze(BaseSemanticAnalyzer.java:250)
    at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:477)
    at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1242)
    at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1384)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1171)
    at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1161)
    at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:232)
    at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:183)
    at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:399)
    at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:776)
    at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:714)
    at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:641)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.util.RunJar.run(RunJar.java:234)
    at org.apache.hadoop.util.RunJar.main(RunJar.java:148)
Caused by: java.lang.ClassNotFoundException: scala.collection.Iterable
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 more

After some research, I tried to had this to my bashrc (and sourced it ;) ) :
for f in ${HIVE_LIB}/*.jar; do
    CLASSPATH=${CLASSPATH}:$f;
done

 for f in ${SPARK_HOME}/jars/*.jar; do
     CLASSPATH=${CLASSPATH}:$f;
 done

for f in ${SCALA_HOME}/lib/*.jar; do
     CLASSPATH=${CLASSPATH}:$f;
done

I checked and I have all these jars in the CLASSPATH and still get the error.
I am using Hive 2.1, Hadoop 2.8 and Spark 2.1.
Any ideas? Thanks a lot by advance!

A: After coming back to it, I found that scala jars files weren't in the lib of Hive.
If you are facing something similar, have a look there:
https://www.linkedin.com/pulse/hive-spark-configuration-common-issues-mohamed-k


text:
Q: Set defaultvalue of sp-pnp-js created boolean field I'm unable to set the default value to false of my boolean field called Done
pnp.sp.web.lists.add("Todo","").then(() => {
  pnp.sp.web.lists.getByTitle("Todo").fields.add("Done","SP.FieldText",{
    FieldTypeKind: 8,
    Hidden: false
  }).then(() => {

  });
});

Does anyone have an idea, because I can't find any documentation on this.

A: You can try setting the xml schema of the field:
pnp.sp.web.lists.getByTitle("Todo").fields.createFieldAsXml('<Field
    Type="Boolean"
    DisplayName="Done"
    Required="FALSE"
    Indexed="FALSE"
    ID="{f1c6f202-f976-4f4e-b0a3-8b984991d00d}"
    StaticName="Done"
    Name="Done" >
<Default>false</Default>
</Field>').then(f => {
    console.log(f);
});


text:
Q: PowerBI Embedded report hangs on loading when rendered by Javascript API I'm trying to embed a PowerBI report into my web app, that is running locally in my dev server, with the Javascript API. I know everything is working since I succesfully rendered the desired report in their Playground, so it can't be a problem with the Embedded Server or Azure. In my console window there are multiple warnings and errors of external resources blocked by the same origin policy, and an uncaught exception: [object Object] error probably related to the PBI Javascript API that i can't decipher. The report just loads forever, displaying the animated PowerBI logo. Is anybody else experiencing this issue while trying to embed a report locally? Here's the code responsible for rendering:
var embedContainer = $("#container");
var models = window.['powerbi-client'].models;

    var config= {
        type: 'report',
        tokenType: models.TokenType.Embed,
        accessToken: ginormous embed token,
        embedUrl: https://app.powerbi.com/reportEmbed?reportId=ommited_for_privacy&groupId=ommited_for_privacy,
        id: the_report_id,
        permissions: models.Permissions.All,
        settings: {
                filterPaneEnabled: true,
                navContentPaneEnabled: true
        }
    };

    // Embed the report and display it within the div container.
    var report = powerbi.embed(embedContainer.get(0), config);

    // Report.off removes a given event handler if it exists.
    report.off("loaded");

    // Report.on will add an event handler which prints to Log window.
    report.on("loaded", function() {
        Log.logText("Loaded");
    });

    report.on("error", function(event) {
        Log.log(event.detail);

        report.off("error");
    });

    report.off("saved");
    report.on("saved", function(event) {
        Log.log(event.detail);
        if(event.detail.saveAs) {
                Log.logText('In order to interact with the new report, create a new token and load the new report');
        }
    });

Here are all the console errors:
uncaught exception: [object Object]

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://dc.services.visualstudio.com/v2/track. (Reason: CORS request did not succeed).

Source map error: request failed with status 404
Resource URL: http://localhost:3000/temp/scripts/App.js

Source Map URL: powerbi.js.map
Source map error: request failed with status 404
Resource URL: https://app.powerbi.com/13.0.5314.162/scripts/ai.0.js

Source Map URL: ai.0.js.map
Source map error: request failed with status 404
Resource URL: https://app.powerbi.com/13.0.5314.162/scripts/reportembed.externals.bundle.min.js

Source Map URL: interact.min.js.map

A: My bad guys.
The problem is that Firefox did not show the reason of the exception, but Chrome did. I should've tested in another browser before asking. With the exception text, I could track the problem to a typo in the tokenType parameter and it worked just fine.


text:
Q: Why does getaddrinfo sometimes behave differently with "example.com" and "www.example.com"? This is a code example from MSDN: getaddrinfo.
You can use "baidu.com" and "www.baidu.com" to test.

A: Because baidu.com and www.baidu.com are different addresses!
www.example.com is registered in DNS with an A type record (or a CNAME, which points to an A record - this is slightly simplified) An A record is a name, in this case www that points to an IP Address 12.34.56.78. (as I'm sure you already know!)
example.com can also have an A record registered (though not a CNAME) this is called the Apex (or naked!) domain. example.com's A record could very well point to 123.45.67.89
A little history
Part of the reason that this came about, is that in the early days of the internet, a server would have a hostname of something like LOCUS.UC.EDU because it can be difficult to know what services LOCUS might provide. you could attach the CNAME FTP.UC.EDU to point to that machine. that way people knew what services it offered. at that point, www was just another service, it had no special place in the collective consciousness. (all of this was happening over the decade or two that the internet was developing!) but you could also quite probably want bob@UC.EDU to work. so UC.EDU needed to be a host name also
In actual fact it started with just the hostname (and host records that got telexed - I do love that fact) - but we'll ignore that for this case.
back to the facts
What usually - should - happen is that there is an A record registered at the Apex and a CNAME registered at www But there is certainly no requirement for this and you can have whatever records you wish at your domain.


text:
Q: Conditional operator assignment with Nullable types? EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),

I often find myself wanting to do things like this (EmployeeNumber is a Nullable<int> as it's a property on a LINQ-to-SQL dbml object where the column allows NULL values).  Unfortunately, the compiler feels that

There is no implicit conversion between 'null' and 'int'

even though both types would be valid in an assignment operation to a nullable int on their own.
Using the null coalescing operator is not an option as far as I can see because of the inline conversion that needs to happen on the .Text string if it's not null.
As far as I know the only way to do this is to use an if statement and/or assign it in two steps.  In this particular case I find that very frustrating because I wanted to use the object initializer syntax and this assignment would be in the initialization block...
Does anyone know a more elegant solution?

A: I think a utility method could help make this cleaner.
public static class Convert
{
    public static T? To<T>(string value, Converter<string, T> converter) where T: struct
    {
        return string.IsNullOrEmpty(value) ? null : (T?)converter(value);
    }
}

then
EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);

A: The problem occurs because the conditional operator doesn't look at how the value is used (assigned in this case) to determine the type of the expression -- just the true/false values.  In this case, you have a null and an Int32, and the type can not be determined (there are real reasons it can't just assume Nullable<Int32>).
If you really want to use it in this way, you must cast one of the values to Nullable<Int32> yourself, so C# can resolve the type:
EmployeeNumber =
    string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? (int?)null
    : Convert.ToInt32(employeeNumberTextBox.Text),

or
EmployeeNumber =
    string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : (int?)Convert.ToInt32(employeeNumberTextBox.Text),

A: While Alex provides the correct and proximal answer to your question, I prefer to use TryParse:
int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
    ? (int?)value
    : null;

It's safer and takes care of cases of invalid input as well as your empty string scenario.  Otherwise if the user inputs something like 1b they will be presented with an error page with the unhandled exception caused in Convert.ToInt32(string).

A: You can cast the output of Convert:
EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
   ? null
   : (int?)Convert.ToInt32(employeeNumberTextBox.Text)

A: //Some operation to populate Posid.I am not interested in zero or null
int? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;
var x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;

EDIT:
Brief explanation of above, I was trying to get the value of Posid (if its nonnull int and having value greater than 0) in varibale X1. I had to use (int?) on Posid.Value to get the conditional operator not throwing any compilation error.
Just a FYI GetHolidayCount is a WCF method that could give null or any number.
Hope that helps

A: As of C# 9.0, this will finally be possible:

Target typed ?? and ?:
Sometimes conditional ?? and ?: expressions don't have an obvious shared type between the branches. Such cases fail today, but C# 9.0 will allow them if there's a target type that both branches convert to:
Person person = student ?? customer; // Shared base type
int? result = b ? 0 : null; // nullable value type

That means the code block in the question will also compile without errors.
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
    ? null
    : Convert.ToInt32(employeeNumberTextBox.Text),


text:
Q: Test FTP connection with PHP I am using the PHP script below to test FTP connections.  Currently it is printing an array of the files, if it successfully connects.
How can I get it to also display a message, if it is able to connect?  Like 'Connection Successful'.
$con = ftp_connect($server) or die("Couldn't connect");
ftp_login($con,  $username,  $password);
print_r(ftp_nlist($con, "."));
ftp_close($con);

EDIT
I have it working now but, I've tested this on a few domains I have on a MediaTemple server and they all seem be timing out. Yet, it works with all other domains I have tried. Are their servers blocking the request?

A: Hey.  I'm new here so maybe posting this late answer is not welcome, but it may help people in the future.
The reason why it's not working with MediaTemple is because they only accept passive connections.
After logging in with ftp_login(), simply call ftp_pasv($ftp, TRUE); and you'll be set.

A: Hello I have tried this..Working properly.
set_time_limit(300);//for setting
$path='/'.date('dmY').'';
$ftp_server='';
$ftp_server_port="";
$ftp_user_name='';
$ftp_user_pass="";

// set up a connection to ftp server
$conn_id = ftp_connect($ftp_server, $ftp_server_port);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);

// check connection and login result
if ((!$conn_id) || (!$login_result)) {
    echo "Fail
";
} else {
    echo "Success
";
    // enabling passive mode
    ftp_pasv( $conn_id, true );
    // get contents of the current directory
    $contents = ftp_nlist($conn_id, $path);
    // output $contents
    var_dump($contents);
}

// close the FTP connection
ftp_close($conn_id);

A: While I agree with the logic in the accepted answer from @Jakub of calling ftp_nlist() and testing data type with is_array(), this can be very slow and cumbersome with particularly large, bloated ftp directories like the ones I am currently working on. And I don't like the idea of creating a blank directory just for testing, which can be renamed/removed later as considered to be unneeded, perhaps by another developer or because you forgot what it was placed there for.
I am using a passive ftp connection, so for my purpose on cron scripts that can take a long time to execute and potentially require reconnection, I detect using this:
function check_connection_status($conn_id) {
    return ftp_pasv($conn_id, true);
}

Issuing a fresh call to ftp_pasv() will make no alteration to the state of the ftp connection, but it will respond true if the connection is active and logged in/false if not so you can program to reconnect again :)

A: Both ftp_connect() and ftp_login() return a boolean indicating success. Thus, something like this should do what you want, if I'm interpreting properly:
try {
    $con = ftp_connect($server);
    if (false === $con) {
        throw new Exception('Unable to connect');
    }

    $loggedIn = ftp_login($con,  $username,  $password);
    if (true === $loggedIn) {
        echo 'Success!';
    } else {
        throw new Exception('Unable to log in');
    }

    print_r(ftp_nlist($con, "."));
    ftp_close($con);
} catch (Exception $e) {
    echo "Failure: " . $e->getMessage();
}

A: Note that you're already dieing when you fail to connect, so you can assume that you are connected. However, you can also check the status of the connection using:
echo $con !== FALSE ? 'Connected' : "Couldn't connect";

ftp_connect: Returns a FTP stream on success or FALSE on error.

A: Simply do a check if ftp_nlist() is an array.
Like:
echo is_array(ftp_nlist($con, ".")) ? 'Connected!' : 'not Connected! :(';
References:

*

*http://php.net/manual/en/function.is-array.php

*http://php.net/manual/en/function.ftp-nlist.php


text:
Q: Angular modal instance can't read DOM elements Hi im playing with angular modal instance..
But when i declare a querySelector in the modal controler it gives console error of Cannot read property 'querySelector' of null
HTML

                    <canvas width="300" height="300"></canvas>

Sign above

                    <button class="button clear" data-action="clear">Clear</button>

        <button class="btn btn-success btn-lg" ng-click="ok();">Gem & Godkend</button>
        <button class="btn btn-warning btn-lg" ng-click="cancel()">Annuler</button>

JS - ModalInstanceController
var ModalInstanceCtrl = function ($scope, $modalInstance) {

            $scope.init = function() {
                var wrapper = document.getElementById("signature-pad"),
                    clearButton = wrapper.querySelector("[data-action=clear]"),
                    canvas = wrapper.querySelector("canvas"),
                    signaturePad;

                signaturePad = new SignaturePad(canvas);

                clearButton.addEventListener("click", function (event) {
                    signaturePad.clear();
                });
                $scope.ok = function () {
                    $modalInstance.close(signaturePad.toDataURL());
                };

                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };

            };

        $modalInstance.opened.then($scope.init);

        };

So it seams like it, can't find dom elements in model .. :s
As you i can i tried to load, model into dom first with    $modalInstance.opened.then($scope.init);
But this dosen't work either

A: Umm seams that DOM elements needed to be loaded first.. found my answer here https://github.com/angular-ui/bootstrap/issues/2586
    $scope.init = function() {
var wrapper = document.getElementById("signature-pad"),
...
}
$modalInstance.opened.then($scope.init);

this initialize the dom elemtens first, so query selector can see the dom elements ! :)
i just need'ed
 in html

A: Controller is instantiated before template is loaded and injected in DOM. In general this is not very good idea do perform such DOM manipulations in controller. You should create directive for this. For example:
add.directive('signaturePad', function() {
    return {
        link: function(scope, element) {

            var wrapper = element[0],
                clearButton = wrapper.querySelector("[data-action=clear]"),
                saveButton = wrapper.querySelector("[data-action=save]"),
                canvas = wrapper.querySelector("canvas"),
                signaturePad;

            signaturePad = new SignaturePad(canvas);

            clearButton.addEventListener("click", function (event) {
                signaturePad.clear();
            });
        }
    };
});

and use it like this:

    <canvas width="100" height="100"></canvas>

Sign above

    <button class="button clear" data-action="clear">Clear</button>
    <button class="button save" data-action="save">Save</button>

A: I concur with dfsk, that's a more elegant solution, just make sure that, if this is is part of a bootstrap ui-tab, do not forget to add an ng-if="activeTab=2", where 2 is the zero-indexed tab where the signature-pad lives. activeTab is a scope variable containing the current tab. And wait till the DOM updates (via $timeout(fn(){})). That's when the right dimensions of the canvas element can be accessed and handled nicely.


text:
Q: Phrases for filling stomach "The food was so bad that I couldn't eat even just to (fill my stomach?)."
What would fit in there?

A: Satisfy my hunger.
The word satisfy is commonly used here, including this definition from TheFreeDictionary:

to put an end to (a desire, want, need, etc.) by sufficient or ample provision: to satisfy one's hunger.

A: fulfill my caloric content
More technically accurate and not completely unrealistic to hear said in a sentence.

A: Sustenance: something (such as food) that keeps someone or something alive.
"The food was so bad that I couldn't eat even for sustenance."
One could also use survive/survival.
"The food was so bad that I couldn't eat even just to survive."

A: sate TFD

*

*To satisfy (an appetite) fully.

As in:

The food was so bad that I couldn't eat even to just sate my
  appetite.


text:
Q: Finding the circumradius-to-inradius ratio for the regular pentagon
Find the value of $R/r$:

I go with co-ordinate geometry, considering the centre of the circles is at the origin, then the equation of the circle becomes as
$$ x^2 + y^2 = R^2 $$
$$ x^2 + y^2 = r^2 $$
After this I not able to solve this.
2nd Attempt :-

A: The hint:
Let $ABCDE$ be our regular pentagon, $O$ be a center of the circles and $T$ be a touching point to $AB$.
Thus, $OT=r$, $OA=R$ and $\measuredangle ATO=90^{\circ}.$
Hence, $$\measuredangle AOT=\frac{360^{\circ}}{5\cdot2}=36^{\circ}$$ and
$$AT=R\sin36^{\circ}=r\tan36^{\circ}.$$
Can you end it now?


text:
Q: Return a value for use in different class I have the class BossInfo which extends JPanel and has a few components like JLabel, JTextField. My main method is in another file ("DamageCalculator").
Basically, a value is entered into a JTextField via an action listener and I'd like to pass that value to a different file (to use it in calculations). I'm having a lot of trouble with the logic. Here is my class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BossInfo extends JPanel {

    private JLabel      bossLabel, resultLabel;
    private JTextField  bossHp;
    String bossHpText = new String("");
    int valRecd = 0;

    public BossInfo() {
        //Labels
        bossLabel = new JLabel("Boss HP: (Hit Enter to set)");
        resultLabel = new JLabel("---");
        //Text field for user input of boss hp
        bossHp = new JTextField(15);
        bossHp.addActionListener(new TempListener());

        //add components
        add(bossLabel);
        add(bossHp);
        add(resultLabel);

    } //end BossInfo object

    public void setVal(int valRecd) {
        this.valRecd = valRecd;
    }

    private class TempListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            int hp;
            bossHpText = bossHp.getText();
            hp = Integer.valueOf(bossHpText);
            dc.setVal(hp);
            resultLabel.setText(bossHpText);
        }//end action performed
    }//end TempListener
} //end class BossInfo

How can I use bossHpText in another class? The "actionPerformed" gets mad if it's any return type other than void so I'm not sure it's meant to return anything.
EDIT: Code updated based on suggestions.

A: Have a variable valRecd in the MainClass.
On your actionPerformed, call the setter method for this valRecd, e.g,
MainClass obj = new MainClass();   //in your constructor.

public void actionPerformed(ActionEvent event) {
        int hp;
        bossHpText = bossHp.getText();
        hp = Integer.parseInt(text);
        obj.setVal(hp);                   //add this line.
        resultLabel.setText(bossHpText);
}

where setVal might be something like this:
public void setVal(int valRecd) {
    this.valRecd = valRecd;
}


text: Q: Conceptual understanding of silk damping CMB anisotropies are washed out below the silk damping scale, because photons travel out of overdense regions. However does silk damping also damp matter perturbations (through scattering) on scales of order of the expected photon travel distance? Or is this effect too tiny to be measured in the matter power spectrum?


text:
Q: Get and count documents in Mongodb I'm using mongodb aggregation pipeline to fetch some data.
After several stages of filtering in my aggregation, I want to have the count of the document before I move to the stage of pagination (sort, skip & limit).
The choice I've had was to use $facet, which helped me to do it:
db.collection.aggregate([
  {
    ...
    $matching and filtering documents
    ...
  },
  {
    $facet: {
      data: [
        { $sort: { "price": -1 } },
        { $skip: 0 },
        { $limit: 10 },
      ],
      count: [{ $count: "totalItems" }],
    },
  },
]);

The issue is that, in the sorting stage, $facet doesn't make use of indexes, and that leads to a big amount of time to perform the operation (large amount of data).
I want to learn an efficient way to have an output like:
{ data: data, count: totalItems }

A: In your case specifically, assuming your pipeline qualifies for index usage on the $sort stage, just move it to be before the $facet stage. you are going to sort the entire collection as it is, so there's no benefit of having it within the $facet:
db.collection.aggregate([
  {
    ...
    $matching and filtering documents
    ...
  },
  { $sort: { "price": -1 } },
  {
    $facet: {
      data: [
        { $skip: 0 },
        { $limit: 10 },
      ],
      count: [{ $count: "totalItems" }],
    },
  },
]);


text:
Q: how to override the product controller in admin panel how to override the catalog/product/new action, but I am not understanding where I start. I have searched on different forums but I couldn't get any idea.
I have tried it by overriding the copy in local but could not succeed.

A: To override the product controller follow this
create file in app/etc/modules/Solsint_Proextended.xml
<?xml version="1.0"?>
<config>
  <modules>
    <Solsint_Proextended>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </Solsint_Proextended>
  </modules>
</config>

create file in app/code/local/Solsint/Proextended/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Solsint_Proextended>
<version>0.1.0</version>
</Solsint_Proextended>
</modules>

<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <Solsint_Proextended before="Mage_Adminhtml">Solsint_Proextended</Solsint_Proextended>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

</config>

and at the end create file in app/code/local/Solsint/Proextended/controllers/catalog/ProductController.php
<?php
include_once("Mage/Adminhtml/controllers/Catalog/ProductController.php");
class Solsint_Proextended_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
{

public function newAction()
{
  echo "Working"; exit; //do here what you want to do
}
}

this is tested code. hope it will be helpful for you.

A: Create a small module for overriding the Controller.let see step by step for overriding
Step 1:- Create YourPackageName_Adminhtml.xml file at app/etc/
<?xml version="1.0"?>
<config>
  <modules>
    <YourPackageName_Adminhtml>
      <active>true</active>
      <codePool>local</codePool>
    <YourPackageName_Adminhtml>
  </modules>
</config>

Step 2:- Create config.xml file at app/code/local/YourPackageName/Adminhtml/etc/config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <YourPackageName_Adminhtml>
            <version>0.0.1</version>
        </YourPackageName_Adminhtml>
    </modules>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <yourpackagename_adminhtml before="Mage_Adminhtml">YourPackageName_Adminhtml</yourpackagename_adminhtml>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
</config>

Step 3:- Create ProductController.php controller file at app/code/local/YourPackageName/Adminhtml/controllers/Catalog/ProductController.php
<?php
    include_once("Mage/Adminhtml/controllers/Catalog/ProductController.php");
    class YourPackageName_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
    {
        public function newAction()
        {
            // echo "done"; exit;
        }
    }
?>

Note:- for more information on overriding the create new product in admin refer http://magento-online-tutorials.blogspot.in/2015/10/how-to-override-create-new-product.html

A: *

*You can use phpstorm and magicento plugin for easy override anything you want.

*Class name for rewrite Mage_Adminhtml_Catalog_ProductController

*Rewrite class may be not best way to do what you want. You should try use observers first.

require_once 'Mage/Adminhtml/controllers/Catalog/ProductController.php';
class YOURMODULENAMESPACE_YOURMODULENAME_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Catalog_ProductController
{
    public function newAction()
    {
        ...
    }

}
And add rewrite to controller address:

        <rewrite>            <module_catalog_product>                <from><![CDATA[#^/.*/catalog_product/new/#]]></from>               <to>/YOURCONTROLLERADDRESS/adminhtml_catalog_product/new/</to>            </module_catalog_product>        </rewrite>


text:
Q: OpenGL VBO Memory Leak I am having some issues with the memory with a very simple OpenGL application that I wrote to learn VBOs. The memory it uses readily increases the longer it is open.  Below is code the duplicates what I am seeing using Windows Task Manager:
int main() {

sf::RenderWindow window(sf::VideoMode(800, 600, 32), "Test");

///Setup the scene, materials, lighting
Scene scene;
scene.resize(800,600);

glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION);
glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_FLAT);
glEnable(GL_LIGHT0);
float XL = .5, YL = .1, ZL = 1;
GLfloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
GLfloat diffuseLight[] = { 0.8f, 0.8f, 0.8, 1.0f };
GLfloat specularLight[] = { 0.5f, 0.5f, 0.5f, 1.0f };
GLfloat lightpos[] = {XL, YL, ZL, 0.};
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
glLightfv(GL_LIGHT0, GL_POSITION, lightpos);

glGenBuffersARB = (PFNGLGENBUFFERSARBPROC)wglGetProcAddress("glGenBuffersARB");
glBindBufferARB = (PFNGLBINDBUFFERARBPROC)wglGetProcAddress("glBindBufferARB");
glBufferDataARB = (PFNGLBUFFERDATAARBPROC)wglGetProcAddress("glBufferDataARB");
glBufferSubDataARB = (PFNGLBUFFERSUBDATAARBPROC)wglGetProcAddress("glBufferSubDataARB");
glDeleteBuffersARB = (PFNGLDELETEBUFFERSARBPROC)wglGetProcAddress("glDeleteBuffersARB");
glGetBufferParameterivARB = (PFNGLGETBUFFERPARAMETERIVARBPROC)wglGetProcAddress("glGetBufferParameterivARB");
glMapBufferARB = (PFNGLMAPBUFFERARBPROC)wglGetProcAddress("glMapBufferARB");
glUnmapBufferARB = (PFNGLUNMAPBUFFERARBPROC)wglGetProcAddress("glUnmapBufferARB");

GLfloat vertices[] = { .5, .5, .5,  -.5, .5, .5,  -.5,-.5, .5};

GLuint VBOID;
glGenBuffersARB(1, &VBOID);
glBindBufferARB(GL_ARRAY_BUFFER_ARB, VBOID);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, 108, vertices, GL_STATIC_DRAW_ARB);

///Start loop
cout << "Starting" << endl;
while( window.isOpen() ) {
    sf::Event event;
    while( window.pollEvent( event ) ) {
        if( event.type == sf::Event::Closed )
            window.close();
    }

    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, 1.0, 1.0, 50);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(5, 5, 5, 0, 0, 0, 0, 1, 0);

    glBindBufferARB(GL_ARRAY_BUFFER_ARB, VBOID);
    glEnableClientState(GL_VERTEX_ARRAY);

    glVertexPointer(3, GL_FLOAT, 0, 0);
    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableClientState(GL_VERTEX_ARRAY);

    ///Reset env settings for SFML
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

    window.display();
}

return 1;

}
EDIT:
Commenting out all event polling changes nothing. The window clearing doesnt seem to make a difference if I use window.clear() or opengl's clear function.
With further commenting out I was able to figure out that the one line of code, window.display(), is causing my memory leak. Ill see if the guys at the SFML forums can figure this one out ;)

A: I can't see anything in your draw loop that should cause this behaviour.
I think you should try the SFML forum : http://en.sfml-dev.org/forums/
There are several threads about this issue :

*

*http://en.sfml-dev.org/forums/index.php?topic=8609.0

*http://en.sfml-dev.org/forums/index.php?topic=8092.0

*http://en.sfml-dev.org/forums/index.php?topic=7146.0
The developers mostly claim that this is a driver issue. You could try to disable all your draw code and see if that changes anything. Use window.clear() instead? Remove the event polling?


text:
Q: display div elements in parent with overflow hidden I have a div with class container. I have 3 more divs inside .container. What I want is to display internal divs float: left so that 2 divs tags are visible inside .container and the third one is invisible and is placed on the right side of first 2 div tags which are visible. I am trying the following code but it makes all tags visible all the time.
jsfiddle

css
.container {
            position: relative;
            width: 405px;
            height: 500px;
            background: red;
            margin: 0 auto;
            overflow: hidden;
        }
        .div {
            width: 200px;
            height: 200px;
            background: blue;
            float: left;
            border: 1px solid red;
        }

I want above to look like this

A: You can do as such in other way,
HTML

CSS
.container {
    position: relative;
    width: 405px;
    height: 500px;
    background: red;
    margin: 0 auto;
    overflow: hidden;
}
.innerContainer {
    position: relative;
    width: 605px;
    height: 500px;
    overflow: hidden;
}
.div {
    width: 200px;
    height: 200px;
    background: blue;
    float: left;
    border: 1px solid red;
}

Check over here http://jsfiddle.net/nftp6/8/

A: Use:
display: inline-block;
white-space: nowrap;

For that effect
Fiddle:
http://jsfiddle.net/Hive7/nftp6/5/

A: Use display:inline-block instead of float and set white-space:nowrap to the container:
.container {
    position: relative;
    width: 405px;
    height: 500px;
    background: red;
    margin: 0 auto;
    overflow: hidden;
    white-space: nowrap;
}
.div {
    width: 200px;
    height: 200px;
    background: blue;
    display: inline-block;
    border: 1px solid red;
}

Demo fiddle
Now you'll most likely face some white-space issues, read this answer for multiple ways to handle that


text:
Q: Retrieve index in LinQ Lambda Join I'm quite new to all the .Net stuff and just wondering about something I would like to do.
I've been using for some time the LinQ Lambda queries to return list values with the Select statement, like this:
        var data = list.Select((x, i) =>
            new
            {
                Index = i,       // <--- this is what I need!
                Value = x.Value,
                Text = x.Text
            })
            .ToList();

The thing is that I have a LinQ Lambda Join expression as it follows:
        var data = DataBase.Table1
            .Join(DataBase.Table2,
                x => x.Id,
                y => y.Id,
                (x, y) => new    // <--- I can't do the same here :(
                {
                    Index = ???, // <--- Here is where I need the index!!
                    Value = x.Id,
                    Text = y.Description,
                })
            .OrderBy(x => x.Id)
            .ToList();

My question is, how can I retrieve the index in this second linq query as I did in the first?

A: You can't use Select<T>(Func<T,int,bool>) with Linq to SQL. You will see NotSupportedException if you'll try to execute your first query:

Unsupported overload used for query operator 'Select'

You can use this operator with Linq to Objects. Just move query execution to memory with AsEnumerable() call. With your second query add another projection after you received result of join and moved execution to memory:
 var data = DataBase.Table1
            .Join(DataBase.Table2,
                t1 => t1.Id,
                t2 => t2.Id,
                (t1, t2) => new { Value = t1.Id, Text = t2.Description }
            )
            .AsEnumerable() //otherwise next operator cannot be translated to SQL
            .Select((x,i) => new { x.Value, x.Text, Index = i})
            .OrderBy(x => x.Value)
            .ToList();

UPDATE: If you want index of t2, then you can use GroupJoin instead of Join:
 var data = DataBase.Table1
            .GroupJoin(DataBase.Table2,
                t1 => t1.Id,
                t2 => t2.Id,
                (t1, t2items) => new { Value = t1.Id, t2items }
            )
            .AsEnumerable() //otherwise next operator cannot be translated to SQL
            .SelectMany(x => x.t2items.Select((t2, i) =>
               new { x.Value, Text = t2.Description, Index = i}))
            .OrderBy(x => x.Value)
            .ToList();

If you need both indexes, then move whole join to memory:
 var data = DataBase.Table1.AsEnumerable().Select((t1,i) => new { t1, i })
            .Join(DataBase.Table2.AsEnumerable().Select((t2,i) => new { t2, i }),
                  x1 => x1.t1.Id,
                  x2 => x2.t2.Id,
                  (x1, x2) => new {
                      Value = x1.t1.Id,
                      Text = x2.t2.Description,
                      Index1 = x1.i,
                      Index2 = x2.i
                  })
            .OrderBy(x => x.Value)
            .ToList();


text:
Q: Question about polynomial ring and coefficients Let $R=k[x_0,...,x_n]$ be the polynomial ring in $n+1$ variables and let $F=c_1f_1+ \cdots +c_kf_k \in R$ with $c_i \in k$. Is it possible to multiply $F$ with some element from $k$ such that the coefficients of all $f_i$ becomes the same? I.e does it exist an $a \in k$ such that $a \cdot F=cf_1+ \cdots +cf_k$?

A: As $a F = a c_1 f_1 + \dots + a c_k f_k$, the questions is really if given
$c_1 , \dots, c_k$ there is an $a$ such that $ac_1 = \dots = ac_k$.
However, if $a\neq 0$, then $a c_i = a c_j $ if and only if $c_i = c_j$.
While for $a=0$ of course $ac_i = ac_j$.
Thus, yes $a=0$ works, but this might not be what you want.
Other than that, no, except the $c_i$ are all equal in the first place.


text:
Q: Creating a trigger which could not be disabled in SQL Server 2005 It is possible to create an trigger (with DBO) on a table which could not be disabled (even by DBO or the sa user)?
I need this trigger for licensing/permission purposes on a piece of software which is deployed on the SQL Server of clients. The problem occurs when the clients try to use an old version of my software and disable the triggers I created.

A: Not possible, if this happens there is deadlock condition, so all software don't want this.
Also it will make system prone to hackers, so you need to understand that this is not possible , sa user or Admin can everytime update rights.
You need to think some other approach like saving licensing in encrypted form, or some code around to fix up such kind of issues


text:
Q: Breakpoint ignored because generated code not found I am trying to set a breakpoint in Visual Studio Code under Windows 7 using the Chrome Debugger extension for an Angular 4 project that was generated by the Angular CLI.  I am getting the error message:  Breakpoint ignored because generated code not found
Here is what I have for my tsconfig.json
{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2016",
      "dom"
    ]
  }
}

Here is what I have for my launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:4200",
            "webRoot": "${workspaceRoot}",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                     "webpack:///./*": "${workspaceRoot}\\*"
            }
        },
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 9222,
            "webRoot": "${workspaceRoot}"
        }
    ]
}

A: I figured out the problem.  The Visual Studio Code Debugger only works with specific combinations of versions for the Debugger for Chrome, Angular CLI, and Angular.  It does not work with Angular 4.0 with the 1.0 version of Angular CLI.  However Angular 4.1.3 and Angular CLI 1.0.6 work fine.  Follow these steps:

*

*Install the Chrome Debugger Visual Code Extension

*On the Debug menu, click Open Configurations

*Modify your .vscode\launch.json to look like this:
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:4200",
            "webRoot": "${workspaceRoot}"
        },
        {
            "type":"chrome",
            "request": "launch",
            "name": "Launch Chrome against Karma",
            "url": "http://localhost:9876/?id=9792346",
            "webRoot": "${workspaceRoot}"
        }
    ]
}

*CLOSE All Chrome Browsers

*Run npm start at the command line in the directory for your application

*Set a breakpoint in the code

*Press Control-F5 in the browser


text:
Q: Spring Scheduled should start immediate after application startup I have a requirement to add schedulers, which will run on a daily basis, but at the same time, I want to run the scheduler on the application startup. But the problem is schedular is not running immediately after application startup.

A: You can implement the ApplicationRunner interface and execute your business logic in the run method
@Component
public class TaskRun implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // do something
    }
}

A: Finally, I solved this by using a listener in the Application.java
@EventListener(ApplicationReadyEvent.class)
public void doSomethingOnceAppIsReady() {
    //Calling a schedular method
    mySchedular();
}


text:
Q: PHP SQL functions don't return valid SQL datatype So I am using the following functions to grab the datatype of certain fields in an SQL database.
$type  = mysql_field_type($result, $i);
$len   = mysql_field_len($result, $i);

I need to use these datatypes to ultimately structure another table. The problem is the returns I am getting from these functions are not valid SQL datatypes, I am getting returns like this: string (25), int (11), string (25)
Int is ok but string is not an SQL datatype, so do I need to figure out which returns need to be reformatted into correct datatypes and make functions to do that? Or am I missing another way to do it?

A: you will see that the mysql_field_type() function will return the following data as per (http://it2.php.net/mysql_field_type):
CHAR, VARCHAR, TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT, ENUM, SET: string
TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT: int
FLOAT, DOUBLE, DECIMAL, NUMERIC: real
TIMESTAMP: timestamp
YEAR: year
DATE: date
TIME: time
DATETIME: datetime
TINYBLOB, MEDIUMBLOB, LONGBLOB, BLOB: blob

Perhaps you can rather try something like:
$table = "my_table";
$result = mysql_query("DESCRIBE TABLE `{$tabler}`");
while ($row = mysql_fetch_object($result)) {
    $field = $row->Field;
    $type = $row->Type;
}

Hope that helps.

A: Try running a query like this:
SELECT column_type FROM information_schema.columns WHERE table_schema = 'databaseName' AND table_name = 'tableName' AND column_name = 'columnName';

A: Thats because mysql_field_len returns the schema length if it exists

Will get the length of the id field as specified in the database
http://php.net/manual/en/function.mysql-field-len.php

Also string is a valid return for mysql_field_type, not sure what the issue is.
Example
<?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows   = mysql_num_rows($result);
$table  = mysql_field_table($result, 0);
echo "Your '" . $table . "' table has " . $fields . " fields and " . $rows . " record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
    $type  = mysql_field_type($result, $i);
    $name  = mysql_field_name($result, $i);
    $len   = mysql_field_len($result, $i);
    $flags = mysql_field_flags($result, $i);
    echo $type . " " . $name . " " . $len . " " . $flags . "\n";
}
mysql_free_result($result);
mysql_close();
?>

Ref: http://www.php.net/manual/en/function.mysql-field-type.php