text:
Q: missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was:? When I use Spark2.0  Dataset and DataFrame to read datas ,the code is :
 def func(docs: DataFrame): RDD[(String, String)] = {
   docs.select("id", "title").map{
     case Row(id: String, title: String) => (id, title)
 }}

but the compile error is
missing parameter type for expanded function The argument types of an anonymous function must be fully known. (SLS 8.5) Expected type was: ?

and i also try the way
def func(docs: DataFrame): RDD[(String, String)] = {
   docs.select("id", "title").map{val => val match{
     case Row(id: String, title: String) => (id, title)
 }}}  but this is not work !   the error on the 'val' is :
◾missing parameter type

how can i slove this !

A: You can resolve it by using DataFrame.rdd
 // before map
 def func(docs: DataFrame): RDD[(String, String)] = {
   docs.select("id", "title").rdd.map{
     case Row(id: String, title: String) => (id, title)
 }}

// or after map
def func(docs: DataFrame): RDD[(String, String)] = {
   docs.select("_1", "_2").map{
     case Row(id: String, title: String) => (id, title)
   }.rdd
}

Note that in Spark 1.x DataFrame.map returns RDD[R], and takes function as (Row) => R.
While in Spark 2.x Dataset.map returns Dataset[U],and takes function as (T) => U.


text:
Q: Setting up proper permissions for laravel app in ubuntu I have a DigitalOcean VPS with ubuntu, I'm fairly new to web apps deployng and I'd like some advice on what would be the best way to properly set permissions on my laravel app folder so I don't have to worry about getting permissions errors.
I know about storage and cache folders and how I should give www-data read and write permissions but is there an easy way to set up all this nicely so I don't have to be changing permissions each time a new folder, file is added?
What does your initial setup looks like after say, cloning a git repository into the /var/www folder of your LEMP stack.
I know there are lots of tutorials on this but I'd like to know the more future-proof, solid way to handle this.
Thanks in advance and I'm open to all advice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get line number in code editor in vs2008?
Possible Duplicate:
How do I enable line numbers in VS2008?

how to get line number in code editor in vs2008?

A: Tools...Options...Text Editor....All Languages... Display... Line Numbers.

A: go to tool>option>text editor check 'line number'


text:
Q: Basic rails - How link_to works and replacing it with a render I am super fresh to Rails, but came across a problem I can't wrap my head around.
I have a link using the link_to helper method:
<%= link_to("Link",  {:controller => 'gitrevision_download', :project_id => @project.id, :rev => @rev}) %>

That link then takes me to a new page and invokes the gitrevision_download controllers index method. All I want to do is render that index template within the template I'm already in, rather then as a link.
Edit: Just realised this function isn't working how I thought it did  It's displaying the data after the link is called, and the routes handler must be redirecting me to the correct controller.
So what I need is to render the index view from that controller, from another controller. Is that bad practice?

A: The best place to go for explanations of Rails functionality is the documentation; it's really surprisingly well done!
To answer your question more directly:

*

*The first parameter, as you've likely deduced, is the name of the link.

*The second parameter is passed to Rails' URL generators to create the destination of the link. By passing a hash, you're instructing Rails to generate a URL for a particular controller and action inside that controller. You could also pass a named URL helper (like submissions_path) instead.

*The third parameter is HTML options and is added directly to the element -- things like assigning classes and titles, and will show up as <a class="specified-classes" title="specified-title" ...> and so on.


text:
Q: nuxt-purgecss with mdb-vue not working in production I am attempting to implement nuxt-purgecss into my nuxt project, I am also using mdb-vue(Material Design Bootstrap).
It seems to be working fine in dev,..
but after I build with 'nuxt generate' or 'npm run generate'
I have tried with both 'with-nuxt-manual' and 'with-nuxt-module' from
https://github.com/FullHuman/purgecss/tree/master/examples
both give the same results, css is purged in dev, but not after nuxt generate
here is my manual mode config..
nuxt-config.js
import path from 'path'
import PurgecssPlugin from 'purgecss-webpack-plugin'
import glob from 'glob-all'

export default {
  mode: 'universal',
  dev: process.env.NODE_ENV !== 'production',
  css: ['bootstrap-css-only/css/bootstrap.min.css', 'mdbvue/build/css/mdb.css'],

  modules: [
    '@nuxtjs/pwa',
    '@nuxtjs/eslint-module',
    'nuxt-fontawesome',
    'bootstrap-vue/nuxt'
  ],
  build: {
    extractCSS: true,
    extend(config, { isDev, isClient, loaders: { vue } }) {
      if (isClient) {
        vue.transformAssetUrls.img = ['data-src', 'src']
        vue.transformAssetUrls.source = ['data-srcset', 'srcset']
      }
      if (!isDev && isClient) {
        // Remove unused CSS using purgecss. See https://github.com/FullHuman/purgecss
        // for more information about purgecss.
        config.plugins.push(
          new PurgecssPlugin({
            paths: glob.sync([
              path.join(__dirname, './pages/**/*.vue'),
              path.join(__dirname, './layouts/**/*.vue'),
              path.join(__dirname, './components/**/*.vue')
            ]),
            whitelist: ['html', 'body']
          })
        )
      }
    },
    transpile: ['mdbvue']
  }
}

I can not seem to find any documentation for configuring webpack for bootstrap/mdb with purgecss.

A: I have I solved the problem, I am pretty sure pwa and cached files were giving me confusing results.
With my current working nuxt.config.js(see below)

*

*I test in dev mode "npm run dev" and css is not purged(what I want).

*then I run "npm run generate" and test locally, css is purged(what I want).

*then I push to github dev branch, netlify builds and deploys a staging subdomain, I test there,.. css is purged(what I want).

*finally I merge the dev branch with master, and push to github, netlify builds and deploys to production, I test there css is purged(what I want).

  build: {
    extractCSS: process.env.NODE_ENV === 'production',
    extend(config, { isDev, isClient, loaders: { vue } }) {
      if (isClient) {
        vue.transformAssetUrls.img = ['data-src', 'src']
        vue.transformAssetUrls.source = ['data-srcset', 'srcset']
      }
      if (isDev && isClient) {
        config.plugins.push(
          new PurgecssPlugin({
            paths: glob.sync([
              path.join(__dirname, './pages/**/*.vue'),
              path.join(__dirname, './layouts/**/*.vue'),
              path.join(__dirname, './components/**/*.vue')
            ]),
            whitelist: ['html', 'body']
          })
        )
      }
    },
    transpile: ['mdbvue']
  }


text:
Q: Why did the Dementors fight for the Dark Lord in the Battle of Hogwarts? During the Battle of Hogwarts, the Dementors fought for the Dark Lord. Why was this the case if the Dementors worked for the Ministry of Magic?

A: The Dementors had long since abandoned the Ministry.
The Dementors had already been (openly) loyal to Voldemort for two years by the time the Battle of Hogwarts took place. They joined Voldemort straight after his return had been publically acknowledged by the Ministry.

"It is great regret that I must confirm that the wizard styling himself Lord - well, you know who I mean - is alive and among us again," said Fudge, looking tired and flustered as he addressed reporters. "It is with almost equal regret that we must report the mass revolt of the Dementors of Azkaban, who have shown themselves adverse to continuing in the Ministry's employ. We believe the Dementors are currently taking direction from Lord - Thingy."
(Order of the Phoenix, Chapter 38, The Second War Begins).

Voldemort had planned this move since his return in Goblet of Fire.

...when Azkaban is broken open, the Lestranges will be honoured beyond their wildest dreams. The Dementors will join us...they are our natural allies...
(Goblet of Fire, Chapter 33, The Death Eaters).

Even Dumbledore foresaw that the Dementors had much more in common with the Death Eaters than with the Ministry.

"The first and most essential step is to remove Azkaban from the control of the Dementors -"
  "Preposterous!" shouted Fudge again. "Remove the Dementors! I'd be kicked out of office for suggesting it! Half of us only feel safe in our beds at night because he know the Dementors are standing guard at Azkaban!"
  "The rest of us sleep less soundly in our beds, Cornelius, knowing that you have put Lord Voldemort's most dangerous supporters in the care of creatures who will join him the instant he asks him!" said Dumbledore. "They will not remain loyal to you, Fudge! Voldemort can offer them much more scope for their powers and their pleasures than you can!"
(Goblet of Fire, Chapter 36, The Parting of the Ways).

Since Voldemort allowed the Dementors free reign to drain the happiness and hope out of everyone (Muggles and wizards, criminals and the innocent alike), the Dementors happily joined him the moment his return was openly declared by the Ministry.


text:
Q: How to deal with all data as non-outliers for boxplot in R? I am new to R project and have to use boxplot function to plot the data.
When I use it, boxplot automatically deals with some points as outliers.
But for my case, every points are not outliers. I just wanted to show min/max, 25/75 percentile and median. So I've searched for boxplot function and haven't found an option that deals every points as non-outliers.
Is there any way to do what I want?

A: You should try using range=0. For example:
x <- rlnorm(1000)
boxplot(x, range = 0)


text:
Q: Can't make a VirtualHost working with ipv6 I have a website served by apache. It works with IPv4 but not with IPv6. I have a 500 error.
Here is my ports.conf file :
# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default.conf

Listen 80
NameVirtualHost *:80

<IfModule ssl_module>
        Listen 443
</IfModule>

<IfModule mod_gnutls.c>
        Listen 443
</IfModule>

And my VHost :
<VirtualHost *:80 [::]:80>
DocumentRoot "/var/www/html/mysite.ca/www.mysite.ca"
ServerName mysite.ca
<Directory "/var/www/html/mysite.ca/www.mysite.ca">
allow from all
Options +Indexes
</Directory>
ServerAlias www.mysite.ca
</VirtualHost>

When I do netstat-tlnpt, I have this :
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      3577/master
tcp        0      0 0.0.0.0:453             0.0.0.0:*               LISTEN      4484/perl
tcp        0      0 0.0.0.0:360             0.0.0.0:*               LISTEN      3254/sshd
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      3307/mysqld
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      2923/vsftpd
tcp6       0      0 ::1:25                  :::*                    LISTEN      3577/master
tcp6       0      0 :::443                  :::*                    LISTEN      7240/apache2
tcp6       0      0 :::360                  :::*                    LISTEN      3254/sshd
tcp6       0      0 :::80                   :::*                    LISTEN      7240/apache2

It seems apache is already listening for IPv6 address.
I tried to add :
Listen [::]:80
Listen [::]:443

To my port file but I have this result when I restart apache :
(98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
(98)Address already in use: AH00072: make_sock: could not bind to address [::]:443

I tried to change wildcars by static address and I have the same issue.
I have other websites that works with IPv6 on the same server. This is the only that doesn't work.
What can I do ?

A: Make sure apache2 is fully being shutdown. Possibly whatever is managing services doesn't know about a copy manually launched in the background. (run netstat when it should be stopped and make sure nothing's still listening)
Depending on your apache version, you may not need NameVirtualHost either. See https://httpd.apache.org/docs/current/upgrading.html
If you're getting a 500 error, then something is definitely listening on the port and responding. This should be logged in your error.log. If not, you may need to adjust logging options to include it. I don't see anything indicating whether you're running apache2.2 or 2.4 and the logging configuration is different between the two.
EDIT: See this page about LogLevel https://httpd.apache.org/docs/2.4/mod/core.html#loglevel

A: Make sure you have Listen once per port per IP per complete config per server, maybe comment out the ones you're aware of until it starts without complaining and see if it's still starting on port 80/443
for ipv6 and ipv4, you only need
listen 80
listen 443 https

find /etc/httpd/ | xargs grep -sniH "listen"

A: I see this in your netstat output:

tcp6       0      0 :::443                  :::*                    LISTEN      3254/sshd

That means you have a ssh process listening on your port 443 in IPv6 and indeed Apache cant bind to that port:

(98)Address already in use: AH00072: make_sock: could not bind to address [::]:443


text:
Q: Join the link to download a pdf file view and url in Django I need to associate a link such as "Protocol" and then drive to download a PDF file. Is giving 404 error in mapping the url and would like some help regarding view.
url-Protocol:
urlpatterns += patterns('suap.views',(r'^manuais/$', 'manuais'),
                       (r'^static/manuais/manual_protocolo.pdf$', 'manual_pdf'))

view-Protocol:
def manual_pdf(request):
    response = HttpResponse(extension='.pdf')
    response['Content-Disposition'] = 'attachment; filename="manual_protocolo.pdf"' %manual_protocolo
    return response

A: you have to use mod x_sendfile in your server. see
also make a small modification to the code
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str('manual_protocolo.pdf')
response['X-Sendfile'] = "/path/to/manual_protocolo.pdf"
return response


text:
Q: Rewrite rules not working: is a regoluar expression or another language? I'm using Rack Rewrite to make some 301 redirect from two website. This is the gem rack rewrite and in documentation there is this example:
rewrite %r{/wiki/John_Trupiano(\?.*)?}, '/john$1'

I try to write my redirect using regular expression:
r301      %r{/(?<=prodotti\/)?.*(?=\/)/},     '/prodotti/$1'

But is doesn't work.
Basically I have some url /prodotti/1996/HTC-One-M8.html and I need a 301 redirect to /prodotti/1996
Update
In my website I also have some other routes like
/prodotti/latest, /prodotti/1996, /prodotti/all
I need something that match the ID between the two / / only if the source is something like this /prodotti/1996/HTC-One-M8.html
My regex works: /(?<=prodotti\/)?.*(?=\/)/ but the Gem ask me to store the querystring in a capture group (via (?.*) ) and the to use $1.

A: The following regex will do that:
\/prodotti\/([^\/]*)
Demo: http://regex101.com/r/tF9oZ0


text:
Q: Exclude div from Angular digest I have a div with a chart that's generated outside of Angular. The div is inside an ng-repeat though, and when the scope is updated, the chart is cleared. Is there a way to prevent the div with the chart from being redrawn?
Here's my HTML:

    {{ object.title }}

I looked into using bindonce, but my data changes, so I can't (?) use that.
To be clear, all I'm changing is an attribute like object.title. I don't expect the chart to stick around if the entire array of objects was replaced.
EDIT
Wrote a JSBin with the problem here: http://jsbin.com/jijalugu/1/edit?html,js,output
Looks like it's a filter that's causing the problem. I'm using the filter to split the objects into partitions (from this answer). Not sure why, it works correctly without the filter.

A: You can use a tracking expression:

    {{ item.title }}

Ben Nadel has an excellent blog post explaining tracking expressions and their benefits:

This feature allows you to associate a JavaScript object with an ngRepeat DOM (Document Object Model) node using a unique identifier. With this association in place, AngularJS will not $destroy and re-create DOM nodes unnecessarily. This can have a huge performance and user experience benefit.


text:
Q: Setting ENV in Azure Container Instances Deployment I tried to automate my deployment of a Docker container to an Azure resource group following the docs on https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-keyvault-parameter#deploy-a-key-vault-and-secret and https://gallery.azure.com/artifact/20161101/microsoft.containerinstances.1.0.8/Artifacts/mainTemplate.json.
I was able to deploy my application successfully, including the retrieval of encrypted secrets from Vault. I'm now struggling to set ENVs for my container, both secrets and normal ENVs. Even though there is a way to set ENVs in the az container API, I cannot find anything in the docs of the resource group deployment API. How can I pass ENVs to my Azure container?

A: The snippet of the json template you need is as follows (the full template is here)
"name": "[toLower(parameters('DeploymentName'))]",
"type": "Microsoft.ContainerInstance/containerGroups",
"properties": {
    "containers": [
        {

            "environmentVariables": [
                {
                    "name": "CertificateName",
                    "value": "[parameters('CertificateName')]"
                },
            ],

A: You may look the sample mentioned here: https://github.com/Azure/azure-quickstart-templates/blob/master/101-aci-storage-file-share/azuredeploy.json
 "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",

    "contentVersion": "1.0.0.0",

    "parameters": {

        "storageAccountType": {

            "type": "string",

            "defaultValue": "Standard_LRS",

            "allowedValues": [

                "Standard_LRS",

                "Standard_GRS",

                "Standard_ZRS"

            ],

            "metadata": {

                "description": "Storage Account type"

            }

        },

        "storageAccountName": {

            "type": "string",

            "defaultValue": "[uniquestring(resourceGroup().id)]",

            "metadata": {

                "description": "Storage Account Name"

            }

        },

        "fileShareName": {

            "type": "string",

            "metadata": {

                "description": "File Share Name"

            }

        },

        "containerInstanceLocation": {

            "type": "string",

            "defaultValue": "[resourceGroup().location]",

            "allowedValues": [

                "westus",

                "eastus",

                "westeurope",

                "southeastaisa",

                "westus2"

            ],

            "metadata": {

                "description": "Container Instance Location"

            }

        }

    },

    "variables": {

        "image": "microsoft/azure-cli",

        "cpuCores": "1.0",

        "memoryInGb": "1.5",

        "containerGroupName":"createshare-containerinstance",

        "containerName": "createshare"

    },

    "resources": [

        {

            "type": "Microsoft.Storage/storageAccounts",

            "name": "[parameters('storageAccountName')]",

            "apiVersion": "2017-10-01",

            "location": "[resourceGroup().location]",

            "sku": {

                "name": "[parameters('storageAccountType')]"

            },

            "kind": "Storage",

            "properties": {}

        },

        {

            "name": "[variables('containerGroupName')]",

            "type": "Microsoft.ContainerInstance/containerGroups",

            "apiVersion": "2018-02-01-preview",

            "location": "[parameters('containerInstanceLocation')]",

            "dependsOn": [

                "[concat('Microsoft.Storage/storageAccounts/', parameters('storageAccountName'))]"

              ],

            "properties": {

                "containers": [

                    {

                        "name": "[variables('containerName')]",

                        "properties": {

                            "image": "[variables('image')]",

                            "command": [

                                "az",

                                "storage",

                                "share",

                                "create",

                                "--name",

                                "[parameters('fileShareName')]"

                            ],

                            "environmentVariables": [

                                {

                                    "name": "AZURE_STORAGE_KEY",

                                    "value": "[listKeys(parameters('storageAccountName'),'2017-10-01').keys[0].value]"

                                },

                                {

                                    "name": "AZURE_STORAGE_ACCOUNT",

                                    "value": "[parameters('storageAccountName')]"

                                }

                            ],

                            "resources": {

                                "requests": {

                                    "cpu": "[variables('cpuCores')]",

                                    "memoryInGb": "[variables('memoryInGb')]"

                                }

                            }

                        }

                    }

                ],

                "restartPolicy": "OnFailure",

                "osType": "Linux"

            }

        }

    ]

}

A: The recommended way for secrets is to Mount secret volume to your container, because it is using tmpfs and your secrets exist only in volatile memory!
NOTE: at the time of this post only Linux based containers support it...


text:
Q: Are there actions or filters I can use for Ajax calls? I'm interested in writing a caching function for Ajax calls.
If a third party plugin does their thing, calls wp_ajax_whatever, how do I pick that off?
If a person does slideshow updates with a plugin that uses Ajax, e.g. wp_ajax_plugin_update_slider, I want to empty my template cache when this happens. How do I do this?

A: If you  check the source for admin-ajax.php you will notice that the admin_init hook fires and that the system checks $_REQUEST['action'] for hooks. Given that, you could hook to admin_init, check the "request" super global, construct wp_ajax_* and wp_ajax_nopriv_* values, then use has_action() to see if anything is hooked in.


text:
Q: How to run Oracle APEX application on Client side PC How can I run Oracle APEX application on Client PC which is connected remotely to Database server side PC through Oracle Client Service software.
Oracle XE 11.2g
Oracle APEX version 19
Client service sotfware version 21.1.

A: You wrote an application. When you run it, all you need is a web browser. There's the application URL in browser's address line. It looks like

http://your.server:8084/apex/f?p=120:1:3120653734023:::::

Client (person) needs this part of it (120 represents APP_ID):

http://your.server:8084/apex/f?p=120

Send it to the client" who will just have to click on it and - if you're in the same network - get application's log in window. If you also provided username and password, client will be able to run the application.
Therefore, you don't have to install any Oracle software on client's PC.


text:
Q: Ruby timeout a block of code after n *milli* seconds In Ruby, I need to time out the execution of a block of code after n milli seconds. I know that the Ruby Timeout library supports timeouts in seconds:
http://ruby-doc.org/stdlib/libdoc/timeout/rdoc/index.html
Is this possible?

A: Just use a decimal value for the timeout. Example for n milliseconds:
Timeout::timeout(n / 1000.0) { sleep(100) }


text:
Q: Flutter NoSuchMethodError: The method 'listen' was called on null
Estoy tratando de hacer un registro en mi app android con flutter, pero al momento dar al boton de registrar me muestra este error y me señala el metodo que muestro acontinuacion, estoy usando postgres, node , y el backend con js.
Agradezco a quien me pueda ayudar !!!
Error
Exception has occurred.
Nosuchmethoderror (NosuchMethodError: The method 'listen' was called on null.
Receiver: null
Tried calling: listen(Closure: (dynamic) => Null))
   stream.listen((res) {
      _progressDialog.close();
      ResponseApi responseApi = ResponseApi.fromJson(json.decode(res));
      print('RESPUESTA: ${responseApi.toJson()}');
      MySnackbar.show(context, responseApi.message);

      if (responseApi.success) {
        Future.delayed(Duration(seconds: 3), () {
          Navigator.pushReplacementNamed(context, 'login');
        });
      } else {
        isEnable = true;
      }
    });


text:
Q: Android move end of line coordinate to face point but retain length I have a line positioned at
Point lineStart = (screenWidth, screenHeight/2);

I want to retain its length as a fixed number, i.e.
int lineLength = 100

When the user taps any part of the screen, I hope to parse (x,y) values to
Point lineEnd;

How can I determine the coordinates to parse given a Touch Point whilst retaining the line's length? Thanks in advance!

A: I think you can determine the coordinates by angle.
At first, get angle by arctan(line with lineStart and touchPoint)
And then, calculate lineEnd by angle above
Point getLineEnd(Point lineStart, Point touchPoint, int length) {
    double rad = Math.atan((touchPoint.y - lineStart.y) / (touchPoint.x - lineStart.x));
    Point lineEnd = new Point(lineStart);
    lineEnd.offset(length * Math.cos(rad), length * Math.sin(rad));
    return lineEnd;
}


text:
Q: Rendering Flask HTML forms results in "UnboundLocalError" I want to make a Flask application that receives the details from a user. After a successful registration, a new page will be displayed showing the entered details.
The application is built using HTML forms and not by using WTForms.
Here is the code for app.py:
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/register',methods = ['POST', 'GET'])
def user():
    if request.method == 'POST':
        result = request.form
        name =  result['name']
        phoneno = result['phoneno']
        email = result['email']
        password = result['password']
        if name or phoneno or email or password is not None:
            print name,phoneno,email,password
    return render_template("register.html",result=result)

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

This is the HTML page of register.html:

  <form action = "/success" method = "POST">

Name <input type = "text" name = "name" />

Phone no <input type = "text" name = "phoneno" />

Email <input type = "text" name = "email" />

Password <input type ="text" name = "password" />

<input type = "submit" value = "submit" />

  </form>

What I am getting now is this error:
Full Traceback
**UnboundLocalError**
UnboundLocalError: local variable 'result' referenced before assignment.

File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000,       in __call__
  return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
  response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
  reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
  response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
  rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
  reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
  rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
  return self.view_functions[rule.endpoint](**req.view_args)
File "/home/protocol/PycharmProjects/tut/app.py", line 17, in user
  return render_template("register.html",result=result)
UnboundLocalError: local variable 'result' referenced before assignment

I tried to print the values, but nothing is shown in the console, so I couldn't rectify this error.

A: result only exists if the request method is POST, so if the request method was GET(which is the default request one), that is when the page is requested before submitting user data form, then result won't be existing, hence the error message. Plus, you need to render the result object into another template, for example user.html:
@app.route('/register',methods = ['POST', 'GET'])
def user():
    if request.method == 'POST':
        result = request.form
        name =  result['name']
        phoneno = result['phoneno']
        email = result['email']
        password = result['password']
        if name or phoneno or email or password is not None:
            print name,phoneno,email,password
            return render_template("user.html",result=result)
    return render_template("register.html")

Another thing, if the above view function is for register.html form, then you also need to change in form block, from:
<form action = "/success" method = "POST">

to
<form action = "/register" method = "POST">

A: Try this:
app.py
from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/')
def form():
    return render_template('register.html')

@app.route('/success',methods = ['POST', 'GET'])
def user():
    if request.method == 'POST':
        results = request.form
    return render_template('new.html',results=results)

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

new.html
{% for k,v in results.iteritems() %}

{{v}}

{% endfor %}

register.html is the same as yours.
You are missing a html template to display your form input data, new.html file will render the values you enter in your form.


text:
Q: Saving data in a promotion / formotion form I have a form that displays, and when i click the submit button it logs the values to the console.
How can i persist the settings so i can access them elsewhere in the application and the form is prepopulated when i return to the form screen?
I have my form set up  like this
class ChimeScreen < FormotionScreen

  title "Chime"

  def on_submit(_form)
    data = _form.render

    # settings.enable = data[:enable]
    # settings.alarm_time = data[:alarm_time]
    PM.logger.debug data[:alarm_time]
    open BrowseScreen
  end

  def table_data
    {
      ...
    }
  end

A: Formotion allows persistent data by setting the persist_as value on the form.
See example here: https://github.com/clayallsopp/formotion/tree/master/examples/Persistence
You can then retrieve this form data as a hash by looking into
App::Persistence["FORMOTION_#{your_symbol_persisting_as_here}"]

A: OK, i think i was expecting something magical to set up there, when actually it's just straight forward value setting.
def on_submit(_form)
  data = _form.render
  @defaults = NSUserDefaults.standardUserDefaults
  unless data.nil?
    @defaults["alarm_time"] = data[:alarm_time]
    @defaults["alarm_enabled"] = data[:alarm_enabled]
  end
  open BrowseScreen
end

and then set the value for each form field...
def table_data
 @defaults = NSUserDefaults.standardUserDefaults
 {
  sections: [{
    title: "Set Daily Reminder",
    rows: [{
      title: "Enable",
      key: :alarm_enabled,
      type: :switch,
      value: @defaults["alarm_enabled"]
    },

...etc


text:
Q: Cursor not align using HTML canvas I have the following Javascript, HTML and CSS code

function distanceBetween(point1, point2) {
    return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}

function angleBetween(point1, point2) {
    return Math.atan2(point2.x - point1.x, point2.y - point1.y);
}

function draw() {
    var img = new Image();
    img.src = 'http://www.tricedesigns.com/wp-content/uploads/2012/01/brush2.png';

    var el = document.getElementById('DrawingPattern');
    var ctx = el.getContext('2d');
    ctx.lineJoin = ctx.lineCap = 'round';

    var isDrawing, lastPoint;

    el.onmousedown = function (e) {
        isDrawing = true;
        lastPoint = {x: e.clientX, y: e.clientY};
    };

    el.onmousemove = function (e) {
        if (!isDrawing) return;

        var currentPoint = {x: e.clientX, y: e.clientY};
        var dist = distanceBetween(lastPoint, currentPoint);
        var angle = angleBetween(lastPoint, currentPoint);

        for (var i = 0; i < dist; i++) {
            x = lastPoint.x + (Math.sin(angle) * i) - 25;
            y = lastPoint.y + (Math.cos(angle) * i) - 25;
            ctx.drawImage(img, x, y);
        }

        lastPoint = currentPoint;
    };

    el.onmouseup = function () {
        isDrawing = false;
    };
}
html, body {
    color: #fff;
    background: #000;
    font-family: "Lucida Grande";
}

canvas{
    position: static;
    cursor: move;
    margin: auto;
    width: 70%;
    border: 3px solid #73AD21;
    background: white;
    overflow: visible;
}
<body onload=draw()>
<canvas width="1024" height="649" id="DrawingPattern">
<!-- add fallback content-->
</canvas>
</body>

The whole code works, the only problem that I'm having is when I start drawing on the canvas, the cursor doesn't line up with the effective position of the cursor. So when I draw it does the lines in another position, higher or lower than the actual position of the cursor is. I've tried different ways but, I guess is some sort of scaling problem but I'm not able how to fix it.

A: It is a scaling problem. Even though you scale the canvas element by setting CSS width by percentage, the size of the drawing area doesn't change. You get the mouse coordinates in screen space, but you need to transform into canvas space when drawing.
To do this, calculate the scale by taking into account the difference between el.width (canvas width) and el.offsetWidth (element width). As the canvas is scaled proportionately by keeping the aspect ratio, the same scaling can be used for both the X and Y coordinates.
I have added an elementScale() function and updated the code to multiply clientX and clientY with the return value.

function distanceBetween(point1, point2) {
    return Math.sqrt(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2));
}

function angleBetween(point1, point2) {
    return Math.atan2(point2.x - point1.x, point2.y - point1.y);
}

function elementScale(el) {
    return el.offsetWidth === 0 ? 0 : (el.width / el.offsetWidth);
}

function draw() {
    var img = new Image();
    img.src = 'http://www.tricedesigns.com/wp-content/uploads/2012/01/brush2.png';

    var el = document.getElementById('DrawingPattern');
    var ctx = el.getContext('2d');
    ctx.lineJoin = ctx.lineCap = 'round';

    var isDrawing, lastPoint;

    el.onmousedown = function (e) {
        var scale = elementScale(el);
        isDrawing = true;
        lastPoint = {x: e.clientX * scale, y: e.clientY * scale};
    };

    el.onmousemove = function (e) {
        if (!isDrawing) return;

        var scale = elementScale(el);
        var currentPoint = {x: e.clientX * scale, y: e.clientY * scale};
        var dist = distanceBetween(lastPoint, currentPoint);
        var angle = angleBetween(lastPoint, currentPoint);

        for (var i = 0; i < dist; i++) {
            x = lastPoint.x + (Math.sin(angle) * i) - 25;
            y = lastPoint.y + (Math.cos(angle) * i) - 25;
            ctx.drawImage(img, x, y);
        }

        lastPoint = currentPoint;
    };

    el.onmouseup = function () {
        isDrawing = false;
    };
}
html, body {
    color: #fff;
    background: #000;
    font-family: "Lucida Grande";
}

canvas{
    position: static;
    cursor: move;
    margin: auto;
    width: 70%;
    border: 3px solid #73AD21;
    background: white;
    overflow: visible;
}
<body onload=draw()>
<canvas width="1024" height="649" id="DrawingPattern">
<!-- add fallback content-->
</canvas>
</body>

A: Just like DarthJDG said, it's a scaling problem with your CSS
You could just remove your CSS width:70% on your canvas, and try to adjust just like usual
CSS CODE
    html, body {
        color: #fff;
        background: #000;
        font-family: "Lucida Grande";
    }

    canvas{
        position: static;
        cursor: move;
        margin: auto;
        //width:70%; //REMOVED
        border: 3px solid #73AD21;
        background: white;
        overflow: visible;
    }

JAVASCRIPT CODE
for (var i = 0; i < dist; i++) {
    x = lastPoint.x + (Math.sin(angle) * i) - 25; //CHANGED
    y = lastPoint.y + (Math.cos(angle) * i) - 25; //CHANGED
    ctx.drawImage(img, x, y);
}

Just by removing the CSS width, your scaling will go normal again.


text:
Q: Access denied on phpmyadmin using XAMPP I get Access denied! when I'm trying to navigate to this URL http://localhost/phpmyadmin/ (using XAMPP).
This happened today. It worked fine yesterday and I didn't change anything in the xampp folder since then.

Below is my mysq.log file output.
2022-03-21 15:39:35 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2022-03-21 15:39:35 0 [Note] InnoDB: Uses event mutexes
2022-03-21 15:39:35 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2022-03-21 15:39:35 0 [Note] InnoDB: Number of pools: 1
2022-03-21 15:39:35 0 [Note] InnoDB: Using SSE2 crc32 instructions
2022-03-21 15:39:35 0 [Note] InnoDB: Initializing buffer pool, total size = 16M, instances = 1, chunk size = 16M
2022-03-21 15:39:35 0 [Note] InnoDB: Completed initialization of buffer pool
2022-03-21 15:39:39 0 [Note] InnoDB: 128 out of 128 rollback segments are active.
2022-03-21 15:39:39 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2022-03-21 15:39:39 0 [Note] InnoDB: Setting file 'C:\xampp\mysql\data\ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2022-03-21 15:39:39 0 [Note] InnoDB: File 'C:\xampp\mysql\data\ibtmp1' size is now 12 MB.
2022-03-21 15:39:39 0 [Note] InnoDB: Waiting for purge to start
2022-03-21 15:39:39 2 [ERROR] InnoDB: Page [page id: space=647, page number=1] log sequence number 3470890319 is in the future! Current system log sequence number 598292042.
2022-03-21 15:39:39 2 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2022-03-21 15:39:39 2 [ERROR] InnoDB: Page [page id: space=615, page number=1] log sequence number 3339553304 is in the future! Current system log sequence number 598292042.
2022-03-21 15:39:39 2 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2022-03-21 15:39:39 4 [ERROR] InnoDB: Page [page id: space=618, page number=0] log sequence number 3462892962 is in the future! Current system log sequence number 598292042.
2022-03-21 15:39:39 1 [ERROR] InnoDB: Page [page id: space=579, page number=1] log sequence number 3262714642 is in the future! Current system log sequence number 598292042.
2022-03-21 15:39:39 4 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2022-03-21 15:39:39 1 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2022-03-21 15:39:39 4 [ERROR] InnoDB: Page [page id: space=618, page number=1] log sequence number 3462891605 is in the future! Current system log sequence number 598292042.
2022-03-21 15:39:39 4 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2022-03-21 15:39:39 1 [ERROR] InnoDB: Page [page id: space=616, page number=1] log sequence number 3426045456 is in the future! Current system log sequence number 598292042.
2022-03-21 15:39:39 1 [ERROR] InnoDB: Your database may be corrupt or you may have copied the InnoDB tablespace but not the InnoDB log files. Please refer to https://mariadb.com/kb/en/library/innodb-recovery-modes/ for information about forcing recovery.
2022-03-21 15:39:39 0 [Note] InnoDB: 10.4.14 started; log sequence number 598292033; transaction id 2595064
2022-03-21 15:39:39 0 [Note] InnoDB: Loading buffer pool(s) from C:\xampp\mysql\data\ib_buffer_pool
2022-03-21 15:39:39 0 [Note] Plugin 'FEEDBACK' is disabled.
2022-03-21 15:39:39 0 [Note] InnoDB: Buffer pool(s) load completed at 220321 15:39:39
2022-03-21 15:39:39 0 [Note] Server socket created on IP: '::'.

Below are my phpmyadmin user interface errors.

A: I solved the problem.
What I did:
step 1: I've copied to a backup folder all the files from xampp/mysql/data (just create a folder on desktop and put the files there)
step 2: Then I uninstalled the XAMPP, and installed again (latest version, my version i think it was from a long time - I think - )
step 3: After that, I've copied to xampp/mysql/data the file named ibdata1 from the backup folder, and also i've copied the folder with my database name (from the backup folder from step 1) to xampp/mysql/data
Also, I read the first post on the following problem: MySql stops unexpectedly from @Senthilnadhan Ramasamy
I did that a while ago 2-3 times and then it doesn't work anymore, like today, so I had to reinstall and do all the above steps.

A: I am not sure about the problem, It may happen for many reasons. But I would like to suggest you to -

*

*Click on config from Xammp control panel beside MySQL.

*Edit my.ini file

*You have to write this line skip-grant-tables after [mysqld].

*Change port=3306 to port=3307

*Open Xammp folder -> PhpMyAdmin .You will see config.inc.php file in phpMyAdmin folder. On this file, find $cfg['Servers'][$i]['host'] = '127.0.0.1';
and change it with $cfg['Servers'][$i]['host'] = 'localhost:3307';
Save these changes. You can find the port number as follows: Open Xammp Control Panel->config->service port setting->mySql.
Now You will be able to access Phpmyadmin.


text:
Q: index.js:1 Warning: A context consumer was rendered with multiple children I simply try to use react provider but somehow i get this error: index.js:1437 Warning: A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure
index.js:1 Warning: A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.
function MiveJat() {
  const consumer = React.useContext(abAnarContext);
  console.log(consumer);
  return (
    <abAnarContext.Consumer>

GOlabi

    </abAnarContext.Consumer>
  );
}

A: just remove for your component <abAnarContext.Consumer>
function MiveJat() {
  const consumer = React.useContext(abAnarContext);
  console.log(consumer);
  return (

GOlabi

  );
}

then it will work again


text:
Q: sharedPreferences - saving background color between sessions sorry for newbie question but I'm starting with Kotlin and Android app development. Currently I'm trying to create simple Activity that will switch background colors. I add 2 buttons that are working and switching colors between white and green, but would you be able to help me how to save it between the session using sharedPreferences ? I cannot retrieve these states from the preferences. Code sample below:
class OptionsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_options)

        val prefs = getSharedPreferences("bgColour", Context.MODE_PRIVATE)
        val editor = prefs.edit()

        bt3.setOnClickListener {
            Screen.setBackgroundColor(Color.GREEN)
        }

        bt4.setOnClickListener {
            Screen.setBackgroundColor(Color.WHITE)
        }

    }
}

A: You need to save the color in your preferences:
val prefs = getSharedPreferences("bgColour", Context.MODE_PRIVATE)

//Retrieve the saved value, default is false.
if (prefs.getBoolean("isGreen", false)) {
    Screen.setBackgroundColor(Color.GREEN)
} else {
    Screen.setBackgroundColor(Color.WHITE)
}

val editor = prefs.edit()

//Save on button click
bt3.setOnClickListener {
    Screen.setBackgroundColor(Color.GREEN)
    editor.putBoolean("isGreen", true)
    editor.apply()
}

bt4.setOnClickListener {
    Screen.setBackgroundColor(Color.WHITE)
    editor.putBoolean("isGreen", false)
    editor.apply()
}

You can read more about saving key-value pairs here.


text:
Q: Inverse of SDL_GetKeyName Is there a function to return a keysym from a string representation of the key?
for example, SDL_GetKeySym("d") == SDLK_d
I need this to read a keysym from a config file, and of course I'm using SDL_GetKeyName to get a string representation of the key and then saving it to the config file.

A: SDL2 adds the SDL_GetKeyFromName function, which does the inverse of SDL_GetKeyName.


text:
Q: What OOP concepts applied in MVC? Yesterday I had an interview over iOS and the interviewer asked, what OOP concepts are applicable in MVC design pattern for which I had no clue can anybody put some light one this.

A: Quote from Developer.Apple.com, Fundamental iOS Design Patterns are:-
"No matter what type of app you are creating, there are a few fundamental design patterns and techniques that you must know before you start writing code. In iOS, the system frameworks provide critical infrastructure for your app and in most cases are the only way to access the underlying hardware. In turn, the frameworks use many specific design patterns and assume that you are familiar with them. Understanding these design patterns is therefore an important first step to understanding how the system can help you develop your app.
The most important design patterns you must know are:
Model-View-Controller—This design pattern governs the overall structure of your app.

Delegation—This design pattern facilitates the transfer information and data from one object to another.

Target-action—This design pattern translates user interactions with buttons and controls into code that your app can execute.

Block objects—You use blocks to implement callbacks and asynchronous code.

Sandboxing—All iOS apps are placed in sandboxes to protect the system and other apps. The structure of the sandbox affects the placement of your app's files and has implications for data backups and some app-related features.

Accurate and efficient memory management is important for iOS apps. Because iOS apps typically have less usable memory than a comparable desktop computer, apps need to be aggressive about deleting unneeded objects and be lazy about creating objects in the first place. Apps use the compiler's Automatic Reference Counting (ARC) feature to manage memory efficiently. Although using ARC is not required, it is highly recommended. The alternative is to manage memory yourself by explicitly retaining and releasing objects."
Also Read this : https://developer.apple.com/library/ios/referencelibrary/GettingStarted/RoadMapiOS/DesignPatterns.html
EDIT :
For programming Examples:
http://www.cs.colorado.edu/~kena/classes/5448/f12/presentation-materials/myrose.pdf

A: Not an exhaustive list..
Inheritance: UIView is often subclassed.
Polymophism. See inheritance.
Design Pattern Model-Viewer-Controller: That's what MVC stands for.
Design pattern Observer: Used extensively in MVC.
Design patterns specificly used in iOS implementation of MVC:
Composite and Chain of Command: Windows and Views pass on messages to subviews.
Adaptor: Often used for delayed load of an UIView etc.
Flyweight: Used in UITable


text:
Q: Escaping many layers of cascaded single and double quotes in osx bash I use a Mac (osx sierra) and I have been learning how to use the bash. I am trying new stuff as I go along to grasp some concepts. This time I was experimenting with functions and aliases. But then I couldn't wrap my head around this problem:
I first echoed this function into the .profile to insert new aliases and functions easily into the .profile file.
function editprofile(){
echo "$@" >> ~/.profile
}

This function worked very well for some alias insertions. But after I tried to insert an alias for the script (the script below) that makes my mac sleep, I realized that the function creates some diffuculties with the cascading single and double quotes. I believe this will be the case for most scripts that uses lots of layers of single and double quotes.
osascript -e 'tell application "Finder" to sleep' && exit

The code below is me trying to use my function to insert the code above as an alias into the .profile.
editprofile 'alias _sleep=' "'" 'osascript -e' "'" 'tell application "Finder" to sleep' "'" '&& exit' "'"

The problem is that when the second script is echoed into the .profile file, I should still keep some escape characters, otherwise the code is interpretted by the bash incorrectly. I think this would also be the case with may other scripts that have this many layers of quotes, so I though I should ask if there is any way around.
P.S.
On a related note, it seems like when I type this:
function editprofile(){echo "$@" >> ~/.profile}

instead of this:
function editprofile(){
echo "$@" >> ~/.profile
}

into the .profile file, the script doesn't work. Is it because of the line breaks?

A: Assuming that you have a function, as opposed to an alias:
_sleep() { osascript -e 'tell application "Finder" to sleep' && exit; }

...you can emit its text with declare -f. Thus:
declare -f _sleep >>~/.profile

...or, to use your existing editprofile function:
editprofile "$(declare -f _sleep)"

The easiest approach is just that: Define the function in your local shell, then have the shell itself do the work of emitting it -- and quote that emitted content so it doesn't get field-split into individual arguments (and then have those arguments individually evaluated as globs).

If you don't want to go that route, there are approaches available; they're just varying degrees of unpleasant.
printf -v cmd_var '%q ' osascript -e 'tell application "Finder" to sleep'

...will put correctly-quoted contents into "$cmd_var". You could then:
printf -v sleep_def '_sleep() { %s && exit; }' "$cmd_var"

...which will give you a function declaration in sleep_dev that can be evaled to execute it locally, or appended to your .profile, &c.
editprofile "$sleep_def"

...will behave appropriately in that context.


text:
Q: c# editing sql table data without loosing the existing
Possible Duplicate:
C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?

I have a sql datatable, and I don't want the users to delete or modify anything, they can only add new rows if they want.
My solution was to use datagridview to show the existing data, but I'm stuck, because I cannot deny editing or deleting without denying adding a new row, so this is not a good way. Otherwise using update method will override all the data the user has changed (later on maybe I can give overriding permissions for that).
I could make a read-only dgw to show the existing data, and allow the user to enter the new data one by one with textboxes, but that's a bigger work and maybe unnecessary.
Is there a simple way to allow adding new row without letting editing the existing data? Maybe manipulating the datatable?
Thank you.

A: The simpler way i could think of is, while populating the grid, ill see how many existing rows i am adding from DB. Ill keep a count on it. Then when user clicks save, ill update the DB from rows after this count. Once update the DB, ill update the count to new rows count.
The same holds good even if you dont want to allow the user to edit, you can write events where you can check if the editable row is less than tis count, then disallow him to edit.

A: As an alternative you could provide the user with a new Form in order for them to add a new record like a lot of new forms. I liked the idea of a user being able to add a row to a DataGridView but in the end gave up fighting with it. You just have far easier control in a Form as opposed to a row in a DGV.
In answer to your question - Rather than fight the source, perhaps ask the DataGridView to officiate:
dataGridView1.DataSource = bs;
dataGridView1.ReadOnly = true;
dataGridView1.CurrentCellChanged += delegate
{
    DataGridViewRow row = dataGridView1.CurrentRow;
    bool readOnly = row == null ||
        row.Index != dataGridView1.NewRowIndex;
    dataGridView1.ReadOnly = readOnly;
};

(and don't set AllowEdit on the list)
Source: C# WinForms BindingList & DataGridView - disallowing EDIT prevents creation of a NEW row? How can I address this?


text:
Q: Gitlab setup not sending email I am trying to setup GitLab in windows azure. I followed this blog Setup GitLab in azure and it is working as charm. But I could not configure smtp mail sending through GitLab.

*

*I have followed this settings SMTP Setup. Tried both Gmail and Zoho, with both ports 465 and 587

I am getting the following error
2016-09-21_09:44:28.55626 2016-09-21T09:44:28.556Z 13562 TID-vskyw WARN: {"class":"ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper","wrapped":"ActionMailer::DeliveryJob","queue":"mailers","args":[{"job_class":"ActionMailer::DeliveryJob","job_id":"6a954ac7-19d6-4b27-b28c-c511f25e6896","queue_name":"mailers","arguments":["DeviseMailer","confirmation_instructions","deliver_now",{"_aj_globalid":"gid://gitlab/User/1"},"tgShkQTx5e1sALoxkkGi",{"to":"<my email here>","_aj_symbol_keys":["to"]}],"locale":"en"}],"retry":true,"jid":"cbd7dc87ce4202265d1a6be7","created_at":1474450319.7324607,"enqueued_at":1474451065.2083879,"error_message":"end of file reached","error_class":"EOFError","failed_at":1474450320.9358478,"retry_count":5,"retried_at":1474451068.5555682}

2016-09-21_09:44:28.55639 2016-09-21T09:44:28.556Z 13562 TID-vskyw WARN: EOFError: end of file reached

*

*I tried various combinations for SSL and TLS, but no luck yet!

I am using GitLab 8.11.7
Any help would be appreciated.
UPDATE:
I tried with GMail smtp and it works fine after allowing access to apps using this URL. This issue might be due to some Zoho's smtp policy

A: You should use the new smtp configurations

If you're installing from source and use SMTP to deliver mail, you will need to add the following line to config/initializers/smtp_settings.rb:
ActionMailer::Base.delivery_method = :smtp

As seen in https://gitlab.com/gitlab-org/gitlab-ce/blob/master/doc/update/8.10-to-8.11.md#smtp-configuration
A configuration exemple for smtp_settings.rb is:
if Rails.env.production?
  Rails.application.config.action_mailer.delivery_method = :smtp
  ActionMailer::Base.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    address: "email.server.com",
    port: 465,
    user_name: "smtp",
    password: "123456",
    domain: "gitlab.company.com",
    authentication: :login,
    enable_starttls_auto: true,
    openssl_verify_mode: 'peer' # See ActionMailer documentation for other possible options
  }
end

You can see the sample file doc for configuring SMTP at https://gitlab.com/gitlab-org/gitlab-ce/blob/8-12-stable/config/initializers/smtp_settings.rb.sample#L13?
You can see more configuration options here http://api.rubyonrails.org/classes/ActionMailer/Base.html#class-ActionMailer::Base-label-Configuration+options


text:
Q: Unicode messing with the spacing in my chess board The unicode chess pieces create an odd spacing and messes up the size of the board. Is there anything I can do with Ruby to fix this?
class GameBoard
   attr_accessor :white_king, :white_queen, :white_rook, :white_bishop, :white_knight, :white_pawn, :black_king, :black_queen, :black_rook, :black_knight, :black_bishop, :black_pawn, :board
      def initialize
      @white_king = "♔"
            @white_queen = "♕"
            @white_rook = "♖"
            @white_bishop = "♗"
            @white_knight = "♘"
            @white_pawn = "♙"
            @black_king = "♚"
            @black_queen = "♛"
            @black_rook = "♜"
            @black_bishop = "♝"
            @black_knight = "♞"
            @black_pawn = "♟"
            @board = Array.new(8) { Array.new(8," ") }
            end
            def display
              @board.each { |i|
                print "\n"
                @a = "+----+----+----+----+----+----+----+----+"
                puts @a
                i.each {|n|
                  print "| #{n}  "
                  }
                  print "|"}
                  print "\n"
                  print @a
            end

            def knight
              @board[0][0] = @black_knight
              display
            end
    end
    J = GameBoard.new
    J.knight

this is the output, the knight seems to take up a space and a half. Maybe a way to change the size of a ruby space?
+----+----+----+----+----+----+----+----+
| ♞  |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+
|    |    |    |    |    |    |    |    |
+----+----+----+----+----+----+----+----+

A: Unicode also has different sized spaces you can use.
@board = Array.new(8) { Array.new(8,"  ") }

Using these spaces instead of a normal space when declaring the second parameter in the array makes it the same size as a Unicode chess piece.
U+0020  SPACE   foo bar     Depends on font, typically 1/4 em, often adjusted
U+00A0  NO-BREAK SPACE  foo bar     As a space, but often not adjusted
U+1680  OGHAM SPACE MARK    foo bar     Unspecified; usually not really a space but a dash
U+180E  MONGOLIAN VOWEL SEPARATOR   foobar     No width
U+2000  EN QUAD     foo bar     1 en (= 1/2 em)
U+2001  EM QUAD     foo bar     1 em (nominally, the height of the font)
U+2002  EN SPACE    foo bar     1 en (= 1/2 em)
U+2003  EM SPACE    foo bar     1 em
U+2004  THREE-PER-EM SPACE  foo bar     1/3 em
U+2005  FOUR-PER-EM SPACE   foo bar     1/4 em
U+2006  SIX-PER-EM SPACE    foo bar     1/6 em
U+2007  FIGURE SPACE    foo bar     "Tabular width", the width of digits
U+2008  PUNCTUATION SPACE   foo bar     The width of a period "."
U+2009  THIN SPACE  foo bar     1/5 em (or sometimes 1/6 em)
U+200A  HAIR SPACE  foo bar     Narrower than THIN SPACE
U+200B  ZERO WIDTH SPACE    foobar     Nominally no width, but may expand
U+202F  NARROW NO-BREAK SPACE   foo bar     Narrower than NO-BREAK SPACE (or SPACE)
U+205F  MEDIUM MATHEMATICAL SPACE   foo bar     4/18 em
U+3000  IDEOGRAPHIC SPACE   foo bar     The width of ideographic (CJK) characters.
U+FEFF  ZERO WIDTH NO-BREAK SPACE   foobar     No width (the character is invisible)


text:
Q: Extract Image and its name from pdf using iTextSharp I am using iTextSharp c# to extract images and its name from catalog pdf. I Am able to extract images from pdf, but struggling with extracting its corresponding image name as per the attached screenshot and save the file with that name. Please find the code below and let me know your suggestions.
  Sample PDF: https://docdro.id/PwBsNR9
Code:
private static List<System.Drawing.Image> ExtractImages(String PDFSourcePath)
{
    List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();

    iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
    iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
    iTextSharp.text.pdf.PdfObject PDFObj = null;
    iTextSharp.text.pdf.PdfStream PDFStremObj = null;

    try
    {
        RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(PDFSourcePath);
        PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);

        for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
        {
            PDFObj = PDFReaderObj.GetPdfObject(i);

            if ((PDFObj != null) && PDFObj.IsStream())
            {
                PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
                iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);
                if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                {
                }
                if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
                {
                    try
                    {

                        iTextSharp.text.pdf.parser.PdfImageObject PdfImageObj =
                 new iTextSharp.text.pdf.parser.PdfImageObject((iTextSharp.text.pdf.PRStream)PDFStremObj);

                        System.Drawing.Image ImgPDF = PdfImageObj.GetDrawingImage();
                        ImgList.Add(ImgPDF);

                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }
        PDFReaderObj.Close();
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    return ImgList;
}

A: Unfortunately the example PDF is not tagged. Thus, one has to otherwise try and associate title text and image, either by analyzing the location in respect to each other or by exploiting a pattern in the content streams.
In the case at hand analyzing the location in respect to each other is feasible as the title always is (at least partially) drawn on the matching image or is the text right beneath it. Thus, one could in a first pass extract the text with position from a page and in a second one the images, at the same time looking for a title in the previously extracted text in the image area or right beneath. Alternatively one could first extract images with position and size and then extract the text in these areas.
But there also is a certain pattern in the content streams: The titel is always drawn in a single text drawing instruction right after the corresponding image is drawn. Thus, one can also go ahead and in one pass extract images and the next drawn text as associated title.
Either approach can be implemented using the iText parser API. For example in case of the latter approach as follows: first, one implements a render listener that behaves as described, i.e. saves images and the following text:
internal class ImageWithTitleRenderListener : IRenderListener
{
    int imageNumber = 0;
    String format;
    bool expectingTitle = false;

    public ImageWithTitleRenderListener(String format)
    {
        this.format = format;
    }

    public void BeginTextBlock()
    { }

    public void EndTextBlock()
    { }

    public void RenderText(TextRenderInfo renderInfo)
    {
        if (expectingTitle)
        {
            expectingTitle = false;
            File.WriteAllText(string.Format(format, imageNumber, "txt"), renderInfo.GetText());
        }
    }

    public void RenderImage(ImageRenderInfo renderInfo)
    {
        imageNumber++;
        expectingTitle = true;

        PdfImageObject imageObject = renderInfo.GetImage();

        if (imageObject == null)
        {
            Console.WriteLine("Image {0} could not be read.", imageNumber);
        }
        else
        {
            File.WriteAllBytes(string.Format(format, imageNumber, imageObject.GetFileType()), imageObject.GetImageAsBytes());
        }
    }
}

Then one parses the document pages using that render listener:
using (PdfReader reader = new PdfReader(@"EVERMOTION ARCHMODELS VOL.78.pdf"))
{
    PdfReaderContentParser parser = new PdfReaderContentParser(reader);
    ImageWithTitleRenderListener listener = new ImageWithTitleRenderListener(@"EVERMOTION ARCHMODELS VOL.78-{0:D3}.{1}");
    for (var i = 1; i <= reader.NumberOfPages; i++)
    {
        parser.ProcessContent(i, listener);
    }
}

A: I hope this would help.
I am doing this type of thing but if this would help.
// existing pdf path
PdfReader reader = new PdfReader(path);
PRStream pst;
PdfImageObject pio;
PdfObject po;
// number of objects in pdf document
int n = reader.XrefSize;
//FileStream fs = null;
// set image file location
//String path = "E:/";
for (int i = 0; i < n; i++)
{
    // get the object at the index i in the objects collection
    po = reader.GetPdfObject(i);
    // object not found so continue
    if (po == null || !po.IsStream())
        continue;
    //cast object to stream
    pst = (PRStream)po;
    //get the object type
    PdfObject type = pst.Get(PdfName.SUBTYPE);
    //check if the object is the image type object
    if (type != null && type.ToString().Equals(PdfName.IMAGE.ToString()))
    {
        //get the image
        pio = new PdfImageObject(pst);
        // fs = new FileStream(path + "image" + i + ".jpg", FileMode.Create);
        //read bytes of image in to an array
        byte[] imgdata = pio.GetImageAsBytes();
        try
        {
            Stream stream = new MemoryStream(imgdata);
            FileStream fs = stream as FileStream;
            if (fs != null) Console.WriteLine(fs.Name);
        }
        catch
        {
        }
    }
}

Now you can save your stream.
public void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Fill the bytes[] array with the stream data
        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

        // Use FileStream object to write to the specified file
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
     }
}


text:
Q: spec files keeps failing, the error says "Cannot configure the test module when the test module has already been instantiated." i'm writing some test for all the components and services of a project not writen by me.
I wrote 160 tests and just 20 of them returns success, i do not understand the differences between the test that fails and the ones thet don't fails, i'm pretty sure that the ones that fails should not, becouse the webapp works propertly.
all the failing tests returns the same error(that makes me think i have some wrong config), the error is:

Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject before R3TestBed.configureTestingModule.

i know that's not the first question abotu this error, but the solutions i found online does not helps me out.
here is the spec file of a very very simple service:
import { TestBed } from '@angular/core/testing';

import { XService } from './X.service';

describe('XService', () => {
  let service: XService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(XService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

(i have spec files way more complex than this, and some of them are asyncronous, and like this one, they fails with the error on top)
here is a .spec of a minimal component:
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { XComponent } from './X.component';

describe('XComponent', () => {
  let component: XComponent;
  let fixture: ComponentFixture<XComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ XComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(XComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

my test.ts:
import 'zone.js/dist/zone-testing'

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: {
  context(path: string, deep?: boolean, filter?: RegExp): {
    keys(): string[];
    <T>(id: string): T;
  };
};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.

const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

COMPLETE LOG OF THE ERROR:

Chrome Headless 99.0.4844.51 (Windows 10) MenuComponent should create
FAILED
Error: Cannot configure the test module when the test module has already been instantiated. Make sure you are not using inject
before R3TestBed.configureTestingModule.
at TestBedRender3.assertNotInstantiated (node_modules/@angular/core/ivy_ngcc/fesm2015/testing.js:1757:1)
at TestBedRender3.configureTestingModule (node_modules/@angular/core/ivy_ngcc/fesm2015/testing.js:1663:1)
at Function.configureTestingModule (node_modules/@angular/core/ivy_ngcc/fesm2015/testing.js:1553:1)
at UserContext. (projects/lazio/src/app/components/menu/menu.component.spec.ts:22:11)
at Generator.next ()
at asyncGeneratorStep (node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3:1)
at _next (node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:25:1)
at node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:32:1
at new ZoneAwarePromise (node_modules/zone.js/fesm2015/zone.js:1387:1)
at UserContext. (node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:21:1)
NullInjectorError: R3InjectorError(DynamicTestModule)[UtilService -> TranslateService ->
TranslateService]:
NullInjectorError: No provider for TranslateService!
error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'UtilService', 'TranslateService', 'TranslateService' ] })
NullInjectorError: R3InjectorError(DynamicTestModule)[UtilService -> TranslateService ->
TranslateService]:
NullInjectorError: No provider for TranslateService!
at NullInjector.get (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11081:1)
at R3Injector.get (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11247:1)
at R3Injector.get (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11247:1)
at injectInjectorOnly (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:4728:1)
at ɵɵinject (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:4732:1)
at Object.UtilService_Factory [as factory] (ng:///UtilService/ɵfac.js:4:39)
at R3Injector.hydrate (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11416:1)
at R3Injector.get (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11236:1)
at NgModuleRef$1.get (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:25341:1)
at Object.get (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:25055:1)
TypeError: Cannot read properties of undefined (reading 'menu')
at UserContext. (projects/lazio/src/app/components/menu/menu.component.spec.ts:43:32)
at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:1)
at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:301:43)
at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:371:1)
at Zone.run (node_modules/zone.js/fesm2015/zone.js:134:1)
at runInTestZone (node_modules/zone.js/dist/zone-testing.js:581:38)
at UserContext. (node_modules/zone.js/dist/zone-testing.js:596:24)
at
Error: Expected undefined to be truthy.
at
at UserContext. (projects/lazio/src/app/components/menu/menu.component.spec.ts:47:23)
at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:1)
at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:301:43)

thank you in advance for your help

A: Try adding providers to the first configureTestingModule.
import { TestBed } from '@angular/core/testing';

import { XService } from './X.service';

describe('XService', () => {
  let service: XService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [XService]
    });
    service = TestBed.inject(XService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });
});

In essence, do not have any empty object configureTestingModules. Also, make sure you await all TestBed.configureTestingModule({...}).compileComponents(); before doing any TestBed.inject.
The above may or may not fix it.
Edit
What I would do if I were you is change all describe to xdescribe and remove each x one by one (the x means skip). Once you have a failure, you know that test suite is problematic.


text:
Q: juniper_junos_software installs software but task fails due to "No handlers.." Im trying to install 12.3X48-D70 on an SRX550 using the juniper_junos_software module, and while it successfully installs and reboots the device the task returns as failed because of a "No handlers" errors.
Playbook:
- name: Upgrade Juniper devices
  juniper_junos_software:
    host: "{{ inventory_hostname }}"
    local_package: "junos-srxsme-12.3X48-D70.3-domestic.tgz"
    reboot: yes
    version: "12.3X48-D70.3"
    user: user
    passwd: "{{ secret }}"
    port: 22
  ignore_errors: True
  register: junos_upgrade
  when: junos_before|success

Verbose output:
TASK [code_upgrade : Upgrade Juniper devices] ***********************************************************
task path: /etc/ansible/new_test/.git/dev/code_upgrade/roles/code_upgrade/tasks/main2.yml:13
fatal: [lab-3]: FAILED! => {
    "changed": false,
    "module_stderr": "No handlers could be found for logger \"ncclient.transport.session\"\nTraceback (most recent call last):\n  File \"/tmp/ansible_0fR5rt/ansible_module_juniper_junos_software.py\", line 747, in <module>\n    main()\n  File \"/tmp/ansible_0fR5rt/ansible_module_juniper_junos_software.py\", line 743, in main\n    junos_module.exit_json(**results)\n  File \"/tmp/ansible_0fR5rt/ansible_modlib.zip/ansible/module_utils/juniper_junos_common.py\", line 792, in exit_json\n  File \"/tmp/ansible_0fR5rt/ansible_modlib.zip/ansible/module_utils/juniper_junos_common.py\", line 1327, in close\n  File \"/usr/lib/python2.7/site-packages/jnpr/junos/device.py\", line 1317, in close\n    self._conn.close_session()\n  File \"/usr/lib/python2.7/site-packages/ncclient/manager.py\", line 162, in wrapper\n    return self.execute(op_cls, *args, **kwds)\n  File \"/usr/lib/python2.7/site-packages/ncclient/manager.py\", line 232, in execute\n    raise_mode=self._raise_mode).request(*args, **kwds)\n  File \"/usr/lib/python2.7/site-packages/ncclient/operations/session.py\", line 28, in request\n    return self._request(new_ele(\"close-session\"))\n  File \"/usr/lib/python2.7/site-packages/ncclient/operations/rpc.py\", line 343, in _request\n    raise TimeoutExpiredError('ncclient timed out while waiting for an rpc reply.')\nncclient.operations.errors.TimeoutExpiredError: ncclient timed out while waiting for an rpc reply.\n",
    "module_stdout": "",
    "msg": "MODULE FAILURE",
    "rc": 1

The error shows up shortly after the device initiates a reboot and goes offline. I do not have this problem with any of the other juniper modules.
Im running Ansible 2.4.2, junos-eznc 2.1.8, python 2.7.5, and the Juniper.junos role is 2.1.0

A: Someone already reported such problem to the developers of Junos, it seems you are hit by bugs https://github.com/Juniper/ansible-junos-stdlib/pull/361 and https://github.com/Juniper/py-junos-eznc/issues/651.
However the fix is present in the release 2.1.0 of ansible-junos-stdlib (the one you have) so it is not clear to me if this is the same bug or another  closely related.
The best way to solve this is to contact the developers to report the issue on Github, to confirm this is the same bug or another and make it fixed.


text:
Q: AutomationProperties in WPF Can anyone give an example as to how AutomationProperties.LiveSettings work?
I have been working on a WPF application and I want a Text Block to be made live. In Html its easy to do, but using an aria-live tag, however I have been struggling to do the same in WPF.

A: AutomationProperties.LiveSetting cannot be used in WPF. It can be used with XAML only for developing windows store app or mobile app. In case of a store/phone app, a different library of AutomationProperties is used which supports the usage of LiveSettings. In case of WPF app, there is a different library of AutomationProperties which doesn't have the LiveSettings property.


text:
Q: Does the UIImage Cache image? UIImage *img = [[UIImage alloc] initWithContentsOfFile:@"xx.jpg"]
UIImage *img = [UIImage imageNamed:@"xx.jpg"]

In the second type will the image get cached ?
Whereas the in the first type the images doesn't get cached?

A: *

*The -initWithContentsOfFile: creates a new image without caching, it's an ordinary initialization method.

*The +imageNamed: method uses cache. Here's a documentation from UIImage Reference:

This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

UIImage will retain loaded image, keeping it alive until low memory condition will cause the cache to be purged.
Update for Swift:
In Swift the UIImage(named: "...") function is the one that caches the image.

A: Just wanted to leave this here to help deal with the pathnames issue. This is a method that you can put on a UIImage category.
+(UIImage *)imageNamed:(NSString *)name cache:(BOOL)cache {
    if (cache)
        return [UIImage imageNamed:name];
    name = [[NSBundle mainBundle] pathForResource:[name stringByDeletingPathExtension] ofType:[name pathExtension]];
    UIImage *retVal = [[UIImage  alloc] initWithContentsOfFile:name];
    return retVal;
}

If you don't have an easy way to switch to cached, you might end up just using `imageNamed. This is a big mistake in most cases. See this great answer for more details (and upvote both question and answer!).

A: @Dan Rosenstark answer in swift..
extension UIImage {

    static func imageNamed(name: String, cache: Bool) -> UIImage? {
        if (cache) {
            return UIImage(named: name)
        }

        // Using NSString for stringByDeletingPathExtension
        let fullName = NSString(string: name)
        let fileName = fullName.stringByDeletingPathExtension
        let ext = fullName.pathExtension
        let resourcePath = NSBundle.mainBundle().pathForResource(fileName, ofType: ext)

        if let path = resourcePath {
            return UIImage(contentsOfFile: path)
        }
        return nil
    }
}

A: Correct, the second item is cached.


text:
Q: Dice Question Probability A fair die is rolled until a $6$ appears. What is the probability that is must be cast more than 5 times?
So this is $1- P(\text{dice has to be cast less than or equal to}\ 5 \ \text{times})$. So this probability is equal to $$ P =\frac{1}{6}+ \frac{5}{6} \frac{1}{6}+\left(\frac{5}{6} \right)^{2} \frac{1}{6} + \cdots + \left(\frac{5}{6} \right)^{4} \frac{1}{6}$$
So just add $-1$ to this?

A: The probability of getting a non-$6$ the first five times is $(5/6)^5$.
$$
\begin{align}
& \Pr(\text{a non-}6\text{ on the 1st }5\text{ trials}) \\  \\
& = \Pr(\text{a non-}6\text{ on the first trial and a non-}6\text{ on the 2nd trial and a non-}6\text{ on the 3rd trial and }\ldots) \\  \\
& = \Pr(\text{a non-}6\text{ on the 1st trial})\cdot\Pr(\text{a non-}6\text{ on the 2nd trial})\cdot\Pr(\text{a non-}6\text{ on the 3rd trial})\cdots\cdots \\  \\
& = \frac56\cdot\frac56\cdot\frac56\cdot\frac56\cdot\frac56.
\end{align}
$$

A: For your solution, you'd subtract what you have from 1. It is fine.
It can be done a bit more simply though:
The probability that it has to be cast more than 5 times to obtain the first 6 is exactly the probability that each of the first 5 rolls do not result in a 6. This would be
$
 \bigl({5\over 6}\bigr)^5
$,
assuming independence of the rolls.

A: The easiest way to do this is simply to raise the probability that a six is not rolled to the fifth power, as these probabilities are independent, which gives $$P(\text{cast more than five times}) = P(\text{individual roll is not 6})^5 = \left(\frac{5}{6}\right)^5$$
This is equivalent to $1 - P$ where $P$ is what you wrote, as
$$1 - P = 1 - \frac{1}{6}\left(\frac{5}{6} + \cdots + \left(\frac{5}{6}\right)^4\right) = 1 - \frac{1}{6}\frac{1-(5/6)^5}{1 - 5/6} = \frac{1}{6}\frac{(5/6)^5}{1/6} = \left(\frac{5}{6}\right)^5$$


text:
Q: Channel swap needs to have the same number of dimensions as the input channels error in caffe I am new to caffe thus was trying to build a model using the MNIST dataset , I have executed the following instructions :
./data/mnist/get_mnist.sh
./examples/mnist/create_mnist.sh
./examples/mnist/train_lenet.sh

At the end of the last instruction, a series of outputs were printed on the console , the last few lines of it is :
I0315 08:46:40.755457  2430 sgd_solver.cpp:106] Iteration 9900, lr = 0.00596843
I0315 08:46:48.754673  2430 solver.cpp:454] Snapshotting to binary proto file examples/mnist/lenet_iter_10000.caffemodel
I0315 08:46:48.761627  2430 sgd_solver.cpp:273] Snapshotting solver state to binary proto file examples/mnist/lenet_iter_10000.solverstate
I0315 08:46:48.832245  2430 solver.cpp:317] Iteration 10000, loss = 0.00262804
I0315 08:46:48.835681  2430 solver.cpp:337] Iteration 10000, Testing net (#0)
I0315 08:46:54.016222  2430 solver.cpp:404]     Test net output #0: accuracy = 0.991
I0315 08:46:54.016377  2430 solver.cpp:404]     Test net output #1: loss = 0.0300069 (* 1 = 0.0300069 loss)
I0315 08:46:54.016427  2430 solver.cpp:322] Optimization Done.
I0315 08:46:54.016474  2430 caffe.cpp:222] Optimization Done.

I tried to now use the model created as binay proto file in examples/mnist/lenet_iter_10000.caffemodel
i ran the following command giving my image as input for testing the model:
python python/classify.py --print_results --model_def examples/mnist/lenet.prototxt --pretrained_model examples/mnist/lenet_iter_10000.caffemodel --force_grayscale --center_only --labels_file data/mnist/mnist_words.txt --images_dim 28,28 /home/kishan/Desktop/gray1.jpg foo

My image is a gray scale 256*256 image (I have tried even with a 256*256 RGB image)
However an error occurs saying :
Traceback (most recent call last):
  File "python/classify.py", line 154, in <module>
    main(sys.argv)
  File "python/classify.py", line 126, in main
    channel_swap=channel_swap)
  File "/home/kishan/deep-learning/caffe/python/caffe/classifier.py", line 40, in __init__
    self.transformer.set_channel_swap(in_, channel_swap)
  File "/home/kishan/deep-learning/caffe/python/caffe/io.py", line 216, in set_channel_swap
    raise Exception('Channel swap needs to have the same number of '
Exception: Channel swap needs to have the same number of dimensions as the input channels.

I haven't changed any of the files , except classify.py where i have added these line of code :
 parser.add_argument(
        "--labels_file",
        default=os.path.join(pycaffe_dir,
        "../data/ilsvrc12/synset_words.txt"),
        help="Readable label definition file."
    )
    parser.add_argument(
        "--print_results",
        action='store_true',
        help="Write output text to stdout rather than serializing to a file."
    )
    parser.add_argument(
        "--force_grayscale",
        action='store_true',
        help="Converts RGB images down to single-channel grayscale versions useful for single-channel networks like MNIST."
    )

My file structure for the ./examples/mnist :
mnist/
|-- convert_mnist_data.cpp
|-- create_mnist.sh
|-- lenet_adadelta_solver.prototxt
|-- lenet_auto_solver.prototxt
|-- lenet_consolidated_solver.prototxt
|-- lenet_iter_10000.caffemodel
|-- lenet_iter_10000.solverstate
|-- lenet_iter_5000.caffemodel
|-- lenet_iter_5000.solverstate
|-- lenet_multistep_solver.prototxt
|-- lenet.prototxt
|-- lenet_solver_adam.prototxt
|-- lenet_solver.prototxt
|-- lenet_solver_rmsprop.prototxt
|-- lenet_train_test.prototxt
|-- mnist_autoencoder.prototxt
|-- mnist_autoencoder_solver_adadelta.prototxt
|-- mnist_autoencoder_solver_adagrad.prototxt
|-- mnist_autoencoder_solver_nesterov.prototxt
|-- mnist_autoencoder_solver.prototxt
|-- mnist_test_lmdb
|   |-- data.mdb
|   `-- lock.mdb
|-- mnist_train_lmdb
|   |-- data.mdb
|   `-- lock.mdb
|-- readme.md
|-- train_lenet_adam.sh
|-- train_lenet_consolidated.sh
|-- train_lenet_docker.sh
|-- train_lenet_rmsprop.sh
|-- train_lenet.sh
|-- train_mnist_autoencoder_adadelta.sh
|-- train_mnist_autoencoder_adagrad.sh
|-- train_mnist_autoencoder_nesterov.sh
`-- train_mnist_autoencoder.sh

File structure for ./data/mnist :
mnist/
|-- get_mnist.sh
|-- t10k-images-idx3-ubyte
|-- t10k-labels-idx1-ubyte
|-- train-images-idx3-ubyte
`-- train-labels-idx1-ubyte

Any help would be appreciated.

A: I figured out what was the problem , Actually classify.py in caffe is written for the imagenet model by default and takes a 3 dimensional channel as input . However The MNIST model requires one dimensional channel as input. So when ever i was passing the image , It was showing me this dimension mismatch error , Thus necessary code had to be written to make this MNIST caffemodel to work .
https://github.com/BVLC/caffe/pull/2359/commits/dd3a5f9268ca3bdf19a17760bd6f568e21c1b521
All necessary that need to be written has been given in this link . Hope it helps .


text:
Q: Missing vertical line when insert column width in tabularx This question is a sequel to this question.
After column width added (Y{2cm}|Y{5cm}|), vertical line is missing.
\documentclass{article}
\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[skins,listings,breakable,listingsutf8,theorems,hooks,fitting]{tcolorbox}%
\tcbuselibrary{most}
\usepackage{makecell,tabularx}
\setcellgapes{12pt}
\usepackage{array}
\usepackage{colortbl}
\tcbuselibrary{skins}

\usepackage{tikz}
\newcolumntype{Y}{>{\centering\arraybackslash}X}

\tcbset{tableA/.style={
enhanced,
fonttitle=\bfseries,
fontupper=\normalsize\sffamily,
colback=blue!10!white,
colframe=green!50!black,
colbacktitle=red!40!white,
coltitle=black,center title}}

\usepackage[export]{adjustbox}

\begin{document}
\begin{tcbraster}[colback=red!5!white,colframe=red!75!black,
fonttitle=\bfseries,fontlower=\itshape] %
{
\makegapedcells
\begin{tcolorbox}[tableA,tabularx*={\renewcommand{\arraystretch}{1.5}}{Y{2cm}|Y{5cm}|},title={This is a table},boxrule=0.8pt]
A & B          \\\hline
A   & \includegraphics[width = 2cm, valign=c]{"example-image-a"}   \\\hline
A & AAA  \\\hline
B  & BBB  \\\hline
A   & \includegraphics[width = 2cm, valign=c]{"example-image-b"}
\end{tcolorbox}
}
\end{tcbraster}

\end{document}

How can I get the vertical line?
Thank you

A: If you want to specify relative widths, you can define Y as
\newcolumntype{Y}[1]{>{\hsize=#1\hsize\centering\arraybackslash}X}

and in the argument you put a decimal number representing the fraction reserved for the column. In the example below, the second column will be three times as wide as the first column. The sum of the factors should equal the number of X columns allocated, here two.
Full example, with some reordering of the code.
\documentclass{article}

\usepackage[usenames,dvipsnames]{xcolor}
\usepackage[most]{tcolorbox}
% add only the libraries you need
%\tcbuselibrary{skins,listings,breakable,listingsutf8,theorems,hooks,fitting}

\usepackage{makecell,tabularx}
\usepackage{array}
\usepackage{colortbl}
\usepackage[export]{adjustbox}

\usepackage{tikz}

\newcolumntype{Y}[1]{>{\hsize=#1\hsize\centering\arraybackslash}X}

\setcellgapes{12pt}

\tcbset{
  tableA/.style={
    enhanced,
    fonttitle=\bfseries,
    fontupper=\normalsize\sffamily,
    colback=blue!10!white,
    colframe=green!50!black,
    colbacktitle=red!40!white,
    coltitle=black,
    center title,
  },
}

\begin{document}

\begin{tcbraster}[
  colback=red!5!white,
  colframe=red!75!black,
  fonttitle=\bfseries,
  fontlower=\itshape
]{
  \makegapedcells
  \begin{tcolorbox}[
    tableA,
    tabularx*={\renewcommand{\arraystretch}{1.5}}{Y{0.5}|Y{1.5}},
    title={This is a table},boxrule=0.8pt
  ]
  A & B \\
  \hline
  A & \includegraphics[width = 2cm, valign=c]{"example-image-a"} \\
  \hline
  A & AAA \\
  \hline
  B & BBB \\
  \hline
  A & \includegraphics[width = 2cm, valign=c]{"example-image-b"}
  \end{tcolorbox}
}
\end{tcbraster}

\end{document}