text:
Q: How can I change SELECT statement to IF statement in Mysql? In mysql, I tried to print '-1' if 3 conditions are satisfied.
SELECT '-1'
WHERE not exists(select * from acq_staff where acq_person_id = staffID)
OR    not exists(select * from acq_training_course_session where training_course_id = course_id)
OR    exists(select * from acq_training_enrolment where acq_staff_acq_person_id = staffID);

But how can I change this SELECT statement to IF statement so that if either those 3 conditions are satisfied, print -1 otherwise I am going to insert a data.
Sorry for not enough information

A: MySQL INNER JOIN, along with WHERE NOT EXISTS, can be used to determine if there's an existing course, and existing staff, and that staff is enrolled in that course, and if not, INSERT the staff and course id in the enrollment table.
-- create
CREATE TABLE acq_staff (
  acq_person_id INTEGER PRIMARY KEY
);
CREATE TABLE acq_training_course_session (
  training_course_id INTEGER PRIMARY KEY
);
CREATE TABLE acq_training_enrolment (
  training_course_id INTEGER NOT NULL,
  acq_staff_acq_person_id INTEGER NOT NULL
);

-- insert
INSERT INTO acq_staff VALUES (1), (2), (3);
INSERT INTO acq_training_course_session VALUES (1), (2), (3), (4);
INSERT INTO acq_training_enrolment VALUES (1,1), (1,2), (2,1), (3,1);

-- fetch
INSERT INTO acq_training_enrolment (training_course_id, acq_staff_acq_person_id)
SELECT 3, 1 WHERE NOT EXISTS
(SELECT *
FROM acq_training_course_session
  INNER JOIN acq_training_enrolment
    ON acq_training_course_session.training_course_id = acq_training_enrolment.training_course_id
  INNER JOIN acq_staff ON acq_training_enrolment.acq_staff_acq_person_id = acq_staff.acq_person_id
WHERE acq_training_course_session.training_course_id = 3
  AND acq_staff.acq_person_id = 1)
;

Try it here: https://onecompiler.com/mysql/3yk7xynkg

A: I guess you can do something like this: How can I simulate a print statement in MySQL?
`mysql>SELECT 'some text' as '';
+-----------+
|           |
+-----------+
| some text |
+-----------+
1 row in set (0.00 sec)`

and just instead of some text set -1.
And one more thing i noticed in your question, that part "if those 3 conditions are satisfied" if you want all 3 conditions to be satisfied you need to change OR to AND. Because in your case, with OR, there needs to be satisfied only 1 condition, but with AND all 3 of them need to be satisfied.

A: maybe you can try that
select
if(
    acq_staff.acq_person_id = staffID , '-1' ,
    if(
        acq_training_course_session.training_course_id = course_id , '-1' ,
        if(acq_training_enrolment.acq_staff_acq_person_id = staffID , '-1' , 'not exist')
    )
) as "check" from acq_staff , acq_training_course_session , acq_training_enrolment limit 1

A: The question is about how to conditionally execute an insert query. In pseudo-code, the question asks how to do the following
flag = (SELECT ... WHERE <all the conditions are met>)
IF flag == 1
   INSERT INTO ....
ELSE IF flag == -1
   DO NOTHING

Now think about it this way
result_set = (SELECT ... WHERE <all the conditions are met>)
# result_set here is the actual rows we want to insert
# length(result_set) > 0 if conditions are met
# length(result_set) == 0 if conditions are not met

INSERT INTO ... (result_set)

or simply
INSERT INTO ... (SELECT ... WHERE <all the conditions are met>)
When <all the conditions are met>, the insert will actually have something to insert. Otherwise, it will have an empty result set so no rows will be inserted.
So use INSERT INTO ... SELECT ... WHERE <all the conditions are met> Syntax to achieve desired results. Unfortunately, this solution does not have a way to return back -1.


text:
Q: SQL Query to get last 4 Quarters with last 2 digit of Year I need to get the last 4 records from a table and it has records with column value like '19Q1','18Q4'.
using below query I can get last 4 quarters but is there any simplest form of this query.
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,0,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,0,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,-1,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,-1,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,-2,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,-2,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period
SELECT CAST(DATEPART(QUARTER,  CONVERT(DATE, DATEADD(q, DATEDIFF(q,0,DATEADD(q,-3,GETDATE())), 0) )) as VARCHAR) + 'Q' + CAST(Right(Cast(Year(DATEADD(q, DATEDIFF(q,0,DATEADD(q,-3,GETDATE())), 0) ) As varchar(4)),2) as VARCHAR) as Period

O/P:
1Q19
4Q18
3Q18
2Q18

A: Assuming you're using 2012 (because you've tagged 3 different versions of SQL Server...) How about:
SELECT CONCAT(DATEPART(QUARTER,Q.D),'Q',RIGHT(DATEPART(YEAR,Q.D),2))
FROM (VALUES(0),(-1),(-2),(-3)) V(i)
     CROSS APPLY (VALUES(DATEADD(QUARTER,V.i,GETDATE()))) Q(D);

A: SELECT CAST( DATEPART(q, DATEADD(q, -v.num, d.CurrentDate) ) AS VARCHAR(1))
+ 'Q'
+ RIGHT( CAST( DATEPART(yyyy, DATEADD(q, -v.num, d.CurrentDate)) AS VARCHAR(4) ), 2 )
FROM ( VALUES ( GETDATE() ) ) d(CurrentDate)
    CROSS JOIN ( VALUES (0), (1), (2), (3) ) v(num)
ORDER BY DATEADD(q, -v.num, d.CurrentDate) DESC

A: Gets Current Quarter start date going back 5 quarters plus Qx - format year
--QCurrent
select DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 0, 0) as QCurrentStartDate,
'Q' + cast(datepart(quarter,( DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 0, 0))) as nvarchar(6)) + ' - '
+ cast(datepart(year, (DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 0, 0))) as nvarchar(6)) as QLast

--LastQuarter
select DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 1, 0) as LastQuarterStartDate,
'Q' + cast(datepart(quarter,( DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 1, 0))) as nvarchar(6)) + ' - '
+ cast(datepart(year, (DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) + 1, 0))) as nvarchar(6)) as QCurrent

--SecondQuarterBack
select DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 2, 0) as SecondQuarterStartDate,
'Q' + cast(datepart(quarter,( DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 2, 0))) as nvarchar(6)) + ' - '
+ cast(datepart(year, (DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 2, 0))) as nvarchar(6)) as SecondCurrent

--ThreeQuarterBack
select DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 3, 0) as SecondQuarterStartDate,
'Q' + cast(datepart(quarter,( DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 3, 0))) as nvarchar(6)) + ' - '
+ cast(datepart(year, (DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 3, 0))) as nvarchar(6)) as SecondCurrent

--FourQuarterBack
select DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 4, 0) as SecondQuarterStartDate,
'Q' + cast(datepart(quarter,( DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) - 4, 0))) as nvarchar(6)) + ' - '
+ cast(datepart(year, (DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) -4, 0))) as nvarchar(6)) as SecondCurrent

select datepart(year, (DATEADD(qq, DATEDIFF(qq, 0, GETDATE()) -4, 0)))

select format(getdate(), 'yy')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Encrypt a SOAP Message Using an X.509 Certificate error Have a nice day need a help from here i have securityManager Class which inherit on SendSecurityFilter class WSE3 but it returns error when it build it genarate this error please help me to solve this some one know about this class details.Thanks
Error   1   'Microsoft.Web.Services3.Security.SendSecurityFilter' does not contain a constructor that takes 0 arguments
public  class SecurityManager : SendSecurityFilter
    {
 public override void SecureMessage(SoapEnvelope envelope, Security security)
   {
 // Get an X.509 certificate for signing the SOAP message.
        X509SecurityToken signatureToken = GetSecurityToken("CN=WSE2QuickStartClient");
        if (signatureToken == null)
        {
            throw new SecurityFault("Message Requirements could not be satisfied.");
        }

        // Add the X.509 certificate to the header.
        security.Tokens.Add(signatureToken);

        // Specify that the SOAP message is signed using this X.509
        // certifcate.
        MessageSignature sig = new MessageSignature(signatureToken);
        security.Elements.Add(sig);

        // Get an X.509 certificate for encrypting the SOAP message.
        X509SecurityToken encryptionToken = GetSecurityToken("CN=WSE2QuickStartServer");
        if (encryptionToken == null)
        {
            throw new SecurityFault("Message Requirements could not be satisfied.");
        }

        // Specify that the SOAP message is encrypted using
        // this X.509 certificate.
        EncryptedData enc = new EncryptedData(encryptionToken);
        security.Elements.Add(enc);
    }

public X509SecurityToken GetSecurityToken(string subjectName)
  {
        X509SecurityToken securityToken = null;
        X509Store store = new X509Store(StoreName.My,
          StoreLocation.CurrentUser);
        store.Open(OpenFlags.ReadOnly);
        try
        {
            X509Certificate2Collection certs =
                store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName,
                subjectName, false);

            X509Certificate2 cert;
            if (certs.Count == 1)
            {
                cert = certs[0];
                securityToken = new X509SecurityToken(cert);
            }
            else
                securityToken = null;
        }
        catch (Exception ex)
        {
            securityToken = null;
        }
        finally
        {
            if (store != null)
                store.Close();
        }
        return securityToken;
    }

A: The reason you getting this error is that base SendSecurityFilter class does not have default constructor that takes 0 arguments. And you did not implement any constructors for your SecurityManager class, so default one should be generated:

10.10.4 Default constructors
If a class contains no instance constructor declarations, a default
  instance constructor is automatically provided. That default
  constructor simply invokes the parameterless constructor of the direct
  base class.

But SendSecurityFilter does not have parameterless constructor to invoke from your SecurityManager class!
To fix this error you should implement one of that constructors or both of them:
//replace "public" with suitable modififier
public SecurityManager(string serviceActor, bool isClient) : base(serviceActor, isClient)
{
}

//replace "public" with suitable modififier
public SecurityManager(string serviceActor, bool isClient, string clientActor) : base(serviceActor, isClient, clientActor)
{
}


text:
Q: Setting NameSpace while storing from Spark to HBase using saveAsNewAPIHadoopDataSet I am trying to save data from Spark into HBase using saveHadoopDataSet API . Please refer the below code . Code is working fine .But the table is getting stored in the default namespace.How can I set the namespace in the below code, so that the table get stored in the desired namespace instead of default.
wordCounts.foreachRDD ( rdd => {
val conf = HBaseConfiguration.create()
conf.set(TableOutputFormat.OUTPUT_TABLE, "stream_count")
conf.set("hbase.zookeeper.quorum", "localhost:2181")
conf.set("hbase.master", "localhost:60000");
conf.set("hbase.rootdir", "file:///tmp/hbase")

val jobConf = new Configuration(conf)
jobConf.set("mapreduce.job.output.key.class", classOf[Text].getName)
jobConf.set("mapreduce.job.output.value.class", classOf[LongWritable].getName)
jobConf.set("mapreduce.outputformat.class", classOf[TableOutputFormat[Text]].getName)

rdd.saveAsNewAPIHadoopDataset(jobConf)   })

A: Got the answer from mailing list .
Replace <output_table_name> with "<namespace>:<output_table_name>"


text:
Q: Button open a Fragment I need to implement Fragment in my Android app that when pressed in a button open up.
But I am not sure where to place the fragment in the XML.
The interaction is inside a listview, when you push the button in a item at the listview, the button will open the fragmemt. But should I have the implementation of the fragment in the xml of the listview row xml or in the main layout xml?

A: First you should create a FragmentActivity which has at least a LinearLayout
And then you should create two Fragment, one with the ListView and its items, one with what you want to do with.
In your FragmentActivity you can manage thoose two Fragment transactions.
Read this Link from Android Developer Site carefully. It has all information you need.

A: I ended up concluding that it was a very bad idea to use fragment when opening a secondary view after pressed an item in the listView.
So my solution was to use and inflate a custom view at the moment the button was pressed inside the listview.


text:
Q: A Diophantine Equation Revisited This question relates to the one I just asked several hours ago:
Find $x+y$ if $x,y \in \mathbb{N}$ and $x^2+y^2 = 2019^2$. There is a short cut to this equation but I haven't found it yet. I tried estimate $x+y$ but it has lots of possible outcomes. Any one sees the trick here? Thank you in advance.

A: We have $2019=3\cdot 673$ and $0^2+3^2=3^2$,
$$
385^2+552^2=673^2
$$
by using the formulas here.
Now we can use two square theorem by Brahmagupta to solve $2019^2=x^2+y^2$.


text:
Q: Crossfilter reduce :: find number of uniques I am trying to create a custom reduce function for a dataset attribute group that would sum a number of unique values for another attribute.
For example, my dataset looks like a list of actions on projects by team members:
{ project:"Website Hosting", teamMember:"Sam", action:"email" },
{ project:"Website Hosting", teamMember:"Sam", action:"phoneCall" },
{ project:"Budjet", teamMember:"Joe", action:"email" },
{ project:"Website Design", teamMember:"Joe", action:"design" },
{ project:"Budget", teamMember:"Sam", action:"email" }

So, team members work on a variable number of projects by performing one action per line. I have a dimension by team member, and would like to reduce it by the number of projects (uniques).
I tried the below (storing project in a uniques array) without success (sorry, this might hurt your eyes):
var teamMemberDimension = dataset.dimension(function(d) {
    return d.teamMember;
});

        var teamMemberDimensionGroup = teamMemberDimension.group().reduce(
            // add
            function(p,v) {
                if( p.projects.indexOf(v.project) == -1 ) {
                    p.projects.push(v.project);
                    p.projectsCount += 1;
                }
                return p;
            },
            // remove
            function(p,v) {
                if( p.projects.indexOf(v.projects) != -1 ) {
                    p.projects.splice(p.projects.indexOf(v.projects), 1);
                    p.projectsCount -= 1;
                }
                return p;
            },
            // init
            function(p,v) {
                return { projects:[], projectsCount:0 }
            }
        );

Thanks a lot!
Edit after DJ Martin's answer ::
So, to be clearer, I would like to get the numbers I am after here would be:
-----------
Sam : 2 (projects he is workin on, no matter the number of actions)
Joe : 2 (projects he is workin on, no matter the number of actions)
-----------

The answer provided by DJ Martin gets me there. But rather than hard coding a table, I would like to find a way to use these numbers for my DC.JS bar chart. When I was only using the number of actions (so just a reduceCount() ), I did it like below:
teamMemberChart.width(270)
    .height(220)
    .margins({top: 5, left: 10, right: 10, bottom: 20})
    .dimension(teamMemberDimension)
    .group(teamMemberDimensionGroup)
    .colors(d3.scale.category20())
    .elasticX(true)
    .xAxis().ticks(4);

I guess there might be something to change in the group().

A: UPDATED ANSWER
Sorry I misunderstood the question... you are actually on the right track.  You'll just need to maintain a count of each project so that your subtract function can know when to remove the value.
teamMemberGroup = teamMemberDimension.group().reduce(

        function (p, d) {
            if( d.project in p.projects)
                p.projects[d.project]++;
            else p.projects[d.project] = 1;
            return p;
        },

        function (p, d) {
            p.projects[d.project]--;
            if(p.projects[d.project] === 0)
                delete p.projects[d.project];
            return p;
        },

        function () {
            return {projects: {}};
        });

Here is an updated fiddle: http://jsfiddle.net/djmartin_umich/3LyhL/


text:
Q: Why is a theorem about extending morphisms $\operatorname{Spec} K\to \mathbb{P}^n_K$ called "The Heavenly L'Hopitals Rule"? In Introduction to Schemes, G. Ellingsrud and J. C. Ottem call the result below "The Heavenly L'Hopitals Rule".

I see absolutely no similarity between this and the usual L'Hopital rule. What do they mean by this name?


text:
Q: Select Column copy another I got this:
+--------+------+
| id  | name    |
+--------+------+
| 1   | George  |
| 2   | Mathew  |
| 3   | Michael |
| 4   | Jones   |
+--------+------+

Now what I want to do is this.
I want to find my name Michael and copy the id "3" of Michael into a string variable in VS10

A: You need the following query to select the id column from the table and specifying the name condition in the WHERE clause
Select id from table where name = 'Michael'

If you are using Csharp in visual studio 2010, you can do something like this:
string idValue = String.Empty
string query = " Select id from table where name = 'Michael'";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
While(reader.Read())
{
idValue = reader["id"].ToString();
}
connection.Close();
return idValue;

In the above code, idValue is the id of the name you searching for and connectionStringis a connection string to your database.
You can also use lambda like this:
string idVal = Table.Where(a => a.name== "Michael")
               .Select(x => x.Id).FirstOrDefault().ToString();

A: At first, you need to establish connection between yout application and database using  mysql .net connector.
This article should help you with that.
Then you should query the database from within your application.
Appropriate SQL query for your request will be "SELECT id FROM table WHERE name = 'Michael'"


text:
Q: opencart payumoney not display even after installation Success messege I am integrating payumoney to opencart 3.0.2.0 version . as per the documentation
i make the installation successfull

even after that in payment list payumoney is not visible
is there any log in which i can check ?


text:
Q: Rails 5 - How to solve HTTP 403 response body error? I am trying to run a rails 5 project with the docker container and front-end is reactjs. While running a sudo bin/houston start command I am getting an error like
Firing engines...
Pulling elasticsearch (docker.elastic.co/elasticsearch/elasticsearch:5.4.0)...
ERROR: error parsing HTTP 403 response body: invalid character '<' looking for beginning of value: "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n\n\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta name=\"referrer\" content=\"no-referrer\">\n    <title>Web Filter Violation</title>\n    \n\n\n
\n
Powered By Fortinet
\n
FortiGuard Web Filtering
\n
\n
\n
blocked
\n
\n
\n
Web Page Blocked!
\n
\n
You have tried to access a web page which is in violation of your internet usage policy.
\n
\n        URL: https://docker.elastic.co/
\n        Category: Business\n
Client IP: 172.16.3.74\n
Server IP: 52.206.9.114\n
User name: \n
Group name: \n
\n
\n       \n
\n
 To have the rating of this web page re-evaluated please click here.
\n
\n
\n\n\r\n"

If I try to solve by running other commands and I will get CA Certification error.
If I run sudo bin/houston bundle then the error is like ERROR: No container found for web_1
Please help me to solve this issue.

A: There is an issue opened in docker-registry github repository and it seems very similar to your bug.
Check it out:
https://github.com/docker/docker-registry/issues/298


text:
Q: vscode change list shortcut key color I have been tweaking vscode theme to my liking. But I am unable to figure out how to change the list and the shortcut key color as shown in the pic.

A: I would like you to check the code as per the following or share your code so that the community can help.
https://code.visualstudio.com/docs/getstarted/theme-color-reference


text:
Q: Django Debug=False whitenoise not working I am trying to deploy my fully functional (when local and Debug=True) site to Heroku. When I use the default Django staticfile_storage settings, my site appears live but without any static files (css, images, etc). The admin panel works but it doesn't have any styles either.
But, when I try to use Whitenoise, which is what I originally intended, I get a server 500 error. The admin panel will not work then. I can't figure out for the life of me what I am doing wrong.
I have tried to model my settings.py file after Heroku's template:
https://github.com/heroku/heroku-django-template, and Whitenoise's documentation http://whitenoise.evans.io/en/latest/django.html.
When I look at my most recent Heroku logs, I see
at=info method=GET path="/static/css/styles.css" host=www.mysite.net request_id=826280da-21ba-48a1-8a05-679c92871d38 dyno=web.1 connect=0ms service=3ms status=404 bytes=361

When I push to Heroku, deployment is successful, but when I run
heroku run python3 manage.py collectstatic

it says that I have to write over preexisting files (yes/no), and when I say yes, I get an error stating that the app/static directory is not to be found.
I am absolutely puzzled - what could I be doing wrong? If my static files directory is not correct, how do I find it?
project structure
mysite/
    blog/
        static/
            css/
                styles.css
            images/
                favicon.png
        templates/
            blog/
                blog_list.html
                blog_detail.html
            index.html
            bio.html
            resume.html
        models.py
        views.py
        urls.py
    media/
        portfoliopieces/
             1.png
             2.png
             3.png
             4.png
    mysite/
        settings.py
        urls.py
        wsgi.py
    portfolio/
        templates/
            portfolio_list.html
            portfolio_detail.html
        models.py
        views.py
        urls.py

mysite/urls.py
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py
import os
from secrets import *
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

# SECURITY WARNING: keep the secret key used in production secret!
# see secrets.py

# SECURITY WARNING: don't run with debug turned on in production!
# DEBUG = bool(os.environ.get('DJANGO_DEBUG', True))
# For production, make false
DEBUG = False

ALLOWED_HOSTS = ['www.mysite.com' ]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'portfolio.apps.PortfolioConfig',
    'blog.apps.BlogConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

# STATIC_URL = '/static/'

STATIC_DIR = os.path.join(BASE_DIR, 'static')

# STATICFILES_DIRS = [
    #os.path.join(BASE_DIR, "static"),
#]

# STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static")

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')

STATIC_URL = '/static/'

# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
     os.path.join(PROJECT_ROOT, 'static'),
]

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")

SECURE_CONTENT_TYPE_NOSNIFF = True

SECURE_BROWSER_XSS_FILTER = True

# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

A: After two full days of trying to get whitenoise to work, and failing, I figured out how to make the default Django staticfiles work over Heroku. This was really tricky, this might help others: the settings.py file should(assuming my project structure) look like this:
import os
from secrets import *
import dj_database_url

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = False

ALLOWED_HOSTS = ['www.mysite.com']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'portfolio.apps.PortfolioConfig',
    'blog.apps.BlogConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation

AUTH_PASSWORD_VALIDATORS = [
    {
         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
{
    'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
    'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]

# Internationalization

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Static files (CSS, JavaScript, Images)

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')

STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media")


text:
Q: Visualizing 10 random test examples, the predicted labels, and the actual label from MNIST data set I am trying to visualize 10 randome test examples, the predicted lables and the actual labels for MNIST data set. but I am getting this error

TypeError: Invalid shape (28, 28, 1) for image data

Can anyone please help me fixing the error? Is it the right approach to visualize test examples, the predicated labels and the actual labels?
%tensorflow_version 1.x
import tensorflow as tf
from matplotlib import pyplot
import matplotlib.pyplot as plt
import random
print(tf.__version__)
    mnist = tf.keras.datasets.mnist
    (training_images, training_labels), (test_images, test_labels) = mnist.load_data()
    training_images = training_images.reshape(60000, 28, 28, 1)
    training_images = training_images / 255.0

    #visualizing 10 random test examples
    for i in range(10):
      pyplot.subplot(330 + 1 + i)
      pyplot.imshow(test_images[i], cmap=pyplot.get_cmap('gray'))
      pyplot.show()

    test_images = test_images.reshape(10000, 28, 28, 1)
    test_images = test_images/255.0
    model = tf.keras.models.Sequential([
      tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(28, 28, 1)),
      tf.keras.layers.MaxPooling2D(2, 2),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(128, activation='relu'),
      tf.keras.layers.Dense(10, activation='softmax')
    ])
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    model.fit(training_images, training_labels, epochs=10)
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    print(test_acc)

A: You simply need to remove the last axis such that your images are of size (28, 28) instead of (28,28,1). Pyplot expects either RGB images with 3 dimensions or black and white images with only 2.

A: Try:
pyplot.imshow(np.squeeze(test_images[i]), cmap=pyplot.get_cmap('gray'))


text:
Q: Html or Aspnet button on ColorBox Popup Redirect to another aspx page on button click I am stuck with a critical issue.Can some one please suggest.
I have an .ascx page on which there is a pop up which has an aspnet button which must redirect to another page on click.
I followed the following steps:

*

*On ascx page after opening colorbox, this function is called on clicking the button.
$.ajax({
     type: 'POST',
     url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
     contentType: 'application/json;charset=utf-8',
     dataType: 'json',
     success: function (response) {
            alert(response);
     },
     error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest + textStatus + errorThrown);
     }
  });

*On aspx page
[WebMethod]
public static void  btnSaveData()
{
  function sahil();//this function i want to call after this function is being called
}

I am getting Json parse error.
I removed dataType:json and made it return a html/text then it is giving me object object error.

A: This would propably be a lot easier if you could use a simple html form, add the value to a hidden input when onsubmit is triggered, and post it to a webservice which will redirect for you.

Anyway:
You need to decorate your btnSaveData method with another attribute and change the return type / parameter to string (or any other type that suits your needs):
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod]
    public static string btnSaveData(string color)
    {
         // do sth with the color

         return "/SaveSuccess.aspx";
    }

And in js:
    // retrieve the color as a string (this is up to you - I don't know what sort of ColorPicker you're using, so this is a placeholder)
    function saveColor()
    {
        var color = $('#myColorPicker').color.toString();

        // create the data for the webmethod,
        // the parameternames have to be the same as they are on the WebMethod
        var colorData = "{ color:'" + color + "'}";

        $.ajax({
             type: 'POST',
             url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
             contentType: 'application/json;charset=utf-8',
             dataType: 'json',
             data: colorData,
             success: function (response) {
                window.location.href = response.d; // redirect on success
         },
         error: function (response, text, error)
         {
                alert(response + ' ' + text + ' ' + error);
         }
    });

Hope this helps and works!


text:
Q: F# throws warning in shadowing record type I have 2 record types having the same signature:
type T1 = { a : int }
type T2 = { a : int }

let badFunc record = { record with a = 0 }
let goodFunc (record : T2) = { record with a = 0 }

The compiler will throw a warning in the badFunc function:

The field labels and expected type of this record expression or pattern do not uniquely determine a corresponding record.

From F# RFC FS-1025 - Improve record type inference:

When resolving a record type, the current behavior of the compiler is to find for each field of the record type, all the types in scope that have that field. Then it takes the intersection of those types for all the fields, and if a single matching type is found, that type is picked. Otherwise, the first type in the list is blindly chosen, and an error can ensue.

So F# should knows the badFunc type is T2 -> T2, why does F# ignore the shadowing and throw a warning instead?

A: As mentioned in the comments, the record T1 is not shadowed by the record T2. I can see where this reasoning might be coming from, because this is how variable shadowing works:
let foo () =
  let a1 = 10
  let a1 = 20
  a1

Here, the second declaration of a1 hides the first one. For records, you might perhaps expect that a record with the same name will hide earlier declaration:
type T1 = { a : int }
type T1 = { a : int }

However, this does not work and you get an error message:

error FS0037: Duplicate definition of type, exception or module 'T1'

In your definition, you are defining two separate types T1 and T2 and they both happen to have the same field. You can always refer to the field using the fully qualified syntax:
let t1Func record = { record with T1.a = 0 }
let t2Func record = { record with T2.a = 0 }

What should the compiler do when you write just a? This is a design decision - it could automatically pick one of the two, but this is generally a bit confusing because it might depend on the order in which you open namespaces. So, giving a warning, as the compiler does currently, is probably more sensible approach.


text:
Q: Adjacency matrix on the basis of two columns I have a data file of two column and want to make a adjacency matrix in the basis of these two column
I have tried
import pandas as pd
df = pd.read_csv("file.csv")
df = pd.crosstab(df.Name_A, df.Name_B)
idx = df.columns.union(df.index)
df = df.reindex(index = idx, columns=idx, fill_value=1)
print (df)

Output
     A  B  C  D
A    0  1  1  0
B    0  0  1  0
C    0  0  0  1
D    0  0  0  0

My input example file
C_1,C_2
A,B
C,D
A,C
B,C

Expected output
    A  B  C  D
A   1  1  1  0
B   1  1  1  0
C   1  1  1  1
D   0  0  1  1


text:
Q: Accessing Object Values Sorry if this is a particularly stupid question but it's late and I'm going slightly round the bend on this.
I have an object returned from an API which echo '
';print_r($r);echo '
'; gives as:
stdClass Object
(
    [id] => 49
    [submitdate] => 2015-11-05 14:33:16
    [lastpage] => 4
    [startlanguage] => en
    [Qu1[SQ001]] => Fred Bloggs
    [Qu1[SQ003]] => Caretaker
    [Feedback] => Great course, thank you
)

The line echo '
Feedback: '.$r -> Feedback.'
'; displays 'Great course, thank you' as expected, but echo '
'.$r -> Qu1 -> SQ001.'
'; doesn't show 'Fred Bloggs', instead I get an error: Notice: Undefined property: stdClass::$Qu1.
Please will somebody tell me what I'm doing wrong?

A: you can do it in two ways(may be there are more, but I know two only :))
1)
$obj['a'] = "A";
$obj['b'] = "B";
$obj['c'] = "C";
$obj['get[d]'] = "D";
$obj['get[E]'] = "E";
$obj = (object) $obj;
echo "This is: ".$obj->{'get[d]'}.PHP_EOL;
echo "This is: ".$obj->{'get[E]'}.PHP_EOL;

will output
This is: D
This is: E

2)
other is, you can get the properties of object by using get_object_vars()
 states

get_object_vars — Gets the properties of the given object

So,
$array = get_object_vars($obj);
echo "This is: ".$array['get[E]']." but getting from array";

DEMO

A: Try:

$r -> Qui[SQ001]

Qui looks to be an array so $r -> Qui -> SQ001 won't work


text:
Q: Code is buggy on comparing strings The issue i'm having, is when I edit the string "dbPassword", my script will run fine as in notice that the 2 string dont match. For example if I remove the letter "c"
d

array(1) { ["c"]=> int(6) } not matching..
123bdcbadbcabcbcadcbadbc
123bcdbddbcabcccbdaabba

but when I do the same thing to the $anPassword string, it gives me an OK message basically.
Instead though, it only causes the issue with
The blank space is where I took out a letter. (The letter B)
$anPassword = "123bdcbad cabcbcadcbadbc"; //Removed 1 letter
$dbPassword = "123bdcbadbcabcbcadcbadbc"; //Unchanged / original string

and it still gives me..
Should be matching... Theoredically...
123bdcbadcabcbcadcbadbc
123abadabccbbbddcbacdcbc
Basically, why is  my code bugging out and returning that it's matchng when it obviously isnt. and why is only some characters causing it.
$anPassword = "123bdcbadbcabcbcadcbadbc"; //User encrypted password on form submission
$dbPassword = "123bdcbadbcabcbcadcbadbc"; //Database encrypted password.

$begChars1[0] = substr($anPassword, 0, 3);
$begChars1[1] = substr($anPassword, 3);

$begChars2[0] = substr($dbPassword, 0, 3);
$begChars2[1] = substr($dbPassword, 3);
$begChars2[2] = str_shuffle($begChars2[1]);

$compData1 = array_count_values(str_split($begChars1[1]));
$compData2 = array_count_values(str_split($begChars2[2]));
$result = array_diff($compData1, $compData2);

if($begChars1[0] != $begChars2[0]) {
    echo "not matching...";

}

if($result == null) {
    echo "Should be matching... Theoredically...";
} else {
    echo "not matching.. " . var_dump($result);
}

echo "
" . $begChars1[0] . $begChars1[1] . "
" . $begChars2[0] . $begChars2[2];

A: I don't understand what it is you're trying to accomplish but here's what I'm seeing.
Most of your confusion stems from what appears to be this line.
$result = array_diff($compData1, $compData2);

You're thinking this is going to return all differences about the two arrays. What this actually does is returns the values in array1 that are not present in array2.
Your arrays both look like this before the comparison.
array (size=4)
  'b' => int 7
  'd' => int 4
  'c' => int 6
  'a' => int 4

array (size=4)
  'a' => int 4
  'c' => int 6
  'd' => int 4
  'b' => int 7

Both strings contain the same amount of each character, youre just shuffling them for some reason. array_diff is understandably going to return nothing because theres really nothing different about the arrays sans the order of the elements.
If you dropped an 'x' in the second string, you'd see something in $result.
You could save yourself a lot of trouble by not storing passwords via whatever crazy method you're trying to invent. Hash them like everyone else instead.


text:
Q: Tcpdf by using Separate management file I am using TCPDF to generate the PDF.
I have two files.The contents of the first file are the invoice contents (table, photo, etc..../without code TCPDF)
The contents of the second file are the following code(Coded by my colleague).
$_factorUrl = PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/views_pdf/".$billName.".php?order_id=".$orderId;
ob_start();
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//Before Write
// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';

// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);

//After Write
$pdf->setRTL(true);
// set font
$pdf->SetFont('dejavusans', '', 12);

// add a page
$pdf->AddPage();
// Persian content
$pdf->WriteHTML(execute($_factorUrl), true, 0, true, 0);

//Close and output PDF document
//$pdf->Output("factor.pdf");
ob_end_clean();
$pdfFileName = $billName."-".$orderId.md5(rand(1,1000).microtime().UserAuth::getCustomerId().$billName.$orderId);
$_fullFilePath = $sourcePath."modules/printer/dl/".$pdfFileName.".pdf";
$pdf->Output($_fullFilePath, 'FI');
header("location: ".PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/dl/".$pdfFileName.".pdf");

Now I have the output(second image), But no style is applied, the tables do not look good and ...
when I add any tcpdf statement to first file, I have no output.
for example I add to the first file :
<?php
$html = '
Example of HTML text flow
';
 ?>
first image is Invoice appearance on web page

second image is Invoice pdf

A: you have to use tcpdf image for background image
https://tcpdf.org/examples/example_009/
and you need to use tcpdf table
https://tcpdf.org/examples/example_045/


text:
Q: Dataproc pyspark on yarn cluster not starting with specified number of cores per executor. Or, maybe it is? This has been talked about here, here, here and here
The problem is the same, however, I suppose that maybe the yarn-reported numbers are buggy. Looking for someone expert to shed some light. What I have noticed:
I start the spark session with
spark = SparkSession.builder.\
config("spark.dynamicAllocation.enabled",False).\
config("spark.executor.cores","3").\
config("spark.executor.instances","4").\
config("spark.executor.memory","6g").\
getOrCreate()

And the yarn only 1 core per executor:

However, I can still see 12 tasks running in parallel from the spark UI

As suggested in the posts linked, I set yarn.scheduler.capacity.resource-calculator=org.apache.hadoop.yarn.util.resource.DominantResourceCalculator in the capacity-scheduler.xml
Situation remains exactly the same:

*

*yarn shows 1 core per executor allocated

*spark UI shows 12 tasks running in parallel

Question:
Is the number being shown in the yarn UI a bug? How to reconcile the two incompatible numbers?


text:
Q: Do I need seperate library with native function in order to load library with main function? Just like in topic do I need seperate lib with native fuction in order to load lib with main function in it ? Or is it recomennded to do so ?
At this moment I got those native functions compiled withing main.so but I am not sure if that's how it should be done.
native is lib loaded before main one
protected String[] getLibraries() {
        return new String[] {
            "SDL2",
            "hidapi",
            "native",
            "main"
        };
    }

And inside I got bunch of those native fucntion one of those is that one as example
JNIEXPORT int JNICALL Java_org_libsdl_app_SDLActivity_nativeRunMain(jstring library, jstring function, jobject array)
{
  return Java_org_libsdl_app_SDLActivity_nativeRunMain("libmain.so", "SDL_main", NULL);
}

So far app is running loading libriaries and nothing more did tried to see if log_android is comming from main function but it does not.

A: OK the solution to my issue was kinda weird. I had to generate whole package from scratch using one of build-scripts provided by SDL2. Then I copied some files from the old one and woila it now have access to int main() function.
Here is log from Logcat.
05-11 12:42:28.829 10315 10315 V SDL     : Device: santoni
05-11 12:42:28.829 10315 10315 V SDL     : Model: Redmi 4X
05-11 12:42:28.829 10315 10315 V SDL     : onCreate()
05-11 12:42:28.890 10315 10315 V SDL     : nativeSetupJNI()
05-11 12:42:28.890 10315 10315 V SDL     : AUDIO nativeSetupJNI()
05-11 12:42:28.890 10315 10315 V SDL     : CONTROLLER nativeSetupJNI()
05-11 12:42:28.900 10315 10315 D hidapi  : Initializing Bluetooth
05-11 12:42:28.929 10315 10315 D AccessibilityManager: current package=org.libsdl.app, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
05-11 12:42:28.952 10315 10315 V SDL     : onResume()
05-11 12:42:28.986 10315 10336 I Adreno  : QUALCOMM build                   : dd15ef5, Ic280a69317
05-11 12:42:28.986 10315 10336 I Adreno  : Build Date                       : 05/09/17
05-11 12:42:28.986 10315 10336 I Adreno  : OpenGL ES Shader Compiler Version: XE031.09.00.04
05-11 12:42:28.986 10315 10336 I Adreno  : Local Branch                     :
05-11 12:42:28.986 10315 10336 I Adreno  : Remote Branch                    : quic/gfx-adreno.lnx.1.0.r5-rel
05-11 12:42:28.986 10315 10336 I Adreno  : Remote Branch                    : NONE
05-11 12:42:28.986 10315 10336 I Adreno  : Reconstruct Branch               : NOTHING
05-11 12:42:28.994 10315 10336 I OpenGLRenderer: Initialized EGL, version 1.4
05-11 12:42:28.994 10315 10336 D OpenGLRenderer: Swap behavior 1
05-11 12:42:28.995 10315 10315 V SDL     : surfaceCreated()
05-11 12:42:28.995 10315 10315 V SDL     : surfaceChanged()
05-11 12:42:28.995 10315 10315 V SDL     : pixel format RGB_565
05-11 12:42:28.996 10315 10315 V SDL     : Window size: 720x1230
05-11 12:42:28.996 10315 10315 V SDL     : Device size: 720x1280
05-11 12:42:29.001 10315 10315 V SDL     : nativeResume()
05-11 12:42:29.002 10315 10338 V SDL     : Running main function SDL_main from library /data/app/org.libsdl.app-1/lib/arm64/libmain.so
05-11 12:42:29.002 10315 10338 V SDL     : nativeRunMain()

Also off to next issue that awaits for me.


text:
Q: fatal error: Array index out of range with many tap Swift When I tap only one time on one of cell in table view, it works perfect to another view controller. But if I tap twice, triple or more times on the cell quickly before move to another view controller.
An error of array index out of range would be shown and highlighted "let labelTitle = self.resultsTitleArray[indexPath.row]". I tried to use self.view.userInteractionEnabled = false before performSegueWithIdenitifier and self.view.userInteractionEnabled = true after performSegueWithIdenitifier. But still doesn't work.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "moreDetail"){
        let viewController = segue.destinationViewController as! ProductDetailViewController

        let indexPath = self.resultsTable.indexPathForSelectedRow!
        let labelTitle = self.resultsTitleArray[indexPath.row]
        viewController.labelTitleText = labelTitle
        self.resultsTable.deselectRowAtIndexPath(indexPath, animated: true)
    }
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("moreDetail", sender: self)
}

A: you need to check if indexpath is nil
if(indexPath == nil){
return
}

and to be 100% sure it works you can also do
if(indexPath == nil || indexPath.row >= self.resultsTitleArray.length){
return
}

A: You can disable the multiple touches from the TableView so that
those events will not be fired by setting the multipleTouchEnabled to false.
self.tableView.multipleTouchEnabled = false

A: Can you try removing didSelectRowAtIndexPath and going to your storyboard and Control-dragging from the cell to the segue view controller. Name that segue "moreDetail." See if the segue fires immediately before you have a chance to double- or triple-click the button.


text:
Q: Construction of the spectral sequence of Katz/Oda In their famous paper "On the differentiation of De Rham cohomology classes..." Katz and Oda construct the spectral sequence for de Rham cohomology for the situation of a smooth morphism
$\pi: X \rightarrow S$
of smooth $k$-schemes ($k$ a field), where $S$ is assumed affine.
There is a step which is not clear to me: in Lemma 8 of this paper they say that the equality
$(*) \qquad \mathbb R^0\Gamma_X =\Gamma_S\circ \mathbb R^0\pi_*$
yields a spectral sequence of composition
$(**) \qquad E_2^{a,b}=R^a \Gamma_S\circ \mathbb R^b\pi_* \Rightarrow \mathbb R^{a+b}\Gamma_X$.
They seem to consider $(*)$ as an equality of functors on the category of complexes of abelian sheaves on $X$ - Arguments involving quasi-coherence and affineness of $S$ only appear in the next step.
My question is a very simple one which I nevertheless can't figure out:
Why do they have $(**)$?
It is a spectral sequence of composition, hence only exists when one knows that $\mathbb R^0 \pi_* $ sends injective objects in the category of complexes of sheaves on $X$ to $\Gamma_S$-acyclic ones. I don't see why this is true: imagine a two-term complex $I^0\rightarrow I^1$ of injective abelian sheaves on $X$, then $\mathbb R^0 \pi_*$ of it is $ker(\pi_*I^0 \rightarrow \pi_*I^1)$. This has no reason to be acyclic for $\Gamma_S$, hasn't it?
A similar problem arises a bit later in Lemma 9 when they consider the equality
$(+) \qquad \mathbb R^0\Gamma_S = H^0\circ \Gamma_S$
which I see as equality of functors on the category of complexes of abelian sheaves on $S$.
Can anybody give a hint how to cleanly resolve these two problems?

A: Let me try to say the same thing as Will but in a different way. Let $f \colon A \to B$ be left exact between abelian categories and assume there are enough injectives. Then one can distinguish between derived functors
$$\newcommand{\R}{\mathrm R} \R^i f \colon A \to B,$$
as well as hyper-derived functors
$$\newcommand{\RR}{\mathbb R} \RR^i f \colon \mathrm{Kom}^+(A) \to B,$$
and the total derived functor
$$ \newcommand{\RRR}{\mathbf R} \RRR f \colon D^+(A) \to D^+(B).$$
Now suppose we also have $g \colon B \to C$ with the same hypotheses and that $f$ maps injective objects of $A$ to $g$-acyclic objects of $B$. Then there is a natural isomorphism
$$ \RRR(g \circ f) \cong \RRR g \circ \RRR f.$$
This isomorphism specializes not only to the usual spectral sequence
$$ E_2^{p,q} = \R^p g( \R^q f(X)) \implies \R^{p+q}(g \circ f)(X),$$
for $X$ any object of $A$, but also to the spectral sequence
$$ E_2^{p,q} = \R^p g( \RR^q f(X^\bullet)) \implies \RR^{p+q}(g \circ f)(X^\bullet),$$
for $X^\bullet$ any object of $\mathrm{Kom}^+(A)$, in a similar way. In particular one needs no extra hypotheses to get the latter spectral sequence; even though the domain of $\RR^i f$ is $\mathrm{Kom}^+(A)$, one should not assume that complexes of injectives are sent to acyclics.

A: You only need injective objects in the underlying abelian category to be mapped to acyclics, not in the category of complexes, to get a Grothendieck spectral sequence. This is because if you take a complex $A$, and take an injective resolution over that complex (to compute hypercohomology), then after applying $R \pi_*$ to this complex, you get an acyclic resolution of $R \pi_* A$. Then you can use that to compute hypercohomology of $\Gamma_s$, which you do by just applying $R^0 \Gamma_s$ to each object, which is the same as applying $R^0 \Gamma$ to the original injective resolution, which is just computing hypercohomology of $R^0 \Gamma$.


text:
Q: Vertx 3 application logging from Javascript Sometimes it's nice to log things to the console during development.  In a Vert.x 3 project I'm creating, I'm trying to follow the instructions on the docs page for Vert.x 3 for logging:
http://vert-x3.github.io/docs/vertx-core/js/#_logging_from_your_application
The docs provide this sample code:
// Note -these classes are Java only

// You would normally maintain one static instance of Logger per Java class:

var logger = Java.type("io.vertx.core.logging.LoggerFactory").getLogger(className);

logger.info("something happened");
logger.error("oops!", exception);

When compiling, the "var logger = ..." line bombs out with this error:

Failed in deploying verticle  java.lang.RuntimeException:
  java.lang.ClassNotFoundException: io.vertx.core.logging.LoggerFactory
    at
  jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:391)
    at
  jdk.nashorn.internal.scripts.Script$Recompilation$13$1895AAAAA$\^eval_.L:27$_load(null:107)
    at
  jdk.nashorn.internal.scripts.Script$Recompilation$4$4036AAAA$\^eval_.L:27$doRequire(null:149)
    at
  jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:644)
    at
  jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:229)

(Note: that "className" variable looks suspicious too.  It doesn't say anywhere what that's supposed to be, it's "undefined" at compile time at the moment)
Any ideas?

A: This is due to versions getting slightly out of sync in the Vertx 3 milestones. The documentation already reflects a change upcoming in milestone 7 where the class package is:
    io.vertx.core.logging.LoggerFactory

However, in milestone 6 you need to use:
    io.vertx.core.logging.impl.LoggerFactory

If you update your code to:
    var logger = Java.type("io.vertx.core.logging.impl.LoggerFactory").getLogger(className);

it should work.


text:
Q: When I use StringBuilder.Append instead of .AppendLine, do I need to add additional .Append(crlf)s? I'm adapting some code I found here: http://nicholas.piasecki.name/blog/2009/03/sending-raw-epl2-directly-to-a-zebra-lp2844-via-c/#comment-1636, but in VS 2003 / .NET 1.1, StringBuilder's AppendLine method is not recognized, so I truncated it to .Append.
Will I need now to add #13#10 or so after each call to Append - I'm assuming that is something AppendLine does automatically.

A: Yes. Be wary of thinking of it as a CRLF though - internally StringBuilder uses Environment.Newline so it's worth using Environment.NewLine yourself for cross compatibility.
 [System.Runtime.InteropServices.ComVisible(false)]
    public StringBuilder AppendLine() {
        Contract.Ensures(Contract.Result<stringbuilder>() != null);
        return Append(Environment.NewLine);
    }

    [System.Runtime.InteropServices.ComVisible(false)]
    public StringBuilder AppendLine(string value) {
        Contract.Ensures(Contract.Result<stringbuilder>() != null);
        Append(value);
        return Append(Environment.NewLine);
    }

Edit: Unless you have a specific need to use CRLF because of hardware, I guess.

A: Decompiled source for StringBuilder.AppendLine
/// <summary>
/// Appends the default line terminator to the end of the current <see cref="T:System.Text.StringBuilder"/> object.
///
/// </summary>
///
/// <returns>
/// A reference to this instance after the append operation has completed.
///
/// </returns>
/// <exception cref="T:System.ArgumentOutOfRangeException">Enlarging the value of this instance would exceed <see cref="P:System.Text.StringBuilder.MaxCapacity"/>.
///                 </exception><filterpriority>1</filterpriority>
[ComVisible(false)]
[__DynamicallyInvokable]
public StringBuilder AppendLine()
{
  return this.Append(Environment.NewLine);
}

A: Yes.
AppendLine() will append its argument, followed by Environment.Newline.
If you don't call AppendLine(), you will need to include the newline yourself.


text:
Q: How to add HTML5 files to Android programatically? I developed a game in HTML5. It contains JavaScript and HTML files. Now I want to add them to my Android app. How can I do this?

A: You need To add Webview to have HTML5  Files to be loaded this can be done like this
 public class HelloWebView extends Activity {

     WebView webview;

     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     webview = (WebView) findViewById(R.id.webview);
     webview.getSettings().setJavaScriptEnabled(true);
     webview.setWebViewClient(new HelloWebViewClient());
     webview.loadUrl("file:///android_asset/test.html");
     WebSettings settings = webview.getSettings();
     settings.setJavaScriptEnabled(true);
     settings.setDatabaseEnabled(true);
     String databasePath = this.getApplicationContext().getDir("database",  Context.MODE_PRIVATE).getPath();
     settings.setDatabasePath(databasePath);
     webview.setWebChromeClient(new WebChromeClient() {
     public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
            quotaUpdater.updateQuota(5 * 1024 * 1024);
        }
    });
    }

And place your HTML5 files inside assets.

A: Android Developer Website should be the first thing comes to mind. Check WebView Page.
For tutorial you can check :
http://www.mkyong.com/android/android-webview-example/

A: You can have webview within your android device which load the page that host your html5 game.


text:
Q: Very slow mysql query for reading orders (joins and group by) A query for reading orders is very slow. I've tried a lot of things, but couldn't get a faster query. Below the query and the database tables. Of course, all the important fields have an index. I noticed that removing the group by function will speed it up, but grouping the query is important.
is there a better way for getting the orders? Thanks in advance.
SELECT
orders.id AS orderId, orders.delivery_from, orders.delivery_to,
orders_products.product_id, orders_products.color_id, ,orders_products.size_id,
sum(orders_products.quantity) as quantity,
customers.id AS customerId, customers.name AS customerName,
products.name
FROM orders
    INNER JOIN orders_products ON orders_products.order_id=orders.id
    INNER JOIN customers ON customers.id=orders.customer_id
    INNER JOIN products ON orders_products.product_id=products.id
    LEFT JOIN orders_product_data ON orders_product_data.order_id=orders.id AND orders_product_data.product_id=orders_product.product_id AND orders_product_data.color_id=orders_product.color_id
WHERE orders.status='0' AND
(orders.delivery_from<='2014-05-05' AND orders.delivery_to>='2014-05-05') AND
((orders_products_data.delivery_from<='2014-05-05' || orders_products_data.delivery_to=0) AND (orders_products_data.delivery_from>='2014-05-05' || orders_products_data.delivery_to=0))
GROUP BY customer_id, product_id, color_id, size_id

Customers
CREATE TABLE IF NOT EXISTS `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(90) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
);

Products
CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
);

Orders
CREATE TABLE IF NOT EXISTS `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `delivery_from` date NOT NULL,
  `delivery_to` date NOT NULL,
  `status` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);

Products of the order
CREATE TABLE IF NOT EXISTS `orders_products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL DEFAULT '0',
  `product_id` int(11) NOT NULL DEFAULT '0',
  `color_id` int(11) NOT NULL DEFAULT '0',
  `size_id` int(11) NOT NULL DEFAULT '0',
  `quantity` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);

Color data. The tabel below stores for the combination order_id, product_id and color_id the delivery information since the delivery of products in different colors could change.
CREATE TABLE IF NOT EXISTS `orders_products_data` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `order_id` int(11) NOT NULL DEFAULT '0',
  `product_id` int(11) NOT NULL DEFAULT '0',
  `color_id` int(11) NOT NULL DEFAULT '0',
  `delivery_from` date NOT NULL,
  `delivery_to` date NOT NULL,
  PRIMARY KEY (`id`)
);

The explain query

A: You have mentioned that you have indexes for all the important fields.
Just for your Info - Index should be prepared based on the access path rather than for important fields.
Check after replacing delivery_from between '...' and '...' for orders, orders_product_data and adding following index:
create index idx_orders_status_delivery_from_to on orders(status,delivery_from,delivery_to);


text:
Q: django.contrib.auth.urls is no longer working after creating a Custom User model I created a Custom user model from AbstractUserModel. I'm using django.contrib.auth.urls for simple login and logout functionalities including password_reset and When i'm still using the default user model of django, but its no longer working on my Custom user model. Is there a way to make this work for custom user model.
(1146, "Table 'db.auth_user' doesn't exist") this is the error message i'm getting every time i login a sample account to my application. Thanks

A: I think if you created your own user profile then you should create your forms and views
for this
P.S: This is how i understood all the things about
AbstracUser


text:
Q: Error in running GWT Map - Is the Maps key missing or invalid? I am trying to integrate the gwt map into my SmartGWT app. But for some reason I am getting this error. Can somebody please help me to resolve it. I am using this link as my reference http://forums.smartclient.com/showthread.php?t=3366.
the error i get is
Uncaught exception escaped : java.lang.RuntimeException
The Maps API has not been loaded.
Is a  tag missing from your host HTML or module file?  Is the Maps key missing or invalid?
See the Development console log for details.
Register a GWT.setUncaughtExceptionHandler(..) for custom uncaught exception handling.
//This is added in my module file and i am using Maps v2 API 1.1.1
<inherits name='com.google.gwt.maps.GoogleMaps' />

   HomeViewImpl homePanel = new HomeViewImpl();
   addTab(homePanel, "Home", "Home");

==============================================
public class HomeViewImpl extends VLayout
{

private MapWidget getMap()
{
    /*MapWidget map = new MapWidget();
    map.setSize("500px", "300px");
    map.addControl(new LargeMapControl());
    map.getInfoWindow().open(map.getCenter(), new InfoWindowContent(getMapInfoWindow()));
    return map;*/
    LatLng cawkerCity = LatLng.newInstance(-22.82, -47.26);
    final MapWidget map = new MapWidget();
    map.setScrollWheelZoomEnabled(true);

    map.addControl(new LargeMapControl());

    map.addOverlay(new Marker(cawkerCity));

    map.getInfoWindow().open(map.getCenter(),
        new InfoWindowContent("World's Largest Ball of Sisal Twine"));

    return map;
}

public Canvas getViewPanel()
{
    HLayout hLayout = new HLayout(5);
    hLayout.addMember(new Label("Dummy Label in a Horizontal Layout"));
    // Add the map to the HTML host page
    hLayout.addMember(getMap());
    return hLayout;
}

private Canvas getMapInfoWindow()
{
    final TabSet topTabSet = new TabSet();
    topTabSet.setTabBarPosition(Side.TOP);
    topTabSet.setWidth(200);
    topTabSet.setHeight(100);

    Tab tTab1 = new Tab("Blue");

    HTMLPane tab1Pane = new HTMLPane();
    tab1Pane.setContents("Hello. This sample shows a google map widget taking part in a SmartGWT Layout");
    tTab1.setPane(tab1Pane);
    Tab tTab2 = new Tab("Green");
    HTMLPane tab2Pane = new HTMLPane();
    tab2Pane.setContents("Google Maps InfoWindow can display SmartGWT Widgets");
    tTab2.setPane(tab2Pane);

    topTabSet.addTab(tTab1);
    topTabSet.addTab(tTab2);
    return topTabSet;
}

@Override
public Widget asWidget()
{
    return getViewPanel();
}

}

cheers
Zolf

A: There are a few things happening here.
Google Maps v2 is no longer available. Please read Upgrading Your Google Maps JavaScript Application To v3. The link you provide is from 2008 and is well and truly out of date.
Second, Google Maps (either v2 or v3) require a valid license key in the host HTML page. GWT has a host HTML page that launches the GWT application. The Google Maps key can go here.
You will also require an updated GWT Google maps API to make use of Maps v3. There are a few available.
Regards,
Thomas.

A: You have to create map and load data like this,
Maps.loadMapsApi("", "2", false, new Runnable() {
  public void run() {
   // add your widget with map
  }
});

see this link for example: http://code.google.com/p/gwt-google-apis/wiki/MapsGettingStarted
& download and use the jar which is used in this example.

A: Ok the problem with my case was that I had to also add this scropt to my module file.Adding this resolved the error and displayed the Map.
 <script src="http://maps.google.com/maps?gwt=1&file=api&v=2"></script>


text:
Q: Extracting coefficients from a generating function g (x) First of all, do not tell me to use Taylor. Using Taylor expansion  is fine when you can symbolically calculate the derivatives. But thst's not always possible.
Given a generating function $g(x)$, how do I numerically calculate the nth coefficient with contour integration? I know nothing algebraic about this function, so I can't use tricks like partial fraction decomposition or Cauchy's residue theorem. I only know the numerical value of $g (x) $ given a real/complex number $x $. How do I choose the correct contour?

A: So $g(z)=\sum_{n\geq 0}a_n z^n$ is known numerically for complex $z$ and you would like to determine each $a_n$. This can be done by fixing any counterclockwise contour $C$ surrounding the origin. Then
$$
\oint_C \frac{g(z)}{z^{n+1}}\ dz=\oint_C \frac{a_n}{z}\ dz=2\pi i a_n,
$$
by the Residue Theorem. Choosing the contour is up to you, depending on the properties of your function (i.e., if you have a better numerical calculation in a certain region then choose a contour passing through that region). Otherwise, just take $C$ to be a circle of radius $r$ about the origin, in which case you can compute the integral as follows:
$$
a_n=\frac{1}{2\pi i}\oint_C \frac{g(z)}{z^{n+1}}\ dz=\frac{1}{2\pi}\int_0^{2\pi}g\!\left(re^{i \theta}\right)r^{-n}e^{-i n\theta}\ d\theta,
$$
and again in the absence of further information, taking $r=1$ would be the simplest choice.


text:
Q: Actions on Google - Ask user to re link their account before token expires Our agent uses OAuth account linking with Authentication code. We would like to suggest to the user to relink their account when the consent they've given is about to expire.
To achieve that, we first invalidate the consent on our auth server and then proceed to respond with a new SignIn(). However, the agent doesn't immediately recognise that the token is invalid, so the new SignIn() doesn't force the user to link their account again and does nothing.
Is there a way to force the agent to do the account linking process?
Note: Returning a 401 response (UnauthorisedError) is not really an option because we don't want the conversation to end. Instead we want the user to continue his conversation after their account is linked.

A: The platform does not have a way to perform reauthentication inline. To force the agent to perform account linking, you will need to return a 401 UnauthorizedError and the user will sign in again the next time they invoke the action.


text:
Q: Create NSSplitView + subview programmatically I am trying to create a horizontal NSSplitView programmatically and to add it 2 subviews.
Unfortunately, if I have no issue to create the splitview, I do not know how to add the subview.
Do you have any idea to do it?

A: You add panes to a split view the same way you add subviews to any view. Each of the split view's subviews will get its own pane. You can use the adjustSubviews method to automatically resize the views so that each pane is the same size.
This example code will create a split view which fills its window and has 3 text views split vertically.
NSSplitView *splitView = [[NSSplitView alloc] initWithFrame:[[theWindow contentView] bounds]];
NSTextView *textView1 = [NSTextView new];
NSTextView *textView2 = [NSTextView new];
NSTextView *textView3 = [NSTextView new];
[splitView addSubview:textView1];
[splitView addSubview:textView2];
[splitView addSubview:textView3];
[splitView adjustSubviews];
[[theWindow contentView] addSubview:splitView];
[textView3 release];
[textView2 release];
[textView1 release];
[splitView release];


text:
Q: Looping through videos in HTML5 I have this JS code:
video_count =1;
videoPlayer = document.getElementById("homevideo");

function run(){
    video_count++;
    if (video_count == 4) video_count = 1;
    var nextVideo = "app/video"+video_count+".mp4";
    videoPlayer.src = nextVideo;
    videoPlayer.play();
};

and i have two videos i want to play one after another. The videos are playing fine - first one and after ended the second one but this code loop through the second video instead of playing the first video again and after ended the second video etc.
Can you please help?
Thanks in advance,
Yaniv

A: Use the ended event to trigger the run function again.
video_count =1;
videoPlayer = document.getElementById("homevideo");
function run(){
  if (video_count == 4) video_count = 1;
  var nextVideo = "app/video"+video_count+".mp4";
  videoPlayer.src = nextVideo;
  videoPlayer.play();
  video_count++;
};
videoPlayer.addEventListener('ended', run);

A: video_count =1;
videoPlayer =     document.getElementById("homevideo");

function run(){
    if (video_count > 2) video_count = 1;
    var nextVideo = "app/video"+video_count+".mp4";
    videoPlayer.src = nextVideo;
    videoPlayer.play();
    video_count++;
};

will solve the problem
You increase the variable before you define the video's file name, so you begin with two...
the condition needs to be changed as well, because we wish to set videocount to 1 only after we display the 2nd video


text:
Q: Angular ng-if not working from scope function(angular function) I understand the concept that, ng-if creates its own scope for the variable inside it.
In the below code, i am enabling Alert (with Confirm and Cancel buttons) to be visible from Show Alert button, which  is doing its job.
But, evidently when i try to achieve the contrary, it is not working out. It seems that setting of showEditAlert has no effect on the ng-if block. This setting is being done using  showConfirm() call, which in turn sets the boolean value of showEditAlert to false (hide view), but instead , view remains enabled.
         //Triggers Alert to show onClick
         <button class="btn launchConfirm" ng-click="showEditAlert=true ">Show Alert</button>

                <button class="close" data-dismiss="alert" aria-label="close">
                        ×
                </button>
                Proceed with edit options Please confirm?

                <button class="btn btn-success btn-xs"
                      ng-click="$parent.enable = false; ShowConfirm()" >
                    confirm
                </button>
                <button class="btn btn-danger btn-xs "
                      ng-click="$parent.showEditAlert=false">
                    cancel
                </button>

AngularJS
$scope.showEditAlert = false; //Initialization

$scope.ShowConfirm = function() {
    $scope.showEditAlert = false // This setting value is not effecting the ng-if block
 }

I know i am missing out with some Scope wise understanding, kindly help me out with clear picture. Would really appreciate the response.
PS. I have acquired the solution using ng-show and ng-hide. But, the intention is to achieve the same using ng-if (because, it directly has an effect on DOM)

A: See the working example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.showEditAlert = false; //Initialization

$scope.ShowConfirm = function() {
    $scope.showEditAlert = false // This setting value is not effecting the ng-if block
 }
});

   //Triggers Alert to show onClick
         <button class="btn launchConfirm" ng-click="showEditAlert=true ">Show Alert</button>

                <button class="close" data-dismiss="alert" aria-label="close">
                        ×
                </button>
                Proceed with edit options Please confirm?

                <button class="btn btn-success btn-xs"
                      ng-click="$parent.enable = false; ShowConfirm()" >
                    confirm
                </button>
                <button class="btn btn-danger btn-xs "
                      ng-click="$parent.showEditAlert=false">
                    cancel
                </button>

A: Its working fine.

.controller('ExampleController', ['$scope', function($scope) {

      $scope.showEditAlert = false; //Initialization

      $scope.ShowConfirm = function() {
          $scope.showEditAlert = false // This setting value is not effecting the ng-if block
       };
    }]);
    </script>
    <form name="myForm" ng-controller="ExampleController">
        <button class="btn launchConfirm" ng-click="showEditAlert=true ">Show Alert</button>

                <button class="close" data-dismiss="alert" aria-label="close">
                        ×
                </button>
                Proceed with edit options Please confirm?

                <button class="btn btn-success btn-xs"
                      ng-click="$parent.enable = false; ShowConfirm()" >
                    confirm
                </button>
                <button class="btn btn-danger btn-xs "
                      ng-click="$parent.showEditAlert=false">
                    cancel
                </button>

    </form>

plunkr
[here] (https://plnkr.co/edit/1D48TWXl8dInTlcVYjn3?p=preview)!


text:
Q: Is any body using sql service broker to update winforms(WPF) GUI? I have a scenario to update Winforms application GUI when ever there is a data change in database table.Is any body  using SQL Service broker to do same?
For example:
I have a customer and order tables in SQl Server 2005 database and I have winform(WPF) application which resides on Call Center executives(say CCE-A,CCE-B,CCE-C,CCE-D) desks to show pending customer orders.
All those Call Center Executives will process pending orders simultaniously.As a developer my challenge is update Call Cener Executives GUIs when ever there is a change in Customer and Order tables.
Thanks in advance for your valuable time.

A: It really depends on the number of GUI's that you would have to be updating.  Essentially, the SqlDependency works of ServiceBroker to fire updates to the application when data changes in the database, so your could use it, or roll your own implementation, but the caveat is that it isn't good for large scale/multi-dependency refreshes because of the overhead of each Dependency.  Pro SQL Server 2008 Service Broker by Klaus Aschenbrenner is a great reference for how you can use service broker with managed code.
You can create a single test SqlDependency on the data you want to watch, and use SQLTrace to capture the statements executed by the Database Engine to create the Service and Queues in SQL Server.  Then you can take those statements and use them as the basis for a customize Service to meet your needs, having the clients setup to use the same Service instead of each starting their own through SqlDependency.  This along with an ObservableCollection in WPF should get your to where you need to be.


text:
Q: Expected null({ }) to equal Object({ }) I have been trying to run AngularJS own unit tests of $resource. The only difference is that I'm running then with Jasmine v2.0 and Karma v0.13.
I did all the work of converting custom actions from older Jasmine to newer, so all tests pass. Well almost all...
I have stumbled with one type of tests. I believe it have something to do $httpBackend. Whilst testing this line I see it fails:
Expected null({  }) to equal Object({  }).
Actual test code, problem is with latest expectation:

      // ---
      callback = jasmine.createSpy();
      // ---

      it("should create resource", function() {
        $httpBackend.expect('POST', '/CreditCard', '{"name":"misko"}').respond({id: 123, name: 'misko'});

        var cc = CreditCard.save({name: 'misko'}, callback);
        expect(cc).toEqualData({name: 'misko'});
        expect(callback).not.toHaveBeenCalled();

        $httpBackend.flush();
        expect(cc).toEqualData({id: 123, name: 'misko'});
        expect(callback).toHaveBeenCalledOnce();
        expect(callback.calls.mostRecent().args[0]).toEqual(cc);
        expect(callback.calls.mostRecent().args[1]()).toEqual({});
      });

UPDATE
Found it.
Turns out, angular uses function bellow to create empty Object. Probably newest versions of Jasmine fails on calling Objects instantiated with null and {} as equals.
/**
 * Creates a new object without a prototype. This object is useful for lookup without having to
 * guard against prototypically inherited properties via hasOwnProperty.
 *
 * Related micro-benchmarks:
 * - http://jsperf.com/object-create2
 * - http://jsperf.com/proto-map-lookup/2
 * - http://jsperf.com/for-in-vs-object-keys2
 *
 * @returns {Object}
 */
function createMap() {
  return Object.create(null);
}

A: After looking at AngularJS source, I see that sometimes objects are created using Object.create(null), like in a snippet below.
/**
 * Creates a new object without a prototype. This object is useful for lookup without having to
 * guard against prototypically inherited properties via hasOwnProperty.
 *
 * Related micro-benchmarks:
 * - http://jsperf.com/object-create2
 * - http://jsperf.com/proto-map-lookup/2
 * - http://jsperf.com/for-in-vs-object-keys2
 *
 * @returns {Object}
 */
function createMap() {
  return Object.create(null);
}

Looks like Jasmine 2.0 added comparison for prototype type as well, so expectation fails.
Test can be written like this: expect(callback.calls.mostRecent().args[1]()).toEqual(Object.create(null));, for it will pass.

A: I think you have a spare () in your code. Convert this;
expect(callback.mostRecentCall.args[1]()).toEqual({});
to
expect(callback.mostRecentCall.args[1]).toEqual({});


text:
Q: How to add a button to bottom of UIPageViewController I would like to add a button to my UIPageViewController just like the bottom right button of the iOS Weather app.
I would like to know what is most correct and clean way of doing it.
Should I access the PageControl somehow and add a subview with the button I want to add or should I hide the Page Control and add a toolbar at the bottom of the view?
Any simple snippet would be most welcome.
Thank you!

A: *

*In viewDidLoad, add the button to the UIPageViewController's view.

*In viewDidAppear, bring the button to front

```
- (void)viewDidLoad {
  [super viewDidLoad];

  // Add the button
  [self.view addSubview:button];
}

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

  // Bring it to front so it appears in front of the UIPageControl
  [self.view bringSubviewToFront:button];
}

```


text:
Q: Configuring EC2 autoscale policies and alarms with ansible I'm trying to setup a our auto-scaling policies in ec2 using ansible.  Each auto-scale group will have multiple policies (IE scale-up and scale-down), and could have multiple cloudwatch alarms per policy (CPU usage, load balancer latency).
I've got the vars for the scaling policies and alarms if a single autoscale group in a .yml file and am trying to build the policies with the playbook:
- ec2_scaling_policy:
    state: present
    region: "{{ region }}"
    adjustment_type: "ChangeInCapacity"
    asg_name: "{{ asg_name }}"
    scaling_adjustment: "{{ item.scaling_adjustment }}"
    min_adjustment_step: 1
    cooldown: "{{ item.cooldown }}"
    name: "{{item.name }}"
  register: "sp_result"
  with_items: scaling_policies

- debug: msg="{{sp_result}}"

- debug:
    msg="{{item[1]['name']}} == {{item[0]['scaling_policy_name']}}"
  with_nested:
    - alarm_metrics
    - sp_result.results

- ec2_metric_alarm:
    state: present
    region: "{{ region }}"
    name: "{{ item[0].name }}"
    metric: "{{ item[0].metric }}"
    namespace: "AWS/EC2"
    statistic: "{{ item[0].statistics }}"
    comparison: "{{ item[0].comparison }}"
    threshold: "{{ item[0].threshold }}"
    period: "{{ item[0].period }}"
    evaluation_periods: "{{ item[0].evaluation_periods }}"
    unit: "{{ item[0].unit }}"
    description: "{{ item[0].description }}"
    dimensions: "{{ item[0].dimensions }}"
    alarm_actions: "{{ item[1]['arn'] }}"
    when: "{{item[1]['name']}} == {{item[0]['scaling_policy_name']}}"
  with_nested:
    - alarm_metrics
    - sp_result.results

This is the closest I've come to making it work but I'm still getting the error: msg: unsupported parameter for module: when
Additionally, the item[0], item[1] and iterating over nested loops is getting messy is there a better way of doing this? If not how do I solve the error I'm getting?
Edit to add vars file:
An example of the vars file for one of our groups:
asg_name: autoscale-group-prod
region: us-east-1
scaling_policies:
  - scaling_adjustment: 1
    name: policy-high-cpu
    cooldown: 300

  - scaling_adjustment: -1
    name: policy-low-cpu
    cooldown: 300

alarm_metrics:
  - name: group-high-cpu-alarm
    metric: "CPUUtilization"
    statistics: Average
    comparison: ">="
    threshold: "85"
    period: 300
    evaluation_periods: 2
    unit: "Percent"
    description: "alerm when CPU utilization is >= 85% for 10 minutes."
    dimensions: {"AutoScalingGroupName": 'autoscale-chameleon-prod'}
    scaling_policy_name: policy-high-cpu

  - name: group-healthy-host-alarm
    metric: "HealthyHostCount"
    statistics: Average
    comparison: "<"
    threshold: "1"
    period: 300
    evaluation_periods: 3
    unit: "Count"
    description: "alarm when there are no healthy instances behind the elb"
    dimensions: {"ElasticLoadBalancerName": "GroupELB"}
    scaling_policy_name: policy-high-cpu

  - name: group-low-cpu-alarm
    metric: "CPUUtilization"
    statistics: Average
    comparison: "<"
    threshold: "50"
    period: 300
    evaluation_periods: 2
    unit: "Percent"
    description: "alerm when CPU utilization is < 50% for 10 minutes."
    dimensions: {"AutoScalingGroupName": 'autoscale-chameleon-prod'}
    scaling_policy_name: policy-low-cpu

A: Wrong indentation & quoting.
- ec2_metric_alarm:
    state: present
    region: "{{ region }}"
    name: "{{ item[0].name }}"
    metric: "{{ item[0].metric }}"
    namespace: "AWS/EC2"
    statistic: "{{ item[0].statistics }}"
    comparison: "{{ item[0].comparison }}"
    threshold: "{{ item[0].threshold }}"
    period: "{{ item[0].period }}"
    evaluation_periods: "{{ item[0].evaluation_periods }}"
    unit: "{{ item[0].unit }}"
    description: "{{ item[0].description }}"
    dimensions: "{{ item[0].dimensions }}"
    alarm_actions: "{{ item[1]['arn'] }}"
    # Wrong:
    # when: "{{item[1]['name']}} == {{item[0]['scaling_policy_name']}}"
  # Correct:
  when: "'{{item[1].name}}' == '{{item[0].scaling_policy_name}}'"
  with_nested:
    - alarm_metrics
    - sp_result.results


text:
Q: Spring Boot - Kafka Consumer in Cloud Foundry I would like to run a Kafka Consumer instance developed using Spring Boot in Cloud Foundry. Is there a way to deploy an app without listening on any port (80 or 443)?

A: Use cf push app --no-route --u process to push your app and not have a route for it generated.
The -u flag ensures that the health checker determines whether the app started successfully by checking the process is alive, as opposed to whether it's listening to the port.
On old CF releases and cf CLI's you may find process is not supported. In that case, use none instead of process. (none was deprecated in favor of the more meaningful process, but they're just aliases and do exactly the same thing.)


text:
Q: Smart Card to Protect RAID Storage I currently have a simple RAID setup, external RAID enclosure, with 2 hard drives, A mirroring B. All data on A is encrpyted using Blowfish (TrueCrypt). Although I would like to know if its possible to use a smart card to mount the drives in Windows?

A: truecrypt supports keyfile & token authentication out of the box.
what you need, of course is to:

*

*generate a keyfile

*import it to a token (a smart card, here)

and then use the token as authentication. you will also need a password for the token. nowadays a token can be a smart card, but it can also be e.g. on a USB device.

A: Keep in mind that you will be using your smart card as a "wird shaped USB thumb drive" and the only protection you get from using a smart card is the same as using a FIPS 140-2 level 3 USB sitck for storing your keyfiles (like an ironkey, so that there's a chance that if you loose your USB keyholding device and somebody wants to break into it, the keys on it get destroyed).
Keyfiles transfer in plaintext between the smart card (or USB token) and the host system, so they are available for interception by hardware loggers or malware.


text:
Q: Plotting different processes of a simulated VAR[2] I have simulated a VAR process with this
simData =
  RandomFunction[ARProcess[a, Sigma], {1, 20001}];

Where the coefficients for a VAR[2] process:
a1 = {{1.6, 0, 0}, {0.3, 1.5, 0}, {0, 0.5, 1.7}};
a2 = {{-0.8, 0, 0}, {0, -0.8, 0}, {0, 0, -0.8}};
a = {a1, a2};

And
Sigma = {{1.0, 0, 0}, {0, 1.0, 0}, {0, 0, 1.0}};

simData is then a TemporalData with 1 path and have 3 Output dimension.
How do I plot (or have a list of values corresponding to) the individual paths for the 3 processes of the VAR simulation?
ListLinePlot can be used to plot different paths. But the way TemporalData is structured, I need to plot the three different processes I've simulated. Please let me know if my question isn't clear enough.
Edit: Performing:
ListLinePlot[simData]

gives me

Which looks like there may be three different paths there. But I would like to only pick them out one by one to be analysed individually.

A: I think you should be able to slice the different output dimensions with TimeSeriesMap. For example, to get the first component:
TimeSeriesMap[#[[1]]&, simData]

Similarly for the other two components.


text:
Q: Haskell Type Promotion I am currently working my way through Write Yourself a Scheme in 48 Hours and am stuck on type promotion.
In short, scheme has a numerical tower (Integer->Rational->Real->Complex) with the numeric promotions one would expect. I modeled numbers with the obvious
data Number = Integer Integer | Rational Rational | Real Double | Complex (Complex Double)

so using Rank2Types seemed like an easy way to make functions work over this range of types. For Num a this looks like
liftNum :: (forall a . Num a => a -> a -> a) -> LispVal -> LispVal -> ThrowsError LispVal
liftNum f a b = case typeEnum a `max` typeEnum b of
  ComplexType  -> return . Number . Complex $ toComplex a `f` toComplex b
  RealType     -> return . Number . Real $ toReal a `f` toReal b
  RationalType -> return . Number . Rational $ toFrac a `f` toFrac b
  IntType      -> return . Number . Integer $ toInt a `f` toInt b
  _            -> typeErr a b "Number"

which works but quickly becomes verbose because a separate block is required for each type class.
Even worse, this implementation of Complex is simplified since scheme can use separate types for the real and complex part. Implementing this would require a custom version holding two Number's which would make the verbosity even worse if I wanted to avoid making the type recursive.
As far as I know there is no way to abstract over the context so I am hoping for a cleaner way to implement this number logic.
Thanks for reading!

A: Here's a proposal. The primary thing we want your typeEnum function to do that it doesn't yet is bring a Num a dictionary into scope. So let's use GADTs to make that happen. I'll simplify a few things to make it easier to explain the idea and write the code, but nothing essential: I'll focus on Number rather than LispVal and I won't report detailed errors when things go wrong. First some boilerplate:
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
import Control.Applicative
import Data.Complex

Now, you didn't give your definition of a type enumeration. But I'll give mine, because it's part of the secret sauce: my type enumeration is going to have a connection between Haskell's term level and Haskell's type level via a GADT.
data TypeEnum a where
    Integer  :: TypeEnum Integer
    Rational :: TypeEnum Rational
    Real     :: TypeEnum Double
    Complex  :: TypeEnum (Complex Double)

Because of this connection, my Number type won't need to repeat each of these cases again. (I suspect your TypeEnum and Number types are quite repetitive compared to each other.)
data Number where
    Number :: TypeEnum a -> a -> Number

Now we're going to define a new type that you didn't have, which will tie a TypeEnum together with a Num dictionary for the appropriate type. This will be the return type of our typeEnum function.
data TypeDict where
    TypeDict :: Num a => TypeEnum a -> TypeDict

ordering :: TypeEnum a -> Int
ordering Integer  = 0 -- lowest
ordering Rational = 1
ordering Real     = 2
ordering Complex  = 3 -- highest

instance Eq  TypeDict where TypeDict l == TypeDict r = ordering l == ordering r
instance Ord TypeDict where compare (TypeDict l) (TypeDict r) = compare (ordering l) (ordering r)

The ordering function reflects (my guess at) the direction that casts can go. If you try to implement Eq and Ord yourself for this type, without peeking at my solution, I suspect you will discover why GHC balks at deriving these classes for GADTs. (At the very least, it took me a few tries! The obvious definitions don't type-check, and the slightly less obvious definitions had the wrong behavior.)
Now we are ready to write a function that produces a dictionary for a number.
typeEnum :: Number -> TypeDict
typeEnum (Number Integer  _) = TypeDict Integer
typeEnum (Number Rational _) = TypeDict Rational
typeEnum (Number Real     _) = TypeDict Real
typeEnum (Number Complex  _) = TypeDict Complex

We will also need the casting function; you can essentially just concatenate your definitions of toComplex and friends here:
-- combines toComplex, toFrac, toReal, toInt
to :: TypeEnum a -> Number -> Maybe a
to Rational (Number Integer  n) = Just (fromInteger n)
to Rational (Number Rational n) = Just n
to Rational _ = Nothing
-- etc.
to _ _ = Nothing

Once we have this machinery in place, liftNum is surprisingly short. We just find the appropriate type to cast to, get a dictionary for that type, and perform the casts and the operation.
liftNum :: (forall a. Num a => a -> a -> a) -> Number -> Number -> Maybe Number
liftNum f a b = case typeEnum a `max` typeEnum b of
    TypeDict ty -> Number ty <$> liftA2 f (to ty a) (to ty b)

At this point you may be complaining: your ultimate goal was to not have one case per class instance in liftNum, and we've achieved that goal, but it looks like we just pushed it off into the definition of typeEnum, where there is one case per class instance. However, I defend myself: you have not shown us your typeEnum, which I suspect already had one case per class instance. So we have not incurred any new cost in functions other than liftNum, and have indeed significantly simplified liftNum. This also gives a smooth upgrade path for more complex Complex manipulations: extend the TypeEnum definition, the cast ordering, and the to function and you're good to go; liftNum may stay the same. (If it turns out that types are not linearly ordered but instead some kind of lattice or similar, then you can switch away from the Ord class.)


text:
Q: How do I add the rewards properly, to this customer account? I'm trying to figure out how to implement the "Rewards" program for the customer accounts on my weekend project, I created an array list and wrote a boolean to return true if the account is in the array.  But I can't figure out how to attach the rewards to the actual account, or I'm just drawing a blank.  ** I just now actually realized it said not to worry about signing in (HA!). I would still appreciate any help though.  ** edit 2 **
The rewards are just a simple 1 point per dollar spent.  10 points =$5 and reset points.
/* Notes for Bonus:
        Users are of two types: Admin and Customer. An admin can check and update inventory.
        You may create your own default admin user, but customers must signup
        Users should have an email and password to verify to access rewards.
        Do not worry about signing in, just signup and verify.
        Admins should have to verify to access inventory functionality.
        Users may be stored inside an array to be kept track of.
        Sally said she would like it if you kept track of user's total $ spent as well
        to make keeping track of rewards easy.

MAIN METHOD
public class SallysLemonadeStand {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);           ArrayList<Customer> customerAccount = new ArrayList<Customer>();
        Lemonade lemonade = new Lemonade();                  Admin admin = new Admin();
        Water water = new Water();
        Soda soda = new Soda();
        Cookies cookies = new Cookies();
        Candy candy = new Candy();

        while(true) {
            System.out.println("Welcome to Sallys Lemonade Stand!");
            System.out.println("Please input your selection");
            System.out.println("1: Lemonade, 2: Water, 3: Soda, 4: Cookies, 5: Candy");
            System.out.println("Press 6 to sign up for a customer account WITH REWARDS!");
            System.out.println("Press 7 to login to Admin Account.");
            int choice = scanner.nextInt();
            scanner.nextLine();

            switch(choice) {
            case 1:
                Customer.customerSignin(scanner, customerAccount);
                customerEngagement(scanner, lemonade, customerAccount);
                break;
            case 2:
                customerEngagement(scanner, water, customerAccount);
                break;
            case 3:
                customerEngagement(scanner, soda, customerAccount);
                break;
            case 4:
                Cookies.cookieSale (scanner, cookies, customerAccount);
                break;
            case 5:
                customerEngagement(scanner, candy, customerAccount);
                break;
            case 6:
                Customer.signupCustomer(scanner, customerAccount);
                break;
            case 7: Admin.adminPriveledge(scanner, admin, lemonade,water,soda,cookies,candy);
                        System.out.println("Would you like to see how many customers have signed up? y/n");
                        String selection = scanner.nextLine();
                            if(selection.equalsIgnoreCase("y")) {
                                Admin.customerAccountSheet(scanner, admin, customerAccount);
                            }

            break;

            }
        }

    }

    public static void customerEngagement(Scanner scanner, ProductInterface product, ArrayList<Customer> customerAccount) {
        System.out.println("Please input the quantity of your product you want: ");
        int amountOfItems = scanner.nextInt();
        double amountDue = product.sellProduct(amountOfItems);
        System.out.println("Your cost is: " + amountDue);
        ProductInterface.pay();
        System.out.println("Thank you for shopping with Sallys!");
        product.removeFromStock(amountOfItems);
            if(Customer.customerSignin(scanner, customerAccount) == true) {

            }
    }

}

As you can see, I'm trying to write a rewards method, but it doesn't seem right to me.
The accounts interface only implements the email and password.
If you need to see the rest of my code, please let me know.  First time posting on here.
public class Customer implements Accounts {
    String email;
    String password;
    int rewards;

    Customer() {}

    public String getEmail() {
        return email;
    }

    public int getRewards() {
        return rewards;
    }

    public void setRewards(int rewards) {
        this.rewards = rewards;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String email() {
        // TODO Auto-generated method stub
        return email;
    }

    @Override
    public String password() {
        // TODO Auto-generated method stub
        return password;
    }
    @Override
    public String toString() {
        return email;
    }

    public static void signupCustomer(Scanner scanner, ArrayList<Customer> customerAccount) {
        String choice;

        System.out.println("Would you like to create a new customer account? y/n");
        choice = scanner.nextLine();
        if (choice.equalsIgnoreCase("y")) {
            Customer account = new Customer();
            System.out.println("Please enter an email for your account. ");
            account.setEmail(scanner.nextLine());
            System.out.println("Is " + account.getEmail() + " correct? y/n");
            choice = scanner.nextLine();
            if(choice.equalsIgnoreCase("y")) {
                System.out.println("Please enter a password for your account. ");
                account.setPassword(scanner.nextLine());
                System.out.println("Is " + account.getPassword() + " correct? y/n");
                choice = scanner.nextLine();
                if(choice.equalsIgnoreCase("y")) {
                    customerAccount.add(account);
                }
            }
        }
    }
    public static boolean customerSignin(Scanner scanner, ArrayList<Customer> customerAccount) {
        System.out.println("Are you enrolled in our Rewards Program? y/n");
        String choice = scanner.nextLine();
        String email;
        String password;

        if (choice.equalsIgnoreCase("y")) {
            System.out.println("Please enter email and password: ");
            System.out.println("Email: ");
            email = scanner.nextLine();

            for (Customer account : customerAccount) {
                if(email.equalsIgnoreCase(account.email)) {
                    System.out.println("Password: ");
                    password = scanner.nextLine();
                    if(password.equalsIgnoreCase(account.password)) {
                        return true;
                    }

                }
            }

        }
        return false;

    }
    public static void customerRewards(Scanner scanner, ArrayList<Customer> customerAccount) {

    }

}