Q:

After upgrading to google play services 8.4.0 my app crashes on startup

I've been previously using google play services 8.3.0 without any issue.  I'm looking to upgrade to google play services 8.4.0.  I'm using the following play libraries:
compile 'com.google.android.gms:play-services-analytics:8.4.0'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'

When I start the app it crashes, with the following log.
12-27 03:01:33.915 20567-20567/com.ryanc.android.stage.debug E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ryanc.android.stage.debug, PID: 20567
    java.lang.NoSuchMethodError: No static method zzz(Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzx; or its super classes (declaration of 'com.google.android.gms.common.internal.zzx' appears in /data/app/com.ryanc.android.stage.debug-1/base.apk:classes17.dex)
    at com.google.android.gms.measurement.internal.zzw.zzaT(Unknown Source)
    at com.google.android.gms.measurement.AppMeasurementContentProvider.onCreate(Unknown Source)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1696)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1671)
    at android.app.ActivityThread.installProvider(ActivityThread.java:4999)
    at android.app.ActivityThread.installContentProviders(ActivityThread.java:4594)
    at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4534)
    at android.app.ActivityThread.access$1500(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Edit: Not sure it'll help, but at @gerardnimo request here is the full build.gradle file.  Also worth noting I have tried a clean build and deleting and reinstalling play services sdks from my computer.
apply plugin: 'com.android.application'
apply plugin: 'checkstyle'

def SDK = "$MIN_SDK_VERSION"
def V_CODE = "$VERSION_CODE"

buildscript {
    repositories {
        mavenCentral()
    }
}

repositories {
    mavenCentral()
    jcenter()
    maven { url 'https://zendesk.artifactoryonline.com/zendesk/repo' }
    maven { url "http://kahuna.github.io/kahuna-android/sdk" }
}

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.2'
    defaultConfig {
        applicationId "com.ryanc.android"
        minSdkVersion SDK.toInteger()
        targetSdkVersion 23
        versionCode V_CODE.toInteger()
        versionName "$APP_VERSION.$BUILD_NUMBER"
        multiDexEnabled true
    }
    signingConfigs {
        debug {
            storeFile file("$DEBUG_KEYSTORE_PATH")
            storePassword "$DEBUG_KEYSTORE_PASSWORD"
            keyAlias "$DEBUG_KEY_ALIAS"
            keyPassword "$DEBUG_KEY_PASSWORD"
        }
        release {
            storeFile file("$KEYSTORE_PATH")
            storePassword "$KEYSTORE_PASSWORD"
            keyAlias "$KEY_ALIAS"
            keyPassword "$KEY_PASSWORD"
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    productFlavors {
        prod {
            applicationId "com.ryanc.android"
        }

        stage {
            applicationId "com.ryanc.android.stage"
        }

        qa {
            applicationId "com.ryanc.android.qa"
        }

        dev {
            applicationId "com.ryanc.android.dev"
        }
    }
    dexOptions {
        javaMaxHeapSize "4g"
    }
}

repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    def supportVersion = "23.1.1"

    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile project(':api')
    compile "com.android.support:support-v4:$supportVersion"
    compile "com.android.support:appcompat-v7:$supportVersion"
    compile "com.android.support:design:$supportVersion"
    compile 'com.facebook.android:facebook-android-sdk:4.8.1'
    compile 'uk.co.chrisjenx:calligraphy:2.0.1'
    compile "com.android.support:cardview-v7:$supportVersion"
    compile "com.android.support:recyclerview-v7:$supportVersion"
    compile "com.android.support:support-v13:$supportVersion"
    compile 'com.google.android.gms:play-services-analytics:8.4.0'
    compile 'com.google.android.gms:play-services-location:8.4.0'
    compile 'com.google.android.gms:play-services-gcm:8.4.0'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.4.5'
    compile 'com.fasterxml.jackson.core:jackson-core:2.4.5'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.4.5'
    compile 'joda-time:joda-time:2.5'
    compile 'com.squareup.retrofit:retrofit:1.7.1'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.5.0'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.netflix.rxjava:rxjava-core:0.20.7'
    compile 'com.netflix.rxjava:rxjava-android:0.20.7'
    compile 'com.squareup.dagger:dagger:1.2.2'
    compile 'com.squareup.mortar:mortar:0.16'
    compile 'com.squareup.flow:flow:0.8'
    compile 'com.jakewharton:butterknife:6.1.0'
    compile 'com.jakewharton.timber:timber:2.5.1'
    compile 'com.braintreepayments:encryption:2.0.0'
    compile 'com.newrelic.agent.android:android-agent:5.3.2'
    compile 'com.instabug.library:instabugsupport:1.7.1'
    compile 'net.hockeyapp.android:HockeySDK:3.0.2'
    provided 'com.squareup.dagger:dagger-compiler:1.2.2'
    compile 'com.rengwuxian.materialedittext:library:2.1.4'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.mixpanel.android:mixpanel-android:4.6.2'
    compile 'com.roomorama:caldroid:2.2.0'
    compile 'com.squareup.phrase:phrase:1.1.0'
    compile 'com.zendesk:sdk:1.5.0.1'
    compile 'com.flipboard:bottomsheet-core:1.4.3'
    compile 'com.kahuna.sdk:kahuna:2.3.1'
    compile 'io.branch.sdk.android:library:1.+''
}

A:

Versions of play-services libs should be equal, for example:
DO
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'

DONT
compile 'com.google.android.gms:play-services-maps:7.8.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'

A:

When selectively compile Google Play service APIs on 8.4.0, I've also encountered problems (8.3.0 -> 8.4.0).
Error:
Could not find method com.google.android.gms.common.internal.zzx.zzy

Before upgrade:
compile 'com.google.android.gms:play-services-maps:8.3.0'

After upgrade (doesn't work):
compile 'com.google.android.gms:play-services-maps:8.4.0'

After upgrade (works fine):
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'

Conclusion: it seems like some of the play services now have some certain dependencies that you have to explicitly specify, e.g.: maps -> gcm.

A:

I was able you solve this.  My coworker was able to upgrade without issues.  I went to my sdk/extras folders saw mine was pretty different.  So I moved my folder copied my coworkers and it worked.
I think that folder and maybe something else in the sdk folder had just gotten into an odd state, clearing the folder and redownloading may work too.


Q:

Tablesorter and date mm/yyyyy

I've been using tablesorter a lot in my website like this
$(".tablesorter").tablesorter({
                widgets: ['zebra'],
                dateFormat: 'uk',
});

But i've a problem with date in the format : MM/YYYY (it's when I don't have the day I prefer showing 12/2005 than 00/12/2005).
This format does not work with tablesorter dateFormat uk. How to make it working ?
And the difficulty is that I can have in the same table differents formats like this :
Date - Title
11/2005 - Movie 1
12/11/2005 - Movie 2
2006 - Movie 3

Thank you.

A:

You could add a custom parser:
$.tablesorter.addParser({
    id: 'rough-date',
    is: function() {
        // return false so this parser is not auto detected
        return false;
    },
    format: function(s) {
        // format to look like an ISO 8601 date (2005-11-12).
        // Month-only dates will be formatted 2005-11.
        return s.split('/').reverse().join('-');
    },
    type: 'text' // sort as strings
});

And then use it like this (where 0 is the column number that contains the date):
$(".tablesorter").tablesorter({
    headers: {
        0: {
            sorter:'rough-date'
        }
    }
});

Here's a JSFiddle.


Q:

any way to tell if user's python environment is anaconda

i'm distributing an in-house python lib where i'd like to make it such that if the user is using anaconda when running this file, that updates to the dependencies of the library will be made automatically.  (this is by request.  if it were up to me, i would let the users control their own packages.)
so far, i've come up with something like
def _user_has_conda():
    cmd = 'conda --help'
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    if len(out) > 0 and len(err) == 0:
        return True
    else:
        return False

but this really only tells me if the user has anaconda installed on their system, and not whether the current python process is running in the anaconda environment.
what i notice is that when i start a python or ipython shell, i see "Python 3.3.3 |Continuum Analytics, Inc|" at the top.  my next idea would be to try to find how to get this string to see if "Continuum Analytics" is there, and if so, assume that the user is running in anaconda.
i'm sure there are better ideas out there, and that's why i'm here.
thank you.

A:

I'm from Continuum, so let me make a quick note:  You'll get a different sys.version string depending on whether you used conda to install the Anaconda Python Distribution or simply Python.  So from conda create -n full_apd anaconda you'd get a sys.version string as follows:
$ python -c "import sys; print sys.version"
2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)]

This is what you get if you use miniconda or are working from a conda environment where you have just specified python (e.g. conda create -n base_py27 python=2.7):
$ python -c "import sys; print sys.version"
2.7.6 |Continuum Analytics, Inc.| (default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)]

If you have simply downloaded and installed the full Anaconda Python Distribution directly, you'll get the former:
$ python -c "import sys; print sys.version"
2.7.6 |Anaconda 1.8.0 (x86_64)| (default, Jan 10 2014, 11:23:15)
[GCC 4.0.1 (Apple Inc. build 5493)]

A:

In [109]: import sys

In [110]: 'conda' in sys.version
Out[110]: True

For version > 3.7, the version info has changed like:
In [2]: sys.version
Out[2]: '3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)]'

From this post
The solution should be changed to:
import sys, os
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta'))

A:

Documentation: http://docs.python.org/2/library/sys.html#sys.version
In [1]: import sys; sys.version
Out[1]: '2.7.5 |Anaconda 1.8.0 (64-bit)| (default, Jul  1 2013, 12:37:52) [MSC v.1500 64 bit (AMD64)]'


Q:

Контент в мобильных браузерах

Страница не корректно отображается в некоторых мобильных браузерах (UC Browser) -- после скролла вниз весь контент, что находится ниже окна браузера, прячется за белым фоном. https://jsfiddle.net/0hey4jkw

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

*:before,
*:after {
  content: '';
  display: block;
  position: absolute;
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
  background: #593c1e;
}

.wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}
/*
=================================
    BACKGROUND STYLE
=================================
*/
.background {
  height: 100%;
  position: fixed;
  width: 100%;
  overflow: hidden;
  left:0;top:0;
}

.landscape {
  position: relative;
  height: 100%;
  background: #db9;
  overflow: hidden;
}

.landscape div {
  position: absolute;
}

.sun {
  left: 50%;
  bottom: 200px;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: linear-gradient(to bottom, #ff8 50%, rgba(208, 73, 73, 0) 100%);
  box-shadow: 0px -20px 200px #FFFF8C;
}

.land {
  left: 50%;
  width: 2000px;
  height: 2000px;
  border-radius: 50%;
}

.l1 {bottom: -1850px;margin-left: -1100px;background: #d0a273}
.l2 {bottom: -1700px;margin-left: -300px;background: #c4884d}
.l3 {bottom: -1900px;margin-left: -800px;background: #a66f37}
.l4 {bottom: -1800px;margin-left: -1700px;background: #80552b}

.windmill {width: 2px;}

.windmill .turbine {
  top: -5px;
  left: -4px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  -webkit-animation: 7s rotate infinite linear;
  animation: 7s rotate infinite linear;
}

.windmill .t {
  left: 2px;
  width: 0;
  height: 0;
  border-style: solid;
  border-color: transparent;
  -webkit-transform-origin: bottom;
  transform-origin: bottom
}

.windmill.s1 {width: 2px;height: 15px}
.windmill.s1 .t {top: -2px;left: 4px;width: 2px;height: 7px;border-width: 0}

.windmill.s2 {height: 20px;
  -webkit-transform: rotateY(120deg);
  -ms-transform: rotateY(120deg);
  transform: rotateY(120deg)}
.windmill.s2 .t {top: -10px;border-bottom-width: 12px}

.windmill.s3 {height: 35px}
.windmill.s3 .t {top: -18px;border-bottom-width: 20px}

.windmill.s4 {height: 50px}
.windmill.s4 .t {top: -28px;border-bottom-width: 30px}

.l1 .s1 {background: #d0a273}
.l1 .s1 .t {background: #d0a273}
.l2 .s2 {background: #c4884d}
.l2 .s2 .t {border-bottom-color: #c4884d}
.l3 .s3 {background: #a66f37}
.l3 .s3 .t {border-bottom-color: #a66f37}
.l4 .s4 {background: #80552b}
.l4 .s4 .t {border-bottom-color: #80552b}

.s1:nth-child(1) {top: -5px;left: 870px}
.s1:nth-child(2) {top: -12px;left: 970px}
.s1:nth-child(3) {top: -9px;left: 1070px}
.s2:nth-child(1) {top: 125px;left: 485px}
.s2:nth-child(2) {top: 85px;left: 555px}
.s2:nth-child(3) {top: 50px;left: 635px}
.s3:nth-child(1) {top: -10px;left: 780px}
.s3:nth-child(2) {top: -30px;left: 940px}
.s3:nth-child(3) {top: -25px;left: 1120px}
.s4:nth-child(1) {top: -25px;left: 1200px}
.s4:nth-child(2) {top: 28px;left: 1380px}
.s4:nth-child(3) {top: 125px;left: 1560px}

.t1 {-webkit-transform: rotate(0deg);
 transform: rotate(0deg)}
.t2 {-webkit-transform: rotate(120deg);
 transform: rotate(120deg)}
.t3 {-webkit-transform: rotate(240deg);
 transform: rotate(240deg)}

@-webkit-keyframes rotate {
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes rotate {
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
/*
=================================
      MENU STYLE
=================================
*/
.menu {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  max-width: 900px;
  border: 2px solid #fff;
}

.menu * {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 2.5%;
  min-height: 34px;
  border: 2px solid #fff;
}

.menu .main {border: 0;padding: 0;}
.menu .main:before {color: #468;}
.menu .content:before {color: #fff;}

.header {padding-bottom: 8%;}
.header:before {content: "";}

.main {}
.main:before {content: "";}

.content {}
.content:before {content: "
";}

.footer {padding-bottom: 8%;}
.footer:before {content: "";}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Windmill Landscape</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <link rel="stylesheet" href="css/style.css">

Heading

Lorem ipsum dolor sit amet, mei doming graecis at, sint debitis expetendis nam ex, quo ad graeci hendrerit theophrastus. Regione tibique assueverit mea ea, sed eu quas latine epicurei. Consul nominavi rationibus qui ex, eu illum eirmod vidisse sit. Ex summo dissentiunt mea. Quot quaeque at eum. In docendi apeirian mel.

Erant sanctus mea eu. Choro exerci gubergren vix an, eum ne enim complectitur, ei dicam singulis disputationi vis. Sed agam referrentur an, ad eum simul ridens. Ne essent assueverit signiferumque eam, ad vel ferri mentitum. Case commodo interpretaris pro id, ad eos graeci blandit, an epicuri suavitate instructior per. Audiam iudicabit sea no, qui ut nihil veritus. Eu aliquam albucius mea.

Atomorum splendide mei te, minim aliquam inciderint et vis. Mei iusto consul facilis cu. Ea justo habemus mei. No ignota constituto usu, qui impedit quaestio definiebas ex.

Aeque ubique te eam, putent voluptatibus mel eu, quodsi efficiantur in has. Minim volutpat sit eu, mutat vidisse ei vel. Quando fabellas vix te. Eu dicam quaestio vim.

Harum nostro eum an, at timeam equidem qui. Cu usu imperdiet voluptatum intellegebat, qui an quot tantas. Eu pro oratio torquatos, summo omnium quaeque eu eum, usu accusamus comprehensam ne. Vidit omnes labitur in ius.

Dicat laudem senserit no eos, vel ex mazim viris. Nec ea omnium lobortis quaerendum, liber adipisci qualisque vis id. Sit quot tibique corrumpit te, qui ferri eirmod fuisset cu. Te alia mazim mollis his, expetenda intellegebat usu at. Oratio oporteat gloriatur his ad. Ea inani erroribus cum.

Atqui mundi adipiscing cu qui. Sit cu paulo nihil, iusto nostrum adolescens ad vim, ei patrioque dissentiet comprehensam nec. Nonumy molestie conceptam cu vel, qui eu eius adipisci vituperatoribus. Eum labores debitis platonem te. Graeco mnesarchum at usu, qui ea viderer deseruisse adipiscing, verterem argumentum vis ne. His id ludus dicam, te vidit zril prompta mea. Eu iriure intellegebat reprehendunt sed, principes theophrastus ea mei.

Mei tollit consequuntur et. His fugit causae in, eu his facer mazim. Latine vituperatoribus cu qui, per ad possim aliquip suavitate, wisi ignota iudicabit cum eu. Pri posse equidem phaedrum ut, usu at iuvaret accusam pertinax. Mel duis ullamcorper ex, ne nam vide novum latine. Ne hinc inimicus delicatissimi sea, quodsi minimum contentiones ei cum.

An quando fabellas scripserit vel, in quidam democritum usu. Augue possim melius id mea, vel cu phaedrum laboramus. Illud graeco discere mea ad, commune tacimates cu mea, an vis accusam tacimates. In ocurreret honestatis nam, quot autem epicurei est et. Et vis congue equidem docendi, duo ut autem similique. Eam percipitur neglegentur comprehensam ex.

Mel harum invidunt elaboraret ut, mea probo idque ex, lorem zril definitiones ea cum. Moderatius intellegam his cu. Per quando equidem et, dicta latine sadipscing pro ne. Vero vidit insolens sed ne. At velit atomorum cum, dicta eleifend vel eu.

Из-за чего такое может быть?

A:

Свойство height: 100% ставьте лишь html, для остальных элементов замените на min-height: 100%. Блок .landskape абсолютно спозиционируйте. А на html поставьте overflow: hidden; - именно заскролирование html вызывает данный эффект. А чтобы наш контент скролировался - на body мы поставим overflow: auto;.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

*:before,
*:after {
  content: '';
  display: block;
  position: absolute;
  box-sizing: border-box;
}

html {
  height: 100%;
  overflow: hidden;
}
body {
  margin: 0;
  padding: 0;
  min-height: 100%;
  background: #593c1e;
  overflow: auto;
}

.wrapper {
  position: relative;
  width: 100%;
  min-height: 100%;
}
/*
=================================
    BACKGROUND STYLE
=================================
*/
.background {
  min-height: 100%;
  position: fixed;
  width: 100%;
  overflow: hidden;
  left:0;top:0;
}

.landscape {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: #db9;
  overflow: hidden;
}

.landscape div {
  position: absolute;
}

.sun {
  left: 50%;
  bottom: 200px;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: linear-gradient(to bottom, #ff8 50%, rgba(208, 73, 73, 0) 100%);
  box-shadow: 0px -20px 200px #FFFF8C;
}

.land {
  left: 50%;
  width: 2000px;
  height: 2000px;
  border-radius: 50%;
}

.l1 {bottom: -1850px;margin-left: -1100px;background: #d0a273}
.l2 {bottom: -1700px;margin-left: -300px;background: #c4884d}
.l3 {bottom: -1900px;margin-left: -800px;background: #a66f37}
.l4 {bottom: -1800px;margin-left: -1700px;background: #80552b}

.windmill {width: 2px;}

.windmill .turbine {
  top: -5px;
  left: -4px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  -webkit-animation: 7s rotate infinite linear;
  animation: 7s rotate infinite linear;
}

.windmill .t {
  left: 2px;
  width: 0;
  height: 0;
  border-style: solid;
  border-color: transparent;
  -webkit-transform-origin: bottom;
  transform-origin: bottom
}

.windmill.s1 {width: 2px;height: 15px}
.windmill.s1 .t {top: -2px;left: 4px;width: 2px;height: 7px;border-width: 0}

.windmill.s2 {height: 20px;
  -webkit-transform: rotateY(120deg);
  -ms-transform: rotateY(120deg);
  transform: rotateY(120deg)}
.windmill.s2 .t {top: -10px;border-bottom-width: 12px}

.windmill.s3 {height: 35px}
.windmill.s3 .t {top: -18px;border-bottom-width: 20px}

.windmill.s4 {height: 50px}
.windmill.s4 .t {top: -28px;border-bottom-width: 30px}

.l1 .s1 {background: #d0a273}
.l1 .s1 .t {background: #d0a273}
.l2 .s2 {background: #c4884d}
.l2 .s2 .t {border-bottom-color: #c4884d}
.l3 .s3 {background: #a66f37}
.l3 .s3 .t {border-bottom-color: #a66f37}
.l4 .s4 {background: #80552b}
.l4 .s4 .t {border-bottom-color: #80552b}

.s1:nth-child(1) {top: -5px;left: 870px}
.s1:nth-child(2) {top: -12px;left: 970px}
.s1:nth-child(3) {top: -9px;left: 1070px}
.s2:nth-child(1) {top: 125px;left: 485px}
.s2:nth-child(2) {top: 85px;left: 555px}
.s2:nth-child(3) {top: 50px;left: 635px}
.s3:nth-child(1) {top: -10px;left: 780px}
.s3:nth-child(2) {top: -30px;left: 940px}
.s3:nth-child(3) {top: -25px;left: 1120px}
.s4:nth-child(1) {top: -25px;left: 1200px}
.s4:nth-child(2) {top: 28px;left: 1380px}
.s4:nth-child(3) {top: 125px;left: 1560px}

.t1 {-webkit-transform: rotate(0deg);
 transform: rotate(0deg)}
.t2 {-webkit-transform: rotate(120deg);
 transform: rotate(120deg)}
.t3 {-webkit-transform: rotate(240deg);
 transform: rotate(240deg)}

@-webkit-keyframes rotate {
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}

@keyframes rotate {
  100% {
    -webkit-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
/*
=================================
      MENU STYLE
=================================
*/
.menu {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 100%;
  max-width: 900px;
  border: 2px solid #fff;
}

.menu * {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  padding: 2.5%;
  min-height: 34px;
  border: 2px solid #fff;
}

.menu .main {border: 0;padding: 0;}
.menu .main:before {color: #468;}
.menu .content:before {color: #fff;}

.header {padding-bottom: 8%;}
.header:before {content: "";}

.main {}
.main:before {content: "";}

.content {}
.content:before {content: "
";}

.footer {padding-bottom: 8%;}
.footer:before {content: "";}
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Windmill Landscape</title>
 <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <link rel="stylesheet" href="css/style.css">

Heading

Lorem ipsum dolor sit amet, mei doming graecis at, sint debitis expetendis nam ex, quo ad graeci hendrerit theophrastus. Regione tibique assueverit mea ea, sed eu quas latine epicurei. Consul nominavi rationibus qui ex, eu illum eirmod vidisse sit. Ex summo dissentiunt mea. Quot quaeque at eum. In docendi apeirian mel.

Erant sanctus mea eu. Choro exerci gubergren vix an, eum ne enim complectitur, ei dicam singulis disputationi vis. Sed agam referrentur an, ad eum simul ridens. Ne essent assueverit signiferumque eam, ad vel ferri mentitum. Case commodo interpretaris pro id, ad eos graeci blandit, an epicuri suavitate instructior per. Audiam iudicabit sea no, qui ut nihil veritus. Eu aliquam albucius mea.

Atomorum splendide mei te, minim aliquam inciderint et vis. Mei iusto consul facilis cu. Ea justo habemus mei. No ignota constituto usu, qui impedit quaestio definiebas ex.

Aeque ubique te eam, putent voluptatibus mel eu, quodsi efficiantur in has. Minim volutpat sit eu, mutat vidisse ei vel. Quando fabellas vix te. Eu dicam quaestio vim.

Harum nostro eum an, at timeam equidem qui. Cu usu imperdiet voluptatum intellegebat, qui an quot tantas. Eu pro oratio torquatos, summo omnium quaeque eu eum, usu accusamus comprehensam ne. Vidit omnes labitur in ius.

Dicat laudem senserit no eos, vel ex mazim viris. Nec ea omnium lobortis quaerendum, liber adipisci qualisque vis id. Sit quot tibique corrumpit te, qui ferri eirmod fuisset cu. Te alia mazim mollis his, expetenda intellegebat usu at. Oratio oporteat gloriatur his ad. Ea inani erroribus cum.

Atqui mundi adipiscing cu qui. Sit cu paulo nihil, iusto nostrum adolescens ad vim, ei patrioque dissentiet comprehensam nec. Nonumy molestie conceptam cu vel, qui eu eius adipisci vituperatoribus. Eum labores debitis platonem te. Graeco mnesarchum at usu, qui ea viderer deseruisse adipiscing, verterem argumentum vis ne. His id ludus dicam, te vidit zril prompta mea. Eu iriure intellegebat reprehendunt sed, principes theophrastus ea mei.

Mei tollit consequuntur et. His fugit causae in, eu his facer mazim. Latine vituperatoribus cu qui, per ad possim aliquip suavitate, wisi ignota iudicabit cum eu. Pri posse equidem phaedrum ut, usu at iuvaret accusam pertinax. Mel duis ullamcorper ex, ne nam vide novum latine. Ne hinc inimicus delicatissimi sea, quodsi minimum contentiones ei cum.

An quando fabellas scripserit vel, in quidam democritum usu. Augue possim melius id mea, vel cu phaedrum laboramus. Illud graeco discere mea ad, commune tacimates cu mea, an vis accusam tacimates. In ocurreret honestatis nam, quot autem epicurei est et. Et vis congue equidem docendi, duo ut autem similique. Eam percipitur neglegentur comprehensam ex.

Mel harum invidunt elaboraret ut, mea probo idque ex, lorem zril definitiones ea cum. Moderatius intellegam his cu. Per quando equidem et, dicta latine sadipscing pro ne. Vero vidit insolens sed ne. At velit atomorum cum, dicta eleifend vel eu.


Q:

Como definir a url para uma rota no Laravel?

Estou utilizando Laravel 5.4 e controllers no padrão Restful.
Configurei o arquivo de rotas da seguinte forma:
Route::resource('entryRegistry', 'EntryRegistryController');

Na view:
{{ route('entryRegistry.create') }}

Na Controller:
public function create() { }

Com isto, a url da minha pagina ficou:
/entryRegistry/create

Como faço para alterar a url que faz referencia a rota da funcion create ?
Eu quero alterar o entryregistry/create para registro-ponto/criar, sem alterar a estrutura da controler e também sem alterar o nome da function e da controller em questão.

A:

A ideia em se utilizar um Route::resource é padronizar todas as rotas de determinado recurso seguindo uma convenção que está documentada aqui:
| Verb      | URI                  | Action  | Route Name     |
|-----------|----------------------|---------|----------------|
| GET       | /photos              | index   | photos.index   |
| GET       | /photos/create       | create  | photos.create  |
| POST      | /photos              | store   | photos.store   |
| GET       | /photos/{photo}      | show    | photos.show    |
| GET       | /photos/{photo}/edit | edit    | photos.edit    |
| PUT/PATCH | /photos/{photo}      | update  | photos.update  |
| DELETE    | /photos/{photo}      | destroy | photos.destroy |

Você pode mudar isso redefinindo suas rotas sem usar o Route::resource, dessa forma você terá mais controle:
Route::get('registro-ponto/criar', 'EntryRegistryController@create')
    ->name('entryRegistry.create');

// Se quiser, pode declarar só a rota de create fora do resource

Route::resource('entryRegistry', 'EntryRegistryController', ['except' => ['create']]);

Tenha em mente que fazer isso quebra o RESTful das rotas.
Leia mais sobre como definir suas rotas e sobre Resource Controllers na documentação do Laravel:

Routingen
Resource Controllersen


Q:

setting up TypeScript unit tests with Mocha

I am trying to organize a new typescript project that has unit tests, also written in TS, running in the Mocha test runner.
My project with the following directory convention:
/project/src/             for server-side code (java)
/project/test/            server's tests
/project/resources/       client-side code (typescript)
/project/test-resources/  typescript tests.

right now I have a typescript module Schema in a typescript file located at resources/many/levels/schema.ts
and I have its test, written for the mocha test runner, in a typescript file:
test-resources/many/levels/schemaTest.ts
The problem is that the typescript compiler can't find the schema module using the following import syntaxes:

TC2307 Can't find module schema

schemaTest.ts (version 1):
/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/chai/chai.d.ts" />
/// <reference path="../../../resources/many/levels/schema.ts" />
import s = require('schema');

schemaTest.ts (version 2):
/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/chai/chai.d.ts" />
/// <reference path="../../../resources/many/levels/schema.ts" />
import {Schema, SchemaFactory} from 'schema';

finally, the following version compiles but leads to a runtime error since the module is not at ../../../resources/many/level but instead is located in the dist directory
/// <reference path="../typings/mocha/mocha.d.ts" />
/// <reference path="../typings/chai/chai.d.ts" />
/// <reference path="../../../resources/many/levels/schema.ts" />
import {Schema, SchemaFactory} from '../../../resources/many/levels/schema';

schema.ts:
module Schema  {

    export interface Schema {
        getName() : string;
        getColumnByIndex(index : number) : Column;
        getColumnById(id : string) : Column;
        getNumberOfColumns(): number;
    }

    export class SchemaFactory{
        ...
        build() : Schema {...}
    }
}

I am compiling both my test and src files to a single dist directory (not ideal) and hope to run tests from there.
I am compiling with the flag --module commonjs.
if it matters, I am using IntelliJ 15 / WebStorm (and using its plugings for mocha, node, and tsc)
Is my Schema module set up incorrectly? Should it be an internal/external module? Should my tests be in the same namespace?
Thanks in advance!

A:

I have been through these problems when I was setting up my jasmine tests but fundamentally the concepts are the same. The problem stems from the fact that while the relative path reference is specified based on the locations of the .ts files, that relative path reference is not maintained when the code is compiled over to the dist location. Below is how I got past that issue.

Separate the compilation of scripts and specs into two different tasks. I am using gulp tasks for my build process but if you are not using gulp, you can still achieve this by having a separate tsconfig.json, one in resources folder for your source code compilation and another tsconfig.json in your resources-test folder for your test scripts compilation. Basically that would logically separate your source code and test scripts as two different typescript projects.
For the typescript compilation of your source code, use the declaration compiler option set to true so that you get a schema.d.ts file. This file is going to be referenced in your schemaTest.ts. To make things super easy, have a build step that when source is compiled, copy over the .d.ts and .js files generated from the source compilation to a specific folder in the test-resources folder (lets say test-resources/compiledsource). The compiledsource folder will in this case have schema.d.ts and schema.js files.

The import statement in your test scripts (schematests.ts) will import from the compiledsource folder as below
import {Schema, SchemaFactory} from './compiledsource/schema';

Your source compilation and test scripts compilation should be done in two steps and the first step would be source compilation so that when your test scripts compile, you have the schema.d.ts available in the compiledsource folder, and when your tests run the schema.js will be available in compiledsource folder.

When typescript interprets "import" statement, it will look for the
  .ts or .d.ts file and when it is compiled to javascript require
  statement, it will look for the .js file.


Q:

OpenGL mipmaps cut out?

Is it possible to cut out the last 3 miplevels, so it wont use higher miplevels than max-3 ?
I have problems with high miplevels, they look really bad no matter how much i pad my textures.

A:

See glTexParameter and GL_TEXTURE_MAX_LEVEL.  I believe this will do what you want.
http://www.opengl.org/sdk/docs/man/xhtml/glTexParameter.xml


Q:

Ruby print button

 <%= link_to "Print", 'window.print();return false;', class: "btn btn-primary" %>

Trying to implement a print button but I don't know what format to use. Could anyone help me. I want it to be using the class btn btn-primary

A:

You need to tell the browser that you want to execute Javascript there.  So you either need to use onClick, which can be given via a :onclick => parameter, or prefix the code with javascript:.
Here is a similar SO question: How can I put a print link/button on my project page to printout an infomation?
Try something like this:
<%= link_to "Print", '#', class: "btn btn-primary",
            onclick: 'window.print();return false;' %>


Q:

How to migrate to Gatling 2.2 from 2.1.7

I'm not really good with Scala and I really want to love Gatling, but lack of documentation makes it really difficult.
Here is the problem that I've encountered after trying to migrate to 2.2.0 version from 2.1.7:

global - now requires GatlingConfiguration for some reason, could someone provide example of how to use it with latest version?
throttling - now should be added via some sort of ThrottlingSteps -as before, could someone give me example how to use it correctly?

Worst part of this madness is that on official Gatling website migration article doesn't cover this part and official documentation is obsolete

A:

Disclaimer: Gatling founder here
No, documentation is perfectly up-to-date and issues are most likely on your side.
First, all the pieces of code in our documentation are actually real classes that gets compiled as part of our build process before their source code is getting pasted into the documentation.
Then, we also have some internal classes stored in the test sources to double check that everything compiles fine, such as HttpCompileTest that uses both assertions and throttling.
Finally, our public layer is the DSL, and only the DSL. So we only document DSL changes, not implementation ones.
Either you're missing Gatling standard imports (such as import io.gatling.core.Predef._), or have transformed them into smaller imports so you end up importing DSL implementations. Those implementations have indeed changed in Gatling 2.2 but then, you're not supposed to see them for normal usage.
Or, you've build your own DSL on top of ours, so you indeed use our implementations. But then, you're only supposed to do that if you're sufficiently proficient with Scala as you're not sticking to our public layer: the DSL.


Q:

Body of Email using Visual force Email templare is missing in email

I am using a visualforce email template from Apex Batch class. I am getting the Body of email when checking from Preview and Test mode. But if I schedule the batch, only blank email is coming. I am using visualforce component with custom controller  inside my visualforce email template to prepare the email body.
Below is the code.
Email Template:
<messaging:emailTemplate subject="Pending Letter" recipientType="Contact"
 relatedToType="Return__c">
  <messaging:htmlEmailBody >
    <c:Pending_Letter caseId="{!relatedTo.Case__r.Id}" contactId={!relatedTo.Case__r.Contact.Id}"/>
  </messaging:htmlEmailBody>
</messaging:emailTemplate>

Vf Component:
<apex:component access="global" controller="Reminder_Letter">
<apex:attribute name="contactId" type="Id" description="Id of the Contact" assignTo="{!contact}"/>
<apex:attribute name="caseId" type="Id" description="Id of the Case" assignTo="{!cId}"/>
 <apex:dataTable value="{!returnList}" var="pr" id="dtCaseInfo"
                 rowClasses="odd,even" styleClass="tableClass">
    <apex:column >
        <apex:facet name="header"> Serial Number  </apex:facet>
        <apex:outputText value="{!pr.Issue__r.SerialNumber__c}"/>
    </apex:column>
    </apex:dataTable>
   OTHER MY HARDCODED TEXT FOR EMAIL BODY
 </apex:component>

Controller:
public class Reminder_Letter {
public Id cId {get;set;}
public Id contact {get;set;}
List<Return__c> productReturnList;
Public List<Return__c> getReturnList(){

   if(cId != null) {
       ReturnList = new List<Return__c>([Select   Id, Name,Return_Status__c, Issue__r.Serial_Number__c FROM  Return__c WHERE Return_Status__c  IN ('Pending') AND Case__c =: cId]);
       return ReturnList;
   }
   return null;
 }
}

Batch Class Code (for sending mail) :
I am referring the VF email template using the following line. As the batch is working fine only sharing the portion related to email functionality.
 EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'Reminder_Letter'];

==============================
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String [] toaddress = toStr;
    EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'Reminder_Letter'];
    mail.setTargetObjectId(tgtObjId);
    mail.setWhatId(prId);
    mail.setTemplateId(et.Id);
    mail.setToAddresses(toaddress);
    mail.setSubject('Test email');

    try{
        results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
    }
    Catch(Exception e){
        System.debug('e'+e.getMessage());
    }

A:

As you are using Email template so you need to remove this line
mail.setSubject('Test email');

It will override your template. So remove this line and you will get email body.


Q:

SQLite rollback robustness

Oracle, SQL Server, DB2 and all major commercial databases work fine with multiple levels of redo by many different users.
Is SQLite robust enough to do this also or are there limitations on the transaction handling?

A:

SQLite database is in a file on disc. if you want to do you have to do multiple database writes, put them inside a transaction. Since every write will lock the file(db). SQLite behaves well with large transactions though. I have no solid data compare this with other databases you mentioned but large transactions are handled well in SQLite.


Q:

After-hook scenario.exception does not exist in Cucumber 2.0

I'm using Capybara, Cucumber, and Selenium-Webdriver for basic web testing. If a test fails, I want to capture the failure message and send it to a separate log file.
Cucumber offers hooks to catch the failure message after the scenario fails (from their wiki):
After do |scenario|
  if scenario.failed?
    subject = "[Project X] #{scenario.exception.message}"
    send_failure_email(subject)
  end
end

However, when I implement this in my features/support/support.rb file, I get a no method error:
undefined method `exception' for #<Cucumber::RunningTestCase::Scenario:0x007fc7b4380968>

Is this error a result of my setup, or is this a bug specific to Cucumber 2.0?
Here is my code for features/support/support.rb:
require 'capybara/cucumber'
Capybara.default_driver = :selenium

After do |scenario|
    if scenario.failed?
        puts scenario.exception.message
    end
end

Here is my code for features/step_definitions/step_definition.rb:
Given(/^I am on the Google homepage$/) do
  visit 'http://www.google.com'
end

Then(/^I will search for "(.*?)"$/) do |searchText|
  fill_in 'lst-ib', :with => searchText
end

Then(/^I should see "(.*?)"$/) do |expectedText|
  page.should have_content(expectedText)
end

Then(/^I will click the Product link$/) do
  click_link('Product')
end

Here is my code for features/findGameSparks.feature:
Feature: Find the GameSparks Website

Scenario: Search for the website
    Given I am on the Google homepage
    Then I will search for "GameSparks"
    Then I should see "A NON-EXISTENT STRING CAUSING TEST FAILURE!!!!"
    Then I will click the Product link

Here are the version numbers for everything I'm using:
OSX 10.10.1
ruby 2.2.1p85
rvm 1.26.11
gem 2.4.6
cucumber 2.0.0
cucumber-core 1.1.3
capybara 2.4.4
selenium-webdriver 2.45.0

A:

This bug is fixed in this commit on April 1: https://github.com/cucumber/cucumber/commit/e92917c8f10a4907dedf26d77665116b69f3e3b9
The most recent release of Cucumber is 2.0.0, released March 27, so it seems the fix hasn't been released yet.
You can point to the github repo in your Gemfile to get the latest available code:
gem 'cucumber', git: 'https://github.com/cucumber/cucumber.git'

Note however that running "prerelease" code like this can lead to other problems, for example if a committer to cucumber messes up the master branch.


Q:

Using Napp Drawer Alloy Widget for TabGroup

could someone please guide me on how to use Napp Drawer widget in TabGroup (i am using 3 tabs currently)?
Though I have not tried it yet but before trying it out, I want your advises. Thanks.

A:

it's not possible.
DrawerLayout Issue
NappDrawer Issue


Q:

maniplate html sent from server

Is is possible, on the client side, to manipulate the HTML sent from a site when you are not the owner of the site, and have no access to the code?

A:

Yes. There are many ways.
HTTP proxies such as Fiddler or Burp can break on all requests and then manipulate the response before it reaches the browser.
Video explaining how this is done in Fiddler.
There are also several browser plugins like Tampermonkey (Chrome) and Greasemonkey (Firefox) that allow you to execute custom JavaScript on page load automatically.


Q:

Singleton with parameter in Kotlin

I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters. There is another singleton that takes a constructor parameter.
Java code:
public class TasksLocalDataSource implements TasksDataSource {

    private static TasksLocalDataSource INSTANCE;

    private TasksDbHelper mDbHelper;

    // Prevent direct instantiation.
    private TasksLocalDataSource(@NonNull Context context) {
        checkNotNull(context);
        mDbHelper = new TasksDbHelper(context);
    }

    public static TasksLocalDataSource getInstance(@NonNull Context context) {
        if (INSTANCE == null) {
            INSTANCE = new TasksLocalDataSource(context);
        }
        return INSTANCE;
    }
}

My solution in kotlin:
class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {

    private val mDbHelper: TasksDbHelper

    init {
        checkNotNull(context)
        mDbHelper = TasksDbHelper(context)
    }

    companion object {
        lateinit var INSTANCE: TasksLocalDataSource
        private val initialized = AtomicBoolean()

        fun getInstance(context: Context) : TasksLocalDataSource {
            if(initialized.getAndSet(true)) {
                INSTANCE = TasksLocalDataSource(context)
            }
            return INSTANCE
        }
    }
}

Am I missing anything? Thread safety? Laziness ?
There were a few similar questions but I don't like the answers :)

A:

Here's a neat alternative from Google's architecture components sample code, which uses the also function:
class UsersDatabase : RoomDatabase() {

    companion object {

        @Volatile private var INSTANCE: UsersDatabase? = null

        fun getInstance(context: Context): UsersDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context.applicationContext,
                    UsersDatabase::class.java, "Sample.db")
                    .build()
    }
}

A:

• Thread-Safe Solution # Write Once; Use Many;
It's a good solution to create a class implementing the logic of singleton which also holds the singleton instance, like the following.
It instantiates the instance using Double-Check Locking in a synchronized block to eliminate possibility of race condition in multi-threaded environments.
SingletonHolder.kt
open class SingletonHolder<out T, in A>(private val constructor: (A) -> T) {

    @Volatile
    private var instance: T? = null

    fun getInstance(arg: A): T {
        return when {
            instance != null -> instance!!
            else -> synchronized(this) {
                if (instance == null) instance = constructor(arg)
                instance!!
            }
        }
    }
}

• Usage
Now in each class that you want to be singleton, write a companion object extending the above class. SingletonHolder is a generic class that accepts type of target class and its requiring parameter as generic params. It also needs a reference to the constructor of target class which is used for instantiating an instance:
class MyManager private constructor(context: Context) {

    fun doSomething() {
        ...
    }

    companion object : SingletonHolder<MyManager, Context>(::MyManager)
}

Finally:
MyManager.getInstance(context).doSomething()

A:

I am not entirely sure why would you need such code, but here is my best shot at it:
class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {
    private val mDbHelper = TasksDbHelper(context)

    companion object {
        private var instance : TasksLocalDataSource? = null

        fun  getInstance(context: Context): TasksLocalDataSource {
            if (instance == null)  // NOT thread safe!
                instance = TasksLocalDataSource(context)

            return instance!!
        }
    }
}

This is similar to what you wrote, and has the same API.
A few notes:

Do not use lateinit here. It has a different purpose, and a nullable variable is ideal here.

What does checkNotNull(context) do? context is never null here, this is guarantied by Kotlin. All checks and asserts are already implemented by the compiler.

UPDATE:
If all you need is a lazily initialised instance of class TasksLocalDataSource, then just use a bunch of lazy properties (inside an object or on the package level):
val context = ....

val dataSource by lazy {
    TasksLocalDataSource(context)
}


Q:

TPA6111 Stereo power amplifier to mono setup

I have a TPA6111 stereo audio power amplifier part (http://www.ti.com/lit/ds/symlink/tpa6111a2.pdf) that has this typical application (from the datasheet):

My application requires a mono signal amplification and I'd like to know if there's a way to sum the audio input&output signals. Alternatively I could use just one channel I think.

A:

You can feed both channels from the same mono signal to have both channels amplify the signal and drive the left and right channels of the output speakers or headphones. Alternately, you could just use one channel to have one channel produce output.


Q:

Why am i getting Error: $injector:unpr Unknown Provider?

I am fairly new to angular and i am trying to replace some scope data structure with a factory but the dependency injection is causing an issue. Help please
https://jsfiddle.net/bennacer860/k8js1o4m/1/
angular.module('flapperNews', [])
  .factory('posts', [function() {
    var o = {
      posts: []
    };
    return o;
  }]);

angular.module('flapperNews', [])
  .service('myService', function() { /* ... */ })
  .controller('MyController', ['myService', function(myService) {
    // Do something with myService
    console.log("test");
  }]);

angular.module('flapperNews', [])
  .controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
    $scope.test = 'Hello world!';
    // $scope.posts = [
    //   {title: 'post 1', upvotes: 5},
    //   {title: 'post 2', upvotes: 2},
    //   {title: 'post 3', upvotes: 15},
    //   {title: 'post 4', upvotes: 9},
    //   {title: 'post 5', upvotes: 4}
    // ];
    $scope.posts = posts.posts;

    $scope.addPost = function() {
      if (!$scope.title || $scope.title === '') {
        return;
      }
      $scope.posts.push({
        title: $scope.title,
        link: $scope.link,
        upvotes: 0
      });
      $scope.title = '';
      $scope.link = '';
    };

    $scope.incrementUpvotes = function(post) {
      post.upvotes += 1;
    };
  }]);

A:

Eliminate the [] in each angular.module('flapperNews', []) after the first.
Passing an argument there tells angular to create a new instance of your module and therefore destroys any previous instances.


Q:

How to Pass URL Image to another activity Android studio

Im trying to send URL Image to another activity at my App. It was successfully added to the circleview for Recycler List, but when i implemented it to intent, it wasn't work.
I tried every tutorial at youtube with no success.
Intent at Main Activity :
private void showSelectedTeam(Team team) {
        Intent moveIntent = new Intent(MainActivity.this, HalamanDeskripsi.class);
        moveIntent.putExtra("restid",team.getPhoto());
        moveIntent.putExtra(HalamanDeskripsi.EXTRA_NAME,team.getName());
        moveIntent.putExtra(HalamanDeskripsi.EXTRA_DESC,team.getFrom());
        startActivity(moveIntent);
        }
}

Received at Detailed Activity :
ImageView iv = findViewById(R.id.gambar_desc);

        Bundle bundle = getIntent().getExtras();
        int res = bundle.getInt("restid");
        iv.setImageResource(res);

        TextView tvDataReceived = findViewById(R.id.tv_hd_nama);
        TextView tvDataReceived2 = findViewById(R.id.tv_hd_desc);

        String name = getIntent().getStringExtra(EXTRA_NAME);
        tvDataReceived.setText(name);

        String desc = getIntent().getStringExtra(EXTRA_DESC);
        tvDataReceived2.setText(desc);
    }

Team Class :
public class Team {
    private String name;
    private String Description;
    private String photo;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFrom() {
        return Description;
    }

    public void setFrom(String from) {
        this.Description = from;
    }

    public String getPhoto() {
        return photo;
    }

    public void setPhoto(String photo) {
        this.photo = photo;
    }
}

Data from Array class :
public class DataTeam {
public static String[][] data = new String[][]{
        {"Arsenal",
                "Arsenal Football Club (dikenal pula sebagai Arsenal atau The Gunners) adalah klub sepak bola profesional Inggris yang berbasis di daerah Holloway, London. didirikan pada 1886 dengan nama Dial Square. ",
                "https://cdn.shopify.com/s/files/1/1888/7339/files/Arsenal_17_grande.jpg?v=1498047935"},
        {"Aston Villa",
                "Jenderal TNI Anumerta Ahmad Yani (juga dieja Achmad Yani; lahir di Purworejo, Jawa Tengah, 19 Juni 1922 – meninggal di Lubang Buaya, Jakarta, 1 Oktober 1965 pada umur 43 tahun) adalah .",
                "https://upload.wikimedia.org/wikipedia/en/thumb/f/f9/Aston_Villa_FC_crest_%282016%29.svg/1200px-Aston_Villa_FC_crest_%282016%29.svg.png"},
        {"Bournemouth",
                "Sutomo (lahir di Surabaya, Jawa Timur, 3 Oktober 1920 – meninggal di Padang Arafah, Arab Saudi, 7 Oktober 1981 pada umur 61 tahun)",
                "https://cdn.shopify.com/s/files/1/1888/7339/files/AFCB_08_grande.jpg?v=1498048525"}

};
public static ArrayList<Team> getListData(){
    ArrayList<Team> list = new ArrayList<>();
    for (String[] aData : data) {
        Team team = new Team();
        team.setName(aData[0]);
        team.setFrom(aData[1]);
        team.setPhoto(aData[2]);
        list.add(team);
    }
    return list;
}

When i run this at my phone, the detailed text is sended successfully, but the picture is not loaded. please help me

A:

Edit: As per updated information
It seems you are trying to load image from an url, It is easier to use Picasso or Glide library
Update gradle
 implementation 'com.squareup.picasso:picasso:2.71828'

Get image and load
String res = bundle.getString("resid");
Picasso.get().load(res).into(iv);


Q:

How do I implement quicksort using a batch file?

While normally it's good to always choose the right language for the job, it can sometimes be instructive to try and do something in a language which is wildly inappropriate.

It can help you understand the problem better.  Maybe you don't have to solve it the way you thought you did.
It can help you understand the language better.  Maybe it supports more features than you realized.

And pushing this idea to it's illogical conclusion...how would you implement quicksort in a batch file?  Is it even possible?

A:

Turns out, it's not as hard as you might think.  The syntax is ugly as hell, but the batch  syntax is actually capable of some surprising things, including recursion, local variables, and some surprisingly sophisticated parsing of strings.  Don't get me wrong, it's a terrible language, but to my surprise, it isn't completely crippled.  I don't think I learnt anything about quicksort, but I learned a lot about batch files!
In any case, here's quicksort in a batch file - and I hope you have as much fun trying to understand the bizarre syntax while reading it as I did while writing it.  :-)
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

call :qSort %*
for %%i in (%return%) do set results=!results! %%i
echo Sorted result: %results%
ENDLOCAL
goto :eof

:qSort
SETLOCAL
    set list=%*
    set size=0
    set less=
    set greater=
    for %%i in (%*) do set /a size=size+1
    if %size% LEQ 1 ENDLOCAL & set return=%list% & goto :eof
    for /f "tokens=2* delims== " %%i in ('set list') do set p=%%i & set body=%%j
    for %%x in (%body%) do (if %%x LEQ %p% (set less=%%x !less!) else (set greater=%%x !greater!))
    call :qSort %less%
    set sorted=%return%
    call :qSort %greater%
    set sorted=%sorted% %p% %return%
ENDLOCAL & set return=%sorted%
goto :eof

Call it by giving it a set of numbers to sort on the command line, seperated by spaces.  Example:
C:\dev\sorting>qsort.bat 1 3 5 1 12 3 47 3
Sorted result:  1 1 3 3 3 5 12 47

The code is a bit of a pain to understand.  It's basically standard quicksort.  Key bits are that we're storing numbers in a string - poor man's array.  The second for loop is pretty obscure, it's basically splitting the array into a head (the first element) and a tail (all other elements).  Haskell does it with the notation x:xs, but batch files do it with a for loop called with the /f switch.  Why?  Why not?
The SETLOCAL and ENDLOCAL calls let us do local variables - sort of.  SETLOCAL gives us a complete copy of the original variables, but all changes are completely wiped when we call ENDLOCAL, which means you can't even communicate with the calling function using globals.  This explains the ugly "ENDLOCAL & set return=%sorted%" syntax, which actually works despite what logic would indicate.  When the line is executed the sorted variable hasn't been wiped because the line hasn't been executed yet - then afterwards the return variable isn't wiped because the line has already been executed.  Logical!
Also, amusingly, you basically can't use variables inside a for loop because they can't change - which removes most of the point of having a for loop.   The workaround is to set ENABLEDELAYEDEXPANSION which works, but makes the syntax even uglier than normal.  Notice we now have a mix of variables referenced just by their name, by prefixing them with a single %, by prefixing them with two %, by wrapping them in %, or by wrapping them in !.  And these different ways of referencing variables are almost completely NOT interchangeable!
Other than that, it should be relatively easy to understand!

A:

Here's a more legible version that I wrote awhile ago:
@echo off

echo Sorting:  %*

set sorted=

:sort
:: If we've only got one left, we're done.
if "%2"=="" (
  set sorted=%sorted% %1
  :: We have to do this so that sorted gets actually set before we print it.
  goto :finalset
)
:: Check if it's in order.
if %1 LEQ %2 (
  :: Add the first value to sorted.
  set sorted=%sorted% %1
  shift /1
  goto :sort
)
:: Out of order.
:: Reverse them and recursively resort.
set redo=%sorted% %2 %1
set sorted=
shift /1
shift /1
:loop
if "%1"=="" goto :endloop
set redo=%redo% %1
shift /1
goto :loop
:endloop
call :sort %redo%
:: When we get here, we'll have already echod our result.
goto :eof

:finalset
echo Final Sort:  %sorted%
goto :eof

Example:
C:\Path> sort 19 zebra blah 1 interesting 21 bleh 14 think 2 ninety figure it out

produces:
Sorting:  19 zebra blah 1 interesting 21 bleh 14 think 2 ninety figure it out
Final Sort:   1 2 14 19 21 blah bleh figure interesting it ninety out think zebra


Q:

Python Speed Command Line Call via Subprocess or Another Method

Is there anything more efficient or faster in Python that using the subprocess.call method? I noticed there was a SO question (Python subprocess module much slower than commands (deprecated)) about this a year ago except it became depreciated due to Python removing that alternative, so I am looking to see if this is now the only and thus fastest means to call a command to the shell from within Python. Specifically I am running the following command:

subprocess.call("foo",shell=True)

Or should I be using os?
Thanks.

A:

Probably not. You might be able to make the call slightly faster but in my experience, the biggest gain is to start the subprocess only once and then keep it alive.
Creating new processes is a very expensive operation that Python can't really make cheaper.
So instead of calling /bin/ls path... 100 times, create an external process that reads paths from stdin and returns the desired output without exiting.
As a (sad) example: In ca. 1997, I made the Java 1 compiler 1000 times faster by writing a wrapper that keeps the VM alive and just kicks off the compilation after receiving options via a socket. This wasn't mainly because of process creation times but also because starting a Java VM at that time and ago took very long.


Q:

for example "party:パーティー",how to type "ー"

"party:パーティー",how to type "ー" in the computer

A:

For all IMEs I'm aware of, typing a "-" results in a "ー".
If you're using the Windows IME, there are various tips on this site which you might be interested in.


Q:

DBGrid incremental search component

I am looking into a improved DBGrid that allows me to search items only by pressing the keyboard without enetering data in the special search fields.
Any advanced functions such as colors will be great.

A:

I would like to recommend TDbGridEH component. It is less popular than QuantumGrid but it is quite powerful one. Also it is somewhat easier to switch to it from standard TDBGrid compared to QuantumGrid.


Q:

./ts_calibrate error : ts_open: No such file or directory

I have a problem in mini2440. touch screen does not work when my app(Qt application i mean) run on it.
these are my output for " printenv" in mini2440 :
[root@FriendlyARM bin]# ./ts_calibrate
ts_open: No such file or directory
[root@FriendlyARM bin]# printenv
TSLIB_TSDEVICE=/usr/local/tslib/lib/ts
USER=root
LD_LIBRARY_PATH=/usr/local/Qt/lib:/usr/local/tslib/lib
TSLIB_TSEVENTTYPE=INPUT
OLDPWD=/usr/local/bin
HOME=/
QTDIR=/usr/local/Qt
TSLIB_FBDEVICE=/dev/fb0
PS1=[\u@\h \W]#
TSLIB_PLUGINDIR=/usr/local/tslib/lib/ts
TSLIB_CONSOLEDEVICE=none
LOGNAME=root
TERM=vt102
PATH=/sbin:/usr/sbin:/bin:/usr/bin
TSLIB_CONFFILE=/usr/local/tslib/etc/ts.conf
SHELL=/bin/sh
QWS_DISPLAY=LinuxFB:mmWidth=105:mmHeight=140
PWD=/usr/local/tslib/bin
QWS_MOUSE_PROTO=tslib:/dev/input/event0
TSLIB_CALIBFILE=/etc/pointercal

and in this directory : /dev/input => just i have two file : enevt0 and mice
in ts.conf : uncomment the first line.
i dont know what is ts_open. where is it? or why show me this error?
i confused :(

A:

ts_open tries to open the file saved in the variable TSLIB_TSDEVICE.
TSLIB_TSDEVICE must be the device to open to read touch inputs. In your case, it should be /dev/input/event0.
Then, ts_calibrate reads the first line in ts.conf to get the module_raw xxx. Check that your plugin folder (/usr/local/tslib/lib/ts) contains the plugin you give to module_raw.


Q:

Image value was null when posted to controller

in controller image comes null i tried this code but it did not work
function bindForm(dialog) {

$("form", dialog).submit(function () {
    var formdata = new FormData($('form').get(0));
    $.ajax({
        url: "/Books/Create",
        type: "POST",
        dataType: "JSON",
        data: formData,
        contentType: false,
        processData: false,
        success: function (result) {
            if (result.success) {
                $("#myModal").modal("hide");
                location.reload();
            } else {
                $("#myModalContent").html(result);
                bindForm();
            }
        }
    });
    return false;
});
}

A:

$(function () {

    $.ajaxSetup({ cache: false });

    $("a[data-modal]").on("click", function (e) {
        $("#myModalContent").load(this.href, function () {

            $("#myModal").modal({
                keyboard: true
            }, "show");

            bindForm(this);
        });

        return false;
    });
});

function bindForm(dialog) {

    $("#crtForm", dialog).submit(function () {
        var myform = document.getElementById("crtForm");
        var fdata = new FormData(myform);
       $.ajax({
            url: this.action,
            data: fdata,
            cache: false,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (result) {
                if (result.success) {
                    $("#myModal").modal("hide");
                    location.reload();
                } else {
                    $("#myModalContent").html(result);
                    bindForm();
                }
            }
        });
        return false;
    });
}


Q:

xml validation error

I have xml file like this
<?xml version="1.0" encoding="UTF-8"?>
<specification xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file://Desktop/normal.xsd">
  <university>
    <refstr>bdvl_te_skrm_stc</refstr>
    <ref_complete_customer path="/work/bsr.xml"/>
    A0f11478
    <Area>sku</Area>
    <started>1987</started>
    <branch>
      <electronics>
        <students Nr="120" ece="ab">
          <student Name="svr" year="2010" rank="3"/>
          <student Name="bvr" year="2010" rank="1"/>
        </students>
      </electronics>
    </branch>
    <semister>
      <semister num="3"/>
      <extrainfo/>
    </semister>
    <address>
      <extrainfo> some data.
      </extrainfo>
    </address>
  </university>
</specification>

genarated xsd schema for this xml file is
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:wmh="http://www.wmhelp.com/2003/eGenerator" elementFormDefault="qualified">

<xs:element name="specification">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="university"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="university">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="refstr"/>
      <xs:element ref="ref_complete_customer"/>
      <xs:element ref="Code"/>
      <xs:element ref="Area"/>
      <xs:element ref="started"/>
      <xs:element ref="branch"/>
      <xs:element ref="semister"/>
      <xs:element ref="address"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="refstr" type="xs:string"/>

<xs:element name="ref_complete_customer">
  <xs:complexType>
    <xs:attribute name="path" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

<xs:element name="Code" type="xs:string"/>

<xs:element name="Area" type="xs:string"/>

<xs:element name="started" type="xs:string"/>

<xs:element name="branch">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="electronics"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="electronics">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="students"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="students">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="student" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="Nr" type="xs:string" use="required"/>
    <xs:attribute name="ece" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

<xs:element name="student">
  <xs:complexType>
    <xs:attribute name="Name" type="xs:string" use="required"/>
    <xs:attribute name="year" type="xs:string" use="required"/>
    <xs:attribute name="rank" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

<xs:element name="semister">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="semister"/>
      <xs:element ref="extrainfo"/>
    </xs:sequence>
    <xs:attribute name="num" type="xs:string"/>
  </xs:complexType>
</xs:element>

<xs:element name="extrainfo" type="xs:string"/>

<xs:element name="address">
  <xs:complexType>
    <xs:sequence>
      <xs:element ref="extrainfo"/>
    </xs:sequence>
  </xs:complexType>
</xs:element>

</xs:schema>

but when I validate this type of xml it gives error like this
"element university{} has invalid structure for schema definition. this error showing at "address element" in the university node."
I am not able to rectify this error, can any one tell me how to modify this error.What should I change in the schema. when I validate schema it has no errors.
Thanks in advance.

A:

If I run your XML through validation with the provided XML Schema, I don't see any problem with the address element. However, in your schema the semister element definition refers to itself. Since it doesn't specify minimal occurrences, the default is gonna be 1. This effectively creates an infinitely recursive requirement. Consider changing your XML Schema like this...
<xs:element name="semister">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="semister" minOccurs="0"/>
            <xs:element ref="extrainfo" minOccurs="0"/>
        </xs:sequence>
        <xs:attribute name="num" type="xs:string"/>
    </xs:complexType>
</xs:element>

Or whatever seems like an appropriate constraint that doesn't force an infinite recursion.


Q:

Adding rows and cells into TableLayout

How can I do the following:

Create a row in a TableLayout programmatically
Create three cells in the row
Add arbitrary text in each cell

Thanks for your help!

A:

Try this..
TableLayout tableLayout = new TableLayout(this);
          tableLayout.setStretchAllColumns(true);
          tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.FILL_PARENT));
          tableLayout.setWeightSum(3);

          for (int i = 0; i < 3; i++) {
              TableRow tableRow = new TableRow(this);
              tableRow.setGravity(Gravity.CENTER);
              tableRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT, 1.0f));

              for (int j = 0; j < 3; j++) {
                  TextView button = new TextView(this);
                  final int buttonNumber = (j + i * 4);
                  button.setText("" + buttonNumber);
                  button.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.FILL_PARENT));

                  tableRow.addView(button);
              }
              tableLayout.addView(tableRow);
          }

          main_lay.addView(tableLayout);


Q:

What is the purpose of flutter testing?

All I am aware of is that flutter testing involves the aircraft shaking violently. How is a flutter test performed and what is its purpose?

A:

Flutter is a phenomenon that can occur when a structure is subjected to aerodynamic forces. It occurs not only in aircraft but also for example in buildings, power lines, road signs and bridges. Flutter is an oscillation caused by interaction of aerodynamic forces, structural elasticity and inertial effects.
Perhaps the best known example of flutter is the bridge over the Tacoma Narrows ('Gallopin' Gertie')  that collapsed due to flutter in gale force winds.

Flutter in aircraft causes the wings and / or stabilizers to oscillate.
When the airspeed increases the energy added in each oscillation to the structure by the aerodynamic forces increases. At some speed the damping of the structure may be insufficient to absorb the energy increase from the aerodynamic loads and the amplitude of the harmonic oscillations will grow until the structure breaks.
A flutter test is performed to determine what speed flutter occurs yet is still damped. Theoretically an aircraft should be able to stay structurally intact up to the design dive speed ($V_d$) which is at least 1.4 times the design cruise speed. In flight tests, the $V_d$ is not always demonstrated as this is very risky since there would not be any margin from breaking up. The maximum speed is slowly increased in subsequent flight tests with careful data analyses in between up to a point where the test team decides that it is no longer safe to continue. This establishes the maximum demonstrated dive speed ($V_{df}$); the published maximum operating speed ($V_{mo}$) and never-exceed speed ($V_{ne}$) are well below $V_{df}$ to give margin from disaster.
This video shows flutter in a Hawker 800. The incident occurred not during testing but was caused by inadequate fitting of the ailerons(FAA PDF).

A:

Aeroelastic flutter is a dynamic instability of an elastic structure where there is feeding between the deformation of the structure and the force provided by the aerodynamics.
Is a very dangerous condition where the vibration on the structure keeps growing and so the stress over it, endangering safe flight. It is a condition that needs to be completely avoided in a commercial flight.
Airplane manufacturers need to provide information to airlines of the operation envelope of the airplane, and part of that information is to include region of flutter to be avoided (or maximum time on it).
For providing such information manufacturers predict using internal methods (usually simulation) the flutter speed for each condition, but certification authorities request that a physical test is perform to detect the flutter velocity which will be the final speed provided in the airplane manuals.
How is made? Taking an specific airplane weight the flight test pilots approach steadily step by step to the flutter speed until certain level of vibration is obtained, determining the final airplane flutter speed.


Q:

Rewrite file with 0's. What am I doing wrong?

I want rewrite file with 0's. It only write a few bytes.
My code:
int fileSize = boost::filesystem::file_size(filePath);

int zeros[fileSize] = { 0 };

boost::filesystem::path rewriteFilePath{filePath};
boost::filesystem::ofstream rewriteFile{rewriteFilePath, std::ios::trunc};
rewriteFile << zeros;

Also... Is this enough to shred the file? What should I do next to make the file unrecoverable?
EDIT: Ok. I rewrited my code to this. Is this code ok to do this?
int fileSize = boost::filesystem::file_size(filePath);

boost::filesystem::path rewriteFilePath{filePath};
boost::filesystem::ofstream rewriteFile{rewriteFilePath, std::ios::trunc};

for(int i = 0; i < fileSize; i++) {
    rewriteFile << 0;
}

A:

There are several problems with your code.

int zeros[fileSize] = { 0 };
You are creating an array that is sizeof(int) * fileSize bytes in size. For what you are attempting, you need an array that is fileSize bytes in size instead. So  you need to use a 1-byte data type, like (unsigned) char or uint8_t.
But, more importantly, since the value of fileSize is not known until runtime, this type of array is known as a "Variable Length Array" (VLA), which is a non-standard feature in C++. Use std::vector instead if you need a dynamically allocated array.
boost::filesystem::ofstream rewriteFile{rewriteFilePath, std::ios::trunc};
The trunc flag truncates the size of an existing file to 0.  What that entails is to update the file's metadata to reset its tracked byte size, and to mark all of the file's used disk sectors as available for reuse. The actual file bytes stored in those sectors are not wiped out until overwritten as sectors get reused over time. But any bytes you subsequently write to the truncated file are not guaranteed to (and likely will not) overwrite the old bytes on disk.  So, do not truncate the file at all.
rewriteFile << zeros;
ofstream does not have an operator<< that takes an int[], or even an int*, as input. But it does have an operator<< that takes a void* as input (to output the value of the memory address being pointed at). An array decays into a pointer to the first element, and void* accepts any pointer.  This is why only a few bytes are being written.  You need to use ofstream::write() instead to write the array to file, and be sure to open the file with the binary flag.

Try this instead:
int fileSize = boost::filesystem::file_size(filePath);

std::vector<char> zeros(fileSize, 0);

boost::filesystem::path rewriteFilePath(filePath);
boost::filesystem::ofstream rewriteFile(rewriteFilePath, std::ios::binary);
rewriteFile.write(zeros.data()/*&zeros[0]*/, fileSize);

That being said, you don't need a dynamically allocated array at all, let alone one that is allocated to the full size of the file. That is just a waste of heap memory, especially for large files.  You can do this instead:
int fileSize = boost::filesystem::file_size(filePath);

const char zeros[1024] = {0}; // adjust size as desired...

boost::filesystem::path rewriteFilePath(filePath);
boost::filesystem::ofstream rewriteFile(rewriteFilePath, std::ios::binary);

int loops = fileSize / sizeof(zeros);
for(int i = 0; i < loops; ++i) {
    rewriteFile.write(zeros, sizeof(zeros));
}
rewriteFile.write(zeros, fileSize % sizeof(zeros));

Alternatively, if you open a memory-mapped view of the file (MapViewOfFile() on Windows, mmap() on Linux, etc)  then you can simply use std::copy() or std::memset() to zero out the bytes of the entire file directly on disk without using an array at all.

Also... Is this enough to shred the file?

Not really, no. At the physical hardware layer, overwriting the file just one time with zeros can still leave behind remnant signals in the disk sectors, which can be recovered with sufficient tools. You should overwrite the file multiple times, with varying types of random data, not just zeros.  That will more thoroughly scramble the signals in the sectors.


Q:

What do the last two fields in fstab mean?

The last two fields on each line in fstab (dump, pass) is some numbers, usually 0. What does these numbers mean?
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
proc            /proc           proc    nodev,noexec,nosuid 0       0
UUID=030ccf66-5195-4835-ba3e-f5d7a5403c05 /               ext4    errors=remount-ro 0       1

A:

Copy/paste from man fstab:

The fifth field, (fs_freq),  is  used  for  these  filesystems  by  the
  dump(8)  command  to determine which filesystems need to be dumped.
  If the fifth field is not present, a value of zero is  returned  and
  dump will assume that the filesystem does not need to be dumped.
The  sixth field, (fs_passno), is used by the fsck(8) program to determine
  the order in which filesystem checks are done at reboot
  time.  The root  filesystem  should  be specified with a fs_passno of 1, and
  other filesystems should have a fs_passno of 2.  Filesystems within  a
  drive will  be checked sequentially, but filesystems on different drives
  will be checked at the same time to utilize  parallelism  available  in
  the hardware.   If  the sixth field is not present or zero, a value of
  zero is returned and fsck will assume that the filesystem does not
  need to be checked.

A:

Simple blockhead answer is , first field determines if it should be dumped, second field determines if it should be checked during startup and in what sequence. Check the manual for the rest!


Q:

php: swiftmailer questions

i've just installed swiftmailer for php and i'm having some questions:

there's issue with german umlauts - i'm getting wrong characters how do i need to encode the message body properly?
is there a property in swiftmailer for getting the server log (the dialog when sending mail for debugging)
how can i set the property if the mail is plain text or html?

thanks

A:

set plain text or html like this
$message = Swift_Message::newInstance($subject)
->setFrom(...)
->setTo(....)
->setBody($message, 'text/html')
;

for plain text change to setBody($message, 'text/plain')
Alternatively set it with:

$message->setContentType('text/html')

or

$message->setContentType('text/plain')

To get umlauts working try this:

$message->setContentType('text/plain;
  charset=UTF-8')

change plain to html for html emails obviously
You can also set it globally with:

Swift_Preferences::getInstance()->setCharset('UTF-8');

However this is default so it is strange you are having problems. Is the problem with the message body or subject? If it is with the subject try:

$subject =
  '=?UTF-8?B?'.base64_encode($subject).'?=';

A:

there's issue with german umlauts - i'm getting wrong characters how do i need to encode the message body properly?

You can set the character set using the third parameter of setBody or addPart.  You'll want to make sure that the passed string is already in that character set.

is there a property in swiftmailer for getting the server log (the dialog when sending mail for debugging)

You should be able to do this by enabling one of the logging plugins.

how can i set the property if the mail is plain text or html?

You can define the HTML-yness of a message by passing the content type to setBody or addPart.
I highly recommend that you browse through the comprehensive online documentation for more information on these topics.


Q:

C weird modulo operation

So I've got this thing where I got the following operation:
NSInteger articleIndex = self.featuredArticlesCounter % self.featuredArticles.count;

In this case self.featuredArticlesCounter is -1 and
self.featuredArticles.count is 10
So it's basically -1 % 10, which should be 9, but the result is 5 instead.
Google says it's 9.
And if I do NSInteger articleIndex = -1 % 10; it gives me -1
I've tried casting the NSUInteger from count to NSInteger and that doesn't work.
I've tried inserting brackets all over the place but that didn't work either.
I've since switched to using ((-1 % 10) + 10) % 10.
But I'm still wondering what the deal is here.
Any ideas?
Edit:
featuredArticlesCounter is a signed int
self.featuredArticles.count is an unsigned int

A:

featuredArticlesCounter is evidently an unsigned int. When you thought you set it to -1, you really set it to 2**32 - 1 (~0). That number mod 10 is 5. (Apparently, 2**(8k)-1 % 10 is 5, so it doesn't matter what size unsigned it actually is)
As for why -1 % 10 is -1, I believe in C the mod of negative numbers is implementation-defined, but in this case (as in Java), it is defined such that x / y + x % y == x. If you plug negative numbers in, -1 / 10 + -1 % 10 = -1 -> -1 % 10 = -1.

A:

Perhaps the hardware (or software?) treats the number as an unsigned integer:

-1 == 0xFFFFFFFF (in two's compliment encoding)
0xFFFFFFFF == 4294967295 (assuming the raw data is an unsigned integer)
4294967295 % 10 == 5 (trivial by observation of last digit)

This would be my best guess.


Q:

RTOS: Micrium uCOS vs Mentor Graphics Nucleus

We're working on a wearable IoT device, and I'm hoping for some guidance on  the common commercially available RTOS, such as what's the difference between the two. As of current I'm leaning toward Mentor (their marketing and easily available info on their website is very grabbing), but my associate is insisting on uCOS. I believe uCOS is more popular, and has a lower minimum footprint but I'm not entirely concerned about these.
Nucleus looks like it has more modules/stacks ready to go, am I wrong?
Furthermore, someone convinced me that have a POSIX layer is important, which Nucleus seems to natively have. Does this make sense?
Some of the stuff we need is, i2c; M4, M0 support; USB OTG; BLE (CC2564)

A:

I'm Jean Labrosse, I wrote the uC/OS series of kernels (uC/OS in 1992, uC/OS-II in 1998 and uC/OS-III in 2008).
There are quite a lot of things to like and in fact prefer over Nucleus.  For one thing, I wrote a book that accompanies each one of the versions (I'd recommend you look at uC/OS-III).  We have 7 variations of the book:
uC/OS-III for the RX62N, STM32, Kinetis, SH7216, Stellaris, NXP and Infineon.  Each book is about 950 pages and is available either for FREE in PDF format or available as a hard cover book:
http://micrium.com/books/ucosiii/

Each book explains the internals of uC/OS-III and provides examples using one of the above 7 MCUs.
You can also download the full source for uC/OS-III from our website so you can see for yourself the level of quality that went into the code.
http://micrium.com/downloadcenter/micrium-source-code/

If you need more than just a kernel, you will be happy to hear that we also have a full suite of protocols tasks: TCP/IP, USB-Host, USB-Device, Modbus, CANbus, File System and GUI so, the kernel is just one part of our offering.
In fact, similar to the uC/OS-III books, we also have 5 flavors of our uC/TCP-IP books:
http://micrium.com/books/uctcpip/

We support just about every MCU and CPU architectures available on the market.
BTW, in early 2015, we have been named the MOST popular RTOS on the planet by UBM (United Business Media) ... assuming you combine uC/OS-II and uC/OS-III).  In fact, we were some 10x more popular than Nucleus!

I urge you to check out our website (www.micrium.com) as well as a tool that can be incredibly useful called uC/Probe which works with or without an RTOS and in fact, any RTOS even non-Micrium.


Q:

php how to get image from url without knowing extension

I would like to retrieve an image from a given url, i have the filename but the issue i have is that the extension is unknown. It could be either, jpg, gif or png.
This is how i have approached it but doesnt seem to be working:
$extensions = array('jpg', 'png', 'gif');
    foreach ($extensions as $ext) {
        if (file_exists('https://mytestimage.com/products/3c763dce-666b-4ba9-a05a-cca846391aea/thumb.' . $ext)) {
            echo 'Found filename.' . $ext;
            break;
        }
    }

Any suggestions?

A:

Since the file is off-site, check if the URL exists instead.
$file = 'http://example.com/image.jpg';
$fileHeaders = @get_headers($file);
if( $fileHeaders[0]=='HTTP/1.1 404 Not Found')
{
    // File doesn't exist
}
else
{
    // File exists
}

You can apply this logic to your loop for the different extensions.
References: PHP.net & SO


Q:

How to make RequiredFieldValidator disappear and then appear?

I want the required  field validator to become only visible whenever there is an error..not all the time.. How can i achieve so?
<asp:RequiredFieldValidator
    runat="server"
    ControlToValidate="Editor1"
    ErrorMessage="fffffff"
    ForeColor="#CC0000"
    Display="Dynamic" />

The error message appears as soon as I run the page..I want it to appear whenever there is an error..When the field is empty!!

A:

The only cause of your problem in your current page is that, in the page Load event, somewhere Page.Validate() is called and you need to to check that.
I have tested this sample at my end and the validator is not fired to me at page load.
Can you try this in a separate new Page?
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"
ErrorMessage="fffffff"
ForeColor="#CC0000"
Display="Dynamic" />
    <asp:Button ID="Button1" runat="server" Text="Button" />

If you check the above mentioned example, it will not fire Validator on page load, but you can add this code, and you will find, the validator is fired on page load..
protected void Page_Load(object sender, EventArgs e)
{
    Page.Validate();
}

Please note, I have tested both scenarios on the new page, just try it and you will understand the problem.


Q:

AVaudioPlayer not working and mp3 located in Compile Bundle

I have mp3 file in Copy Bundle Resources and this my code
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"mymp3" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
[player prepareToPlay];

but it doesn't play what is the problem ?
FYI: AVFoundation.framework is included.
Thanks

A:

Try adding
[player prepareToPlay];
[player play]; //missing play action

If that doesn't help try this
@interface AudioPlayerViewController : UIViewController {
    AVAudioPlayer *audioPlayer;
}

//in your *.m file
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/mymp3.mp3", [[NSBundle mainBundle] resourcePath]]];

        NSError *error;
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.volume = 1.0; // 0.0 - no volume; 1.0 full volume

        if (audioPlayer == nil)
            NSLog([error description]);
        else
            [audioPlayer play];


Q:

Looping through a array of objects with nested arrays

Given this simple example:
const testdata = [
  {
    id: "001",
    name: "Bob",
    comments: [
      {
        id: "01",
        text: "Hello World"
      },
      {
        id: "02",
        text: "Hello Mars"
      }
    ]
  }
];

I would like to output all the comments for this object:
With this I get the id and the name
testdata.map(i => { console.log(i.id + i.name)});

What is the best way to output the nested array that holds the comments?

A:

Get an array of comments arrays with Array.map(), then flatten by spreading into Array.concat():

const testdata = [{"id":"001","name":"Bob","comments":[{"id":"01","text":"Hello World"},{"id":"02","text":"Hello Mars"}]},{"id":"002","name":"Sara","comments":[{"id":"03","text":"Hello Jupiter"},{"id":"04","text":"Hello Moon"}]}];

const comments = [].concat(...testdata.map((d) => d.comments));

console.log(comments);


Q:

Method of characteristics beyond the Lipschitz setting

I have come across the following easy-looking problem that is driving me mad.
I have a family of measures (on the real line $\mathbb R$) $\{\mu_t\}_{t>0}$ which is uniformly bounded (the measures being possibly signed). I know that $\mu_0 = 0$ and that for every $\varphi \in C_c^\infty([0,+\infty) \times \mathbb R)$ it holds
$$
\iint_{(0,+\infty) \times \mathbb R} \left[ \partial_t \varphi(t,x)- \sqrt[3]{x} \partial_x \varphi(t,x) \right]  d\mu_t(x)dt = 0.
$$

Question. Does $\mu_t \equiv 0$ for every $t>0$?

At the beginning I thought it was an easy consequence of the method of characteristics, but the point is that the (1d-)vector field $f(x) = -\sqrt[3]{x}$ is not Lipschitz, so the standard theory does not apply. Nevertheless, I know that the characteristics of $f$ are unique for every initial data (for $t>0$, am I right?). Do you know any references showing the extension of the method of characteristics to this setting?

A:

Let us show that the condition ${\mu_0}|_{x>0} = 0$ implies that ${\mu_T}|_{x>0} = 0$ (for a.e. $T>0$). Let $\omega \in C_0^\infty(\mathbb R)$ and $\delta\in (0,1)$ be such that $\omega(\xi) = 0$ for all $\xi\le \delta$. Define
$$
\varphi(t,x):=
\begin{cases}
0, & \frac{3}{2} x^{\frac{2}{3}} + t - T \le \delta\\
\omega(\frac{2}{3}(\frac{3}{2} x^{\frac{2}{3}} + t - T)^{\frac{3}{2}}),
& \frac{3}{2} x^{\frac{2}{3}} + t - T > \frac{1}{2}\delta
\end{cases}
$$
(clearly this definition is consistent in the intersection of the cases above). Note that $\varphi$ is smooth, compactly supported (in $[0,T]\times \mathbb R$) and $\partial_t \varphi + f \cdot \partial_x \varphi = 0$,
so from the equation for $\mu_t$ we get $0=\int_{\mathbb R} \varphi(T, x) \, d\mu_T(x) = \int_{\mathbb R} \omega(x)\, d\mu_T(x)$. By arbitrariness of $\omega$ it follows that $\mu_T|_{x>0} = 0$.
In a similar fashion one should be able to show that $\mu_0|_{x<0}=0$ implies that $\mu_T|_{x<0} = 0$.
Therefore $\mu_t$ can only have the form $\mu_t = g(t) \, \delta_0$, and by the equation for $\mu_t$ we get $g'(t)=0$.


Q:

CAKEPHP - MSSQL Error When Filtering Records by Distant Association

So I'm a bit stuck on the above and I keep getting an sql server error. Yes I'm using mssql server :| - not my database.
A little background, my relationships concerned look like this:
AssetMaintenanceRecord->(belongs to)->Asset->(belongs to)->Project->(has one)->ProjectManager
(note ProjectManager is like an alias model for a personnel table. The project table has an id for ProjectManager which is just the personnel id.
So I'm trying to do a simple filter whereby I select all the AssetMaintenanceRecords by a search on ProjectManager.
The related index function in AssetMaintenanceRecordsController.php looks like:
public function index() {
        $conditions = NULL;
        if (isset($this->params['url']['report']) && $this->params['url']['report']  == 'open') {
            $conditions[] = array('CompletedDate' => NULL);
        }

        if (isset($this->params['url']['report']) && $this->params['url']['report'] == 'notified') {
            $conditions[] = array('NotifiedDate BETWEEN ? AND ?' => array(date('M d Y g:iA', strtotime($this->params['url']['datefrom'])), date('M d Y g:iA', strtotime($this->params['url']['dateto']))));
        }

        if (isset($this->params['url']['report']) && $this->params['url']['report'] == 'completed') {
            $conditions[] = array('CompletedDate BETWEEN ? AND ?' => array(date('M d Y g:iA', strtotime($this->params['url']['datefrom'])), date('M d Y g:iA', strtotime($this->params['url']['dateto']))));
        }

        if (isset($this->params['url']['project'])) {
            $conditions[] = array('Asset.aCurrProject' => $this->params['url']['project']);
        }

        if (isset($this->params['url']['ptCode']) && $this->params['url']['ptCode'] != NULL) {
            $conditions[] = array('Asset.ptCode' => $this->params['url']['ptCode']);
        }

        if (isset($this->params['url']['asset']) && $this->params['url']['asset'] != NULL) {
            $conditions[] = array('Asset.aFullCode' => $this->params['url']['asset']);
        }

        if (isset($this->params['url']['pm']) && $this->params['url']['pm'] != NULL) {
            $pm_search_terms = explode(' ', $this->params['url']['pm']);
            foreach($pm_search_terms as $pm_search_term) {
                $conditions[] = array(
                                'OR' => array(
                                        'ProjectManager.PerGivenName LIKE' =>'%'.$pm_search_term.'%',
                                        'ProjectManager.PerSurname LIKE' =>'%'.$pm_search_term.'%',
                                  )
                          );
            }
        }

        $this->paginate['AssetMaintenanceRecord'] = array(
            'contain' => array(
              'Asset' => array(
                'Project' => array(
                    'ProjectManager'
             ))
            ),
          'order' => 'CompletedDate ASC',
          'limit' => 10
        );

        $planttype = $this->AssetMaintenanceRecord->Asset->PlantType->find('list');
        $this->set(compact('planttype'));
        $this->AssetMaintenanceRecord->recursive = -1;
        $this->set('records', $this->paginate('AssetMaintenanceRecord', $conditions));
    }

Without the ProjectManager filter it works fine and I can echo out the ProjectManager array etc. but when I enter in a search term I get this error:

The multi-part identifier "ProjectManager.PerSurname" could not be bound.

The executed sql looks like:
'SELECT TOP 10 [AssetMaintenanceRecord].[MtceRegID] AS [AssetMaintenanceRecord_0], [AssetMaintenanceRecord].[AssetID] AS [AssetMaintenanceRecord_1], CAST(CAST([AssetMaintenanceRecord].[MtceRegNote] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_2], [AssetMaintenanceRecord].[POno] AS [AssetMaintenanceRecord_3], CAST(CAST([AssetMaintenanceRecord].[NotifiedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_4], CAST(CAST([AssetMaintenanceRecord].[CompletedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_5], [AssetMaintenanceRecord].[MtceRegTitle] AS [AssetMaintenanceRecord_6], CAST(CAST([AssetMaintenanceRecord].[CreatedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_7], [AssetMaintenanceRecord].[CreatedUserID] AS [AssetMaintenanceRecord_8], CAST(CAST([AssetMaintenanceRecord].[ModifiedDate] AS VARCHAR(8000)) AS TEXT) AS [AssetMaintenanceRecord_9], [AssetMaintenanceRecord].[ModifiedUserID] AS [AssetMaintenanceRecord_10], [Asset].[aID] AS [Asset_11], [Asset].[ptCode] AS [Asset_12], [Asset].[aNo] AS [Asset_13], [Asset].[aFullCode] AS [Asset_14], [Asset].[aDesc] AS [Asset_15], [Asset].[aMake] AS [Asset_16], [Asset].[aModel] AS [Asset_17], [Asset].[aSerialNo] AS [Asset_18], [Asset].[aRegNo] AS [Asset_19], CAST(CAST([Asset].[aRegExpDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_20], [Asset].[aActive] AS [Asset_21], [Asset].[aIncAssetRpt] AS [Asset_22], [Asset].[aIncFinanceRpt] AS [Asset_23], [Asset].[aIsTrailer] AS [Asset_24], [Asset].[aIsSurveyEquip] AS [Asset_25], [Asset].[aCostedItem] AS [Asset_26], [Asset].[aCostedPeriod] AS [Asset_27], [Asset].[aWarrantyPeriod] AS [Asset_28], [Asset].[aPONo] AS [Asset_29], CAST(CAST([Asset].[aPODate] AS VARCHAR(8000)) AS TEXT) AS [Asset_30], CAST(CAST([Asset].[aPOCostExGst] AS VARCHAR(8000)) AS TEXT) AS [Asset_31], [Asset].[aQtyStock] AS [Asset_32], [Asset].[aQtyInUse] AS [Asset_33], [Asset].[aCurrProject] AS [Asset_34], [Asset].[aCurrOperator] AS [Asset_35], [Asset].[aStolen] AS [Asset_36], CAST(CAST([Asset].[aStolenDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_37], [Asset].[aWO] AS [Asset_38], CAST(CAST([Asset].[aWODate] AS VARCHAR(8000)) AS TEXT) AS [Asset_39], [Asset].[aSold] AS [Asset_40], CAST(CAST([Asset].[aSoldDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_41], CAST(CAST([Asset].[aSoldPrice] AS VARCHAR(8000)) AS TEXT) AS [Asset_42], CAST(CAST([Asset].[aNotes] AS VARCHAR(8000)) AS TEXT) AS [Asset_43], CAST(CAST([Asset].[LastModDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_44], CAST(CAST([Asset].[CreatedDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_45], [Asset].[aCat] AS [Asset_46], [Asset].[aPoliceRptNo] AS [Asset_47], [Asset].[aRelatedAssetID] AS [Asset_48], [Asset].[aRelatedAssetFullCode] AS [Asset_49], [Asset].[aPayMethod] AS [Asset_50], [Asset].[aInvoiceNo] AS [Asset_51], CAST(CAST([Asset].[aLastFuelDate] AS VARCHAR(8000)) AS TEXT) AS [Asset_52], [Asset].[aFuelType] AS [Asset_53] FROM [tbMtceRegister] AS [AssetMaintenanceRecord] LEFT JOIN [tbAsset] AS [Asset] ON ([AssetMaintenanceRecord].[AssetID] = [Asset].[aID]) WHERE [CompletedDate] IS NULL AND [Asset].[aCurrProject] IS NULL AND (([ProjectManager].[PerGivenName] LIKE '%test%') OR ([ProjectManager].[PerSurname] LIKE '%test%')) ORDER BY [CompletedDate] ASC'
Looks ok to me but I'm obviously going wrong somwhere?
Any help appreciated.
Thanks in advance.

A:

ProjectManager is not contained in FROM or JOIN Part
but used in WHERE :  OR ([ProjectManager].[PerSurname] LIKE


Q:

passing a function as an argument in python

Suppose I want to calculate the following f(f(...f(x)..) .
Basically many times function of itself.
Currently I am doing the following to achieve this result (and to return all the intermediate steps):
def iterator(function, x, n=4):
    x = float(x)
    arr = []
    for i in range(n + 1):
        arr.append(x)
        x = function(x)

    return arr

def funcM(x):
    return x / 4 + 12

and then I am passing my function funcM as an argument:
print iterator(funcM, 100, 5).
There is nothing wrong with this approach, and calculations are correct.
But is there a way to do the same without defining function funcM ?
May be passing lambda function as an argument to iterator function (Sorry if it does not make sense, I do not really know what lambda functions are).

A:

A lambda function (or more accurately, a lambda expression) is simply a function you can define on-the-spot, right where you need it. For example,
f = lambda x: x * 2

is exactly the same thing as
def f(x):
    return x * 2

And when I say exactly, I mean it -- they disassemble to the same bytecode. The only difference between the two is that the one defined in the second example has a name.
Lambda expressions become useful because creating one is not a statement, which means that, as others have already answered, you can do
print iterator(lambda x: x / 4 + 12, 100, 5)

to get precisely what you want.
The main difference between lambda expressions and regular functions, however, is that lambdas are more limited. Lambdas can only contain expressions, not statements. An expression is anything you can put on the right side of an = assignment. (if you want to get more pedantic, Python defines an expression as http://docs.python.org/2/reference/expressions.html )
What this means is a lambda expression can not assign to a variable (in fact, it can't have local variables at all, other than its parameters). It can't print (unless it calls another function that does). It can't have a for loop, a while loop, an if test (other than the ternary operator x if cond else y), or a try/except block.
If you need to do any of those, just define a regular function. In fact, any time you think you want to use a lambda, think twice. Wouldn't the code be more readable if you used a regular function? Isn't that lambda expression something you'd like to reuse somewhere else in your code?
In the end, always do what leads to the most readable and maintainable code. There is no difference between lambdas and normal functions as far as performance is concerned.

A:

Yes, you can just use lambda expressions. They are made for this.
iterator(lambda x: x/4+12, 100, 5)

Words from the docs:

Lambdas are usually used to create small, anonymous functions.
  Actually, they are just a syntatic sugar to define functions. The
  lambda expression above is exactly the same as your function, only
  without a name.

If you wish to learn more, Here is some good read:
http://www.diveintopython.net/power_of_introspection/lambda_functions.html
Why use lambda functions?