Delete record from MongoDB using express.js and react.js

Question: I am trying to delete a Record from MongoDB. My express code is like below
const deleteAddress = (req, res, next) => {
    var curid = req.params.id;
    curid = curid.replace(/\s/g, '');
    Address.findByIdAndRemove(curid)
      .then(result => {
        res.status(200).json({
          message: 'Address Deleted',
          result
        });
      })
      .catch(err => {
        console.log(err);
        res.status(500).json({
          message: 'Error Occured',
          error: err
        });
      });
}

I am getting error like below
{ CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Address"
[0]     at new CastError (/home/foysal/Videos/my-app/node_modules/mongoose/lib/error/cast.js:29:11)
[0]     at ObjectId.cast (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schema/objectid.js:242:11)
[0]     at ObjectId.SchemaType.applySetters (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:845:12)
[0]     at ObjectId.SchemaType._castForQuery (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:1248:15)
[0]     at ObjectId.SchemaType.castForQuery (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:1238:15)
[0]     at ObjectId.SchemaType.castForQueryWrapper (/home/foysal/Videos/my-app/node_modules/mongoose/lib/schematype.js:1217:15)
[0]     at cast (/home/foysal/Videos/my-app/node_modules/mongoose/lib/cast.js:307:32)
[0]     at model.Query.Query.cast (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:4340:12)
[0]     at castQuery (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:4192:18)
[0]     at model.Query.Query._findAndModify (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:3204:23)
[0]     at model.Query.<anonymous> (/home/foysal/Videos/my-app/node_modules/mongoose/lib/query.js:3165:8)
[0]     at model.Query._wrappedThunk [as _findOneAndRemove] (/home/foysal/Videos/my-app/node_modules/mongoose/lib/helpers/query/wrapThunk.js:16:8)
[0]     at process.nextTick (/home/foysal/Videos/my-app/node_modules/kareem/index.js:369:33)
[0]     at process._tickCallback (internal/process/next_tick.js:61:11)
[0]   message:
[0]    'Cast to ObjectId failed for value "undefined" at path "_id" for model "Address"',
[0]   name: 'CastError',
[0]   stringValue: '"undefined"',
[0]   kind: 'ObjectId',
[0]   value: 'undefined',
[0]   path: '_id',
[0]   reason: undefined,
[0]   model:
[0]    { [Function: model]
[0]      hooks: Kareem { _pres: [Map], _posts: [Map] },
[0]      base:
[0]       Mongoose {
[0]         connections: [Array],
[0]         models: [Object],
[0]         modelSchemas: [Object],
[0]         options: [Object],
[0]         _pluralize: [Function: pluralize],
[0]         Schema: [Function],
[0]         model: [Function],
[0]         plugins: [Array] },
[0]      modelName: 'Address',
[0]      model: [Function: model],
[0]      db:
[0]       NativeConnection {
[0]         base: [Mongoose],
[0]         collections: [Object],
[0]         models: [Object],
[0]         config: [Object],
[0]         replica: false,
[0]         options: null,
[0]         otherDbs: [],
[0]         relatedDbs: {},
[0]         states: [Object],
[0]         _readyState: 1,
[0]         _closeCalled: false,
[0]         _hasOpened: true,
[0]         '$internalEmitter': [EventEmitter],
[0]         _listening: false,
[0]         _connectionOptions: [Object],
[0]         name: 'addresses',
[0]         host: 'localhost',
[0]         port: 27017,
[0]         user: undefined,
[0]         pass: undefined,
[0]         client: [MongoClient],
[0]         '$initialConnection': [Promise],
[0]         _events: [Object],
[0]         _eventsCount: 2,
[0]         db: [Db] },
[0]      discriminators: undefined,
[0]      events:
[0]       EventEmitter { _events: {}, _eventsCount: 0, _maxListeners: undefined },

Comment: It looks like the `curid` you are passing is `undefined`, check it before passing it to mongo query.
Comment: Since you appear to have separated your "route handler" definition from the method, check that you are even passing `id` at all there. You should have something like `route.delete('/yourpath/:id', deleteAddress)` defined there. Without the `:id` the `req.params.id` will be `undefined`. Note also your request should be using a `DELETE` verb and including the `id` on the path. i.e `DELETE /yourpath/5ca97bf60c3b7005121b2e21`
Answer: there can be two reason, as  kgangadhar said you would have not getting the curid, second if you are getting the curid than you have pass as a
ObjectId you would have getting a stringID
var ObjectId = Schema.ObjectId

const deleteAddress = (req, res, next) => {
   var curid = new ObjectId(req.params.id);
   curid = curid.replace(/\s/g, '');
   Address.findByIdAndRemove(curid)
     .then(result => {
        res.status(200).json({
        message: 'Address Deleted',
        result
     });
   })
   .catch(err => {
      console.log(err);
      res.status(500).json({
      message: 'Error Occured',
      error: err
    });
  });
}

Comment: Mongoose actually **automatically** casts to `ObjectId` based on the schema defined with methods like `findByIdAndRemove()` ( and any other methods for that matter). The specific error actually says `undefined` as well, therefore **manually casting** would make no difference at all.


Does GridGain support SSL connection between each cluster member?

Question: Does GridGain support SSL connection between each cluster member? If yes, can you show me how to do that?
Thanks,
Bill
Comment: Generally using SSL for clustered communication will introduce significant overhead and add latencies to the network. A much better approach would be to encrypt the portions of data you need to protect on your own, before storing them in cache.
Answer: GridGain supports SSL only for client connections (GridGain provides .NET and C++ thin clients), but not for communication between nodes.
To enable SSL for client connections, configure your server nodes like this:
<bean id="grid.cfg" class="org.gridgain.grid.GridConfiguration">

    <property name="restEnabled" value="true"/>

    <property name="clientConnectionConfiguration">
        <bean class="org.gridgain.grid.GridClientConnectionConfiguration">

            <property name="restTcpSslEnabled" value="true"/>

            <property name="restTcpSslContextFactory">
                <bean class="org.gridgain.client.ssl.GridSslBasicContextFactory">
                    <property name="keyStoreFilePath" "keystore/server.jks"/>
                    <property name="keyStorePassword" value="123456"/>
                    <property name="trustStoreFilePath" "keystore/trust.jks"/>
                    <property name="trustStorePassword" value="123456"/>
                </bean>
            </property>
        </bean>
    </property>
</bean>

You will also need to provide SSL context factory on client configuration.
Answer: Ignite (and GridGain) allows you to use SSL for all possible connections.
To use SSL connection between nodes define property sslContextFactory in IgniteConfiguration.
<bean id="cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
  <property name="sslContextFactory">
    <bean class="org.apache.ignite.ssl.SslContextFactory">
      <property name="keyStoreFilePath" value="keystore/server.jks"/>
      <property name="keyStorePassword" value="123456"/>
      <property name="trustStoreFilePath" value="keystore/trust.jks"/>
      <property name="trustStorePassword" value="123456"/>
    </bean>
  </property>
</bean>

You can also check official security documentation.
https://apacheignite.readme.io/docs/ssltls


How to reach array's elements from map?

Question: Here is my codes;
I have map and arrays like this;
Array dayHours{0,0,0,0,0,0};
Array1 day{"Monday","Tuesday","Wednesday","Thursday","Friday"};
map<pair<string,int>,pair<Array1 ,Array> > matchMap;

And i have a function like this;
void Course::addCourse()
{
    string a;
    int b;
    int total;
    int courseAdd;
    cout<<"How many course you want to add?"<<endl;
    cin>>courseAdd;
    cout<<"Enter the name of course and number of hours"<<endl;
    for(int i=0;i<courseAdd;++i)
    {

        setCourseName(a);
        setHours(b);
        getCourseList().insert({a, b});
        total += getHours();
        matchMap.insert({make_pair(a,b),make_pair(day,dayHours)});
    }

Here is the print function for map:
void Course::seeMap()
{
    map<pair<string,int>,pair<Array1 ,Array> >::iterator it;
    for(it=matchMap.begin();it!=matchMap.end();++it)
    {
        for(int i=0;i<5;++i)
        {
            cout<<(it->first).first<<(it->first).second<<(it->second).first[i]<<endl;
        }
    }
}

Here is what i get at the end:
    How many course you want to add?
2
Enter the name of course and number of hours
Enter the course name
124124124
Enter the course hours
5
Enter the course name
12414124
Enter the course hours
6
You added the courses succesfully!
124124124--->5--->Monday
124124124--->5--->Tuesday
124124124--->5--->Wednesday
124124124--->5--->Thursday
124124124--->5--->Friday
12414124--->6--->Monday
12414124--->6--->Tuesday
12414124--->6--->Wednesday
12414124--->6--->Thursday
12414124--->6--->Friday

What i need is a template like this;
Coursename1 ---> Coursehour1 ---> Monday;
Coursename2 ---> Coursehour2 ---> Tuesday;
Coursename3 ---> Coursehour3 ----> wednesday;

....
How can i organize the code for a template like this?
Here is a minimal example for everyone can understand what i get.
How many course you want to add?
1
Enter the name of course and number of hours
Enter the course name
Coursenam1
Enter the course hours
4
You added the courses succesfully!
Coursenam1--->4--->Monday
Coursenam1--->4--->Tuesday
Coursenam1--->4--->Wednesday
Coursenam1--->4--->Thursday
Coursenam1--->4--->Friday

Comment: please make a minimal runnable example
Comment: Or is it possible to get this template with lists or vectors?
Comment: i add simple example about what i get
Comment: Is this what you said?
Answer: I changed the codes like this;
for(int i=0;i<courseAdd;++i)
    {
        setCourseName(a);
        setHours(b);
        getCourseList().insert({a, b});
        total += getHours();
        matchMap.insert({make_pair(a,b),make_pair(day1[i],dayHours)});
    }

void Course::seeMap()
{
    map<pair<string,int>,pair<string ,Array> >::iterator it;
    for(it = matchMap.begin();it!=matchMap.end();++it)
    {
        cout<<(it->first).first<<"--->"<<(it->first).second<<"--->"<<(it->second).first<<endl;
    }
}

And I get the template which I want.
How many course you want to add?
2
Enter the name of course and number of hours
Enter the course name
214124124
Enter the course hours
4
Enter the course name
12512515
Enter the course hours
5
You added the courses succesfully!
12512515--->5--->Tuesday
214124124--->4--->Monday

How to reach array's elements from map?


How to compute $\int_0^1x^a(1-x)^be^{cx}dx$?

Question:
How to compute the integral $I(a,b,c) = \int_0^1x^a(1-x)^be^{cx}dx$ ?

I know that,
$\int_0^1{x^a(1-x)^b}dx = \frac{\Gamma(a+1)\Gamma(b+1)}{\Gamma(a+b+2)}$. Using this result, I tried integration by parts; I got the following recurrence relation,
$I(a,b,c) = \frac{b}{c}I(a,b-1,c) - \frac{a}{c}I(a-1,b,c)$.
I don't know how to proceed. Any help is appreciated.
Thanks in advance.
Comment: Series expanding $e^{cx}$ is one option. This leads to something like $\sum_{n=0}^\infty\frac{c^n}{n!} \frac{\Gamma(a+n+1)\Gamma(b+1)}{\Gamma(a+b+n+2)}$ which looks like some sort of hypergeometric function.
Answer: This is essentially the the moment generating function of the beta distribution. The result is hypergeometric and cannot be further simplified.


Version 1 in trunk, Version 2 in a branch in SVN, what should I do going forward?

Question: Right now my project v1 (in production) is in Trunk, while v2 (in development) is in a Branch in SVN.  It is not likely that v2 will ever be merged into v1.
I want to migrate to Git in the near future because switching between v1 and v2  are very slow in SVN, and branch driven development is a pain in SVN.
I'm thinking of using a local Git repo and use git svn for now, and push the Git repo to a centralize server later when the team is ready.
How should my git workflow be if I want to work on v2 and dcommit to v2 branch in SVN?  Is there a better way of managing v1 and v2 concurrently going forward?
Thanks!
update: I'm thinking of doing the following, please comment whether this is a good idea:

SVN branch head to /branches/v1
git rebase branches/v2 on master
git svn dcommit to trunk
work on Master (trunk) going forward

What do you think?
Answer: The best thing to do is get everyone to move sooner than later to git.  It simply handles things like this better.  Git svn isn't designed to deal with branches that well, and although it works sometimes it's really not that safe.  IMHO, but then I'm not a git developer and I'm only speaking from experience of trying it and having pain.  For me, it's always much easier if the upstream (yourself, your team or someone else) can convert to git.  Suddenly problems just go away.
In the future, you can do what I did in Net-SNMP's conversion to git and branch management: merge everything over, and do an initial merge of the v1 project into the main development branch with -s ours.  That basically sets the version history to ignoring all the past development differences between the new branches, but lets you apply new patches to v1 into the tree and still merge those new patches into v2.  This way we have, in Net-SNMP, often 4-5 active branches.  Patches go into the oldest most relevant branch and get merged upward.  Suddenly we no longer have issues remembering to apply patches to every branch!
Simple git wrapper scripts automate the multiple-branch patch management and the whole effort is mostly harmless.  Only some major architectural changes cause minor-headaches and require manual merging/porting.


Multiplus dominio com Codeigniter

Question: Tenho uma hospedagem com dois domínios, dominio1.com.br e dominio2.com.br.
Como o Codeigniter esta na raiz da hospedagem, como faço para que, quando
eu acessar o dominio1.com.br ele pegue o conteudo da pasta site1 e exiba, e faça
a mesma coisa no dominio2.com.br e exiba o conteudo da pasta site2 em que se misture?
Não sei se é possível fazer isso no .htaccess
Eu gostaria de aproveitar a mesma hospedagem para 2 sites diferentes com domínios diferentes sem ter que comprar uma hospedagem para cada site.
Answer: Você pode fazer isso usando o .htaccess. Depois você precisa tratar isso no Code Igniter.
<code>Options +FollowSymLinks

RewriteEngine on

#
# Redirecionando o domínio para a pasta correta
#
# Regra para cada domínio, copie e adapte para cada domínio
RewriteCond %{HTTP_HOST} ^(www.)?dominio1.com$
RewriteCond %{REQUEST_URI} !^/pastadominio1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /pastadominio1/$1

#
# Removendo /pastadominio1/index.php da URL
#
# Regra para cada domínio, copie e adapte para cada domínio
RewriteCond %{HTTP_HOST} ^(www.)?dominio1.com$
RewriteRule ^(/)?$ pastadominio1/index.php
</code>

Multiplus dominio com Codeigniter


Rhodes mobile: How to get the current action?

Question: I'm creating a pagination partial here, and I would like it to work from any controller/action.
I'm trying something like: url_for(:query => {:page => 2}) for example.
it works, but it redirects for the controller_root?page=2
I need it be controller_root/current_action?page=2
I tryed url_for(:action => action_name, :query => ...) but it didn't work.
is there any method that returns the current action?
Answer: ok, i found it at <code>@request['action']</code>


Efeito "Fade in e Delete - VBA"

Question: por gentileza, estou com uma dúvida no VBA - MS EXCEL 2016
Eu preciso criar uma macro que quando eu a aciono, ela busca uma imagem.png em meu computador e insere-a sobre a planilha com o efeito gradativo de Fade-in. Após isso, a imagem deve aparecer por 3 segundos e deve ocorrer o efeito de "Delete" desa imagem, para não atrapalhar a edição da planilha.
Tentei vários metodos de macro para essa solução, e sempre algo da errado.
Por gentileza, voces poderiam me ajudar com a codificação?
Muito obrigado!
OBS: O código que eu estava usando era:
Sub Imagem_na_Planilha()

 Dim Plan As Worksheet, Imagem As Shape
 Dim Clear As Double
 Set Plan = ActiveSheet
 Set Imagem = Plan.Shapes.AddPicture("C:\Downloads\gg.PNG", msoFalse, msoCTrue, 50, 100, 170, 70)

 End Sub

Answer: O problema é que ao inserir como Shape de imagem, a alteração da transparência não é possível. Você precisa antes inserir um AutoShape.
Passos

Criar um AutoShape na Planilha Ativa (um retângulo ou outra forma)
Preencher o Shape com a imagem desejada
Loop de alterar a transparência para causar o efeito de Fade in
Esperar 3000 ms e apagar a imagem

Código
Segue o código com um exemplo de como realizar isto:
Option Explicit
'Declara função Sleep
#If VBA7 Then
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) 'For 64 Bit Systems
#Else
    Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'For 32 Bit Systems
#End If

Sub Imagem_na_Planilha()

    Dim Plan As Worksheet, Imagem As Shape
    Dim I As Long

    Set Plan = ActiveSheet
    Set Imagem = Plan.Shapes.AddShape(msoShapeRectangle, 50, 100, 170, 70)
    Imagem.Name = "imagem"
    Plan.Shapes("imagem").Select
    With Selection.ShapeRange.Fill
        .Visible = msoTrue
        .UserPicture "C:\TestFolder\imagem.jpeg"
        .TextureTile = msoFalse
        .Transparency = 1
        'Fade in
        For I = 1 To 100
            .Transparency = 1 - I / 100
            DoEvents
        Next
    End With
    Sleep (3000)
    Plan.Shapes("imagem").Delete
End Sub

Efeito "Fade in e Delete - VBA"


How to get the id of tr where id = value in array in jquery

Question: I have a table with tr that have unique numeric ids set. I also have an array that contains the ids.
So basically I need to check if the tr id is in the array of values, if so add or remove a class from an element inside of it.
I have figured this out....
Comment: No one is going to write this from scratch for you. Where are you stuck?
Comment: Numbers are not valid for IDs in HTML. Please refer to this answer for naming conventions: http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html
Comment: Not asking anybody to write it for me...Just not sure how to go about it.
Answer: with:
var ids = [ /* array of ids */ ];
do:
$('#'+ids.join(',#')).addClass('classy');
Answer: Something like this?
var ARR = [ /* some ids */ ];

$('tr').each(function() {
  if (ARR.indexof($(this).attr('id')) != -1)
     $(this).addClass('hurray!');
});

Comment: `this.id` works perfectly well - `$(this).attr('id')` is totally unnecessary.
Comment: Older IEs don't have Array#indexOf.
Comment: @AnthonyGrist Oh, of course, bad habit. :)
Comment: @Flo Yeah, one can easily implement it by himself... but who cares about older IE anyway? :)
Answer: Solution assumes same class being add/removed to same elemnt within row. Passing true/false to toggleClass() determines add/remove
$('tr').each(function() {
    var isInArray=$.inArray(parseInt( $(this).attr('id'), 10)) > -1;
    $(this).find(someEleemntSelector).toggleClass('className',isInArray );
});


Proof related to matrix

Question: Let $A$ and $B$ be $n \times n$ real matrices such that  $A^2 = I, B^2 = I$ and $(AB)^2 = I$.  Prove that $AB = BA$.
Someone help me with this problem
Comment: You could help yourself by searching.
Answer: $I = (AB)^2 = (AB)(AB) = A(BA)B \implies AB = A(A(BA)B)B = (A^2)(BA)(B^2) = BA$
Answer: $AB=(AB)^{-1} \iff AB=B^{-1}A^{-1} \iff AB=BA$
Comment: how do AB becomes equal to its inverse
Comment: @AmpatishanArun: Because $(AB)^2=I$. That's the definition of inverse.
Comment: $AB^2=I \iff (AB)^{-1}(AB)^2=AB^{-1}I \iff AB=AB^{-1}$
Comment: okay i got it thanks

Proof related to matrix


Classify elements from a list to another classification

Question: I''ve got a List<Foo>. Foo class contains a Type property. Type property is a enum.
  public enum Type
  {
       Arithmetic, Fraction, ...
  }

  public class Foo
  {
      public Type ProblemType
      {
          get; set;
      }
  }

I'd like to generate another list where it is sorted by ProblemType, and each one contains Foo clases which belong to the same Type. I can imagine I should use Enumerable, but I don't know how use them.
Thanks in advance
Comment: So you want a list of lists, where each inner list contains `Foo`s with the same `ProblemType`?
Answer: You can use GroupBy() to do that:
List<List<Foo>> groupedLists
    = yourList.GroupBy(foo => foo.ProblemType)
              .OrderBy(group => group.Key)
              .Select(group => group.ToList())
              .ToList();

In passing, I would advise against using Type as the name of your enum, as getting into name conflicts with System.Type is usually not a good idea. You can even name it ProblemType, since writing public ProblemType ProblemType { get; set; } is unambiguous.
Comment: If you first order and then select, you could use the `Key` property of the grouping. I think it's clearer than using `First()`.
Comment: @svick, you're absolutely right. Answer updated accordingly, thanks :)
Answer: To sort by ProblemType, you can try this
var sortedFooList = fooList.OrderBy(f => f.ProblemType);

sortedFooList will be IOrderedEnumerable<Foo>. If you want List<Foo>, just add .ToList() after calling OrderBy().
Answer: Assuming you already have a List<Foo>, you can query that list to provide an ordered collection by ProblemType:
List<Foo> myFoos = GetFooList();

var sortedFoos = myFoos.OrderBy(f => f.ProblemType);

sortedFoos is an enumerated collection sorted by Foo.ProblemType.


Custom warning on when viewing cart (anonymous users)

Question: I am wondering with what mechanisms it would be possible to add a warning message to anonymous users viewing their cart saying: "Please log in with any of the listed services in order to proceed to checkout".
If possible I'd like to avoid changing the module's code in order to avoid future update problems.
Thanks for any help,
Best
Answer: The easiest way is overriding a default cart page template (cart page has been created with Views module, name - 'commerce_cart_form', display - 'default');

Create a template for Style Output
Copy the content of it
Views module provides logged_in variable in template_preprocess_views_view(&$vars) function, so you can check with that variable and display a text;

example (views-view-table--commerce-cart-form--default.tpl.php):
<?php if (!$logged_in): ?>
  MY MESSAGE FOR THE ANONYMOUS
<?php endif; ?>

<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>
  // Rest of code from Style Output

Comment: Hi, thanks for your quick answer! I have found the view, and figure that I could add the message, right? Unfortunately I'm totally lost on the first step: Create template for Style Output. Since I dont know what it is I don't find where I could do that.
Comment: @dmeu Open the 'Commerce cart form' in Views UI, expand `Advanced` section, open `Theme:Information`, copy the last template suggestion from `Style Output` section, paste it into your theme's folder (`views-view-table--commerce-cart-form--default.tpl.php`), click the StyleOutput link again, copy the code and put it into your created file, save the view, clear the cache, that's it. After that you can modify that template as I mentioned above.
Comment: @dmeu Here is a [video](http://www.youtube.com/watch?v=1Cfc11_sb5M) which shows how to theme a views..
Comment: Ok, thanks for the explanation, found it! Very useful. Meanwhile I have discovered the php views module which enables me to add your proposed code as a field in the footer. Thanks for your help!


how do I update new image on JFrame ? (I tried everything but it didn't work)

Question: so this is my source code, I'm trying to make stick man moving so first, I tried to make head moving. it works, but the problem is that the past movement and the reccentt movement stick together so it goes like this OOOOOOOOOOO when it's supposed to go like this O
I tried repaint() validate() updateUI() but it still didn't work
any idea?
<code>    package JamesTestPackage;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    import javax.swing.*;
    public class StickmanUI extends JPanel implements ActionListener, KeyListener{
Timer t = new Timer(1,this);
int x=180;
int x_vel = 0;
int y_vel = 0;
public StickmanUI(){
    t.start();
    addKeyListener(this);
    setFocusable(true);
}
public void paintComponent(Graphics g)
{
    Graphics2D g2 = (Graphics2D) g;

    g2.setStroke(new BasicStroke(5));

    g2.drawLine(200, 50, 200, 100); // body

    g2.drawLine(200, 100, 220, 150); // right leg

    g2.drawLine(200, 100, 180, 150); // left leg

    g2.drawLine(200, 75, 170, 100); //left arm

    g2.drawLine(200, 75, 230, 100); //right arm

    g2.drawOval(x, 10, 40, 40); // head

}
@Override
public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    x= x + x_vel;
    repaint();
}
@Override
public void keyPressed(KeyEvent arg0) {
    // TODO Auto-generated method stub
    if(arg0.getKeyCode()==KeyEvent.VK_RIGHT)
        x_vel = 1;
    else if(arg0.getKeyCode() == KeyEvent.VK_LEFT)
        x_vel = -1;

}
@Override
public void keyReleased(KeyEvent arg0) {
    // TODO Auto-generated method stub
    x_vel =0;
}
@Override
public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub

}
}
</code>
Answer: When doing custom painting the first statement in your paintComponent() method should be:
<code>super.paintComponent(g);
</code>
to make sure the background is cleared before painting is done.
Read the section from the Swing tutorial on Custom Painting for more information and working examples to get your started.
Comment: thanks ! it works now ! but one more question though what does
super.paintComponent(g); do? I've always seen those but never really understood what it does


AngularJS routing 404 error with HTML5 mode

Question: I just got started with angular js , i tried routing and worked pretty well .The problem is when i refresh the page it is showing 404 error since it is checking in my actual directory rather than checking in routes.
here is the complete code
<!DOCTYPE html>

  <base href="/" />

  blue

  green //blue.html and green.html are in same directory as index.html

Click on the links to load blue or green.

here are the browser outputs

this is when i refresh

please provide me with some solution.
Comment: is becouse you need call ´localhost/blue´  when you need use ´localhost/#/blue´
Comment: https://stackoverflow.com/a/44271854/4588990 check if is working fine, please
Comment: Possible duplicate of [Reloading the page gives wrong GET request with AngularJS HTML5 mode](https://stackoverflow.com/questions/16569841/reloading-the-page-gives-wrong-get-request-with-angularjs-html5-mode)
Answer: HTML5 mode requires URL rewriting.
From the Docs:

HTML5 Mode
Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html). Requiring a <base> tag is also important for this case, as it allows AngularJS to differentiate between the part of the url that is the application base and the path that should be handled by the application.
— AngularJS Developer Guide - Using $location (HTML5 Mode Server Side)

For NodeJS and ExpressJS
var express = require('express');
var path = require('path');
var router = express.Router();

// serve angular front end files from root path
router.use('/', express.static('app', { redirect: false }));

// rewrite virtual urls to angular app to enable refreshing of internal pages
router.get('*', function (req, res, next) {
    res.sendFile(path.resolve('app/index.html'));
});

module.exports = router;

For IIS on Windows
<rewrite>
  <rules>
    <rule name="AngularJS" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <action type="Rewrite" url="/" />
    </rule>
  </rules>
</rewrite>

See, How do I configure IIS for URL Rewriting an AngularJS application in HTML5 mode?
For apache
RewriteEngine On RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^

See, How to rewrite url in apache htaccess for angularjs app
For more information
Article: AngularJS - Enable HTML5 Mode Page Refresh Without 404 Errors in NodeJS and IIS.
Comment: I changed the .htaccess to redirect to index.html. now it works fine!
Comment: done !  RewriteEngine On

  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
  RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
  RewriteRule ^ - [L]

  RewriteRule ^ /index.html
this is the code i have used in .htaccess
Answer: I had the same problem using http-server as my local webserver, its a known issue with html5 and detailed in the angular-ui/ui-router FAQ.
I switched to Nginx (install via apt-get) with the following /etc/nginx/sites-enabled/default
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    #root /var/www/html;

    root /home/conor/workspace/code_institute/route_test;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;

    #server_name _;
    server_name localhost;

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to displaying a 404.
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.html;
    }

 }

To start/stop/reload after changes;
sudo service nginx <start|stop|status>

The FAQ also covers Apache/Express/asp.NET
Answer: The problem is that you are not assigning the variable,$routeProvider to your controller, this causes the controller not to be able to access the variable $ routeParams
try it
 /*app.controller("blue_control", function($scope) {

      $scope.msg = "this is blue";
    });
    app.controller("green_control", function($scope) {
      $scope.msg = "this is green";
    });*/
 app.controller("blue_control", function($scope,$routeParams) {
     console.log( $routeParams.term_user);
      $scope.msg = "this is blue";
    });
    app.controller("green_control", function($scope,$routeParams) {
      $scope.msg = "this is green";
    });

UPDATE

I think you can not use a route version with a lower version of angulajs
please change a upper version of angularjs for example
/* */

<!DOCTYPE html>

  <base href="/#/" />

  blue

  green //blue.html and green.html are in same directory as index.html

Click on the links to load blue or green.


should we invent a new type of numbers to solve this?

Question: in the beginning humans tried to solve equations such as 2+x=0 and they invented negative numbers for that purpose, then things like x²=-1 to invent imaginary numbers, but equation like x²+x⁴=0 have no solution? so should humans again invent a new type of numbers?
Comment: Surely $x=0$ is a solution to $x^{2}+x^{4}=0$? With $x\in\mathbb{R}$. Have a look at [Algebraic Closure](http://en.wikipedia.org/wiki/Algebraic_closure)
Comment: You can solve all real equations in $\mathbb{C}$.
Comment: @LorieKirchner What is your definition of "number"?
Comment: Also: this is not how things work in real life. Nobody cared to solve $x^2=-1$ back in the day. The historical reason was a weird property of [Cardano's formula](http://usf.usfca.edu/vca/PDF/vca-bombelli.pdf). The $x^2=-1$ thing is a fairytale.
Comment: It has solutions in $\mathbb{C}$. Let $x^2=u$. Alternatively, write $x^4+x^2=x^2(x^2+1)=x\cdot x \cdot(x-i)\cdot(x+i)=0$
Comment: i mean could there be equations that humans dont know the solution to yet and they have to invent a new type of numbers to do that?
Comment: $$0=x^2+x^4=x^2(x^2+1)\iff x=0\;\;or\;\;x^2=-1\iff x=\sqrt{-1}$$and the complex numbers $\;\Bbb C\;$ solve the last equation.
Comment: so we humans discovered all types of numbers?
Comment: Yes, we are really powerful. Don't you think so?
Comment: Bill's question's on the money: what do *you*, @LorieKirchner, understand by "number" ?
Comment: @LorieKirchner. Just for curiosity, I suggest you have a look at http://en.wikipedia.org/wiki/Hypercomplex_number. Happy New Year !
Comment: See [here](http://en.wikipedia.org/wiki/Number_system#Classification_of_numbers) a probably nonextensive list of commonly used numbers in mathematics.
Comment: @LorieKirchner. Humans discovered all types of numbers required for today problems. I am sure that other numbers will appear to solve problems we do not know they exist TODAY.
Answer: The fundamental theorem of algebra tells you that every polynomial equation can be (completely) solved in $\mathbb{C}$.
By the way:
$$x^2+x^4 = x^2(x+i)(x-i)$$
and thus $x^2+x^4=0$ is solved by $x=0,-i,i$.
As for having to "invent new types of numbers", you can do that. If you are interested in the subject, I would advise you to take a look at the subject of field extensions.
Answer: To offer a softer answer than Daniel's:
I invented a new (so far as I know) kind of number just the other day. They have horrible properties and no application that I can see. And using known model-theoretic tricks I could keep making more ugly number systems (especially if I don't even require them to be rings or some such).
The set-theoretic universe is likely brimming with things we could call "number systems", that's not really the question. The question is whether there are any of these that solve as many problems as $\mathbb{C}$ does, or which aren't most easily thought of as a construction on an existing number system (e.g. the hyperreals).
Further, many of our common number systems have notable universal properties that make them especially useful, the way $\mathbb{N}$ is a NNO and the free monoid on one generator, and $\mathbb{Z}$ is the free group on one generator and a separator in the category of groups. These sorts of properties make our common number systems very natural and very powerful to single out.


Why can't a strictly injective function have a right inverse?

Question: let $A = \{a \in A\}$ and $B = \{b \in B\}$. Let $f$ be a strictly surjective map $f: A \to B$ meaning for every $b$ in $f$'s codomain there must exist some $a$ in $f$'s domain.
$f$ is surjective if and only if it has a right inverse. Why not a left? let $g$ be the inverse map $g: B \to A$ there is no composite function $g\circ f$ that maps $(A \to B) \to A$ Since $f$ is only surjective there can be multiple elements of $A$ that are mapped to the same element in $B$.
Actually it makes sense since $g$ must be a function and its domain would be mapping to multiple co-domain.
What is the reason for a strictly injective function not to have a right inverse?
There cannot be a composite function $f\circ g = (B\to A)\to B$ when $f$ is strictly injective.
if $f$ is strictly injective, there must exist a subset of $A$ that uniquely maps to a subset of $B$ of equal order.
It makes sense that it cannot exist if $f$'s codomain is smaller than $g$'s domain but otherwise it looks fine to me. Can someone explain how this does not make sense?
Comment: I assume that with "strictly ..." you mean "..., but not bijective"?
Comment: yes. $~~~~~~~~~$
Comment: The elements of $B$ which are not contained in $f(A)$ are the problem. Any candidate $g$ must map these elements to $A$, but then $f \circ g$ maps them into $f(A)$, so $f \circ g$ cannot be the identity map. If you replace $B$ with $f(A)$ then a right inverse does exist.
Comment: Just a remark on style: "$A=\{a\in A\}$" is literally the same as writing "$A=A$". It would be a bit more elegant to just say "Let $A,B$ be sets$\dots$".
Comment: @Bungo I don't think so. Since $f$ is defined as $f: A \to B$ , $B$ is the image of $A$ under $f$ is it not? So $g$ just re-uses this image in its domain. I think the wording is unspecific.
Comment: @Obliv: The image of $A$ under $f$ is $f(A)$. This equals $B$ if and only if $f$ is **surjective**. Otherwise, $f(A)$ is a proper subset of $B$.
Comment: okay but when I defined $f: A \to B$ and $f$ is strictly injective, I defined it wrong? I cannot say $f: A \to B$ but instead $f: A \to f(A)$?
Comment: @Obliv: The notation $f : A \to B$ means that $B$ is the **codomain** of $f$. This only means that $f(A) \subset B$, not that $f(A) = B$. The latter is only true if $f$ is surjective.
Comment: Okay. So I don't see why the right inverse does not exist still. $g$ maps $B \to A$ and $B$ is the codomain of $f$ and $A$ is the domain of $f$. Why wouldn't $f$ be able to map its own domain back to its codomain?
Comment: @Obliv  $f$ can't map **anything** into $B \setminus f(A)$, by the definition of $f(A)$.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/38343/discussion-between-obliv-and-bungo).
Answer: Summarizing the discussion in the comments and chat:
The notation $f : A \to B$ means that $f$ maps each element $x \in A$ to some $y \in B$. In general, not every element of $B$ is "reached" by $f$ in this way. The image of $A$ under $f$, denoted $f(A)$, is the subset of $B$ consisting of the elements of $B$ which are "reached" by $f$.
We always have $f(A) \subset B$, but the containment is proper in general. We have $f(A) = B$ if and only if $f$ is surjective.
Let us suppose that $f$ is not surjective. We will show that in this case, $f$ does not have a right inverse.
Any candidate right inverse $g$ must be a map $g : B \to A$.
Now, since $f$ is not surjective, the set $B \setminus f(A)$ is nonempty. Choose any element $y \in B \setminus f(A)$. Since $y \in B$, it is mapped by $g$ to some element $x \in A$. Then, $f$ maps $x$ to some $z \in f(A)$, by definition of $f(A)$.
Summarizing, we have $y \in B \setminus f(A)$, and $g(y) = x$, and $(f \circ g)(y) = f(g(y)) = z$. Since $z \in f(A)$ and $y \not\in f(A)$, clearly $ z\neq y$. Since $f \circ g$ does not map $y$ to itself, $f \circ g$ cannot be the identity map on $B$. Therefore $g$ is not a right inverse of $f$.

Here is a concrete example. Let $A = [0,1]$ and $B = [2,4]$, and define $f : A \to B$ by $f(x) = x + 2$. Note that $f(A) = [2,3] \subset B$, and the containment is proper, so $f$ is not surjective.
If $g$ is a candidate right inverse for $f$, we must have $g : B \to A$, so in particular, $g$ must map $4$ to some element of $A$, say $g(4) = x \in A$. Then $(f \circ g)(4) = f(g(4)) = f(x) \in [2,3]$ by definition of $f$, and in particular, $(f \circ g)(4)$ cannot be $4$. Thus $f \circ g$ is not the identity map on $B = [2,4]$, so $g$ is not a right inverse of $f$.

Note that we could have defined $f$ the same way except with $B = [2,3]$ instead of $[2,4]$. Then $f$ would be surjective, and $g$ would have a right inverse, namely $g(y) = y - 2$.
Answer: Note that $f$ is surjective iff it has a right inverse, and $f$ is injective iff it has a left inverse. In particular, a surjective map that also has a left inverse is both surjective and injective, i.e., bijective. Likewise, an injective function that also has a right inverse is both injective and surjective, i.e., bijective. In other words, a strictly surjective/injective function does not have a left/right inverse.
Comment: Your memory is sharp. Thank you for reciting exactly what my textbook says.


How to write code to avoid pep8 W502 and E504 issue

Question: I couldn't find a good way to around pep8 E502 and W504
I have code like this
if (foo(a, b) or
    foo1(c, d) or
    foo2(e, f) ) and
    foo3(g, h):

If I write like this, then I get complain that I violate "W504 line break after binary operator".
However, if I add line break after binary operator, then I get complain that I violate "E502 the backslash is redundant between brackets"
If I couldn't make them into one line,  how should I write the code?
Answer: You are "supposed" to write
if (foo(a, b)
    or foo1(c, d)
    or foo2(e, f)
    and foo3(g, h)):

with the binary operator at the start of the next line.
Even PEP-8 wavers a bit on this; it suggests pre-operator breaks for new code, but accepts post-operator breaks as long as it is consistent throughout a file.
(I prefer post-operator breaks. To me, it more strongly suggests that the expression will continue onto the next line. As such, I would just use --ignore W504.)
Comment: this triggers W503 "line break before binary operator"
Comment: This might depend on which tool you are using. `pycodestyle` doesn't report *either* one by default (possibly a new decision since I posted this answer), because there is no universal consensus (even in PEP-8) on which is correct.


Python try except not using imported variable

Question: Imported module, connection_status_message.py:
connection_status_message = "Not Connected"

Try Except file, connect_to_server.py:
from Server.connection_status_message import connection_status_message

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        connection_status_message = "Could not reach host..."
        return
...

The issue is the variable is trying to be made local. So I read up on the issue and saw how to reference a global variable:
def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        global connection_status_message
        connection_status_message = "Could not reach host..."
        return
...

But now PyCharm is stating the import statement at the top is no longer being used.
How can I get this Try/Except to use the imported variable?
Comment: Consider using a OOP approach, creating a class called `Connection` that handles the `connect()` and have an attribute of `connection_status_message`.
Comment: Possible duplicate of [How can I override a constant in an imported Python module?](https://stackoverflow.com/questions/12496089/how-can-i-override-a-constant-in-an-imported-python-module)
Comment: `pass` is a keyword. You can't use it as a variable name.
Comment: `pass` was just an abbreviation. I was unaware that it was a keyword so I changed it to `password` in the question to avoid confusion. Sorry.
Answer: I couldn't replicate your issue, but if your import line is stored under a function, the variable is nonlocal instead of global:
def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        nonlocal connection_status_message
        connection_status_message = "Could not reach host..."

Another way is to not load the variable directly into your namespace so you have reference of where it came from to avoid local variables being created:
from Server import connection_status_message as csm
csm.connection_status_message

# "No Connection"

def func():
    csm.connection_status_message = "Could not reach host..."

csm.connection_status_message

# "Could not reach host..."

You might also consider creating a class to handle all these as an object:
class Connection(object):
    def __init__(self):
        self.connection_status_message = "No Connection"
        # TODO: initialize your class

    def connect(self, host, user, password):
        # TODO code connect criteria stuff here

    def connect_to_server(self, host, user, password):
        try:
            self.connect(host,user,password)
        except NoConnection:
            self.connection_status_message = "Could not reach host..."
            # ... return whatever ...#

Now you can do from Server import Connection and create a local Connection object to manipulate:
conn = Connection()
conn.connect_to_server(host, user, password)

This might be obvious, but in any case the value is only stored in memory during this execution.  The actual connection_status_message.py is never updated with this value.


Excel: Empilhar todas as colunas em uma única coluna

Question: Tenho uma planilha onde a mesma possui 2412 colunas com 20 linhas preenchidas cada uma. O que gostaria de fazer é mover todas essas 2412 colunas com seus respectivos registros em uma única coluna. Cheguei a tentar a opção Tranpor, a função =VSTACK e no Power Query as opções transformar colunas para tentar empilhar todas as colunas que possuo em uma única lista/coluna porém sem sucesso.
Abaixo segue um esboço/exemplo da planilha na ordem que está:
coluna 1 | coluna 2 | coluna 3
-------------------------------
01       | 06       | 11
02       | 07       | 12
03       | 08       | 13
04       | 09       | 14
05       | 10       | 15

Abaixo, a forma como gostaria que estivesse:
coluna 1
---------
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15

Como forma de demonstrar o problema, segue um link de uma planilha excel:
Planilha - Transformar colunas em uma única lista/coluna
Answer: Irei postar a solução que encontrei para o problema relatado aqui.

Primeiro, selecionei a área onde encontram-se os dados das colunas.

Feito isso, cliquei no menu "Dados" e em seguida fui em "Obter e Transformar Dados" clicando na opção "De Tabela / Intervalo".

Após ter clicado na opção "De Tabela / Intervalo", aparecerá uma caixa de diálogo. Clique no botão "ok". Feito isso, o editor Power Query será aberto.

Já no editor Power Query, vá até o menu "Adicionar Coluna" e clique em "Coluna de índice" na setinha com sentido pra baixo e em seguida clique na opção "De 0". Após isso, será criada uma coluna chamada "índice".

Clique com o botão direito no cabeçalho dessa coluna "índice" e escolha a opção "Transformar Outras Colunas em Linha".

Após isso, uma nova tabela com os dados empilhados aparecerão. Caso os dados estejam empilhados corretamente, é só ir no menu "Arquivo" e clicar na opção "Fechar e Carregar" e todos os dados aparecerão empilhados e ordenados.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: Para juntar todas as colunas em uma única coluna, uma opção é usar a função "Consolidar" do Excel. Aqui estão os passos para fazer isso:
Selecione a célula onde você deseja colocar os dados consolidados.
Na guia "Dados", clique em "Consolidar" na seção "Dados de Análise".
Na caixa de diálogo "Consolidar", selecione a opção "Por posição de células" e clique em "OK".
Na caixa de diálogo "Referências", adicione todas as colunas que você deseja consolidar na seção "Referências". Você pode fazer isso clicando na seta para baixo ao lado da caixa de texto e selecionando cada coluna na planilha.
Clique em "OK" para fechar a caixa de diálogo "Referências" e a função "Consolidar" irá juntar todas as colunas em uma única coluna na célula selecionada


$m$ people choosing $l$ elements out of $n$ independently, what is the probability of each element being chosen at least $k$ times?

Question: We have $m$ people and a set of $n$ elements. Each person chooses $l$ elements out of $n$, independently from each other. What is the probability that each element is chosen at least $k$ times?
Let $X_1, \dots X_n$ be the random variables counting how many times each element is chosen. I want to determine the density $\mathbb{P}(X_1=k_1, \dots X_n=k_n)$, then I can sum over all values greater than $k$ to determine the probability.
I am having a hard time trying to compute the combinations. The denominator of the probability is easy, because it's all possible combinations of $l$ elements out of $n$, repeated $m$ times, due to independence:
$$\binom{n}{l}^m$$
But how can I determine only those combinations, such that the elements are chosen exactly $k_1, \dots k_n$ times? I don't know if a simple formula exists for this.
Example:
Let's say we have $m=10$ people voting for $n=5$ parties. Each person is expressing $l=2$ votes (more precisely, they randomly choose $2$ different parties). What is the probability that each party gets at least $k=1$ vote?
Addendum: I am not sure if it helps, but I also thought of formalizing this problem in a different way. Basically it's a random $m \times n$ binary matrix, with each row summing to $l$ and each column summing to a number $\geq k$. I need to count all the possible matrices.
Comment: The example should be doable using brute force (case-by-case), and using a few tricks here and there to cut down on computation, although even then it's still very long and tedious. I don't see another way.
Answer: ۤFor $\color{blue}{l=1}$, the problem is equivalent to count the ways that $m$ distinct things can be distributed in $n$ distinct urns such that each urn has at least $k$ elements. It is given by
$$n!S_k(m,n)$$
where $S_k$ denotes the $k$-associated Stirling number of the second kind; for $k=1$ it is the Stirling number of the second kind (see Variants section in the link).
The probability is then given by
$$\frac{n!S_k(m,n)}{(m)^n}$$
The same idea can be used to find an upper bound for the number as follows:
$$n!S_k(m \times l,n)$$
in which each of the $n$ items can be selected multiple times (each person can give more than one vote to each party). Hence, the probability is less than
$$\frac{n!S_k(m \times l,n)}{\binom{n}{l}^m}.$$
The above results show that the problem for arbitrary $\color{blue}{l \ge 1}$ should be very difficult. I checked different recurrences, but could not find low-dimensional recurrences. Finally I reached to the following one, which seems to be more reasonable when $n$ is not a large number (other similar ones can be developed, but they seem to be less useful).
Let $A_{m,l}(k_1,...,k_n)$ denote the number of ways that $m$ persons can select $l$ items from $n$ distinct items such that each item $i$ is selected at least $k_i$ times by different persons. Then, we have the recurrence
$$A_{\color{blue}{m},l}(k_1,...,k_n)=\sum_{i_1+ \cdots +i_n=l}A_{\color{blue}{m-1},l}([k_1-i_1]^+,...,[k_n-i_n]^+)$$
where $[x]^+=\max(x,0)$, and
$$A_{m,l}(0,...,0)=\binom{n}{l}^m.$$ The recurrence is obtained by assuming that person 1 first selects his/her $l$ items, and the other persons select their items next.
The solution to the OP is $A_{m,l}(k,...,k)$, which can be obtained from the above recurrence.
To see how much the solution can be complex, the explicit formulas for two simple cases $k_2=0,k_3=0,\cdots, k_n=0$ and $k_3=0,k_4=0,\cdots, k_n=0$ are given below:
$$ A_{m,l}(k_1,0,...,0)=\sum_{i=k_1}^{n} \binom{n}{i} \binom{n}{l-1}^i\binom{n}{l}^{n-i}, n\ge \, k_1$$
$$A_{m,l}(k_1,k_2,0,...,0)=\\ \sum_{i=k_1}^{n}\sum_{j=k_2}^{n} \sum_{j_1} \binom{n}{i}\binom{i}{j_1}\binom{n-i}{j-j_1} \binom{n}{l-2}^{j_1}\binom{n}{l-1}^{i-j_1+j-j_1}\binom{n}{l}^{n-(i+j-j_1)}, \, n\ge k_1+k_2.$$


Dynamic JPanels error

Question: I hava CardLayout and want to have changing panels on it. For that I wrote my JFrame Class:
public class GUI_NewList extends javax.swing.JFrame {

CardLayout layout = new CardLayout();

public GUI_NewList() {
    initComponents();
    this.setLayout(layout);

    JPanel paChoose = new Choose();

    layout.addLayoutComponent(paChoose, "1");
    layout.show(paChoose, "1");
}

The class Choose:
public class Choose extends JPanel {

    public Choose() {
        setLayout(new GridLayout(3, 1));

        JButton btnPractice = new JButton("Practice");
        add(btnPractice);

        JButton btnNewList = new JButton("Create a new List");
        add(btnNewList);

        JButton btnEditList = new JButton("Edit a List");
        add(btnEditList);
    }
}

If I run this I get an error:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: wrong parent for CardLayout

Could you please tell me what I have done wrong?
Comment: For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/).
Answer: Here is an MCVE that fixes the problem. See code comments for details of the problem(s).
import java.awt.*;
import javax.swing.*;

public class GUI_NewList extends JFrame {

    CardLayout layout = new CardLayout();

    public GUI_NewList() {
        this.setLayout(layout);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel paChoose = new Choose();

        // this only adds it to the layout, not the container.
        layout.addLayoutComponent(paChoose, "1");
        // this adds it to the container (the content pane)
        add(paChoose);
        // the container of interest is the content pane.
        layout.show(this.getContentPane(), "1");

        pack();
        setVisible(true);
    }

    public static void main(String[] args) {
        Runnable r = () -> {
            new GUI_NewList();
        };
        SwingUtilities.invokeLater(r);
    }
}

class Choose extends JPanel {

    public Choose() {
        setLayout(new GridLayout(3, 1));

        JButton btnPractice = new JButton("Practice");
        add(btnPractice);

        JButton btnNewList = new JButton("Create a new List");
        add(btnNewList);

        JButton btnEditList = new JButton("Edit a List");
        add(btnEditList);
    }
}

Note: There is no good case here for extending either JFrame or JPanel.

Dynamic JPanels error


Populating multiple text fields based on a combo box

Question: What I am trying to do is populate text fields based on what a user selects in a combo box. The problem I'm running into is the text fields need data from multiple queries. One text box per query and in total there are 6. So the me.txtTextBox1 = me.cboComboBox1.column(1) will not work. This is probably a very simple fix but any help would be appreciated.
Comment: I read your question a couple of times and your intent is still not clear at all. Please elaborate and provide examples of current and desired situation.
Answer: You need an Event Procedure for the AfterUpdate event of you combo box. In that procedure, you could use 6 statements using the DLookup function, but that function is very slow. Therefore, I suggest to open 6 recordsets that return (at most) one record to retrieve the values for the 6 textboxes. When using 6 parameterized queries, the code could look like this:
Private Sub cboComboBox1_AfterUpdate()

    With CurrentDb

        Me.txtTextBox1 = Null
        With .QueryDefs("qryQuery1")
            !ParameterNameInQuery1 = Me.cboComboBox1
            With .OpenRecordset()
                If Not .EOF Then
                    Me.txtTextBox1 = !NameOfFieldInQuery1
                End If
                .Close
            End With
            .Close
        End With

        ' ... other 5 code Fragments for the other 5 textboxes ...

    End With

End Sub


Do the instruments used in a piece of music play a role in determining its genre?

Question: I am researching about music genres but I am confused if instruments played in music help in determining its genre?
What could be the differentiating features in genre recognition of music?
Comment: For all imaginable genres this may be impossible to answer. Even if I stop short of voting to close due to *needs more focus* narrowing the choice may also help getting more  answers.
Comment: It depends on how tight the sieve of the genre's definition is. A harp doesn't make a rock song not rock. A drum kit seems to turn Irish folk into country if you're not careful, especially if your bass is electric. A bassoon doesn't belong in a string quartet. Singing fifths instead of unisons and octaves makes Gregorian chant into organum.
Answer: Yes and no.
It mostly depends on the age in which the genre was born, but it should be noted that some labels often used as "genres" are more vague "instrumentation-based" (and, technically, not actual genres): it's pretty obvious that "Opera" requires singers, "Symphonic" can't be played by a percussion duo, and "Electronic" cannot be done without electronic instruments.
It is true that, usually, a genre is defined by the instruments that generated and popularized it:

rock music generally has at least one of guitars, drums or voice;
baroque is specific to instruments of its age: for instance you cannot have "strict" baroque music played with saxophones (that doesn't mean that you can't play baroque music with them);
EDM is by definition electronic, so it should be done using at least some electronic instrument (drum machines, synthesizers, etc);

As long as the genre-era instruments are used, any instrument can be used even if it's not one that is generally associated with the genre:

you can have a string quartet in a rock band;
some symphonic music of the 20th century used electronic instruments (like the ondes Martenot used in the Turangalila symphonie by Messiaen);
a friend of mine plays harp in a jazz band;
you certainly won't have modern drums in a romantic symphony;

Things get a bit weirder in the modern genres: on one side, some genres are really "vague", and on the other hand there are hundreds of very fragmentized "microgenres", which are controversely strictly defined.
"Pop" music is more a concept than a genre, also defined by its intention other than its music.
"Jazz" is more than a century old, and it's valid for New Orleans' music done with marching band instruments in the 1910s as well as when played with electronic instruments.
I won't even try to talk about "Rock".
Some genres of electronic music are defined by the age (and instrumentation) of their composition: songs that sound as 80-90s pop are considered "retro-pop" if written after that period. Some metal sub-genres are defined by specific usage of drums and guitars that have more than 6 strings.
Some genres are even specific to the lyrics: consider Christian metal.
So, in summary, the genre can also be determined by the instruments, but instruments alone can not determine the genre.
Comment: @developer101 well, it's not easy, and there's no absolute "rule": more than "what" instruments are used, it's usually a matter of "how" they are played, both considered alone and in the context of the others. Rhythm plays an important role in defining genre of modern music: a steady 4/4 bass drum is usually more "dance-oriented", alternation and syncopation leads to more "rock-ish" feelings, as with distorted guitars that play "power chords" (tonic, fifth, no thirds); harmonic structure is also considered, as pop and rock are often based on very few chords, while other genres have more ->
Comment: complex and longer harmonic progressions. Jazz music often has long progressions of chords rarely used in other genres. The whole structure is also a valid hint: pop music is generally based on 2-3 short and alternated sections (chorus, verse, bridge, etc) based on repetitions of few simple chords, as most rock music is (but pop usually has more lighter "tones"). Some groups of instruments are more typical of a genre (jazz, rock, latin music). There are dozens of aspects that could be considered, and that's also a reason for which identifying a specific "genre" is usually pointless :-)
Comment: @PiedPiper Tell it to ancient music fanatics who say that "if it's played with an 18th century violin, it's not baroque" ;-) Also, many classical and/or jazz enthusiast would even have harsh opinions on Loussier's music being one or the other... I know that baroque music played with modern instruments that didn't exist at the time is "still" baroque music (to some extent, actually: Tomita's or Gould's Bach renditions can hardly be considered "baroque" in the strict meaning of the genre), but that's exactly my point: genres are just approximate *reference* labels, beyond that they're pointless.
Comment: Thank you for such an explained answer :) Can you please list what other features can be used besides instruments?
Comment: I am questioning myself why I took this research topic. But your inputs are valuable. Thank You :)
Comment: By waiting longer before accepting an answer, it might encourage more answers to be offered.
Comment: Baroque music played on saxophones or synthesizers is still baroque. Played on a piano it's baroque unless you do something like Jacque Loussier where it becomes something else.
Comment: Yep.  I would add that this answer, and discussion, show well the futility of trying to draw lines about such complex and flexible categories as musical genres.
Answer: My position is that genre comes from audience. Country is what Country fans listen to. Opera is what Opera fans listen to.
It isn't that Country is in 2/4, 3/4 and 4/4, and Rock can be in 4/4 and more odd meters because those are genre rules. Country is about social dancing and the dancers want songs they can dance to. Rock audiences are less about that and (dependent on subgenre) more willing to be musically challenged, so songs with odd meters, like "Whipping Post"'s 11/8 or "Turn It On Again" in 13/4.
The base Rock band has one or more guitars, one bass, one drummer and vocals. I can name Rock bands without vocals, without guitar and with two drummers, two bassists, keys, accordion, sax, various brass instruments, flute, mandolin, electric and acoustic violin,  sitar, theremin and a long pipe and a propane torch, listed as a propane-o-phone. It is not limited by instrument.
Jazz is generally various brass instruments, a small drum kit, acoustic bass and piano. Some bands have lots of electric instruments. One band I know had tablas, classical guitar and oboe as the main instruments. It is not limited by instrument.
The genre whose instrumental choices seem most tightly constricted is Bluegrass. You should expect mandolin, fiddle, acoustic guitar, banjo and acoustic bass. Bill Monroe has had accordion and snare drum on his recordings. It is not limited by instruments.
Composers know that audiences associate different instruments with different emotions and use that in their compositions. I feel that guitar can express melancholy, for example, but movie scores are more likely to use something like a french horn for that.
Genres are audiences and built on audience expectation.
Answer: I would say it's the other way around. Instruments (weakly) determine genre. Given a piece of music, people like to classify into some specific genres. Sometimes based on the instrumentation. As mentioned before, a piano concerto needs a piano and a contrasting sound source, usually an orchestra.
Nevertheless, an orchestra playing "You Picked a Fine Time to Leave Me, Lucille" doesn't change it from a country waltz. (Using the melody as a symphonic theme does though. This is less common now due to copyright considerations.)


AutoARIMA prediction giving a straight line

Question: I'm doing time series forecasting using AutoARIMA model from the darts library. However, the prediction output is a straight line. I don't know how I should fix this, any suggestion & help please!
Comment: What happened around 2500?
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Very similar questions have been asked a number of times on this site. Check them out: https://stats.stackexchange.com/search?q=%5Barima%5D+straight+line. (There are probably more.) How is your question different from these?
Answer: Please notice that your forecast is not "completely flat", you converge to a particular value as the selected ARIMA model is (1,1,1)(0,0,0) so in the end our estimates get attenuated around their expected mean.
Just some background: An AR(1) is suggests $y_t = \mu +\phi_1 y_{t-1} + e_t$,  MA(1) suggests that $y_t = e_t +\theta_1 y_{t-1}$ and ARIMA(0,1,0) suggests: $y_t = \mu + y_{t-1}$. Here $e_t$ are our white noise (error) at time $t$ and $\theta_i$ and $\phi_i$ reflect how much we weigh them, they are simple scalars.
With that out  of way our ARIMA(1,1,1) will  therefore be: $y_t - y_{t-1} = \mu + \phi_1(y_t - y_{t-1})+ e_t + \theta_1 e_{t-1}$. (Sometimes this is equivalently written  out as: $(1-\phi_1 B)(1-B)y_t = \mu + (1 + \theta_1 B) e_t$ where B  is the backward shift operator describing our differencing.)
The second tuple (0,0,0) suggests no seasonal components.
Now let's notice what happens as we move forward in forecasting time. $\mu$ is stable so that's "flat", the expectation of $E\{e_t\} = 0$ as it is white noise so that will slowly converge to zero, so that will slowly be flat too, so the only thing left to "drive" our forecasts is $y_{t-1}$. While the post does not output the ARIMA coefficients, assuming $\phi_1$ is not much larger than $\theta_1$, the contribution of it will slowly also be attenuated in the long run as ($y_t - y_{t-1}$) gets smaller due too the dumping effect all other factors have. To that extent,  as the estimated $| \phi\ |$ is most likely below $1$, that also suggests convergence to $0$ (i.e. flat). Finally do note that the forecast horizon used, is "very long", the plots shows a situation where we are forecasting hunderds of steps into the future. As similar exposition for a ARIMA(1,0,0) can  be found here: ARIMA converges to mean.
I would suggest the following:

Limit your ARIMA estimates' forecasting horizon substantially. "In the long run we are all dead", and so are our forecasts.
If we need very long term forecasts  we should consider using something like a linear model with an ARMA error structure. We need "stronger" assumptions about the evolution of $\mu$ across time.
Consider the  use of external variables. (Sometimes called exogenous) They allow us to explain events that do not necessarily related to the stochastic nature of our data. For example as @forecaster mentioned, something probably happened at around time 2500 tha had little to do with the overall stochastic volatility and mean trend as we model it with the ARIMA.
Consider defining a seasonal trend if our data have a periodic pattern (e.g. weekly or daily), while "not much" it helps making the long term forecasts a bit more realistic (assuming that the pattern still holds).


Access main form from child unit in Delphi

Question: I want to access a main form variable from a class that is called from the main from.
Something like this:
Unit1:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,Unit2, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
  public
  end;
var
  Form1: TForm1;
  Chiled:TChiled;
const
 Variable = 'dsadas';
implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Chiled.ShowMainFormVariable;
end;

end.

Unit2:
unit Unit2;

interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

  type
  TChiled = class
  private
  public
    procedure ShowMainFormVariable;
  end;
var
  Form1: TForm1;
implementation

procedure TChiled.ShowMainFormVariable;
begin
  ShowMessage(Form1.Variable);
end;
end.

if in Unit2 i add to uses Unit1 an circular errors pops up.
How to make the Unit1 to be GLOBAL?
Comment: Name "Variable" for a constant, that's simply... genious.
Answer: As other answers tell, you should use one of the units in implementation section.
Suppose you chose in 'unit2' you'd use 'unit1' in implementation. then you need to devise a mechanism to tell the 'TChiled' how to access 'Form1'. That's because since you haven't used 'unit1' in interface section of 'unit2', you cannot declare the 'Form1:TForm1' variable in interface section. Below is just one possible solution:
unit2

type
  TChiled = class
  private
    FForm1: TForm;
  public
    procedure ShowMainFormVariable;
    property Form1: TForm write FForm1;
  end;

implementation

uses
  unit1;

procedure TChild.ShowMainFormVariable;
begin
  ShowMessage((FForm1 as TForm1).Variable);
end;

then in unit1 you can set the Form1 property of TChiled before calling TChiled's method:
procedure TForm1.Button1Click(Sender: TObject);
begin
  Chiled.Form1 := Self;
  Chiled.ShowMainFormVariable;
end;

Answer: Well, the simple naive answer is that you should add Unit1 to the uses clause of the implementation section of Unit2:
unit Unit2;
......
implementation

uses
  Unit1;
.....

You can't add it to the uses clause in the interface section of Unit2 since that would create a circular reference at the interface section. In order words, the interface of Unit1 would uses Unit2, and the interface of Unit2 would use Unit1. The language does not allow that. The common solution is to use one of the units at the implementation level.

Having said that, your code is rather confused and fails in many other ways. Your problems run deeper than the circular reference. For example, what do you mean by Form1.Variable? The constant Variable is not a member of TForm1. You declare two global variables named Form1 of type TForm1. Why do you do that?
Also, you have spelled child incorrectly.
Answer: the simplest solution is to add Unit1 to a uses clause inside Unit2's implementation section  as this gets around the circular reference.
However I'd suggest that this design is flawed. It is hard to see what you are trying to achieve with the sample code so it is difficult to offer any real advice.
Answer: I generally create a Data Module (or any type of non-visual container) to share global variables. This way both units can use the variable without a circular reference.
Comment: @golez Why not? I mean a data module is over the top I guess, a plain unit would do. But do you mean more than that?
Comment: Whilst that might be a good idea, it would be better if you answered the question that was asked, as well as offering sound advice.
Comment: Well, no special reason to use a DataModule. I almost always use a data module in my projects and I used to share globals in it. More over, he asked a form variable but the example has a unit variable (e.g. not defined in private or public sections of form). I just brought another unit. This is my point of view for this very problem I think.
Comment: I think an application shouldn't have many (or any) globals at all. You could get away with globals for a main form and/or a main datamodule, but if you need to create a unit or datamodule to contain 'all' your globals, I think you should consider a redesign. Especially in this case. I think circular references between forms is bad. Use events, or some observer like construction instead. Usually it takes maybe 5 lines of code to eliminate such a dependancy.
Comment: @golez in this case the 'variable' is a constant. I see no problems with constants of global scope. Centralising them in a single unit often makes sense.


How to properly convert currency in C#

Question: I have been working on a currency convert on VS in c# , my current challenging is how to properly convert Dollar to Frank ,Euro to Pound  Sterling to Frank, but when i run the programing everything seems working fine until i enter the amount to be converted in Dollar it works and when i try with the other currencies just doesn't show any result or raise any exception. below is my program, I tried searching for similar challenges but couldn't find one that suit my case ! I am very new to the C# language and community, Maybe it might not be a very smart question but i really do need help !
class Program
    {
        public static void Main()
        {
            int ;
            double val,frank;
            Console.WriteLine("Enter your Choice :\n 1- Dollar to Frank \n 2- Euro to Frank \n 3- Sterling to Frank ");
            choice = int.Parse(Console.ReadLine());

             (choice)
            {
                case 1:
                    Double dollar;
                    Console.Write("Enter the Dollar Amount :");
                    dollar = Double.Parse(Console.ReadLine());
                    Console.Write("Enter the Dollar Value :");
                    val = double.Parse(Console.ReadLine());
                    frank = dollar * val;
                    Console.WriteLine("{0} Dollar Equals {1} Frank", dollar, frank);
                    break;
                case 2:
                    Double Euro;
                    Console.Write("Enter the Euro Amount :");
                    Euro  Double.Parse(Console.ReadLine());
                    Console.Write("Enter the Euro Value :");
                    val = double.Parse(Console.ReadLine());
                    frank = Euro * val;
                    Console.WriteLine("{0} Euro Equals {1} Frank", Euro, frank);
                    break;
                case 3:
                    Double sterling;
                    Console.Write("Enter the Sterling Amount :");
                    Double.Parse(Console.ReadLine());
                    Console.Write("Enter the Sterling Value :");
                    val = double.Parse(Console.ReadLine());
                    frank = sterling * val;
                    Console.WriteLine("{0} Sterling Equals {1} Frank", sterling, frank);
                    break;
            }
            Console.ReadLine();
        }
    }

Comment: Your code doesnt compile, which is a good place to start with investigating the problem. `int;` on the first line. A missing `switch` statement before `(choice)` plus a [whole load of other mistakes the compiler will tell you about](https://dotnetfiddle.net/YWzSKH) in the error or output windows of your favourite IDE
Comment: Also, don't use `double` for currency amounts. Always use `decimal`.
Comment: What is a "Frank Euro" and what is a "Frank Sterling"?
Answer: I'd try to tackle this in a more generic way and with less repetition.
public static void Main()
{
    decimal EnterDecimal(string message, bool zero_allowed)
    {
        while (true)
        {
            Console.WriteLine(message);
            if (decimal.TryParse(Console.ReadLine(), out decimal value))
                if (zero_allowed || value != 0m)
                    return value;
        }
    }

    string EnterCurrency(string message)
    {
        while (true)
        {
            Console.WriteLine(message);
            string currency = Console.ReadLine().ToUpperInvariant();
            if (currency.Length == 3)
                return currency;
        }
    }

    string currency_from = EnterCurrency("Enter From Currency");
    string currency_to = EnterCurrency("Enter To Currency");
    decimal rate = EnterDecimal($"Enter exchange rate from {currency_from} to {currency_to}", false);
    decimal amount_from = EnterDecimal($"Enter the amount of {currency_from} to convert", true);
    decimal amount_to = amount_from * rate;
    Console.WriteLine($"{amount_from} {currency_from} equals {amount_to} {currency_to}");
}

A typical run of this code might be:
Enter From Currency
AUD
Enter To Currency
USD
Enter exchange rate from AUD to USD
0.7
Enter the amount of AUD to convert
100
100 AUD equals 70.0 USD

How to properly convert currency in C#


AnimationDrawable, are all images loaded in memory

Question: In animation drawable, you can load up an animation list that has multiple frames that would play one after the other. I am just wondering about memory consumption/efficiency here . If  I have 50 or 60 images, does that mean they are all loaded in memory and then rendered one by one, or is it loaded one by one and replacing the older one?
Any idea how this works?
Thanks
Answer: Yes, AnimationDrawable loads all of the frames into memory at once. You can read more on this here - link


How to programmatically set custom display settings for an RSS feed?

Question: I am using Drupal 7 and Views 3.0-RC1.
I have defined an RSS feed for a view, but the full node content keeps showing up instead of the teaser. I believe it is because of these two issues:

http://drupal.org/node/1211008
http://drupal.org/node/1137116

The steps that appear to work are to:

Enable a custom display for RSS,
Configure the RSS custom display truncate the teaser and hide extra fields,
Enable the view to display full text for RSS.

I need to make this work programmatically as part of a features module.
The first step is easy. I do it with the following code in my .module file:
    function mymodule_entity_info_alter(&$entity_info) {
      $entity_info['customtype']['view modes']['rss'] = array (
        'label' => t('RSS Feed'),
        'custom settings' => TRUE,
      );

The last step is easy, as I can export the view.
The middle step has me stumped. I can't figure out how to set the display properties on the RSS display. I suspect it has something to do with field settings, but I can't seem to pull the pieces together. Any suggestions?
Answer: @JeremyFrench pointed out that the Features Module correctly exports the field settings for the view-mode, which fulfilled the middle step. No extra API calls is necessary.
My problem was with step 1. Though field settings are defined per-content-type and per-view-mode, the actual definition of view modes is independent of content-types. All content types share the same set of view modes, though each can implement their own field settings for that view mode.
This means that in my call to hook_entity_info_alter(), I should not have referenced customtype, I should just reference 'node'. That simple change enables everything to work.


How can I import a CSV file to custom entity created using ECK module?

Question: I have created a custom entity type using ECK module. I want to import a csv file with data to my custom entity. How do I do this?
Answer: Content imports are often done with Feeds or Migrate modules.


Combining .txt files in R using a loop

Question: I'm currently trying to use R to combine dozens of .txt files into one single .txt file. Attached below is the code that I've been experimenting with so far. The files that I'm trying to combine have very similar names, for example: "e20171ny0001000.txt" and "e20171ct0001000.txt". As you can see, the only difference in the file names are the different state abbreviations. This is why I've been trying to use a for loop, in order to try to go through all the state abbreviations.
setwd("/Users/tim/Downloads/All_Geographies")

statelist = c('ak','al','ar','az','ca','co','ct','dc','de','fl','ga','hi','ia','id','il','in','ks','ky','la','ma','md','me','mi','mn','mo','ms','mt','nc','nd','ne','nh','nj','nm','nv','ny','oh','ok','or','pa','ri','sc','sd','tn','tx','ut','va','vt','wa','wi','wv','wy')

for (i in statelist){
  file_names <- list.files(getwd())
  file_names <- file_names[grepl(paste0("e20171", i, "0001000.txt"),file_names)]
  files <- lapply(file_names, read.csv, header=F, stringsAsFactors = F)
  files <- do.call(rbind,files)
}

write.table(files, file = "RandomFile.txt", sep="\t")

When I run the code, there isn't a specific error that pops up. Instead the entire code runs and nothing happens. I feel like my code is missing something that is preventing it from running correctly.
Comment: You might as well benefit from a solution for a related problem here:   https://stat.ethz.ch/pipermail/r-help/2011-December/297456.html .
Answer: We need to create a list to update.  In the OP's code,files is a list of data.frame that gets updated in the for loop.  Instead, the output needss to be stored in a list.  For this, we can create a list of NULL 'out' and then assign the output to each element of 'out'
out <- vector('list', length(statelist))
for (i in seq_along(statelist)){
  file_names <- list.files(getwd())
  file_names <- file_names[grepl(paste0("e20171", statelist[i],
              "0001000.txt"),file_names)]
  files <-  lapply(file_names, read.csv, header=FALSE, stringsAsFactors = FALSE)
   out[[i]] <- do.call(rbind, files)

  }

As out is a list of data.frame, we need to loop over the list and then write it back to file
newfilenames <- paste0(statelist, "_new", ".txt")
lapply(seq_along(out), function(i) write.table(out[[i]],
      file = newfilenames[i], quote = FALSE, row.names = FALSE))

Comment: Thank you so much! I already upvoted your answer but it isn't publicly displayed. If you don't mind, how would you convert 'out' to a .txt file? I'm trying to use the write.table() function without much success right now.
Comment: @TimApple24. Regarding writing to file.  The `out` is a list of `data.frames`

Combining .txt files in R using a loop


Why mvn pact:publish throws NoClassDefFoundError kotlin.TypeCastException

Question: i'm trying to publish a Pact-File to my Pact-Broker with maven-plugin this way (taken from github Pact-Project):
<build>
<plugins>
<plugin>
<groupId>au.com.dius</groupId>
<artifactId>pact-jvm-provider-maven_2.12</artifactId>
<version>3.5.11</version>
<configuration>
<pactDirectory>${project.build.directory}/pacts</pactDirectory>
<pactBrokerUrl>mybrokerurl.de</pactBrokerUrl>
<projectVersion>${project.version}</projectVersion>
<trimSnapshot>true</trimSnapshot>
</configuration>
</plugin>
</plugins>
</build>

If i try to execute the maven build with pact:publish, i get following error:
Failed to execute goal au.com.dius:pact-jvm-provider-maven_2.12:3.5.11:publish (default-cli) on project myproject-test: Execution default-cli of goal au.com.dius:pact-jvm-provider-maven_2.12:3.5.11:publish failed: A required class was missing while executing au.com.dius:pact-jvm-provider-maven_2.12:3.5.11:publish: kotlin.TypeCastException

Top of Stack-Trace:
Error injecting: au.com.dius.pact.provider.maven.PactPublishMojo
java.lang.NoClassDefFoundError: kotlin.TypeCastException
    at java.lang.J9VMInternals.prepareClassImpl(Native Method)

Pact-File Creation with a JUnit-Tests works fine, so I assumed i had the correct dependencies and required files in classpath.
What am I missing? It seems, the kotlin.TypeCastExeption-Class is in package
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-runtime</artifactId>

so i tried to add the dependency (version 1.2.0) to my pom after i got this error - but this didn't help.
Does anyone know a solution for my problem?
Comment: Are you trying to build the source for pact-jvm somehow? Could you post the rest of your pom.xml file? I need to try to reproduce this locally to figure out what's going on.
Answer: I was also getting the same error. The workaround I have applied is to delete maven repository from local disk and rebuild the project. It has solved error for me.


Long Touch with Delphi VCL on Windows Tablet

Question: I've created a TCustomControl derived class for a VCL application running on a Windows 8.1 tablet.
I'm using the OnMouseDown / OnMouseUp events even though this is obviously touch based.
What I'd like to do is detect a long press - i.e. touch down and hold for 1 second. So in the OnMouseDown event I record the down timestamp, set a flag to indicate the mouse is down and create an anonymous thread which sleeps for 1 second, and then checks the flag.
In OnMouseUp I set the flag to false.
This works as long as you wiggle your finger on the control. Otherwise if you just touch and hold the mouse down event is not called until you release your finger.
I've look at gestures, but that just looks completely overkill and from what I understand doesn't support long press anyway.
Thanks for any suggestions.
Richard
Comment: How about just activating a timer with a 1000ms interval when MouseDown occurs, and cancelling it on MouseUp. Put your code in the OnTimer event. It should only fire after they have held the mouse down for over a  second. You could probably get away with one timer for the whole form as long as you save which control launched it. Don't forget to disable the timer immediately in the OnTimer event.
Comment: Thanks, but that won't work for the same reason as the anonymous thread, the MouseDown doesn't fire unless you wiggle your finger or lift your finger.
Comment: I don't have a windows tablet, but I just added a TButton and a TMemo to a new VCL form (Berlin) and added code to add a line to the memo in the MouseDown and MouseUp event handlers, both events clearly fire individually and in sync with the mouse clicks.
There must be a difference between the way the tablet fires the events from the standard PC mouse.
Comment: Thanks - yes it is different to a standard mouse handling. If I run the application on my desktop PC and use my mouse rather than my finger it behaves as expected.
Answer: What you're facing is "normal" yet ridiculously stupid behaviour of Windows with touch input devices. We're facing the same issue for a while now, and are trying to solve it actively for the last couple weeks.
The trick is, that windows handles touch input device as "mouse, that can be fully controlled with single finger". Therefore, it has several states, more than events:
Events are: Touch begin (down), move, up, right click, and if you really want to register for a callback you'll get stationary (not moved since last report but still down).
Meanwhile, there are more states. First, when you press your finger down, it internally detects "Touch down!" event. It than waits a certain amount of time (which might or might not be available to hack-change, depends on drivers etc...), to determine whether what you wanted was a right click (after x time, upon release !before Y time! it will fire right click event) or whether it was a left click down (triggering event TouchBegin - after y time, which is LONGER than x-time, and after the y expires, it will fire left down event (not click!)).
Meanwhile, if the first touch down is interrupted by either move or - !! while waiting for x time to expire!! release of the finger BEFORE x time is ran out, it will automatically trigger left down (on move) or left click (on release). Same goes for any time after the Y time expires as well, or MOVE is triggered.
To put it more simply and understandable, I'll try to give an example:
Let's say that you have touch device, and the timings are as follows:
Point B is beginning, positioned at 0 seconds of our timeline.
Point X is first trigger breakpoint, positioned at 5 seconds of our timeline.
Point Y is second trigger breakpoint, positioned a 10 seconds of our timeline.
You put your finger on touch, and that starts the timeline.
Possible scenarios:
 - You release it anytime before point X -> Left click is triggered (Touch down and up events, in order immediately one after another)
 - You release it after point X but before point Y -> Right click is triggered (Touch down and up events, with right click flag)
 - You reach point Y - Left down is triggered!
 - You release it after point Y anytime, no matter if move triggers between release or not (but move is NOT triggered before reaching this point in timeline) -> Left up is triggered.

You trigger (do) move event before reaching point X -> Left down is triggered, followed by as many move events as it detects it, until you release it -> then left up is triggered
You trigger (do) move event after X but before Y -> same as above!
You reach point Y and move it afterwards -> check point no4 above.

Hope this is making any sense to you.
Now to jump to the possible solutions: Custom driver would be one option, but we're not there yet, so we're still trying other options. The most promising for now seems to be use of RAW_INPUT and Touch hooks, looks like we'll have to combine them to get what we want tho.
The bright side is, that windows itself DOES detect when finger touches the device, regardless of the timings and events that it wants to detect, determine and then forward to apps, but they for some reason made it hard to use in such nature. As a proof you could simply check the transparent dot that appears underneath your finger the very first moment you touch the screen.
Meanwhile, Android handles these things way better...
Hope it helps, and I'm happy to come around with the complete solution once we come through and get something good enough for usage.
M.*
Answer: If the MouseDown event is not triggered and you want to make your delay counter dependent on it then you are basically screwed. That said, I assume you are open to slight changes of concept. :)
I think it can still be done if you change your button into something like a flip-switch. The user has to "grab" (touch) it, "pull it up" (drag, should trigger StartDrag event) and hold it there for the desired amount of time. Upon release of the switch (MouseDown event), it snaps back down.
To design such a button, you could use a tiny TPanel for the knob and a slightly larger one for allowing limited vertical movement on it. Set BevelInner property to bvLowered and BevelOuter to bvRaised to make it look like a frame and the knob panel its child. Or use a TImage to display the knob in it's up/down positions. In any case, set the knob element's DragKind property to dkDrag or the StartDrag event won't occur. If still no event is fired, please try to detect touch input capabilities and report your findings..
Not sure this qualifies for an answer but maybe it's worth a swing.


What would the British name of a 1073741824th note be?

Question: The wikipedia page for a 256th note (demisemihemidemisemiquaver) talks about a 1073741824th note. This note seems to only be supported by the LilyPond software.
I'm guessing that since such a note is never used, and wasn't established alongside the other notes with the same name, there isn't a British name for it. However, if there is, what is it? I'm not sure of the naming convention for these notes.
Answer: Actually, I just found out. Looking at the naming for the other notes, you add semi then hemi then demi. Since that note is 2^30, we can just copy-paste hemidemisemi 9 times (including the first quaver level). Doing this, we get the glorious:
<code>hemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemiquaver
</code>

(Thanks to user1079505 and Divizna for correcting the name, I put 10
hemidemisemis the first time)
Comment: Wouldn't that be a 8589934592nd note? Note, that quaver is an eighth note, not a whole note.
Comment: @user1079505 Don't worry about that, we don't speak English. I'm all for calling it "miliardsedmdesáttřimilionsedmsetčtyřicetjednatisícosmsetčtyřiadvacetinová nota" but I'm afraid you'd have trouble pronouncing the ř that comes up three times there.
Comment: Yep, it's "hemidemisemi" *nine* times, so hemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemiquaver, not hemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemihemidemisemiquaver.
Comment: Just call it a grace note & be done with it ;)
Comment: @Divizna "billion" will be confusing in countries using long scale https://en.wikipedia.org/wiki/Long_and_short_scales
Comment: @Divizna would we more trouble with these ř's than we do with Dvořak?
Comment: Or we can call it a billion-seventy-three-million-seven-hundred-forty-one-thousand-eight-hundred-twenty-fourth note, what's wrong with that?
Comment: I've always just called it "Steve".
Comment: @phoog Depends, if you pronounce his name as "Dvorak" you're doing it wrong. If you pronounce it like they show at [Wikipedia](https://en.wikipedia.org/wiki/Anton%C3%ADn_Dvo%C5%99%C3%A1k) then the sound in "čtyři" is the same, in "tři" it's its nonvoiced twin. (Btw I can't resist telling you it's spelled Dvořák, to denote that the second syllable is long.) So if you can say Dvořák then you'd only stumble on "tisíc" and "dvacetina" which contain the ť sound that's also foreign to English. (It's not written that way but ti is always pronounced as ťi in domestic words.)
Comment: @Divizna - seems like a pain in the rs to me...
Comment: @Tim No no, not rs, it's ř. One consonant, not a cluster of two. :o)) Like when you say řiť. That's what we call the body part you mentioned. (Not a swearword. It's the correct term. We do have a less polite word too of course but here's not the place for extended linguistic discussions.)
Comment: @Divizna - I have a wind-up computer, that doesn't have that accent. Only a joke - perhaps a wind-up..? Things get quite tedious on this site - no-one seems to have a sense of humour!
Comment: @Tim  Ah, don't get wound up, or you'll wound me.
Comment: @Divizna: In German, this part of the body is called "Ař". ;-)


Homogeneous Systems and Symmetric Matrices?

Question: I'm having trouble showing that given a symmetric matrix $A$, the homogenous system $x' = Ax$ will be stable (ie it has a fundamental matrix whose entries all remain bounded as $t \rightarrow \infty$).
I know that a symmetric matrix is such that $A = A^T$, but I'm unsure of how to use this information to show the solutions are bounded.
Answer: In general, this will be wrong, for example $A = 1$ (a $1\times1$-matrix) is symmetric, but $\exp(tA) = \exp(t)$ is unbounded as $t \to \infty$. If the eigenvalues of $A$ are moreover non-positive, you can use the following:
Hint: A symmetric $A$ is diagonalisable, that is, there is an $S \in \mathrm{GL}_n(\mathbb R)$ such that $S^{-1}AS =: \Lambda$ is diagonal. Now use $\exp(tA) = S\exp{t\Lambda}S^{-1}$


HTTP/1.1 200 OK with SharePoint Server 2010

Question: I have installed  SharePoint Server 2010 on our server. The problem is: If I go to the website, where I expect to see the SharePoint site, I get the following message:

HTTP/1.1 200 OK
Server: Microsoft-IIS/7.5
Date: Wed, 28 Mar 2012 16:12:19 GMT
Connection: close

Can anybody give me some tips?
Comment: Go to... in a browser?
Comment: Yes, with the browser. Sorry.
Answer: Did you configured a managed path ?
If you deploy your new site collection under a web application with a managed path and there's nothing at the root of the web application (eg : you deployed on http://fqdn/sites/your-site and you try to acces http://fqdn) you'll get a connection close.
Did you check in IIS if there's a relevant binding for your web application ?


Using a MIDI foot switch as MIDI input for my DAW?

Question: I use a Nektar Impact LX61 MIDI keyboard with FL Studio 20. I have a pedal plugged into the 1/4" foot switch jack on the back. Currently, this functions as a "sustain" in that it continues to act as if keys are pressed down after they have been released. However, many piano libraries feature a more realistic sustain function when MIDI CC64 is greater than 50%. The Nektar Impact series does not feature a MIDI CC input for pedals.
When I press down or release the sustain pedal, FL Studio indicates that it is reviving a MIDI signal by lighting up an orange indicator in the top left. I do not, however, know what type of signal this is or what channel it is on. If I knew, I may be able to link it to MIDI CC64 as an on/off (0% or 100%) switch using FL Studio's internal "Remote Control Settings" feature.
I am looking for information regarding how MIDI controllers send data from the foot switch jack. Or even better, if anybody has done this in FL Studio before, I would like to know the process.
Comment: If you want to see what data type it is, why not record it? In all likelihood it's going to be CC64 0 & CC64 127. Few simple sustain pedals on keyboards can do a full sweep of 0-127 & few can respond to that, hence the implied toggle at 64.
Answer: If your pedal has a 1/4 inch jack socket then it's not a MIDI foot switch. It will very probably be a simple on/off switch. Unless your keyboard has a very unusual MIDI implementation, when you press the foot switch the keyboard will send a MIDI CC64 (sustain) message on whatever channel it's set to. The value of the CC message will depend on the keyboard but it's most likely 127 (100%) or 0 for off. The exact details should be in the manual for your keyboard.
There is a setting in FL called "foot pedal controls note off" that is on by default. This blocks CC64 messages and uses them to control the lengths of notes while recording MIDI. When you turn this off, foot pedals work.
Comment: Note that some of these pedals, having TRS Jack can allow for continuous signal. It's not midi yet until it has been converted by the keyboard thought!
Comment: I used the wrong term when I said "channel", I apologize for that. What I meant was which CC it would send information to. It is not sending a CC64 signal. I have both recorded and looked in FL's full list of MIDI functions. For both of these, I can verify that the mod wheel works, but the switch does not set the CC64 to 127. The manual has a section for assigning controls including the switch, but when I use the settings mode it does not recognize the switch, despite it clearly outputting some sort of MIDI data to FL. Maybe this is a question for Nektar support. Thank you, though.
Comment: MIDI monitoring was an excellent suggestion, thank you. In case anyone runs into the same issue and happens to find this thread, I'm going to leave the solution here. The MIDI monitor confirmed that the keyboard actually was outputting a CC64 message, FL Studio just wasn't picking it up. Turns out there is a setting in FL called "foot pedal controls note off" that is on by default. This blocks CC64 messages and uses them to control the lengths of notes while recording MIDI. When you turn this off, foot pedals work.
Comment: @Noah I updated the answer to include the info from your comment.