Q:

Future redshifting and effect on the 'pitch' of CMB radiation

After discovering this question exploring the sound of a blackbody, I started wondering about the sound of the Cosmic Microwave Background radiation from the Big Bang, specifically what the current pitch might be at its peak frequency and how that might evolve over time due to redshifting. Here's what I've been able to deduce so far:
$$
pitch_{CMB} = 160.4\,GHz \approx D_{33} = 157.7\,GHz
\\
pitch_{CMB}\,lowered\,by\,30\,octaves = {160.4\, GHz \over 2^{30}} = 149.38\, Hz \approx D_3 = 146.83\,Hz
$$
Building on this result:
How much time will need to elapse before the CMB redshift will cause this pitch to drop by an octave (or even by a semitone)?
How much variability would this pitch have depending on the dipole anisotropy of the CMB from our perspective as well as due to more generalized anisotropies in the CMB?
What pitch would the peak value of this blackbody have had at earlier points in the history of the Universe?

I've tried to apply some of the information in this question and elsewhere, but would greatly appreciate hearing from someone with more expertise in the subject area if this unorthodox comparison has piqued your interest like it has mine.

A:

The wavelength of the CMB increases linearly with the scale factor $a$, which is defined as 1 today, so the "sound" of the CMB has dropped an octave when the Universe has doubled in size (in all three directions), i.e. when $a = 2$, which will happen when it is roughly 25 billion years old (see e.g. Fig 1 of Davis & Lineweaver 2004).
The magnitude of the dipole of the CMB is $3.4\,\mathrm{mK}$ (Kogut et al. 1993), i.e. $\sim10^{-3}$ of the peak value. The primordial fluctuations are even lower, roughly a factor $10^{-5}$ of the peak value. The dipole is partly due to our motion round the Milky Way, and so will fluctuate somewhat with the period of a Galactic year, which is 225 million years.
The figure shows how the peak frequency evolved in the past. Its current value is 160.4 Ghz. To calculate how a human would perceive the sound at a given time, I suppose you'll have to multiply the spectrum with the frequency-dependent transmission function of the human ear, but that's physiology which I know nothing about.

The figure was produced by calculating the frequency at a given time as
$$
\nu(t) = \frac{160.4\,\mathrm{GHz}}{a},
$$
where $a$ runs from $1/1100$ to $4$,
and calculating the age by integrating the Friedmann equation, assuming a Planck 2015 cosmology.


Q:

Render date option with Values.get

Cannot bind the query parameter for rendering the date using Google Sheets API v4 Values.get, it is giving the error:

Invalid JSON payload received. Unknown name "DateTimeRenderOption":
  Cannot bind query parameter.

What is the correct JSON payload?
var response = Sheets.Spreadsheets.Values.get("someSpreadsheetId", "Sheet1!A7", {"DateTimeRenderOption" : "SERIAL_NUMBER"});

PS = Quite strange that there is no code samples in Google Sheets API documentation.

A:

Change DateTimeRenderOption to dateTimeRenderOption
The API Docs are a bit strange, especially when they mix capitalization use.


Q:

How to call phone in android fragment class?

I want to call to phone when I click OK button. Now I am getting error
Error message
12-23 17:19:39.547: E/AndroidRuntime(4095): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.CALL dat=91 90-37-300100 flg=0x10000000 }

Here is my code
public class ContactFragment extends Fragment {
private View parentView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //return inflater.inflate(R.layout.contact, container, false);
    parentView = inflater.inflate(R.layout.contact, container, false);
    setUpViews();
    return parentView;
}

 private void setUpViews() {
     parentView.findViewById(R.id.contact_phone).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            // Creating alert Dialog with two Buttons
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
            // Setting Dialog Title
            alertDialog.setTitle("Do you want to call?");
            // Setting Dialog Message
            alertDialog.setMessage("+91 XXXXXXXXXX");
            // Setting Icon to Dialog
            //alertDialog.setIcon(R.drawable.warning);
            // Setting Negative "NO" Button
            alertDialog.setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            // Write your code here to execute after dialog
                            dialog.cancel();
                        }
                    });
            // Setting Positive "Yes" Button
            alertDialog.setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int which) {
                            // Write your code here to execute after dialog
                            Intent callIntent = new Intent(Intent.ACTION_CALL);
                            callIntent.setData(Uri.parse("91 XXXXXXXXXX"));
                            callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(callIntent);

                        }
                    });

            // Showing Alert Message
            alertDialog.show();
        }
    });
 }  }

A:

just replace your code with:
 Intent callIntent = new Intent(Intent.ACTION_CALL);
 callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 callIntent.setData(Uri.parse("tel:" + "91XXXXXXXXXX"));
 getActivity().startActivity(callIntent);

and Add permission for call in manifest file

A:

Change this:
callIntent.setData(Uri.parse("91 XXXXXXXXXX"));

with this:
callIntent.setData(Uri.parse("tel:" + "91XXXXXXXXXX"));


Q:

How to create a runnable code snippet using React?

I'm following the React.js tutorial (https://reactjs.org/tutorial/tutorial.html) and would like to ask a question about it using Stackoverflow's Code Snippets. I've tried following the instructions on How do I create a React Stack Snippet with JSX support?, but I'm getting an
Error: {
  "message": "Uncaught ReferenceError: require is not defined",
  "filename": "",
  "lineno": 5,
  "colno": 14
}

My attempt at a React.js Code Snippet is shown below:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class Square extends React.Component {
  render() {
    return (
      <button className="square">
        {/* TODO */}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square />;
  }

  render() {
    const status = 'Next player: X';

    return (

{status}

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

class Game extends React.Component {
  render() {
    return (

          <Board />

{/* status */}

{/* TODO */}

    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('react')
);
body {
  font: 14px "Century Gothic", Futura, sans-serif;
  margin: 20px;
}

ol, ul {
  padding-left: 30px;
}

.board-row:after {
  clear: both;
  content: "";
  display: table;
}

.status {
  margin-bottom: 10px;
}

.square {
  background: #fff;
  border: 1px solid #999;
  float: left;
  font-size: 24px;
  font-weight: bold;
  line-height: 34px;
  height: 34px;
  margin-right: -1px;
  margin-top: -1px;
  padding: 0;
  text-align: center;
  width: 34px;
}

.square:focus {
  outline: none;
}

.kbd-navigation .square:focus {
  background: #ddd;
}

.game {
  display: flex;
  flex-direction: row;
}

.game-info {
  margin-left: 20px;
}

How can I modify this snippet so that it runs?

A:

Try removing the import statements, I think they happen automatically.


Q:

Can you launch an item farther by slamming into it or accelerating it along a length

I am trying to desgin a little penny balista toy (built with a 3d printer).
The short description is that there is a track with a mass ("hammer") that slides along it. There is a stack of pennies in a hopper at the front. The hammer goes from back to the front, slams into the penny at the end and launches it.
I had a debate with a friend about whether it would go farther if the penny started at the back and was accelerated along the full length of the track along with the hammer (a more difficult design).
My question is, all else being the same, which method would impart more energy to the penny? (my suspicion, based on those "newtons cradle" toys, is that it would be the same).

A:

If the mass of the penny is negligible comparing to the hammer, The speed of the hammer at the end of the track should be the same in both cases. With the collision in the first scenario, the speed of the penny should be twice of the hammer if the collision is complete elastic. But, for the second move-along scenario, the speed of the penny will be just the same as the hammer at the end of the track.


Q:

Cannot invoke 'saveInBackgroundWithBlock'

I've checked the syntax a gazillion times here, on GitHub, parse.com & elsewhere, without any luck. The problem is when I'm calling saveInBackgroundWithBlock for PFObject I get the the following error:

Cannot invoke 'saveInBackgroundWithBlock' with an argument list of type '((Bool, NSError) -> Void)'

I'm on Xcode 6.3 beta 2. All frameworks are loaded to the project (including Bolts & Parse, but not provided by parse.com ParseCrashReporting & ParseUI), <Parse/Parse.h> & even <Bolts/Bolts.h> are brought through the Bridge Header.
var score = PFObject(className: "score")
    score.setObject("Rob", forKey: "name")
    score.setObject(95, forKey: "scoreNumber")
    score.saveInBackgroundWithBlock {
        (success: Bool!, error: NSError) -> Void in
        if success == true {
            println("Score created with ID: \(score.objectId)")
        } else {
            println(error)
        }
    }

Any thoughts?

A:

The error parameter is supposed to be an implicitly unwrapped optional, but not the success one:
(success: Bool, error: NSError!) -> Void in
              ^               ^

However unless you need to specify the type for whatever reason, I suggest you to use the closure simply as:
(success, error) in

less prone to type declaration errors.

A:

In Swift 1.2 the declaration of .saveInBackgroundWithBlock should look like this:
Void saveInBackgroundWithBlock(block: PFBooleanResultBlock?(Bool, NSError?) -> Void)

So it should have been as follows:
score.saveInBackgroundWithBlock {
        (success: Bool, error: NSError?) -> Void in


Q:

How to set animator for left to right and inverse for Multiple Screens

I want to make an animation for ImageView which runs from left to right on screen and when it reached to 50% of screen, it comes back. My XML:
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"

    android:duration="1000"
    android:propertyName="x"
    android:repeatMode="reverse"
    android:repeatCount="1"
    android:valueFrom="0"
    android:valueTo="250" >
</objectAnimator>

My application ran well on my phone but when it ran on a smaller or bigger phone, it didn't run well.
I want to use ObjectAnimator and my application min SDK API is 13. Who can help me? Thanks in advance.

A:

For better structure, a dynamic approach is recommended which uses display screen width
First calculate the screen width to measure the half of the screen
    Display display = getWindowManager().getDefaultDisplay();
    Point point=new Point();
    display.getSize(point);
    final int width = point.x; // screen width
    final float halfW = width/2.0f; // half the width or to any value required,global to class
    ObjectAnimator lftToRgt,rgtToLft; // global to class

    // initialize the view in onCreate
    imageView = (ImageView) findViewById(R.id.imageButtontest);

    // set the click listener
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
               anim();// call to animate
         }
     });

Add the below function to your class and enjoy.
void anim(){
    // translationX to move object along x axis
    // next values are position value
    lftToRgt = ObjectAnimator.ofFloat( imageView,"translationX",0f,halfW )
            .setDuration(700); // to animate left to right
    rgtToLft = ObjectAnimator.ofFloat( imageView,"translationX",halfW,0f )
            .setDuration(700); // to animate right to left

    AnimatorSet s = new AnimatorSet();//required to set the sequence
    s.play( lftToRgt ).before( rgtToLft ); // manage sequence
    s.start(); // play the animation
}

Check out the complete Code Snippet


Q:

wordpress super loop style posts in rows N times

I am trying to adapt the Wordpress loop to style posts differently in rows that get
infinitely smaller until all posts are displayed
The concept here is to display posts in rows
first row 1 post
second row 2 posts
third row 3 posts
fourth row 4 posts
fifth row 5 posts
sixth row 6 posts
seventh row 7 posts
and onward until all posts have been retrieved
the below code is limited and does not do the above how would you adapt to make the below do the above?
the below code is functional and can be seen here: http://ccs.btcny.net/redhook/
<?php if (have_posts()) : ?>
<?php $count = 0; ?>
<?php while (have_posts()) : the_post(); ?>
<?php $count++; ?>
<?php if ($count == 1) : ?>

<?php the_content(); ?>

<?php elseif ($count == 2 || $count == 3) : ?>

<?php the_content(); ?>

<?php elseif ($count == 4 || $count == 5 || $count == 6) : ?>

<?php the_content(); ?>

<?php elseif ($count == 7 || $count == 8 || $count == 9 || $count == 10) : ?>

<?php the_content(); ?>

<?php elseif ($count == 11 || $count == 12 || $count == 13 || $count == 14 || $count == 15 ) : ?>

<?php the_content(); ?>

<?php elseif ($count >= 16 ) : ?>

<?php the_content(); ?>

<?php endif; ?>
<?php endwhile; ?>

A:

Here is my solution. Basically I am setting the row number by checking if the next element is inside the current row. To do that I need to see if next index is equal to the first index of the next row.
The tricky part is to find the index of the first item in the row. As this is not linear but geometrical order the items number in each row will be increasing. To calculate the first item of the next row I need to add the number of elements in the current row (in this case simply the current row) to the first index of the current row. When I get the first index of the next row and when the next item will be equal to that number I need to go to the next row and set the first index for the current row for that calculated index.
<?php //The first index of the first row is 1?>
<?php $row = 1;?>
<?php $curFirstIndex = 1;?>

<?php //start counting items ?>
<?php $count = 0;?>
<?php while (have_posts()) : the_post();?>

   <?php //create actual html code ?>
   <div class="style-<?php echo $row;?>"><?php the_content(); ?>

   <?php //check if the next item is equal to the first index of the next row ?>
   <?php if ($count+1 >= ($row + $curFirstIndex)) :
       <?php
         //the next item will be in the new row
         //in $curFirstIndex store the first number of the current row
         $curFirstIndex = $row + $curFirstIndex;

         //go to the next row
         $row++;
       ?>
   <?php endif; ?>
   <?php $count++;?>

<?php endwhile;?>

[EDIT]
The above solution works but it has one little flaw, namely it incorporates the logic into the template. Wordpress does not follow some strict layer separation but in my opinion it is always good to try to do that if it is possible. So I come up with two ways that can reduce the logic of this in the template file and move the logic outside. Since wordpress has functions.php in its theme we can use this file to create a function which will handle that logic. Here is the code
Template view file:
<?php //Initial values?>
<?php $row = 1;?>
<?php $count = 1;?>
<?php while (have_posts()) : the_post();?>

   <?php //create actual html code ?>
   <div class="style-<?php echo $row;?>"><?php the_content(); ?>

   <?php //check if the current item is the last in the row ?>
   <?php if ($count == getRowLastItemIndex($row)) {$row++;} ?>
   <?php $count++;?>

<?php endwhile;?>

in functions.php:
function getRowLastItemIndex($row) {
    $index = 0;
    for($i = 1; $i <= $row; $i++) {
        $index += $i;
    }
    return $index;
}

Or make it even more separate in the following way
The template file
<?php //Initial values?>
<?php $row = 1;?>
<?php $count = 1;?>
<?php while (have_posts()) : the_post();?>

   <?php //create actual html code ?>
   <div class="style-<?php echo $row;?>"><?php the_content(); ?>

   <?php $row = getRowNumber($row,$count);?>
   <?php $count++;?>

<?php endwhile;?>

And add another function to the functions.php
function getRowNumber($row,$count) {

    if ($count == getRowLastItemIndex($row))
        $row++;
    }
    return $row;
}


Q:

Enabling CORS globally in Spring Boot

I tried to enable CORS globally like this:
@Configuration
@ComponentScan("com.example")
@EnableWebMvc
public class OriginFilter extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE");
    }
}

I also tried this approach:
@Configuration
public class OriginFilter implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowCredentials(true);
    }
}

But none of these worked for me.
An annotation @CrossOrigin for an individual class works, but I wanted to enable CORS it globally.

A:

You could indeed define your own Filter as you mentioned in your answer. Spring already has such a CorsFilter already though, so you don't have to create one yourself. Just register it as a bean and it should work:
@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // Don't do this in production, use a proper list  of allowed origins
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
    config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

A:

The working global CORS configuration using WebMvcConfigurer for me without using filter.
@Configuration
public class GlobalCorsConfiguration {

    public GlobalCorsConfiguration() {
        super();
    }

    /**
     * Bean to define global CORS.
     *
     * @return
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
            }
        };
    }
}

Thanks.


Q:

In Ruby why does "or " have to be on the same line as the first condition?

@organization = Organization.where(:slug => subdomain).first
  or raise ActiveRecord::RecordNotFound

SyntaxError (/Users/bmckim/Workspace/telvue/ion/app/controllers/application_controller.rb:36: syntax error, unexpected keyword_or, expecting keyword_end
  or raise ActiveRecord::RecordNotFound
    ^):

Why does the does the "or condition" have to be on the same line as the first condition? Using parenthesis around the entire statement does not work either. The following works as expected and is arguably better anyway.
@organization = Organization.where(:slug => subdomain).first or
  raise ActiveRecord::RecordNotFound

A:

@organization = Organization.where(:slug => subdomain).first is a complete expression on its own, so the parser thinks that's what you meant. If Ruby had required expression terminators (semicolon, or whatever), putting the or on the second line would work.


Q:

AEM deployment from atom editor

I am using Atom editor to work on AEM project.
Is there any package available for atom to deploy changes from editor to Aem server, just like a plugin is provided with brackets editor.

A:

As of the time of this answer, the only extension I know of is vlt-atom.


Q:

Ionic pullToRefresh + lazyLoad + infinityScroll

When I use Ionic pullToRefresh +  lazyLoad (https://github.com/paveisistemas/ionic-image-lazy-load) + infinityScroll page begins to run very slowly. If I scroll the page is scrolled choppy on android, animation is jerky. How can I improve the page performance?
This is my template:
<ion-content>
<ion-refresher
  pulling-text="Pull to refresh..."
  on-refresh="doRefresh()">
</ion-refresher>

    <ion-slide-box>
      <ion-slide style="background-image: url({{item.image}});" ng-repeat="item in data.mainnews | orderBy:'-date'">

{{item.title}}

      </ion-slide>
    </ion-slide-box>

  <ion-list class="news-list">
    <ion-item collection-repeat="item in data.news | orderBy:'-date'" href="#news/{{item.id}}" class="item-thumbnail-left">

{{item.title}}

{{item.short_content}}

    </ion-item>
  </ion-list>
  <ion-infinite-scroll
    ng-if="!data.noMoreNews"
    on-infinite="loadMore()"
    distance="1%">
  </ion-infinite-scroll>

A:

Ok, I find the way by myself:
https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview
My app size grew up from 5mb to 25, but all animations and other things now looks much better)
Good luck)


Q:

Cannot acces a specific webpage from one computer, but I can access from different devices. All are connected to the same wifi network. Why?

I'm trying to access a git domain eg: "git.company.com" and I can access it from only one of the two computers. The domain is online and both computers have internet access. I need to be able to connect to the repo from both.
Thing I've tried on the non-working computer:

Connect to a different wifi network and access the address on
browser.
Use a different browser (first chrome then edge)
Ping the domain name(Request timeout, different ip shown from what working pc shows when it pings too)
Open in browser the ip address shown by working pc in the non-working computer (sends me to a different subdomain of the same domain eg:"start.company.com" instead of "git.company.com")
Change the DNS server in non-working pc (nothing changed)
Reset firewall setttings (still not being able to connect)
Access from a virtual machine hosted in non-working pc (surprisingly
    it works)

I can also access the website from different devices (phones etc), just that computer does not connect for some reason.
Both computers have the same OS (windows 10). I'm not the owner of the domain I'm trying to connect, thus I cannot make changes on it. No VPN service is running in either pc.
Any idea of what might be happening?

A:

I'm trying to access git.company.com and I can access it from only one of two computers.
Given all of the troubleshooting you have already performed you should also check your hosts file.
This has been confirmed by the OP in a comment as the cause of the problem:

you were right, for some reason the host file had a different ip address mapped to the domain name


Q:

@() inside an always block

Whether using @() inside an always block is a bad practice or in other words it is wrong? The example code is given below:
always@(negedge clk)begin

        @(valueI)begin
            deterministicEnable=0;
            iterate=iterate+1;
            deterministicEnable=1;
            j=0;
            $display("%h  %d   %d",valueI,$time,j);
        end

end

A:

It's wrong for synthesisable code. It's not wrong for your testbench.


Q:

How to provide value and get a Key back

So I have made 2 databases:

Db1 that contains: [{james,london}]
Db2 that contains: [{james,london},{fredrik,berlin},{fred,berlin}]

I have a match function that looks like this:
match(Element, Db) -> proplists:lookup_all(Element, Db).

When I do: match(berlin, Db2) I get: [ ]
What I am trying to get is a way to input the value and get back the keys in this way: [fredrik,fred]

A:

Regarding to documentation proplists:lookup_all works other way:
Returns the list of all entries associated with Key in List.

So, you can lookup only by keys:
(kilter@127.0.0.1)1> Db = [{james,london},{fredrik,berlin},{fred,berlin}].
[{james,london},{fredrik,berlin},{fred,berlin}]
(kilter@127.0.0.1)2> proplists:lookup_all(berlin, Db).
[]
(kilter@127.0.0.1)3> proplists:lookup_all(fredrik, Db).
[{fredrik,berlin}]

You can use lists:filter and lists:map instead:
(kilter@127.0.0.1)7> lists:filter(fun ({K, V}) -> V =:= berlin end, Db).
[{fredrik,berlin},{fred,berlin}]
(kilter@127.0.0.1)8> lists:map(fun ({K,V}) -> K end, lists:filter(fun ({K, V}) -> V =:= berlin end, Db)).
[fredrik,fred]

So, finally
match(Element, Db) -> lists:map(
    fun ({K,V}) -> K end,
    lists:filter(fun ({K, V}) -> V =:= Element end, Db)
).


Q:

Why is the speed of light the same for all colors in a vacuum but different depending on the color when light goes through a non-air medium?

I know that red light travels faster in non-air mediums than blue light because of its wavelength, but I'm not understanding why this doesn't happen in a vacuum? This is related to the topic of dispersion and the change of index refractions with wavelength. However, I'm not understanding why this happens. All I know based on educational materials that the index of refraction increases for colors with higher frequencies or lower wavelengths, ie. blue travels much more slowly.

A:

In fact your statement is not quite right: air does disperse light - its refractive index does depend on frequency, albeit very weakly. If you replace "air" with "vacuum" in your question, then the statement you are asking about is a correct one.
Dispersion arises from the interaction of light (an electromagnetic field) with the electrical charge present in the atoms of the dispersing materials.
In air, there are far, far fewer atoms per unit volume than do materials we think of as dispersive. A vacuum, by definition, has no electric charge at all for the light to interact with. Therefore, its refractive does not depend on frequency. This last statement is true because (1) light is mediated by a massless field and (2) special relativity requires that all such fields propagate at exactly $c$.


Q:

Use of q-ary lattices in developing cryptosystems

Why q-ary lattices are used to most cryptosystems rather than lattices.
In most of the papers q-ary lattices are used. Is there any advantage?
and
Given $$B=(v_1,v_2,v_3,.....v_n)$$ is the basis, lattice generated by B
               $$ L(B)=\{a_1v_1 + ........ + a_nv_n\ |\ a_1........,a_n ∈ Z\}$$
Fix q and given a matrix $$A ∈ Z_{q}^{n×m}$$
 m-dimensional lattice $Λ(A^T)$ is defined as
$$Λ(A^T)=\{y ∈ Z^m | y ≡ A^Ts\ (\text{mod } q) \text{ for some } s ∈ Z^n_q\}$$
How can we say that the above set of points forms the lattice and does it contains exactly $q^n$ points?

A:

The main advantage of using $q$-ary lattices is that it allows a cryptosystem designer to rely on the standard Short Integer Solution (SIS) and Learning With Errors (LWE) problems, which are known to be at least as hard as worst-case lattice problems.  So the SIS/LWE problems abstract away the connection to lattices, and give the designer a strong hardness guarantee "for free."  By contrast, if one were to work "directly" with lattices, one would have to explicitly describe a distribution over lattices and their secret "trapdoors," show (or assume) that lattices generated in this way are hard, etc. etc.
Another reason is that the SIS/LWE problems are very easy to work with, and admit a lot of versatility; it's less obvious how to obtain comparable properties when working with general lattices.  For example, one can perform arithmetic on parity-check/generator matrices $\mathbf{A}$, which can yield many interesting properties and applications (e.g., trapdoor manipulations, homomorphisms, etc.).  Most of these arithmetic operations do have interpretations in terms of general lattices, but they've been much easier to discover and exploit when working with $q$-ary lattices and their parity-check/generator matrices.
Regarding your question about $\Lambda(\mathbf{A}^t)$, this is a lattice and hence it has an infinite number of points.  However, modulo $q$, it has at most $q^n$ distinct points, at most one per value of $\mathbf{s}$.  It has exactly $q^n$ points if and only if no two distinct values of $\mathbf{s}$ yield the same value of $\mathbf{A}^t \mathbf{s} \pmod{q}$, which holds if and only if the right-nullspace (mod $q$) of $\mathbf{A}^t$ is simply $\{ \mathbf{0} \}$.


Q:

Cannot make a static reference to the non-static field for time

Hello I am trying to code the time for Android development
import android.text.format.Time;

This is my code in the MainActivity class within the protected void onCreate.
TextView abc;
abc= (TextView) findViewById(R.id.clockTextView);
abc.setText("Time is " + Time.hour + ":" + Time.minute);

Why do I keep getting the error Cannnot make a static reference to the non-static field Time.hour and how would I fix this? Thanks.

A:

The hour and minute fields of android.text.format.Time are instance fields. You need to create an instance of Time to access them:
TextView abc;
Time time = new Time(); // initialized to January 1, 1970 in default time zone
time.setToNow();
abc= (TextView) findViewById(R.id.clockTextView);
abc.setText("Time is " + time.hour + ":" + time.minute);


Q:

Someone plagiarized an answer I wrote. What's the right thing to do?

It's come to my attention that someone has copied something I wrote on music.SE, without attribution, and posted it to his own website.
I learned of this today when someone posted a new answer to this question, to which I had posted an answer of my own on January 22, 2011 (the same day the question was asked). In the new answer, the poster makes reference to an outside resource and observes that the outside resource contains (on page 4) the same material, verbatim, as my answer—as indeed it does, to my dismay.
Obviously, we're all volunteers here and our contributions aren't copyrighted. But in the interests of preserving my reputation and the reputation of my fellow contributors, I'm wondering whether these kinds of situations have come up before and how we can deal with them, if in fact we can deal with them at all.
Thanks, and here's hoping this isn't too common.

A:

Obviously, we're all volunteers here and our contributions aren't copyrighted.

Actually, they are. Per the bottom of the page,

site design / logo © 2014 stack exchange inc; user contributions licensed under cc by-sa 3.0 with attribution required

Given the existence of StackOverflow, I'm SURE StackExchange has a policy for dealing with things like this, but I don't know what it is off the top of my head. I'll check around and report back what I find.
Update:
This post on Meta.SO details the appropriate actions, so I've made the support submission as requested. That's all we can do, I think!


Q:

Selenium Webdriver: Specify filepath for Firefox exe

Can someone advise me on how to set the path for the firefox exe file in Selenium (C#).
I'm using the following code presently, however it is not working as hoped:
 FirefoxProfile profile = new FirefoxProfile();

 profile.SetPreference("webdriver.firefox.bin", "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

 IWebDriver driver = new FirefoxDriver(profile);

Any suggestions would be appreciated.

A:

You should use FirefoxBinary instead of FirefoxProfile as below
FirefoxBinary binary = new FirefoxBinary(new File("path/to/binary"));

FirefoxOptions options = new FirefoxOptions();
options.setBinary(binary);

IWebDriver driver = new FirefoxDriver(options);


Q:

Wrap html  tag around a twitter username in a tweet with php

I want to wrap  tags around the usernames in my tweets so that I can style them a differen't colour and link through to them. For example if this was my tweet:
@benpaton Lorem ipsum dolor sit amet, consectetur adipiscing elit.
I would like to do this:
@benpaton Lorem ipsum dolor sit amet, consectetur adipiscing elit.

This is the php I'm using at the moment to render my latest tweet at the moment currently with out links:
        <?php
        /** Script to pull in the latest tweet */
        $username='benpaton'; // set user name
        $format='json'; // set format
        $tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}")); // get tweets and decode them into a variable
        $latestTweet = $tweet[0]->text; // copy the text element from the latest tweet[0] to var $latestTweet
        $latestTweet = str_replace("\"","",$latestTweet);  // remove speech marks from tweets as this closes the alt tag
    ?>

Thanks for your help!

A:

Try this:
<?php

$username = 'benpaton';
$format = 'json';
$tweet = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
$latestTweet = htmlentities($tweet[0]->text, ENT_QUOTES);
$latestTweet = preg_replace('/@([a-z0-9_]+)/i', '@$1', $latestTweet);
echo $latestTweet;

?>

The preg_replace will handle the link writing, the htmlentities() will encode quotation marks so they should be able to be included in your output without breaking anything.


Q:

Which files do I have to back up to not lose my Security Key?

I am using the Security Application for Android via BlueStacks so I get the extra 100 Cartel Points per Month. This works fine, but I had to enter multiple codes into the app and the account to make it work, which is normal.
Now in case I reinstall my Operating System, which files would I need to back up to keep my security key on my account and not having to go through support to remove it?

A:

There are no files that you need to back up.
The serial number and activation code that you used to activate the application the first time will be same code you enter when you set it up again.


Q:

The Method of Ascent in Diophantine Equations

Can someone help me to prove there are infinitely many solutions to the Diophantine
equation: $$x^2 − 3y^2 = 1$$ using the method of ascent.
The Method of Ascent:
We can do this by showing how, given one solution $(u, v)$, we can compute another solution
$(w, z)$ that is larger is some suitable sense. Then my proof will involve finding a pair of
formulas, something like: $w = x + y$ and $z = x − y$.
However I tried these formulas and they don't work. So I asked my teacher and she said that there is a pair of second degree formulas which do work; one of them has a cross term and one of them involves the number 3.
I asked this question earlier, but it was put on hold because it looked as a duplicate. However, I am asking to prove this using another method, the method of ascent which is quite different and has not yet been proven in such a way. Can someone please help me on this. I have been wanting an answer for a few days now. I know that the other page has the answer, but I don't care about the answer, I want to know how to do it.

A:

The answers in the prior mentioned question imply that solutions may be composed by multiplying the quadratic integers $\,x_i+y_i\sqrt{3}\,$ associated with solutions $(x_i,y_i).\,$ In particular the powers of $\,2+\sqrt{3}\,$ generate an infinite increasing sequence of solutions (hence the ascent)
$$\begin{align}
(2+\sqrt3)^2 &=\ \ \ \color{#c00}7\ +\ \color{#c00}4\sqrt3\ \ \Rightarrow\ \ \ \ 7^2-3\cdot 4^2\ \ = 1\\
(2+\sqrt3)^3 &=\ \color{#0a0}{26} + \color{#0a0}{15}\sqrt3\ \ \Rightarrow\ \ 26^2-3\cdot 15^2 = 1\\
(2+\sqrt3)^4 &=\ \color{#b0f}{97} + \color{#b0f}{56}\sqrt3\ \ \Rightarrow\ \ 97^2-3\cdot 56^2 = 1\\
&\ \ \vdots
\end{align}$$
Or, using the composition law  $\,(x,y) = \color{#c00}{(7,4)}\,\mapsto \,(2x+3y,2y+x) = \color{#0a0}{(26,15)},\ $ Then, again applying the composition law $(x,y) = \color{#0a0}{(26,15)}\,\mapsto \,(2x+3y,2y+x) = \color{#b0f}{(97,56)},\ \ldots$


Q:

How to set multiple selected items on a WinForms ListBox

I have a System.Windows.Forms.ListBox in multiple selection mode and a set of items I'd like to be selected.  How do I do that?
[Test]
public void SetListBox()
{
    var listBox = new ListBox();
    var items = new List<string>{"one", "two", "three", "four"};
    listBox.SelectionMode = SelectionMode.MultiSimple;
    listBox.Items.AddRange(items.ToArray());
    var selectedItems = new List<string> {"two", "four"};
    // ???
    Assert.AreEqual(selectedItems, listBox.SelectedItems);
}

A:

Do this:
selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));

For:
    [Test]
    public void SetListBox()
    {
        var listBox = new ListBox();
        var items = new List<string>{"one", "two", "three", "four"};
        listBox.SelectionMode = SelectionMode.MultiSimple;
        listBox.Items.AddRange(items.ToArray());

        var selectedItems = new List<string> {"two", "four"};
        selectedItems.Select(sd => listBox.Items.IndexOf(sd)).Where(i => i >= 0).ToList().ForEach(i => listBox.SetSelected(i, true));

        Assert.AreEqual(selectedItems, listBox.SelectedItems);
    }


Q:

Preferred BCrypt.Net implementation

There are a few different ports of BCrypt.net out there and it's very hard to tell which is the "best".
Has anyone taken the time to review them and come to any conclusion as to which project to patronize?  I'm most interested in which has the most active community of developers.  Of course feature set, effectiveness, simplicity and documentation are nice too :)
Here is the list of BCrypt.Net implementations I was able to track down:
Derek Slager
As far as I can tell, this is the first port and has not been updated in a while.  Version 0.1
Google Code
The user posted Derek Slager's copy to google code and made some improvements. Version 0.3
NuGet
Visual studio's only NuGet version, it's a compiled copy with no source so I can't know anything about it for sure.  It does appear to support a new function only available in the Version 0.3 Google Code edition.  It lists no support site and I can't tell if it's open source and has no attribution of any kind (A bit sketchy). Version 1.0, 213 downloads.
Code Plex
This seems to be a completely independent port with no relation to Derek Slager's port. It appears to have some semi-regular updates. Version R5, 140 downloads.
Is this list complete?  Is there any reason to pick one over the other?

A:

Initially reviewed these in Feb 2013, updated with info from the comments by Justin and Coulton, and to reflect my current use.
The more recent of these appear to be secure, or at least "without known bugs". (There are other weaknesses in bcrypt but they are algorithmic rather than code-related. I assume that if you are using bcrypt you already know about those.)
The libraries listed in the question are all based on the jBCrypt code (except maybe CryptSharp, no idea there), which received bug fixes in Feb 2010 to fix the "weak entropy" security advisory. (http://www.mindrot.org/files/jBCrypt/internat.adv)
Breakdown:

The Codeplex port of BCrypt was started in late 2010 (checking in Dec), and was updated to more recent sources in 2013. It is almost certainly safe, and available on NuGet (https://www.nuget.org/packages/BCrypt-Official/).
CryptSharp (http://www.zer7.com/software/cryptsharp) is a living, supported project that looks very well done, but I have not evaluated it in depth. Definitely worth checking out. Also available on NuGet (http://www.nuget.org/packages/CryptSharpOfficial/).
The Google Code version changelog indicates that it incorporates the Feb 2010 `jBCrypt` bug fixes. But that's kind of ancient and dead.
Derek Slager's 2007 port probably does **not** have these fixes, I think you should avoid it.

Rough timeline, based on from the revision control change logs:

Derek Slager made a port of jBCrypt in 2007
This was imported into Google Code and updated somewhat in Oct 2010.
The Codeplex code by Ryan D. Emerle started with a later version of jBCrypt as its source (late 2010). This import is dated *after* the last change to Google Code's version. This was updated to the latest source in Nov 2013.
CryptSharp was initially released in Nov 2010, with regular releases through the present (Dec 2014). Written from scratch??

I am currently using the Codeplex version, as it appears to be maintained, and comes up early in the google search results.
On the 2011 crypt_blowfish bug: (j)BCrypt.net is a stand-alone implementation of the algorithm, and does not depend on the unix crypt_blowfish library. So it should not be affected at all. It's overdue for a rewrite to support $2y$ format, though.


Q:

Accessing Facebook cookies in browser

When I type in javascript:alert(document.cookie) in the URL bar, I only get to see some cookies which facebook has set for my account.
I think this is because the other cookies are http only.

First question: Is this true? Are some Facebook cookies http only, and is that why I am not able to access them through javascript. When I view the cookies, in Web Developer Firefox Add on, I can see so many more cookies. For example: the "xs" cookie is not visible through javascript and only seen through the web developer add on.
Second question: How do I access all cookies through javascript, if The Add-On can do it(access all the cookie), why can't javascript do it?
Thirdly, if I can't use javascript to access all cookies, how I should I access them?

A:

Different browsers will treat the httponly flag in different ways.  It should be very clear that the httponly flag does not prevent XSS attacks.  Using javascript you can still "ride" on the victim's session.   The MySpace Sammy worm is a good example of this.  So you shouldn't need the cookie value,  even if you are an attacker.
Firefox add-ons are not subject to the same security limitations as javascript running from the address bar or loaded on the page.  For instance the same origin policy doesn't really apply,  because it doesn't have an origin.  It is useful and secure enough for add-ons to bypass these rules.


Q:

IOS ScrollView Issues

Hey I'm following this tutorial and currently on the first step but am experiencing some weird behavior.  The tutorial is on creating scroll views for images and ends with showing how to create a paged horizontal ScrollView with a page controller.  I followed the first section and things seemed to be working fine.  However when I ran the code it did not perform properly, after about an hour of debugging I downloaded the final project, ran it on my phone to check if it was working correctly (it was) then copied the code into the required files in my project.  My project still wouldn't run.  So I figured it must be the way in which my story board was configured on the project setup.  I then oped the working example cleared their storyboard and created the views and segues my self, in the exact same way and order I had done in my project. Bam! it still worked, when I deleted all views in my story board and recreated them in the exact same fashion, still nothing.  Could someone look into this tutorial and tell me if I'm going crazy or they experience similar results.  I have narrowed it down to two possibilities, the project provided at the end of the tutorial was created differently and the delegates or outlets were hooked up in a way that only works with the project, or the project was created with an earlier version of the iPhone development kit that works with the current version of XCode but not when I create a new project.  Then again I am fairly new to this so I will throw up the code I'm using and hope for the best.
ViewController.h file:
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIScrollViewDelegate>

@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;

@end

ViewController.m file:
#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) UIImageView *imageView;

- (void)centerScrollViewContents;
- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer;
- (void)scrollViewTwoFingerTapped:(UITapGestureRecognizer*)recognizer;
@end

@implementation ViewController

@synthesize scrollView = _scrollView;

@synthesize imageView = _imageView;

- (void)centerScrollViewContents {
    CGSize boundsSize = self.scrollView.bounds.size;
    CGRect contentsFrame = self.imageView.frame;

    if (contentsFrame.size.width < boundsSize.width) {
        contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
    } else {
        contentsFrame.origin.x = 0.0f;
    }

    if (contentsFrame.size.height < boundsSize.height) {
        contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
    } else {
        contentsFrame.origin.y = 0.0f;
    }

    self.imageView.frame = contentsFrame;
}

- (void)scrollViewDoubleTapped:(UITapGestureRecognizer*)recognizer {
    // Get the location within the image view where we tapped
    CGPoint pointInView = [recognizer locationInView:self.imageView];

    // Get a zoom scale that's zoomed in slightly, capped at the maximum zoom scale specified by the scroll view
    CGFloat newZoomScale = self.scrollView.zoomScale * 1.5f;
    newZoomScale = MIN(newZoomScale, self.scrollView.maximumZoomScale);

    // Figure out the rect we want to zoom to, then zoom to it
    CGSize scrollViewSize = self.scrollView.bounds.size;

    CGFloat w = scrollViewSize.width / newZoomScale;
    CGFloat h = scrollViewSize.height / newZoomScale;
    CGFloat x = pointInView.x - (w / 2.0f);
    CGFloat y = pointInView.y - (h / 2.0f);

    CGRect rectToZoomTo = CGRectMake(x, y, w, h);

    [self.scrollView zoomToRect:rectToZoomTo animated:YES];
}

- (void)scrollViewTwoFingerTapped:(UITapGestureRecognizer*)recognizer {
    // Zoom out slightly, capping at the minimum zoom scale specified by the scroll view
    CGFloat newZoomScale = self.scrollView.zoomScale / 1.5f;
    newZoomScale = MAX(newZoomScale, self.scrollView.minimumZoomScale);
    [self.scrollView setZoomScale:newZoomScale animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Set a nice title
    self.title = @"Image";

    // Set up the image we want to scroll & zoom and add it to the scroll view
    UIImage *image = [UIImage imageNamed:@"photo1.png"];
    self.imageView = [[UIImageView alloc] initWithImage:image];
    self.imageView.frame = (CGRect){.origin=CGPointMake(0.0f, 0.0f), .size=image.size};
    [self.scrollView addSubview:self.imageView];

    // Tell the scroll view the size of the contents
    self.scrollView.contentSize = image.size;

    UITapGestureRecognizer *doubleTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewDoubleTapped:)];
    doubleTapRecognizer.numberOfTapsRequired = 2;
    doubleTapRecognizer.numberOfTouchesRequired = 1;
    [self.scrollView addGestureRecognizer:doubleTapRecognizer];

    UITapGestureRecognizer *twoFingerTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewTwoFingerTapped:)];
    twoFingerTapRecognizer.numberOfTapsRequired = 1;
    twoFingerTapRecognizer.numberOfTouchesRequired = 2;
    [self.scrollView addGestureRecognizer:twoFingerTapRecognizer];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    // Set up the minimum & maximum zoom scales
    CGRect scrollViewFrame = self.scrollView.frame;
    CGFloat scaleWidth = scrollViewFrame.size.width / self.scrollView.contentSize.width;
    CGFloat scaleHeight = scrollViewFrame.size.height / self.scrollView.contentSize.height;
    CGFloat minScale = MIN(scaleWidth, scaleHeight);

    self.scrollView.minimumZoomScale = minScale;
    self.scrollView.maximumZoomScale = 1.0f;
    self.scrollView.zoomScale = minScale;

    [self centerScrollViewContents];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    // Return the view that we want to zoom
    return self.imageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    // The scroll view has zoomed, so we need to re-center the contents
    [self centerScrollViewContents];
}

@end

The above code doesn't work as it does in the tutorials project.  The following UIScrollView delegate method viewForZoomingInScrollView produces this error:

2013-05-14 10:01:18.585 TestScrollView[3809:907] Made it
May 14 10:01:18 Scott-Laroses-iPhone TestScrollView[3809] : CGAffineTransformInvert: singular matrix.
May 14 10:01:18 Scott-Laroses-iPhone TestScrollView[3809] : CGAffineTransformInvert: singular matrix.

which makes me think the delate isn't properly set up despite me doing it exactly the same as in the tutorial and programmatically when that didn't work. Any ideas?

A:

I figured it out! The issues was that the auto layout constraints were messing up the off screen views.  So I disabled auto layout and it worked fine.


Q:

add timestamp attribute to ingredients of iphonecoredatarecipes sample code

I'm really sorry for such a simple question but I tried several ways and cannot find a solution.
I just want to add a timestamp attribute in the ingredients entity. Whenever I change the recipes.xcdatamodel I get this:

error NSError     domain: @"NSCocoaErrorDomain" - code: 134100    0x000000010c162890

I already tried model versioning and:
options:@{NSMigratePersistentStoresAutomaticallyOption:@YES,
NSInferMappingModelAutomaticallyOption:@YES}

The code is original as provided by Apple!

A:

Select your .xcdatamodeld file in the Project Navigator.
Under the menu option "Editor", select "Add Model Version".
A new copy of your data model file will be created.
In this new copy, let's call it version 2 for simplicity, you need to add an attribute to store the time.
In version 2 of the .xcdatamodeld file (and I note here - be careful to select the new file and not the old file) add an attribute, call it "timeStamp", set the Type to "Date", and save.
Now when you run the sample project, the migration options you have included in your "Core Data Stack" will migrate the stored information from the old .xcdatamodeld file to version 2 of that file.
Also refer to...
Core Data; Cocoa error 134100
UPDATE
I loaded iPhoneCoreDataRecipes sample code, and then followed these steps...

added a new version of the data model (as described above),
in the new version of the data model, being VERY CAREFUL to make certain that it is the new model I am modifying, added an attribute "timeStamp" to the Entity "Ingredients",
to the Ingredient.m file, added @dynamic timeStamp,
to the Ingredient.h file, added @property (nonatomic, retain) NSDate *timeStamp;,
to the RecipesAppDelegate.m file, added the following lines of code...
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setValue:[NSNumber numberWithBool:YES]
           forKey:NSMigratePersistentStoresAutomaticallyOption];
[options setValue:[NSNumber numberWithBool:YES]
           forKey:NSInferMappingModelAutomaticallyOption];

changed this line of code to include my above noted options,
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:options error:&error]) {

and executed a Build & Run.
Mine crashed with a different message...
Can't merge models with two different entities named 'Ingredient'

Which triggered a memory that I was required to change this line of code,
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];

to these two lines of code...
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:classPersistentStore withExtension:@"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:self.modelURL];

This loads without error for me.
Please follow these steps - should also work for you.


Q:

Make 00:19:59 by jsvascript

I try to show 20 minute by this format : (00:20:00) using setInterval and when it is done the format should be like this (00:00:00) ; but i can't.

A:

Using a single interval makes everything easier :

var seconds, minutes, interval;
function onloadFunc(){
    seconds=parseInt(document.getElementById("second").innerText);
    minutes=parseInt(document.getElementById("minute").innerText);
    interval = setInterval(tick, 1000);
}
function tick() {
  if (seconds > 0) {
   seconds--;
  } else { // seconds == 0
      if (minutes > 0) {
       minutes--;
        seconds=59;
        document.getElementById("minute").innerText = minutes;
      } else { // minutes == 0 && seconds == 0 , let's stop the timer
       clearInterval(interval);
      }
  }
  document.getElementById("second").innerText = seconds < 10 ? "0"+ seconds : seconds; // seconds are always updated, minutes only when it matters
}

20:00


Q:

PCRE format to QRegexp format

I have a PCRE format regular expression:
  <a\s*href=\"([^<]*)\"([^<]*)\((.*?)\)\">
but i can not use it in QT, how can i
convert it to QRegexp format to make it work in QT.
Thanks

A:

Did you try reading the documentation?  Specifically the section called "Notes for Perl Users"?  It appears that this should be pretty straightforward:
QRegExp regex( "<a\\s*href=\\"([^<]*)\\"([^<]*)\\((.*?)\\)\\">",
    Qt::CaseSensitive, QRegExp:: RegExp2 );

Note that all I did there was double-up the backslashes, since C will "eat" one when interpreting the code.  However, I have my doubts that you wanted the quotes double-backslashed, so perhaps this is more like what you wanted:
QRegExp regex( "<a\\s*href=\"([^<]*)\"([^<]*)\\((.*?)\\)\">",
    Qt::CaseSensitive, QRegExp:: RegExp2 );

I also don't know why you are trying to match 3 quote marks in the expression, but that is beyond the scope of what you asked.


Q:

Inequality with differential equations solutions

I would love some help working through this problem:
Let $f_1,f_2,f : [0,\infty) \to \mathbb{R}$ be three bounded, continuous and absolutely Riemann integrable functions so that $|f_1(x)|, |f_2(x)| \leq |f(x)|$, for every $x \in [0,\infty)$.  Given the system of differential equations:$$\alpha'(x)=f_1(x)\beta(x)\quad and\quad \beta'(x)=f_2(x)\alpha(x)\quad with\quad \alpha(0)=a, \beta(0) = b
$$ show that solutions $\alpha$ and $\beta$ can be expressed as infinite series:$$\alpha(x)=a+b\int_0^xf_1(y)dy+a\int_0^xf_1(y)\int_0^yf_2(z)dzdy+b\int_0^xf_1(y)\int_0^yf_2(z)\int_0^zf_1(w)dwdzdy..$$ $$\beta(x)=b+a\int_0^xf_2(y)dy+b\int_0^xf_2(y)\int_0^yf_1(z)dzdy+a\int_0^xf_2(y)\int_0^yf_1(z)\int_0^zf_2(w)dwdzdy..$$
and show that as a consequence of this, both $\alpha$ and $\beta$ are bounded functions and moreover they satisfy the estimate$$|\alpha(x)|,|\beta(x)| \leq max(|a|,|b|)exp(||f||_1)$$
for every $x \in [0,\infty)$, where $||f||_1 = \int_0^\infty|f(y)|dy$.
I have already shown that $\alpha$ and $\beta$ are solutions but I am not sure how to go about showing that they are bounded and that the inequality holds.  The textbook that I am using suggests that this can be shown by using Picard iteration but I'm not sure how to do this.
I'd appreciate any help with this.
Thanks!

A:

The system is
$$
\begin{bmatrix}
α'(x)\\β'(x)
\end{bmatrix}
=
\begin{bmatrix}
0&f_1(x)\\f_2(x)&0
\end{bmatrix}
·
\begin{bmatrix}
α(x)\\β(x)
\end{bmatrix}
$$
or as Picard integral equation
$$
\begin{bmatrix}
α(x)\\β(x)
\end{bmatrix}
=
\begin{bmatrix}
a\\b
\end{bmatrix}
+
\int_0^x
\begin{bmatrix}
0&f_1(y)\\f_2(y)&0
\end{bmatrix}
·
\begin{bmatrix}
α(y)\\β(y)
\end{bmatrix}
dy
$$
which gives the time- or path-ordered exponential solution formula.

As a linear ODE with continuous coefficient matrix the solution exists everywhere and is unique per Picard-Lindelöf, a Lipschitz constant over the interval $[-N,N]$ is the maximum of $|f(x)|$ over that interval.
Applying the max norm to the integral equation gives
$$
\max(|α(x)|,|β(x)|)\le \max(|a|,|b|)+\int_0^x\max(|f_1(y)|,|f_2(y)|)·\max(|α(y)|,|β(y)|)\,dy
$$
Name $e(x)=\max(|α(x)|,|β(x)|)$, $e(0)=\max(|a|,|b|)$, then, following one of the proofs of the Gronwall lemma,
$$
\frac{d}{dx}\ln\left(e(0)+\int_0^x|f(y)|·e(y)\,dy\right)=\frac{|f(x)|·e(x)}{e(0)+\int_0^x|f(y)|·e(y)\,dy}\le |f(x)|
$$
so that after integration
$$
e(x)\le e(0)e^{\int_0^x|f(y)|\,dy}\implies \max(|α(x)|,|β(x)|)\le\max(|a|,|b|)e^{\int_0^\infty|f(y)|\,dy}
$$


Q:

How can I run Android applications on my PC with the Android emulator?

Is it possible to run Android applications on PC (with emulator)? I have Android SDK on my PC and I want to run Angry Bird on it. Can any body help to me?

A:

I guess what you mean is to install applications from the market on the Android emulator. Well, normally this is not possible and also not suggested. The emulator is mainly intended for development purposes. The problem is also that you'd need to get the Android market in order to be able to download apps (Angry Birds in your case), but the emulator doesn't have the market app installed.
However, there is an interesting article by how-to-geek which describes how to install the Android market application on the emulator:
http://www.howtogeek.com/howto/21862/how-to-enable-the-android-market-in-the-google-android-emulator/
I didn't try it myself, but you may give it a try. Personally I think the overall user experience of playing Angry Birds on the emulator won't be great :)

A:

Note that although Android OS itself is free (gratis and libre), Google's Android Market is not a free application (proprietary and device manufacturers have to pay license fee to Google if they want to legally include Market on their device); so installing Market on an emulator have a shady legality  (though I doubt Google would knock on your front door, you don't have enough money to be worth suing, and they wouldn't want to ruin their image of being open-friendly).
However, Angry Bird itself is free (gratis, not libre) application and there is no restriction on installing free application on an Android platform (e.g. emulator). As long as you can get the APK through other means than the Android Market (e.g. developer's site, etc), installing it on the emulator is fine. As it happens, GetJar is one of Rovio's official distribution channel, and you can Angry Bird from there, note that you need to allow third party installation (Settings > Applications > tick "Unknown Sources", this is already ticked by default on the emulator).

A:

If you're not particular about using SDK, then I would suggest using BlueStacks. It allows you to run android apps on your PC without the need for the Android SDK. It's a standalone installer and hence easy to setup and use.


Q:

wp_query not working with post_type

I have two machines: local and deployment.
On my local machine I have the code:
$all_prods = array(
    'posts_per_page' => -1,
    'post_type'      => 'product',
);

dump(query_posts($all_prods));

The result I'm getting is my three products, that I've created earlier.
But the same code on deployment machine returns an empty array despite of the website has many products in it.
I thought that somehow deployment machine has the other prefix for it's post type, than my local one, but when I type on deployment machine:
$prod = wc_get_product(440);
dump($prod);

I get WC_Simple_Product object with field "post_type" equal to "product". How can I debug it?

A:

First I would state that in most cases the query_posts should be avoided!

This function will completely override the main query and isn’t
  intended for use by plugins or themes. Its overly-simplistic approach
  to modifying the main query can be problematic and should be avoided
  wherever possible.

I would suggest transfer your query with WP_Query and try something like this:
$all_prods = array(
    'posts_per_page' => -1,
    'post_type'      => 'product',
);
$query = new WP_Query($all_prods);

while ($query->have_posts()) {
    $query->the_post();
    $post_id = get_the_ID();
    echo $post_id;
}

For the Debug part, I would use the get_post($post_id); to verify that we talk about the same post_type.

A:

I've found the solution.
$query = new WP_Query();
$all_prods = array(
    'posts_per_page' => -1,
    'post_type'      => 'product',
);
$query = new WP_Query($all_prods);
echo $query->request . '<BR>';

The output was different on 2 machines, there was a problem with a multilanguage plugin that automatically added a second table and made inner join with it.


Q:

extract character preceding first dot in a string

I would like to extract the character preceding the first dot in a column of strings.  I can do so with the code below.  Although, the code seems overly complex and I had to resort to a for-loop.  Is there an easier way?  I particularly am interested in a regex solution.
Note that finding the last number in each string will not work with my real data, although that approach would work with this example.
Thank you for any advice.
my.data <- read.table(text = '
     my.string  state
     .........    A
     1........    B
     112......    C
     11111....    D
     1111113..    E
     111111111    F
     111111111    G
', header = TRUE, stringsAsFactors = FALSE)

desired.result <- c(NA,1,2,1,3,NA,NA)

Identify the position of the first dot:
my.data$first.dot <- apply(my.data, 1, function(x) {
                                as.numeric(gregexpr("\\.", x['my.string'])[[1]])[1]
                          })

Split strings:
split.strings <- t(apply(my.data, 1, function(x) { (strsplit(x['my.string'], '')[[1]]) } ))

my.data$revised.first.dot <- ifelse(my.data$first.dot < 2, NA, my.data$first.dot-1)

Extract the character preceding the first dot:
for(i in 1:nrow(my.data)) {
     my.data$character.before.dot[i] <- split.strings[i,my.data$revised.first.dot[i]]
}

my.data

#   my.string state first.dot revised.first.dot character.before.dot
# 1 .........     A         1                NA                 <NA>
# 2 1........     B         2                 1                    1
# 3 112......     C         4                 3                    2
# 4 11111....     D         6                 5                    1
# 5 1111113..     E         8                 7                    3
# 6 111111111     F        -1                NA                 <NA>
# 7 111111111     G        -1                NA                 <NA>

Here is a related post:
find location of character in string

A:

Use the below regex and don't forget to enable perl=TRUE parameter.
^[^.]*?\K[^.](?=\.)

In R, the regex would be like,
^[^.]*?\\K[^.](?=\\.)

DEMO
> library(stringr)
> as.numeric(str_extract(my.data$my.string, perl("^[^.]*?\\K[^.](?=\\.)")))
[1] NA  1  2  1  3 NA NA

Pattern Explanation:

^ Asserts that we are at the start.
[^.]*? Non-greedy match of any character upto the first dot.
\K Discards previously matched characters.
[^.] Character we are going to match must not be a dot.
(?=\.) And this character must be followed by a dot. So it matches the character which exists just before to the first dot.

A:

The simplest regex would be ^([^.])+(?=\.):
^      # Start of string
(      # Start of group 1
 [^.]  # Match any character except .
)+     # Repeat as many times as needed, overwriting the previous match
(?=\.) # Assert the next character is a .

Test it live on regex101.com.
The contents of group 1 will be your desired character. I'm not much of an R guy, but according to RegexBuddy, the following should work:
matches <- regexpr("^([^.])+(?=\\.)", my.data, perl=TRUE);
result <- attr(matches, "capture.start")[,1]
attr(result, "match.length") <- attr(matches, "capture.length")[,1]
regmatches(my.data, result)

A:

In the example, it was all digits and .
library(stringr)
as.numeric(str_extract(my.data$my.string, perl('\\d(?=\\.)')))
#[1] NA  1  2  1  3 NA NA

Or using stringi
library(stringi)
as.numeric(stri_extract(my.data$my.string, regex='\\d(?=\\.)'))
#[1] NA  1  2  1  3 NA NA

If it is for a general case:
as.numeric(str_extract(my.data$my.string, perl('[^.](?=\\.)')))


Q:

Go learning resources

I am looking for resources to begin with the go language.
I know go is a very new language but don't you know tutorials, documentation or books to learn it ?
What was your way to begin with ?

A:

If you have some programming experience already the Go Tour is really great. You can't ask for a much better way to get introduced. It's fun and you'll learn a lot in a hurry.
After going through that (and playing a bit with some toy programs as I went along) I read the Effective Go page and just started hacking away on the program I wanted make (I was porting an existing program I knew well to Go, so I was just learning Go not my problem domain at the same time).
The package documentation is really good, too. Don't forget that you can click on function names to get to the Go code that implements that function. Reading working code is a great way to learn and get ideas.
As I was getting started I also sometimes read a chapter or two from Miek Giebens Learning Go book. It's available for free in PDF and the book layout is nice, don't get scared off by the black and green website. :-)
I've heard good things about "An Introduction to Programming in Go" (also available for free).


Q:

App Preview submission, video has audio that is not two-channel

When submitting my App Preview, iTunes Connect says:
"This video has audio that is not two-channel, no-surround stereo. Please refer to Apple's documentation for appropriate formats."
Well heres the catch, when I created my App Preview in iMovie, I deleted the audio track!
After giving up for a while, I came back and tried again, then I was receiving an error saying "file could not be loaded".
Each time I go to submit for review, my App Preview disappears.
Any ideas on how I can get my App Preview successfully submitted?

A:

For most apps that do not have the primary purpose of handling audio, I find background music or audio voice over to be a distraction in an app preview. If you want to add silence to preview, you can easily do it with ffmpeg:
ffmpeg -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 -i preview.mp4 -shortest -c:v copy -c:a aac previewWithSilence.mp4

A:

If you're using iMovie:

Drag in any audio clip. It doesn't matter what it is.
Shorten the length to less than your project's total length.
Set the sound level to 0% by dragging the horizontal bar over the clip down.
Share as App Preview.

A:

Unfortunately "no audio channel", isn't an option in the official docs.
I'd follow the official Apple guide over here and add some "background music":

Create a Soundtrack

Choose File > Import Media, then select the audio file in the window that appears.
Drag music to the Background Music area at the bottom of the timeline.
Drag sound effects directly underneath any clip in the timeline.

Apple is quite picky when it comes to the allowed file formats and configurations, but once you fixed that, it should work!


Q:

SwiftUI HStack slider does not appear

I want to make a horizontal stack of images.
Unfortunately I am not able to slide to see full images.

struct ContentView: View {
    var body: some View {
        NavigationView {
                List {

                    ScrollView {
                        VStack{
                            Text("Images").font(.title)
                        HStack {

                            Image("hike")
                            Image("hike")
                            Image("hike")
                            Image("hike")

                        }
                        }

                }.frame(height: 200)
            }
        }
    }
}

A:

There are a couple of issues with your view.
You have got a List around your content - it causes problems because a list scrolls vertically, while I assume you want your images to scroll horizontally.
Next thing is that you probably don't want your title to scroll with the images - it needs to go outside the scroll view.
Last but not least, you need to make the images resizable and set their aspect ratio so that they are scaled down to fit the allocated space.
Try this:
struct ContentView: View {

    var body: some View {
        NavigationView {
            VStack{
                Text("Images").font(.title)
                ScrollView(.horizontal) {
                    HStack {
                        Image("hike")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                        Image("hike")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                        Image("hike")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                        Image("hike")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                    } .frame(height: 200)
                    Spacer()
                }
            }
        }
    }
}


Q:

Check if ModPagespeed is allowed and enabled for the current domain via php

i'm trying to figure out how to check if ModPagespeed is enabled and allowed on the current domain via PHP. I've written the following code, but I'm not fully satisfied of this solution. It works, but it's a crock.
Excerpt from .htaccess (serving different domains) with Pagespeed filters:
<IfModule pagespeed_module>
  ModPagespeed On
  ModPagespeedRewriteLevel PassThrough
  ...
  ModPagespeedEnableFilters combine_css
  ...
</IfModule>

Excerpt from pagespeedtest.html:
...
<head>
...
  <!-- If combine_css filter is active, the following code should be combined -->
  <style type="text/css" media="all">@import url("/style1.css");</style>
  <style type="text/css" media="all">@import url("/style2.css");</style>
  <style type="text/css" media="all">@import url("/style3.css");</style>
...
</head>

Check if Pagespeed is enabled or allowed by this PHP code:
        $psturl = 'http://'. $_SERVER['HTTP_HOST'] .'/pagespeedtest.html';
        $pagespeed_is_active = TRUE;
        $pstheaders = get_headers($psturl, 1);
        if ($pstheaders['Content-Length'] == 960) {
          $pagespeed_is_active = FALSE;
        }

I get the Content-Length header using the PHP 5 function get_headers($url). I know the original file is 960 bytes long so I suppose that if no optimization is performed the Content-Length should be the same when served to the client.
Are there any alternatives to this approach? I don't like the supplemental HTTP request I perform on pagespeedtest.html and that solution strongly relies on PageSpeed configuration: if combine_css filter will be disabled, I will got $pagespeed_is_active == FALSE even when ModPagespeed is On and allowed.
An alternative solution must be validated through different domains, since I can disallow some domains in this very same .htaccess. Thank you.

A:

Instead of checking the Content-Length, you can instead look for the X-Mod-Pagespeed header, which will give you the answer you're looking for as long as "ModPageSpeed on" directive is there for the domain.
Other then that, I don't think there is any way for you to check if PageSpeed is enabled from within the request. The whole point of PageSpeed is that it runs as an output filter: you generate your page, PageSpeed picks it up and does the optimization and rewriting.


Q:

Regulated function has countably many discontinuities

How do you prove that a regulated, real valued function defined on a closed domain has countably many discontinuities using the fact that it is the uniform limit of a sequence of step functions?

A:

Let $f$ be a regulated function and $(f_n)$ be a sequence of step functions converging uniformly to $f$. For any $n$, let $D_n$ be the set of discontinuities of $f_n$, and $D= \bigcup\limits_n D_n$.
Show that if $x \notin D$, then $f$ is continuous at $x$. Therefore, the set of discontinuities of $f$ is included in $D$, which is countable (since each $D_n$ is finite).


Q:

merge pandas csv in different directories

I have csv files with same names in different directories and i want to merge them as a single csv.

dir1
abcd__diff.csv
efgh__diff.csv

dir2
abcd_diffhere.csv
efgh_diffhere.csv

operation
dir1/abcd_diff.csv join dir2/abcd_diffhere.csv
dir1/efgh_diff.csv join dir2/efgh_diffhere.csv

I want to merge them using a common field. I can use pandas join operator but what is the most efficient way to search and map the filenames across directories.
I split the filenames using character __  giving the list of files with same names in each directory. I can do two for loops and iterate but that would not be efficient as I have around 200 files.

A:

Situate files like this
files1 = []
files2 = []
dir1path = './dir1/'
dir2path = './dir2/'
dir1 = os.listdir(dir1path)
dir2 = os.listdir(dir2path)

for f in dir1:
    fmatch = f.split('.csv')[0] + 'here.csv'
    if fmatch in dir2:
        files1.append(f)
        files2.append(fmatch)

files1 = [os.path.join(dir1path, f) for f in files1]
files2 = [os.path.join(dir2path, f) for f in files2]

fpairs = zip(files1, files2)

Then create list of dataframes
# edit this lambda function accroding to your needs
# it will have to be specific to your csv formatting
rf = lambda f: pd.read_csv(f)

dfs = [rf(fp[0]).merge(rf(fp[1]), on='Key') for fp in fpairs]


Q:

Row_Number() Over Partition - Easier Way

I have the below query:
INSERT into @TEST (col1,staffnumber,rn)
SELECT starttime as col1,staffnumber,ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY STARTTIME DESC) AS rn
  FROM @TempTable2 t2
UNION
SELECT eventdate as col1, staffnumber,ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY EVENTDATE DESC) AS rn
  FROM @TempTable1 t1

But, obviously, this gives me the following values:
COL1                | staffnumber    | rn
10/02/2014 10:29:24         1          1
10/02/2014 09:08:19         1          3
10/02/2014 10:00:23         1          2
10/02/2014 10:00:29         1          1

Whereas, I need it to show:
COL1                | staffnumber    | rn
10/02/2014 10:29:24         1          1
10/02/2014 09:08:19         1          4
10/02/2014 10:00:23         1          3
10/02/2014 10:00:29         1          2

I can do this by doing the following:
INSERT into @TEST1 (col1,staffnumber,rn)
SELECT convert(time,col1),staffnumber,ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY convert(time,COL1) DESC) AS rn
FROM @TEST

But there must be an easier more efficient way of doing it. Any ideas?

A:

Compute the ROW_NUMBER after the UNION.
SELECT *, ROW_NUMBER() OVER (PARTITION BY StaffNumber ORDER BY STARTTIME DESC) AS rn
FROM (
 SELECT * FROM T1
 UNION ALL
 SELECT * FROM T2
) x

I suspect you need UNION ALL.


Q:

How to know earning LN routing fees

I am using c-lightning version:v0.6-182-g1851ebb. Is there a way to know how much I have earned routing fees? I found that lnd has lncli feereport command that shows earned fees. Does c-lightning have same functionality? If not, is there a way to know earned routing fees?
I created a query for calculating earned routing fees. However, this doesn't work because HTLCs info is removed when a channel forwarded HTLCs closed.
sqlite3 $HOME/.lightning/lightningd.sqlite3 "select sum(a.msatoshi - b.msatoshi) from channel_htlcs a inner join channel_htlcs b on a.id = b.origin_htlc"

Any ideas?

A:

lightning-cli listforwards
List all forwarded payments and their information


Q:

How to build the smallest regular n-sided polygon that covers an (n-1)-sided polygon?

I want to build a figure that contains seven regular polygons, from a triangle up to a nonagon, where each n-sided polygon covers, with the minimal area possible, the n-1 sided one. An added restriction is that each of them should have a horizontal base.
With this figure constructed, I'd like to study its properties (mainly the side and area of each polygon, ideally expressed as a function of the triangle's side).
I wonder if there's a way to build this, either with a rule and a compass (unlikely, I presume) or by using a dedicated software program for this effect.
Thanks.

A:

To expland upon Willie Wong's question, is this what you mean by
"each of them should have a horizontal base."?

Or, just to use $n=3,4,5,6$, this?


Q:

Testing functions using Protractor

I am trying to test a angular code using protractor. I am able to test the elements which are visible on html using element(by.id or by.css). I need a way to test the functions which are in the javascript file. Suppose when we click on a button on html that calls a function in javascript file which is what I want to test.

A:

I think you have a scoping problem here. With protractor, you test your application from one end to another from an end-user perspective through the user interface opened in your browser by automating user actions - clicking, entering keys, hovering etc.
To test a function, you should look into AngularJS unit-testing.


Q:

using the Router component inside of a function react

I have a react component called react-dropzone. It allows you to drag and drop files, which then invokes a function (usually you "do" something with the file, but you can have it invoke any function you please).
When a file is dropped, I want to route the client to 'page-redirect'. The following code has no errors, but does nothing.
import React, { Component } from "react";
import Dropzone from "react-dropzone";
import { BrowserRouter as Router, Route } from "react-router-dom";
import PageRedirect from "./pages/page-redirect.jsx";

class DragAndDrop extends Component {

//function invoked by the Dropzone Component
handleOnDrop = files => {
      console.log(files);
      return (
        <Router>
          <Route exact path="/pages/page-redirect" component={PageRedirect} />
        </Router>
      );
    };

  render() {
    return (
      <div>
        <Dropzone onDrop={this.handleOnDrop}> Drop File Here </Dropzone>
      </div>
    );
  }
}
export default DragAndDrop;

Any insight is greatly appreciated!

A:

Your code returns nothing because you are essentially defining a new route not going to it.
If you want to just open the redirect page in another tab, you can just insert the following after you log the files.
window.open("/pages/pages-redirect")
or you could do:
window.location.href("/pages/pages-redirect") //please ignore this and see below for the update

This assumes that you have already defined your route in your root js file, i.e. your index.js or App.js or even your routes directory (if your using one). If you haven't define your route first wherever you have your other routes defined.
Hope that helps...
Update
The href will not work the way I have it above in React. You should change that to:
window.location.href = "/pages/pages-redirect"

If you received a "window.location.href is not a function" error that is why. Sorry about that. Hope that helps anyone that got an error.
Also, the .open will open in a new tab and the href will redirect to that path.


Q:

Modelling a Notification System

I am trying to model a notification system where an event occurs during a time period (start date and end date). If the time period has been exceeded, the user is required to either update the time period or set a flag that the event has been i) cancelled, ii) completed, or iii) closed. If today is one day past the event's scheduled completion date, the manager is emailed. If  two days, the manager and their supervisor is emailed. If > two days, the manager, their supervisor, and the company owner is emailed. Every day after that it emails the three of them that the event is delinquent. Events can be scheduled any time in the future so the process needs to simply track when the event is Pending, Active, Delinquent (past the end date), Cancelled, Closed, or Complete.
I have started building workflow as a WorkFlow Service application hosted in Windows Server AppFabric because it appears that that is the best way to persist this long-running workflow. I have also started using the WF State Machine Activity Pack CTP 1 as it seemed the best way to model these different event states.
I am uncertain how to model this process as well as get the process to persist and continue running in the background to monitor the event's state and behave as outlined above. I think I have all the states modeled correctly in the state machine. I am still trying to figure out the transitions from one state to another Any guidance is appreciated.

A:

State Machines run in a burst of execution.  There is really nothing to "run" while the workflow is persisted.  I suspect what you mean is how will the workflow "wake up" when the timeout is exceeded.
The answer is that the Delay activity will create a durable timer.  The AppFabric Workflow Management service periodically asks the persistence layer if there are runnable workflow instances - that is instances which have crashed or where a durable timer has expired.
Eventually the timer will be expired and the Workflow will be loaded and the Delay activity bookmark will be resumed.


Q:

Incomplete answers

I was just posting an answer to a question and realized that I didn't actually have a full solution to the problem. I'll often start typing/formatting my answer as I work on it, and occasionally, I'll get very close to the solution and something doesn't quite work. The answer still provides insight to a solution method, and is at least a starting point for the asker. My intention in actually posting this as an answer is that feedback from others usually "completes" the solution.
Since what I've posted doesn't technically answer the question when it is first posted, I assume this isn't allowed. Do others see this as my essentially using a "placeholder" to later complete the solution?
I know that this discussion exists, but I think this is slightly different. I'm not immediately intending to finish up the question. Rather, I'm hoping to open a dialogue that will result in an answer that is educational to both the OP, and myself.
The question/answer that sparked my worry about this: WeatherData for the 15th day of each month

A:

I often see answers prefixed with statements such as "This is a partial answer" or "This is not a complete answer", etc. I have posted such answers myself. I haven't seen any comments complaining about such answers, so I conclude they are permitted.
I think it best that anyone giving a partial answer note that it is partial and explain why it is still worth posting.


Q:

How to connect to ftp server trough VPN

There is a remote FTP server, which has my VPN Gateway IP address in white list. I have a name of FTP server, username and password. How can I connect to it? (I need my connection to go through VPN)

A:

# route add <name-or-ip-of-ftp-server> gw <gateway-ip>
$ ftp <name-or-ip-of-ftp-server> [<port>]

then type your username and password


Q:

Will reading the same book in two languages confuse my daughter?

My husband and I are raising our two-year-old daughter in a bilingual home. I speak English, my husband speaks Afrikaans, and we speak each of our respective languages to our daughter. (We basically do OPOL, and we speak mostly English to eachother)
My husband and I both read to her at different times, but we both choose from the same pool of books. We have differing opinions on how to handle opposite language books. My husband will only read Afrikaans books to her, but I will read both languages and if she chooses a book in the opposite language, I'll just translate it on the fly (They're big picture books, so there aren't too many words in any case).
I'm concerned that reading the exact same book in two languages may be confusing to her. Sometimes when I'm reading a book, my daughter will use the Afrikaans word because she knows that one best (which is fine!) and I just say "yes, that's a {english word}".
I'm just concerned that I'm un-doing her learning of the other language when I read to her the exact same book in another language. Is this something I should be worried about? Should I just stick with one language per book?

A:

Don’t worry.
I have 3 kids who are now fluent in 3 languages...
When the youngest was learning to count we were giving her the numbers in either of two languages - because she was also at nursery where she only got one language.
One day she was asked to count so she did in French. Then her brother asked her to count in English - she did and then it seemed to dawn on her that she had two ways of naming numbers ...
So, upside is kids will assimilate two languages with ease.
Downside is that because they are processing double the vocabulary then progress can be slow at times. Just don’t worry and it will get sorted.
She was slower than her peers at reading for a while, but then caught up and was reading in two languages in front of the class... At school her peers are now learning English and she is coasting...
Have just remembered a book that we had in both languages - but the format and pictures were the same: Big Hare and Little Hare discussing "How much I love you" (answer all the way to the moon ... and back). She loved it in either language -  good bedtime read.
One issue I did face was my kids pointing out my limited vocabulary in my second language as theirs increased, as well as my pronunciation.. :) That is a good indicator of their progression though.

A:

I wouldn't worry about this at all. It's entirely expected with young bilinguals that they will switch language mid sentence and use whatever noun (say) is most readily accessible to them, not necessarily from the same language as the previous word.
While we only have one language spoken in our household, I frequently don't read books exactly as written. And I don't read them consistently each time I read them.
Reading to your kids is a great way to get them interested in reading, which will serve them tremendously well. It will also expand their vocabulary beyond the smaller set of words you'd otherwise use. It is also a great way to connect and get some quality time together. It can also be a powerful tool to open their eyes to worlds beyond their own limited experience and raise their curiosity for just about anything. Books are fantastic at all these things, and these are some of the reasons you should read to your children every day. Your reading does all of this regardless of language. So that they would have a knowledge of what the exact words in a particular book is, is not one of those great reasons, and that's all that you're missing.
On the contrary, I could just as well imagine that these books could serve as a Rosetta stone for your children, a handy key to how one story translates to another language.


Q:

Using execCommand for formatting in Angular

I have this code:
  @HostListener('document:click', ['$event'])
  onClick(targetElement) {
    console.log(targetElement);
    var command = 'bold';
    if (command == 'h1' || command == 'h2' || command == 'p') {
      document.execCommand('formatBlock', false, command);
    } else document.execCommand(targetElement.data('command'), false, null);
  });

But this isn't working.  The first if statement will be skipped as I just want to ensure that the execCommand is working.
It does print out the console.log so it gets into that function.
The HTML element that will be modified is:

A WYSIWYG Editor.

Change this text, or format

How do I change the text that was selected, for bold?
How do I use document.execCommand in Typescript?
I have a feeling in this section, document.execCommand(targetElement that I should have passed in the div with id editor to the directive so it know what that particular button should act upon.

A:

I suppose you have data on your document object.
Anyways, you are passing in the $event into the HostListener. This will make the targetElement a MouseEvent instead of a HTMLElement. You can use type hinting to foresee such errors.
On the other hand you are using a data function, from which I've never heard of. Not onMouseEvent nor on a HTMLElement or Document. My guess is that you are trying to access the dataset? If that's the case, this might work for you:
@HostListener('document:click', ['$event.target'])
  onClick(targetElement: Document) {
    let command: string = 'bold';
    if (command === 'h1' || command === 'h2' || command === 'p') {
       document.execCommand('formatBlock', false, command);
    } else {
       document.execCommand(targetElement.dataset['command'], false, null);
    }
}


Q:

2D Vectors/Dynamic Arrays

I'm trying to work with 2D arrays in order to keep track of some objects that are laid out in a grid fashion. I would like each element of the of the 2d array to contain an Object*. Object being a class I have defined. However working with these things isn't exactly easy.
This is the my method for filling the 2D array with Object pointers:
int xDim;
//how far to go in the x direction
//x's Dimension that is

Object *** test; //the highest level pointer used

test = new  Object ** [xDim];
//add horizontal array of Object **

for(int fillPos=0; fillPos < xDim; fillPos++){
    //point each Object ** to  a new Object * array
    //add column arrays
    test[fillPos] = new Object*[zDim];
}

My intention is then to use this array's Object pointers to point to the child class of Object, say childObj. My intent is to use them in this way.
for (int xPos=0; xPos < xDim; xPos++){
    for(int zPos=0; zPos < zDim; zPos++){
        //pointing each Object * in the 2D array to
        //a new childObj
        test[xPos] [zPos] = new childObj;
    }
}

I realize this could potentially be a real hassle in terms of memory. I'm asking if this is a nice way to handle such a situation. Could perhaps something like
vector< <vector<Object*> > work better? Would vectors manage the deletion nicely so as to avoid memory leaks? Or perhaps I would simply have to loop through the vector and call delete on each Object* before getting rid of the vectors themselves?
So, should I use arrays as I have or vectors? What could be some problems associated with each method?

A:

Using Object *** requires that you go through and delete each Object Pointer, each Array of Object Pointers, and then the finally delete the outermost Array of Object**, in that order. In my opinion this leaves a lot of room for carelessness and mistakes.
for (int xPos=0; xPos < xDim; xPos++) {
    for (int zPos=0; zPos < zDim; zPos++) {
        delete test[xPos][yPos];  // delete the object ptr
    }
    delete[] test[xPos];          // delete each array of object ptr
}
delete[] test;                    // delete the array of array of object ptrs

I would much rather prefer the vector approach, because the vectors are locally scoped. Dynamic allocation can be rather expensive and should be avoided if possible.
So for the vector approach, you would only need to delete the Object ptrs. (A good rule of thumb is that every call to new requires a corresponding call to delete).

vector<vector<Object*>> matrix;

... // some code here

for each (vector<Object*> vec in matrix)
    for each (Object* oPtr in vec)
        delete oPtr;

If you knew the size of your 2-D array at compile-time, you could achieve the same effect of avoiding memory management for the 2-D array, and simply manage the Object pointers.
Object * matrix[xDim][yDim];  // xDim and yDim are compile-time constants

But I still like vectors because they have the added benefit of being able to resize themselves dynamically unlike arrays, so you won't have to worry about knowing the size upfront.


Q:

Populate a Ruby array like [a,a,a,a].. [f,f,f,f]

I need to populate an array, but not by directly counting and splitting the numbers.
I need to do generate the following:
[[a,a,a,a], [a,a,a,b], [a,a,a,c]..... [f,f,f,d], [f,f,f,e], [f,f,f,f]]

And I am struggling to understand it. I realize it should use recursive logic,  but I don`t know how to actually build the method.

A:

I would do something like this:
('a'..'f').to_a.repeated_permutation(4).to_a
#=> returns 1296 different combination from ['a','a','a','a'] to ['f','f','f','f']


Q:

function does not create image yet image it passed

Ok so the problem seems to be in the function not creating the image, or in the script it self which does not pass the image to the function
Here is the upload script (note: this is injected into AJAX)
    $path = "cache/";

    $valid_formats = array("jpg", "png", "gif", "jpeg");
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
        {
        $name = $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];

        if(strlen($name))
                {
                ist($txt, $ext) = explode(".", $name);
                if(in_array($ext,$valid_formats))
                {
                if($size<(2024*2024))
                    {
                    $new_file = "header.".$ext;
                    $tmp = $_FILES['photoimg']['tmp_name'];
                    if(move_uploaded_file($tmp, $path.$new_file))
                    {

            echo "";

               createHeader($new_file);
                    }

                    else
                    echo "failed";
                    }

                    else
                    echo "Image file size max 1 MB";
                    }
                    else
                echo "Invalid file format..";
                }

            else
                echo "Please select image..!";

            exit;
        }

now here is the function
function createHeader($new_file) {

$path = "uploads/";
$image = "cache/";
$width = 800;

    if(preg_match('/[.](jpg)|(jpeg)$/', $new_file)) {

        $im = imagecreatefromjpeg($image . $new_file);

    } else if (preg_match('/[.](gif)$/', $new_file)) {

        $im = imagecreatefromgif($image . $new_file);
        imagecolortransparent($im, black);

    } else if (preg_match('/[.](png)$/', $new_file)) {

        $im = imagecreatefrompng($image . $new_file);
    }

    imagealphablending($im, false);
    imagesavealpha($im, true);

    $ox = imagesx($im);
    $oy = imagesy($im);

    $nx = $width;
    $ny = floor($oy * ($width / $ox) );

    imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
    imagealphablending($im, true);
    if(!file_exists($path)) {
      if(!mkdir($path)) {
           die("There was a problem. Please try again!");
      }
       }

    imagejpeg($nm, $path . $new_file, 100);

    imagedestroy($im);
    imagedestroy($nm);

}

In logic what the code must do is if a user using my cms is loged-in he or she can change the header on the page by clicking an icon which will make a jQuery call to edit.php passing needed query string. From there own user can upload a new image which will be renamed header.jpg and over-write the original image
The header.jpg has to be uploaded into uploads/ directory and a copy of original image cache/ should be unlinked ones the function can create a copy and put it into uploads/ directory.
What is happening is that the first script is uploading the file and is putting it into cache/ directory but the function does not seem to work and does nothing for uploads/ directory.
Any idea what I may be doing wrong or not doing that is causing this annoying problem?

A:

$path = "cache/";
$valid_formats = array("jpg", "png", "gif", "jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
    {
    $name = $_FILES['photoimg']['name'];
    $size = $_FILES['photoimg']['size'];

    if(strlen($name))
            {
            list($txt, $ext) = explode(".", $name);
            if(in_array($ext,$valid_formats))
            {
            if($size<(2024*2024))
                {
                $new_file = "header.".$ext;
                $tmp = $_FILES['photoimg']['tmp_name'];
                if(move_uploaded_file($tmp, $path.$new_file))
                {

           // This needs to happen before the echo of the image tag
           createHeader($new_file);

        echo "";
                }

                else
                echo "failed";
                }

                else
                echo "Image file size max 1 MB";
                }
                else
            echo "Invalid file format..";
            }

        else
            echo "Please select image..!";

        exit;
    }


Q:

How to replace the blank

Given the code:
import clr
clr.AddReference('System')

from System.Text.RegularExpressions import *

def ReplaceBlank(st):
    return Regex.Replace(
        st,r'[^a-z\s](\s+)[^a-z\s]',
        lambda s:s.Value.Replace(' ', ''),RegexOptions.IgnoreCase)

I expect the input ABC EDF to return ABCDEF but it doesn't work, what did I do wrong?

A:

[^a-z\s] with ignore-case flag set matches anything other than letters and whitespace characters. ^ at the beginning of a character class (the thing between []) negates the character class.
To replace blanks, you can simply replace \s+ with empty strings or, if you need to match only letters replace
(?<=[a-z])\s+(?=[a-z])

with an empty sting. The second regex will match string of whitespaces between two letters; to account for beginning/end of strings, use
(?<=(^|[a-z]))\s+(?=($|[a-z]))

or
\b\s+\b

The second one will match spaces between two word boundaries, which include symbol chars like period, comma, hyphen etc.