text:
Q: MySQL - Atualizar coluna com valor de data brasileira Estou atualizando uma tabela num banco com mais de 100 mil registros para poder realizar futuros SELECTS para gerar um relatório estatistico.
A tabela atualmente tem uma coluna 'Nascimento' do tipo varchar(10) que armazena a data de nascimento do cliente no formato 'dd/mm/yyyy'. Como está em varchar está demorando por volta de 2 minutos para terminar a query.
Então criei uma coluna chamada 'data_nascimento' do tipo date e estou tentando usar o seguinte código para converter os valores da coluna 'Nascimento':
update cadastros_dados set data_nascimento = STR_TO_DATE(nascimento,'%d%m%Y')

Mas dá o seguinte erro:
[Err] 1411 - Incorrect datetime value: '23/02/1971' for function str_to_date
Por que não está aceitando a data que está armazenada em 'Nascimento' na função STR_TO_DATE? O que estou fazendo de errado?

A: Está faltando as barras no seu formato
update cadastros_dados set data_nascimento = STR_TO_DATE(nascimento,'%d/%m/%Y')

documentação da função: https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_str-to-date


text:
Q: MvvmCross Monodroid.Dialog layout like iMessage I'm using MvvmCross and Dialog to create an iPhone and Android app. I've hit a bit of a stumbler when trying to layout a screen similar to the iMessage app on the iPhone.
I basically need a scrollview which takes up most of the screen but has a text entry and submit button stuck to the bottom of the screen. If the list grows to be larger than the height of the screen the list should scroll, preserving the positioning of the text entry and submit button at the bottom of the screen.
In a very quick, dirty and lame attempt I have tried:
Root = new RootElement{
    new BindableSection<CustomStringElement>(null, () => new CustomStringElement(),(o, i) => {
        //do something when clicked
    }).Bind(bindings, element => element.ItemsSource, vm => vm.Comments),
    new Section{
        new ButtonElement("Test")
    }
};

Which obviously pushes the buttonelement down when the list is larger than the screen height.
What I would like to know is how best to achieve this? I know I can create elements using layouts. But what would I lay out for this? I'm thinking this would be much easier to achieve if it were a straight MvxActivity but I don't think I can mix MvxActivity and MvxDialogActivity - I could be wrong?
How would you achieve this layout?

A: You can mix dialogs with non-dialogs - so this might be the best way to go.
Also, @csteeg submitted some code last year which enabled dialogs to be used inside linear layouts (scroll views) and listviews (and fragments) - it should be relatively straightforward to use those inside your custom activities - their source code is in https://github.com/MvvmCross/MvvmCross/tree/v3.1/CrossUI/CrossUI.Droid/Dialog

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server : declaring a cursor with a PARAMETER This question is mostly to confirm a (sad) conclusion I reached after some googling.
I need to use a CURSOR in SQL Server 2012 in which there is a WHERE clause that depends on a parameter, something like:
...
DECLARE @MyParam INT ;

DECLARE My_Cur CURSOR FOR
     SELECT A
     FROM MyTable
     WHERE B = @MyParam
...
...

SET @MyParam = 2 ;
...
...
OPEN My_Cur

WHILE ...
BEGIN

    FETCH My_Cur INTO ...
END;

When executing this, I get no results at all. If, instead of the variable in the cursor declaration, I deploy the value 2, results come out as needed.
This works perfectly in other DBMS (e.g. ORACLE).
Is it possible at all to have this type of parameterized cursors? If not, can anyone suggest a workaround?
I found some posts suggesting to declare the cursor AFTER the value is assigned to the variable but... this looks to me a very strange limitation.
Thanks.


text:
Q: How to make sure Kubernetes autoscaler not deleting the nodes which runs specific pod I am running a Kubernetes cluster(AWS EKS one) with Autoscaler pod So that Cluster will autoscale according to the resource request within the cluster.
Also, cluster will shrink no of nodes when the load is reduced. As I observed, Autosclaer can delete any node in this process.
I want to control this behavior such as asking Autoscaler to stop deleting nodes that runs a specific pod.
For example, If a node runs the Jenkins pod, Autoscaler should skip that node and delete other matching node from the cluster.
Will there a way to achieve this requirement. Please give your thoughts.

A: You should set a pod disruption budget that references specific pods by label.  If you want to ensure that there is at least one Jenkins worker pod running at all times, for example, you could create a PDB like
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: jenkins-worker-pdb
spec:
  minAvailable: 1
  selector:
    matchLabels:
      app: jenkins
      component: worker

(adapted from the basic example in Specifying a Disruption Budget in the Kubernetes docs).
Doing this won't prevent nodes from being destroyed; the cluster autoscaler is still free to scale things down.  What it will do is temporarily delay destroying a node until the disruption budget can be met again.
For example, say you've configured your Jenkins setup so that there are three workers.  Two get scheduled on the same node, and the autoscaler takes that node offline.  The ordinary Kubernetes Deployment system will create two new replicas on nodes that still exist.  If the autoscaler also decides it wants to destroy the node that has the last worker, the pod disruption budget above will prevent it from doing so until at least one other worker is running.
When you say "the Jenkins pod" in the question, there are two other important implications to this.  One is that you should almost always configure your applications using higher-level objects like Deployments or StatefulSets and not bare Pods.  The other is that it is generally useful to run multiple copies of things for redundancy if nothing else.  Even absent the cluster autoscaler, disks fail, Amazon occasionally arbitrarily decommissions EC2 instances, and nodes otherwise can go offline outside of your control; you often don't want just one copy of something running in your cluster, especially if you're considering it a critical service.

A: In autoscaler FAQ on github you can read the following:

What types of pods can prevent CA from removing a node?

*

*Pods with restrictive PodDisruptionBudget.

*Kube-system pods that:

*

*are not run on the node by default, *

*

*don't have a pod disruption
budget
set or their PDB is too restrictive (since CA 0.6).

*Pods that are not backed by a controller object (so not created by deployment, replica set, job, stateful set etc). *

*Pods with local storage. *

*Pods that cannot be moved elsewhere due to various constraints (lack of resources, non-matching node selectors or affinity, matching
anti-affinity, etc)

*Pods that have the following annotation set: "cluster-autoscaler.kubernetes.io/safe-to-evict": "false"
*Unless the pod has the following annotation (supported in
CA 1.0.3 or later): "cluster-autoscaler.kubernetes.io/safe-to-evict": "true"

A: You can use "cluster-autoscaler.kubernetes.io/safe-to-evict": "false"
...

template:
     metadata:
       labels:
         app: jenkins
       annotations:
         "cluster-autoscaler.kubernetes.io/safe-to-evict": "false"

     spec:
       nodeSelector:
         failure-domain.beta.kubernetes.io/zone: us-west-2b
...


text:
Q: Limit the GDB output length I have a structure that describes a bitmap. It looks like this
struct bitmap {
    int XSize;
    int YSize;
    unsigned char *pData;
};

When an instances of this structure is initialized pData points to thousands of random-like but non-zero bytes. When I print the instance of the structure GDB shows a lot of meaningless bytes. That very time consuming. When the disp of such a variable is active I get the output for each step what delays debugging.
Is there a GDB option that limits the output length?
When the bytes are meaningless I could change the type of pData to void *. But since the structure is used in a precompiled library the type can't be changed. Can the type that GDB uses for print and disp be "overridden"?

A: As Paul has pointed out the answer in this question gives the correct command to allow unlimited length.
To limit the length you need the command
set print elements n

where n is the maximum number of elements. Setting n to 0 gives the unlimited length.

A: Setting print elements 4 will limit the number of pData characters to 4, but it will also limit all other strings and arrays, which could be quite annoying (e.g. print filename would produce /tmp... when the actual value is /tmp/foobar.
A possibly better approach is to write a Python pretty-printer for struct bitmap (assuming you have sufficiently recent GDB). See this answer on how to do that.


text:
Q: R: using ggplot2 with a group_by data set I can't quite figure this out. A CSV of 200+ rows assigned to data like so:
gid,bh,p1_id,p1_x,p1_y
90467,R,543333,80.184,98.824
90467,L,408045,74.086,90.923
90467,R,543333,57.629,103.797
90467,L,408045,58.589,95.937

Trying to group by p1_id and plot the mean values for p1_x and p1_y:
grp <- data %>% group_by(p1_id)

Trying to plot geom_point objects like so:
geom_point(aes(mean(grp$p1_x), mean(grp$p1_y), color=grp$p1_id))

But that isn't showing unique plot points per distinct p1_id values.
What's the missing step here?

A: Why not calculate the mean first?
library(dplyr)
grp <- data %>%
        group_by(p1_id) %>%
        summarise(mean_p1x = mean(p1_x),
                  mean_p1y = mean(p1_y))

Then plot:
library(ggplot2)
ggplot(grp, aes(x = mean_p1x, y = mean_p1y)) +
        geom_point(aes(color = as.factor(p1_id)))

Edit: As per @eipi10, you can also pipe directly into ggplot
data %>%
        group_by(p1_id) %>%
        summarise(mean_p1x = mean(p1_x),
                  mean_p1y = mean(p1_y)) %>%
        ggplot(aes(x = mean_p1x, y = mean_p1y)) +
        geom_point(aes(color = as.factor(p1_id)))


text:
Q: git prepush hook: get branches pushed to How can I get a list of the branches that are being pushed to in the context of a pre push hook? I know how to get the current branch, but it can differ from the one/many branches being pushed to.
I've thought of parsing the command, but I'm worried I might forget about some cases. Like git push, git push origin master will both push to master etc.

A: while read oldrev newrev refname
do
     if [[ "$newrev" != "0000000000000000000000000000000000000000" ]] ; then
          branch=${refname#refs/heads/}
     fi
done

A: Here's one possible loop, although it's not clear to me what you want to do with the remote branch or tag name, and/or the local ref:
#! /bin/sh

NULLSHA=0000000000000000000000000000000000000000 # 40 0's

say() {
    echo "$@" 1>&2
}

while read localref localhash foreignref foreignhash; do
    case $foreignref in
    refs/heads/*)
        reftype=branch
        shortref=${foreignref#refs/heads/};;
    refs/tags/*)
        reftype=tag
        shortref=${foreignref#refs/tags/};;
    *)  reftype=unknown-ref-type
        shortref=$foreignref;;
    esac
    say "pushing to $reftype $shortref"
    case $localhash,$foreignhash in
    $NULLSHA,*) say "(push with intent to delete)";;
    *,$NULLSHA) say "(push with intent to create)";;
    *) say "(push with intent to update from $foreignhash to $localhash)"
       # for branch updates only, let's see if it's a fast-forward
       if [ $reftype = branch ]; then
           if git merge-base --is-ancestor $foreignhash $localhash; then
               say "(this is a fast-forward)"
           else
               say "(this can only work if forced)"
           fi
       fi;;
    esac
done

(note: this is not well tested).


text:
Q: Select de produtos por categoria PAI, com produtos cadastrados na categoria filho Seguinte, fiz as seguintes tabelas:
CREATE TABLE produto (
  codigo        INT UNSIGNED      NOT NULL AUTO_INCREMENT,
  nome          VARCHAR(128)      NOT NULL,
  url           VARCHAR(255)      NOT NULL,
  PRIMARY KEY (codigo)
);

CREATE TABLE categoria (
  codigo INT UNSIGNED NOT NULL AUTO_INCREMENT,
  nome   VARCHAR(128) NOT NULL,
  url    VARCHAR(255) NOT NULL,
  parent INT UNSIGNED          DEFAULT '0',
  PRIMARY KEY (codigo)
);

CREATE TABLE produto_categoria (
  cod_categoria INT UNSIGNED NOT NULL,
  cod_produto   INT UNSIGNED NOT NULL,
  FOREIGN KEY (cod_categoria) REFERENCES categoria (codigo),
  FOREIGN KEY (cod_produto) REFERENCES produto (codigo)
);

Como vocês podem perceber, a tabela categoria, possui o campo parent, que serve para atribuir a categoria pai.
No entanto estou com o seguinte problema:

Select dos produtos são realizados pela URL da categoria que pertence.

Quando faço com a categoria  da tabela produto_categoria OK.
No entanto quando faço o Select pela categoria pai, e retornado null, pois o produto não pertence diretamente a categoria pai.
Exemplo:
Produto -> Atum (codigo 1)
Categoria -> Comida (codigo 1) -> Enlatados (codigo 2| parent 1)
Produto_Categoria -> cod_categoria (2) | cod_produto (1)

Quando faço o select pelo enlatados, fica OK, mas gostaria que quando seleciona-se pela categoria Comida, aparece-se os produtos das categorias filho!

Fiz esta view, para o select, no entanto ele so retorna da categoria que o produto esta vinculado.
CREATE OR REPLACE VIEW view_site_produtos AS
SELECT
  p.codigo, p.nome, c.url,
FROM
  produto p
  LEFT JOIN produto_categoria pc ON p.codigo = pc.cod_produto
  LEFT JOIN categoria c ON pc.cod_categoria = c.codigo;

E faço a consulta da seguinte maneira:
SELECT * FROM view_site_produtos WHERE url = '';

A: Você precisa pegar todos ids dos filhos que tem aquele pai para assim fazer o select. Isso é possível através de um subselect, no exemplo eu usei a coluna nome, porém você pode mudar o where para a coluna url que o select não deve ser afetado.
SELECT * FROM categoria c
    JOIN produto_categoria pc ON pc.cod_categoria = c.codigo
    JOIN produto p ON p.codigo = pc.cod_produto
WHERE c.codigo IN (select c_filho.codigo from categoria c_pai
                        join categoria c_filho on c_filho.parent = c_pai.codigo
                     where c_pai.nome = 'Comida');


text:
Q: How to mimic the shading effect of modal popups in Bootstrap? In Bootstrap, there's the effect of modal popup window  where the rest of the page gets inactivated (when clicking on a link, for instance) and grayed out. I'd like to mimic that effect in my own CSS.

After looking for a few hours into the CSS files of the package, I concluded that I won't be able to back-engineer the behavior myself. Simply too much junk in the trunk for me.
How can I mimic the described behavior in a custom way? Or did I happen to hit a very complicated issue that requires border-line black magic to get working?

A: You can add a div that covers the entire page with a higher z-index than your content. Make the div partially see through to get the desired look.
If you are adding a modal/popup, make sure this has a higher z-index than the backdrop.
Here's an example:

$('#test').click(function() {
  var backdropHeight = $(document).height();
  $('#backdrop').css('height', backdropHeight);
  $('#backdrop').fadeIn(100, function() {
    $('#modal').fadeIn(200);
  });
});

$('#closeModal').click(function() {
  $('#modal').fadeOut(200, function() {
    $('#backdrop').fadeOut(100);
  });
});
#backdrop {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.3);
  z-index: 10;
}

#modal {
  display: none;
  position: absolute;
  left: calc(50% - 100px);
  top: calc(50% - 100px);
  height: 200px;
  width: 200px;
  background: #fff;
  text-align: center;
  z-index: 11;
}

Hellow World

<button id="test">Show Modal</button>

My modal

  <button id="closeModal">Close Modal</button>

A: There's nothing complicated about it. It's just a "backdrop" using an absolute positioned element with partial opacity so that elements behind it show through.
.backdrop {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 1040;
  background-color: #000;
  opacity: 0.5;
}

Demo http://www.codeply.com/go/KhCqGTSCBe

A: I guess the simplest solution is to override .modal-backdrop.show class.
By default it is set to:
.modal-backdrop.show{
    opacity: .5;
}

and you can just override it to
.modal-backdrop.show{
    opacity: 0!important; /* to disable "gray effect" */
    /* OR */
    opacity: 1;
    background: red;
    /* to change background to red */
}

You can change anything u want in this class

A: use css position & z-index and opacity can implements modal overlay.

$('input').click(function(){
  var methodName=$(this).attr('id');
   $('.modal-dialog')[methodName]();;
});
html,body{border:0;padding:0;margin:0;}

.modal-dialog,.overlay{
 position:absolute;
 width:100%;
 height:100%;
 left:0;
 top:0;
}
.overlay{
 background:#000;
 opacity:0.1;
 z-index:100;
}
.dialog{
 position:absolute;
 z-index:1000;
 left:50%;
 top:50%;
}
.modal-dialog{
 display:none;
}

<input type="button" id='fadeIn' value="Show"/>

    <input id='fadeOut' type='button' value='Cancel'>


text:
Q: VBScript Run/Exec setting environment once and reusing Is there a way to have Run or Exec preserve the environmental variables after each call?
For example, call vcvars32 that does a lot of configuring of paths and whatever:
shell.Run "vcvars32.bat", 0, True
Then I'd like to be able to call msbuild in this configured environment:
shell.Run "msbuild.exe example.sln /t:Rebuild /p:Configuration=""Debug|Win32""", 0, True
Is this possible?
The only alternative I could find is to create a combo batch script with both commands and call that instead. But that seems wasteful if I need to call the setup script each time, it would be great to have the environment set up once and then reuse it.

A: Well you could put it as a function? Im not sure if that answers your final question but it will create a lot less "stuff" you need to remember.
i put the vcvars32.bat in the same function because i do not know whether you would need them in the same function.
sub
funcmsbuild
end sub

Function funcmsbuild
shell.Run "vcvars32.bat", 0, True
shell.Run "msbuild.exe example.sln /t:Rebuild /p:Configuration=""Debug|Win32""", 0, True
end function

Or else you could put all your environmental variables in a string and call that? But that would be confusing since you have alot of quotes in that "would be" string, and it would require you to have your triple and quadruple quotes in order (unless you used chr(22) i belive for quotes)

A: Put the calls for vcvars32.bat and msbuild.exe in one batch file. Use CALL to call vcvars32.bat and it will preserve the environment. Pass your SLN and other arguments to the batch file and retrieve them using %1, %2, %3, etc. remember to put quotes around them if needed.
It's not as clean as having everything in one VBS file, but it's the simplest way.


text:
Q: What is best way to find different keys and values in dictionary? What is best way to find different keys and values in python dictionary?
Rules:

*

*Check input and contains keys and values are same, if yes return True
Contains = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }
input = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }

Expected Output: True

*Check input and contains values are different , if dirrent return False
Contains = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }
input = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 6 }

Expected Output: False (Reason e values are different)

*Check input and contains Keys are different for same values, if different return False
Contains = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }
input = {"a": 1, "b": 2, "c": 3, "d": 4, "f": 5 }

Expected Output: False (Contains key "e" is 5 and input key "f" is 5)

*Input contains extra keys and values but does not present in Contains dict hence no duplicates return True
Contains = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5 }
input = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}

Expected output: True (input has extra key value that is f and 6 but it does not duplicating )
Code to achieve:
Contains = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 }
input = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6}

def key_value_check(Contains, input):
    for k, v in input.items():
        if k in Contains.keys():
            if v != Contains[k]:
                return False
        if v in Contains.values():
            try:
                if v != Contains[k]:
                    return False
            except Exception as e:
                return False
    return True
print(key_value_check(Contains, input))

Code is working but required best way or one liner code to achieve this.

A: def oneliner(a, b):
    return all([a.get(i) == b.get(i) for i in a.keys()])

A: Try this:
all( Input.get(c,0)==n for c,n in Contains.items() )


text:
Q: How to reflect another project's class info there are two projects in eclipse! how to reflect one class in other project? I put other project's class path into system's property. but still popup class not found exception. Is there any good solution for it?
System.out.println(System.getProperty("java.class.path"));

System.getProperties().put("java.class.path",
    System.getProperty("java.class.path") +
        ";C:\\Users\\fu.jian\\workspace\\Study\\bin");

System.out.println(System.getProperty("java.class.path"));

Class<?> forName2 = Class.forName("study.Activator");
System.out.println(forName2);

A: Right click the project to bring up the context menu.
Build Path->Configure Build Path
Under the Java Build Path dialog, select the Projects tab and add the project.

A: Try to add the project B to classpath of project A by:
In Eclipse click on project A -> mouse right click and select Properties -> Select Java Build Path -> Select Projects tab -> Click on Add... and check project B
The problem will be resolved inside Eclipse, if you use external tools for compilation and building the project - your problem will still appear.
You can export the project B as jar and copy the jar into the project A libs. This way you won't depend on Eclipse.


text:
Q: Outlook Add-In Where to save configuration, C# I am developing a add-in for outlook using VS2008, C#.
I am trying to figure out a way to allow user to specify some settings during the installation and use them in the add-in.
seeking ways I don't have to write use registry.
thanks in advance~

A: Thanks,
I actually decided to read the outlook addins registry for the installed location and have configuration file copied there during installation. so far it works fine :)

A: app.config, and make sure that it's copied to dll directory?

A: Its an Addin, so how exactly is

app.config, and make sure that it's
  copied to dll directory?

going to help?
Basically you would need to create a file called Outlook.exe.config and put it in the Office12 folder with Outlook.exe (c:\Program Files\Microsoft Office\Office12)
If you do this it will get loaded, the only potential issue is that it is also available to any other addins that are loaded into the outlook.exe process.
A better idea is just as the OP suggested an use an arbitary config file copied to the targetdir and read it from there.


text:
Q: Páginas archivo json con ajax jquery Hola amigos tengo un archivo json algo pesado construido clave valor aquí un fragmento.
{
  "3d_rotation": "e84d",
  "ac_unit": "eb3b",
  "access_alarm": "e190",
  "access_alarms": "e191",
  "access_time": "e192",
  "accessibility": "e84e",
  "accessible": "e914",
  "account_balance": "e84f",
  "account_balance_wallet": "e850",
  "account_box": "e851",
  "account_circle": "e853",
  "adb": "e60e",
  "add": "e145",
  "add_a_photo": "e439",
  "add_alarm": "e193",
  "add_alert": "e003",
  "add_box": "e146",
  "add_circle": "e147",
  "add_circle_outline": "e148",
  "add_location": "e567",
  "add_shopping_cart": "e854",
  "add_to_photos": "e39d",
  "add_to_queue": "e05c",
  "adjust": "e39e",
}

Ese archivo tiene aproximadamente 25.500 líneas de código.
Mi pregunta es como puedo paginarlo para crear un modal con Metro y laravel para que los usuarios puedan seleccionar el icono a incluir.
intente usar $.ajax pero se tarda demasiado solo en abrir el diálogo. Ese problema lo tengo con los icono y animaciones. de mi sistema estoy creando un mini blog en laravel y uno de los requerimientos es qu puedan crear listas con Iconos los cuales me los pasaron.

A: ya lo he resuelto gracias por sus ideas, busque en la documentacion oficial de MetroUi (EL framework css que estoy utilizando) y encontre este link. https://metroui.org.ua/list.html resulta que este framework posee un uso de listas que me permite cargar un json y paginalo a antojo, es primera vez que uso este framework por eso mi desoconocimiento lo resolvi con el siguiente codigo.
<ul class="unstyled-list list icon-list"
                        data-role="list"
                        data-show-pagination="true"
                        data-items="15"
                        data-items-steps="15, 25, 50, 100, 150"
                        data-show-items-steps="true"
                        data-show-list-info="true"
                        data-list-info-title="Mostrando $1 a $2 de $3 Icons"
                        data-sort-target="li"
                        data-sort-class="label"
                        data-cls-list-item="bg-orange-hover fg-dark"
                        data-source="{{asset('/js/icons/json/MaterialIcons.json')}}">


text:
Q: Installing custom font in JetBrains PyCharm? How does one install a different font into PyCharm to use in the code editor?
The default font choices seem pretty limited and some of those fonts are not rendered properly.
Also, which font do you prefer to use in PyCharm?

A: First you need to install the font you want then close out the program, open it back up and go t File > Settings > Appearance And Behavior > Appearance, click "Override Default Fonts", look for your font, and click apply then Ok.

A: To me it seems all installed system fonts are available (Windows 10).
Even if I use some weird font, it renders ok.
I stay with default Segoe UI and for code I use Consolas.


text:
Q: QFT: Prove this relationship In my notes from QFT appears this relationship between exponential and sinh and cosh, my question is: How demonstrate this?
$$\exp{(\pm\frac{1}{2} \eta \sigma^3)}=\cosh(\frac{1}{2}\eta) \mathbb{I}_{2x2}\pm \sinh(\frac{1}{2}\eta)\sigma^3,$$
where $\sigma^3$  is a Pauli matrix, $\eta$ is the "rapidity" and $\mathbb{I}_{2x2}$ is the 2x2 identity matix. Thank you for your attention.

A: The first step is to expand the exponential as a Taylor series:
$$ \exp \left( \pm \frac{1}{2} \eta \sigma \right) = I \pm \left( \eta \sigma/2 \right) + \frac{1}{2} \left( \eta \sigma / 2 \right)^2 \pm \frac{1}{3!} \left( \eta \sigma / 2 \right)^3 \dots$$
Noting that $\sigma^2 = I$, this series can now be split into even and odd terms: the even terms sum to $\cosh \left( \eta/2 \right) \ I$, and the odd terms to $\pm \sinh \left( \eta/2 \right) \ \sigma$, which gives the result you want.

A: You just need to use the series expansion and observe that
$$(\sigma^3)^{2n} = \mathbb I_{2}$$
and
$$(\sigma^3)^{2n+1} = \sigma^3$$

A: The shortest way is the following one. Define
$$f(\eta):= \exp{(\pm\frac{1}{2} \eta \sigma^3)}\:,\quad g(\eta):=\cosh(\frac{1}{2}\eta) \mathbb{I}_{2x2}\pm \sinh(\frac{1}{2}\eta)\sigma^3.$$
Now notice that
$$f'(\eta) = \pm\frac{1}{2}  f(\eta)\sigma_3$$
and
$$g'(\eta) = \frac{1}{2} \sinh(\frac{1}{2}\eta) \mathbb{I}_{2x2}\pm\cosh(\frac{1}{2}\eta)\sigma^3 =  \pm\frac{1}{2}  g(\eta)\sigma_3\:.$$
We conclude that both functions satisfy the same first order system of  differential equations
$$y'= \pm \frac{1}{2} y\sigma_3$$
and the same initial condition
$$y(0)=f(0)=g(0) = \mathbb{I}_{2x2}$$
Since the functions are smooth, we can safely apply the uniqueness theorem for first order differential equations concluding that:
$$f(\eta)=g(\eta) \quad \eta \in \mathbb{R}\:.$$


text:
Q: Rails has many through with same model I have one user model and one viewed_contractor model. I am treating user model as customer and contractor. customer can view many contractors by visiting their respective profile.Contractor can be viewed by many customers. I have customer_id and contractor_id in my viewed_contractor. I want to handle this relation as has_many through. Is it possible thorough has_many through?

A: It is possible. First, you'd need to specify the class_name option for the belongs_to associations in your ViewedContractor model so that they both refer to your User class. Then you could specify the has_many through: relations in your User model.
Something like this should work:
# viewed_contractor.rb
class ViewedContractor < ActiveRecord::Base
  belongs_to :contractor, class_name: 'User', foreign_key: :contractor_id
  belongs_to :customer, class_name: 'User', foreign_key: :customer_id
end

# user.rb
class User < ActiveRecord::Base
  has_many :viewed_contractors_as_contractor, class_name: 'ViewedContractor', foreign_key: :contractor_id
  has_many :viewed_contractors_as_customer, class_name: 'ViewedContractor', foreign_key: :customer_id

  has_many :visited_contractors, through: :viewed_contractors_as_customer, source: :contractor
  has_many :visited_customers, through: :viewed_contractors_as_contractor, source: :customer
end


text:
Q: Convert to USD payments made with PayPal for unaccepted currencies in Magento Synopsis: PayPal payment module from Magento will not convert currency to USD or any paypal accepted currency if your base currency is other than those listed here https://www.paypal.com/us/webapps/helpcenter/helphub/article/?solutionId=FAQ2390
I have a Magento installation with 3 currencies installed.
I use PayPal standard payments as a payment option but the problem is that users are charged the same amount but in USD. For example if I have 100 RON and choose to pay by paypal i will be charged for 100 USD instead.
I checked the paypal module that makes the redirection available in

app/code/core/Mage/Paypal/Block/Standard/Redirect.php

and the variables related to currency and amount are correctly set and sent to paypal.
I do not know exactly how to tackle this issue and it is very frustrating as I guess the standard PayPal module in Magento is designed by PayPal (needs confirmation) and is verified for this kind of situations.
Info #1: PayPal does not accept some currencies (like Romanian Lei for example which happens to be the base currency for this shop) for transactions (allowed currencies are listed here https://www.paypal.com/us/webapps/helpcenter/helphub/article/?solutionId=FAQ2390) so by the time you click submit they will convert only the currency sign (to $) and not the amount. The amount you will have to change yourself, however the default PayPal module in Magento (v 1.5) is not doing this and this is why I opened this question.
EDIT #1
I tried the solution proposed down below but it did not work as in fact it replaces some of the variables but not in the desired way.
There are two options I see here:
Option #1: 'find and replace' option is where I find all the float values in the final form and replace them with the values converted to USD. However this is not a viable option because is not converting the values correctly and error may occur.
Option #2:
I found the functions that pop out the values in the form and it is located in spp/code/core/Mage/Paypal/Model/Api/Abstract.php
protected function _exportLineItems(array &$request, $i = 0)
    {
        if (!$this->_cart) {
            return;
        }

        // always add cart totals, even if line items are not requested
        if ($this->_lineItemTotalExportMap) {
            foreach ($this->_cart->getTotals() as $key => $total) {
                if (isset($this->_lineItemTotalExportMap[$key])) { // !empty($total)
                    $privateKey = $this->_lineItemTotalExportMap[$key];
                    $request[$privateKey] = $this->_filterAmount($total);
                }
            }
        }

        // add cart line items
        $items = $this->_cart->getItems();
        if (empty($items) || !$this->getIsLineItemsEnabled()) {
            return;
        }
        $result = null;
        foreach ($items as $item) {
            foreach ($this->_lineItemExportItemsFormat as $publicKey => $privateFormat) {
                $result = true;
                $value = $item->getDataUsingMethod($publicKey);
                if (isset($this->_lineItemExportItemsFilters[$publicKey])) {
                    $callback   = $this->_lineItemExportItemsFilters[$publicKey];
                    $value = call_user_func(array($this, $callback), $value);
                }
                if (is_float($value)) {
                    $value = $this->_filterAmount($value);
                }
                $request[sprintf($privateFormat, $i)] = $value;
            }
            $i++;
        }
        return $result;
    }

These 2 lines:
$request[$privateKey] = $this->_filterAmount($total);
$value = $this->_filterAmount($value);

print out the amount in the list of variables so instead of the function _filterAmount I have written the following function that should convert the amount from any base currency to USD based on the exchange rates defined in backend:
protected function _convertAmounttoUSD($value)
    {
        $baseCode = Mage::app()->getBaseCurrencyCode();
        $fromCur = Mage::app()->getStore()->getCurrentCurrencyCode();
        $toCur = 'USD';
        $allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();
        $rates = Mage::getModel('directory/currency')->getCurrencyRates($baseCode, array_values($allowedCurrencies));

        $output = ( $value * $rates[$toCur] ) / $rates[$fromCur];

        return sprintf('%.2F', $output);
    }

And I have replaced the lines above with the following:
$request[$privateKey] = $this->_convertAmounttoUSD($total);
$value = $this->_convertAmounttoUSD($value);

The problem is that the values do not get converted.

A: In magento when user get redirected to paypal it magento send store currency to charge but paypal use currency which associated in paypal account so we need to convert it to paypal account currency.
It will charge 100RON but convert it into USD currency.
you need to change in below file with below function:
app\code\core\Mage\Paypal\Model\Standard.php
Replace the getStandardCheckoutFormFields function with below function:
public function getStandardCheckoutFormFields()
{
    $orderIncrementId = $this->getCheckout()->getLastRealOrderId();
    $order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);
    $api = Mage::getModel('paypal/api_standard')->setConfigObject($this->getConfig());
    $api->setOrderId($orderIncrementId)
        ->setCurrencyCode($order->getBaseCurrencyCode())
        //->setPaymentAction()
        ->setOrder($order)
        ->setNotifyUrl(Mage::getUrl('paypal/ipn/'))
        ->setReturnUrl(Mage::getUrl('paypal/standard/success'))
        ->setCancelUrl(Mage::getUrl('paypal/standard/cancel'));

    // export address
    $isOrderVirtual = $order->getIsVirtual();
    $address = $isOrderVirtual ? $order->getBillingAddress() : $order->getShippingAddress();
    if ($isOrderVirtual) {
        $api->setNoShipping(true);
    } elseif ($address->validate()) {
        $api->setAddress($address);
    }

    // add cart totals and line items
    $api->setPaypalCart(Mage::getModel('paypal/cart', array($order)))
        ->setIsLineItemsEnabled($this->_config->lineItemsEnabled)
    ;
    $api->setCartSummary($this->_getAggregatedCartSummary());

    $result = $api->getStandardCheckoutRequest();

    $baseCode = Mage::app()->getBaseCurrencyCode();
    $fromCur = Mage::app()->getStore()->getCurrentCurrencyCode();
    $toCur = 'USD';

    $allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();
    $rates = Mage::getModel('directory/currency')->getCurrencyRates($baseCode, array_values($allowedCurrencies));
    $result['amount'] = round((($order->getGrandTotal() * $rates[$toCur])/$rates[$fromCur]),2);

    $result['currency_code'] = $toCur;

    $j = 0;
    $items = $order->getAllItems();

    foreach ($items as $itemId => $item)
    {
        if ($item->getParentItem()) {
            continue;
        }
        $j ++;
        $result['amount_'.$j] = round((($item->getPrice() * $rates[$toCur])/$rates[$fromCur]),2);
    }
    $j++;
    $result['country']          = $order->getBillingAddress()->getCountryId();
    $shippingSpo            = $order->getBaseShippingAmount();
    $result['shipping']         = round((($shippingSpo * $rates[$toCur])/$rates[$fromCur]),2);
    $result['discount_amount']  = -1*round((($order->getDiscountAmount() * $rates[$toCur])/$rates[$fromCur]),2);
    $result['discount_amount_cart'] = $result['discount_amount'];

    $result['amount_'.$j] = $result['shipping'];

    unset($result['discount_amount']);
    unset($result['shipping']);
    unset($result['discount_amount_cart']);
    unset($result['amount_'.$j]);
    return $result;
}


text:
Q: Grabbing current list item in infopath with C# I am trying to grab the current list item, which is an infopath form. So far I am connecting to the sharepoint site, opening the list and trying to grab the current item, but I keep getting an index out of range error. Here is my code
            SPSite WebApp = new SPSite("http://site/");
            SPWeb site = WebApp.OpenWeb();
            site.AllowUnsafeUpdates = true;
            SPList list = Site.Lists.TryGetList("List_Library");

            WebApp.AllowUnsafeUpdates = true;

            SPListItem item = list.Items[list.Items.Count];

My question is how can I grab the current list? This code is located in the code behind for the infopath form and is in the FormEvents_Submit method that is called when the Submit event is fired. I tried moving the code to the bottom of the method to ensure that the form gets submitted first, but was still receiving the out of range error.

A: the list item is zero based index: Count-1

A: Side note: Is it server form (Forms Server) or client? If it is client form you should not be using SharePoint server side OM unless your form will always run on the server.
FormEvents_Submit should handle submission of the form completely. So it is responsibility of your code to save item first in whatever way you need. Generally as result of saving an object you get back some idenity that you can use to retrive it back (i.e. SPList.AddItem already returns you SPListItem)

A: It turns out I was trying to access the list item BEFORE the InfoPath form was submitted, so it didn't exist in the list yet. To get around this, I would have to put my code at the end of the Form_Submit event and make sure the list.Update() was finished before trying to grab the item.


text:
Q: Misbehaviour single click uploading image twice I have a button to find an image on gallery and a button to upload the image to the server.
The problem is, user clicks on it once and it send 2 requests to server, uploading 2 times. Any ideas whats is wrong? And how to solve?
//gallery and upload buttons:

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageToUpload:

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                        String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
                        requestPermissions(permissions, PERMISSION_REQUEST_CODE);
                    }
                }

                Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
                break;
            case R.id.bUploadImage:

                bUploadImage.setEnabled(false);

                Bitmap image = null;
                if(hasImage(imageToUpload)) {
                    image = ((BitmapDrawable) imageToUpload.getDrawable()).getBitmap();
                }
                else{
                    if(uploadImageName.length() < 2){ // no image and no text
                        bUploadImage.setEnabled(true);
                        return;
                    }
                }
                new UploadImage(image, uploadImageName.getText().toString());
                break;
        }
        super.onClick(v); //to baseactivity profile click work.
    }

and class to upload:
private class UploadImage {
    Bitmap image;
    String name;
    String encodedImage = "";

    UploadImage(Bitmap image, String name) {
        this.image = image;
        this.name = name;

        if(image != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
        }

        Response.Listener<String> responseListener = new Response.Listener<String>(){

            @Override
            public void onResponse(String response){
                try {
                    JSONObject jsonResponse = new JSONObject(response);
                    boolean success = jsonResponse.getBoolean("success");
                    if(success){
                        String done = getResources().getString(R.string.done);
                        Toast.makeText(getApplicationContext(), done, Toast.LENGTH_SHORT).show();
                    }
                    else{
                        AlertDialog.Builder builder = new AlertDialog.Builder(Upload.this);
                        String error = getResources().getString(R.string.error);
                        String retry = getResources().getString(R.string.retry);
                        builder.setMessage(error)
                                .setNegativeButton(retry,null)
                                .create()
                                .show();
                    }
                } catch (JSONException e){
                    e.printStackTrace();
                }
            }

        };

        UploadRequest uploadRequest = new UploadRequest(encodedImage, UserId, name, token, responseListener);
        RequestQueue queue = Volley.newRequestQueue(Upload.this);
        queue.add(uploadRequest);

    }
}

any ideas why it is sending the post 2 times to the server when user clicks on button once?


text:
Q: Python function to multiple individual lines in text file I am trying to write a function that can take every individual line in a txt file and multiply that line by 2 so that each integer in the text file is doubled.  So far I was able to get the code to print. However, when I added the code (reading & reading_int) to convert the strings to integers the function is now not working. There are no errors in the code to tell me what I am doing wrong. I am not sure what is wrong with reading and reading_int that is making my function not work.
def mult_num3():
data=[]
w = open('file3.txt', 'r')
with w as f:
    reading = f.read()
    reading_int = [int(x) for x in reading.split()]
    for line in f:
        currentline = line[:-1]
        data.append(currentline)
    for i in data:
        w.write(int(i)*2)
w.close()

file3.txt:
1
2
3
4
5
6
7
8
9
10

Desired output:
2
4
6
8
10
12
14
16
18
20

A: I added a try except to check for not integer data. I dont konw your data. But maybe it helps you.
def mult_num3():
    input = open('file3.txt', 'r')
    output = open('script_out.txt', 'w')

    with input as f:

        for line in f:

            for value in line.split():
                try:
                    output.write(str(int(value) * 2) + " ")
                except:
                    output.write(
                        "(" + str(value + ": is not an integer") + ") ")

            output.write("\n")

    output.close()

A: Problems with original code:
def mult_num3():
    data=[]
    w = open('file3.txt', 'r')  # only opened for reading, not writing
    with w as f:
        reading = f.read()  # reads whole file
        reading_int = [int(x) for x in reading.split()] # unused variable
        for line in f:  # file is empty now
            currentline = line[:-1] # not executed
            data.append(currentline) # not executed
        for i in data:  # data is empty, so...
            w.write(int(i)*2) # not executed, can't write an int if it did
                              # and file isn't writable.
    w.close() # not necessary, 'with' will close it

Note that int() ignores leading and trailing whitespace so no need for .split() if only one number per line, and a format string (f-string) can format each line as needed by converting and doubling the value and adding a newline.
with open('file3.txt', 'r') as f:
    data = [f'{int(line)*2}\n' for line in f]
with open('file3.txt', 'w') as f:
    f.writelines(data)


text:
Q: Imprimir nombres y contenidos de varios archivos y duda sobre fecha de creación de los archivos en carpeta - Python Después de un poco de investigación y de mucha de ayuda de las respuestas a mi pregunta anterior ( Imprimir automáticamente cada vez que se cree un archivo en una carpeta - Python ), dejé el código de la siguiente manera para que sea capaz de imprimir el nombre y contenido del último archivo creado dentro de una carpeta cada 15 segundos, pero no imprimima nada si no se ha creado un nuevo archivo en la carpeta.
import glob
import os
import time

oldfile = None

while True:
    newest = max(glob.glob('/Users/BetaBrawler/Downloads/HernanVillela/*'), key=os.path.getctime)

    if newest == oldfile:
        time.sleep(15)
        continue

    oldfile = newest
    print newest

    with open(newest) as infile:
        print [line.strip() for line in infile]

    time.sleep(15)

Output

/Users/BetaBrawler/Downloads/HernanVillela\Prueba.txt
  ['texto de prueba']

Hay dos problemas que no se como resolver:

*

*1- ¿ Cómo hago para imprimir los nombres de varios archivos, con sus respectivos contenidos? Por ejemplo, seleccione todos los documentos (Control + E), los copie (Control + C) y cree varias copias (Control + V), que por ende se consideran archivos nuevos, pero solamente imprime uno y no varios como yo esperaba.

*2- Cuando copio varios archivos de otras carpetas y los pego en mi carpeta donde trabaja mi código, solamente muestra el archivo con fecha de modificación mas reciente y lo ideal seria que muestre el archivo ( o los archivos) más reciente que llego a la carpeta.

A: Debes comparar no solo el último creado como haces ahora, sino que debes encontrar todos los archivos que están ahora y antes no. Tienes varias opciones:

*

*Creas una lista con todos los archivos presentes en tu directorio. Luego entras en el while y en cada iteración creas una lista con los archivos presentes y la comparas con la anterior. Imprimes los archivos diferentes y sustituyes la lista antigua por la nueva. Si quieres hacer esto lo mejor es usar conjuntos (set) y usar la diferencia de conjuntos:
import time
import glob

RUTA = 'D:\Programacion\Python\StackOverflow\Pruebas\*'
DELAY = 15 #en segundos

ultimo = set(glob.iglob(RUTA))
while True:
    actual = set(glob.iglob(RUTA))
    for file in actual - ultimo:
        with open(file,'r') as f:
            texto = [x.strip() for x in f.readlines()]
            print(texto)

    ultimo = actual
    time.sleep(DELAY)

*También puedes comparar la fecha de la última comprobación con las de creación de tus archivos. Todo archivo que tenga una fecha superior es nuevo:
import time
import glob
import os

RUTA = '/Users/BetaBrawler/Downloads/HernanVillela/*'
DELAY = 15 #en segundos

last_time = time.time()
while True:
    new_time = time.time()
    for file in glob.iglob(RUTA):
        if os.path.getctime(file) > last_time:
            with open(file,'r') as f:
                texto = [x.strip() for x in f.readlines()]
                print(texto)

    last_time = new_time
    time.sleep(DELAY)

Otra versión basada en la anterior sería crear una lista ordena con los archivos y su fecha de creación en tuplas. La recorremos y rompemos el ciclo en cuanto se encuentre un archivo que no sea nuevo. Esto evita recorrer siempre la lista completa:
import time
import glob
import os

RUTA = '/Users/BetaBrawler/Downloads/HernanVillela/*'
DELAY = 15 #en segundos

last_time = time.time()
while True:
    new_time = time.time()
    files = sorted([(os.path.getctime(file),  file)
                         for file in glob.iglob(RUTA)],  reverse = True)
    for date, file in files:
        if date > last_time:
            with open(file,'r') as f:
                texto = [x.strip() for x in f.readlines()]
                print(texto)
        else:
            break

    last_time = new_time
    time.sleep(DELAY)

Existen muchas formas más, la cuestión sería ver cual es la más eficiente para tu caso concreto. De todas formas, esto funciona bién para un número relativamente pequeño de archivos, si vas a tratar con un directorio con miles de archivos mejor usar las herramientas propias del sistema operativo como FindFirstChangeNotification (Win32 API ) o bibliotecas ya creadas con estos fines como  Watchdog.
Nota importante: no dices en que sistema operativo trabajas (por la ruta parece que Windows). En Linux  getctime no tiene porqué obtener la fecha de creación del fichero, puede ser vete a saber que (por ejemplo la fecha de la última modificación). Esto no tiene nada que ver con Python sino con el SO (ver: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_08) y con el sistema de ficheros que use. Se puede obtener la fecha real de creación pero no en todos los casos, en EXT4 si es posible pero no en otros sistemas de ficheros.


text:
Q: Connect to SQL Server running on Windows host from a WSL 2/Ubuntu sqlcmd I have a host running Windows 10, WSL 2. My guest is Ubuntu.
I'm trying to use sqlcmd to connect to the SQL Server running on my host machine, but I'm not sure what IP to use in the connection?
I've exposed/enabled basically everything from the SQL Configuration Manager on the host Windows SQL Server, and am using commands like this to try to connect:
sqlcmd -S 127.0.0.1 -U sa -P pass

Sqlcmd: Error: Microsoft ODBC Driver 17 for SQL Server : Login timeout expired.

A: Have you try looking on the IP on /etc/resolv.conf?
Try connecting using that one, example: sqlcmd -S 192.168.202.65 -U sa -P pass
This is because of this

A: *

*In your connection string, use the IP address from cat /etc/resolv.conf

*open the 1433 port in Windows Firewall. Go to New rule - Port - Next - Specific ports: 1433 - Next - Allow - Next - Next - Name "WSL2 sql"

*Disable VPN software in Windows (if any) - it might brake WSL2/Windows network connectivity

NOTE: You just opened the port to the entire world, so either enable-disable this rule only when needed, or limit this rule to your WSL2 IP address only (double click the rule - Scope - Remote IP ads - Add your WSL2 address. To find your wsl host address type wsl hostname -I in windows cmd shell)

A: Enabling the "Virtual Machine Monitoring" worked for me. These four firewall rules are located in the inbound list, names starting with "Virtual Machine Monitoring" for:

*

*Echo Requests (ICMPv4/v6)

*RPC

*DCOM-In

*NB-Session-In

They appear to be disabled by default and once I enabled them, I was able to ping the host as well connect to my host sql server service using the IP address from the WSL generated resolv.conf file --
cat /etc/resolv.conf
# This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:
# [network]
# generateResolvConf = false
nameserver 1xx.1xx.1xx.1xx


text:
Q: Operation parameter must be str while inserting values to table in sql3 python I am getting an error message stating
ValueError: operation parameter must be str
while inserting data into the table
here is my code below
import csv
import sqlite3

conn = sqlite3.connect('results.db')
curs = conn.cursor()

total = []
headerlist = []
headerlisttype = []

rowindex = 1
def parse_csv():
    '''
    Adds all the rows in csv file to total list
    '''
    with open('3-1 RESULTS.csv', 'r') as csvfile:
        parser = csv.reader(csvfile)
        headerlist = next(parser)
        for row in parser:
            total.append(row)
# end parse_csv

def create_table():
    '''
    Creates a table with just auto incremented SNO column
    '''
    sql = '''CREATE TABLE IF NOT EXISTS RESULTS31
    (SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
    MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
    OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) '''
    curs.execute(sql)
    conn.commit()
#end create_table function

def insert_to_table(row):
    global rowindex
    sno = rowindex
    rowindex += 1

    reg, name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, sgpa, cgpa = row

    sql = '''INSERT INTO RESULTS31
    (SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
    MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
    OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''',
    (int(sno), int(reg), name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, float(sgpa), float(cgpa))

    try:
        curs.execute(sql)
    except Exception as e:
        print(e)

def print_from_table():
    sql = ''' SELECT * FROM RESULTS31 '''
    curs.execute(sql)

    data = curs.fetchall()

    for row in data:
        print(row)

parse_csv()
create_table()

for row in total:
    insert_to_table(row)

print_from_table()

can anyone please find the error in my code
Help will be much apreciated

A: INSERT wants only the column names, not any column types.
And execute() has two parameters, the SQL statement text, and the list of SQL parameters:
sql = '''INSERT INTO RESULTS31 (SNO, REGNUMBER, ...'''
params = (int(sno), ...)
curs.execute(sql, params)

A: I've never seen this Python construct:

sql = '''INSERT INTO RESULTS31
(SNO NUMBER NOT NULL, REGNUMBER NUMBER, NAME TEXT,
MPII TEXT, SP TEXT, CG TEXT, FLAT TEXT, FS TEXT, OS TEXT,
OSLAB TEXT, MPIILAB TEXT, SS TEXT, SGPA REAL, CGPA REAL) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''',
(int(sno), int(reg), name, mpII, sp, cg, flat, fs, os, oslab, mpIIlab, ss, float(sgpa), float(cgpa))

Unless this is perfectly valid syntax for formatting strings, your code will create a tuple and bind it to 'sql'
look into format()


text:
Q: How to change width of bar in bar charts in charts_flutter? Trying to use charts_flutter for bar charts but couldn't find a property to reduce the width of bars in simple bar charts.
Following is my mock:

Also, don't know how to:
-add below indexes in this package
-add values inside the bars like shown in mock.
Following is my Code:
class HiddenTicksAndLabelsAxis extends StatelessWidget {
  final List<charts.Series> seriesList;
  final bool animate;

  HiddenTicksAndLabelsAxis(this.seriesList, {this.animate});

  factory HiddenTicksAndLabelsAxis.withSampleData() {
    return new HiddenTicksAndLabelsAxis(
      _createSampleData(),
      // Disable animations for image tests.
      animate: true,
    );
  }

  @override
  Widget build(BuildContext context) {
    return new charts.BarChart(
      seriesList,
      animate: animate,

      /// Assign a custom style for the measure axis.
      ///
      /// The NoneRenderSpec can still draw an axis line with
      /// showAxisLine=true.
      primaryMeasureAxis:
          new charts.NumericAxisSpec(renderSpec: new charts.NoneRenderSpec()),

      /// This is an OrdinalAxisSpec to match up with BarChart's default
      /// ordinal domain axis (use NumericAxisSpec or DateTimeAxisSpec for
      /// other charts).
      domainAxis: new charts.OrdinalAxisSpec(
          // Make sure that we draw the domain axis line.
          showAxisLine: true,
          // But don't draw anything else.
          renderSpec: new charts.NoneRenderSpec()),
    );
  }

  /// Create series list with single series
  static List<charts.Series<OrdinalSales, String>> _createSampleData() {
    final globalSalesData = [
      new OrdinalSales('2014', 3, Colors.lightGreen),
      new OrdinalSales('2015', 6,Colors.lightBlue),
      new OrdinalSales('2016', 0.5,Colors.red),
      // new OrdinalSales('2017', 750000),
    ];

    return [
      new charts.Series<OrdinalSales, String>(
        id: 'Global Revenue',
        domainFn: (OrdinalSales sales, _) => sales.year,
        measureFn: (OrdinalSales sales, _) => sales.sales,
        colorFn: (OrdinalSales sales, _) => sales.color,

        data: globalSalesData,
      ),
    ];
  }
}

/// Sample ordinal data type.
class OrdinalSales {
  final String year;
  final double sales;

  final charts.Color color;

  OrdinalSales(this.year, this.sales, Color color)
      : this.color = new charts.Color(
            r: color.red, g: color.green, b: color.blue, a: color.alpha);
}

I being a newbie to flutter, please excuse if any problem.

A: You can use maxBarWidthPx inside of new charts.BarRendererConfig to set a max width to your bars.
Example:
var chart = charts.BarChart(
   series,
   animate: true,
   vertical: true,
   defaultRenderer: new charts.BarRendererConfig(
     maxBarWidthPx: 40,
   ),
),
...

A: There have no feature to set bar width yet. The Issue is open see Here.
You can minimize bar width by barGroupingType: charts.BarGroupingType.grouped and set fillColorFn: (Mileage mileage, _) => charts.ColorUtil.fromDartColor(Colors.transparent) inside charts.Series without middle one.
I share my code below:
Output:

Code:
custom_rounded_bars.dart file,
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:easytrax/screens/analytics_page.dart';

class CustomRoundedBars extends StatelessWidget {
  final List<dynamic> data;
  final bool animate;

  CustomRoundedBars(this.data, {this.animate});

  @override
  Widget build(BuildContext context) {

    var seriesList = _createSampleData(data);

    return new charts.BarChart(
      seriesList,
      animate: animate,
      barGroupingType: charts.BarGroupingType.grouped,
      defaultRenderer: new charts.BarRendererConfig(
          cornerStrategy: const charts.ConstCornerStrategy(30)),
    );
  }

  /// Create one series with sample hard coded data.
  static List<charts.Series<Mileage, String>> _createSampleData(dynamic data) {

    return [
      new charts.Series<Mileage, String>(
        id: 'mileage1',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (Mileage mileage, _) => mileage.day,
        measureFn: (Mileage mileage, _) => mileage.km,
        data: data,
        fillColorFn: (Mileage mileage, _) => charts.ColorUtil.fromDartColor(Colors.transparent),
      ),
      new charts.Series<Mileage, String>(
        id: 'mileage',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (Mileage mileage, _) => mileage.day,
        measureFn: (Mileage mileage, _) => mileage.km,
        data: data,
      ),
      new charts.Series<Mileage, String>(
        id: 'mileage2',
        colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
        domainFn: (Mileage mileage, _) => mileage.day,
        measureFn: (Mileage mileage, _) => mileage.km,
        data: data,
        fillColorFn: (Mileage mileage, _) => charts.ColorUtil.fromDartColor(Colors.transparent),
      ),
    ];
  }

}

analytics_page.dart file,
import 'package:easytrax/Common/custom_rounded_bars.dart';
import 'package:flutter/material.dart';

class AnalyticsPage extends StatefulWidget {
  static const String page = 'analytics_page';
  @override
  _AnalyticsPageState createState() => _AnalyticsPageState();
}

class _AnalyticsPageState extends State<AnalyticsPage> {

  List<Mileage> _createSampleData(){
    final data = [
      new Mileage(10, 'April 27'),
      new Mileage(38, 'April 28'),
      new Mileage(60, 'April 29'),
      new Mileage(20, 'April 30'),
      new Mileage(45, 'May 01'),
      new Mileage(35, 'May 02'),
      new Mileage(55, 'May 03'),
    ];

    return data;
  }

  @override
  Widget build(BuildContext context) {

    var data = _createSampleData();

    return Scaffold(
      body:Container(
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(16.0),
              height: 300.0,
              child: CustomRoundedBars(data),
            ),
          ],
        ),
      ),
    );
  }
}

/// data type.
class Mileage {
  final int km;
  final String day;

  Mileage(this.km, this.day);
}

A: inside the bar renderer there is a strokeWidthPx property
defaultRenderer: new charts.BarRendererConfig(
    strokeWidthPx: 1.0,
)

A: The size of the bar depends on the parent widget size.
In my case im using a vertical bar chart.
Size is the responsive size from the utility:
MediaQuery.of(context).size;

Im using it to make it responsive, but you can use you paren height or width if is horizontal.
Container(
  height: size.height * 0.1 * list.length +
    (size.height * 0.05),
  child: SimpleBarChart(),
),

Finally im setting the height by each list item to size.height * 0.1 (10% height of the device), and also (IMPORTANT) i add the half of the parent meassure (size.height * 0.05), because this will be the height (in my case (width in yours if you have it horizontal (normal))), of the meassure axises.
I hope you get a solution. Happy coding!


text:
Q: How to Limit The Size of Div in Twig What i Need :
    * All div should be of Equal Height and width.

problem im facing
 * is some data some div are bigger then another div.

Here is Snapshot Url:
 http://postimg.org/image/bxelzcb09/.

Api:
 {
 data: [
 {
id: 42166,
Company_Website: "http://www.amphenol-highspeed.com/",
company_name: "Amphenol High Speed Interconnect",
city_name: "New York",
country_name: "USA",
comp_img: null,
Product_Name: null
},
{
id: 42167,
Company_Website: "http://www.clearfieldconnection.com/",
company_name: "Clearfield, Inc.",
 city_name: "Plymouth",
country_name: "USA",
comp_img: null,
Product_Name: null
},
}

code of twig :
 {% for item in data.about.data%}
 {%if  ((loop.index-1)%2)=='0' %}

 {% endif %}

{{item.company_name }}

{{item.city_name }}
           {% if item.Company_Website is defined and item.Company_Website is not empty%}

                     {% endif %}

            {% if item.comp_img is not empty %}

          {% endif %}

            {% set foo = item.Product_Name|split(',') %}
            {% for i in  foo|slice(0, 5) %}
            {{ i }} {% if loop.index > 1 %}
                      ,{{ i }}
                    {% endif %}
            {% endfor %}

   {%if ((loop.index)%2) == '0' %}

 {% elseif  (loop.last) %2 !='0'%}

 {% endif %}
  {% endfor %}

  {% if data.about.data|length < '30' and request.ajax =='0' %}

    {% elseif data.about.data|length < '30' %}

  {% endif %}

*

*i just want size of each div  should be equivalent of each .

*cases a.) consider 4 div as  shown in image

*

*if first div is enrich with data and second infront of enrich div is null with no data.

*if first div is enrich with null data and other with big amount of data .

*please tell how to resolve this issue , problem is in css or i could solve this issue through coding.

*i need all div with or without enrichment of data should be of same size.

*i tried to remove spaces i follow link:http://twig.sensiolabs.org/doc/tags/spaceless.html.
any  valuable idea are most welcome ?

A: Maybe you should use CSS as said by DarkBee, or you could use the JS equalizer system of Foundation working fine.
http://foundation.zurb.com/docs/components/equalizer.html


text:
Q: What do we gain with higher order logics? Gödel's speed up theorems seem to say that higher order logics offer shorter shortest proofs of various propositions in number theory. Explicitly, he gave the following

Theorem.
  Let $n>0$ be a natural number. If $f$ is a computable function, then there are infinitely many formulas $A$, provable in $S_n$ ($n$-th order logic), such that if $k$ is the length of the shortest proof of $A$ in $S_n$ and $l$ is the length of the shortest proof of $A$ in $S_{n+1}$, then $k>f(l)$.

I am not well versed in computable functions but I believe the identity function is computable, so the above inequality would simplify to tell us that the shortest proofs get shorter as we move into higher logics.
How does this reconcile with the following quote from Bell and Machover's "A course in Mathematical Logic":

However, most logicians agree that [second and higher order] languages are, at least in principle, dispensable. Indeed, let $\mathfrak{U}$ be any structure and let $\mathfrak{B}$ be a structure obtained from $\mathfrak{U}$ in the following way.  The universe of $\mathfrak{B}$ consists of all undividuals of $\mathfrak{U}$ plus all sets of individuals of $\mathfrak{U}$. The basic operations of $\mathfrak{B}$ are defined in such a way that when they are restricted to the universe of $\mathfrak{U}$ they behave exactly as the corresponding basic operations of $\mathfrak{U}$. Finally, the basic relations of $\mathfrak{B}$ are all the basic relations of $\mathfrak{U}$ plus two additional relations: the property of being an individual of $\mathfrak{U}$, and the relation of membership between an individual of $\mathfrak{U}$ and a set of individuals of $\mathfrak{U}$. Then any statement about $\mathfrak{U}$ expressed in a second-order language with set variables, can easily be "translated" into a statement about $\mathfrak{B}$ in first order language. A similar argument applies to other higher-order languages. We therefore do not lose much by confining our attention to first order languages only.

From the argument they outline it seems they lose nothing by restricting their attention to first order languages, but this goes against the grain of the speed up theorems unless I'm missing something - does the "translation" from a second order statement over $\mathfrak{U}$ to a first order statement over $\mathfrak{B}$ require more symbols? This goes against what seems to be the implied translation, where we interpret the symbols for subsets of the universe of $\mathfrak{U}$ as the symbols in $\mathfrak{B}$ added to denote these subsets, which seems like it would yield a translation of equal length.
Giorgio Mossa's answer here seems to indicate that the difference lies in the standard semantics of the languages in question, not their syntax, but this is somewhat unclear to me as the semantics of a language are fixed as soon as we choose a structure to interpret the language in, which it seems has been done in the above quote. Any assistance is greatly appreciated.

A: Bell and Machover don't say (in the quote) anything about statement length, so this doesn't necessarily contradict Gödel.
I can't speak about (universal) shortest proof, but "translating" between higher and lower logics can become unwieldy. This paper by Shapiro [1] might be of general interest to the question, but also specifically an example by Boolos discussed on page 46 (I don't have access to the Boolos paper [2])

If the logic were complete, it might be natural to assume that the mathematician proceeds, or could proceed (or should proceed), by deducing consequences of the axiomatization. This would weigh in favor of first-order logic, since it is complete. However, this natural thought is problematic. Boolos [1987] gives an example of a valid argument $I$ in a first-order language and sketches a short derivation of the conclusion of $I$ from its premises in a second-order deductive system. A slight variation on the argument would yield a model-theoretic proof that $I$ is valid in the model-theoretic semantics. Since $I$ is first-order, and first-order logic is complete, there is a derivation of the conclusion of $I$ from its premises in a standard first-order deductive system. Boolos shows, however, that the shortest first-order derivation of $I$ has more lines than there are particles in the known universe.$^1$ We cannot know that $I$ is valid via a derivation of it in a first-order deductive system. Boolos concludes that

... the fact that we so readily recognize the validity of $I$ would seem to provide as strong a proof as could be reasonably be asked for that no standard first-order logical system can be taken to be a satisfactory idealization of the... processes... whereby we recognize (first-order!) logical consequences.

Clearly, if a first-order argument is valid then in principle an epistemic agent can learn this via a derivation in a standard, first-order deductive system. However, examples like these should make one wary of the epistemic significance of these 'in principle' declarations
$^1$ See my [Foundations without Foundationalism] Chapter 5, Section 5.3.4 for this and other cases of 'speed-up'

I think Shapiro and Boolos have different views ("cannot know") related to finitism than Bell and Machover ("We therefore do not lose much"), but that's getting a bit off topic. The example, I think, is still relevant though.
Of course, the one example does not mean all such statements "blow up" in a similar manner.
[1] Stewart Shapiro. "Do Not Claim Too Much: Second-order Logic and First-order Logic" Philosophia Mathematica, Volume 7, Issue 1, February 1999, Pages 42–64, https://doi.org/10.1093/philmat/7.1.42
[2] Boolos, G. [1987]: "The consistency of Frege's Foundations of Arithmetic" in Judith Jarvis Thompson (ed.), On being and saying: Essays for Richard Cartwright.Cambridge, Massachusetts: MIT Press, pp. 3-20.

A: The debate about first-order and higher-order logics is a bit of a  religious issue. There are many ways to argue one way or the other: first-order logic has very nice meta-theoretical properties, higher-order logic achieves categoricity, etc., and one can always produce an argument in one's favor.
The Stanford Encyclopedia on the Emergence of First-order Logic makes a point that the logicians who established the importance of first-order logic used higher-order logic for many years after first-order logic was identified as an object of interest. When the fundamental meta-theoretic theorems about first-order logic were discovered, they were sometimes taken as evidence of deficiency of first-order logic. While today many think it is obvious that first-order logic is the One True Logic to rule them all (as I said, it's a religious issue), this was not the case in the past.
It really depends on what you want to do with logic.
If you're a logician who wants to study meta-theoretic properties of formal systems, then first-order logic is a sweet spot. It is very expressive, but it also has extremely good meta-theoretic features (completeness theorem, compactness theorem, Lindström's theorem). Higher-order logic is even more expressive, but lacks some of the nice properties of first-order logic.
If you're a categorical logician, then you are interested in the connections between formal systems and structure, as perceived in category theory. In this case your view might be that logic is dictated by semantics. For example, the internal language of toposes is fully higher-order, while the internal logic of algebraic varieties is regular logic (just equations, conjunctions, and $\exists$). And if you only care about Grothendieck toposes and geometric morphism, geometric logic is for you.
If you're a mathematician, you probably care mostly about using logic as a tool, in which case the primary concern is expressivity. You do not want to be told that some very natural mathematical idea cannot be stated formally, so you would naturally gravitate towards higher-order logics. However, it is known that such needs for expressivity can largely be met by combining first-order logic with set theory. And since logic and set theory are typically taught by logicians, who prefer first-order logic for their own purposes, the prevalent formal system advocated today is first-order logic with set theory. But ultimately, for an ordinary mathematician it does not matter much which one they use.
Computer-scientists have their own ideas about logic and typically take an engineering point of view: use the tool that is appropriate for the situation at hand. For example, when we formalize mathematics with a proof assistant (software that aids and oversees writing of formal proofs), we seek a formalism that allows us to get the job done as directly as possible. For large scale projects the overriding concern becomes proof engineering: how to organize large libraries of definitions and theorems, how to search them, how to write proofs so that they are robust with respect to small changes, etc. Traditional logic has almost nothing to say about these topics, and consequently does not influence much the choice of formalism used in proof assistants. So many proof assistants use type theory, which could be characterized as "predicative higher-order", a reasonable middle ground between first-order and unrestricted higher-order.

A: I think my dissertation topic gives a distinction from the perspective of a functional type. Although it is a specialization, it seems to me a natural one. For a poster which expands on some details, see http://arxiv.org/abs/1408.2784 .
One can express hyperassociativity, the statement "All term operations are associative", by means of a hyperidentity, which is a (in a linguistic sense) compact object in  a certain second order language, and this will apply to various classes of universal algebras.  In the case that the corresponding first order language has only one binary operation symbol, there is another compact representation: the conjunction of the five sentences that assert that the five binary term operations b(x,x), b(x,y), b(x,b(x,y)),b(x,b(y,y)), and b(x,b(y,x)) are associative.  There is also a similar and less interesting version when the language has only finitely many unary function symbols.
However, if the language incorporates more function symbols, we no longer have this: hyperassociativity is not logically equivalent to a finite set of first order identities. There does not appear to be a compact way to present hyperassociativity for these kinds of structures.  So second order here means shorter in a significant way.
Gerhard "The Many Ways Of Hyperassociativity" Paseman, 2019.05.30.

A: I think the difference lies in the specific structures.
What the second statement says is

"For any second order formula $\phi$, there is some first order formula $\hat\phi$ such that $(\mathfrak U, R_0...R_n)\vDash\phi \leftrightarrow (\mathfrak V, Q_0...Q_n,\in,\mathfrak U)\vDash\hat\phi$."

This is easy enough to verify, as $\mathfrak U\vDash R_n(x_0...x_n) \leftrightarrow\mathfrak B\vDash Q_n(x_0...x_n)\land x_0\in\mathfrak U...x_n\in\mathfrak U$.
What the first statement says is that second order logic can provide proofs for theorems in first order logic in general faster. This would be confusing if $\mathfrak U$ and $\mathfrak B$ were the same structures, yet they are different. A proof using the relation symbols of $\mathfrak U$ is not nesscarily as fast as a proof using the relation symbols of $\mathfrak B$, as $\mathfrak B$ has the additional unary predicate $\mathfrak U$ and the relation symbol $x\in X$.
The point of the second quote, is that for a larger structure $(\mathfrak W,E)$ such that $E$ can interpret $Q_0...Q_n,\in,\mathfrak U$, $(V,\in)$ for example, every second order statement about $(\mathfrak U, R_0...R_n)$ can be reduced to a first order statement about $(\mathfrak V, Q_0...Q_n,\in,\mathfrak U)$. However, from the perspective of $(\mathfrak V, Q_0...Q_n,\in,\mathfrak U)$, it is much larger then $(\mathfrak U, R_0...R_n)$.

A: Your error is simply assuming that there is only one kind of higher-order logic (HOL). Contrary to your last paragraph, there are at least 2 major kinds, corresponding to 2 different semantics:
In full semantics, once you fix the domain (of individuals), you can no longer choose the interpretation of the higher-order sorts (starting with the subsets of individuals), because that is determined by the iterated power-sets of the domain (more precisely what the meta-system thinks are the power-sets). By the incompleteness theorem for PA, even second-order logic (SOL) with full semantics cannot be captured by a computable formal system.
In general semantics, you not only must choose the domain but also must choose the interpretation of each higher-order sort, and typically the only restriction is that it must respect the comprehension axioms that you want to have. For example if you want to have full higher-order comprehension, then you have the axiom ( $∃x∈S_{k+1}\ ∀t∈S_k\ ( t∈x ⇔ φ(t) )$ ) for each (higher-order) property $φ$ with one parameter from $S_k$, where $S_k$ denotes the level-$k$ sort. In SOL we usually require just predicative comprehension, namely where $φ$ only quantifies over $S_0$ (i.e. the individuals), which correspond to the first-order definable subsets of the domain.
Note that HOL with general semantics can be captured by multi-sorted FOL, and hence by one-sorted FOL (simply by using predicate-symbols to represent the sorts). It is in this precise technical sense that we "do not lose much by confining our attention to first order languages only". But it is wrong to infer that "it would yield a translation of equal length". Even merely extending an FOL system to the SOL system with predicative comprehension is equivalent to having internal definitorial expansion, which allows one to avoid repetition of long formulae.
Note that multi-sorted FOL (and the one-sorted translation) is semantically complete for HOL with general semantics, but of course not semantically complete for HOL with full semantics. Moreover, the Henkin construction shows that if a countable HOL system $T$ (i.e. with countable language) has a general model, then it also has a countable general model.
Furthermore, the speedup theorem you linked to does not actually show a speedup attributable to the use of HOL over FOL! Note that the proof in that SEP article uses additional assumptions, namely the higher-order induction schema instead of just the first-order induction schema. That speedup is due to the ω-incompleteness of PA rather than anything to do with HOL, as shown clearly by the proof. This is also obvious from the fact that if PA proves Q then PA+Q is still an FOL system and proves Q with a very short proof...


text:
Q: How can I call an instance method from a generic object? Say I have an arrayList containing items of different classes, all of them having the same method: draw();
I have a third class with a method drawItems() that takes in the arrayList as a parameter. Now, how can I call the draw() method on those objects if they are passed as generic objects?
This below doesn't work. I can see why.
Java doesn't know the item has such a function.
How can I get around this?
public void drawItems(ArrayList<T> data)
{
    data.forEach((T item) -> {
        item.draw();
   });
}

UPDATE
Thank you everyone. I did it as follows:
1) Create interface named Drawable:
public interface Drawable {
    public void draw();
}

2) Implement interface into Item class:
public class Item implements Drawable {

    @Override
    public void draw(GraphicsContext gc) {
        //...
    }
}

3) Adjust drawItems:
public void drawItems(ArrayList<Drawable> data) {

    data.forEach((Drawable item) -> {
        item.draw();
    });
}

A: Your T type parameter is unbounded, so the compiler makes no assumptions about the methods guaranteed to be available (except for Object methods).  That's why it can't find the draw method.
Do your classes that have the draw method inherit from some superclass or interface that declares the draw method?  If not, create that interface, e.g. Drawable.
Then change the parameter data to be of type List<? extends Drawable>, so you can pass in a List<Drawable> or e.g. a List<DrawableSubclass>.
If instead you must use the type parameter T, declare T (I'm assuming it's on the class) to be T extends Drawable.
Either way, with the upper bound, everything in the List will be Drawable, so the compiler knows that any objects in that list will have a draw method.


text:
Q: How do I turn on JMX in ActiveMQ 5.2 Whats the proper way to enable JMX in ActiveMQ 5.2? I've seen conflicting documents, so I was wondering if anyone out there knows what the proper config file change should be. I think I might have it working by changing the batch file I use to start ActiveMQ, but I don't really know.

A: <!-- Use the following to configure how ActiveMQ is exposed in JMX -->
<managementContext>
  <managementContext createConnector="true" />
</managementContext>

Put this inside the bean of your broker in the activemq.xml file and it should do the trick. Your connector will be created in localhost:1099, and you shouldn't need to modify the batch file.
Regards,
Seb

A: with a default installation, just edit your /bin/activemq file and setup the ACTIVEMQ_SUNJMX_START property as follows...

ACTIVEMQ_SUNJMX_START="-Dcom.sun.management.jmxremote.port=1099
  -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false"

A: What conflicting documents have you seen? This one explains it pretty well. There is no need to change any batch files.


text:
Q: How to add markers on svg image rendered in xamarin forms I am new to xamarin and developing a cross-platform app using xamarin forms PCL way.
I have a map image in svg format. I am using SkiaSharp library to load that image on my UWP application through PCL. I have 1 ListView having names of locations. I want to draw annotation or location marker on image, on click of the respective list view item.
For ex: If I will click on XYZ location the marker will be shown on the particular location.
This functionality can be easily achieved by using any map api or xamarin maps, But my problem is I can't use any map api and have to show location on image only.
Please Suggest any solution. Any help would be appreciated.
Thanks in advance.

A: I do not think this is possible the way you are handling the SVG image.
When a map is presented in a vector or raster file, there is usually a header or companion file containing the latitude and longitude of the top right and bottom left of the image. This is then used along with the image to load the map into a mapping plugin. Simply drawing the map using SkiaSharp will  not allow you to determine where a pin should be positioned.
Can you get the map in another format suitable for using with Xamarin Maps?


text:
Q: Unmodifiable form in sencha touch I have a Map<String, String> that I'd like to display to a user but I don't want them to be able to select the field to modify it's value. I've been using a form with textfields and setting setting a property to disable them. This is not ideal as their aesthetics change. Am I doing it the correct way and simply need to apply some css or is their a better way of doing this?

A: You could make a form 'label' which is un-modifiable but looks like the rest of the form. Might need a few tweaks but this should get you started:
Ext.form.LabelField = function(config){
   Ext.form.LabelField.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.LabelField, Ext.form.Field,  {
    isField: true,
    value: '',
    renderSelectors: {fieldEl: '.x-form-labelfield'},
    renderTpl: [
        '<tpl if="label">',
            '
{label}
',
        '</tpl>',
        '
{value}
',
   ],
   setValue:function(val) {
      this.value = val;
      if(this.rendered){
         this.fieldEl.update('' + val + '');
      }
    return this;
   },

});

Ext.reg('labelfield', Ext.form.LabelField);

A: I have had the same need and wanted the field to function similar to the ExtJS displayfield. I have done this in Sencha Touch by creating the field, disabling it, then adding back the normal field class. The editor is removed using the disable : true, but the field isn't grayed out and still is easy to read.
{
    xtype: 'textfield',
    disabled: true,
    disabledCls: 'x-field',
    label: 'Label',
    name: 'name'
}

This could become a simple override if I had enough of these fields and took the time to override the other field types I needed.


text:
Q: Estimating number of infected people and getting bounds of its probability based on a few samples. This question came on my exam a few week ago, and I've been stuck on it ever since.
Say a hospital has received 500 blood samples for COVID testing. We want to estimate how many of the the samples are of infected people before testing them all. Also, we can assume that are no false positives/negatives.
Let m be the total no. of infected samples out of these 500. Now, 20 samples are randomly chosen, and it is found that n of these are of infected people. These are the following questions we have to answer:

*

*What is the estimate of m, given the value of n? That is, $E[M|N=n]$ where N denotes the random variable  of infected samples from the 20 randomly chosen ones, and M denotes the number of infected samples out of 500.

*Say, 4 out of these 20 are of those infected. What is $P[M>E[M] + 1| N = 4]$? This is to find out how reliable the expected value is.
Any other assumptions required can be made.
My approach:
$P(M=m, N=n) = \frac{\binom{m}{n}\binom{500-m}{20-n}}{\binom{500}{20}}$, so we can find $E[M|N=n]$ as $\sum_{m=n}^{500} m\frac{P(M=m, N=n)}{Pr(N=n)}$, where $Pr(N=n) = \frac{1}{21}$(I don't think this part is correct, but since $n ={0,1,2....20}$, I wrote this down)
Thanks in advance, this question has really been bugging me!

A: Your expression $\ {500\choose20}\ $ is the number of subsets of size $20$ that can be drawn from your set of $500$.  The expression $\ {m\choose n}{500-m\choose 20-n}\ $ is, for a given subset of size $\ m\ $, the number of subsets of size $\ 20\ $ which include exactly $\ n\ $ members of that given subset and exactly $\ 20-n\ $ members of its complement.  So, if each subset of size $\ 20\ $ is equally likely, the fraction $\ \frac{{m\choose n}{500-m\choose 20-n}}{{500\choose20}}\ $ is the probability that your randomly chosen subset of size $\ 20\ $ contains exactly $\ n\ $ members of the given subset of size $\ m\ $.
The problem here is that the description of the problem makes $\ m\ $ a non-random number whose value is already determinable, although unknown.  Its exact value could be obtained by testing all $500$ blood samples.  Non-Bayesians would consider it inappropriate to treat it as a random variable and if they had to estimate its value from a random sample of size $20$ they would probably use some sort of significance test.
That your exam question does treat it as a random variable implies, I presume, that you're required to adopt a Bayesian approach, which would entail your assigning a prior distribution to that random variable. For the moment, let's treat this prior, $\ \pi\ $, say, as arbitrary:
$$
\pi_m=P(M=m)\ .
$$
You can then obtain the posterior distribution of $\ M\ $, given $\ N=n\ $ , from Bayes's theorem:
\begin{align}
P(M=m\,|\ N=n\,)&=\frac{P(N=n\ |\,M=m\,)P(M=m)}{P(N=n)}\\
&=\cases{ \frac{{m\choose n}{500-m\choose 20-n}\pi_m}{\sum_{i=n}^{480+n} {i\choose n}{500-i\choose 20-n}\pi_i}& if $\ n\le m\le n+ 480$\\
0&otherwise .}
\end{align}
Your formula for $\ E[M|N=n]\ $ is correct, except that \begin{align}
P(M=m, N=n)&=\frac{{m\choose n}{500-m\choose 20-n}\pi_m}{{500\choose20}}\ \text{ and}\\
P(N=n)&= \displaystyle\sum_{i=n}^{480+n} \frac{{i\choose n}{500-i\choose 20-n}\pi_i}{{500\choose20}}\ .
\end{align}
The value of $\ P\big(M>E[M]+1\,|\,N=4\big)\ $ is given by
\begin{align}
P\big(M>E[M]+1\,|\,N=4\big)&=\sum_{m=
\max(\lfloor E[M] \rfloor +2, 4)}^{484}P(M=m\,|\,N=4\,)\\
&=\frac{\sum_{m=
\max(\lfloor \sum_{m=0}^{500}m\pi_m \rfloor +2, 4)}^{484} {m\choose 4}{500-m\choose 16}\pi_m}{\sum_{i=4}^{484} {i\choose 4}{500-i\choose 16}\pi_i}\ .
\end{align}
Coming to the vexed question of what to choose for $\ \pi\ $, the choice of priors in Bayesian statistics is nearly always going to be somewhat subjective.  Since I have no idea how this topic was treated in your course, I also have little idea how your examiners would have expected you to handle it in the exam question you've quoted.  Also, while I have used statistics professionally, I certainly wouldn't claim to have ever been a professional statistician, let alone one with a good working knowledge of Bayesian statistics.  Please bear that in mind while reading the following suggestion.
If your $\ 500\ $ blood samples were taken somewhat randomly from a large population, it seems to me that a reasonable choice for $\ \pi\ $ would be $\ \text{Binomial}(500,p)\ $:
$$
P(M=m)={500\choose m}p^m(1-p)^m
$$
for some value of $\ p\ $, which would be the proportion of the large population that are infected.  For COVID-$19$, $\ p\ $ will not be known exactly, but if you know the population from which the sample was drawn you may have a reasonable estimate that you could use for the value of $\ p\ $.  Otherwise, the best you're likely to be able to do is to get expert epidemiologists to suggest a range $\ [a,b]\ $ in which they think $\ p\ $ is $90\%$ (say) likely to lie, and choose a suitable prior distribution $\ \Pi\ $ for $\ p\ $ such that  $\ \Pi\big([a,b]\big)=0.9\ $. Your prior distribution for $\ M\ $ will then be
$$
P(M=m)={500\choose m}\int_0^1p^m(1-p)^md\Pi(p)\ ,
$$
and $\ E[M]=500E[p]=500\displaystyle\int_0^1pd\Pi(p)\ $.


text:
Q: Не могу добавить элемент в массив в React через setState Нужно добавить имя в конец массива при нажатии на кнопку. Не могу найти ошибку.
class App extends React.Component {
    constructor() {
        super();
        this.state = {arr: ['Коля', 'Вася', 'Петя', 'Иван', 'Дима']};
    }

    addItem() {

        this.setState({arr: this.state.arr.push("Tom")});
    }

    render() {

        const list = this.state.arr.map((item, index) => {
            return
{item}

        })

        return

{list}

            <button onClick={this.addItem}>Press me</button>

    }
}

A: Забудь про классы, переходи на функциональное программирование с хуками
const App = () => {
    let [_state, setArray] = useState(['Коля', 'Вася', 'Петя', 'Иван', 'Дима']);

    return (

                {
                    _state.map((item, index) =>
{item}
)
                }

            <button onClick={() => setArray([..._state, 'Tom'])}>Press me</button>

    )
}


text:
Q: Curve Fitting piecewise function with a fixed parameter I have a function as shown below
   def PPM(x,a,b,c,d):  # d is the fixed parameter
       if x>d:
          return 100/(1+((x-d)/c)**(-a))**b
        else: return 0

the parameter d is fixed(calculated with lab data), and I need to curve fit to get all other parameters.
I am now using lmfit because I can easily fix parameter d.
    from lmfit import minimize, Parameters
    def residual(params, x, data):
        d = params['d']
        a = params['a']
        b = params['b']
        c = params['c']
        if x>d:
            PP = 100/(1+((x-d)/c)**(-a))**b
        else: PP = 0
        return data-PP

but it shows ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(), I know it is related to vectorize the function with array but no idea how to do that in lmfit
I also modified the code above a little bit by doing
    def residual(params, x, data):
        d = params['d'] #the value of d is 0.078528, the fixed parameter
        a = params['a']
        b = params['b']
        c = params['c']
        PP = 100/(1+((x-d)/c)**(-a))**b
        PP[np.where(d>x)] = 0
     return data-PP

    params = Parameters()
    params.add('d', value=0.078528, vary=False)
    params.add('a', value=0.25, min=0, max=1)
    params.add('b', value=5, min=0.5, max=500)
    params.add('c', value=0.001, min=0.0001, max=1)
    out = minimize(residual, params, args=(x, data))

After modifying the code, there is no warning (error) after running but the fitted data looks terrible. It seems whatever the initial values I assigned, none have been changed. (I guess because if x is less than d, the function has no value)
By the way I use minimize from lmfit to leastsquare the residual
Is there a way to do it in python?
Data and Fitting in excel the picture is what I expected
And the data
    x = [6.2e-5, 1.2e-4, 2.5e-4, 5.0e-4, 1.0e-3, 2.0e-3, 4.2e-3, 8.8e-3, 2.0e-2,
       4.6e-2, 1.1e-1, 2.6e-1, 6.0e-1]
    Data = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.056, 0.478, 3.725, 7.800]

Thanks!
Regards,
Steve

A: If it doesn't have to be vectorized you can use list comprehension
from lmfit import minimize, Parameters
import numpy as np

x=[0.0000621, 0.0001242, 0.00024932, 0.00049772, 0.00100004, 0.00202676, 0.00417128,0.00878876, 0.01984992, 0.04636064, 0.10731156, 0.25733504, 0.60121724]
data=[ 0,0,0,0,0,0,0,0,0,0.056443102,0.478543944,3.724743415,7.795926674]

def residual(params, x, data):
    d = params['d']
    a = params['a']
    b = params['b']
    c = params['c']
    PP = [100/(1+((x_-d)/c)**(-a))**b if x_>d else 0 for x_ in x]
    return np.array(data)-np.array(PP)

I have no idea what the values of a,b,c, and d should be so I made them up.
residual({'d':1,'a':2,'b':3,'c':4},x,data)
array([0.        , 0.        , 0.        , 0.        , 0.        ,
       0.        , 0.        , 0.        , 0.        , 0.0564431 ,
       0.47854394, 3.72474341, 7.79592667])

A: It is always better to include a full, minimal script showing what you actually did, and the actual results that you actually got, including the fit report.
Your question shows that you did fix the np.any() vs. np.where() issue. Great!
Your model still has
    PP = 100/(1+((x-d)/c)**(-a))**b

and the plot and question suggest that some values of x will be < d.  With c and a both positive real numbers
    ((x-d)/c)**(-a)

will have some values that are complex or give nan.   You then take
1 + ((x-d)/c)**(-a) and raise that to the b power, with a starting value for b of 20!  That's pretty big and not very stable: 2.0**20 ~= 1 million, 2.5**20 ~= 100 million, and 3.0**20 ~= 3000 million.
I would suggest exploring your parameter space a little more.  For example, what do you get when you just evaluate your model with the starting values?  Is b=20 reasonable for your data?   Note that the fit will start with your initial value, make very, very small changes to that to see what direction to move the parameter values.  If that very, very small change does not change the result, the fit does not know where to move to.
As a hint that you gave yourself: your plot of the data uses a log scale for the x axis.   I would also suggest using a log-scale for the y-axis,  and even fitting in log-space:  that is, treat log(data) as the data to be fit, and have the model compute the log of your PP function. Of course you wouldn't set PP=0 where x<d, but you might set it to some very small value, perhaps like:
  pparg = (x-d)/c
  pparg[np.where(pparg<0)] = 1.e-30
  # log(pp) = np.log(100 * (1 + pparg**(-a)) **(-b)))
  logpp = np.log(100)  - b * np.log(1 + pparg**(-a))
  return (log(data) - logpp)

hope that helps....

A: I want to thank all of you who participated in the question.
I finally got what I would like by constraining the fixed value in a very small range.
I will show the code below.
import numpy as np
from scipy import optimize
import pylab as pl

def PPM(x,a,b,c,d):  #  model
    """
    The model is pp=100/(1+((x-d)/c)**(-a))**b, d is the fixed parameter
    """
    pp = np.piecewise(x,[x <= d, x > d],[ 0,lambda x: 100/(1+((x-d)/c)**(-a))**b])
    return pp

x = [6.2e-5, 1.2e-4, 2.5e-4, 5.0e-4, 1.0e-3, 2.0e-3, 4.2e-3, 8.8e-3, 2.0e-2, 4.6e-2, 1.1e-1, 2.6e-1, 6.0e-1]
y0 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0.056, 0.478, 3.725, 7.800] #x,yo are lab data
d = 0.071010176 #Calculated value for the fixed parameter
p1 = [1,1,0.5,d] # initial values for parameters
param_bounds = ([0, 0.1, 0.00001,0.99*d],[1, 18, 1, 1.01*d])
popt,pcov = optimize.curve_fit(PPM, x, y0, p0=p1,bounds=param_bounds)

#interpolation for plotting
x1 = np.linspace(x[0],x[-1],100)
y1 = [PPM(i,popt[0], popt[1], popt[2], popt[3]) for i in x1]

#plot
pl.semilogx(x, y0, "o", label=u"Lab Data")
pl.semilogx(x1, y1, label=u"Fitted Model")
pl.legend(loc="best")
pl.show

It looks good enough for me. If you have any advice or recommendations, please comment.
Thanks again!
Steve


text:
Q: Cant change Textview with Handler @Override
public void run() {
int ret = 0;
byte[] buffer = new byte[16384]; //ByteArray
int i;
while (ret >= 0) {
    try {
        ret = mInputStream.read(buffer);
    } catch (IOException e) {
        break;
    }
    i = 0;
    while (i < ret) {
        int len = ret - i;
       if(len >=1){
           Message m = Message.obtain(mHandler);
           int value = (int) buffer[i];
           m.obj = new ValueMsg(value);
           mHandler.sendMessage(m);

Here i think i send byte for byte from buffer to mHandler. It´s possible to send the total value? Or is the like Bluetooth byte for byte?
           }
1
    }

};

Handler mHandler = new Handler(){
    public void handleMessage(Message msg){
        ValueMsg t = (ValueMsg)msg.obj;
        mTextView.setText(""+t.getReading()+" Value");
        }

};
It does not change the textView i dont understand why.
@Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
public class ValueMsg{
private int reading;

public ValueMsg(int reading){
    this.reading = reading;
}
public int getReading(){
    return reading;
}

Is it always necessarily to write a new class to for the value?
And the last question can you advise me a good book for android and java or a youtube site?:)
EDIT:
Handler mHandler = new Handler(){
        public void handleMessage( Message msg){
             post (new Runnable() {
                public void run() {
                    ValueMsg t = (ValueMsg) msg.obj;
                    mTextView.setText(" Value");
                }
            }
        }
    };

A: change
ValueMsg t = (ValueMsg)msg.obj;
        mTextView.setText(""+t.getReading()+" Value");

to
 post(new Runnable() {
void run() {
 ValueMsg t = (ValueMsg)msg.obj;
            mTextView.setText(""+t.getReading()+" Value");
});

use your handler to post the change to the UI thread