Q:

how to load values (users and users_profiles) to a database upon application start?

In my application, I have a file called HibernateConfiguration.java that has the main database configuration and using the code excerpt bellow I manage to create the tables upon the application start:
   private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        return properties;
    }
Now I'd like to populate some tables upon start after they are created by Hibernate. Currently I have to run a sql script to populate USER_PROFILE and USER before accessing the application.
How to do it in Spring? I'm using it without XMLs files to configure everything.

A:

If you would like populate tables upon start, simplest way is using of @PostConstruct annotation. Actually, you can mark with it method of configuration, but I would I prefer to create separate bean:
public class DataInitializer {

    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    public void populate(){
        User user = new User();
        //set user props ...
        userRepository.save(user);
    }
}

Now just register this component into configuration (or mark this class with @Component if you use component scan):
@Configuration
public class AppConfig{
    ...

    @Bean
    public DataInitializer createDataInitializer(){
        return new DataInitializer();
    }
}

I don't know do you use JPA repositories, or not. But if you work with EntityManager directly, be note, that you cant use @Transactional annotation on @PostConstruct. In this case you have to use TransactionTemplate:
public class DataInitializer {

    @PersistenceContext
    private EntityManager manager;
    @Autowired
    private PlatformTransactionManager txManager;

    @PostConstruct
    public void populate(){

        TransactionTemplate template = new TransactionTemplate(txManager);
        template.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                User user = new User();
                //set user props ...
                manager.merge(user);
                return null;
            }
        });
    }
}

Same way you can do, if you work with Hibernate session.


Q:

Facebook Comment Box doesn't expand its container div

I've embedded a Facebook Comment box into my site (http://ponycountdown.com), but the div it is contained within doesn't expand to accommodate it. Does anyone know what causes this, and if there is a way around it?
To see the problem in action, click the comments tab on the left of that page.
An additional query - is it possible to reverse the order of comments so that the most recent is on top? I tried adding reverse="true", but it doesn't have any effect.

A:

Change height of the div to min-height in CSS.
In other words, use min-height: 392px instead of height: 392px.
This way it will expand and not be of fixed height as it is now. Hope this helps.


Q:

Markup and CSS to present Table Data

I have the following "Table" :

Where i want the blue blocks to have specific width and the yellow blocks to expand to fill the rest of the space, based on the container width.
My current approach is to have every block of every row float left and i give them specific width, but this approach is not scalable and not responsive.
Can you please suggest me a better approach for what i want to achieve?
I have also made a fiddler so you can play with the markup and see what i did.
http://jsfiddle.net/RickyStam/bG4dA/
Below is my HTML

Match Outcome

AwayDrawHome

TEAM A v TEAM B3.303.302.15

Goal

Over 2.52.05Over 2.51.70

1st Half

AwayDrawHome

TEAM A v TEAM B3.802.002.80

Half with most goals

1st Half3.20

2nd Half1.95

Draw3.30

Here is my CSS:
.clear {
    clear: both;
}

body {
    font-family: Arial;
}
.iframe-container {
    width: 610px;
    height: 370px;
    background: #f3f3f3;
    position:relative;
    overflow:hidden;
}

.content {
    margin-top: 40px;
    height:300px;
    overflow-y:auto;
    padding:0px 20px;
}

.bet {
    width:66px;
    display:block;
    line-height:27px;
    text-align:center;
    background:blue;
    float:left;
    border-top:1px solid #cad6e4;
    border-bottom:1px solid #cad6e4;
    border-right:1px solid #cad6e4;
    cursor:pointer;
    font-weight:bold;
    color:white;
}
.bet:hover{
    background:grey;
    color:white;
}

.betcontainer {
    width:556px;
    font-size:12px;
    font-family:Arial;
}
.bettitle {
    width:551px;
    line-height:27px;
    padding-left:3px;
    background: red;
    color:white;
    font-weight:bold;
    border:1px solid #cad6e4;
}

.bettext-big{
    float:left;
    line-height:27px;
    width:347px;
    background:yellow;
    padding-left:6px;
    border:1px solid #cad6e4;
}
.bettext-medium{
    float:left;
    line-height:27px;
    width:203px;
    background:yellow;
    padding-left:6px;
    border:1px solid #cad6e4;

}
.bettext-xlarge{
    float:left;
    line-height:27px;
    width:481px;
    background:yellow;
    padding-left:6px;
    border:1px solid #cad6e4;
}

.betheaderwrap {
    width:100%;
    height:15px;
    background:#ddd;
}
.betheader {
    width:66px;
    line-height:15px;
    color:#666;
    float:right;
    text-align:center;
    font-weight:bold;
}

.seperatebets {
    width:100%;
    height:10px;
    background:white;
}

A:

You can use floats. If you need your layout to be responsive, give % width instead of px.
You will need to calculate so that the sum of width of every block on each row doesn't exeed 100%.
Then use box-sizing:border-box; css property so that the width set on each block also contains the border (see here for an overview of that property).
Here is an example FIDDLE


Q:

Why won't this change the values of some of the elements in array1 in memory?

I wrote some assembly code on Keil where if an element in array is < 5, the program increments that element. Trouble is, the ARM code does not change the values of array1 in memory. What changes do I need to make in order to do so?
    ADR r0, array1      ; loads address of 'a' to r0

    MOV r1, #0          ; r1 = index

L0  CMP r1, #8
    BGE stop
    LDR r2, [r0, r1, LSL#2] ; load content of array1[index] to r2
    CMP r2, #5
    ADDLT   r2, r2, #1      ; array1[index]++
    STRLT   r2, [r0, r1, LSL#2] ; store r2 as content of array1[index]
    ADD r1, r1, #1      ; index++
    B   L0

stop B  stop
array1  DCD 1, 7, 4, 9, 2, 3, 8, 6
    END

A:

Below is the memory map for Cortex-M3 DesignStart Eval. Granted, this is Cortex-M rather than ATM7TDMI, but it is good as an example.
You can see here, FLASH region, various expansion regions, peripherals and different types of RAM. You can compare this to the memory map of the LPC2140 to check the relevant addresses for your device.
Generally, for program code, FLASH regions are read only (a special control sequence is required to modify FLASH, specific to the actual part). The areas marked as expansion in this diagram have nothing. Accesses to these should fault (from an idealistic point of view), but could also just be ignored. In DesignStart, they are regions for designers to add their own hardware.
The only region that your code can reliably use for read/write storage are the RAM regions. ARM-7 does not have the clearly defined memory map of ARMv7-M, but for an LPC2140 device, you can be sure there is RAM between 0x40000000 and 0x40001FFF (as well as FLASH starting from 0x00000000).
The ARM architecture allows you to use a code region as data (so litterals can be embedded in the code, and accessed just like variables). It does not guarantee that the code memory can be modified.

Fig 4-1 from ARM100894_0000_00_en


Q:

Salvar dado em LocalStorage e depois verificar se ele existe em outra pagina

Boa tarde pessoa.
Estou precisando salvar um dado em LocalStorage e depois verificar se esse valor existe em outra página, tentei aqui mas não funcionou.
Primeiro defino o valor da "variavel" Prof_AMC
if($(myEmail == singleMail)){
            if(approved == true && categoria == 'PLF'){
                // Cria um item "Prof_AMC" com o e-mail do usuário
                window.localStorage.setItem('Prof_AMC', singleMail);
                window.location.href = document.referrer+'?sc=2'; // Parametro URL Politica PLF
            }

Depois em outra página eu tento verificar se ela existe e se o parametro SC é diferente de -1:
if(window.location.href.indexOf("sc")!=-1 && localStorage.getItem('Prof_AMC')){

}

A:

Funcionou quando fiz da seguinte maneira:
if($(myEmail == singleMail)){
            if(approved == true && categoria == 'PLF'){
                // Cria um item "Prof_AMC" com o e-mail do usuário
                window.localStorage.setItem('Prof_AMC', ""+singleMail+"");
                window.location.href = document.referrer+'?sc=2'; // Parametro URL Politica PLF
            }


Q:

Convergence in probability vs. convergence in quadratic mean

I read in some paper that convergence in probability implies the convergence in quadratic mean if all moments of higher order exists, but I don't know how to prove it. Can someone please provide the proof?

A:

Convergence in probability does not imply convergence in quadratic mean, did you accidentally  write the reverse statement? Some good
notes on convergence can be found here. The relevant parts to your question
are reproduced below.
$X_{n}$ converges to $X$ in probability, $X_n \xrightarrow{P} X$, if for every $\epsilon$,
$$
P(|X_n - X| > \epsilon) \rightarrow 0
$$
as $n \rightarrow \infty$
$X_{n}$ converges to $X$ in quadratic mean, $X_n \xrightarrow{qm} X$, if
$$
E[(X_n - X)^2] \rightarrow 0
$$
as $n \rightarrow \infty$
As a counterexample to show convergence in probability does not imply convergence in quadratic mean,
take $U \sim Unif(0, 1)$ and let $X_n = \sqrt{n} I_{[0, \frac{1}{n}]}(U)$. Then
$$
P(|X_n| > \epsilon) = P(|\sqrt{n} I_{[0, \frac{1}{n}]}(U)| > \epsilon) = P(0 \leq U \leq 1/n) = 1/n \rightarrow 0
$$
as $n \rightarrow \infty$ and therefore $X_n \xrightarrow{P} 0$
but
$$
E[X_{n}^2] = n\int_{0}^{\frac{1}{n}}dx = 1
$$
and therefore $X_n \not\xrightarrow{qm} 0$

With the additional constraint that $P(|X_n| < M) = 1$ for some constant $M > 0$, we do have that
convergence in probability implies convergence in quadratic mean or L2. This can
be seen as a restricted version of the following theorem from
chapter 17 of Convergence of Random Variables by Jean Jacod and Philip Protter.
The relevant chapter is available here.

Theorem 17.4 Suppose $X_n \xrightarrow{P} X$ and also that $|X_{n}| \leq Y$, all $n$, and $Y \in L^p$.
  Then $|X|$ is in $L^{p}$ and $X_{n} \xrightarrow{L^p} X$.


Q:

Create a subclass not to repeat matching fields

I created two class models in Django. Is there a way not to repeat the same matching fields storing them in a different class or variable?
This is what i got:
class Post(models.Model):
    title = models.CharField(max_length=50)
    content = RichTextField(blank=True)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE)
    posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    slug = models.SlugField(null=True, unique=True, editable=False)

    def __str__(self):
            return str(self.category) + self.slug + " " + str(self.id)

    def save(self, *args, **kwargs):
        self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id))
        super(Post, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

class Post2(models.Model):
    title = models.CharField(max_length=50)
    content = RichTextField(blank=True)
    category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE)
    posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    slug = models.SlugField(null=True, unique=True, editable=False)

    def __str__(self):
            return str(self.category) + self.slug + " " + str(self.id)

    def save(self, *args, **kwargs):
        self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id))
        super(Post2, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

A:

I think you are trying to find out the abstract model class.
You can create an abstract model class by setting abstract=True  in the Meta class of a model.
class AbstractPost(models.Model):
    title = models.CharField(max_length=50)
    # common fields and functions

    class Meta:
        abstract = True

class Post(AbstractPost): # inherit the abstract base class
    pass

class Post2(AbstractPost):
    pass


Q:

Set default language on a CodeMirror TextArea

How can i set that a CodeMirror TextArea will understand PHP WITHOUT echo the tag?
The Textarea
<textarea id="code" name="code">
  <?php
    echo '<?php';
  ?>
</textarea>

The JS script
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: false,
        matchBrackets: true,
        mode: "application/x-httpd-php",
        indentUnit: 4,
        indentWithTabs: true,
        enterMode: "keep",
        tabMode: "shift"
    });

A:

I've solved it, you have to change the mode to mode: "text/x-php",


Q:

Spring queryForLong - Loss of precision

I have a Spring application running against a MySql database.  I have a sales table like:
+-------------------+------------------------------+------+-----+---------+-------+
| Field             | Type                         | Null | Key | Default | Extra |
+-------------------+------------------------------+------+-----+---------+-------+
| Price             | decimal(19,4)                | NO   |     | NULL    |       |
| ItemId            | int(10) unsigned             | NO   |     | NULL    |       |
+-------------------+------------------------------+------+-----+---------+-------+

In my Spring class, I have the following:
long price = getSimpleJdbcTemplate().queryForLong("SELECT price FROM sales WHERE itemID = :itemID", params);
logger.info("price: " + price + ");

However, this is returning a price of 1, even if this query directly on the database returns 0.8500.  How do I avoid this loss of precision from the decimal in the database to the long in my code?

A:

long does not support decimal places because it is an integer type.  Have you tried queryForObject(sql, BigDecimal.class, params)?


Q:

Дублируется значение в мультиселекте при отправке формы

Есть форма на Yii 1.1, в ней мультиселект, каждый раз при отправке формы на сервер, выбранные значения в форме дублируются.
View:
$form = $this->beginWidget('CActiveForm', array(
                'id' => 'PersonnelInput-form',
                'method' => 'get',
                'htmlOptions' => array(
                    'class'=>'form-horizontal',
                ),
                'enableClientValidation' => true,
                'clientOptions' => array(
                    'validateOnSubmit' => true,
                    'afterValidate' => 'js:function(f,d,e) {
            if (e) $("html, body").animate({scrollTop: $("#PersonnelInput-form").offset().top - 50}, 1000);
            return true;
        }',
                ),
            ));

                <?php echo $form->labelEx($model, 'roles', array('class'=>'control-label col-md-4')); ?>

                    <?php echo $form->dropdownList($model, 'roles',
                        ListDataHelper::getAttributeList($employee, false, 'system_role'),
                        array(
                            'class' => 'select2',
                            'style' => 'width: 100%;',
                            'placeholder' => 'Select value',
                            'multiple' => true,
                        )
                    ); ?>
                    <?php echo $form->error($model, 'roles', array('class' => 'help-inline error')); ?>

Controller:
public function actionPersonnelInput() // TODO: Fix roles input!
{
    $form = new PersonnelInputForm();

    $au_data = $percent = array();
    $au_finished = $su_finished = null;

    if (isset($_GET['PersonnelInputForm'])) {
        $form->attributes = $_GET['PersonnelInputForm'];

        if ($form->validate()) {
            $au_data = Employee::aucasuChartData($form);
            $percent = Employee::percentInputChartData($form);

            $au_finished = Employee::auFinished($form);
            $su_finished = Employee::suFinished($form);
        }
    }

    $this->render('personnelInput', array(
        'au_data' => $au_data,
        'au_finished' => $au_finished,
        'su_finished' => $su_finished,
        'percent' => $percent,
        'model' => $form,
        'monthhr' => date('F, Y', mktime(0,0,0, $form->month, 1, $form->year)),
    ));
}

var_dump:

A:

Проблема в том что при отправке формы GET запросом, при повторной отправке берутся данные не только из формы но и из URL'а, поэтому значения дублируются.


Q:

What is the relationship between data structures and algorithms?

I have been searching for a good online course in data structures but have found that Google also returns results for algorithms courses, which say stuff like:

In this course you will learn several fundamental principles of
  algorithm design: divide-and-conquer methods, graph algorithms,
  practical data structures (heaps, hash tables, search trees),
  randomized algorithms, and more. [source]

and

By the end of this class you will understand key concepts needed to
  devise new algorithms for graphs and other important data structures
  and to evaluate the efficiency of these algorithms. [source]

and

This course provides an introduction to mathematical modeling of
  computational problems. It covers the common algorithms, algorithmic
  paradigms, and data structures used to solve these problems. [source]

My question is: are algorithms and data structures intimately linked, meaning that they must be understood together or is one topic more foundational than the other?
EDIT: For those voting to close this question, can you please tell me why and maybe how to improve this one? Learning to ask the right questions is part of the educational process.

A:

All sorts of mixtures do exist. You have data structures, which are not associated with algorithms, algorithms, which require no (real) data structures, but most often the two come in one package.
Edit: as @Doval correctly pointed out, data structures per se do not have any operations associated with them. The act of combining data structure and algorithm forms an abstract data type.
Data structures without algorithms
Consider for example a data structure for storing 2-dimensional coordinates, appropriately called Point. There is nothing much in terms of algorithms to be done for a point and it really is just a container for an x and y value. Of course, giving this data structure, you can now add all sorts of algorithms on top of it (distance calculation, convex hulls, what-have-you).
You can think of a lot of data structures, which are simply an accumulation of individual data. While these do occur frequently in practice, they do not make for good teaching material, because there is nothing to be learned from it, once you have understood, that single data items can be accumulated into a new data structure (like what do you learn after the above Point example, if I provide you with that awesome data structure called Point3D, which can do the same thing for 3-dimensional space?)
Algorithms without (real) data structures
"Real", because obviously every interesting algorithm needs primitive data types like integers or booleans, and we do not want to consider those as data structures in this context. Similarly to above, these algorithms are typically rather simple ones. In particular, they do not come with a complicated state of any sort, because that usually goes into a data structure (see next section).
An example for such an algorithm would be calculating the greatest common divisor of two numbers. Euklid's algorithms for the gcd really only needs to hold two integers and manipulates them.
Once things start to get more interesting, you very soon enter the world of abstract data types though. For example, the sieve of Eratosthenes is based on an array. We could have a discussion now, whether an array is still primitive, or in fact, you could discuss if an integer isn't already a data structure. Either way, algorithms that exist completely without data structures are rather boring, even if you accept their isolated existence.
Algorithms combined with data structures, aka abstract data types
Now these are the interesting ones, but for two very different reasons. Typically, you can approach these from two directions: data structure first, or algorithm first.
While an abstract data type is defined by the combination of data structure + algorithms/operations, we often view them with a focus on either one of those and consider the other one as enablers.
Data structure, then algorithm
You will encounter abstract data types, which are rather simple to use, but involve more or less complicated algorithms to make them work internally. For example, a HashMap is trivial to use, but involves a nifty hash function and dealing with the hash collisions on the inside. Yet, from your point of view as a user you care about it as something that holds data for you, not something that does something for you.
In contrast to the last group below, these data structures do not expose their users to these algorithms. You do not need to know, nor care, about a HashMaps internal hash function in order to be able to use it. (To use it effectively though, you may want to know these things ;)
Algorithm, then data structure
The other direction means you have an algorithm, which you want to be able to simply use, but which needs data structures internally to make it work as intended. An example would be a binary space partitioning (BSP) algorithm, that you can simply ask for the 2-dimensional Point from a large set of points that is closest to a given query point. However, you need a tree structure (and even additional algorithms like distance calculations) on the inside to actually write the algorithm.
In general, one can say that algorithms in this group use involved data structures for their internal state representation. I would argue, that this group of algorithms is the most diverse and you will find many many different ones that fit this general scheme. Regarding the point of view, we see these as interesting, because they do something (f.ex. sorting) for us, and do not care as much about the data holding part.
Closely related data structures and algorithms
Finally, you have data structures, which are very close related to algorithms that directly correspond with them. A typical example is a binary tree, which, when you want to do anything meaningful with it, forces the topic of tree-walking algorithms on you (depth-first, breadth-first, whatever).
For these cases, we change the focus of our view of the resulting abstract data types every so often. Sometimes you care about the structure of your tree, a few minutes later you care about being able to run a find operation on it, then you wonder about deleting a node, and right-away about how the structure looks afterwards. While all of this holds true for the other sections above as well, it is not something that is the primary focus in your mind, for example, when you store/retrieve data to/from a Map, or when you sort a linked list.

A:

Data structures often influence the details of an algorithm. Because of this the two often go hand in hand.
Consider for example an algorithm for cutting your lawn. How you go about cutting your lawn is likely to be influenced by the actual structure of your lawn. If you live in a small house in a densely packed suburb and your lawn is just a small rectangle a few meters squared in area, you would probably prefer to cut your lawn with a push-mower instead of a tractor/riding mower. If your lawn involves many acres of flat meadow land, your preference may be for the riding mower as opposed to the push-mower (though either mower may eventually get the job done). If your lawn involves acres of land with large flat areas, but a few small hills and a number of trees, you may develop a more interesting algorithm for cutting the lawn that involves both a riding mower and a push-mower, or some other grass cutting techniques.
Ultimately though, the structure of your data may have a significant impact on your decisions for how to develop your algorithm (or which algorithms to use). For this reason, the two topics often go hand in hand.
And vice versa: sometimes the algorithm we want to use influences (at least at the onset of computing) the data structures you develop to support the algorithm. For example going from an array list to the idea of a linked list and eventually to a BST for storing an ordered list that will allow for quick find.


Q:

Setting value of Observable not updating in Knockout

(There are a ton of questions every day that link back to why can't I set the value of my observable, instead of having so many different answers saying the same thing I wanted to create a question to refer back to for everyone)
Setting value of Knockout Observable / Observable Array doesn't update
Setting the value of my observable observableArray isn't updating!
Adding an item to an Observable Array
Why can't I add an item into my Knockout observable array?

A:

Setting value of Knockout Observable / Observable Array doesn't update
You need to use the setter function to update the value of your observable / observableArray -
Ex. 1 (observable) -
var name = 'John';
var myValue = ko.observable();
myValue(name); // Set myValue equal to John, update any subscribers

var newObservable = ko.observable('Bill');
myValue(newObservable()); // Set myValue equal to the value of newObservable, which is Bill

Ex. 2 (observableArray) -
var names = ['John', 'William', 'Dave'];
var myArray = ko.observableArray();
myArray(names); // Set myArray equal to the array of names John, update any subscribers

var newArray = ko.observableArray(['Sanford']);
myArray(newArray()); // Makes a clone of the array

Note See this Question to understand why this probably not what you are trying to do - What is the best way of cloning/copying an observablearray in knockoutJS?
Adding an item to an Observable Array
You need to push the item into the observableArray, not the underlying value of the observableArray -
var name = 'John';
var myValue = ko.observable(name);
var myArray = ko.observableArray();
myValue.push(myValue()); // Add myValue to my observableArray**

Creating a model to use/share in your view model
You can create a re-usable model to use in your view models.  This is similar to using a class in C# to create objects that have common properties.
function objectModel(item) {
    var self = this;
    self.Name = ko.observable(item.name);
    self.Description = ko.observable(item.description);
}

Which can be created like -
var object = {
    name: 'John',
    description: 'a person'
}

var john = new objectModel(object);

Which could also be done by parameters instead of just objects -
function objectModel(name, description) {
    var self = this;
    self.Name = ko.observable(name);
    self.Description = ko.observable(description);
}

var john = new objectModel('John', 'a person');


Q:

Joomla component doesn't show Permissions actions

I am creating a new component that has a Permissions tab like other components using config.xml and access.xml files.
but i have a weird problem, everything is fine when i install it on localhost but when i install the component on my host on the web it doesn't show the actions for access levels (Configure,  Access Administration Interface, Create, Edit, Edit state, Edit own).
other components work fine and my component works fine on localhost.
i tested it on cPanel and Direct Admin and again the same problem happens.
does anyone had this problem before?

A:

I copied the code from com_weblinks/config.xml to my component config.xml file and it worked!
<fieldset name="permissions"
        description="JCONFIG_PERMISSIONS_DESC"
        label="JCONFIG_PERMISSIONS_LABEL">
        <field name="rules" type="rules"
               component="com_component_name"
               filter="rules"
               validate="rules"
               label="JCONFIG_PERMISSIONS_LABEL"
               section="component" />
</fieldset>

I found I had entered my component name in capital letters component="COM_COMPONENT_NAME", so cPanel and Direct admin both were case sensitive about this, but localhost didn't care!


Q:

ArrayAdapter initialization error (Android)

I have written the following code snippet in my App:
public Fragment getItem(int position) {

    switch(position){
        case 0:
            LP_Events_Tab mEventsTab= new LP_Events_Tab();
            mList= (ListView) findViewById(R.id.event_list);
            String[] temp= {"1","2","3"};
            ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, temp);
            return mEventsTab;

           /*Other cases*/
    }
    return null;
}

For case 0, I am using an array of strings named temp to initialize the ArrayAdapter. However, Android Studio redlines the ArrayAdapter initialization arguments: (this,android.R.layout.simple_list_item_1, temp) and thus, I cannot proceed. I do not see any error with these arguments but Android Studio does and hence, I am stuck.

A:

Replace the following line of code inside your Fragment -
ArrayAdapter<String> arrayAdapter= new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, temp);

Hope this helps, let me know if you need any more help.


Q:

How to make Compression Gzip in my xml request using asp code?

I need to implement Compression Gzip in the below xml request
 <%

    pXML=Server.URLencode(XML_Request)
set http = server.CreateObject("MSXML2.ServerXMLHTTP")
http.open "post", "http://213.171.234.70/appservices/http/FrontendService", false

    http.setRequestHeader "Content-Type",
 "application/x-www-form-urlencoded"
http.send  "xml_request=" &pXML

     http_response= http.responsexml.xml
     Set xd= Server.CreateObject("Microsoft.XMLDOM")
     xd.async = "false"
     xd.loadXML(http_response)

 %>

Please help to fix this.....
tks

A:

You can try to add the accept header, so the server will send gzip encoded content.
Add this to your code before http.send:
http.setRequestHeader "Accept-Encoding", "compress, gzip"


Q:

How common were cybernetics in Star Wars?

In Star Wars, how many characters have cybernetic enhancements?
In The Empire Strikes Back, Luke has his severed hand replaced shortly after losing it.
Anakin also has most of his arm replaced in Attack of the Clones; later, he becomes more machine than man with cybernetics.
Commander Wolffe also gets a cybernetic eye.
General Grievous has most of his body replaced by cybernetics. However, his organs still appear mostly intact.
The technology seems to perfectly replicate the mechanics of a human hand/arm/eye/cardiovascular system/respiratory system/skin.
Would it be considered a common medical practice to replace lost/damaged body parts with Cybernetics? Or Were these procedures considered available to only elite characters?
At first it seems fairly common however the three characters mentioned above may be considered special enough to have an uncommon medical procedure executed:

Luke: Hero of the Rebel Alliance to Restore the Republic, leader of Rouge/Red Squadron, Friends with Princess/General Leia Organa.
Anakin: Jedi Knight at the height of their power during a war with a nearly blank check policy.
Darth Vader: Sith Lord during tyrannical rule of Sith Empire. Apprentice to said Empire's leader.
Commander Wolf: Commander with some skill over the standard trooper. He also had a personal relationship with Jedi Master Plo Koon, who may have more pull to help out Wolf.
General Grievous: Second in command to the Separatist Army. A tool to be used by Darth Sidious and en elite warrior in his own right.

A:

Cybernetics were common enough that a noodle shop owner named Lauli Wahlo was able to afford a cybernetic right eye:

Wahlo's artificial eye is much more simplistic than the cybernetics we've seen on main characters, though, so it's possible that only the wealthiest and/or most important could afford something as nice as Luke's artificial hand.
It's hard to say how common cybernetics really were since not many characters use them (even Wookieepedia's Legends article for cybernetics has only a short list of mostly major characters who had cybernetic enhancements).


Q:

Mail sent on iPhone via Safari or Twitter or other apps is never received, but email sent from within Mail is fine

I am using iOS 6.1.4 on iPhone 5, and I've noticed that at some point in the past few weeks - I do not know exactly when it began - any email I try to send from within any non-Mail app, such as sharing links from within Safari, InstaPaper, Twitter, or Tweetbot, are never received by the recipient. The email does not show up in my Sent Items folder either. There is no error message displayed when trying to send these emails - I press Send and the email window is animated into the background as normal.
I do not have any problem with sending emails from directly within the Mail app itself, these are received fine by recipients and show up in the Sent folder as expected. I have verified that the emails that originate from within Safari or other apps are not simply ending up in a Spam folder.
I have two email accounts set up on my phone, Gmail and an Exchange account for work that I leave disabled/inactive most of the time. The Gmail account is set up as Exchange and the server name is listed as m.google.com with Use SSL enabled.
Has anyone seen anything like this before or know what might be the cause?

A:

I thought I had tried this before, but powering off and restarting the phone has fixed everything.


Q:

jQuery UI Datepicker - Date of Birth - Year not being selected correctly

I am having a problem getting users to select the correct year in their date of birth on a form. I have set the yearRange and changeYear options but it still defaults to 2011 when selected.
Fiddle here http://jsfiddle.net/allyreid/H94cc/

A:

I moved the yearRange selection into the datepicker options, and then added changeYear.
// UI Date Picker
$(".datepicker").datepicker({

    showOn: "both",
    buttonImage: "/images/calendar.png",
    buttonImageOnly: true,
    yearRange: '1910:2010',
    changeYear: true
});

A:

Did you read the documentation? http://jqueryui.com/demos/datepicker/#min-max It even gives an example.
http://jsfiddle.net/H94cc/4/
http://jsfiddle.net/H94cc/13/
$(".datepicker").datepicker({
    minDate: new Date(1910,0,1),
    maxDate: new Date(2010,0,1),
    yearRange: '1910:2010' ,
    changeYear: true,
    changeMonth: true
});


Q:

Jquery will not hide/show div

I'm trying to hide a Live Chat box on page load and then when a hyperlink is clicked, display the Chat box after 30 seconds.
Anybody have any ideas what I'm doing wrong?
Jquery

cshtml

@Umbraco.Field("contactustab3title")

                        @Umbraco.Field("contactustab3content")

UPDATE
The below works. I think the problem is with the chat script itself. It seems even when its inside the div it has a mind of its own.

        test

A:

I resolved the issue by using the setTimeout() method.
My chatBox hyperlink now has an onclick call to a new method called loadChat().
This then calls another method called showChat which then in turn loads the chat box script.


Q:

Symbols on the end of a line

is it possible to remove these symbols, and if it is, how am I goding to do that?
Thanks in advance!

A:

Window | Preferences | General | Editors | Text Editors --> Show
  whitespace characters


Q:

Exclude first 'x' bytes of binary data from a file while reading in VB.NET

I am a noob working on binary files. And its an extension to this question: Reading 'x' bytes of data
My binary file size if 1025 KB, which is 1049600 bytes that contains 1024 bytes of header info. I would like to read remaining data only after 1023th bit, which equals 1048576 bytes.
How do I exclude the first 1024 bytes?
I am using the same code but I can't get it to work, is there anything wrong in my code?
Dim arraySizeMinusOne = 5
Dim buffer() As Byte = New Byte(arraySizeMinusOne) {}
Using fs As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)
    fs.Read(buffer, 0, buffer.Length)
    Dim _arraySizeMinusOne = 1048575
    Dim _buffer() As Byte = New Byte(_arraySizeMinusOne) {}
    'Process 1048576 bytes of data here
End Using

A:

Create a byte array of length the entire file minus, the size you exclude, and minus 1. The last 1 is because vb arrays are different from c# ones. In vb:
Dim buff() As Byte = New Byte(10) {}

creates a 11 size array and in c#:
byte[] buff = new byte[10];

creates a 10 size!
Using fs As New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)
    Dim buff() As Byte = New Byte(CInt(fs.Length - 1024 - 1)) {}
    Dim buffTotal() As Byte = New Byte(CInt(fs.Length - 1)) {}
    'read all file
    fs.Read(buffTotal, 0, buffTotal.Length)
    If fs.Length > 1024 Then
        'move from 1024 byte to the end to buff array
        Buffer.BlockCopy(buffTotal, 1024, buff, 0, buffTotal.Length - 1024)
    End If
End Using

buffer is not a good name because in vb exist already a class Buffer! Change it to something else like buff.


Q:

How to execute JS from Python, that uses 'Document' and/or 'Window'

I am currently working on getting JavaScript to execute successfully from within Python. I have implemented a JS engine (v8) using the PyV8 package. From here I can execute primitive JavaScript ("1+2", etc). However, for JavaScript that uses references to "document" or "window" the code will throw an error. I am looking, ideally, for a Python implementation however a JavaScript implementation would work as well as I could prepend it to my script before executing it what my JavaScript engine.
To summarize: How can I execute JavaScript, that uses 'Document' and/or 'Window', from within JavaScript?

A:

I was having the same problem when using Spidermonkey (a command-line JavaScript interpreter) and trying to run a script that relied on the non-existent document and window objects.
I solved it by using the Env-JS project, which sets up independent "fake" objects for them.


Q:

Can early exposure to stimulates, like ritalin, result in higher tolerance to them?

As a child I was diagnosed with ADD and put on Ritalin from a young age.  As a child I use to have significant insomnia, but did not realize it was due to Ritalin until I finally stopped taking it much later, as I didn't realize my difficulty with sleeping was unusual or qualified as insomnia.
As an adult it seems as if I have an above-average tolerance to stimulants, especially considering I'm slim (if not short) and thus likely in in the lower 50th percentile for mass for males.
In particular I can drink a soda, or coffee, without any difficulty falling asleep or help 'waking up' when tired.  I also find that no AD/HD medication appears to have a significant affect on me.
I'm wondering if early exposure to stimulant like Ritalin could have resulted in a higher tolerance to stimulants in general, or if I'm just crazy :).

A:

Yes, unfortunately, Ritalin produces a tolerance in individuals who take it.
In the conclusion of this double blind trial, the author notes,

Acute tolerance to methylphenidate appears to exist. This should be
  considered in the design of an optimal dosing regimen for the
  treatment of children with attention deficit hyperactivity disorder.

Acute tolerance to methylphenidate in the treatment of attention deficit hyperactivity disorder in children.
Addendum:
This might be a useful reference for ADHD in general:
Attention Deficit Hyperactivity Disorder: Diagnosis and Management of ADHD in Children, Young People and Adults.


Q:

Accessing resources from a service launched at boot

At boot, I have a BroadcastReceiver which launches a Service. In this Service, I trigger a Notification, and I want the text of the Notification to be retrieved from the Activity which will be launched when the user clicks the Notification (through it's resources).
The BroadcastRecevier, the Service and the Activity are all bundled in the same package.
The question is : how can I retrieve the Activity's resources from the Service as I don't have any handler for my Activity in it? And I can't have one since the Service is launched before the Activity.
Thanks in advance for the time you will spend trying to help me.

A:

Activities don't have resources. Applications have resources. Your service would access your application's resources in the same way anything else does (e.g., via calls to getString(), or `getResources()).


Q:

How do I track a long running async request in AngularJS / ui-router

I am building an Angular app using state hierarchy provided by the angular-ui/ui-router library.
I have a request that takes many minutes to complete, so the goal is to POST to a request resource and then poll the server to determine when the request completes. The app is quite large and different areas of the site are organized into different decoupled modules, but the header is managed by a common root state.
In order to message the completion event to the user without disturbing their browsing session, I would like to:

Add a "loading" spinner to the header of the app when the request is made
Allow the user to continue browsing the site but retain the "loading" spinner
Replace the spinner with a "check" icon once the polling determines that the request has been completed.

How can i encapsulate this process and allow it to continue running through multiple state transitions?

A:

I'm not entirely sure how  ui-router works, but if it's anything like $routeProvider (or you're using $routeProvider as well), you can assign a controller to the "header of the app" and let that controller do the work.
Below is a basic example of how it would work.  _handleLoad simulates polling the server, and when it's all done, you can change the header easily (or the rest of your site using $broadcast).  The $routeProvider let's the user browse the site while the HeaderCtrl continues executing on the page.
http://plnkr.co/edit/EYqcjhX8kI1GmkYs5VZe?p=preview
app.controller('HeaderCtrl', function ($scope, $timeout) {
  var _i = 0,
      _handleLoad = function () {
        console.log('checking..');
        // TODO check the server here, fire the $timeout in the callback if the process isn't complete
        if (_i == 3) {
          $scope.loading = false;
          _i = 0;
          $scope.headerText = 'we have loaded something';
          console.log('all done');
          return;
        }
        _i += 1;

        $timeout(_handleLoad, 1000);
      };

  $scope.headerText = 'click here to load something';
  $scope.loading = false;

  $scope.load = function () {
    $scope.loading = true;
    _handleLoad();
  }
});


Q:

How do get the rows between row A and row B in a table

I have an event log that contains many rows like:

I would like to get back:
group                  | text
-----------------------------------------------------
ErB0zyuzRq6DstbP0UdMag | Received: 1
                       | Received: more text
                       | Received: and some more text

So essentially I want to group and extract all text that occurs between group since there is multiple events that can occur between the start and end occurrence of ErB0zyuzRq6DstbP0UdMag.
I've tried to partition by number (in this case 36 / 37) but I just cannot seem to win. Any help would be appreciated. The start of each sequence is always labelled with 36 and the end with 37, so I definitely think using WINDOW will work, but no luck so far.
In addition, the contents that I want is always labelled as 25.

A:

Below is for BigQuery Standard SQL
#standardSQL
SELECT grp, ARRAY_AGG(text ORDER BY ts) AS text
FROM (
  SELECT *,
    LAST_VALUE(IF(label=36, text, NULL) IGNORE NULLS) OVER(ORDER BY ts) AS grp
  FROM `project.dataset.table`
  WHERE label IN (36, 37, 25)
)
WHERE label = 25
GROUP BY grp

If to apply to sample / dummy data as in below example
#standardSQL
WITH `project.dataset.table` AS (
  SELECT 36 label, '2020-06-01 15:54:31.266711 UTC' ts, 'ErB0zyuzRq6DstbP0UdMag' text UNION ALL
  SELECT 25, '2020-06-01 15:55:31.266711 UTC', 'Received: 1' UNION ALL
  SELECT 25, '2020-06-01 15:56:31.266711 UTC', 'Received: more text' UNION ALL
  SELECT 26, '2020-06-01 15:57:31.266711 UTC', 'Received: more text - to ignore' UNION ALL
  SELECT 25, '2020-06-01 15:58:31.266711 UTC', 'Received: and some more text' UNION ALL
  SELECT 37, '2020-06-01 16:54:31.266711 UTC', 'ErB0zyuzRq6DstbP0UdMag' UNION ALL
  SELECT 36, '2020-06-01 16:55:31.266711 UTC', 'XrB0zyuzRq6DstbP0UdMag' UNION ALL
  SELECT 28, '2020-06-01 16:56:31.266711 UTC', 'Received: 2 - to ignore' UNION ALL
  SELECT 25, '2020-06-01 16:57:31.266711 UTC', 'Received: more text 2' UNION ALL
  SELECT 37, '2020-06-01 16:58:31.266711 UTC', 'XrB0zyuzRq6DstbP0UdMag'
)
SELECT grp, ARRAY_AGG(text ORDER BY ts) AS text
FROM (
  SELECT *,
    LAST_VALUE(IF(label=36, text, NULL) IGNORE NULLS) OVER(ORDER BY ts) AS grp
  FROM `project.dataset.table`
  WHERE label IN (36, 37, 25)
)
WHERE label = 25
GROUP BY grp

result is


Q:

Creating primitive array out of wrapper collection in java

Is there a fast (in terms of saving programmers time not the execution time of program) utility method in default java libraries (without any external 3rd util libs)  which would enable to create primitive array from a primitive wrapper collection?
Example:
int[] array = magicMethod(Collection<Integer>);

Without manually creating new array instance iterating over the collection myself?
If not for collection, even for List<Integer> would be nice.

A:

You can't, because you must at least check how you're going to convert a null Integer to a primitive value.
Even Guava and Apache Commons have to iterate on the object list to make the conversion internally.
Guava - http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/Ints.html#toArray%28java.util.Collection%29
Apache Commons - http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#toPrimitive%28java.lang.Integer[]%29


Q:

How to access controls of dynamically added user controls in a panel in C#?

I have a panel which has multiple dynamically added user controls (all the same) and I need to see if a checkbox is checked and what the label.text is in each of these controls. Not sure how I would get these values?
This is where the user controls are being added to the panel
private void Employee_Add_Load(object sender, EventArgs e)
    {
        List<string> VehicleTypes = DAL.LicenseDAL.GetAllVehicleTypes();

        foreach (string Vehicle in VehicleTypes)
        {
            User_Controls.Vehicle_Bar VTB = new Vehicle_Bar(Vehicle);
            pnlVehicleChecks.Controls.Add(VTB);
        }
    }

This is the user control (which is literally just a label and checkbox)
public partial class Vehicle_Bar : UserControl
{
    public string Vehicle = "";

    public Vehicle_Bar(string vehicle)
    {
        Vehicle = vehicle;
        InitializeComponent();
    }

    private void Vehicle_Bar_Load(object sender, EventArgs e)
    {
        lblType.Text = Vehicle;
    }
}

All of these check-boxes are for a vehicle license for an employee, depending on what check boxes are checked depends what vehicle they will be allowed to drive

A:

You can handle the retrieval of checkbox data inside the UserControl and store it in a publicly accessible data object
public class VehicleInfo
{
    public bool allowdrive {get; set; }
    public string vehicle {get; set; }
}

public partial class Vehicle_Bar : UserControl
{
    public VehicleInfo vehicleInfo;

    public Vehicle_Bar(string vehicle)
    {
        vehicleInfo = new VehicleInfo(){
            vehicle = vehicle,
            allowdrive = false
        };

        InitializeComponent();
    }

    private void Vehicle_Bar_Load(object sender, EventArgs e)
    {
        lblType.Text = vehicleInfo.vehicle;
    }

    //Handle checkbox click event to set the value of "allowdrive"
}

The combined data of the string and the checkbox are stored in the object vehicleInfo, which can be accessed using an instance of the UserControl Vehicle_Bar
example :
Console.WriteLine(VTB.vehicleInfo.allowdrive);


Q:

¿Porque no puedo acceder a la clase R desde este metodo?

Estoy empezando en Android y me he encontrado con que desde el siguiente metodo que os voy a mostrar no me lee un string que tengo puesto en la clase R, es decir en el archivo "strings.xml" los cuales son:
<string name="registrarse">Registrarse</string>
<string name="iniciar">Iniciar Sesion</string>

El metodo esta en el MainActivity y es el siguiente:
public void RegistroInicio (View view){

    String InfoBtn = btInicio.getText().toString();

    if(InfoBtn.equals(R.string.iniciar)){
                IniciarSesion(view);
    }else if(InfoBtn.equals(R.string.registrarse)){
            Registrarse(view);
        }
}

La cosa es que si lo sustituyo por texto entre comillas, "Iniciar Sesion" si que me funciona. ¿Que podría estar fallando?
Gracias de antemano.

A:

Muy buenas Enzo,
Lo que se encuentra en la clase R es una referencia y por tanto para poder acceder a los string definidos deberías hacer:
context.getString(R.string.iniciar)

Espero que te pueda ayudar. Un saludo


Q:

add_filter not working on Wordpress custom login page

I'm creating a custom login page in wordpress. Everything is good so far but I want to add error handling to my page.
In default-filters.php, I added this:
add_filter('authenticate', 'wp_return_login_error', 40, 3);

In users.php, I added this:
function wp_return_login_error(){

    if (is_wp_error($user)) {
        $error = $user->get_error_message();
        wp_redirect( get_permalink() . "/login/?login=failed&reason=" . $error);
        exit;
    }
}

No matter what, when you enter invalid/blank credentials, the user is simply redirected to the login screen without any indication of what went wrong. I tried adding debug messages in my function and it looks like it isn't being called.
What should I try?
Thanks in advance for your help.

A:

The easiest way around this is to change the error message with this code in your functions.php file:
function login_error_override()
{
    return 'Incorrect login details.';
}
add_filter('login_errors', 'login_error_override');


Q:

Reading from a html form object in javascript only if object exists

post submit I want to javascript/client side read user input
var h = document.getElementById("myTEXTbox").value;

but the textbox only exists depending earlier user choices. is the an if object exists in javascript?

A:

Try this:
var element = document.getElementById("myTEXTbox"),
    h = element ? element.value : null;


Q:

How much FIDE rated chess was played in April 2020?

FIDE has just published the May 2020 rating list which brings the ratings up to date for games played in April. The rating file can be downloaded from the FIDE download page.
Many countries have locked down some time in April (due to the current pandemic) and chess is no longer played. Some countries haven't locked down and chess may still being played. How has this affected the numbers?
A short explanation of how FIDE counts games.
Suppose I have a rating and I play two games, one against Jim Unrated and one against Jane Rated and I draw both games.
In Jim Unrated's record his game against me will be recorded because if he has enough games and reached a high enough level then his game against me will be used to calculate his rating. Even if he didn't qualify yet it will still be recorded to be used to calculate his first rating sometime in the future.
In Jane Rated's record her game against me will, of course, be recorded. The result will be used to calculate her rating adjustment.
In my record the game against Jane will be recorded because that affects my rating but the one against Jim won't be. He is unrated so our game won't affect my rating.
So, between the three of us we played 2 games but that will be recorded as 3 "half games".
I have some statistical questions regarding these “half-games.”
1) How many half-games of standard time control were played in April?
2) How many half-games of rapid were played in April?
3) How many half-games of blitz were played in April?
4) How do these numbers compare to March?
Note that some chess was played in April. For instance the Nigerian national championships was played. It was a 10 player all-play-all which started on 30th March and finished on 3rd April.
Sweden is also a country where there has been no lockdown and (some) chess has continued. Here is an example of a tournament which is played over several months but in any case lasting more than 90 days (looks like a club tournament where one round is played per month, started in October 2019) Round 7 of Horndal KM 201920 played on 15th April.

A:

Fascinating question. I computed the stats for each individual file (Standard, Rapid and Blitz) downloaded from the FIDE download page.
I added up the number of games reported for each FIDE player for each control time and list.
Standard Time Control

145,618 games played in  and reported in the April list.
Only 9,946 games played in standard time control and reported in the May list!

Rapid

54,192 games played and reported in the April list.
Only 1,446 games and reported in the May list!

Blitz

24,514 games played and reported in the April list.
only 1,005 games and reported in the May list!

Regarding games played in April 2020.
The round 7 of Horndal KM 201920 has indeed been played on 15th April. However, the Nigerian national championships were played in March. See the report of the Nigerian Chess Federation.

A:

As I said in an earlier answer I've built a database with downloaded data from Olimpbase and FIDE to allow me to do data mining. To answer this question I downloaded the latest (May 1st) rating list and loaded the data into my database and ran a few queries.
These are the results I get for Sum(Games) for April and May for Standard, Rapid and Blitz:
April Standard: 164531
May Standard: 10295
April Rapid: 68490
May Rapid: 1550
April Blitz: 56683
May Blitz: 1341
Interesting to note the small differences between my figures and Kortchnoi's.
I download the XML format file from the section on the download page where it says:

Download full list of players (not rated included) STD, RPD, BLZ
  combined TXT format (01 May 2020, Sz: 21.11 MB) | XML format (01 May
  2020, Sz: 23.77 MB)

I suspect Kortchnoi is downloading the individual files from where it says:

Download STANDARD rating list TXT format (01 May 2020, Sz: 7.92 MB) |
  XML format (01 May 2020, Sz: 8.55 MB)
Download RAPID rating list TXT format (01 May 2020, Sz: 4.28 MB) | XML
  format (01 May 2020, Sz: 4.58 MB)
Download BLITZ rating list TXT format (01 May 2020, Sz: 3.15 MB) | XML
  format (01 May 2020, Sz: 3.38 MB)

Before this I always thought the main difference between the data sets was that the full set I download and use also includes the FIDE online Arena players as well. It looks as if the individual files miss out on some of the data.
EDIT:
To explore how many of these tournaments that were reported in the May list were actually played at least partly in April I looked at the players in the May list who are recorded as having played some games. There were 181, which is too many to list but it is worth looking at their federations.
Fed - Number of players with Games > 0
ARM 1
CUB 1
HON 1
ISL 1
NCA 22
NGR 14
PER 33
POR 38
RUS 59
SWE 6
TUR 1
USA 1
VEN 3
These players played in tournaments in 6 countries which, not surprisingly, correspond to the federations with the most number of players in this list.
Here are the federations with links to the FIDE page for the FIDE tournaments for May for each federation together with a list of the blitz tournaments for that federation, again with links.
Nicaragua
1er Torneo Blitz Nicaragua 2020, played - 15/3, reported - 13/4
Note, there was a rapid III Torneo Academia de Ajedrez Julio Ramirez de Arellano 2020 which was played from 18th to 19th April and reported on 28/4
Nigeria
DR NIYI ORIOLOWO NATIONAL BLITZ CHESS CHAMPIONSHIP, played - 29/3, reported - 31/3 (impressively quick reporting by the Nigerians)
Peru
II IRT TORNEO BLITZ CLUB DE AJEDREZ WANKA 2020, played - 8/3, reported - 30/4 (taking "manyana" to South American extremes)
Portugal - 5 tournaments all played on 8/3, reported - 21/4
CD Rapidas Jovens Porto 2019-20 - U10,
D Rapidas Jovens Porto 2019-20 - U12 U14,
CD Rapidas Jovens Porto 2019-20 - U16,
CD Rapidas Jovens Porto 2019-20 - U18 U20,
CD Rapidas Veteranos Porto 2019-20
Russia
CHESS PLAZA_March Blitz, played - 9/3, reported - 3/4
Perm blitz 17-03-2020, played - 17/3, reported - 4/4
Initsiativa club march blitz, played - 29/3, reported - 8/4
Sweden
Kristianstad Pasksnabben 2020, played - 13/4, registered - 13/4
So, only one Swedish blitz tournament was actually played in April although a couple of tournaments were played close enough to the end of March to justify reporting in April. There was also one rapid I spotted in passing played in April in Nicaragua.
Looking at Sweden in general there looks to be lots of league chess still being played at standard time control. Interestingly there was one standard tournament played in April in Russia that I noticed - Bratsk championship 2020, 11 round standard time control.
It will be interesting to do a similar analysis on the 1st June to see if any other countries are joining Sweden, or even if Sweden continues.


Q:

Prompt to replace empty cells with user-defined text

I need VBA code to check for blank cells within a range. If there are any blanks within that range, a box should come up to allow you to type in what you want to replace the blanks with. The code below does what I want, but the prompt ALWAYS appears, even if there aren't any blanks. How do I make it so the box only appears if there are blanks?
Sub ReplaceBlanks()
  Dim Lastrow As Integer
  Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

  Range("D84:D" & Lastrow).Select
  Dim cell As Range
  Dim InputValue As String
  On Error Resume Next
  InputValue = InputBox("Enter value that will fill empty cells in selection", "Fill Empty Cells")
  For Each cell In Selection
    If IsEmpty(cell) Then
      cell.Value = InputValue
    End If
  Next
End Sub

A:

Sub ReplaceBlanks()
Dim Lastrow As Integer
Dim srchRng As Range

Lastrow = Cells(Rows.Count, 1).End(xlUp).Row
Set srchRng = Range(Cells(84, 4), Cells(Lastrow, 4))

Dim InputValue As String

If srchRng.Count - WorksheetFunction.CountA(srchRng) > 0 Then
    InputValue = InputBox("Enter value that will fill empty cells in selection", _
                          "Fill Empty Cells")
    srchRng.SpecialCells(xlCellTypeBlanks).Value = InputValue
End If
End Sub

This also adds in the range variable, so you avoid using .Select. It also assumes that you only want ONE inputvalue. If you want it to trigger for each empty cell, put the inputValue = ... in the If IsEmpty(cell) loop.
An alternative to your If a cell is empty loop, is a one line fix:
Range(Cells(84,4),Cells(lastRow,4)).SpecialCells(xlCellTypeBlanks).Value = InputValue.  That will take ALL blanks in D84:DlastRow and fill in with whatever the InputValue is.  No need to loop.


Q:

Check if a double > 1 is divisible by a double < 1

I'm trying to check if a double (time) > 1 is divisible by another double (samplePeriod) which is > 0 and < 1. The following code works for samplePeriods > 1, but not < 1. Any ideas? Thanks.
    /// <summary>
    ///   Check if a sample is within 1/10 of a samplePeriod from being on a samplePeriod
    /// </summary>
    /// <param name="time"> The time of the sample </param>
    /// <param name="samplePeriod"> The period between samples </param>
    /// <returns> True if the sample is on a sample period, false if not </returns>
    public static bool SampleIsOnSamplePeriod(double time, double samplePeriod)
    {
        if (Math.Abs(time%samplePeriod - 0d) > (samplePeriod/10))
        {
            return false;
        }
        return true;
    }

A:

public static bool SampleIsOnSamplePeriod(double time, double samplePeriod)
{
    double mod1 = (time / samplePeriod) % 1;
    return (mod1 < .1) || (mod1 > .9);
}

Basically you are dividing time by samplePeriod and then doing a mod by 1. If it is "close enough", then this value should be between 0 and 0.1 or between 0.9 and 1.
The left side of the check is checking [0, 0.1]. The right side is for [0.9, 1].


Q:

Sorting columns in GridView

I use such method to sort columns in GridView
private BandedGridView bandedGridView;

public void SetControlsSortOrder(ColumnSortOrder sortOrder)
        {
            bandedGridView.BeginDataUpdate();
            try
            {
                bandedGridView.SortInfo.ClearSorting();
                bandedGridView.SortInfo.Add(new GridColumnSortInfo(colName, sortOrder));
            }
            finally
            {
                bandedGridView.EndDataUpdate();
            }
        }

When sortOrder is Ascending or Descending method works fine, but when sortOrder is None columns in table is sorted by descending.
Could you help me solve this problem?

A:

If your colName is grouped then its sort order cannot be set to ColumnSortOrder.None value and your column using the last sort order that was applied to it. If your colName is not grouped then check for sort glyph if you see sort glyph then sorting is applied to your column. If you can not see sort glyph then your DataSource is coming already sorted as mentioned by Burak Ogutken.
Also, for sorting use BandedGridView.BeginSort and BandedGridView.EndSort methods. To set the sort order you simply can use the BandedGridColumn.SortOrder property. To clear sorting you can use BandedGridView.ClearSorting method.
Here is example:

public void SetControlsSortOrder(ColumnSortOrder sortOrder)
    bandedGridView.BeginSort();
    try {
       bandedGridView.ClearSorting();
       colName.SortOrder = sortOrder;
    }
    finally {
       bandedGridView.EndSort();
    }
}


Q:

Pandas dataframe - speed in python: dataframe operations, numba, cython

I have a financial dataset with ~2 million rows. I would like to import it as a pandas dataframe and add additional columns by applying rowwise functions utilizing some of the existing column values. For this purpose I would like to not use any techniques like parallelization, hadoop for python, etc, and so I'm faced with the following:
I am already doing this similar to the example below and performance is poor, ~24 minutes to just get through ~20K rows. Note: this is not the actual function, it is completely made up. For the additional columns I am calculating various financial option metrics. I suspect the slow speed is primarily due to iterating over all the rows, not really the functions themselves as they are fairly simple (e.g. calculating price of an option). I know I can speed up little things in the functions themselves, such as using erf instead of the normal distribution, but for this purpose I want to focus on the holistic problem itself.
def func(alpha, beta, time, vol):
    px = (alpha*beta)/time * vol
    return px

# Method 1 (could also use itertuples here) - this is the one that takes ~24 minutes now
for row in df.iterrows():
    df['px'][row] = func(alpha, beta, df['time'][row], df['vol'][row])

I have also tried vectorizing this but keep getting an error about 'cannot serialize float' or something like that.
My thought is to try one of the following methods, and I am not sure which one would theoretically be fastest? Are there non-linearities associated with running these, such that a test with 1000 rows would not necessarily indicate which would be fastest across all 2 million rows? Probably a separate question, but should I focus on more efficient ways to manage the dataset rather than just focus on applying the functions?
# Alternative 1 (df.apply with existing function above)
df['px'] = df.apply(lambda row: func(alpha, beta, row['time'], row['vol']), axis=1)

# Alternative 2 (numba & jit)
@jit
def func(alpha, beta, time, vol):
    px = (alpha*beta)/time * vol
    return px

# Alternative 3 (cython)
def func_cython(double alpha, double beta, double time, double vol):
    cdef double px
    px = (alpha*beta)/time * vol
    return px

In the case of Cython and numba, would I still iterate over all the rows using df.apply? Or is there a more efficient way?
I have referenced the following and found them to be helpful in understanding the various options, but not what the 'best' way is to do this (though I suppose it depends ultimately on the application).
https://lectures.quantecon.org/py/need_for_speed.html
Numpy vs Cython speed
Speeding up a numpy loop in python?
Cython optimization
http://www.devx.com/opensource/improve-python-performance-with-cython.html

A:

How about simply:
df.loc[:, 'px'] = (alpha * beta) / df.loc[:, 'time'] * df.loc[:, 'vol']

By the way, your for-loop/lambda solutions are slow because the overhead for each pandas access is large. So accessing each cell separately (via looping over each row) is much slower than accessing the whole column.


Q:

The Laplace Transform of Piecewise Function

Write the following as an unit step function and find the Laplace transform.
$f(t)=\begin{cases}{t}&0 \leq t < 3\\ 3&3 \leq t < 4\\ 11-2t& 4 \leq t < 5.5 \\ 0&t \geq 5.5  \end{cases}$
Workings:
$f(t) = t - u(t-3)(t) + u(t-3)(3) - u(t-4)(3) + u(t-4)(11-2t) - u(t-5.5)(11-2t)$
$f(t) = t - u(t-3)t+ 3u(t-3) - 3u(t-4) + u(t-4)(11-2t) - u(t-5.5)(11-2t)$
$\mathcal{L}\{f(t)\} = \mathcal{L}\{t\} - \mathcal{L}\{u(t-3)t\} + 3\mathcal{L}\{u(t-3)\} - 3\mathcal{L}\{u(t-4)\} + \mathcal{L}\{u(t-4)(11-2t)\} - \mathcal{L}\{u(t-5.5)(11-2t)\}$
$\mathcal{L}\{f(t)\} = \frac{1}{s^2} - \mathcal{L}\{u(t-3)t\} + \frac{3e^{-3s}}{s} - \frac{3e^{-4s}}{s} + + \mathcal{L}\{u(t-4)(11-2t)\} - \mathcal{L}\{u(t-5.5)(11-2t)\}$
Now I'm not sure what to do. Any help will be appreciated.

A:

Note that if $a>0$,
$$ \mathcal{L}(u(t-a)f(t)) = \int_0^{\infty} e^{-st} u(t-a)f(t) \, dt = \int_a^{\infty} e^{-st} f(t) \, dt, $$
since $u(t-a)$ is $0$ for $t<a$. Then setting $x+a=t$, we have
$$ \mathcal{L}(u(t-a)f(t)) = e^{-as}\int_0^{\infty} e^{-sx} f(a+x) \, dx, $$
if you prefer.


Q:

Java bytecode with Jasmin: why is the message not printed on the screen?

I recently became interested in Java bytecode and I created the following Hello World program.
The "Hello World" is printed, however I can't figure out why "Creating awesome object" isn't printed. Can you help me figure out what I'm doing wrong?
.class public HelloWorld
.super java/lang/Object

.method public <init>()V
    .limit stack 2

    aload_0  ; push 'this' unto stack
    invokespecial java/lang/Object/<init>()V  ; invoke constructor

    getstatic java/lang/System/out Ljava/io/PrintStream;
    ldc "Creating awesome object!"
    invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V

    return
.end method

.method public static main([Ljava/lang/String;)V
    .limit stack 2

    getstatic java/lang/System/out Ljava/io/PrintStream;
    ldc "Hello world"
    invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V

    return
.end method

A:

I don't know much about Java bytecode, but it seems to me you don't create an instance of HelloWorld in main. If you don't create an instance, the constructor does not get called, so there you have it. :)


Q:

Listing all k-element subsets of an n-element set where consecutive sets differ by 2 elements

Let $S$ be the set of all $k$-element subsets of some given universe $M$.
My question is as follows: Is it possible to enumerate (without repetition) the elements of $S$ such that each pair of  consecutive sets differ in 2 elements.
I've been thinking about the following approaches, but so far haven't made much progress:
We can think of the sets in $S$ as binary vectors of length |M|, where the vector for set $A$ is 1 at index $i$ iff the $i$-th element of $M$ is in $A$.
We can form a graph by using these vectors as vertices and where there is an edge between $2$ vertices if their Hamming distance is exactly $2$. Now the goal becomes finding a Hamiltonian path in this graph.

A:

According to the claim after Lemma 1.1 in this paper, the answer is yes. Take the $k$-subsets in the order they appear in the (reflected) Gray code for the full power set of $M$.


Q:

javascript script unescape hangs IE and Chrome but not Firefox

The following script request seems to have problems in any browser except Firefox.
<!DOCTYPE html>
<html>
    <head>
        <title>Browser Delay</title>
        <script type="text/javascript"  src="http://www.google.com/jsapi"></script>
        <script type="text/javascript">
            google.load("jquery", "1.4.4");
        </script>
    </head>
    <body>
        <div id="logicbuy_ad">
            <!-- Problem is here!!!!! -->
            <script type="text/javascript" src="http://www.symbiosting.com/LogicBuy/content-syndicate-laptopmag.php"></script>
        </div>
    </body>
</html>

When the script loads, even in an iframe, IE and Chrome seem to hangs until the script finishes.
Is there a way to load this script so that it will not stop/hang the browser?

A:

It appears that the problem only happens when the script is loaded from a local page. (ie. C:\Users{username}{Code Base}\index.html )
Once I hosted the file on IIS, the problem went away.
I'm still very curious as to why the script would hang when displaying the local file as opposed to the hosted version


Q:

Does Linux use GPT flags?

As seen below in output of parted, Windows 8/8.1 seems to use flags in GUID partition entries:

I guess that for example partition with hidden flag is not shown in Windows Explorer. However, does Linux also use GPT flags?

A:

Does it use GPT flags? Define use :)
The only "important" flag to Linux is the boot flag, and that's not directly handled by Linux per se: your system's firmware at boot time will select the filesystem with this flag and search therein for an EFI bootloader, boot that, and then the bootloader will use the filesystem in which it lives to configure itself and do all that it needs.
Linux probably wouldn't modify filesystem flags without your knowledge or consent, and I can't think of a way that it would rely on them as they're not too useful to a booted OS. If you were to also install a BIOS-based bootloader on a GPT volume, there's a flag for that and Linux might use that to determine where it should, say, update that BIOS bootloader.
Typically, you're on your own when it comes to filesystem layout and Linux won't make decisions for you. If you want your EFI volume mounted, you need to shove a line into /etc/fstab. If you have a separate /boot partition, you're going to need to shove that into /etc/fstab too. The only thing I can think of which might look at flags would be bootloader code/installation code, so possibly GRUB or rEFInd. (rEFInd probably just uses EFI variables, though, which are something else)
To answer your question about Windows, it maintains a "secret" partition and uses these flags to hide the partition from the operating system. It's still there and you can access it if you want, but it's made to be difficult. Linux couldn't care less if you call it secret or not, and if you plug in a hard drive with one of these partitions installed, it will show up and be displayed and may be automounted if your machine is configured for that.


Q:

PHP: Show/Hide Div On Specific Pages

I've added the following code to pages to display a notice I only have to write once.
PHP
<?php require $_SERVER['DOCUMENT_ROOT']."/notice.php"; ?>

HTML

2018-09-30 11:00

Daylight Saving begins Sunday 30th Sept

From time to time, however, I want to display this message on particular pages, such as /contact.
Here's what I've come up with. I'm new to this, so I have no idea...
PHP
<?php
    if( is_page( array( "new1", "contact1" ) ) ) {
        $showdiv = 'notice-1';
    }
?>

Note: I've assigned a page id (e.g. "contact1") to help make an array.
In action: https://www.citychurchchristchurch.co.nz/new
I can't get this to work. Any help you can provide would be greatly appreciated. Thanks.

A:

 <?php
      //list your intended pages in an array
      $intended_pages = array('page1', 'page7', 'page12');

      //get the current page name
      $page_name= basename($_SERVER['PHP_SELF']);

      //check if the current page is on the list
      If(in_array($page_name, $intended_pages))
      {
        //current page is on the list so perform function
        $showdiv = 'notice-1';
      }
 ?>


Q:

Question on wave interference?

When dealing with double slit interference or interference of waves from numerous slits, the equation nλ=dsin θ . However I do not understand why for calculating the angle for maxima and minima it is okay to consider the path difference of waves from each slit, where only one wave from each slit is considered. Surely, there are numerous waves from each slit, following huygens principle that each wave from a wave front is a source of a secondary wavelet. Therefore surely, there is interference of infinite waves from each slit. Therefore, surely it is unfair to assume that if one wave interferes in a certain way with another wave from another slit, then all the waves from each slit will interfere in the same way.

A:

Actually, you're completely right. Most treatments of the double slit have some kind of simplification. The usual idea is that we approximate each slit in the double slit to be a point source, so what you're really analyzing is the case of "two coherent point sources."
This approximation can be justified by the assumption that your slits are really tiny compared to the distance between them and the wavelengths. When each slit is tiny, there are "less amount of wavelets" coming out (there are infinitely many but hopefully my point still makes sense), and if there are less amount of wavelets coming out, there are less of them to be out of phase.
When you make your openings smaller and smaller, the two wavelets most out of phase are closer and closer, and they are more and more in phase.
Indeed, in the case of the single slit, when you make the slit opening smaller and smaller, the middle bar becomes wider. At some point, it becomes so wide that you might as rather approximate the slit as a point source.
Of course, you actually can do the full treatment of both the single slit and the double slit in detail (assuming far-field approximations). In fact, you can get the full blown function that describes the pattern. The derivation gets messy, but the idea is that you have infinitely many wavefronts coming out, and you want to "add up" the effects of each wavefront, each of which is infinitesimally small. It turns out this will require an integral to sum them up (much the same way people speak of integrals "adding up" infinitesimal area).
When you do this, the intensity of the wave at the screen is $$ I(\theta) = I_{0}\frac{\sin^{2}(\tfrac{\pi a\sin\theta}{\lambda})}{(\tfrac{\pi a\sin\theta}{\lambda})^{2}}.$$
The double slit pattern (slit width $a$, distance between slits $d$) turns out to have a surprisingly similar function and the pattern is approximately given by
$$ I(\theta) = I_{0}\frac{\sin^{2}(\tfrac{\pi a\sin\theta}{\lambda})}{(\tfrac{\pi a\sin\theta}{\lambda})^{2}} \cos^{2}(\tfrac{\pi d\sin\theta}{\lambda}).$$
When we take $a\ll\lambda$, we have $\pi a\sin\theta /\lambda \approx 0$ so then $\left(\sin^{2}(\tfrac{\pi a\sin\theta}{\lambda})\right) / (\tfrac{\pi a\sin\theta}{\lambda})^{2}  \approx 1$.
Then the equation above becomes
$$ I(\theta)\approx I_{0}\cos^{2}(\tfrac{\pi d\sin\theta}{\lambda})$$
and you can see that the maxima occur when $\tfrac{\pi d\sin\theta}{\lambda} = n\pi$ or rather $d\sin\theta = n\lambda$. But at the end of the day, this is nothing but a simplification/approximation.

I will provide the derivations for the formulas below. A discussion of this and the equations are provided in the last chapter of  Vibration and Waves by A.P. French.

Two Point Sources
Before we answer what happens with infinitely many wavefronts, it'd make sense to ask what if we have two point sources?

Given a point on the screen ahead, what is the straight path from one of the sources to that point? Since the screen is far away, we approximate these two paths to be parallel, as given by the two arrows in the image. The only difference between these two paths here is that one of them is longer by $d\sin\theta$.
We're dealing with 2D waves where they spread out in a circle from each source, but along each line we essentially have a 1D wave. In the picture above, if $x$ is the distance along one of the arrows, the wave is given by $A\sin(kx-\omega t)$. If the right arrow has total distance $x=D$, the left arrow has total distance $x=D+d\sin\theta$ (all that matters is that if you draw a really long triangle, the two longest sides would differ by about $d\sin\theta$).
At the screen, the wave due to the right source is $A\sin\big(kD-\omega t\big)$. The wave due to the left source is $A\sin\big( k(D+d\sin\theta)-\omega t  \big)$. Therefore, our total wave is
$$ A\sin\big(kD-\omega t\big) + A\sin\big( k(D+d\sin\theta)-\omega t \big).$$
To clean this up a little, let $\phi = kD-\omega t$ and let $\Delta\phi = kd\sin\theta$. This gives the expression
$$ A\sin(\phi)+A\sin(\phi+\Delta\phi). $$
This sum of sines is actually just a single sine wave in disguise!
We have to use some non-trivial trig identities. This one is given on wikipedia in the section called "Linear combinations". Then
$$
A\sin(\phi)+A\sin(\phi+\Delta\phi) = \underbrace{\sqrt{A^{2}+A^{2}+2A^{2}\cos(\Delta\phi)}}_{\text{Amplitude}}\sin(\cdots).
$$
The amplitude (using the half-angle formula) is given as
\begin{align*}
\sqrt{2A^{2}+2A^{2}\cos(\Delta\phi)} &= A\sqrt{2}\sqrt{1+\cos(\Delta\phi)} \\
&= 2A\sqrt{ \frac{1+\cos(\Delta\phi)}{2} } \\
&= 2A\cos(\tfrac{\Delta\phi}{2}).
\end{align*}
Ooookay. One more thing. If we back up, we need to clarify that $k$ is called the wave number. It is related to wavelength by $k = 2\pi/\lambda$. With this, we know $\Delta\phi = kd\sin\theta = 2\pi d\sin\theta/\lambda$. Therefore, the wave is $2A\cos\left(\frac{\pi d\sin\theta}{\lambda}\right)$. The intensity is given by the square of the amplitude, so
$$ I(\theta) = 4A^{2}\cos^{2}\left(\frac{\pi d\sin\theta}{\lambda}\right). $$
Single-Slit Pattern
The above was given just so that we have the general approach to looking at these problems, so you can attack the problem where you have three point sources or $N$ many, and this will be useful here.
We have a single slit of width $a$. The strategy is to split the wave into $N$ waves in the spirit of Hyugens.
The wave sources are equally spaced out by $\Delta s = a/N$. Each wave source contributes $1/N$ of the original wave.

This will mirror the reasoning employed for the case of two-point sources.
Let $D$ be the distance between the exact center of our slit to the target.
The distance from each point to the target is then $x=D + s_{n}\sin\theta$ where $s_{n}$ is the position of the source relative to the center (if the source is farther to the right, $s_{n}$ shall be greater).
The wave due to each source is now $(A/N)\cos\big(k(D + s_{n}\sin\theta) - \omega t \big)$. Since we already noted $\Delta s = a/N$, we have $\Delta s / a = 1/N$. Summing up all the waves, we have
$$ \sum_{n} A\cos\big(k(D+s_{n}\sin\theta) - \omega t \big)\frac{\Delta s}{a}. $$
We are now going to use a trick. The trick is to take advantage of Euler's identity $e^{iu} = \cos(u)+i\sin(u)$. This will seem cheap, but we will simply replace all of the $\cos u$ terms by $e^{iu}$, and we will understand that we're dealing only with the real part when necessary.
The key to this is that the "real part" is additive, so $\text{Re}\; (e^{iu}+e^{iu'}) = \text{Re}\; (e^{iu}) + \text{Re}\; (e^{iu'})$ (this is not so simple if we are multiplying complex numbers though). This only works because we are adding things. Also, what we're doing respects integration, so $\int_{a}^{b} \text{Re}\;e^{iu}\;du = \text{Re}\;\int_{a}^{b}e^{iu}\;du$.
The magic to this trick is that it makes all of the trigonometry unbelievably easy.
We are going to go back to the sum above and write
$$\sum_{n} Ae^{i\left[ k(D+s_{n}\sin\theta)-\omega t\right]} \frac{\Delta s}{a}.$$
Hyugens principle deals with infinitely many wavefronts. This means we are meant to send $N\rightarrow \infty$. The above sum then transforms into
\begin{align*}
\int_{-a/2}^{a/2} \frac{A}{a}e^{iks \sin\theta} e^{ikD-i\omega t} \;ds &= \frac{Ae^{ikD-i\omega t}}{a}\left( \frac{e^{iks\sin\theta}}{ik\sin\theta} \right) \Big|_{s=-a/2}^{s=a/2} \\[1em]
&= \frac{Ae^{ikD-i\omega t}}{aik\sin\theta}\left( e^{ika\sin\theta/2}-e^{-ika\sin\theta/2} \right) \\[1em]
&= \frac{Ae^{ikD-i\omega t}}{aik\sin\theta}\left(2i\sin\left(\frac{ka\sin\theta}{2}\right)\right)\\[1em]
&= A\frac{\sin\left( \tfrac{ka\sin\theta}{2} \right)}{\left(\tfrac{ka\sin\theta}{2}\right) }e^{ikD-i\omega t} \\[1em]
&= \underbrace{A\frac{\sin\left( \tfrac{\pi a\sin\theta}{\lambda} \right)}{\left( \tfrac{\pi a\sin\theta}{\lambda} \right)}}_{\text{Amplitude}}e^{ikD-i\omega t}.
\end{align*}
Finally, the intensity is the square of the amplitude so
$$ I(\theta) = A^{2}\frac{\sin^{2}\left( \tfrac{\pi a\sin\theta}{\lambda} \right)}{\left(\tfrac{\pi a\sin\theta}{\lambda} \right)^{2}}$$
Double-Slit Pattern
Each slit has width $a$. The distance between the center of each slit is $d$.

Just as before, we split the wave in each opening into $N$ waves, respectively. For each opening, $\Delta s = a / N$. As we send $N\rightarrow \infty$ for both slits, we obtain the integrals
$$ \int_{-\frac{d}{2}-\frac{a}{2}}^{-\frac{d}{2}+\frac{a}{2}}\frac{A}{a}e^{iks\sin\theta}e^{ikD-i\omega t}\;ds + \int_{\frac{d}{2}-\frac{a}{2}}^{\frac{d}{2}+\frac{a}{2}}\frac{A}{a}e^{iks\sin\theta}e^{ikD-i\omega t}\;ds. $$
We need to evaluate the integrals, and do serious trig acrobatics. Evaluating and simplifying a few things gives
$$ \frac{Ae^{ikD-i\omega t}}{ak\sin\theta/2}\left[ \sin\left(k(\tfrac{d}{2}+\tfrac{a}{2})\sin\theta\right)-\sin\left(k(\tfrac{d}{2}-\tfrac{a}{2})\sin\theta\right) \right].$$
We can hatch open this expression by applying sine addition formulas and getting cancellation. This yields
$$ \frac{Ae^{ikD-i\omega t}}{ak\sin\theta/2}\cdot 2\cos\left(k\left(\tfrac{d}{2}\right)\sin\theta\right)\sin\left(k\left(\tfrac{a}{2}\right)\sin\theta\right). $$
As before, the wavenumber is $k = 2\pi/\lambda$, so now the expression equal to
$$ \frac{Ae^{ikD-i\omega t}}{(\tfrac{\pi a\sin\theta}{\lambda})} \cdot 2\cos\left(\tfrac{\pi d\sin\theta}{\lambda}\right)\sin\left(\tfrac{\pi a\sin\theta}{\lambda}\right) $$
and this is
$$ \underbrace{2A\frac{\sin\left(\tfrac{\pi a\sin\theta}{\lambda}\right)}{\left(\tfrac{\pi a\sin\theta}{\lambda}\right)}\cos\left(\tfrac{\pi d\sin\theta}{\lambda}\right)}_{\text{Amplitude}}e^{ikD-i\omega t}. $$
By squaring the amplitude, we obtain
$$ I(\theta) = 4A^{2}\frac{\sin^{2}\left(\tfrac{\pi a\sin\theta}{\lambda}\right)}{\left(\tfrac{\pi a\sin\theta}{\lambda}\right)^{2}}\cos^{2}\left(\tfrac{\pi d\sin\theta}{\lambda}\right). $$


Q:

Method now allowed while creating a website with Flask

I have just started to learn Flask, and I'm following a tutorial to create a login form, and I'm getting an error while trying to load the website, I'm doing the exact same thing like the guy in the tutorial, I'm running Ubuntu and coding in VS-Code, why is this happening ?
Tutorial and the status code of the request is 405.
Error: 405 - The method is not allowed for the requested URL.
Program:
from flask import *

app = Flask(__name__)

@app.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        return 'Hello Boss!'

@app.route('/login', methods=['POST'])
def do_admin_login():
    if request.form['password'] == 'password' and request.form['username'] == 'admin':
        session['logged_in'] = True
    else:
        flash('wrong password!')
    return home()

if __name__=='__main__':
    app.run(debug=True)

A:

It's probably because you are trying to access /login with a GET request. You have 2 options:

Allow GET requests for the /login endpoint (which is probably not the best way to solve this):

@app.route('/login', methods=['POST', 'GET'])

Reach your /login endpoint by clicking a Submit button or something like that. There should be a form with action="/login" method="POST" in your login.html and you should use it to reach your endpoint.


Q:

Finding single escaped characters

I would like to replace some escaping character in a given text. Here what I've tried.
_RE_SPECIAL_CHARS = re.compile(r"(?:[^@\\]|\\.)+@")

text = r"ok@\@.py"
search = re.search(_RE_SPECIAL_CHARS, text)

print(text)

if search:
    print(_RE_SPECIAL_CHARS.sub("<star>", text))

else:
    print('<< NOTHING FOUND ! >>')

This prints :
ok@\@.py
<star>\@.py

What I need to have instead is ok<star>\@.py.

A:

You can use lookbehind and just match the special character:
re.compile(r"(?<=[^@\\]|\\.)@")

See DEMO
Or you can capture the part before @ in group 1 and replace with \1<star>
re.compile(r"((?:[^@\\]|\\.)+)@")

and
print(_RE_SPECIAL_CHARS.sub("\1<star>", text))

See DEMO


Q:

Run Python program from shell and keep variables in scope

Python has a nice execfile function inside the interpreter where you can run a program, keep all the variables in scope, and then inspect them at your leisure. However, as far as I know you can't run execfile on a program that takes arguments from the command line; if you try to include the arguments, Python throws an IOError and complains that the file (with spaces and arguments) can't be found.
Is there any way to run a Python script that takes command line arguments, and keep all of the variables in scope after the program executes? Like an execfile that takes flags?
Thanks,
Kevin

A:

You could modify sys.argv directly. The file:
# foo.py
import sys

print sys.argv

The other file:
import sys
import shlex   # thanks Matt

old_argv = sys.argv
sys.argv = shlex.split('foo.py is a happy camper')

execfile('foo.py')

Output:
$ python foo.py is a happy camper
['foo.py', 'is', 'a', 'happy', 'camper']
$ python bar.py
['foo.py', 'is', 'a', 'happy', 'camper']

But I must say, quoting Ignacio Vazquez-Abrams:

This sounds all sorts of messed up.

I'm assuming you have your reasons though.


Q:

Creating xml for SQL Server stored procedure

I have a function to insert an item into the database. It takes a lot of values as input and the values are passed as XML.
Consider a sample item XML:
<ROOT>
    <Item
        ItemName="CarlsApplication"
        ItemTypeID="2">
        <TSDefaultDescription DefaultitemDescription="C:\t.text"/>
        <ItemSellers>
            <ComputerObject Alias="" DisplayName="" ServiceName="" UserAccount="" />
            <ComputerObject Alias="" DisplayName="" ServiceName="" UserAccount="" />
        </ItemSellers>
        <ItemOwners>
            <ItemOwner Alias="rafchen" FirstName="Rafael" LastName="Chenkov"/>
        </ItemOwners>
    </Item>
</ROOT>

This has to be passed to stored procedure.
Now, each of these individual values in this XML, I have to extract from somewhere else. I can get the individual values like Item name etc, but how do I organize them into an XML that can be passed?
How do I construct this XML from the values I have?
I guess I will have to make some sort of template with this format and then put variables in that template and fill the variables to prepare the template.
Any help is greatly appreciated.

A:

If I understand what you really want, You can use a query like this to generate  that XML:
select
    ItemName 'Item/@ItemName',            --> Node:`Item` Attribute: `ItemName`
    ItemTypeId 'Item/@ItemTypeId',
    cast((
        select
            Alias 'ComputerObject/@Alias',
            DisplayName 'ComputerObject/@DisplayName',
            ServiceName 'ComputerObject/@ServiceName',
            UserAccount 'ComputerObject/@UserAccount'
        from
            ItemSellers
        where
            ItemSellers.ItemId = Item.ItemId
        for xml path('')) as xml) 'Item/ItemSellers',    --> Node:`Item` Sub-Node:`ItemSellers`
    cast((
        select
            Alias 'ItemOwner/@Alias',
            FirstName 'ItemOwner/@FirstName',
            LastName 'ItemOwner/@LastName'
        from
            ItemOwners
        where
            ItemOwners.ItemId = Item.ItemId
        for xml path('')) as xml) 'Item/ItemOwners'
from
    Item
for xml path('ROOT');

SQL Fiddle Demo


Q:

Delphi Intraweb website crash on IIS

I've made an Intraweb ISAPI application. After building the dll, I've created an Web site on IIS and a pool for the application. On the Inetpub directory the permissions are set for the Internet Guest Account and for the IIS_WPG accounts.
When I'm trying to access the webpage from IE (http://ip.0.0.1/website/application.dll)  it returns me HTTP 500 or

errors. After searching on the Internet it says that is a problem of COM initialization. But in the datamodule of the application there is this code:
initialization
  CoInitialize(nil);

finalization
  CoUninitialize;

Can anybody give any advice?

A:

Do not use your own CoInitliaze calls, but instread use the ServerController and set the ComInitialization property to ciMultiThread for example.
From my IntraWeb Courseware manual: "The ComInitialization property of type TComInitialization (ciNone, ciNormal, ciMultiThread) is needed when the application requires the use of (D)COM. Since IntraWeb executes requests in different threads, each thread must make its own call to CoInitialize.
By default this property is set to ciNone, to indicate that no COM support is required. If you need COM support - for example if you want to connect to a DataSnap server - then you need to set ComInitialization to ciNormal or ciMultiThreaded.
Personally, I’ve found no reason not to set it to ciMultiThreaded when working with COM in one way or another inside an ISAPI DLL, although IIS 6 and higher may handle the required ComInitialization already for you, and you should set it to ciNone (but it looks like it’s ignored when set to some other value, so ciMultiThread won’t hurt either)."


Q:

Center of $SU(N)$ group in general Young-tableaux representation

Let us consider $ SU(2)$ irrep. with a $1\times k$ Young tableaux. Then the center group of such linear representation depends on the value of $k$ in the following sense. If $k\in$odd, then the center is nontrivial, namely $Z_2$, while the center is trivial when $k\in$even.
I wonder whether it can be generalized to $SU(N)$ irrep. with a general Young tableaux consisting of $b$ blocks. What I can guess or expect is the result should be that the center is $Z_{N/(b,N)}$ where $(b,N)$ is the greatest common divsor of $b$ and $N$. Is this statement correct? If so, how to prove it?

A:

The matrix representing the center generator of $SU(N)$ can be calculated within some (larger) irreducible representation since the matrix is proportional to the identity matrix. More specifically, any Young-tableaux representation with $b$ blocks is contained in the $b$-fold tensor product of fundamental representations, namely
\begin{eqnarray}
\text{irrep}(b)\in\otimes_1^bN.
\end{eqnarray}
Thus we can calculated the prefactor by the right-hand side:
\begin{eqnarray}
Z(b)&=&\left[\exp(i2\pi/N)\right]^b\nonumber\\
&=&\exp(i2\pi b/N),
\end{eqnarray}
which generates $Z_{N/(b,N)}$.


Q:

Does my dual core AMD Athlon 64 X2 4400+ support AMD-V?

I am trying to setup some VM's on Citrix XenServer but can't enable Hardware Virtualization support. In the XenServer install it prompted me to enable this, and upon creating a VM I got a "HVM required" error.
I have a dual core AMD Athlon 64 X2 4400+ processor - does this have support for AMD-V?
How can I enable this to run this software/VM's?
If it helps I am running:

a Mach Speed MSNV-939 motherboard
with 3 gigs of RAM.
Pheonix Technologies 6.0 BIOS

Edit: It looks like the chip can do it, but not with the 939 socket, I need the AM2 socket. Can anyone confirm this?
Thank you,

A:

AMD added hardware virtualization with the AM2 socket.  Your current chip is made for socket 939 and does not support hardware virtualization.

A:

Yes, it have. You should look at svm flag in your /proc/cpuinfo.
Here is the output from my system that uses this processor (two lines are for two cores):

$ grep svm /proc/cpuinfo
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch


Q:

Otsu thresholding method

Hi All and Happy New Year
I am writing my matlab code for otsu method but I have errors, If someone can look at my code and suggest me some corrections, I will be very grateful.
This is my code:

im1=imread('cameraman.tif');
%im1=rgb2gray(im1);
[n,m]=size(im1);
hst=imhist(im1);
mu=0;
N=0;
for i=1:255
    N=N+hst(i);
end
% The total mean level of the original image
for i=1:255
    mu(i)=mu(i)+((i.*hst(i))./N);
end

for T=1:254
    qb=0;
    muT=0;
    qo=0;
    for i=1:T
        qb=qb+(hst(i)./N); % probability of class occurence (background)
        m=m+((i.*hst(i))./N);% probability of class mean (background)
    end
    for i=T+1:255
        qo=qo+(hst(i)./N);% probability of class occurence (object)
    end
    sigma(T)=((mu-(qb*muT))^2)/(qb*qo)
end
[Y,T] = max(sigma)

[n,m]=size(im1);
for i=1:n
    for j=1:m
        if im1(i,j)>T
            im(i,j)=1;
        else
            im(i,j)=0;
        end
    end
end
figure(1);
subplot(1,3,1);
imshow(im1);
subplot(1,3,2);
imhist(im1);
subplot(1,3,3);
imshow(im);

thanks in advance

A:

Changed two lines that induced errors, please test:
mu=zeros(255,1); instead of mu=0;
sigma(T)=((mu(T)-(qb*muT))^2)/(qb*qo); instead of sigma(T)=((mu-(qb*muT))^2)/(qb*qo);


Q:

Why must certain functions on a group take commutators to the identity?

My question is about the identity pictured above. Can't figure out why it is true.

A:

The statement is poorly worded. What is $\kappa$ a function to? For instance, if $G$ is a non-commutative group and $\kappa$ is the identity function, the result is false. If $\kappa$ maps to a commutative group, however, then note that
$$\kappa(1)=\kappa(1\cdot 1)=\kappa(1)\cdot \kappa(1)$$
so $\kappa(1)$ is the identity in the codomain. Also,
$$\kappa(1)=\kappa(a\cdot a^{-1})=\kappa(a)\cdot \kappa(a^{-1})$$
so $\kappa(a^{-1})=\kappa(a)^{-1}$ in the codomain. So if the codomain is commutative,
$$\kappa(aba^{-1}b^{-1})=\kappa(a)\kappa(b)\kappa(a^{-1})\kappa(b^{-1})=\kappa(a)\kappa(b)\kappa(a)^{-1}\kappa(b)^{-1}=1.$$


Q:

Using c# to call google translator

I have to write some C# code which will enable me to translate a text file saved on my computer, using Google Translator. I want to write code to do this, but i am not sure where to start. I am new to this topic, but I think i have to download Google Translator API, but I'm not sure where to download this from. Please help me with this problem.

A:

Try this http://code.google.com/intl/en-US/apis/language/

A:

There is actually an open source project hosted on CodePlex named "Free language translator and file converter"
Here is the link: http://languagetranslator.codeplex.com/
This also use Google Translator service. As it is open source you can always see how it works. :-)